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:id.ridon.keude.AppDetailsData.java

/**
 * Attempt to extract the appId from the intent which launched this activity.
 * Various different intents could cause us to show this activity, such as:
 * <ul>// w ww.j a  v a 2  s. c om
 *     <li>market://details?id=[app_id]</li>
 *     <li>https://f-droid.org/app/[app_id]</li>
 *     <li>fdroid.app:[app_id]</li>
 * </ul>
 * @return May return null, if we couldn't find the appId. In this case, you will
 * probably want to do something drastic like finish the activity and show some
 * feedback to the user (this method will <em>not</em> do that, it will just return
 * null).
 */
private String getAppIdFromIntent() {
    Intent i = getIntent();
    Uri data = i.getData();
    String appId = null;
    if (data != null) {
        if (data.isHierarchical()) {
            if (data.getHost() != null && data.getHost().equals("details")) {
                // market://details?id=app.id
                appId = data.getQueryParameter("id");
            } else {
                // https://f-droid.org/app/app.id
                appId = data.getLastPathSegment();
                if (appId != null && appId.equals("app")) {
                    appId = null;
                }
            }
        } else {
            // fdroid.app:app.id
            appId = data.getEncodedSchemeSpecificPart();
        }
        Log.d(TAG, "AppDetails launched from link, for '" + appId + "'");
    } else if (!i.hasExtra(EXTRA_APPID)) {
        Log.e(TAG, "No application ID in AppDetails!?");
    } else {
        appId = i.getStringExtra(EXTRA_APPID);
    }
    return appId;
}

From source file:org.appcelerator.titanium.util.TiUIHelper.java

/**
 * To get the redirected Uri/*w ww . j a v  a 2s.co m*/
 * @param Uri
 */
public static Uri getRedirectUri(Uri mUri) throws MalformedURLException, IOException {
    if (!TiC.HONEYCOMB_OR_GREATER && ("http".equals(mUri.getScheme()) || "https".equals(mUri.getScheme()))) {
        // Media player doesn't handle redirects, try to follow them
        // here. (Redirects work fine without this in ICS.)
        while (true) {
            // java.net.URL doesn't handle rtsp
            if (mUri.getScheme() != null && mUri.getScheme().equals("rtsp"))
                break;

            URL url = new URL(mUri.toString());
            HttpURLConnection cn = (HttpURLConnection) url.openConnection();
            cn.setInstanceFollowRedirects(false);
            String location = cn.getHeaderField("Location");
            if (location != null) {
                String host = mUri.getHost();
                int port = mUri.getPort();
                String scheme = mUri.getScheme();
                mUri = Uri.parse(location);
                if (mUri.getScheme() == null) {
                    // Absolute URL on existing host/port/scheme
                    if (scheme == null) {
                        scheme = "http";
                    }
                    String authority = port == -1 ? host : host + ":" + port;
                    mUri = mUri.buildUpon().scheme(scheme).encodedAuthority(authority).build();
                }
            } else {
                break;
            }
        }
    }
    return mUri;
}

