Example usage for android.net Uri getScheme

List of usage examples for android.net Uri getScheme

Introduction

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

Prototype

@Nullable
public abstract String getScheme();

Source Link

Document

Gets the scheme of this URI.

Usage

From source file:org.apache.cordova.CordovaWebViewImpl.java

@Override
public void showWebPage(String url, boolean openExternal, boolean clearHistory, Map<String, Object> params) {
    LOG.d(TAG, "showWebPage(%s, %b, %b, HashMap)", url, openExternal, clearHistory);

    // If clearing history
    if (clearHistory) {
        engine.clearHistory();//from  w  w  w . j a  va2s. c  o  m
    }

    // If loading into our webview
    if (!openExternal) {
        // Make sure url is in whitelist
        if (pluginManager.shouldAllowNavigation(url)) {
            // TODO: What about params?
            // Load new URL
            loadUrlIntoView(url, true);
        } else {
            LOG.w(TAG,
                    "showWebPage: Refusing to load URL into webview since it is not in the <allow-navigation> whitelist. URL="
                            + url);
        }
    }
    if (!pluginManager.shouldOpenExternalUrl(url)) {
        LOG.w(TAG,
                "showWebPage: Refusing to send intent for URL since it is not in the <allow-intent> whitelist. URL="
                        + url);
        return;
    }
    try {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // To send an intent without CATEGORY_BROWSER, a custom plugin should be used.
        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        Uri uri = Uri.parse(url);
        // Omitting the MIME type for file: URLs causes "No Activity found to handle Intent".
        // Adding the MIME type to http: URLs causes them to not be handled by the downloader.
        if ("file".equals(uri.getScheme())) {
            intent.setDataAndType(uri, resourceApi.getMimeType(uri));
        } else {
            intent.setData(uri);
        }
        cordova.getActivity().startActivity(intent);
    } catch (android.content.ActivityNotFoundException e) {
        LOG.e(TAG, "Error loading url " + url, e);
    }
}

From source file:com.android.providers.downloads.DownloadInfo.java

/**
 * Returns whether this download should be enqueued.
 *///from   w w w. j  a v  a2s.  co m
private boolean isReadyToDownload() {
    if (mControl == Downloads.Impl.CONTROL_PAUSED) {
        // the download is paused, so it's not going to start
        Log.i(Constants.DL_ENHANCE, "Download is paused " + "then no need to start");
        return false;
    }
    switch (mStatus) {
    case 0: // status hasn't been initialized yet, this is a new download
    case Downloads.Impl.STATUS_PENDING: // download is explicit marked as ready to start
    case Downloads.Impl.STATUS_RUNNING: // download interrupted (process killed etc) while
                                        // running, without a chance to update the database
        return true;

    case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
    case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
        return checkCanUseNetwork(mTotalBytes) == NetworkState.OK;

    case Downloads.Impl.STATUS_WAITING_TO_RETRY:
        // download was waiting for a delayed restart
        final long now = mSystemFacade.currentTimeMillis();
        return restartTime(now) <= now;
    case Downloads.Impl.STATUS_DEVICE_NOT_FOUND_ERROR:
        // is the media mounted?
        final Uri uri = Uri.parse(mUri);
        if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
            final File file = new File(uri.getPath());
            return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState(file));
        } else {
            Log.w(TAG, "Expected file URI on external storage: " + mUri);
            return false;
        }
        /// M: Because OMA DL spec, if insufficient memory, we
        /// will show to user but not retry.
        //case Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR:
        // should check space to make sure it is worth retrying the download.
        // but thats the first thing done by the thread when it retries to download
        // it will fail pretty quickly if there is no space.
        // so, it is not that bad to skip checking space availability here.
        //return true;
        /// M: Add for fix alp00406729, file already exist but user do not operation. @{
    case Downloads.Impl.STATUS_FILE_ALREADY_EXISTS_ERROR:
        return false;
    /// @}
    }
    return false;
}

From source file:uk.bowdlerize.service.CensorCensusService.java

