Example usage for android.util Patterns WEB_URL

List of usage examples for android.util Patterns WEB_URL

Introduction

In this page you can find the example usage for android.util Patterns WEB_URL.

Prototype

Pattern WEB_URL

To view the source code for android.util Patterns WEB_URL.

Click Source Link

Document

Regular expression pattern to match most part of RFC 3987 Internationalized URLs, aka IRIs.

Usage

From source file:org.proninyaroslav.libretorrent.core.utils.Utils.java

public static String normalizeURL(String url) {
    if (!Patterns.WEB_URL.matcher(url).matches()) {
        return null;
    }/*from   w  w  w .j a v a2  s.  co  m*/

    if (!url.startsWith(HTTP_PREFIX) && !url.startsWith(HTTPS_PREFIX)) {
        return HTTP_PREFIX + "://" + url;
    } else {
        return url;
    }
}

From source file:com.scooter1556.sms.android.fragment.EditConnectionFragment.java

public void saveConnection() {
    // Populate connection
    if (connection == null) {
        connection = new Connection();
    }/*w  w w .  ja v a2 s  .  c  om*/

    connection.setTitle(nameText.getText().toString());
    connection.setUrl(urlText.getText().toString());
    connection.setUsername(usernameText.getText().toString());
    connection.setPassword(passwordText.getText().toString());

    if (connection.getTitle() == null || connection.getTitle().isEmpty()) {
        nameTextLayout.setError(getString(R.string.connections_no_name));
        nameText.requestFocus();
        return;
    } else {
        nameTextLayout.setErrorEnabled(false);
    }

    if (connection.getUrl() == null || !Patterns.WEB_URL.matcher(connection.getUrl()).matches()) {
        urlTextLayout.setError(getString(R.string.connections_invalid_url));
        urlText.requestFocus();
        return;
    } else {
        urlTextLayout.setErrorEnabled(false);
    }

    if (connection.getUsername() == null || connection.getUsername().isEmpty()) {
        usernameTextLayout.setError(getString(R.string.connections_no_username));
        usernameText.requestFocus();
        return;
    } else {
        usernameTextLayout.setErrorEnabled(false);
    }

    if (connection.getPassword() == null || connection.getPassword().isEmpty()) {
        passwordTextLayout.setError(getString(R.string.connections_no_password));
        passwordText.requestFocus();
        return;
    } else {
        passwordTextLayout.setErrorEnabled(false);
    }

    // Test connection
    RESTService.getInstance().testConnection(connection, new TextHttpResponseHandler() {
        Toast error;

        @Override
        public void onStart() {
            testProgress = ProgressDialog.show(getContext(), getString(R.string.connections_testing),
                    getString(R.string.notification_please_wait), true);
        }

        @Override
        public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers,
                String responseString) {
            int version = Integer.valueOf(responseString);

            testProgress.dismiss();

            if (version < RESTService.MIN_SUPPORTED_SERVER_VERSION) {
                error = Toast.makeText(getContext(), getString(R.string.error_unsupported_server_version),
                        Toast.LENGTH_SHORT);
                error.show();
            } else {
                // Save connection
                connectionListener.SaveConnection(connection);
            }
        }

        @Override
        public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers,
                String responseString, Throwable throwable) {
            testProgress.dismiss();

            switch (statusCode) {
            case 401:
                error = Toast.makeText(getContext(), getString(R.string.error_unauthenticated),
                        Toast.LENGTH_SHORT);
                error.show();
                break;

            case 404:
            case 0:
                error = Toast.makeText(getContext(), getString(R.string.error_server_not_found),
                        Toast.LENGTH_SHORT);
                error.show();
                break;

            default:
                error = Toast.makeText(getContext(), getString(R.string.error_server) + statusCode,
                        Toast.LENGTH_SHORT);
                error.show();
                break;
            }
        }

        @Override
        public void onRetry(int retryNo) {
            // Do nothing for now...
        }
    });
}

From source file:com.tomeokin.lspush.biz.home.UriDialogFragment.java

public boolean isValidWebUri(CharSequence url) {
    return Patterns.WEB_URL.matcher(url).matches();
}

From source file:com.jpventura.alexandria.AddBook.java

