List of usage examples for android.net Uri getAuthority
@Nullable public abstract String getAuthority();
From source file:com.mishiranu.dashchan.ui.navigator.page.PostsPage.java
private void onAfterPostsLoad(boolean fromCache) { PageHolder pageHolder = getPageHolder(); PostsExtra extra = getExtra();/*from w w w . j a v a 2s . c o m*/ if (!extra.isAddedToHistory) { extra.isAddedToHistory = true; HistoryDatabase.getInstance().addHistory(pageHolder.chanName, pageHolder.boardName, pageHolder.threadNumber, pageHolder.threadTitle); } if (extra.cachedPosts != null) { Pair<String, Uri> originalThreadData = null; Uri archivedThreadUri = extra.cachedPosts.getArchivedThreadUri(); if (archivedThreadUri != null) { String chanName = ChanManager.getInstance().getChanNameByHost(archivedThreadUri.getAuthority()); if (chanName != null) { originalThreadData = new Pair<>(chanName, archivedThreadUri); } } if ((this.originalThreadData == null) != (originalThreadData == null)) { this.originalThreadData = originalThreadData; updateOptionsMenu(false); } } if (!fromCache) { FavoritesStorage.getInstance().modifyPostsCount(pageHolder.chanName, pageHolder.boardName, pageHolder.threadNumber, getAdapter().getExistingPostsCount()); } Iterator<PostItem> iterator = getAdapter().iterator(); if (iterator.hasNext()) { String title = iterator.next().getSubjectOrComment(); if (StringUtils.isEmptyOrWhitespace(title)) { title = null; } FavoritesStorage.getInstance().modifyTitle(pageHolder.chanName, pageHolder.boardName, pageHolder.threadNumber, title, false); if (!StringUtils.equals(StringUtils.nullIfEmpty(pageHolder.threadTitle), title)) { HistoryDatabase.getInstance().refreshTitles(pageHolder.chanName, pageHolder.boardName, pageHolder.threadNumber, title); pageHolder.threadTitle = title; notifyTitleChanged(); } } }
From source file:com.mishiranu.dashchan.ui.navigator.DrawerForm.java
@Override public void onClick(View v) { String text = searchEdit.getText().toString().trim(); int number = -1; try {/* ww w . ja va2 s . com*/ number = Integer.parseInt(text); } catch (NumberFormatException e) { // Not a number, ignore exception } if (number >= 0) { int result = callback.onEnterNumber(number); if (FlagUtils.get(result, RESULT_SUCCESS)) { clearTextAndHideKeyboard(); return; } if (FlagUtils.get(result, RESULT_REMOVE_ERROR_MESSAGE)) { return; } } else { { String boardName = null; String threadNumber = null; Matcher matcher = PATTERN_NAVIGATION_BOARD_THREAD.matcher(text); if (matcher.matches()) { boardName = matcher.group(1); threadNumber = matcher.group(2); } else { matcher = PATTERN_NAVIGATION_BOARD.matcher(text); if (matcher.matches()) { boardName = matcher.group(1); } else { matcher = PATTERN_NAVIGATION_THREAD.matcher(text); if (matcher.matches()) { threadNumber = matcher.group(1); } } } if (boardName != null || threadNumber != null) { boolean success; if (threadNumber == null) { callback.onSelectBoard(chanName, boardName, false); success = true; } else { success = callback.onSelectThread(chanName, boardName, threadNumber, null, null, false); } if (success) { clearTextAndHideKeyboard(); return; } } } Uri uri = Uri.parse(text); String chanName = ChanManager.getInstance().getChanNameByHost(uri.getAuthority()); if (chanName != null) { boolean success = false; String boardName = null; String threadNumber = null; String postNumber = null; ChanLocator locator = ChanLocator.get(chanName); if (locator.safe(false).isThreadUri(uri)) { boardName = locator.safe(false).getBoardName(uri); threadNumber = locator.safe(false).getThreadNumber(uri); postNumber = locator.safe(false).getPostNumber(uri); success = true; } else if (locator.safe(false).isBoardUri(uri)) { boardName = locator.safe(false).getBoardName(uri); threadNumber = null; postNumber = null; success = true; } if (success) { if (threadNumber == null) { callback.onSelectBoard(chanName, boardName, false); } else { callback.onSelectThread(chanName, boardName, threadNumber, postNumber, null, false); } clearTextAndHideKeyboard(); return; } } } ToastUtils.show(context, R.string.message_enter_valid_data); }
From source file:com.android.messaging.mmslib.pdu.PduPersister.java
/** * Update all parts of a PDU.// w ww . java2 s. c o m * * @param uri The PDU which need to be updated. * @param body New message body of the PDU. * @param preOpenedFiles if not null, a map of preopened InputStreams for the parts. * @throws MmsException Bad URI or updating failed. */ public void updateParts(final Uri uri, final PduBody body, final Map<Uri, InputStream> preOpenedFiles) throws MmsException { try { PduCacheEntry cacheEntry; synchronized (PDU_CACHE_INSTANCE) { if (PDU_CACHE_INSTANCE.isUpdating(uri)) { if (LOCAL_LOGV) { LogUtil.v(TAG, "updateParts: " + uri + " blocked by isUpdating()"); } try { PDU_CACHE_INSTANCE.wait(); } catch (final InterruptedException e) { Log.e(TAG, "updateParts: ", e); } cacheEntry = PDU_CACHE_INSTANCE.get(uri); if (cacheEntry != null) { ((MultimediaMessagePdu) cacheEntry.getPdu()).setBody(body); } } // Tell the cache to indicate to other callers that this item // is currently being updated. PDU_CACHE_INSTANCE.setUpdating(uri, true); } final ArrayList<PduPart> toBeCreated = new ArrayList<PduPart>(); final ArrayMap<Uri, PduPart> toBeUpdated = new ArrayMap<Uri, PduPart>(); final int partsNum = body.getPartsNum(); final StringBuilder filter = new StringBuilder().append('('); for (int i = 0; i < partsNum; i++) { final PduPart part = body.getPart(i); final Uri partUri = part.getDataUri(); if ((partUri == null) || !partUri.getAuthority().startsWith("mms")) { toBeCreated.add(part); } else { toBeUpdated.put(partUri, part); // Don't use 'i > 0' to determine whether we should append // 'AND' since 'i = 0' may be skipped in another branch. if (filter.length() > 1) { filter.append(" AND "); } filter.append(Part._ID); filter.append("!="); DatabaseUtils.appendEscapedSQLString(filter, partUri.getLastPathSegment()); } } filter.append(')'); final long msgId = ContentUris.parseId(uri); // Remove the parts which doesn't exist anymore. SqliteWrapper.delete(mContext, mContentResolver, Uri.parse(Mms.CONTENT_URI + "/" + msgId + "/part"), filter.length() > 2 ? filter.toString() : null, null); // Create new parts which didn't exist before. for (final PduPart part : toBeCreated) { persistPart(part, msgId, preOpenedFiles); } // Update the modified parts. for (final Map.Entry<Uri, PduPart> e : toBeUpdated.entrySet()) { updatePart(e.getKey(), e.getValue(), preOpenedFiles); } } finally { synchronized (PDU_CACHE_INSTANCE) { PDU_CACHE_INSTANCE.setUpdating(uri, false); PDU_CACHE_INSTANCE.notifyAll(); } } }
From source file:com.tct.mail.browse.ConversationCursor.java
/** * Regenerate the original Uri from a forwarding (ConversationProvider) Uri * NOTE: See note above for uriToCachingUri * @param uri the forwarding Uri/* w w w. j ava 2 s . c om*/ * @return the original Uri */ public static Uri uriFromCachingUri(Uri uri) { //TS: zheng.zou 2015-07-17 EMAIL BUGFIX_-943618 MOD String authority = uri.getAuthority(); // Don't modify uri's that aren't ours if (!authority.equals(ConversationProvider.AUTHORITY)) { return uri; } List<String> path = uri.getPathSegments(); Uri.Builder builder = new Uri.Builder().scheme(uri.getScheme()).authority(path.get(0)); for (int i = 1; i < path.size(); i++) { builder.appendPath(path.get(i)); } return builder.build(); }
From source file:com.lgallardo.qbittorrentclient.RSSFeedParser.java
public RSSFeed getRSSChannelInfo(String url) { // Parse url//from w ww .j a v a2 s . com Uri uri = Uri.parse(url); int event; String text = null; String torrent = null; boolean header = true; HttpResponse httpResponse; DefaultHttpClient httpclient; XmlPullParserFactory xmlFactoryObject; XmlPullParser xmlParser = null; HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = connection_timeout * 1000; // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = data_timeout * 1000; // Set http parameters HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android"); HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); // Log.d("Debug", "Host: " + uri.getAuthority()); // Making HTTP request HttpHost targetHost = new HttpHost(uri.getAuthority()); // httpclient = new DefaultHttpClient(httpParameters); // httpclient = new DefaultHttpClient(); httpclient = getNewHttpClient(); httpclient.setParams(httpParameters); RSSFeed rssFeed = new RSSFeed(); try { // AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password); // // httpclient.getCredentialsProvider().setCredentials(authScope, credentials); // set http parameters HttpGet httpget = new HttpGet(url); httpResponse = httpclient.execute(targetHost, httpget); StatusLine statusLine = httpResponse.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); if (mStatusCode != 200) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(mStatusCode); } HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); xmlFactoryObject = XmlPullParserFactory.newInstance(); xmlParser = xmlFactoryObject.newPullParser(); xmlParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); xmlParser.setInput(is, null); event = xmlParser.getEventType(); // Get Channel info String name; RSSFeedItem item = null; List<RSSFeedItem> items = new ArrayList<RSSFeedItem>(); // Get items while (event != XmlPullParser.END_DOCUMENT && header) { name = xmlParser.getName(); switch (event) { case XmlPullParser.START_TAG: if (name != null && name.equals("item")) { header = false; } break; case XmlPullParser.TEXT: text = xmlParser.getText(); break; case XmlPullParser.END_TAG: if (name.equals("title")) { if (header) { rssFeed.setChannelTitle(text); } } else if (name.equals("description")) { if (header) { } } else if (name.equals("link")) { if (header) { rssFeed.setChannelLink(text); } } break; } event = xmlParser.next(); } is.close(); } catch (Exception e) { Log.e("Debug", "RSSFeedParser - : " + e.toString()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } // return JSON String return rssFeed; }
From source file:org.opendatakit.survey.android.activities.MainMenuActivity.java
@Override public void initializationCompleted(String fragmentToShowNext) { // whether we have can cancelled or completed update, // remember to not do the expansion files check next time through ScreenList newFragment = ScreenList.valueOf(fragmentToShowNext); if (newFragment == ScreenList.WEBKIT && getCurrentForm() == null) { // we were sent off to the initialization dialog to try to // discover the form. We need to inquire about the form again // and, if we cannot find it, report an error to the user. final Uri uriFormsProvider = FormsProviderAPI.CONTENT_URI; Uri uri = getIntent().getData(); Uri formUri = null;//from w ww . ja va 2 s . co m if (uri.getScheme().equalsIgnoreCase(uriFormsProvider.getScheme()) && uri.getAuthority().equalsIgnoreCase(uriFormsProvider.getAuthority())) { List<String> segments = uri.getPathSegments(); if (segments != null && segments.size() >= 2) { String appName = segments.get(0); setAppName(appName); formUri = Uri.withAppendedPath(Uri.withAppendedPath(uriFormsProvider, appName), segments.get(1)); } else { swapToFragmentView(ScreenList.FORM_CHOOSER); createErrorDialog(getString(R.string.invalid_uri_expecting_n_segments, uri.toString(), 2), EXIT); return; } // request specifies a specific formUri -- try to open that FormIdStruct newForm = FormIdStruct.retrieveFormIdStruct(getContentResolver(), formUri); if (newForm == null) { // error swapToFragmentView(ScreenList.FORM_CHOOSER); createErrorDialog(getString(R.string.form_not_found, segments.get(1)), EXIT); return; } else { transitionToFormHelper(uri, newForm); swapToFragmentView(newFragment); } } } else { WebLogger.getLogger(getAppName()).i(t, "initializationCompleted: swapping to " + newFragment.name()); swapToFragmentView(newFragment); } }
From source file:org.opendatakit.survey.activities.MainMenuActivity.java
public void swapToFragmentView(ScreenList newScreenType) { WebLogger.getLogger(getAppName()).i(t, "swapToFragmentView: " + newScreenType.name()); FragmentManager mgr = getFragmentManager(); FragmentTransaction trans = null;//w w w .j a v a2s .co m Fragment newFragment = null; if (newScreenType == ScreenList.MAIN_SCREEN) { throw new IllegalStateException("unexpected reference to generic main screen"); } else if (newScreenType == ScreenList.FORM_CHOOSER) { newFragment = mgr.findFragmentByTag(newScreenType.name()); if (newFragment == null) { newFragment = new FormChooserListFragment(); } } else if (newScreenType == ScreenList.FRONT_PAGE) { newFragment = mgr.findFragmentByTag(newScreenType.name()); if (newFragment == null) { newFragment = new FrontPageFragment(); } } else if (newScreenType == ScreenList.INITIALIZATION_DIALOG) { newFragment = mgr.findFragmentByTag(newScreenType.name()); if (newFragment == null) { newFragment = new InitializationFragment(); } } else if (newScreenType == ScreenList.WEBKIT) { newFragment = mgr.findFragmentByTag(newScreenType.name()); if (newFragment == null) { WebLogger.getLogger(getAppName()).i(t, "[" + this.hashCode() + "] creating new webkit fragment " + newScreenType.name()); newFragment = new WebViewFragment(); } } else if (newScreenType == ScreenList.ABOUT_MENU) { newFragment = mgr.findFragmentByTag(newScreenType.name()); if (newFragment == null) { newFragment = new AboutMenuFragment(); } } else { throw new IllegalStateException("Unrecognized ScreenList type"); } boolean matchingBackStackEntry = false; for (int i = 0; i < mgr.getBackStackEntryCount(); ++i) { BackStackEntry e = mgr.getBackStackEntryAt(i); WebLogger.getLogger(getAppName()).i(t, "BackStackEntry[" + i + "] " + e.getName()); if (e.getName().equals(newScreenType.name())) { matchingBackStackEntry = true; } } if (matchingBackStackEntry) { if (trans != null) { WebLogger.getLogger(getAppName()).e(t, "Unexpected active transaction when popping state!"); trans = null; } // flush backward, to the screen we want to go back to currentFragment = newScreenType; WebLogger.getLogger(getAppName()).e(t, "[" + this.hashCode() + "] popping back stack " + currentFragment.name()); mgr.popBackStackImmediate(currentFragment.name(), 0); } else { // add transaction to show the screen we want if (trans == null) { trans = mgr.beginTransaction(); } currentFragment = newScreenType; trans.replace(R.id.main_content, newFragment, currentFragment.name()); WebLogger.getLogger(getAppName()).i(t, "[" + this.hashCode() + "] adding to back stack " + currentFragment.name()); trans.addToBackStack(currentFragment.name()); } // and see if we should re-initialize... if ((currentFragment != ScreenList.INITIALIZATION_DIALOG) && ((Survey) getApplication()).shouldRunInitializationTask(getAppName())) { WebLogger.getLogger(getAppName()).i(t, "swapToFragmentView -- calling clearRunInitializationTask"); // and immediately clear the should-run flag... ((Survey) getApplication()).clearRunInitializationTask(getAppName()); // OK we should swap to the InitializationFragment view // this will skip the transition to whatever screen we were trying to // go to and will instead show the InitializationFragment view. We // restore to the desired screen via the setFragmentToShowNext() // // NOTE: this discards the uncommitted transaction. // Robolectric complains about a recursive state transition. if (trans != null) { trans.commit(); } swapToFragmentView(ScreenList.INITIALIZATION_DIALOG); } else { // before we actually switch to a WebKit, be sure // we have the form definition for it... if (currentFragment == ScreenList.WEBKIT && getCurrentForm() == null) { // we were sent off to the initialization dialog to try to // discover the form. We need to inquire about the form again // and, if we cannot find it, report an error to the user. final Uri uriFormsProvider = FormsProviderAPI.CONTENT_URI; Uri uri = getIntent().getData(); Uri formUri = null; if (uri.getScheme().equalsIgnoreCase(uriFormsProvider.getScheme()) && uri.getAuthority().equalsIgnoreCase(uriFormsProvider.getAuthority())) { List<String> segments = uri.getPathSegments(); if (segments != null && segments.size() >= 2) { String appName = segments.get(0); setAppName(appName); String tableId = segments.get(1); String formId = (segments.size() > 2) ? segments.get(2) : null; formUri = Uri.withAppendedPath(Uri.withAppendedPath( Uri.withAppendedPath(FormsProviderAPI.CONTENT_URI, appName), tableId), formId); } else { swapToFragmentView(ScreenList.FRONT_PAGE); createErrorDialog(getString(R.string.invalid_uri_expecting_n_segments, uri.toString(), 2), EXIT); return; } // request specifies a specific formUri -- try to open that FormIdStruct newForm = FormIdStruct.retrieveFormIdStruct(getContentResolver(), formUri); if (newForm == null) { // error swapToFragmentView(ScreenList.FRONT_PAGE); createErrorDialog(getString(R.string.form_not_found, segments.get(1)), EXIT); return; } else { transitionToFormHelper(uri, newForm); } } } if (trans != null) { trans.commit(); } invalidateOptionsMenu(); } }
From source file:com.gelakinetic.mtgfam.FamiliarActivity.java
private boolean processIntent(Intent intent) { boolean isDeepLink = false; if (Intent.ACTION_SEARCH.equals(intent.getAction())) { /* Do a search by name, launched from the quick search */ String query = intent.getStringExtra(SearchManager.QUERY); Bundle args = new Bundle(); SearchCriteria sc = new SearchCriteria(); sc.name = query;//from w ww .java 2s .com args.putSerializable(SearchViewFragment.CRITERIA, sc); selectItem(R.string.main_card_search, args, false, true); /* Don't clear backstack, do force the intent */ } else if (Intent.ACTION_VIEW.equals(intent.getAction())) { boolean shouldSelectItem = true; Uri data = intent.getData(); Bundle args = new Bundle(); assert data != null; boolean shouldClearFragmentStack = true; /* Clear backstack for deep links */ if (data.getAuthority().toLowerCase().contains("gatherer.wizards")) { SQLiteDatabase database = DatabaseManager.getInstance(this, false).openDatabase(false); try { String queryParam; if ((queryParam = data.getQueryParameter("multiverseid")) != null) { Cursor cursor = CardDbAdapter.fetchCardByMultiverseId(Long.parseLong(queryParam), new String[] { CardDbAdapter.DATABASE_TABLE_CARDS + "." + CardDbAdapter.KEY_ID }, database); if (cursor.getCount() != 0) { isDeepLink = true; args.putLongArray(CardViewPagerFragment.CARD_ID_ARRAY, new long[] { cursor.getInt(cursor.getColumnIndex(CardDbAdapter.KEY_ID)) }); } cursor.close(); if (args.size() == 0) { throw new Exception("Not Found"); } } else if ((queryParam = data.getQueryParameter("name")) != null) { Cursor cursor = CardDbAdapter.fetchCardByName(queryParam, new String[] { CardDbAdapter.DATABASE_TABLE_CARDS + "." + CardDbAdapter.KEY_ID }, true, database); if (cursor.getCount() != 0) { isDeepLink = true; args.putLongArray(CardViewPagerFragment.CARD_ID_ARRAY, new long[] { cursor.getInt(cursor.getColumnIndex(CardDbAdapter.KEY_ID)) }); } cursor.close(); if (args.size() == 0) { throw new Exception("Not Found"); } } else { throw new Exception("Not Found"); } } catch (Exception e) { /* empty cursor, just return */ ToastWrapper.makeText(this, R.string.no_results_found, ToastWrapper.LENGTH_LONG).show(); this.finish(); shouldSelectItem = false; } finally { DatabaseManager.getInstance(this, false).closeDatabase(false); } } else if (data.getAuthority().contains("CardSearchProvider")) { /* User clicked a card in the quick search autocomplete, jump right to it */ args.putLongArray(CardViewPagerFragment.CARD_ID_ARRAY, new long[] { Long.parseLong(data.getLastPathSegment()) }); shouldClearFragmentStack = false; /* Don't clear backstack for search intents */ } else { /* User clicked a deep link, jump to the card(s) */ isDeepLink = true; SQLiteDatabase database = DatabaseManager.getInstance(this, false).openDatabase(false); try { Cursor cursor = null; boolean screenLaunched = false; if (data.getScheme().toLowerCase().equals("card") && data.getAuthority().toLowerCase().equals("multiverseid")) { if (data.getLastPathSegment() == null) { /* Home screen deep link */ launchHomeScreen(); screenLaunched = true; shouldSelectItem = false; } else { try { /* Don't clear the fragment stack for internal links (thanks Meld cards) */ if (data.getPathSegments().contains("internal")) { shouldClearFragmentStack = false; } cursor = CardDbAdapter.fetchCardByMultiverseId( Long.parseLong(data.getLastPathSegment()), new String[] { CardDbAdapter.DATABASE_TABLE_CARDS + "." + CardDbAdapter.KEY_ID }, database); } catch (NumberFormatException e) { cursor = null; } } } if (cursor != null) { if (cursor.getCount() != 0) { args.putLongArray(CardViewPagerFragment.CARD_ID_ARRAY, new long[] { cursor.getInt(cursor.getColumnIndex(CardDbAdapter.KEY_ID)) }); } else { /* empty cursor, just return */ ToastWrapper.makeText(this, R.string.no_results_found, ToastWrapper.LENGTH_LONG).show(); this.finish(); shouldSelectItem = false; } cursor.close(); } else if (!screenLaunched) { /* null cursor, just return */ ToastWrapper.makeText(this, R.string.no_results_found, ToastWrapper.LENGTH_LONG).show(); this.finish(); shouldSelectItem = false; } } catch (FamiliarDbException e) { e.printStackTrace(); } DatabaseManager.getInstance(this, false).closeDatabase(false); } args.putInt(CardViewPagerFragment.STARTING_CARD_POSITION, 0); if (shouldSelectItem) { selectItem(R.string.main_card_search, args, shouldClearFragmentStack, true); } } else if (ACTION_ROUND_TIMER.equals(intent.getAction())) { selectItem(R.string.main_timer, null, true, false); } else if (ACTION_CARD_SEARCH.equals(intent.getAction())) { selectItem(R.string.main_card_search, null, true, false); } else if (ACTION_LIFE.equals(intent.getAction())) { selectItem(R.string.main_life_counter, null, true, false); } else if (ACTION_DICE.equals(intent.getAction())) { selectItem(R.string.main_dice, null, true, false); } else if (ACTION_TRADE.equals(intent.getAction())) { selectItem(R.string.main_trade, null, true, false); } else if (ACTION_MANA.equals(intent.getAction())) { selectItem(R.string.main_mana_pool, null, true, false); } else if (ACTION_WISH.equals(intent.getAction())) { selectItem(R.string.main_wishlist, null, true, false); } else if (ACTION_RULES.equals(intent.getAction())) { selectItem(R.string.main_rules, null, true, false); } else if (ACTION_JUDGE.equals(intent.getAction())) { selectItem(R.string.main_judges_corner, null, true, false); } else if (ACTION_MOJHOSTO.equals(intent.getAction())) { selectItem(R.string.main_mojhosto, null, true, false); } else if (ACTION_PROFILE.equals(intent.getAction())) { selectItem(R.string.main_profile, null, true, false); } else if (ACTION_DECKLIST.equals(intent.getAction())) { selectItem(R.string.main_decklist, null, true, false); } else if (Intent.ACTION_MAIN.equals(intent.getAction())) { /* App launched as regular, show the default fragment if there isn't one already */ if (getSupportFragmentManager().getFragments() == null) { launchHomeScreen(); } } else { /* Some unknown intent, just finish */ finish(); } mDrawerList.setItemChecked(mCurrentFrag, true); return isDeepLink; }
From source file:com.lgallardo.qbittorrentclient.RSSFeedParser.java
public RSSFeed getRSSFeed(String channelTitle, String channelUrl, String filter) { // Decode url link try {//from w w w . jav a 2s . co m channelUrl = URLDecoder.decode(channelUrl, "UTF-8"); } catch (UnsupportedEncodingException e) { Log.e("Debug", "RSSFeedParser - decoding error: " + e.toString()); } // Parse url Uri uri = uri = Uri.parse(channelUrl); ; int event; String text = null; String torrent = null; boolean header = true; // TODO delete itemCount, as it's not really used this.itemCount = 0; HttpResponse httpResponse; DefaultHttpClient httpclient; XmlPullParserFactory xmlFactoryObject; XmlPullParser xmlParser = null; HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = connection_timeout * 1000; // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = data_timeout * 1000; // Set http parameters HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android"); HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); RSSFeed rssFeed = new RSSFeed(); rssFeed.setChannelTitle(channelTitle); rssFeed.setChannelLink(channelUrl); httpclient = null; try { // Making HTTP request HttpHost targetHost = new HttpHost(uri.getAuthority()); // httpclient = new DefaultHttpClient(httpParameters); // httpclient = new DefaultHttpClient(); httpclient = getNewHttpClient(); httpclient.setParams(httpParameters); // AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password); // // httpclient.getCredentialsProvider().setCredentials(authScope, credentials); // set http parameters HttpGet httpget = new HttpGet(channelUrl); httpResponse = httpclient.execute(targetHost, httpget); StatusLine statusLine = httpResponse.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); if (mStatusCode != 200) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(mStatusCode); } HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); xmlFactoryObject = XmlPullParserFactory.newInstance(); xmlParser = xmlFactoryObject.newPullParser(); xmlParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); xmlParser.setInput(is, null); event = xmlParser.getEventType(); // Get Channel info String name; RSSFeedItem item = null; ArrayList<RSSFeedItem> items = new ArrayList<RSSFeedItem>(); // Get items while (event != XmlPullParser.END_DOCUMENT) { name = xmlParser.getName(); switch (event) { case XmlPullParser.START_TAG: if (name != null && name.equals("item")) { header = false; item = new RSSFeedItem(); itemCount = itemCount + 1; } try { for (int i = 0; i < xmlParser.getAttributeCount(); i++) { if (xmlParser.getAttributeName(i).equals("url")) { torrent = xmlParser.getAttributeValue(i); if (torrent != null) { torrent = Uri.decode(URLEncoder.encode(torrent, "UTF-8")); } break; } } } catch (Exception e) { } break; case XmlPullParser.TEXT: text = xmlParser.getText(); break; case XmlPullParser.END_TAG: if (name.equals("title")) { if (!header) { item.setTitle(text); // Log.d("Debug", "PARSER - Title: " + text); } } else if (name.equals("description")) { if (header) { // Log.d("Debug", "Channel Description: " + text); } else { item.setDescription(text); // Log.d("Debug", "Description: " + text); } } else if (name.equals("link")) { if (!header) { item.setLink(text); // Log.d("Debug", "Link: " + text); } } else if (name.equals("pubDate")) { // Set item pubDate if (item != null) { item.setPubDate(text); } } else if (name.equals("enclosure")) { item.setTorrentUrl(torrent); // Log.d("Debug", "Enclosure: " + torrent); } else if (name.equals("item") && !header) { if (items != null & item != null) { // Fix torrent url for no-standard rss feeds if (torrent == null) { String link = item.getLink(); if (link != null) { link = Uri.decode(URLEncoder.encode(link, "UTF-8")); } item.setTorrentUrl(link); } items.add(item); } } break; } event = xmlParser.next(); // if (!header) { // items.add(item); // } } // Filter items // Log.e("Debug", "RSSFeedParser - filter: >" + filter + "<"); if (filter != null && !filter.equals("")) { Iterator iterator = items.iterator(); while (iterator.hasNext()) { item = (RSSFeedItem) iterator.next(); // If link doesn't match filter, remove it // Log.e("Debug", "RSSFeedParser - item no filter: >" + item.getTitle() + "<"); Pattern patter = Pattern.compile(filter); Matcher matcher = patter.matcher(item.getTitle()); // get a matcher object if (!(matcher.find())) { iterator.remove(); } } } rssFeed.setItems(items); rssFeed.setItemCount(itemCount); rssFeed.setChannelPubDate(items.get(0).getPubDate()); rssFeed.setResultOk(true); is.close(); } catch (Exception e) { Log.e("Debug", "RSSFeedParser - : " + e.toString()); rssFeed.setResultOk(false); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources if (httpclient != null) { httpclient.getConnectionManager().shutdown(); } } // return JSON String return rssFeed; }
From source file:com.taobao.weex.WXSDKInstance.java
private String wrapPageName(String pageName, String url) { if (TextUtils.equals(pageName, WXPerformance.DEFAULT)) { pageName = url;/*from w w w . j a va2 s . co m*/ WXExceptionUtils.degradeUrl = pageName; try { Uri uri = Uri.parse(url); if (uri != null) { Uri.Builder builder = new Uri.Builder(); builder.scheme(uri.getScheme()); builder.authority(uri.getAuthority()); builder.path(uri.getPath()); pageName = builder.toString(); } } catch (Exception e) { } } return pageName; }