private CensorPayload checkURL(String checkURL) throws IllegalArgumentException, URISyntaxException {
    if (!checkURL.startsWith("http"))
        checkURL = "http://" + checkURL;

    CensorPayload censorPayload = new CensorPayload(checkURL);

    Uri mUri = Uri.parse(checkURL);

    if (null == mUri.getEncodedQuery()) {
        checkURL = mUri.getScheme() + "://" + mUri.getHost() + mUri.getPath();
    } else {//from  w  w  w .  jav  a 2  s . c o  m
        checkURL = mUri.getScheme() + "://" + mUri.getHost() + mUri.getPath() + "?"
                + URLEncoder.encode(mUri.getEncodedQuery());
    }

    Log.e("Checking url", checkURL);

    client = new DefaultHttpClient();

    /*headRequest = new HttpHead(checkURL);
    headRequest.setHeader("User-Agent", "OONI Android Probe");*/

    httpGet = new HttpGet(checkURL);
    httpGet.setHeader("User-Agent", "OONI Android Probe");

    try {
        //response = client.execute(headRequest);
        client.addResponseInterceptor(new HttpResponseInterceptor() {
            @Override
            public void process(HttpResponse httpResponse, HttpContext httpContext)
                    throws HttpException, IOException {
                if (httpResponse.getStatusLine().getStatusCode() == 302
                        || httpResponse.getStatusLine().getStatusCode() == 301) {
                    for (Header hdr : httpResponse.getAllHeaders()) {
                        if (hdr.getName().equals("Location")) {
                            /*if (hdr.getValue().equals("http://ee-outage.s3.amazonaws.com/content-blocked/content-blocked-v1.html") ||
                            hdr.getValue().contains("http://ee-outage.s3.amazonaws.com"))
                            {
                            Log.e("Blocked", "Blocked by EE");
                            throw new CensoredException("Blocked by EE", "EE", 100);
                            }
                            else if (hdr.getValue().contains("http://www.t-mobile.co.uk/service/wnw-mig/entry/") ||
                                 hdr.getValue().contains("http://tmobile.ee.co.uk/common/system_error_pages/outage_wnw.html"))
                            {
                            Log.e("Blocked", "Blocked by TMobile");
                            throw new CensoredException("Blocked by TMobile", "TMobile", 100);
                            }
                            else if (hdr.getValue().contains("http://online.vodafone.co.uk/dispatch/Portal/ContentControlServlet?type=restricted"))
                            {
                            Log.e("Blocked", "Blocked by Vodafone");
                            throw new CensoredException("Blocked by Vodafone", "Vodafone", 100);
                            }
                            else if (hdr.getValue().contains("http://blockpage.bt.com/pcstaticpage/blocked.html"))
                            {
                            Log.e("Blocked", "Blocked by BT");
                            throw new CensoredException("Blocked by BT", "BT", 100);
                            }
                            else if (hdr.getValue().contains("http://www.talktalk.co.uk/notice/parental-controls?accessurl"))
                            {
                            Log.e("Blocked", "Blocked by TalkTalk");
                            throw new CensoredException("Blocked by TalkTalk", "TalkTalk", 100);
                            }
                            else if (hdr.getValue().contains("http://www.plus.net/support/security/abuse/blocked.shtml"))
                            {
                            Log.e("Blocked", "Blocked by PlusNet");
                            throw new CensoredException("Blocked by PlusNet", "PlusNet", 100);
                            }
                            else if (hdr.getValue().contains("http://mobile.three.co.uk/pc/Live/pcreator/live/100004/pin/blocked?"))
                            {
                            Log.e("Blocked", "Blocked by Three");
                            throw new CensoredException("Blocked by Three", "Three", 100);
                            }
                            else if (hdr.getValue().contains("http://m.virginmedia.com/MiscPages/AdultWarning.aspx"))
                            {
                            Log.e("Blocked", "Blocked by VirginMobile");
                            throw new CensoredException("Blocked by VirginMobile", "VirginMobile", 100);
                            }
                            else if (hdr.getValue().contains("http://assets.o2.co.uk/18plusaccess/"))
                            {
                            Log.e("Blocked", "Blocked by O2");
                            throw new CensoredException("Blocked by O2", "O2", 100);
                            }*/
                            api.checkHeader(hdr);
                        }
                    }
                }

                /*Log.e("intercepted return code",httpResponse.getStatusLine().toString());
                        
                for(Header hdr : httpResponse.getAllHeaders())
                {
                Log.e("intercepted header",hdr.getName().toString() + " / " + hdr.getValue().toString());
                }
                Log.e("intercepted header","------------------\r\n------------------\r\n------------------\r\n------------------\r\n------------------\r\n");*/

            }
        });
        response = client.execute(httpGet);
    }
    //This is the best case scenario!
    catch (CensoredException CE) {
        censorPayload.consumeCensoredException(CE);
        return censorPayload;
    } catch (UnknownHostException uhe) {
        uhe.printStackTrace();
        censorPayload.consumeError(uhe.getMessage());
        return censorPayload;
    } catch (ConnectTimeoutException CTE) {
        CTE.printStackTrace();
        censorPayload.consumeError(CTE.getMessage());
        return censorPayload;
    } catch (NoHttpResponseException NHRE) {
        NHRE.printStackTrace();
        censorPayload.consumeError(NHRE.getMessage());
        return censorPayload;
    } catch (IOException ioe) {
        ioe.printStackTrace();
        censorPayload.consumeError(ioe.getMessage());
        return censorPayload;
    } catch (IllegalStateException ise) {
        ise.printStackTrace();
        censorPayload.setCensored(false);
        censorPayload.setConfidence(0);
        return censorPayload;
    } catch (Exception e) {
        e.printStackTrace();
        censorPayload.setCensored(false);
        censorPayload.setConfidence(0);
        return censorPayload;
    }

    int statusCode = response.getStatusLine().getStatusCode();

    censorPayload.setReturnCode(statusCode);

    Log.e("checkURL code", Integer.toString(statusCode));
    if (statusCode == 403 || statusCode == 404) {
        censorPayload.setCensored(true);
        censorPayload.setConfidence(25);
        return censorPayload;
    } else if (statusCode == 504 || statusCode == 503 || statusCode == 500) {
        censorPayload.consumeError("Server Issue " + Integer.toString(statusCode));
        return censorPayload;
    }

    String phrase = response.getStatusLine().getReasonPhrase();

    Log.e("checkURL phrase", phrase);

    if (phrase.contains("orbidden")) {
        censorPayload.setCensored(true);
        censorPayload.setConfidence(50);
        return censorPayload;
    }

    if (phrase.contains("blocked")) {
        censorPayload.setCensored(true);
        censorPayload.setConfidence(100);
        return censorPayload;
    }

    for (Header hdr : response.getAllHeaders()) {
        Log.e("checkURL header", hdr.getName() + " / " + hdr.getValue());
    }

    censorPayload.setCensored(false);
    censorPayload.setConfidence(1);
    return censorPayload;
}

