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:uk.ac.ucl.excites.sapelli.collector.activities.ProjectManagerActivity.java

@Override
public void projectLoadStoreSuccess(File sapelliFile, String sourceURI, Project project,
        List<String> warnings) {
    // Deal with downloaded file...
    if (Patterns.WEB_URL.matcher(sourceURI).matches())
        // Change temporary name to proper one:
        sapelliFile.renameTo(new File(sapelliFile.getParentFile().getAbsolutePath() + File.separator
                + FileHelpers.makeValidFileName(project.toString(false) + ".sapelli")));

    // Warnings...
    TransactionalStringBuilder bldr = new TransactionalStringBuilder("\n");
    //   Parser/loader warnings: 
    if (!warnings.isEmpty())
        bldr.append(listWarnings(R.string.projectLoadingWarnings, warnings));
    //   Check file dependencies:
    List<String> missingFiles = project.getMissingFilesRelativePaths(getFileStorageProvider());
    if (!missingFiles.isEmpty()) {
        bldr.append(getString(R.string.missingFiles) + ":");
        for (String missingFile : missingFiles)
            bldr.append(" - " + missingFile);
    }//from w w w  .  ja  va  2 s.  c  om
    //   Show warnings dialog:
    if (!bldr.isEmpty())
        showWarningDialog(bldr.toString()); // no need to worry about message not fitting the dialog, it will have a scrollbar when necessary 

    // Select project:
    setCurrentProject(project);

    // Update project list:
    updateProjectList(true);
}

From source file:uk.ac.ucl.excites.sapelli.collector.activities.ProjectManagerActivity.java

@Override
public void projectLoadStoreFailure(File sapelliFile, String sourceURI, Exception cause) {
    // Deal with downloaded file...
    if (Patterns.WEB_URL.matcher(sourceURI).matches())
        org.apache.commons.io.FileUtils.deleteQuietly(sapelliFile);
    // Report problem:
    Log.e(TAG, "Could not load/store Sapelli file", cause);
    showErrorDialog(getString(R.string.sapelliFileLoadFailure,
            (Patterns.WEB_URL.matcher(sourceURI).matches() ? sapelliFile.getAbsolutePath() : sourceURI),
            ExceptionHelpers.getMessageAndCause(cause)), false);
}

From source file:com.klinker.android.twitter.activities.tweet_viewer.TweetPager.java

public String restoreLinks(String text) {
    String full = text;/*from w  w  w.  j  a v a  2s.c  o  m*/

    String[] split = text.split("\\s");
    String[] otherLink = new String[otherLinks.length];

    for (int i = 0; i < otherLinks.length; i++) {
        otherLink[i] = "" + otherLinks[i];
    }

    for (String s : otherLink) {
        Log.v("talon_links", ":" + s + ":");
    }

    boolean changed = false;
    int otherIndex = 0;

    if (otherLink.length > 0) {
        for (int i = 0; i < split.length; i++) {
            String s = split[i];

            //if (Patterns.WEB_URL.matcher(s).find()) { // we know the link is cut off
            if (Patterns.WEB_URL.matcher(s).find()) { // we know the link is cut off
                String f = s.replace("...", "").replace("http", "");

                f = stripTrailingPeriods(f);

                try {
                    if (otherIndex < otherLinks.length) {
                        if (otherLink[otherIndex]
                                .substring(otherLink[otherIndex].length() - 1, otherLink[otherIndex].length())
                                .equals("/")) {
                            otherLink[otherIndex] = otherLink[otherIndex].substring(0,
                                    otherLink[otherIndex].length() - 1);
                        }
                        f = otherLink[otherIndex].replace("http://", "").replace("https://", "").replace("www.",
                                "");
                        otherLink[otherIndex] = "";
                        otherIndex++;

                        changed = true;
                    }
                } catch (Exception e) {

                }

                if (changed) {
                    split[i] = f;
                } else {
                    split[i] = s;
                }
            } else {
                split[i] = s;
            }

        }
    }

    if (!webpage.equals("")) {
        for (int i = split.length - 1; i >= 0; i--) {
            String s = split[i];
            if (Patterns.WEB_URL.matcher(s).find()) {
                String replace = otherLinks[otherLinks.length - 1];
                if (replace.replace(" ", "").equals("")) {
                    replace = webpage;
                }
                split[i] = replace;
                changed = true;
                break;
            }
        }
    }

    if (changed) {
        full = "";
        for (String p : split) {
            full += p + " ";
        }

        full = full.substring(0, full.length() - 1);
    }

    return full;
}

From source file:com.klinker.android.twitter.ui.tweet_viewer.TweetPager.java