From source file:de.cachebox_test.splash.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (!FileFactory.isInitial()) {
        new AndroidFileFactory();
    }/*w  ww. j av  a  2 s.  c  o  m*/

    requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.splash);

    DisplayMetrics displaymetrics = this.getResources().getDisplayMetrics();

    GlobalCore.displayDensity = displaymetrics.density;
    int h = displaymetrics.heightPixels;
    int w = displaymetrics.widthPixels;

    int sw = h > w ? w : h;
    sw /= GlobalCore.displayDensity;

    // check if tablet
    GlobalCore.isTab = sw > 400 ? true : false;

    int dpH = (int) (h / GlobalCore.displayDensity + 0.5);
    int dpW = (int) (w / GlobalCore.displayDensity + 0.5);

    if (dpH * dpW >= 960 * 720)
        GlobalCore.displayType = DisplayType.xLarge;
    else if (dpH * dpW >= 640 * 480)
        GlobalCore.displayType = DisplayType.Large;
    else if (dpH * dpW >= 470 * 320)
        GlobalCore.displayType = DisplayType.Normal;
    else
        GlobalCore.displayType = DisplayType.Small;

    // berprfen, ob ACB im Hochformat oder Querformat gestartet wurde.
    // Hochformat -> Handymodus
    // Querformat -> Tablet-Modus
    if (w > h)
        isLandscape = true;

    // Portrt erzwingen wenn Normal oder Small display
    if (isLandscape
            && (GlobalCore.displayType == DisplayType.Normal || GlobalCore.displayType == DisplayType.Small)) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    // chek if use small skin
    GlobalCore.useSmallSkin = GlobalCore.displayType == DisplayType.Small ? true : false;

    // chk if tabletLayout posible
    GlobalCore.posibleTabletLayout = (GlobalCore.displayType == DisplayType.xLarge
            || GlobalCore.displayType == DisplayType.Large);

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

    // try to get data from extras
    if (extras != null) {
        GcCode = extras.getString("geocode");
        name = extras.getString("name");
        guid = extras.getString("guid");
    }

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

        if (uriHost.contains("geocaching.com")) {
            GcCode = uri.getQueryParameter("wp");
            guid = uri.getQueryParameter("guid");

            if (GcCode != null && GcCode.length() > 0) {
                GcCode = GcCode.toUpperCase();
                guid = null;
            } else if (guid != null && guid.length() > 0) {
                GcCode = null;
                guid = guid.toLowerCase();
            } else {
                // warning.showToast(res.getString(R.string.err_detail_open));
                finish();
                return;
            }
        } else if (uriHost.contains("coord.info")) {
            if (uriPath != null && uriPath.startsWith("/gc")) {
                GcCode = uriPath.substring(1).toUpperCase();
            } else {
                // warning.showToast(res.getString(R.string.err_detail_open));
                finish();
                return;
            }
        }
    }

    if (uri != null) {
        if (uri.getEncodedPath().endsWith(".gpx")) {
            GpxPath = uri.getEncodedPath();
        }
    }

    // if ACB running, call this instance
    if (main.mainActivity != null) {

        Bundle b = new Bundle();
        if (GcCode != null) {

            b.putSerializable("GcCode", GcCode);
            b.putSerializable("name", name);
            b.putSerializable("guid", guid);

        }

        if (GpxPath != null) {
            b.putSerializable("GpxPath", GpxPath);
        }

        Intent mainIntent = main.mainActivity.getIntent();

        mainIntent.putExtras(b);

        startActivity(mainIntent);
        finish();
    }

    splashActivity = this;

    LoadImages();

    if (savedInstanceState != null) {
        mSelectDbIsStartet = savedInstanceState.getBoolean("SelectDbIsStartet");
        mOriantationRestart = savedInstanceState.getBoolean("OriantationRestart");
    }

    if (mOriantationRestart)
        return; // wait for result

}

From source file:org.planetmono.dcuploader.ActivityUploader.java

