Example usage for android.net Uri getHost

List of usage examples for android.net Uri getHost

Introduction

In this page you can find the example usage for android.net Uri getHost.

Prototype

@Nullable
public abstract String getHost();

Source Link

Document

Gets the encoded host from the authority for this URI.

Usage

From source file:org.mozilla.gecko.GeckoApp.java

private void initialize() {
    mInitialized = true;// w ww .j a v a  2  s.  c  o m

    Intent intent = getIntent();
    String args = intent.getStringExtra("args");
    if (args != null && args.contains("-profile")) {
        Pattern p = Pattern.compile("(?:-profile\\s*)(\\w*)(\\s*)");
        Matcher m = p.matcher(args);
        if (m.find()) {
            mProfile = GeckoProfile.get(this, m.group(1));
            mLastTitle = null;
            mLastViewport = null;
            mLastScreen = null;
        }
    }

    if (ACTION_UPDATE.equals(intent.getAction()) || args != null && args.contains("-alert update-app")) {
        Log.i(LOGTAG, "onCreate: Update request");
        checkAndLaunchUpdate();
    }

    mBrowserToolbar.init();
    mBrowserToolbar.setTitle(mLastTitle);

    String passedUri = null;
    String uri = getURIFromIntent(intent);
    if (uri != null && uri.length() > 0)
        passedUri = mLastTitle = uri;

    if (passedUri == null || passedUri.equals("about:home")) {
        // show about:home if we aren't restoring previous session
        if (!getProfile().hasSession()) {
            mBrowserToolbar.updateTabCount(1);
            showAboutHome();
        }
    } else {
        mBrowserToolbar.updateTabCount(1);
    }

    if (sGREDir == null)
        sGREDir = new File(this.getApplicationInfo().dataDir);

    Uri data = intent.getData();
    if (data != null && "http".equals(data.getScheme()) && isHostOnPrefetchWhitelist(data.getHost())) {
        Intent copy = new Intent(intent);
        copy.setAction(ACTION_LOAD);
        GeckoAppShell.getHandler().post(new RedirectorRunnable(copy));
        // We're going to handle this uri with the redirector, so setting
        // the action to MAIN and clearing the uri data prevents us from
        // loading it twice
        intent.setAction(Intent.ACTION_MAIN);
        intent.setData(null);
        passedUri = null;
    }

    sGeckoThread = new GeckoThread(intent, passedUri, mRestoreSession);
    if (!ACTION_DEBUG.equals(intent.getAction())
            && checkAndSetLaunchState(LaunchState.Launching, LaunchState.Launched))
        sGeckoThread.start();

    mFavicons = new Favicons(this);

    Tabs.getInstance().setContentResolver(getContentResolver());

    if (cameraView == null) {
        cameraView = new SurfaceView(this);
        cameraView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    if (mLayerController == null) {
        /*
         * Create a layer client so that Gecko will have a buffer to draw into, but don't hook
         * it up to the layer controller yet.
         */
        mSoftwareLayerClient = new GeckoSoftwareLayerClient(this);

        /*
         * Hook a placeholder layer client up to the layer controller so that the user can pan
         * and zoom a cached screenshot of the previous page. This call will return null if
         * there is no cached screenshot; in that case, we have no choice but to display a
         * checkerboard.
         *
         * TODO: Fall back to a built-in screenshot of the Fennec Start page for a nice first-
         * run experience, perhaps?
         */
        mLayerController = new LayerController(this);
        mPlaceholderLayerClient = PlaceholderLayerClient.createInstance(this);
        mLayerController.setLayerClient(mPlaceholderLayerClient);

        mGeckoLayout.addView(mLayerController.getView(), 0);
    }

    mPluginContainer = (AbsoluteLayout) findViewById(R.id.plugin_container);

    mDoorHangerPopup = new DoorHangerPopup(this);
    mAutoCompletePopup = (AutoCompletePopup) findViewById(R.id.autocomplete_popup);

    Log.w(LOGTAG, "zerdatime " + SystemClock.uptimeMillis() + " - UI almost up");

    if (!sTryCatchAttached) {
        sTryCatchAttached = true;
        mMainHandler.post(new Runnable() {
            public void run() {
                try {
                    Looper.loop();
                } catch (Exception e) {
                    GeckoAppShell.reportJavaCrash(e);
                }
                // resetting this is kinda pointless, but oh well
                sTryCatchAttached = false;
            }
        });
    }

    //register for events
    GeckoAppShell.registerGeckoEventListener("DOMContentLoaded", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("DOMTitleChanged", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("DOMLinkAdded", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("DOMWindowClose", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("log", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("Content:LocationChange", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("Content:SecurityChange", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("Content:StateChange", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("Content:LoadError", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("onCameraCapture", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("Doorhanger:Add", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("Doorhanger:Remove", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("Menu:Add", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("Menu:Remove", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("Gecko:Ready", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("Toast:Show", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("DOMFullScreen:Start", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("DOMFullScreen:Stop", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("ToggleChrome:Hide", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("ToggleChrome:Show", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("FormAssist:AutoComplete", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("Permissions:Data", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("Downloads:Done", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("CharEncoding:Data", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("CharEncoding:State", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("Update:Restart", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("Tab:HasTouchListener", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("Session:StatePurged", GeckoApp.mAppContext);
    GeckoAppShell.registerGeckoEventListener("Bookmark:Insert", GeckoApp.mAppContext);

    IntentFilter batteryFilter = new IntentFilter();
    batteryFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
    mBatteryReceiver = new GeckoBatteryManager();
    registerReceiver(mBatteryReceiver, batteryFilter);

    if (SmsManager.getInstance() != null) {
        SmsManager.getInstance().start();
    }

    GeckoNetworkManager.getInstance().init();

    final GeckoApp self = this;

    GeckoAppShell.getHandler().postDelayed(new Runnable() {
        public void run() {
            Log.w(LOGTAG, "zerdatime " + SystemClock.uptimeMillis() + " - pre checkLaunchState");

            /*
              XXXX see bug 635342
               We want to disable this code if possible.  It is about 145ms in runtime
            SharedPreferences settings = getPreferences(Activity.MODE_PRIVATE);
            String localeCode = settings.getString(getPackageName() + ".locale", "");
            if (localeCode != null && localeCode.length() > 0)
            GeckoAppShell.setSelectedLocale(localeCode);
            */

            if (!checkLaunchState(LaunchState.Launched)) {
                return;
            }

            checkMigrateProfile();
        }
    }, 50);
}

From source file:im.vector.receiver.VectorUniversalLinkReceiver.java

@Override
public void onReceive(final Context aContext, final Intent aIntent) {
    String action, uriString;/* w  ww .ja  v  a 2 s .  c o m*/
    Uri intentUri;

    Log.d(LOG_TAG, "## onReceive() IN");

    // get session
    mSession = Matrix.getInstance(aContext).getDefaultSession();

    // user is not yet logged in
    if (null == mSession) {
        Log.e(LOG_TAG, "## onReceive() Warning - Unable to proceed URL link: Session is null");

        // No user is logged => no session. Just forward request to the login activity
        Intent intent = new Intent(aContext, LoginActivity.class);
        intent.putExtra(EXTRA_UNIVERSAL_LINK_URI, aIntent.getData());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK
                | Intent.FLAG_ACTIVITY_NEW_TASK);
        aContext.startActivity(intent);
        return;
    }

    // sanity check
    if (null != aIntent) {

        action = aIntent.getAction();
        uriString = aIntent.getDataString();
        boolean isSessionActive = mSession.isAlive();
        boolean isLoginStepDone = mSession.getDataHandler().isInitialSyncComplete();

        Log.d(LOG_TAG, "## onReceive() uri getDataString=" + uriString + "isSessionActive=" + isSessionActive
                + " isLoginStepDone=" + isLoginStepDone);

        if (TextUtils.equals(action, BROADCAST_ACTION_UNIVERSAL_LINK)) {
            Log.d(LOG_TAG, "## onReceive() action = BROADCAST_ACTION_UNIVERSAL_LINK");
            intentUri = aIntent.getData();

        } else if (TextUtils.equals(action, BROADCAST_ACTION_UNIVERSAL_LINK_RESUME)) {
            Log.d(LOG_TAG, "## onReceive() action = BROADCAST_ACTION_UNIVERSAL_LINK_RESUME");

            // A first BROADCAST_ACTION_UNIVERSAL_LINK has been received with a room alias that could not be translated to a room ID.
            // Translation has been asked to server, and the response is processed here.
            // ......................
            intentUri = aIntent.getParcelableExtra(EXTRA_UNIVERSAL_LINK_URI);
            // aIntent.getParcelableExtra(EXTRA_UNIVERSAL_LINK_SENDER_ID);
        } else {
            // unknown action (very unlikely)
            Log.e(LOG_TAG,
                    "## onReceive() Unknown action received (" + action + ") - unable to proceed URL link");
            return;
        }

        if (null != intentUri) {
            Log.d(LOG_TAG, "## onCreate() intentUri - host=" + intentUri.getHost() + " path="
                    + intentUri.getPath() + " queryParams=" + intentUri.getQuery());
            //intentUri.getEncodedSchemeSpecificPart() = //vector.im/beta/  intentUri.getSchemeSpecificPart() = //vector.im/beta/

            HashMap<String, String> params = parseUniversalLink(intentUri);

            if (null != params) {

                if (!isSessionActive) {
                    Log.w(LOG_TAG, "## onReceive() Warning: Session is not alive");
                }

                if (!isLoginStepDone) {
                    Log.w(LOG_TAG, "## onReceive() Warning: Session is not complete - start Login Activity");

                    // Start the login activity and wait for BROADCAST_ACTION_UNIVERSAL_LINK_RESUME.
                    // Once the login process flow is complete, BROADCAST_ACTION_UNIVERSAL_LINK_RESUME is
                    // sent back to resume the URL link processing.
                    Intent intent = new Intent(aContext, LoginActivity.class);
                    intent.putExtra(EXTRA_UNIVERSAL_LINK_URI, aIntent.getData());
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    aContext.startActivity(intent);
                } else {
                    mParameters = params;

                    if (mParameters.containsKey(ULINK_ROOM_ID_OR_ALIAS_KEY)) {
                        manageRoomOnActivity(aContext);
                    } else if (mParameters.containsKey(ULINK_MATRIX_USER_ID_KEY)) {
                        manageMemberDetailsActivity(aContext);
                    } else if (mParameters.containsKey(ULINK_GROUP_ID_KEY)) {
                        manageGroupDetailsActivity(aContext);
                    } else {
                        Log.e(LOG_TAG, "## onReceive() : nothing to do");
                    }
                }
            } else {
                Log.e(LOG_TAG, "## onReceive() Path not supported: " + intentUri.getPath());
            }
        }
    }
}

From source file:gc.david.dfm.ui.MainActivity.java

/**
 * Handles a send intent with position data.
 *
 * @param intent Input intent with position data.
 *///from ww  w  .jav  a  2s.  com
private void handleViewPositionIntent(final Intent intent) throws Exception {
    Mint.leaveBreadcrumb("MainActivity::handleViewPositionIntent");
    final Uri uri = intent.getData();
    Mint.addExtraData("queryParameter", uri.toString());

    final String uriScheme = uri.getScheme();
    if (uriScheme.equals("geo")) {
        final String schemeSpecificPart = uri.getSchemeSpecificPart();
        final Matcher matcher = getMatcherForUri(schemeSpecificPart);
        if (matcher.find()) {
            if (matcher.group(1).equals("0") && matcher.group(2).equals("0")) {
                if (matcher.find()) { // Manage geo:0,0?q=lat,lng(label)
                    setDestinationPosition(matcher);
                } else { // Manage geo:0,0?q=my+street+address
                    String destination = Uri.decode(uri.getQuery()).replace('+', ' ');
                    destination = destination.replace("q=", "");

                    // TODO check this ugly workaround
                    new SearchPositionByName().execute(destination);
                    mustShowPositionWhenComingFromOutside = true;
                }
            } else { // Manage geo:latitude,longitude or geo:latitude,longitude?z=zoom
                setDestinationPosition(matcher);
            }
        } else {
            final NoSuchFieldException noSuchFieldException = new NoSuchFieldException(
                    "Error al obtener las coordenadas. Matcher = " + matcher.toString());
            Mint.logException(noSuchFieldException);
            throw noSuchFieldException;
        }
    } else if ((uriScheme.equals("http") || uriScheme.equals("https"))
            && (uri.getHost().equals("maps.google.com"))) { // Manage maps.google.com?q=latitude,longitude

        final String queryParameter = uri.getQueryParameter("q");
        if (queryParameter != null) {
            final Matcher matcher = getMatcherForUri(queryParameter);
            if (matcher.find()) {
                setDestinationPosition(matcher);
            } else {
                final NoSuchFieldException noSuchFieldException = new NoSuchFieldException(
                        "Error al obtener las coordenadas. Matcher = " + matcher.toString());
                Mint.logException(noSuchFieldException);
                throw noSuchFieldException;
            }
        } else {
            final NoSuchFieldException noSuchFieldException = new NoSuchFieldException(
                    "Query sin parmetro q.");
            Mint.logException(noSuchFieldException);
            throw noSuchFieldException;
        }
    } else {
        final Exception exception = new Exception("Imposible tratar la query " + uri.toString());
        Mint.logException(exception);
        throw exception;
    }
}

From source file:org.mozilla.gecko.GeckoApp.java

@Override
protected void onNewIntent(Intent intent) {
    Log.w(LOGTAG, "zerdatime " + SystemClock.uptimeMillis() + " - onNewIntent");

    if (checkLaunchState(LaunchState.GeckoExiting)) {
        // We're exiting and shouldn't try to do anything else just incase
        // we're hung for some reason we'll force the process to exit
        System.exit(0);//from  w  ww.j a va 2s.  c  om
        return;
    }

    if (checkLaunchState(LaunchState.Launched)) {
        Uri data = intent.getData();
        Bundle bundle = intent.getExtras();
        // if the intent has data (i.e. a URI to be opened) and the scheme
        // is either http, we'll prefetch it, which means warming
        // up the radio and DNS cache by connecting and parsing the redirect
        // if the return code is between 300 and 400
        if (data != null && "http".equals(data.getScheme())
                && (bundle == null || bundle.getInt("prefetched", 0) != 1)
                && isHostOnPrefetchWhitelist(data.getHost())) {
            GeckoAppShell.getHandler().post(new RedirectorRunnable(intent));
            return;
        }
    }
    final String action = intent.getAction();
    if (ACTION_DEBUG.equals(action)
            && checkAndSetLaunchState(LaunchState.Launching, LaunchState.WaitForDebugger)) {
        mMainHandler.postDelayed(new Runnable() {
            public void run() {
                Log.i(LOGTAG, "Launching from debug intent after 5s wait");
                setLaunchState(LaunchState.Launching);
                sGeckoThread.start();
            }
        }, 1000 * 5 /* 5 seconds */);
        Log.i(LOGTAG, "Intent : ACTION_DEBUG - waiting 5s before launching");
        return;
    }
    if (checkLaunchState(LaunchState.WaitForDebugger) || intent == getIntent())
        return;

    if (Intent.ACTION_MAIN.equals(action)) {
        Log.i(LOGTAG, "Intent : ACTION_MAIN");
        GeckoAppShell.sendEventToGecko(GeckoEvent.createLoadEvent(""));
    } else if (ACTION_LOAD.equals(action)) {
        String uri = intent.getDataString();
        loadUrl(uri, AwesomeBar.Type.EDIT);
        Log.i(LOGTAG, "onNewIntent: " + uri);
    } else if (Intent.ACTION_VIEW.equals(action)) {
        String uri = intent.getDataString();
        GeckoAppShell.sendEventToGecko(GeckoEvent.createLoadEvent(uri));
        Log.i(LOGTAG, "onNewIntent: " + uri);
    } else if (ACTION_WEBAPP.equals(action)) {
        String uri = getURIFromIntent(intent);
        GeckoAppShell.sendEventToGecko(GeckoEvent.createLoadEvent(uri));
        Log.i(LOGTAG, "Intent : WEBAPP - " + uri);
    } else if (ACTION_BOOKMARK.equals(action)) {
        String uri = getURIFromIntent(intent);
        GeckoAppShell.sendEventToGecko(GeckoEvent.createLoadEvent(uri));
        Log.i(LOGTAG, "Intent : BOOKMARK - " + uri);
    }
}

From source file:cgeo.geocaching.CacheDetailActivity.java

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState, R.layout.cachedetail_activity);

    // get parameters
    final Bundle extras = getIntent().getExtras();
    final Uri uri = AndroidBeam.getUri(getIntent());

    // try to get data from extras
    String name = null;//from www .j  av  a2  s.  co m
    String guid = null;

    if (extras != null) {
        geocode = extras.getString(Intents.EXTRA_GEOCODE);
        name = extras.getString(Intents.EXTRA_NAME);
        guid = extras.getString(Intents.EXTRA_GUID);
    }

    // When clicking a cache in MapsWithMe, we get back a PendingIntent
    if (StringUtils.isEmpty(geocode)) {
        geocode = MapsMeCacheListApp.getCacheFromMapsWithMe(this, getIntent());
    }

    if (geocode == null && uri != null) {
        geocode = ConnectorFactory.getGeocodeFromURL(uri.toString());
    }

    // try to get data from URI
    if (geocode == null && guid == null && uri != null) {
        final String uriHost = uri.getHost().toLowerCase(Locale.US);
        final String uriPath = uri.getPath().toLowerCase(Locale.US);
        final String uriQuery = uri.getQuery();

        if (uriQuery != null) {
            Log.i("Opening URI: " + uriHost + uriPath + "?" + uriQuery);
        } else {
            Log.i("Opening URI: " + uriHost + uriPath);
        }

        if (uriHost.contains("geocaching.com")) {
            if (StringUtils.startsWith(uriPath, "/geocache/gc")) {
                geocode = StringUtils.substringBefore(uriPath.substring(10), "_").toUpperCase(Locale.US);
            } else {
                geocode = uri.getQueryParameter("wp");
                guid = uri.getQueryParameter("guid");

                if (StringUtils.isNotBlank(geocode)) {
                    geocode = geocode.toUpperCase(Locale.US);
                    guid = null;
                } else if (StringUtils.isNotBlank(guid)) {
                    geocode = null;
                    guid = guid.toLowerCase(Locale.US);
                } else {
                    showToast(res.getString(R.string.err_detail_open));
                    finish();
                    return;
                }
            }
        }
    }

    // no given data
    if (geocode == null && guid == null) {
        showToast(res.getString(R.string.err_detail_cache));
        finish();
        return;
    }

    // If we open this cache from a search, let's properly initialize the title bar, even if we don't have cache details
    setCacheTitleBar(geocode, name, null);

    final LoadCacheHandler loadCacheHandler = new LoadCacheHandler(this, progress);

    try {
        String title = res.getString(R.string.cache);
        if (StringUtils.isNotBlank(name)) {
            title = name;
        } else if (geocode != null && StringUtils.isNotBlank(geocode)) { // can't be null, but the compiler doesn't understand StringUtils.isNotBlank()
            title = geocode;
        }
        progress.show(this, title, res.getString(R.string.cache_dialog_loading_details), true,
                loadCacheHandler.disposeMessage());
    } catch (final RuntimeException ignored) {
        // nothing, we lost the window
    }

    final int pageToOpen = savedInstanceState != null ? savedInstanceState.getInt(STATE_PAGE_INDEX, 0)
            : Settings.isOpenLastDetailsPage() ? Settings.getLastDetailsPage() : 1;
    createViewPager(pageToOpen, new OnPageSelectedListener() {

        @Override
        public void onPageSelected(final int position) {
            if (Settings.isOpenLastDetailsPage()) {
                Settings.setLastDetailsPage(position);
            }
            // lazy loading of cache images
            if (getPage(position) == Page.IMAGES) {
                loadCacheImages();
            }
            requireGeodata = getPage(position) == Page.DETAILS;
            startOrStopGeoDataListener(false);

            // dispose contextual actions on page change
            if (currentActionMode != null) {
                currentActionMode.finish();
            }
        }
    });
    requireGeodata = pageToOpen == 1;

    final String realGeocode = geocode;
    final String realGuid = guid;
    AndroidRxUtils.networkScheduler.scheduleDirect(new Runnable() {
        @Override
        public void run() {
            search = Geocache.searchByGeocode(realGeocode, StringUtils.isBlank(realGeocode) ? realGuid : null,
                    false, loadCacheHandler);
            loadCacheHandler.sendMessage(Message.obtain());
        }
    });

    // Load Generic Trackables
    if (StringUtils.isNotBlank(geocode)) {
        AndroidRxUtils.bindActivity(this,
                // Obtain the active connectors and load trackables in parallel.
                Observable.fromIterable(ConnectorFactory.getGenericTrackablesConnectors())
                        .flatMap(new Function<TrackableConnector, Observable<Trackable>>() {
                            @Override
                            public Observable<Trackable> apply(final TrackableConnector trackableConnector) {
                                processedBrands.add(trackableConnector.getBrand());
                                return Observable.defer(new Callable<Observable<Trackable>>() {
                                    @Override
                                    public Observable<Trackable> call() {
                                        return Observable
                                                .fromIterable(trackableConnector.searchTrackables(geocode));
                                    }
                                }).subscribeOn(AndroidRxUtils.networkScheduler);
                            }
                        }).toList())
                .subscribe(new Consumer<List<Trackable>>() {
                    @Override
                    public void accept(final List<Trackable> trackables) {
                        // Todo: this is not really a good method, it may lead to duplicates ; ie: in OC connectors.
                        // Store trackables.
                        genericTrackables.addAll(trackables);
                        if (!trackables.isEmpty()) {
                            // Update the UI if any trackables were found.
                            notifyDataSetChanged();
                        }
                    }
                });
    }

    locationUpdater = new CacheDetailsGeoDirHandler(this);

    // If we have a newer Android device setup Android Beam for easy cache sharing
    AndroidBeam.enable(this, this);
}

From source file:org.cafemember.ui.LaunchActivity.java

private boolean handleIntent(Intent intent, boolean isNew, boolean restore, boolean fromPassword) {
    int flags = intent.getFlags();
    if (!fromPassword && (AndroidUtilities.needShowPasscode(true) || UserConfig.isWaitingForPasscodeEnter)) {
        showPasscodeActivity();//  w  w  w. ja v  a2  s  .c  o m
        passcodeSaveIntent = intent;
        passcodeSaveIntentIsNew = isNew;
        passcodeSaveIntentIsRestore = restore;
        UserConfig.saveConfig(false);
    } else {
        boolean pushOpened = false;

        Integer push_user_id = 0;
        Integer push_chat_id = 0;
        Integer push_enc_id = 0;
        Integer open_settings = 0;
        long dialogId = intent != null && intent.getExtras() != null ? intent.getExtras().getLong("dialogId", 0)
                : 0;
        boolean showDialogsList = false;
        boolean showPlayer = false;

        photoPathsArray = null;
        videoPath = null;
        sendingText = null;
        documentsPathsArray = null;
        documentsOriginalPathsArray = null;
        documentsMimeType = null;
        documentsUrisArray = null;
        contactsToSend = null;

        if (UserConfig.isClientActivated() && (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) {
            if (intent != null && intent.getAction() != null && !restore) {
                if (Intent.ACTION_SEND.equals(intent.getAction())) {
                    boolean error = false;
                    String type = intent.getType();
                    if (type != null && type.equals(ContactsContract.Contacts.CONTENT_VCARD_TYPE)) {
                        try {
                            Uri uri = (Uri) intent.getExtras().get(Intent.EXTRA_STREAM);
                            if (uri != null) {
                                ContentResolver cr = getContentResolver();
                                InputStream stream = cr.openInputStream(uri);

                                String name = null;
                                String nameEncoding = null;
                                String nameCharset = null;
                                ArrayList<String> phones = new ArrayList<>();
                                BufferedReader bufferedReader = new BufferedReader(
                                        new InputStreamReader(stream, "UTF-8"));
                                String line;
                                while ((line = bufferedReader.readLine()) != null) {
                                    String[] args = line.split(":");
                                    if (args.length != 2) {
                                        continue;
                                    }
                                    if (args[0].startsWith("FN")) {
                                        String[] params = args[0].split(";");
                                        for (String param : params) {
                                            String[] args2 = param.split("=");
                                            if (args2.length != 2) {
                                                continue;
                                            }
                                            if (args2[0].equals("CHARSET")) {
                                                nameCharset = args2[1];
                                            } else if (args2[0].equals("ENCODING")) {
                                                nameEncoding = args2[1];
                                            }
                                        }
                                        name = args[1];
                                        if (nameEncoding != null
                                                && nameEncoding.equalsIgnoreCase("QUOTED-PRINTABLE")) {
                                            while (name.endsWith("=") && nameEncoding != null) {
                                                name = name.substring(0, name.length() - 1);
                                                line = bufferedReader.readLine();
                                                if (line == null) {
                                                    break;
                                                }
                                                name += line;
                                            }
                                            byte[] bytes = AndroidUtilities
                                                    .decodeQuotedPrintable(name.getBytes());
                                            if (bytes != null && bytes.length != 0) {
                                                String decodedName = new String(bytes, nameCharset);
                                                if (decodedName != null) {
                                                    name = decodedName;
                                                }
                                            }
                                        }
                                    } else if (args[0].startsWith("TEL")) {
                                        String phone = PhoneFormat.stripExceptNumbers(args[1], true);
                                        if (phone.length() > 0) {
                                            phones.add(phone);
                                        }
                                    }
                                }
                                try {
                                    bufferedReader.close();
                                    stream.close();
                                } catch (Exception e) {
                                    FileLog.e("tmessages", e);
                                }
                                if (name != null && !phones.isEmpty()) {
                                    contactsToSend = new ArrayList<>();
                                    for (String phone : phones) {
                                        TLRPC.User user = new TLRPC.TL_userContact_old2();
                                        user.phone = phone;
                                        user.first_name = name;
                                        user.last_name = "";
                                        user.id = 0;
                                        contactsToSend.add(user);
                                    }
                                }
                            } else {
                                error = true;
                            }
                        } catch (Exception e) {
                            FileLog.e("tmessages", e);
                            error = true;
                        }
                    } else {
                        String text = intent.getStringExtra(Intent.EXTRA_TEXT);
                        if (text == null) {
                            CharSequence textSequence = intent.getCharSequenceExtra(Intent.EXTRA_TEXT);
                            if (textSequence != null) {
                                text = textSequence.toString();
                            }
                        }
                        String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT);

                        if (text != null && text.length() != 0) {
                            if ((text.startsWith("http://") || text.startsWith("https://")) && subject != null
                                    && subject.length() != 0) {
                                text = subject + "\n" + text;
                            }
                            sendingText = text;
                        } else if (subject != null && subject.length() > 0) {
                            sendingText = subject;
                        }

                        Parcelable parcelable = intent.getParcelableExtra(Intent.EXTRA_STREAM);
                        if (parcelable != null) {
                            String path;
                            if (!(parcelable instanceof Uri)) {
                                parcelable = Uri.parse(parcelable.toString());
                            }
                            Uri uri = (Uri) parcelable;
                            if (uri != null) {
                                if (isInternalUri(uri)) {
                                    error = true;
                                }
                            }
                            if (!error) {
                                if (uri != null && (type != null && type.startsWith("image/")
                                        || uri.toString().toLowerCase().endsWith(".jpg"))) {
                                    if (photoPathsArray == null) {
                                        photoPathsArray = new ArrayList<>();
                                    }
                                    photoPathsArray.add(uri);
                                } else {
                                    path = AndroidUtilities.getPath(uri);
                                    if (path != null) {
                                        if (path.startsWith("file:")) {
                                            path = path.replace("file://", "");
                                        }
                                        if (type != null && type.startsWith("video/")) {
                                            videoPath = path;
                                        } else {
                                            if (documentsPathsArray == null) {
                                                documentsPathsArray = new ArrayList<>();
                                                documentsOriginalPathsArray = new ArrayList<>();
                                            }
                                            documentsPathsArray.add(path);
                                            documentsOriginalPathsArray.add(uri.toString());
                                        }
                                    } else {
                                        if (documentsUrisArray == null) {
                                            documentsUrisArray = new ArrayList<>();
                                        }
                                        documentsUrisArray.add(uri);
                                        documentsMimeType = type;
                                    }
                                }
                                if (sendingText != null) {
                                    if (sendingText.contains("WhatsApp")) { //remove unnecessary caption 'sent from WhatsApp' from photos forwarded from WhatsApp
                                        sendingText = null;
                                    }
                                }
                            }
                        } else if (sendingText == null) {
                            error = true;
                        }
                    }
                    if (error) {
                        Toast.makeText(this, "Unsupported content", Toast.LENGTH_SHORT).show();
                    }
                } else if (intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
                    boolean error = false;
                    try {
                        ArrayList<Parcelable> uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
                        String type = intent.getType();
                        if (uris != null) {
                            for (int a = 0; a < uris.size(); a++) {
                                Parcelable parcelable = uris.get(a);
                                if (!(parcelable instanceof Uri)) {
                                    parcelable = Uri.parse(parcelable.toString());
                                }
                                Uri uri = (Uri) parcelable;
                                if (uri != null) {
                                    if (isInternalUri(uri)) {
                                        uris.remove(a);
                                        a--;
                                    }
                                }
                            }
                            if (uris.isEmpty()) {
                                uris = null;
                            }
                        }
                        if (uris != null) {
                            if (type != null && type.startsWith("image/")) {
                                for (int a = 0; a < uris.size(); a++) {
                                    Parcelable parcelable = uris.get(a);
                                    if (!(parcelable instanceof Uri)) {
                                        parcelable = Uri.parse(parcelable.toString());
                                    }
                                    Uri uri = (Uri) parcelable;
                                    if (photoPathsArray == null) {
                                        photoPathsArray = new ArrayList<>();
                                    }
                                    photoPathsArray.add(uri);
                                }
                            } else {
                                for (int a = 0; a < uris.size(); a++) {
                                    Parcelable parcelable = uris.get(a);
                                    if (!(parcelable instanceof Uri)) {
                                        parcelable = Uri.parse(parcelable.toString());
                                    }
                                    String path = AndroidUtilities.getPath((Uri) parcelable);
                                    String originalPath = parcelable.toString();
                                    if (originalPath == null) {
                                        originalPath = path;
                                    }
                                    if (path != null) {
                                        if (path.startsWith("file:")) {
                                            path = path.replace("file://", "");
                                        }
                                        if (documentsPathsArray == null) {
                                            documentsPathsArray = new ArrayList<>();
                                            documentsOriginalPathsArray = new ArrayList<>();
                                        }
                                        documentsPathsArray.add(path);
                                        documentsOriginalPathsArray.add(originalPath);
                                    }
                                }
                            }
                        } else {
                            error = true;
                        }
                    } catch (Exception e) {
                        FileLog.e("tmessages", e);
                        error = true;
                    }
                    if (error) {
                        Toast.makeText(this, "Unsupported content", Toast.LENGTH_SHORT).show();
                    }
                } else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
                    Uri data = intent.getData();
                    if (data != null) {
                        String username = null;
                        String group = null;
                        String sticker = null;
                        String botUser = null;
                        String botChat = null;
                        String message = null;
                        Integer messageId = null;
                        boolean hasUrl = false;
                        String scheme = data.getScheme();
                        if (scheme != null) {
                            if ((scheme.equals("http") || scheme.equals("https"))) {
                                String host = data.getHost().toLowerCase();
                                if (host.equals("telegram.me") || host.equals("telegram.dog")) {
                                    String path = data.getPath();
                                    if (path != null && path.length() > 1) {
                                        path = path.substring(1);
                                        if (path.startsWith("joinchat/")) {
                                            group = path.replace("joinchat/", "");
                                        } else if (path.startsWith("addstickers/")) {
                                            sticker = path.replace("addstickers/", "");
                                        } else if (path.startsWith("msg/") || path.startsWith("share/")) {
                                            message = data.getQueryParameter("url");
                                            if (message == null) {
                                                message = "";
                                            }
                                            if (data.getQueryParameter("text") != null) {
                                                if (message.length() > 0) {
                                                    hasUrl = true;
                                                    message += "\n";
                                                }
                                                message += data.getQueryParameter("text");
                                            }
                                        } else if (path.length() >= 1) {
                                            List<String> segments = data.getPathSegments();
                                            if (segments.size() > 0) {
                                                username = segments.get(0);
                                                if (segments.size() > 1) {
                                                    messageId = Utilities.parseInt(segments.get(1));
                                                    if (messageId == 0) {
                                                        messageId = null;
                                                    }
                                                }
                                            }
                                            botUser = data.getQueryParameter("start");
                                            botChat = data.getQueryParameter("startgroup");
                                        }
                                    }
                                }
                            } else if (scheme.equals("tg")) {
                                String url = data.toString();
                                if (url.startsWith("tg:resolve") || url.startsWith("tg://resolve")) {
                                    url = url.replace("tg:resolve", "tg://telegram.org").replace("tg://resolve",
                                            "tg://telegram.org");
                                    data = Uri.parse(url);
                                    username = data.getQueryParameter("domain");
                                    botUser = data.getQueryParameter("start");
                                    botChat = data.getQueryParameter("startgroup");
                                } else if (url.startsWith("tg:join") || url.startsWith("tg://join")) {
                                    url = url.replace("tg:join", "tg://telegram.org").replace("tg://join",
                                            "tg://telegram.org");
                                    data = Uri.parse(url);
                                    group = data.getQueryParameter("invite");
                                } else if (url.startsWith("tg:addstickers")
                                        || url.startsWith("tg://addstickers")) {
                                    url = url.replace("tg:addstickers", "tg://telegram.org")
                                            .replace("tg://addstickers", "tg://telegram.org");
                                    data = Uri.parse(url);
                                    sticker = data.getQueryParameter("set");
                                } else if (url.startsWith("tg:msg") || url.startsWith("tg://msg")
                                        || url.startsWith("tg://share") || url.startsWith("tg:share")) {
                                    url = url.replace("tg:msg", "tg://telegram.org")
                                            .replace("tg://msg", "tg://telegram.org")
                                            .replace("tg://share", "tg://telegram.org")
                                            .replace("tg:share", "tg://telegram.org");
                                    data = Uri.parse(url);
                                    message = data.getQueryParameter("url");
                                    if (message == null) {
                                        message = "";
                                    }
                                    if (data.getQueryParameter("text") != null) {
                                        if (message.length() > 0) {
                                            hasUrl = true;
                                            message += "\n";
                                        }
                                        message += data.getQueryParameter("text");
                                    }
                                }
                            }
                        }
                        if (username != null || group != null || sticker != null || message != null) {
                            runLinkRequest(username, group, sticker, botUser, botChat, message, hasUrl,
                                    messageId, 0);
                        } else {
                            try {
                                Cursor cursor = getContentResolver().query(intent.getData(), null, null, null,
                                        null);
                                if (cursor != null) {
                                    if (cursor.moveToFirst()) {
                                        int userId = cursor.getInt(cursor.getColumnIndex("DATA4"));
                                        NotificationCenter.getInstance()
                                                .postNotificationName(NotificationCenter.closeChats);
                                        push_user_id = userId;
                                    }
                                    cursor.close();
                                }
                            } catch (Exception e) {
                                FileLog.e("tmessages", e);
                            }
                        }
                    }
                } else if (intent.getAction().equals("org.telegram.messenger.OPEN_ACCOUNT")) {
                    open_settings = 1;
                } else if (intent.getAction().startsWith("com.tmessages.openchat")) {
                    int chatId = intent.getIntExtra("chatId", 0);
                    int userId = intent.getIntExtra("userId", 0);
                    int encId = intent.getIntExtra("encId", 0);
                    if (chatId != 0) {
                        NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats);
                        push_chat_id = chatId;
                    } else if (userId != 0) {
                        NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats);
                        push_user_id = userId;
                    } else if (encId != 0) {
                        NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats);
                        push_enc_id = encId;
                    } else {
                        showDialogsList = true;
                    }
                } else if (intent.getAction().equals("com.tmessages.openplayer")) {
                    showPlayer = true;
                }
            }
        }

        if (push_user_id != 0) {
            Bundle args = new Bundle();
            args.putInt("user_id", push_user_id);
            if (mainFragmentsStack.isEmpty() || MessagesController.checkCanOpenChat(args,
                    mainFragmentsStack.get(mainFragmentsStack.size() - 1))) {
                ChatActivity fragment = new ChatActivity(args);
                if (actionBarLayout.presentFragment(fragment, false, true, true)) {
                    pushOpened = true;
                }
            }
        } else if (push_chat_id != 0) {
            Bundle args = new Bundle();
            args.putInt("chat_id", push_chat_id);
            if (mainFragmentsStack.isEmpty() || MessagesController.checkCanOpenChat(args,
                    mainFragmentsStack.get(mainFragmentsStack.size() - 1))) {
                ChatActivity fragment = new ChatActivity(args);
                if (actionBarLayout.presentFragment(fragment, false, true, true)) {
                    pushOpened = true;
                }
            }
        } else if (push_enc_id != 0) {
            Bundle args = new Bundle();
            args.putInt("enc_id", push_enc_id);
            ChatActivity fragment = new ChatActivity(args);
            if (actionBarLayout.presentFragment(fragment, false, true, true)) {
                pushOpened = true;
            }
        } else if (showDialogsList) {
            if (!AndroidUtilities.isTablet()) {
                actionBarLayout.removeAllFragments();
            } else {
                if (!layersActionBarLayout.fragmentsStack.isEmpty()) {
                    for (int a = 0; a < layersActionBarLayout.fragmentsStack.size() - 1; a++) {
                        layersActionBarLayout
                                .removeFragmentFromStack(layersActionBarLayout.fragmentsStack.get(0));
                        a--;
                    }
                    layersActionBarLayout.closeLastFragment(false);
                }
            }
            pushOpened = false;
            isNew = false;
        } else if (showPlayer) {
            if (AndroidUtilities.isTablet()) {
                for (int a = 0; a < layersActionBarLayout.fragmentsStack.size(); a++) {
                    BaseFragment fragment = layersActionBarLayout.fragmentsStack.get(a);
                    if (fragment instanceof AudioPlayerActivity) {
                        layersActionBarLayout.removeFragmentFromStack(fragment);
                        break;
                    }
                }
                actionBarLayout.showLastFragment();
                rightActionBarLayout.showLastFragment();
                drawerLayoutContainer.setAllowOpenDrawer(false, false);
            } else {
                for (int a = 0; a < actionBarLayout.fragmentsStack.size(); a++) {
                    BaseFragment fragment = actionBarLayout.fragmentsStack.get(a);
                    if (fragment instanceof AudioPlayerActivity) {
                        actionBarLayout.removeFragmentFromStack(fragment);
                        break;
                    }
                }
                drawerLayoutContainer.setAllowOpenDrawer(true, false);
            }
            actionBarLayout.presentFragment(new AudioPlayerActivity(), false, true, true);
            pushOpened = true;
        } else if (videoPath != null || photoPathsArray != null || sendingText != null
                || documentsPathsArray != null || contactsToSend != null || documentsUrisArray != null) {
            if (!AndroidUtilities.isTablet()) {
                NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats);
            }
            if (dialogId == 0) {
                Bundle args = new Bundle();
                args.putBoolean("onlySelect", true);
                if (contactsToSend != null) {
                    args.putString("selectAlertString",
                            LocaleController.getString("SendContactTo", R.string.SendMessagesTo));
                    args.putString("selectAlertStringGroup",
                            LocaleController.getString("SendContactToGroup", R.string.SendContactToGroup));
                } else {
                    args.putString("selectAlertString",
                            LocaleController.getString("SendMessagesTo", R.string.SendMessagesTo));
                    args.putString("selectAlertStringGroup",
                            LocaleController.getString("SendMessagesToGroup", R.string.SendMessagesToGroup));
                }
                DialogsActivity fragment = new DialogsActivity(args);
                dialogsFragment = fragment;
                fragment.setDelegate(this);
                boolean removeLast;
                if (AndroidUtilities.isTablet()) {
                    removeLast = layersActionBarLayout.fragmentsStack.size() > 0
                            && layersActionBarLayout.fragmentsStack.get(
                                    layersActionBarLayout.fragmentsStack.size() - 1) instanceof DialogsActivity;
                } else {
                    removeLast = actionBarLayout.fragmentsStack.size() > 1 && actionBarLayout.fragmentsStack
                            .get(actionBarLayout.fragmentsStack.size() - 1) instanceof DialogsActivity;
                }
                actionBarLayout.presentFragment(fragment, removeLast, true, true);
                pushOpened = true;
                if (PhotoViewer.getInstance().isVisible()) {
                    PhotoViewer.getInstance().closePhoto(false, true);
                }

                drawerLayoutContainer.setAllowOpenDrawer(false, false);
                if (AndroidUtilities.isTablet()) {
                    actionBarLayout.showLastFragment();
                    rightActionBarLayout.showLastFragment();
                } else {
                    drawerLayoutContainer.setAllowOpenDrawer(true, false);
                }
            } else {
                didSelectDialog(null, dialogId, false);
            }
        } else if (open_settings != 0) {
            actionBarLayout.presentFragment(new SettingsActivity(), false, true, true);
            if (AndroidUtilities.isTablet()) {
                actionBarLayout.showLastFragment();
                rightActionBarLayout.showLastFragment();
                drawerLayoutContainer.setAllowOpenDrawer(false, false);
            } else {
                drawerLayoutContainer.setAllowOpenDrawer(true, false);
            }
            pushOpened = true;
        }

        if (!pushOpened && !isNew) {
            if (AndroidUtilities.isTablet()) {
                if (!UserConfig.isClientActivated()) {
                    if (layersActionBarLayout.fragmentsStack.isEmpty()) {
                        layersActionBarLayout.addFragmentToStack(new LoginActivity());
                        drawerLayoutContainer.setAllowOpenDrawer(false, false);
                    }
                } else {
                    if (actionBarLayout.fragmentsStack.isEmpty()) {
                        actionBarLayout.addFragmentToStack(new DialogsActivity(null));
                        drawerLayoutContainer.setAllowOpenDrawer(true, false);
                    }
                }
            } else {
                if (actionBarLayout.fragmentsStack.isEmpty()) {
                    if (!UserConfig.isClientActivated()) {
                        actionBarLayout.addFragmentToStack(new LoginActivity());
                        drawerLayoutContainer.setAllowOpenDrawer(false, false);
                    } else {
                        actionBarLayout.addFragmentToStack(new DialogsActivity(null));
                        drawerLayoutContainer.setAllowOpenDrawer(true, false);
                    }
                }
            }
            actionBarLayout.showLastFragment();
            if (AndroidUtilities.isTablet()) {
                layersActionBarLayout.showLastFragment();
                rightActionBarLayout.showLastFragment();
            }
        }

        intent.setAction(null);
        return pushOpened;
    }
    return false;
}

From source file:cgeo.geocaching.cgBase.java

public String requestJSONgc(String host, String path, String params) {
    int httpCode = -1;
    String httpLocation = null;//ww w. jav  a2 s  .  co m

    final String cookiesDone = CookieJar.getCookiesAsString(prefs);

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    final StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < 3; i++) {
        if (i > 0) {
            Log.w(cgSettings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer.delete(0, buffer.length());
        timeout = 30000 + (i * 15000);

        try {
            // POST
            final URL u = new URL("http://" + host + path);
            uc = u.openConnection();

            uc.setRequestProperty("Host", host);
            uc.setRequestProperty("Cookie", cookiesDone);
            uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            uc.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            uc.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
            uc.setRequestProperty("Referer", host + "/" + path);

            if (settings.asBrowser == 1) {
                uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                uc.setRequestProperty("Accept-Language", "en-US");
                uc.setRequestProperty("User-Agent", idBrowser);
                uc.setRequestProperty("Connection", "keep-alive");
                uc.setRequestProperty("Keep-Alive", "300");
            }

            connection = (HttpURLConnection) uc;
            connection.setReadTimeout(timeout);
            connection.setRequestMethod("POST");
            HttpURLConnection.setFollowRedirects(false); // TODO: Fix these (FilCab)
            connection.setDoInput(true);
            connection.setDoOutput(true);

            final OutputStream out = connection.getOutputStream();
            final OutputStreamWriter wr = new OutputStreamWriter(out);
            wr.write(params);
            wr.flush();
            wr.close();

            CookieJar.setCookies(prefs, uc);

            InputStream ins = getInputstreamFromConnection(connection);
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            httpCode = connection.getResponseCode();
            httpLocation = uc.getHeaderField("Location");

            final String paramsLog = params.replaceAll(passMatch, "password=***");
            Log.i(cgSettings.tag + " | JSON",
                    "[POST " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                            + (int) (buffer.length() / 1024) + "k] Downloaded " + "http://" + host + path + "?"
                            + paramsLog);

            connection.disconnect();
            br.close();
            ins.close();
            inr.close();
        } catch (IOException e) {
            Log.e(cgSettings.tag, "cgeoBase.requestJSONgc.IOException: " + e.toString());
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgeoBase.requestJSONgc: " + e.toString());
        }

        if (buffer != null && buffer.length() > 0) {
            break;
        }
    }

    String page = null;
    if (httpCode == 302 && httpLocation != null) {
        final Uri newLocation = Uri.parse(httpLocation);
        if (newLocation.isRelative()) {
            page = requestJSONgc(host, path, params);
        } else {
            page = requestJSONgc(newLocation.getHost(), newLocation.getPath(), params);
        }
    } else {
        replaceWhitespace(buffer);
        page = buffer.toString();
    }

    if (page != null) {
        return page;
    } else {
        return "";
    }
}

From source file:com.irccloud.android.activity.MainActivity.java

private boolean open_uri(Uri uri) {
    if (uri != null && conn != null && conn.ready) {
        launchURI = null;//from   w w w. j ava2  s .com
        ServersDataSource.Server s = null;
        try {
            if (uri.getHost().equals("cid")) {
                s = ServersDataSource.getInstance().getServer(Integer.parseInt(uri.getPathSegments().get(0)));
            }
        } catch (NumberFormatException e) {

        }
        if (s == null) {
            if (uri.getPort() > 0)
                s = ServersDataSource.getInstance().getServer(uri.getHost(), uri.getPort());
            else if (uri.getScheme() != null && uri.getScheme().equalsIgnoreCase("ircs"))
                s = ServersDataSource.getInstance().getServer(uri.getHost(), true);
            else
                s = ServersDataSource.getInstance().getServer(uri.getHost());
        }

        if (s != null) {
            if (uri.getPath() != null && uri.getPath().length() > 1) {
                String key = null;
                String channel = uri.getLastPathSegment();
                if (channel.contains(",")) {
                    key = channel.substring(channel.indexOf(",") + 1);
                    channel = channel.substring(0, channel.indexOf(","));
                }
                BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(s.cid, channel);
                if (b != null) {
                    server = null;
                    return open_bid(b.bid);
                } else {
                    onBufferSelected(-1);
                    title.setText(channel);
                    getSupportActionBar().setTitle(channel);
                    bufferToOpen = channel;
                    conn.join(s.cid, channel, key);
                }
                return true;
            } else {
                BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(s.cid, "*");
                if (b != null)
                    return open_bid(b.bid);
            }
        } else {
            if (!getResources().getBoolean(R.bool.isTablet)) {
                Intent i = new Intent(this, EditConnectionActivity.class);
                i.putExtra("hostname", uri.getHost());
                if (uri.getPort() > 0)
                    i.putExtra("port", uri.getPort());
                else if (uri.getScheme().equalsIgnoreCase("ircs"))
                    i.putExtra("port", 6697);
                if (uri.getPath() != null && uri.getPath().length() > 1)
                    i.putExtra("channels", uri.getPath().substring(1).replace(",", " "));
                startActivity(i);
            } else {
                EditConnectionFragment connFragment = new EditConnectionFragment();
                connFragment.default_hostname = uri.getHost();
                if (uri.getPort() > 0)
                    connFragment.default_port = uri.getPort();
                else if (uri.getScheme().equalsIgnoreCase("ircs"))
                    connFragment.default_port = 6697;
                if (uri.getPath() != null && uri.getPath().length() > 1)
                    connFragment.default_channels = uri.getPath().substring(1).replace(",", " ");
                connFragment.show(getSupportFragmentManager(), "addnetwork");
            }
            return true;
        }
    }
    return false;
}

From source file:cgeo.geocaching.cgBase.java

public cgResponse request(boolean secure, String host, String path, String method, String params, int requestId,
        Boolean xContentType) {//from w w w. j ava  2s.c  om
    URL u = null;
    int httpCode = -1;
    String httpMessage = null;
    String httpLocation = null;

    if (requestId == 0) {
        requestId = (int) (Math.random() * 1000);
    }

    if (method == null
            || (method.equalsIgnoreCase("GET") == false && method.equalsIgnoreCase("POST") == false)) {
        method = "POST";
    } else {
        method = method.toUpperCase();
    }

    // https
    String scheme = "http://";
    if (secure) {
        scheme = "https://";
    }

    String cookiesDone = CookieJar.getCookiesAsString(prefs);

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    StringBuffer buffer = null;

    for (int i = 0; i < 5; i++) {
        if (i > 0) {
            Log.w(cgSettings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer = new StringBuffer();
        timeout = 30000 + (i * 10000);

        try {
            if (method.equals("GET")) {
                // GET
                u = new URL(scheme + host + path + "?" + params);
                uc = u.openConnection();

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Cookie", cookiesDone);
                if (xContentType) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }

                if (settings.asBrowser == 1) {
                    uc.setRequestProperty("Accept",
                            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
                    // uc.setRequestProperty("Accept-Encoding", "gzip"); // not supported via cellular network
                    uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                    uc.setRequestProperty("Accept-Language", "en-US");
                    uc.setRequestProperty("User-Agent", idBrowser);
                    uc.setRequestProperty("Connection", "keep-alive");
                    uc.setRequestProperty("Keep-Alive", "300");
                }

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false);
                connection.setDoInput(true);
                connection.setDoOutput(false);
            } else {
                // POST
                u = new URL(scheme + host + path);
                uc = u.openConnection();

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Cookie", cookiesDone);
                if (xContentType) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }

                if (settings.asBrowser == 1) {
                    uc.setRequestProperty("Accept",
                            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
                    // uc.setRequestProperty("Accept-Encoding", "gzip"); // not supported via cellular network
                    uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                    uc.setRequestProperty("Accept-Language", "en-US");
                    uc.setRequestProperty("User-Agent", idBrowser);
                    uc.setRequestProperty("Connection", "keep-alive");
                    uc.setRequestProperty("Keep-Alive", "300");
                }

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false);
                connection.setDoInput(true);
                connection.setDoOutput(true);

                final OutputStream out = connection.getOutputStream();
                final OutputStreamWriter wr = new OutputStreamWriter(out);
                wr.write(params);
                wr.flush();
                wr.close();
            }

            CookieJar.setCookies(prefs, uc);

            InputStream ins = getInputstreamFromConnection(connection);
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr, 16 * 1024);

            readIntoBuffer(br, buffer);

            httpCode = connection.getResponseCode();
            httpMessage = connection.getResponseMessage();
            httpLocation = uc.getHeaderField("Location");

            final String paramsLog = params.replaceAll(passMatch, "password=***");
            Log.i(cgSettings.tag + "|" + requestId,
                    "[" + method + " " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                            + (int) (buffer.length() / 1024) + "k] Downloaded " + scheme + host + path + "?"
                            + paramsLog);

            connection.disconnect();
            br.close();
            ins.close();
            inr.close();
        } catch (IOException e) {
            Log.e(cgSettings.tag, "cgeoBase.request.IOException: " + e.toString());
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgeoBase.request: " + e.toString());
        }

        if (buffer.length() > 0) {
            break;
        }
    }

    cgResponse response = new cgResponse();

    try {
        if (httpCode == 302 && httpLocation != null) {
            final Uri newLocation = Uri.parse(httpLocation);
            if (newLocation.isRelative()) {
                response = request(secure, host, path, "GET", new HashMap<String, String>(), requestId, false,
                        false, false);
            } else {
                boolean secureRedir = false;
                if (newLocation.getScheme().equals("https")) {
                    secureRedir = true;
                }
                response = request(secureRedir, newLocation.getHost(), newLocation.getPath(), "GET",
                        new HashMap<String, String>(), requestId, false, false, false);
            }
        } else {
            if (StringUtils.isNotEmpty(buffer)) {
                replaceWhitespace(buffer);
                String data = buffer.toString();
                buffer = null;

                if (data != null) {
                    response.setData(data);
                } else {
                    response.setData("");
                }
                response.setStatusCode(httpCode);
                response.setStatusMessage(httpMessage);
                response.setUrl(u.toString());
            }
        }
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgeoBase.page: " + e.toString());
    }

    return response;
}