public String restoreLinks(String text) {
    String full = text;//from ww w.  ja  v a 2 s .c  o m

    String[] split = text.split("\\s");
    String[] otherLink = new String[otherLinks.length];

    for (int i = 0; i < otherLinks.length; i++) {
        otherLink[i] = "" + otherLinks[i];
    }

    for (String s : otherLink) {
        Log.v("talon_links", ":" + s + ":");
    }

    boolean changed = false;

    if (otherLink.length > 0) {
        for (int i = 0; i < split.length; i++) {
            String s = split[i];

            //if (Patterns.WEB_URL.matcher(s).find()) { // we know the link is cut off
            if (s.contains("...")) { // we know the link is cut off
                String f = s.replace("...", "").replace("http", "");

                f = stripTrailingPeriods(f);

                for (int x = 0; x < otherLink.length; x++) {
                    if (otherLink[x].toLowerCase().contains(f.toLowerCase())) {
                        changed = true;
                        // for some reason it wouldn't match the last "/" on a url and it was stopping it from opening
                        try {
                            if (otherLink[x].substring(otherLink[x].length() - 1, otherLink[x].length())
                                    .equals("/")) {
                                otherLink[x] = otherLink[x].substring(0, otherLink[x].length() - 1);
                            }
                            f = otherLink[x].replace("http://", "").replace("https://", "").replace("www.", "");
                            otherLink[x] = "";
                        } catch (Exception e) {
                            // out of bounds exception?
                        }
                        break;
                    }
                }

                if (changed) {
                    split[i] = f;
                } else {
                    split[i] = s;
                }
            } else {
                split[i] = s;
            }

        }
    }

    if (!webpage.equals("")) {
        for (int i = 0; i < split.length; i++) {
            String s = split[i];
            if (s.contains("...")) {
                s = s.replace("...", "");

                if (Patterns.WEB_URL.matcher(s).find()
                        && (s.startsWith("t.co/") || s.contains("twitter.com/"))) { // we know the link is cut off
                    String replace = otherLinks[otherLinks.length - 1];
                    if (replace.replace(" ", "").equals("")) {
                        replace = webpage;
                    }
                    split[i] = replace;
                    changed = true;
                }
            }
        }
    }

    if (changed) {
        full = "";
        for (String p : split) {
            full += p + " ";
        }

        full = full.substring(0, full.length() - 1);
    }

    return full;
}

From source file:com.stoutner.privacybrowser.MainWebViewActivity.java