@Override
public void onLoadFinished(android.support.v4.content.Loader<Cursor> loader, Cursor data) {
    if (!data.moveToFirst()) {
        return;// w  w  w.jav a  2 s  . co m
    }

    String bookTitle = data.getString(data.getColumnIndex(AlexandriaContract.BookEntry.TITLE));
    ((TextView) rootView.findViewById(R.id.bookTitle)).setText(bookTitle);

    String bookSubTitle = data.getString(data.getColumnIndex(AlexandriaContract.BookEntry.SUBTITLE));
    ((TextView) rootView.findViewById(R.id.bookSubTitle)).setText(bookSubTitle);

    String authors = data.getString(data.getColumnIndex(AlexandriaContract.AuthorEntry.AUTHOR));
    String[] authorsArr = authors.split(",");
    ((TextView) rootView.findViewById(R.id.authors)).setLines(authorsArr.length);
    ((TextView) rootView.findViewById(R.id.authors)).setText(authors.replace(",", "\n"));
    String imgUrl = data.getString(data.getColumnIndex(AlexandriaContract.BookEntry.IMAGE_URL));
    if (Patterns.WEB_URL.matcher(imgUrl).matches()) {
        new DownloadImage((ImageView) rootView.findViewById(R.id.bookCover)).execute(imgUrl);
        rootView.findViewById(R.id.bookCover).setVisibility(View.VISIBLE);
    }

    String categories = data.getString(data.getColumnIndex(AlexandriaContract.CategoryEntry.CATEGORY));
    ((TextView) rootView.findViewById(R.id.categories)).setText(categories);

    rootView.findViewById(R.id.save_button).setVisibility(View.VISIBLE);
    rootView.findViewById(R.id.delete_button).setVisibility(View.VISIBLE);
}

From source file:org.runnerup.export.RuntasticUploader.java

@Override
public Status connect() {
    Exception ex = null;//from   w  w w  .  j av  a2  s.c o  m
    HttpURLConnection conn = null;
    formValues.clear();

    Status s = Status.NEED_AUTH;
    s.authMethod = AuthMethod.USER_PASS;
    if (username == null || password == null) {
        return s;
    }

    System.out.println("userId: " + userId + ", authToken: " + authToken);
    if (userId != null && authToken != null) {
        return Status.OK;
    }

    cookies.clear();

    try {
        /**
         * connect to START_URL to get cookies/formValues
         */
        conn = (HttpURLConnection) new URL(START_URL).openConnection();
        conn.setInstanceFollowRedirects(false);
        addRequestHeaders(conn);
        {
            //                int responseCode = conn.getResponseCode();
            //                String amsg = conn.getResponseMessage();
            getCookies(conn);
            getFormValues(conn);
            authToken = formValues.get("authenticity_token");
        }
        conn.disconnect();

        if (authToken == null)
            return Status.ERROR;

        /**
         * Then login using a post
         */
        FormValues kv = new FormValues();
        kv.put("user[email]", username);
        kv.put("user[password]", password);
        kv.put("authenticity-token", authToken);

        conn = (HttpURLConnection) new URL(LOGIN_URL).openConnection();
        conn.setInstanceFollowRedirects(false);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        addRequestHeaders(conn);
        conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        String url2 = null;
        {
            OutputStream wr = new BufferedOutputStream(conn.getOutputStream());
            kv.write(wr);
            wr.flush();
            wr.close();
            // int responseCode = conn.getResponseCode();
            // String amsg = conn.getResponseMessage();
            getCookies(conn);
            InputStream in = new BufferedInputStream(conn.getInputStream());
            JSONObject ret = parse(in);
            if (ret != null && ret.has("success") && ret.getBoolean("success")) {
                Matcher matcher = Patterns.WEB_URL.matcher(ret.getString("update"));
                while (matcher.find()) {
                    String tmp = matcher.group();
                    final String users = "/users/";
                    if (tmp.contains(users)) {
                        int i = tmp.indexOf(users) + users.length();
                        int i2 = tmp.indexOf('/', i);
                        if (i2 > 0)
                            url2 = tmp.substring(0, i2);
                        else
                            url2 = tmp;

                        if (url2 != null)
                            break;
                    }
                }
            }
            System.out.println("found url2: " + url2);
            conn.disconnect();
        }

        if (url2 == null) {
            return s;
        }

        {
            url2 = url2 + "?authenticity_token=" + URLEncode(authToken);
            conn = (HttpURLConnection) new URL(url2).openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Host", "www.runtastic.com");
            conn.addRequestProperty("Accept", "application/json");
            InputStream in = new BufferedInputStream(conn.getInputStream());
            getCookies(conn);
            JSONObject ret = parse(in);
            userId = ret.getJSONObject("user").getInt("id");
            conn.disconnect();
        }

        if (userId != null && authToken != null) {
            return Status.OK;
        }
    } catch (MalformedURLException e) {
        ex = e;
    } catch (IOException e) {
        ex = e;
    } catch (JSONException e) {
        ex = e;
    }

    if (conn != null)
        conn.disconnect();

    s.ex = ex;
    if (ex != null) {
        ex.printStackTrace();
    }
    return s;
}