@SuppressWarnings("unchecked")
@Override//from  ww  w .  j a  v  a 2s.  c om
public void onCreate(Bundle savedState) {
    super.onCreate(savedState);

    initViews();
    if (formLocation)
        queryLocation(true);

    if (savedState != null) {
        if (savedState.containsKey("tempfile"))
            tempFile = new File(savedState.getString("tempfile"));
        if (savedState.containsKey("target"))
            resolveTarget(savedState.getString("target"));
        if (savedState.containsKey("tempfiles"))
            tempFiles = savedState.getStringArrayList("tempfiles");
        if (savedState.containsKey("contents")) {
            contents = new ArrayList<Uri>();
            String[] carr = savedState.getStringArray("contents");
            for (String s : carr)
                contents.add(Uri.parse(s));
        }
    }

    postfix = "from <a href=\"http://palladium.planetmono.org/dcuploader\">DCUploader</a>";

    Button uploadVisit = (Button) findViewById(R.id.upload_visit);
    if (passThrough || target == null)
        uploadVisit.setEnabled(false);
    else
        uploadVisit.setEnabled(true);

    /* populate data by getting STREAM parameter */
    Intent i = getIntent();
    Bundle b = i.getExtras();
    String action = i.getAction();

    if (action.equals(Intent.ACTION_SEND) || action.equals(Intent.ACTION_SEND_MULTIPLE)) {
        called = true;

        if (i.hasExtra(Intent.EXTRA_STREAM)) {
            Object o = b.get(Intent.EXTRA_STREAM);

            /* quick and dirty. any better idea? */
            try {
                contents.add((Uri) o);
            } catch (Exception e1) {
                try {
                    contents = (ArrayList<Uri>) ((ArrayList<Uri>) o).clone();
                } catch (Exception e2) {
                }
            }

            boolean exceeded = false;
            if (contents.size() > 5) {
                exceeded = true;

                do {
                    contents.remove(5);
                } while (contents.size() > 5);
            }

            galleryChanged = true;

            updateImageButtons();
            resetThumbnails();
            updateGallery();

            if (exceeded)
                Toast.makeText(this,
                        " 5  . 5 ??? ? ?.",
                        Toast.LENGTH_LONG).show();
        }
        if (i.hasExtra(Intent.EXTRA_TEXT)) {
            ((EditText) findViewById(R.id.upload_text)).setText(b.getString(Intent.EXTRA_TEXT));
        }
    } else if (action.equals("share")) {
        called = true;
        /* HTC web browser uses non-standard intent */

        ((EditText) findViewById(R.id.upload_text)).setText(b.getString(Intent.EXTRA_TITLE));
    } else if (action.equals(Intent.ACTION_VIEW)) {
        Uri uri = i.getData();

        if (i.getCategories().contains(Intent.CATEGORY_BROWSABLE)) {
            passThrough = true;

            Pattern p = Pattern.compile("id=([\\-a-zA-Z0-9_]+)");
            Matcher m = p.matcher(uri.toString());

            if (m.find()) {
                resolveTarget(m.group(1));
            } else {
                passThrough = false;
            }

            if (uri.getHost().equals(Application.HOST_DCMYS)) {
                destination = Application.DESTINATION_DCMYS;
                postfix = "from dc.m.dcmys.kr w/ <a href=\"http://palladium.planetmono.org/dcuploader\">DCUploader</a>";
            } else if (uri.getHost().equals(Application.HOST_MOOLZO)) {
                destination = Application.DESTINATION_MOOLZO;
                postfix = "- From m.oolzo.com w/ <a href=\"http://palladium.planetmono.org/dcuploader\">DCUploader</a>";
            } else if (uri.getHost().equals(Application.HOST_DCINSIDE)) {
                destination = Application.DESTINATION_DCINSIDE;
            }

            setDefaultImage();
        }
    }

    reloadConfigurations();
}

From source file:androidVNC.VncCanvasActivity.java