private void loadUrlFromTextBox() throws UnsupportedEncodingException {
    // Get the text from urlTextBox and convert it to a string.
    String unformattedUrlString = urlTextBox.getText().toString();
    URL unformattedUrl = null;//from   w w w  .  ja  va2 s  .  c o  m
    Uri.Builder formattedUri = new Uri.Builder();

    // Check to see if unformattedUrlString is a valid URL.  Otherwise, convert it into a Duck Duck Go search.
    if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
        // Add http:// at the beginning if it is missing.  Otherwise the app will segfault.
        if (!unformattedUrlString.startsWith("http")) {
            unformattedUrlString = "http://" + unformattedUrlString;
        }

        // Convert unformattedUrlString to a URL, then to a URI, and then back to a string, which sanitizes the input and adds in any missing components.
        try {
            unformattedUrl = new URL(unformattedUrlString);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
        final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
        final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
        final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
        final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
        final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;

        formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
        formattedUrlString = formattedUri.build().toString();
    } else {
        // Sanitize the search input and convert it to a DuckDuckGo search.
        final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");

        // Use the correct search URL based on javaScriptEnabled.
        if (javaScriptEnabled) {
            formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
        } else { // JavaScript is disabled.
            formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
        }
    }

    mainWebView.loadUrl(formattedUrlString);

    // Hides the keyboard so we can see the webpage.
    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(
            Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
}

From source file:com.android.email.activity.MessageView.java

/**
 * Reload the body from the provider cursor.  This must only be called from the UI thread.
 *
 * @param bodyText text part//  www  .  j  av a 2 s  . c  o  m
 * @param bodyHtml html part
 *
 * TODO deal with html vs text and many other issues
 */
private void reloadUiFromBody(String bodyText, String bodyHtml) {
    String text = null;
    mHtmlTextRaw = null;
    boolean hasImages = false;

    if (bodyHtml == null) {
        text = bodyText;
        /*
         * Convert the plain text to HTML
         */
        StringBuffer sb = new StringBuffer("<html><body>");
        if (text != null) {
            // Escape any inadvertent HTML in the text message
            text = EmailHtmlUtil.escapeCharacterToDisplay(text);
            // Find any embedded URL's and linkify
            Matcher m = Patterns.WEB_URL.matcher(text);
            while (m.find()) {
                int start = m.start();
                /*
                 * WEB_URL_PATTERN may match domain part of email address. To detect
                 * this false match, the character just before the matched string
                 * should not be '@'.
                 */
                if (start == 0 || text.charAt(start - 1) != '@') {
                    String url = m.group();
                    Matcher proto = WEB_URL_PROTOCOL.matcher(url);
                    String link;
                    if (proto.find()) {
                        // This is work around to force URL protocol part be lower case,
                        // because WebView could follow only lower case protocol link.
                        link = proto.group().toLowerCase() + url.substring(proto.end());
                    } else {
                        // Patterns.WEB_URL matches URL without protocol part,
                        // so added default protocol to link.
                        link = "http://" + url;
                    }
                    String href = String.format("<a href=\"%s\">%s</a>", link, url);
                    m.appendReplacement(sb, href);
                } else {
                    m.appendReplacement(sb, "$0");
                }
            }
            m.appendTail(sb);
        }
        sb.append("</body></html>");
        text = sb.toString();
    } else {
        text = bodyHtml;
        mHtmlTextRaw = bodyHtml;
        hasImages = IMG_TAG_START_REGEX.matcher(text).find();
    }

    mShowPicturesSection.setVisibility(hasImages ? View.VISIBLE : View.GONE);
    if (mMessageContentView != null) {
        mMessageContentView.loadDataWithBaseURL("email://", text, "text/html", "utf-8", null);
    }

    // Ask for attachments after body
    mLoadAttachmentsTask = new LoadAttachmentsTask();
    mLoadAttachmentsTask.execute(mMessage.mId);
}

From source file:cn.suishen.email.activity.MessageViewFragmentBase.java

/**
 * Reload the body from the provider cursor.  This must only be called from the UI thread.
 *
 * @param bodyText text part//  ww w  .java 2  s  .co m
 * @param bodyHtml html part
 *
 * TODO deal with html vs text and many other issues <- WHAT DOES IT MEAN??
 */
private void reloadUiFromBody(String bodyText, String bodyHtml, boolean autoShowPictures) {
    String text = null;
    mHtmlTextRaw = null;
    boolean hasImages = false;

    if (bodyHtml == null) {
        text = bodyText;
        /*
         * Convert the plain text to HTML
         */
        StringBuffer sb = new StringBuffer("<html><body>");
        if (text != null) {
            // Escape any inadvertent HTML in the text message
            text = EmailHtmlUtil.escapeCharacterToDisplay(text);
            // Find any embedded URL's and linkify
            Matcher m = Patterns.WEB_URL.matcher(text);
            while (m.find()) {
                int start = m.start();
                /*
                 * WEB_URL_PATTERN may match domain part of email address. To detect
                 * this false match, the character just before the matched string
                 * should not be '@'.
                 */
                if (start == 0 || text.charAt(start - 1) != '@') {
                    String url = m.group();
                    Matcher proto = WEB_URL_PROTOCOL.matcher(url);
                    String link;
                    if (proto.find()) {
                        // This is work around to force URL protocol part be lower case,
                        // because WebView could follow only lower case protocol link.
                        link = proto.group().toLowerCase() + url.substring(proto.end());
                    } else {
                        // Patterns.WEB_URL matches URL without protocol part,
                        // so added default protocol to link.
                        link = "http://" + url;
                    }
                    String href = String.format("<a href=\"%s\">%s</a>", link, url);
                    m.appendReplacement(sb, href);
                } else {
                    m.appendReplacement(sb, "$0");
                }
            }
            m.appendTail(sb);
        }
        sb.append("</body></html>");
        text = sb.toString();
    } else {
        text = bodyHtml;
        mHtmlTextRaw = bodyHtml;
        hasImages = IMG_TAG_START_REGEX.matcher(text).find();
    }

    // TODO this is not really accurate.
    // - Images aren't the only network resources.  (e.g. CSS)
    // - If images are attached to the email and small enough, we download them at once,
    //   and won't need network access when they're shown.
    if (hasImages) {
        if (mRestoredPictureLoaded || autoShowPictures) {
            blockNetworkLoads(false);
            addTabFlags(TAB_FLAGS_PICTURE_LOADED); // Set for next onSaveInstanceState

            // Make sure to reset the flag -- otherwise this will keep taking effect even after
            // moving to another message.
            mRestoredPictureLoaded = false;
        } else {
            addTabFlags(TAB_FLAGS_HAS_PICTURES);
        }
    }
    setMessageHtml(text);

    // Ask for attachments after body
    new LoadAttachmentsTask().executeParallel(mMessage.mId);

    mIsMessageLoadedForTest = true;
}