From source file:org.runnerup.export.RuntasticSynchronizer.java

@Override
public Status connect() {
    Exception ex = null;/*from   w w  w.  j  a va2 s  .com*/
    HttpURLConnection conn = null;
    formValues.clear();

    Status s = Status.NEED_AUTH;
    s.authMethod = AuthMethod.USER_PASS;
    if (username == null || password == null) {
        return s;
    }

    Log.i(getName(), "userId: " + userId + ", authToken: " + authToken);
    if (userId != null && authToken != null) {
        return Status.OK;
    }

    cookies.clear();

    try {
        /**
         * connect to START_URL to get cookies/formValues
         */
        conn = (HttpURLConnection) new URL(START_URL).openConnection();
        conn.setInstanceFollowRedirects(false);
        addRequestHeaders(conn);
        {
            //                int responseCode = conn.getResponseCode();
            //                String amsg = conn.getResponseMessage();
            getCookies(conn);
            getFormValues(conn);
            authToken = formValues.get("authenticity_token");
        }
        conn.disconnect();

        if (authToken == null)
            return Status.ERROR;

        /**
         * Then login using a post
         */
        FormValues kv = new FormValues();
        kv.put("user[email]", username);
        kv.put("user[password]", password);
        kv.put("authenticity-token", authToken);
        kv.put("grant_type", "password");

        conn = (HttpURLConnection) new URL(LOGIN_URL).openConnection();
        conn.setInstanceFollowRedirects(false);
        conn.setDoOutput(true);
        conn.setRequestMethod(RequestMethod.POST.name());
        addRequestHeaders(conn);
        conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        String url2 = null;
        {
            OutputStream wr = new BufferedOutputStream(conn.getOutputStream());
            kv.write(wr);
            wr.flush();
            wr.close();
            // int responseCode = conn.getResponseCode();
            // String amsg = conn.getResponseMessage();
            getCookies(conn);
            InputStream in = new BufferedInputStream(conn.getInputStream());
            JSONObject ret = SyncHelper.parse(in);
            if (ret != null && ret.has("success") && ret.getBoolean("success")) {
                Matcher matcher = Patterns.WEB_URL.matcher(ret.getString("update"));
                while (matcher.find()) {
                    String tmp = matcher.group();
                    final String users = "/users/";
                    if (tmp.contains(users)) {
                        int i = tmp.indexOf(users) + users.length();
                        int i2 = tmp.indexOf('/', i);
                        if (i2 > 0)
                            url2 = tmp.substring(0, i2);
                        else
                            url2 = tmp;

                        if (url2 != null)
                            break;
                    }
                }
            }
            Log.i(getName(), "found url2: " + url2);
            conn.disconnect();
        }

        if (url2 == null) {
            return s;
        }

        {
            url2 = url2 + "?authenticity_token=" + SyncHelper.URLEncode(authToken);
            conn = (HttpURLConnection) new URL(url2).openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setRequestMethod(RequestMethod.GET.name());
            conn.setRequestProperty("Host", "www.runtastic.com");
            conn.addRequestProperty("Accept", "application/json");
            InputStream in = new BufferedInputStream(conn.getInputStream());
            getCookies(conn);
            JSONObject ret = SyncHelper.parse(in);
            userId = ret.getJSONObject("user").getInt("id");
            conn.disconnect();
        }

        if (userId != null && authToken != null) {
            return Status.OK;
        }
    } catch (MalformedURLException e) {
        ex = e;
    } catch (IOException e) {
        ex = e;
    } catch (JSONException e) {
        ex = e;
    }

    if (conn != null)
        conn.disconnect();

    s.ex = ex;
    if (ex != null) {
        ex.printStackTrace();
    }
    return s;
}

From source file:com.ewintory.alexandria.ui.activity.AddActivity.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if (!data.moveToFirst()) {
        mFoundBook = false;/* w  ww.  j  av  a 2  s.c om*/
        return;
    }

    mFoundBook = true;
    clearMessage();

    String bookTitle = data.getString(data.getColumnIndex(AlexandriaContract.BookEntry.TITLE));
    mBookTitleView.setText(bookTitle);

    String bookSubTitle = data.getString(data.getColumnIndex(AlexandriaContract.BookEntry.SUBTITLE));
    mBookSubtitleView.setText(bookSubTitle);

    String authors = data.getString(data.getColumnIndex(AlexandriaContract.AuthorEntry.AUTHOR));
    String[] authorsArr = (authors != null) ? authors.split(",") : new String[0];
    mBookAuthorsView.setLines(authorsArr.length);
    mBookAuthorsView.setText((authors != null) ? authors.replace(",", "\n") : "");

    String imgUrl = data.getString(data.getColumnIndex(AlexandriaContract.BookEntry.IMAGE_URL));
    if (Patterns.WEB_URL.matcher(imgUrl).matches()) {
        Glide.with(this).load(imgUrl).crossFade().into(mBookImageView);
    }

    String categories = data.getString(data.getColumnIndex(AlexandriaContract.CategoryEntry.CATEGORY));
    mBookCategoriesView.setText(categories);

    showBookCard(true);
}