@Override
public void onCreate(Bundle icicle) {

    super.onCreate(icicle);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    database = new VncDatabase(this);
    connection = new ConnectionBean();

    Intent i = getIntent();/*w  ww .j  a  va 2 s  . c o m*/
    Uri data = i.getData();
    if ((data != null) && (data.getScheme().equals("vnc"))) {
        String host = data.getHost();
        // This should not happen according to Uri contract, but bug introduced in Froyo (2.2)
        // has made this parsing of host necessary
        int index = host.indexOf(':');
        int port;
        if (index != -1) {
            try {
                port = Integer.parseInt(host.substring(index + 1));
            } catch (NumberFormatException nfe) {
                port = 0;
            }
            host = host.substring(0, index);
        } else {
            port = data.getPort();
        }
        if (host.equals(VncConstants.CONNECTION)) {
            if (connection.Gen_read(database.getReadableDatabase(), port)) {
                MostRecentBean bean = androidVNC.getMostRecent(database.getReadableDatabase());
                if (bean != null) {
                    bean.setConnectionId(connection.get_Id());
                    bean.Gen_update(database.getWritableDatabase());
                }
            }
        } else {
            connection.setAddress(host);
            connection.setNickname(connection.getAddress());
            connection.setPort(port);
            List<String> path = data.getPathSegments();
            if (path.size() >= 1) {
                connection.setColorModel(path.get(0));
            }
            if (path.size() >= 2) {
                connection.setPassword(path.get(1));
            }
            connection.save(database.getWritableDatabase());
        }
    } else {

        Bundle extras = i.getExtras();

        if (extras != null) {
            connection.Gen_populate((ContentValues) extras.getParcelable(VncConstants.CONNECTION));
        }
        if (connection.getPort() == 0)
            connection.setPort(5900);

        // Parse a HOST:PORT entry
        String host = connection.getAddress();
        if (host.indexOf(':') > -1) {
            String p = host.substring(host.indexOf(':') + 1);
            try {
                connection.setPort(Integer.parseInt(p));
            } catch (Exception e) {
            }
            connection.setAddress(host.substring(0, host.indexOf(':')));
        }
    }

    try {
        setContentView(fi.aalto.openoranges.project1.mcc.R.layout.canvas);
        vncCanvas = (VncCanvas) findViewById(fi.aalto.openoranges.project1.mcc.R.id.vnc_canvas);
        zoomer = (ZoomControls) findViewById(R.id.zoomer);
    } catch (Exception e) {
        e.printStackTrace();
    }

    vncCanvas.initializeVncCanvas(connection, new Runnable() {
        public void run() {
            setModes();
        }
    });
    vncCanvas.setOnGenericMotionListener(this);
    zoomer.hide();

    zoomer.setOnZoomInClickListener(new View.OnClickListener() {

        /*
         * (non-Javadoc)
         *
         * @see android.view.View.OnClickListener#onClick(android.view.View)
         */
        @Override
        public void onClick(View v) {
            showZoomer(true);
            vncCanvas.scaling.zoomIn(VncCanvasActivity.this);

        }

    });
    zoomer.setOnZoomOutClickListener(new View.OnClickListener() {

        /*
         * (non-Javadoc)
         *
         * @see android.view.View.OnClickListener#onClick(android.view.View)
         */
        @Override
        public void onClick(View v) {
            showZoomer(true);
            vncCanvas.scaling.zoomOut(VncCanvasActivity.this);

        }

    });
    zoomer.setOnZoomKeyboardClickListener(new View.OnClickListener() {

        /*
         * (non-Javadoc)
         *
         * @see android.view.View.OnClickListener#onClick(android.view.View)
         */
        @Override
        public void onClick(View v) {
            InputMethodManager inputMgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMgr.toggleSoftInput(0, 0);
        }

    });

    panner = new Panner(this, vncCanvas.handler);
    inputHandler = getInputHandlerById(fi.aalto.openoranges.project1.mcc.R.id.itemInputFitToScreen);

    mToken = getIntent().getStringExtra("token");
    mId = getIntent().getStringExtra("id");
    mName = getIntent().getStringExtra("name");

    //listener for the back-button
    registerClickCallback();

    //Notification in status bar
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(VncCanvasActivity.this)
            .setSmallIcon(R.drawable.icon_white).setContentTitle(mName + " running")
            .setContentText("Click to open the application screen");

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(VncCanvasActivity.this, VncCanvasActivity.class);
    resultIntent.setAction(Long.toString(System.currentTimeMillis()));
    mBuilder.setContentIntent(PendingIntent.getActivity(VncCanvasActivity.this, 0, resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT));

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    // mNotifyID allows you to update the notification later on.
    mNotificationManager.notify(mNotifyId, mBuilder.build());
    startService();
}

From source file:com.iiordanov.bVNC.RemoteCanvasActivity.java

void initialize() {
    if (android.os.Build.VERSION.SDK_INT >= 9) {
        android.os.StrictMode.ThreadPolicy policy = new android.os.StrictMode.ThreadPolicy.Builder().permitAll()
                .build();/*from  www  .ja  v  a  2  s .co  m*/
        android.os.StrictMode.setThreadPolicy(policy);
    }

    handler = new Handler();

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    database = new Database(this);

    Intent i = getIntent();
    connection = null;

    Uri data = i.getData();

    boolean isSupportedScheme = false;
    if (data != null) {
        String s = data.getScheme();
        isSupportedScheme = s.equals("rdp") || s.equals("spice") || s.equals("vnc");
    }

    if (isSupportedScheme || !Utils.isNullOrEmptry(i.getType())) {
        if (isMasterPasswordEnabled()) {
            Utils.showFatalErrorMessage(this,
                    getResources().getString(R.string.master_password_error_intents_not_supported));
            return;
        }

        connection = ConnectionBean.createLoadFromUri(data, this);

        String host = data.getHost();
        if (!host.startsWith(Constants.CONNECTION)) {
            connection.parseFromUri(data);
        }

        if (connection.isSaved()) {
            connection.saveAndWriteRecent(false);
        }
        // we need to save the connection to display the loading screen, so otherwise we should exit
        if (!connection.isReadyForConnection()) {
            if (!connection.isSaved()) {
                Log.i(TAG, "Exiting - Insufficent information to connect and connection was not saved.");
                Toast.makeText(this, getString(R.string.error_uri_noinfo_nosave), Toast.LENGTH_LONG).show();
                ;
            } else {
                // launch bVNC activity
                Log.i(TAG, "Insufficent information to connect, showing connection dialog.");
                Intent bVncIntent = new Intent(this, bVNC.class);
                startActivity(bVncIntent);
            }
            finish();
            return;
        }
    } else {
        connection = new ConnectionBean(this);
        Bundle extras = i.getExtras();

        if (extras != null) {
            connection.Gen_populate((ContentValues) extras.getParcelable(Constants.CONNECTION));
        }

        // Parse a HOST:PORT entry
        String host = connection.getAddress();
        if (host.indexOf(':') > -1) {
            String p = host.substring(host.indexOf(':') + 1);
            try {
                connection.setPort(Integer.parseInt(p));
            } catch (Exception e) {
            }
            connection.setAddress(host.substring(0, host.indexOf(':')));
        }

        if (connection.getPort() == 0)
            connection.setPort(Constants.DEFAULT_VNC_PORT);

        if (connection.getSshPort() == 0)
            connection.setSshPort(Constants.DEFAULT_SSH_PORT);
    }
}