From source file:net.wequick.small.webkit.WebView.java

private void initSettings() {
    WebSettings webSettings = this.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setUserAgentString(webSettings.getUserAgentString() + " Native");
    this.addJavascriptInterface(new SmallJsBridge(), "_Small");

    this.setWebChromeClient(new WebChromeClient() {
        @Override/*  www  . j a  v a2  s.  c o m*/
        public void onReceivedTitle(android.webkit.WebView view, String title) {
            // Call if html title is set
            super.onReceivedTitle(view, title);
            mTitle = title;
            WebActivity activity = (WebActivity) WebViewPool.getContext(view);
            if (activity != null) {
                activity.setTitle(title);
            }
            // May receive head meta at the same time
            initMetas();
        }

        @Override
        public boolean onJsAlert(android.webkit.WebView view, String url, String message,
                final android.webkit.JsResult result) {
            Context context = WebViewPool.getContext(view);
            if (context == null)
                return false;

            AlertDialog.Builder dlg = new AlertDialog.Builder(context);
            dlg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mConfirmed = true;
                    result.confirm();
                }
            });
            dlg.setMessage(message);
            AlertDialog alert = dlg.create();
            alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (!mConfirmed) {
                        result.cancel();
                    }
                }
            });
            mConfirmed = false;
            alert.show();
            return true;
        }

        @Override
        public boolean onJsConfirm(android.webkit.WebView view, String url, String message,
                final android.webkit.JsResult result) {
            Context context = WebViewPool.getContext(view);
            AlertDialog.Builder dlg = new AlertDialog.Builder(context);
            dlg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mConfirmed = true;
                    result.confirm();
                }
            });
            dlg.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mConfirmed = true;
                    result.cancel();
                }
            });
            dlg.setMessage(message);
            AlertDialog alert = dlg.create();
            alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (!mConfirmed) {
                        result.cancel();
                    }
                }
            });
            mConfirmed = false;
            alert.show();
            return true;
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            String msg = consoleMessage.message();
            if (msg == null)
                return false;
            Uri uri = Uri.parse(msg);
            if (uri != null && null != uri.getScheme() && uri.getScheme().equals(SMALL_SCHEME)) {
                String host = uri.getHost();
                String ret = uri.getQueryParameter(SMALL_QUERY_KEY_RET);
                if (host.equals(SMALL_HOST_POP)) {
                    WebActivity activity = (WebActivity) WebViewPool.getContext(WebView.this);
                    activity.finish(ret);
                } else if (host.equals(SMALL_HOST_EXEC)) {
                    if (mOnResultListener != null) {
                        mOnResultListener.onResult(ret);
                    }
                }
                return true;
            }
            Log.d(consoleMessage.sourceId(),
                    "line" + consoleMessage.lineNumber() + ": " + consoleMessage.message());
            return true;
        }

        @Override
        public void onCloseWindow(android.webkit.WebView window) {
            super.onCloseWindow(window);
            close(new OnResultListener() {
                @Override
                public void onResult(String ret) {
                    if (ret.equals("false"))
                        return;

                    WebActivity activity = (WebActivity) WebViewPool.getContext(WebView.this);
                    activity.finish(ret);
                }
            });
        }
    });

    this.setWebViewClient(new android.webkit.WebViewClient() {

        private final String ANCHOR_SCHEME = "anchor";

        @Override
        public boolean shouldOverrideUrlLoading(android.webkit.WebView view, String url) {
            if (mLoadingUrl != null && mLoadingUrl.equals(url)) {
                // reload by window.location.reload or something
                return super.shouldOverrideUrlLoading(view, url);
            }

            Boolean hasStarted = mHasStartedUrl.get(url);
            if (hasStarted != null && hasStarted) {
                // location redirected before page finished
                return super.shouldOverrideUrlLoading(view, url);
            }

            HitTestResult hit = view.getHitTestResult();
            if (hit != null) {
                Uri uri = Uri.parse(url);
                if (uri.getScheme().equals(ANCHOR_SCHEME)) {
                    // Scroll to anchor
                    int anchorY = Integer.parseInt(uri.getHost());
                    view.scrollTo(0, anchorY);
                } else {
                    Small.openUri(uri, WebViewPool.getContext(view));
                }
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageStarted(android.webkit.WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mHasStartedUrl.put(url, true);

            if (mLoadingUrl != null && mLoadingUrl.equals(url)) {
                // reload by window.location.reload or something
                mInjected = false;
            }
            if (sWebViewClient != null && url.equals(mLoadingUrl)) {
                sWebViewClient.onPageStarted(WebViewPool.getContext(view), (WebView) view, url, favicon);
            }
        }

        @Override
        public void onPageFinished(android.webkit.WebView view, String url) {
            super.onPageFinished(view, url);
            mHasStartedUrl.remove(url);

            HitTestResult hit = view.getHitTestResult();
            if (hit != null && hit.getType() == HitTestResult.SRC_ANCHOR_TYPE) {
                // Triggered by user clicked
                Uri uri = Uri.parse(url);
                String anchor = uri.getFragment();
                if (anchor != null) {
                    // If is an anchor, calculate the content offset by DOM
                    // and call native to adjust WebView's offset
                    view.loadUrl(JS_PREFIX + "var y=document.body.scrollTop;"
                            + "var e=document.getElementsByName('" + anchor + "')[0];" + "while(e){"
                            + "y+=e.offsetTop-e.scrollTop+e.clientTop;e=e.offsetParent;}" + "location='"
                            + ANCHOR_SCHEME + "://'+y;");
                }
            }

            if (!mInjected) {
                // Re-inject Small Js
                loadJs(SMALL_INJECT_JS);
                initMetas();
                mInjected = true;
            }

            if (sWebViewClient != null && url.equals(mLoadingUrl)) {
                sWebViewClient.onPageFinished(WebViewPool.getContext(view), (WebView) view, url);
            }
        }

        @Override
        public void onReceivedError(android.webkit.WebView view, int errorCode, String description,
                String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            Log.e("Web", "error: " + description);
            if (sWebViewClient != null && failingUrl.equals(mLoadingUrl)) {
                sWebViewClient.onReceivedError(WebViewPool.getContext(view), (WebView) view, errorCode,
                        description, failingUrl);
            }
        }
    });
}

From source file:io.ionic.links.IonicDeeplink.java

public void handleIntent(Intent intent) {
    final String intentString = intent.getDataString();

    // read intent
    String action = intent.getAction();
    Uri url = intent.getData();
    JSONObject bundleData = this._bundleToJson(intent.getExtras());
    Log.d(TAG, "Got a new intent: " + intentString + " " + intent.getScheme() + " " + action + " " + url);

    // if app was not launched by the url - ignore
    if (!Intent.ACTION_VIEW.equals(action) || url == null) {
        return;/*w  w  w  .  j a  v  a2s . c o m*/
    }

    // store message and try to consume it
    try {
        lastEvent = new JSONObject();
        lastEvent.put("url", url.toString());
        lastEvent.put("path", url.getPath());
        lastEvent.put("queryString", url.getQuery());
        lastEvent.put("scheme", url.getScheme());
        lastEvent.put("host", url.getHost());
        lastEvent.put("fragment", url.getFragment());
        lastEvent.put("extra", bundleData);
        consumeEvents();
    } catch (JSONException ex) {
        Log.e(TAG, "Unable to process URL scheme deeplink", ex);
    }
}

From source file:com.xabber.android.ui.activity.ContactListActivity.java

@Override
protected void onResume() {
    super.onResume();

    if (!AccountManager.getInstance().hasAccounts()) {
        startActivity(IntroActivity.createIntent(this));
        finish();//from  ww  w.  j  av  a 2s  .  com
        return;
    }

    barPainter.setDefaultColor();
    rebuildAccountToggle();
    Application.getInstance().addUIListener(OnAccountChangedListener.class, this);

    if (action != null) {
        switch (action) {
        case ContactListActivity.ACTION_ROOM_INVITE:
        case Intent.ACTION_SEND:
        case Intent.ACTION_CREATE_SHORTCUT:
            if (Intent.ACTION_SEND.equals(action)) {
                sendText = getIntent().getStringExtra(Intent.EXTRA_TEXT);
            }
            Toast.makeText(this, getString(R.string.select_contact), Toast.LENGTH_LONG).show();
            break;
        case Intent.ACTION_VIEW: {
            action = null;
            Uri data = getIntent().getData();
            if (data != null && "xmpp".equals(data.getScheme())) {
                XMPPUri xmppUri;
                try {
                    xmppUri = XMPPUri.parse(data);
                } catch (IllegalArgumentException e) {
                    xmppUri = null;
                }
                if (xmppUri != null && "message".equals(xmppUri.getQueryType())) {
                    ArrayList<String> texts = xmppUri.getValues("body");
                    String text = null;
                    if (texts != null && !texts.isEmpty()) {
                        text = texts.get(0);
                    }

                    UserJid user = null;
                    try {
                        user = UserJid.from(xmppUri.getPath());
                    } catch (UserJid.UserJidCreateException e) {
                        LogManager.exception(this, e);
                    }

                    if (user != null) {
                        openChat(user, text);
                    }
                }
            }
            break;
        }
        case Intent.ACTION_SENDTO: {
            action = null;
            Uri data = getIntent().getData();
            if (data != null) {
                String path = data.getPath();
                if (path != null && path.startsWith("/")) {
                    try {
                        UserJid user = UserJid.from(path.substring(1));
                        openChat(user, null);
                    } catch (UserJid.UserJidCreateException e) {
                        LogManager.exception(this, e);
                    }
                }
            }
            break;
        }

        case ContactListActivity.ACTION_MUC_PRIVATE_CHAT_INVITE:
            action = null;
            showMucPrivateChatDialog();
            break;

        case ContactListActivity.ACTION_CONTACT_SUBSCRIPTION:
            action = null;
            showContactSubscriptionDialog();
            break;

        case ContactListActivity.ACTION_INCOMING_MUC_INVITE:
            action = null;
            showMucInviteDialog();
            break;

        }
    }

    if (Application.getInstance().doNotify()) {
        if (BatteryHelper.isOptimizingBattery() && !SettingsManager.isBatteryOptimizationDisableSuggested()) {
            BatteryOptimizationDisableDialog.newInstance().show(getFragmentManager(),
                    BatteryOptimizationDisableDialog.class.getSimpleName());
        }

        if (!SettingsManager.isTranslationSuggested()) {
            Locale currentLocale = getResources().getConfiguration().locale;
            if (!currentLocale.getLanguage().equals("en") && !getResources().getBoolean(R.bool.is_translated)) {
                new TranslationDialog().show(getFragmentManager(), "TRANSLATION_DIALOG");
            }
        }

        if (SettingsManager.isCrashReportsSupported() && !SettingsManager.isCrashReportsDialogShown()) {
            CrashReportDialog.newInstance().show(getFragmentManager(), CrashReportDialog.class.getSimpleName());
        }

        if (SettingsManager.interfaceTheme() != SettingsManager.InterfaceTheme.dark) {
            if (!SettingsManager.isDarkThemeSuggested() && SettingsManager.bootCount() > 1) {
                new DarkThemeIntroduceDialog().show(getFragmentManager(),
                        DarkThemeIntroduceDialog.class.getSimpleName());
            }
        } else {
            SettingsManager.setDarkThemeSuggested();
        }

        if (SettingsManager.bootCount() > 2 && !SettingsManager.connectionStartAtBoot()
                && !SettingsManager.startAtBootSuggested()) {
            StartAtBootDialogFragment.newInstance().show(getFragmentManager(), "START_AT_BOOT");
        }
    }
}

From source file:com.owncloud.android.ui.activity.Uploader.java

public void uploadFiles() {
    try {/*from  w  w  w  . java2 s.c o m*/

        // ArrayList for files with path in external storage
        ArrayList<String> local = new ArrayList<String>();
        ArrayList<String> remote = new ArrayList<String>();

        // this checks the mimeType 
        for (Parcelable mStream : mStreamsToUpload) {

            Uri uri = (Uri) mStream;
            String data = null;
            String filePath = "";

            if (uri != null) {
                if (uri.getScheme().equals("content")) {
                    String mimeType = getContentResolver().getType(uri);

                    if (mimeType.contains("image")) {
                        String[] CONTENT_PROJECTION = { Images.Media.DATA, Images.Media.DISPLAY_NAME,
                                Images.Media.MIME_TYPE, Images.Media.SIZE };
                        Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null, null, null);
                        c.moveToFirst();
                        int index = c.getColumnIndex(Images.Media.DATA);
                        data = c.getString(index);
                        filePath = mUploadPath + c.getString(c.getColumnIndex(Images.Media.DISPLAY_NAME));

                    } else if (mimeType.contains("video")) {
                        String[] CONTENT_PROJECTION = { Video.Media.DATA, Video.Media.DISPLAY_NAME,
                                Video.Media.MIME_TYPE, Video.Media.SIZE, Video.Media.DATE_MODIFIED };
                        Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null, null, null);
                        c.moveToFirst();
                        int index = c.getColumnIndex(Video.Media.DATA);
                        data = c.getString(index);
                        filePath = mUploadPath + c.getString(c.getColumnIndex(Video.Media.DISPLAY_NAME));

                    } else if (mimeType.contains("audio")) {
                        String[] CONTENT_PROJECTION = { Audio.Media.DATA, Audio.Media.DISPLAY_NAME,
                                Audio.Media.MIME_TYPE, Audio.Media.SIZE };
                        Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null, null, null);
                        c.moveToFirst();
                        int index = c.getColumnIndex(Audio.Media.DATA);
                        data = c.getString(index);
                        filePath = mUploadPath + c.getString(c.getColumnIndex(Audio.Media.DISPLAY_NAME));

                    } else {
                        Cursor cursor = getContentResolver().query(uri,
                                new String[] { MediaStore.MediaColumns.DISPLAY_NAME }, null, null, null);
                        cursor.moveToFirst();
                        int nameIndex = cursor.getColumnIndex(cursor.getColumnNames()[0]);
                        if (nameIndex >= 0) {
                            filePath = mUploadPath + cursor.getString(nameIndex);
                        }
                    }

                } else if (uri.getScheme().equals("file")) {
                    filePath = Uri.decode(uri.toString()).replace(uri.getScheme() + "://", "");
                    if (filePath.contains("mnt")) {
                        String splitedFilePath[] = filePath.split("/mnt");
                        filePath = splitedFilePath[1];
                    }
                    final File file = new File(filePath);
                    data = file.getAbsolutePath();
                    filePath = mUploadPath + file.getName();
                } else {
                    throw new SecurityException();
                }
                if (data == null) {
                    mRemoteCacheData.add(filePath);
                    CopyTmpFileAsyncTask copyTask = new CopyTmpFileAsyncTask(this);
                    Object[] params = { uri, filePath, mRemoteCacheData.size() - 1, getAccount().name,
                            getContentResolver() };
                    mNumCacheFile++;
                    showWaitingCopyDialog();
                    copyTask.execute(params);
                } else {
                    remote.add(filePath);
                    local.add(data);
                }
            } else {
                throw new SecurityException();
            }

            Intent intent = new Intent(getApplicationContext(), FileUploader.class);
            intent.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
            intent.putExtra(FileUploader.KEY_LOCAL_FILE, local.toArray(new String[local.size()]));
            intent.putExtra(FileUploader.KEY_REMOTE_FILE, remote.toArray(new String[remote.size()]));
            intent.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
            startService(intent);

            //Save the path to shared preferences
            SharedPreferences.Editor appPrefs = PreferenceManager
                    .getDefaultSharedPreferences(getApplicationContext()).edit();
            appPrefs.putString("last_upload_path", mUploadPath);
            appPrefs.apply();

            finish();
        }

    } catch (SecurityException e) {
        String message = String.format(getString(R.string.uploader_error_forbidden_content),
                getString(R.string.app_name));
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }
}