From source file:fr.alecanu.samplerssreader.RssReaderActivity.java

private void changeURL() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    final EditText input = new EditText(this);
    builder.setTitle(getString(R.string.title_change_url)).setMessage(getString(R.string.message_change_url))
            .setView(input).setCancelable(false)
            .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    if (Patterns.WEB_URL.matcher(input.getText().toString()).matches()) {
                        if (URLUtil.isValidUrl(input.getText().toString())) {
                            url = input.getText().toString();
                        } else {
                            url = HTTP + input.getText().toString();
                        }//from  ww w.  j  a v  a2s  .c o  m
                        SharedPreferences.Editor edit = PreferenceManager
                                .getDefaultSharedPreferences(getApplicationContext()).edit();
                        edit.putBoolean(PREFERENCE_SETUP, true);
                        edit.putString(PREFERENCE_URL, url);
                        edit.commit();
                        refreshList();

                    } else {
                        new AlertDialog.Builder(RssReaderActivity.this).setCancelable(false)
                                .setMessage(getString(R.string.fail_url))
                                .setNeutralButton(getString(R.string.ok),
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface arg0, int arg1) {
                                                arg0.dismiss();
                                                changeURL();
                                            }
                                        })
                                .create().show();
                    }
                }
            }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    if (!PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
                            .getBoolean(PREFERENCE_SETUP, false)) {
                        finish();
                    } else {
                        dialog.dismiss();
                    }
                }
            });
    builder.create().show();
}

From source file:com.adobe.phonegap.contentsync.Sync.java