From source file:com.juick.android.MainActivity.java

private boolean parseUri(Uri uri, boolean shouldFinish) {
    List<String> segs = uri.getPathSegments();
    if (uri == null || uri.getHost() == null)
        return true;
    if (uri.getHost().contains("juick.com")) {
        if ((segs.size() == 1 && segs.get(0).matches("\\A[0-9]+\\z"))
                || (segs.size() == 2 && segs.get(1).matches("\\A[0-9]+\\z") && !segs.get(0).equals("places"))) {
            int mid = Integer.parseInt(segs.get(segs.size() - 1));
            if (mid > 0) {
                if (shouldFinish)
                    finish();/*from  ww w. j a  v  a2s. c o m*/
                Intent intent = new Intent(this, ThreadActivity.class);
                intent.setData(null);
                JuickMessageID jmid = new JuickMessageID(mid);
                intent.putExtra("mid", jmid);
                intent.putExtra("messagesSource", ChildrenMessageSource.forMID(this, jmid));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                return true;
            }
        } else if (segs.size() == 1 && segs.get(0).matches("\\A[a-zA-Z0-9\\-]+\\z")) {
            //TODO show user
        }
    }
    if (uri.getHost().contains("bnw.im")) {
        String[] hostPart = uri.getHost().split("\\.");
        if (hostPart.length == 2 && segs.size() == 2 && segs.get(0).equals("p")) { // http://bnw.im/p/KLMNOP
            // open thread
            if (shouldFinish)
                finish();
            Intent intent = new Intent(this, ThreadActivity.class);
            intent.setData(null);
            BnwMessageID mid = new BnwMessageID(segs.get(1));
            intent.putExtra("mid", mid);
            intent.putExtra("messagesSource", ChildrenMessageSource.forMID(this, mid));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }

    }
    if (uri.getHost().contains("point.im")) {
        String s = uri.toString();
        if (s.endsWith("/"))
            return false;
        s = s.substring(s.indexOf("point.im") + 9);
        if (s.contains("#")) {
            s = s.substring(0, s.indexOf("#"));
        }
        if (s.contains("/") || s.length() > 6)
            return false;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) != Character.toLowerCase(s.charAt(i)))
                return false;
        }
        PointMessageID mid = new PointMessageID("", s, -1);
        Intent intent = new Intent(this, ThreadActivity.class);
        intent.setData(null);
        intent.putExtra("mid", mid);
        intent.putExtra("messagesSource", ChildrenMessageSource.forMID(this, mid));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);

    }
    return false;
}

From source file:com.iiordanov.runsoft.bVNC.RemoteCanvasActivity.java