From source file:com.keepassdroid.PasswordActivity.java

private boolean hasFileUri(Uri uri) {
    try {//w ww.  j a  v  a 2  s . com
        if (uri == null) {
            return false;
        }

        return uri.getScheme().equalsIgnoreCase("file");
    } catch (Exception e) {
        return false;
    }

}

From source file:com.percolatestudio.cordova.fileupload.PSFileUpload.java

/**
 * Uploads the specified file to the server URL provided using an HTTP multipart request.
 * @param source        Full path of the file on the file system
 * @param target        URL of the server to receive the file
 * @param args          JSON Array of args
 * @param callbackContext    callback id for optional progress reports
 *
 * args[2] fileKey       Name of file request parameter
 * args[3] fileName      File name to be used on server
 * args[4] mimeType      Describes file content type
 * args[5] params        key:value pairs of user-defined parameters
 * @return FileUploadResult containing result of upload request
 *//*from w  w  w.j av a 2s.  c  o  m*/
private void upload(final String source, final String target, JSONArray args, CallbackContext callbackContext)
        throws JSONException {
    Log.d(LOG_TAG, "upload " + source + " to " + target);

    // Setup the options
    final String mimeType = getArgument(args, 4, "image/jpeg");
    final JSONObject params = args.optJSONObject(5) == null ? new JSONObject() : args.optJSONObject(5);
    final boolean trustEveryone = args.optBoolean(6);
    // Always use chunked mode unless set to false as per API
    final boolean chunkedMode = args.optBoolean(7) || args.isNull(7);
    // Look for headers on the params map for backwards compatibility with older Cordova versions.
    final JSONObject headers = args.optJSONObject(8) == null ? params.optJSONObject("headers")
            : args.optJSONObject(8);
    final String objectId = args.getString(9);
    final String httpMethod = getArgument(args, 10, "POST");

    final CordovaResourceApi resourceApi = webView.getResourceApi();

    Log.d(LOG_TAG, "mimeType: " + mimeType);
    Log.d(LOG_TAG, "params: " + params);
    Log.d(LOG_TAG, "trustEveryone: " + trustEveryone);
    Log.d(LOG_TAG, "chunkedMode: " + chunkedMode);
    Log.d(LOG_TAG, "headers: " + headers);
    Log.d(LOG_TAG, "objectId: " + objectId);
    Log.d(LOG_TAG, "httpMethod: " + httpMethod);

    final Uri targetUri = resourceApi.remapUri(Uri.parse(target));
    // Accept a path or a URI for the source.
    Uri tmpSrc = Uri.parse(source);
    final Uri sourceUri = resourceApi
            .remapUri(tmpSrc.getScheme() != null ? tmpSrc : Uri.fromFile(new File(source)));

    int uriType = CordovaResourceApi.getUriType(targetUri);
    final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;
    if (uriType != CordovaResourceApi.URI_TYPE_HTTP && !useHttps) {
        JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0);
        Log.e(LOG_TAG, "Unsupported URI: " + targetUri);
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
        return;
    }

    final RequestContext context = new RequestContext(source, target, callbackContext);
    synchronized (activeRequests) {
        activeRequests.put(objectId, context);
    }

    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            if (context.aborted) {
                return;
            }
            HttpURLConnection conn = null;
            HostnameVerifier oldHostnameVerifier = null;
            SSLSocketFactory oldSocketFactory = null;
            int totalBytes = 0;
            int fixedLength = -1;
            try {
                // Create return object
                PSFileUploadResult result = new PSFileUploadResult();
                PSFileProgressResult progress = new PSFileProgressResult();

                //------------------ CLIENT REQUEST
                // Open a HTTP connection to the URL based on protocol
                conn = resourceApi.createHttpConnection(targetUri);
                if (useHttps && trustEveryone) {
                    // Setup the HTTPS connection class to trust everyone
                    HttpsURLConnection https = (HttpsURLConnection) conn;
                    oldSocketFactory = trustAllHosts(https);
                    // Save the current hostnameVerifier
                    oldHostnameVerifier = https.getHostnameVerifier();
                    // Setup the connection not to verify hostnames
                    https.setHostnameVerifier(DO_NOT_VERIFY);
                }

                // Allow Inputs
                conn.setDoInput(true);

                // Allow Outputs
                conn.setDoOutput(true);

                // Don't use a cached copy.
                conn.setUseCaches(false);

                // Use a post method.
                conn.setRequestMethod(httpMethod);
                conn.setRequestProperty("Content-Type", mimeType);

                // Set the cookies on the response
                String cookie = CookieManager.getInstance().getCookie(target);
                if (cookie != null) {
                    conn.setRequestProperty("Cookie", cookie);
                }

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

                // Get a input stream of the file on the phone
                OpenForReadResult readResult = resourceApi.openForRead(sourceUri);

                if (readResult.length >= 0) {
                    fixedLength = (int) readResult.length;
                    progress.setLengthComputable(true);
                    progress.setTotal(fixedLength);
                }
                Log.d(LOG_TAG, "Content Length: " + fixedLength);
                // setFixedLengthStreamingMode causes and OutOfMemoryException on pre-Froyo devices.
                // http://code.google.com/p/android/issues/detail?id=3164
                // It also causes OOM if HTTPS is used, even on newer devices.
                boolean useChunkedMode = chunkedMode
                        && (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO || useHttps);
                useChunkedMode = useChunkedMode || (fixedLength == -1);

                if (useChunkedMode) {
                    conn.setChunkedStreamingMode(MAX_BUFFER_SIZE);
                    // Although setChunkedStreamingMode sets this header, setting it explicitly here works
                    // around an OutOfMemoryException when using https.
                    conn.setRequestProperty("Transfer-Encoding", "chunked");
                } else {
                    conn.setFixedLengthStreamingMode(fixedLength);
                }

                conn.connect();

                OutputStream sendStream = null;
                try {
                    sendStream = conn.getOutputStream();
                    synchronized (context) {
                        if (context.aborted) {
                            return;
                        }
                        context.currentOutputStream = sendStream;
                    }
                    //We don't want to change encoding, we just want this to write for all Unicode.

                    // create a buffer of maximum size
                    int bytesAvailable = readResult.inputStream.available();
                    int bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
                    byte[] buffer = new byte[bufferSize];

                    // read file and write it into form...
                    int bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);

                    long prevBytesRead = 0;
                    while (bytesRead > 0) {
                        result.setBytesSent(totalBytes);
                        sendStream.write(buffer, 0, bytesRead);
                        totalBytes += bytesRead;
                        if (totalBytes > prevBytesRead + 102400) {
                            prevBytesRead = totalBytes;
                            Log.d(LOG_TAG, "Uploaded " + totalBytes + " of " + fixedLength + " bytes");
                        }
                        bytesAvailable = readResult.inputStream.available();
                        bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
                        bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);

                        // Send a progress event.
                        progress.setLoaded(totalBytes);
                        PluginResult progressResult = new PluginResult(PluginResult.Status.OK,
                                progress.toJSONObject());
                        progressResult.setKeepCallback(true);
                        context.sendPluginResult(progressResult);
                    }

                    sendStream.flush();
                } finally {
                    safeClose(readResult.inputStream);
                    safeClose(sendStream);
                }
                context.currentOutputStream = null;
                Log.d(LOG_TAG, "Sent " + totalBytes + " of " + fixedLength);

                //------------------ read the SERVER RESPONSE
                String responseString;
                int responseCode = conn.getResponseCode();
                Log.d(LOG_TAG, "response code: " + responseCode);
                Log.d(LOG_TAG, "response headers: " + conn.getHeaderFields());
                TrackingInputStream inStream = null;
                try {
                    inStream = getInputStream(conn);
                    synchronized (context) {
                        if (context.aborted) {
                            return;
                        }
                        context.currentInputStream = inStream;
                    }

                    ByteArrayOutputStream out = new ByteArrayOutputStream(
                            Math.max(1024, conn.getContentLength()));
                    byte[] buffer = new byte[1024];
                    int bytesRead = 0;
                    // write bytes to file
                    while ((bytesRead = inStream.read(buffer)) > 0) {
                        out.write(buffer, 0, bytesRead);
                    }
                    responseString = out.toString("UTF-8");
                } finally {
                    context.currentInputStream = null;
                    safeClose(inStream);
                }

                Log.d(LOG_TAG, "got response from server");
                Log.d(LOG_TAG, responseString.substring(0, Math.min(256, responseString.length())));

                // send request and retrieve response
                result.setResponseCode(responseCode);
                result.setResponse(responseString);

                context.sendPluginResult(new PluginResult(PluginResult.Status.OK, result.toJSONObject()));
            } catch (FileNotFoundException e) {
                JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn);
                Log.e(LOG_TAG, error.toString(), e);
                context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
            } catch (IOException e) {
                JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
                Log.e(LOG_TAG, error.toString(), e);
                Log.e(LOG_TAG, "Failed after uploading " + totalBytes + " of " + fixedLength + " bytes.");
                context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
                context.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
            } catch (Throwable t) {
                // Shouldn't happen, but will
                JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
                Log.e(LOG_TAG, error.toString(), t);
                context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
            } finally {
                synchronized (activeRequests) {
                    activeRequests.remove(objectId);
                }

                if (conn != null) {
                    // Revert back to the proper verifier and socket factories
                    // Revert back to the proper verifier and socket factories
                    if (trustEveryone && useHttps) {
                        HttpsURLConnection https = (HttpsURLConnection) conn;
                        https.setHostnameVerifier(oldHostnameVerifier);
                        https.setSSLSocketFactory(oldSocketFactory);
                    }
                }
            }
        }
    });
}

From source file:net.gsantner.opoc.util.ContextUtils.java

/**
 * Detect MimeType of given file/*from w  ww.  ja  v  a2s .co  m*/
 * Android/Java's own MimeType map is very very small and detection barely works at all
 * Hence use custom map for some file extensions
 */
public String getMimeType(Uri uri) {
    String mimeType = null;
    if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
        ContentResolver cr = _context.getContentResolver();
        mimeType = cr.getType(uri);
    } else {
        String ext = MimeTypeMap.getFileExtensionFromUrl(uri.toString());
        mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext.toLowerCase());

        // Try to guess if the recommended methods fail
        if (TextUtils.isEmpty(mimeType)) {
            switch (ext) {
            case "md":
            case "markdown":
            case "mkd":
            case "mdown":
            case "mkdn":
            case "mdwn":
            case "rmd":
                mimeType = "text/markdown";
                break;
            case "yaml":
            case "yml":
                mimeType = "text/yaml";
                break;
            case "json":
                mimeType = "text/json";
                break;
            case "txt":
                mimeType = "text/plain";
                break;
            }
        }
    }

    if (TextUtils.isEmpty(mimeType)) {
        mimeType = "*/*";
    }
    return mimeType;
}