private boolean download(final String source, final File file, final JSONObject headers,
        final ProgressEvent progress, final CallbackContext callbackContext, final boolean trustEveryone) {
    Log.d(LOG_TAG, "download " + source);

    if (!Patterns.WEB_URL.matcher(source).matches()) {
        sendErrorMessage("Invalid URL", INVALID_URL_ERROR, callbackContext);
        return false;
    }//ww w  .ja  v  a2  s .c om

    final CordovaResourceApi resourceApi = webView.getResourceApi();
    final Uri sourceUri = resourceApi.remapUri(Uri.parse(source));

    int uriType = CordovaResourceApi.getUriType(sourceUri);
    final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;
    final boolean isLocalTransfer = !useHttps && uriType != CordovaResourceApi.URI_TYPE_HTTP;

    synchronized (progress) {
        if (progress.isAborted()) {
            return false;
        }
    }
    HttpURLConnection connection = null;
    HostnameVerifier oldHostnameVerifier = null;
    SSLSocketFactory oldSocketFactory = null;
    PluginResult result = null;
    TrackingInputStream inputStream = null;
    boolean cached = false;

    OutputStream outputStream = null;
    try {
        OpenForReadResult readResult = null;
        final Uri targetUri = resourceApi.remapUri(Uri.fromFile(file));

        progress.setTargetFile(file);
        progress.setStatus(STATUS_DOWNLOADING);

        Log.d(LOG_TAG, "Download file: " + sourceUri);
        Log.d(LOG_TAG, "Target file: " + file);
        Log.d(LOG_TAG, "size = " + file.length());

        if (isLocalTransfer) {
            readResult = resourceApi.openForRead(sourceUri);
            if (readResult.length != -1) {
                progress.setTotal(readResult.length);
            }
            inputStream = new SimpleTrackingInputStream(readResult.inputStream);
        } else {
            // connect to server
            // Open a HTTP connection to the URL based on protocol
            connection = resourceApi.createHttpConnection(sourceUri);
            if (useHttps && trustEveryone) {
                // Setup the HTTPS connection class to trust everyone
                HttpsURLConnection https = (HttpsURLConnection) connection;
                oldSocketFactory = trustAllHosts(https);
                // Save the current hostnameVerifier
                oldHostnameVerifier = https.getHostnameVerifier();
                // Setup the connection not to verify hostnames
                https.setHostnameVerifier(DO_NOT_VERIFY);
            }

            connection.setRequestMethod("GET");

            // TODO: Make OkHttp use this CookieManager by default.
            String cookie = getCookies(sourceUri.toString());

            if (cookie != null) {
                connection.setRequestProperty("cookie", cookie);
            }

            // This must be explicitly set for gzip progress tracking to work.
            connection.setRequestProperty("Accept-Encoding", "gzip");

            // Handle the other headers
            if (headers != null) {
                addHeadersToRequest(connection, headers);
            }

            connection.connect();
            if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
                cached = true;
                connection.disconnect();
                sendErrorMessage("Resource not modified: " + source, CONNECTION_ERROR, callbackContext);
                return false;
            } else {
                if (connection.getContentEncoding() == null
                        || connection.getContentEncoding().equalsIgnoreCase("gzip")) {
                    // Only trust content-length header if we understand
                    // the encoding -- identity or gzip
                    int connectionLength = connection.getContentLength();
                    if (connectionLength != -1) {
                        if (connectionLength > getFreeSpace()) {
                            cached = true;
                            connection.disconnect();
                            sendErrorMessage("Not enough free space to download", CONNECTION_ERROR,
                                    callbackContext);
                            return false;
                        } else {
                            progress.setTotal(connectionLength);
                        }
                    }
                }
                inputStream = getInputStream(connection);
            }
        }

        if (!cached) {
            try {
                synchronized (progress) {
                    if (progress.isAborted()) {
                        return false;
                    }
                    //progress.connection = connection;
                }

                // write bytes to file
                byte[] buffer = new byte[MAX_BUFFER_SIZE];
                int bytesRead = 0;
                outputStream = resourceApi.openOutputStream(targetUri);
                while ((bytesRead = inputStream.read(buffer)) > 0) {
                    synchronized (progress) {
                        if (progress.isAborted()) {
                            return false;
                        }
                    }
                    Log.d(LOG_TAG, "bytes read = " + bytesRead);
                    outputStream.write(buffer, 0, bytesRead);
                    // Send a progress event.
                    progress.setLoaded(inputStream.getTotalRawBytesRead());

                    updateProgress(callbackContext, progress);
                }
            } finally {
                synchronized (progress) {
                    //progress.connection = null;
                }
                safeClose(inputStream);
                safeClose(outputStream);
            }
        }

    } catch (Throwable e) {
        sendErrorMessage(e.getLocalizedMessage(), CONNECTION_ERROR, callbackContext);
    } finally {
        if (connection != null) {
            // Revert back to the proper verifier and socket factories
            if (trustEveryone && useHttps) {
                HttpsURLConnection https = (HttpsURLConnection) connection;
                https.setHostnameVerifier(oldHostnameVerifier);
                https.setSSLSocketFactory(oldSocketFactory);
            }
        }
    }

    return true;
}

From source file:com.nbplus.vbroadlauncher.BroadcastWebViewActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Constants.OPEN_BETA_PHONE && LauncherSettings.getInstance(this).isSmartPhone()) {
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }/*from  w w w .ja v a2s  .co  m*/
    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    setContentView(R.layout.activity_broadcast_webview);

    Log.d(TAG, "BroadcastWebViewActivity onCreate()");
    WebView webView = (WebView) findViewById(R.id.webview);
    mWebViewClient = new BroadcastWebViewClient(this, webView);

    IntentFilter filter = new IntentFilter();
    filter.addAction(Constants.ACTION_BROWSER_ACTIVITY_CLOSE);
    filter.addAction(Constants.ACTION_IOT_DEVICE_LIST);
    LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, filter);

    Intent i = getIntent();
    String url = null;
    if (i != null && Constants.ACTION_SHOW_NOTIFICATION_CONTENTS.equals(getIntent().getAction())) {
        url = getIntent().getStringExtra(Constants.EXTRA_SHOW_NOTIFICATION_CONTENTS);
    } else {
        mShortcutData = i.getParcelableExtra(Constants.EXTRA_NAME_SHORTCUT_DATA);
        url = mShortcutData.getDomain() + mShortcutData.getPath();
    }

    //url="http://183.98.53.165:8010/web_test/audio_autoplay.html";
    if (StringUtils.isEmptyString(url) || !Patterns.WEB_URL.matcher(url).matches()) {
        Log.e(TAG, "Wrong url ....");
        new AlertDialog.Builder(this).setMessage(R.string.alert_wrong_page_url)
                //.setTitle(R.string.alert_network_title)
                .setCancelable(true)
                .setPositiveButton(R.string.alert_ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        finishActivity();
                    }
                }).show();
        return;
    } else {
        mWebViewClient.loadWebUrl(url);
    }
    Log.d(TAG, "start URL = " + url);
    setContentViewByOrientation();
}