void initialize() {
    if (android.os.Build.VERSION.SDK_INT >= 9) {
        android.os.StrictMode.ThreadPolicy policy = new android.os.StrictMode.ThreadPolicy.Builder().permitAll()
                .build();/*from w ww  .  j a  v  a  2s.  co  m*/
        android.os.StrictMode.setThreadPolicy(policy);
    }

    handler = new Handler();

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    database = new Database(this);

    Intent i = getIntent();
    connection = null;

    Uri data = i.getData();

    Log.e(TAG, "uri=" + data);

    boolean isSupportedScheme = false;
    if (data != null) {
        String s = data.getScheme();
        isSupportedScheme = s.equals("rdp") || s.equals("spice") || s.equals("vnc");
    }

    if (isSupportedScheme || !Utils.isNullOrEmptry(i.getType())) {
        if (isMasterPasswordEnabled()) {
            Utils.showFatalErrorMessage(this,
                    getResources().getString(R.string.master_password_error_intents_not_supported));
            return;
        }

        connection = ConnectionBean.createLoadFromUri(data, this);

        String host = data.getHost();
        if (!host.startsWith(Constants.CONNECTION)) {
            connection.parseFromUri(data);
        }

        if (connection.isSaved()) {
            connection.saveAndWriteRecent(false);
        }
        // we need to save the connection to display the loading screen, onclso otherwise we should exit
        if (!connection.isReadyForConnection()) {
            if (!connection.isSaved()) {
                Log.i(TAG, "Exiting - Insufficent information to connect and connection was not saved.");
                Toast.makeText(this, getString(R.string.error_uri_noinfo_nosave), Toast.LENGTH_LONG).show();
                ;
            } else {
                // launch bVNC activity
                Log.i(TAG, "Insufficent information to connect, showing connection dialog.");
                Intent bVncIntent = new Intent(this, bVNC.class);
                startActivity(bVncIntent);
            }
            finish();
            return;
        }
    } else {
        connection = new ConnectionBean(this);
        Bundle extras = i.getExtras();

        if (extras != null) {
            connection.Gen_populate((ContentValues) extras.getParcelable(Constants.CONNECTION));
        }

        // Parse a HOST:PORT entry
        String host = connection.getAddress();
        if (!Utils.isValidIpv6Address(host) && host.indexOf(':') > -1) {
            String p = host.substring(host.indexOf(':') + 1);
            try {
                int parsedPort = Integer.parseInt(p);
                connection.setPort(parsedPort);
                connection.setAddress(host.substring(0, host.indexOf(':')));
            } catch (Exception e) {
            }
        }

        if (connection.getPort() == 0)
            connection.setPort(Constants.DEFAULT_VNC_PORT);

        if (connection.getSshPort() == 0)
            connection.setSshPort(Constants.DEFAULT_SSH_PORT);
    }
}

From source file:com.owncloud.android.authentication.AuthenticatorActivity.java

/**
 * Creates a new account through the Account Authenticator that started this
 * activity./*from  ww w. j  av a 2  s  .c o  m*/
 * 
 * This makes the account permanent.
 * 
 * TODO Decide how to name the OAuth accounts
 */
private boolean createAccount() {
    // / create and save new ownCloud account
    boolean isOAuth = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mAuthTokenType);
    boolean isSaml = AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType);

    Uri uri = Uri.parse(mHostBaseUrl);
    String username = mUsernameInput.getText().toString().trim();
    username = username + "@" + location;

    if (isSaml) {
        username = getUserNameForSamlSso();

    } else if (isOAuth) {
        username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();
    }
    String accountName = username + "@" + uri.getHost();
    if (uri.getPort() >= 0) {
        accountName += ":" + uri.getPort();
    }

    mAccount = new Account(accountName, AccountAuthenticator.ACCOUNT_TYPE);
    if (AccountUtils.exists(mAccount, getApplicationContext())) {
        // fail - not a new account, but an existing one; disallow
        RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW);
        updateAuthStatusIconAndText(result);
        showAuthStatus();
        Log_OC.d(TAG, result.getLogMessage());
        return false;

    } else {

        if (isOAuth || isSaml) {
            mAccountMgr.addAccountExplicitly(mAccount, "", null); // with
                                                                  // external
                                                                  // authorizations,
                                                                  // the
                                                                  // password
                                                                  // is
                                                                  // never
                                                                  // input
                                                                  // in the
                                                                  // app
        } else {
            mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);
        }

        // / add the new account as default in preferences, if there is none
        // already
        Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
        if (defaultAccount == null) {
            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
            editor.putString("select_oc_account", accountName);
            editor.commit();
        }

        // / prepare result to return to the Authenticator
        // TODO check again what the Authenticator makes with it; probably
        // has the same effect as addAccountExplicitly, but it's not well
        // done
        final Intent intent = new Intent();
        intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, AccountAuthenticator.ACCOUNT_TYPE);
        intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
        /*
         * if (!isOAuth) intent.putExtra(AccountManager.KEY_AUTHTOKEN,
         * AccountAuthenticator.ACCOUNT_TYPE);
         */
        intent.putExtra(AccountManager.KEY_USERDATA, username);
        if (isOAuth || isSaml) {
            mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
        }
        // / add user data to the new account; TODO probably can be done in
        // the last parameter addAccountExplicitly, or in KEY_USERDATA
        mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION, mDiscoveredVersion.toString());
        mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL, mHostBaseUrl);
        if (isSaml) {
            mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE");
        } else if (isOAuth) {
            mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_OAUTH2, "TRUE");
        }

        setAccountAuthenticatorResult(intent.getExtras());
        setResult(RESULT_OK, intent);

        // / immediately request for the synchronization of the new account
        Bundle bundle = new Bundle();
        bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
        ContentResolver.requestSync(mAccount, AccountAuthenticator.AUTHORITY, bundle);
        syncAccount();
        // Bundle bundle = new Bundle();
        // bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
        // ContentResolver.requestSync(mAccount,
        // AccountAuthenticator.AUTHORITY, bundle);
        return true;
    }
}

From source file:info.guardianproject.otr.app.im.app.NewChatActivity.java

private void doResolveIntent(Intent intent) {

    if (requireOpenDashboardOnStart(intent)) {
        long providerId = intent.getLongExtra(ImServiceConstants.EXTRA_INTENT_PROVIDER_ID, -1L);
        mLastAccountId = intent.getLongExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID, -1L);
        if (providerId == -1L || mLastAccountId == -1L) {
            finish();//from www  .j  av a  2  s .  c  o m
        } else {
            //   mChatSwitcher.open();
        }
        return;
    }

    if (ImServiceConstants.ACTION_MANAGE_SUBSCRIPTION.equals(intent.getAction())) {

        long providerId = intent.getLongExtra(ImServiceConstants.EXTRA_INTENT_PROVIDER_ID, -1);
        mLastAccountId = intent.getLongExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID, -1L);
        String from = intent.getStringExtra(ImServiceConstants.EXTRA_INTENT_FROM_ADDRESS);

        if ((providerId == -1) || (from == null)) {
            finish();
        } else {

            showSubscriptionDialog(providerId, from);

        }
    } else if (intent != null) {
        Uri data = intent.getData();

        if (intent.getBooleanExtra("showaccounts", false))
            mDrawer.openDrawer(GravityCompat.START);

        if (data != null) {
            if (data.getScheme() != null && data.getScheme().equals("immu")) {
                String user = data.getUserInfo();
                String host = data.getHost();
                String path = null;

                if (data.getPathSegments().size() > 0)
                    path = data.getPathSegments().get(0);

                if (host != null && path != null) {

                    IImConnection connMUC = findConnectionForGroupChat(user, host);

                    if (connMUC != null) {

                        startGroupChat(path, host, user, connMUC);
                        setResult(RESULT_OK);
                    } else {
                        mHandler.showAlert("Connection Error",
                                "Unable to find a connection to join a group chat from. Please sign in and try again.");
                        setResult(Activity.RESULT_CANCELED);
                        finish();
                    }

                }

            } else {

                String type = getContentResolver().getType(data);
                if (Imps.Chats.CONTENT_ITEM_TYPE.equals(type)) {

                    long requestedContactId = ContentUris.parseId(data);

                    Cursor cursorChats = mChatPagerAdapter.getCursor();

                    if (cursorChats != null) {
                        cursorChats.moveToPosition(-1);
                        int posIdx = 1;
                        boolean foundChatView = false;

                        while (cursorChats.moveToNext()) {
                            long chatId = cursorChats.getLong(ChatView.CONTACT_ID_COLUMN);

                            if (chatId == requestedContactId) {
                                mChatPager.setCurrentItem(posIdx);
                                foundChatView = true;
                                break;
                            }

                            posIdx++;
                        }

                        if (!foundChatView) {

                            Uri.Builder builder = Imps.Contacts.CONTENT_URI.buildUpon();
                            ContentUris.appendId(builder, requestedContactId);
                            Cursor cursor = getContentResolver().query(builder.build(),
                                    ChatView.CHAT_PROJECTION, null, null, null);

                            try {
                                if (cursor.getCount() > 0) {
                                    cursor.moveToFirst();
                                    openExistingChat(cursor);
                                }
                            } finally {
                                cursor.close();
                            }
                        }
                    }

                } else if (Imps.Invitation.CONTENT_ITEM_TYPE.equals(type)) {
                    //chatView.bindInvitation(ContentUris.parseId(data));

                }
            }
        } else if (intent.hasExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID)) {
            //set the current account id
            mLastAccountId = intent.getLongExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID, -1L);

            //move the pager back to the first page
            if (mChatPager != null)
                mChatPager.setCurrentItem(0);

        } else {
            //  refreshConnections();
        }
    }

}