Example usage for android.webkit URLUtil guessFileName

List of usage examples for android.webkit URLUtil guessFileName

Introduction

In this page you can find the example usage for android.webkit URLUtil guessFileName.

Prototype

public static final String guessFileName(String url, @Nullable String contentDisposition,
        @Nullable String mimeType) 

Source Link

Document

Guesses canonical filename that a download would have, using the URL and contentDisposition.

Usage

From source file:Main.java

@SuppressLint("NewApi")
public static CompressFormat guessImageFormatC(String urlOrPath) {
    CompressFormat format = null;// w w  w.j  a v  a 2  s.c o  m
    String fileName;
    if (URLUtil.isNetworkUrl(urlOrPath)) {
        fileName = URLUtil.guessFileName(urlOrPath, null, null);
    } else if (urlOrPath.lastIndexOf('.') <= 0) {
        return null;
    } else {
        fileName = urlOrPath;
    }
    fileName = fileName.toLowerCase(Locale.US);
    if (fileName.endsWith(".png")) {
        format = CompressFormat.PNG;
    } else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
        format = CompressFormat.JPEG;
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && fileName.endsWith(".webp")) {
        format = CompressFormat.WEBP;
    }
    return format;
}

From source file:org.mozilla.focus.broadcastreceiver.DownloadBroadcastReceiver.java

private void displaySnackbar(final Context context, long completedDownloadReference,
        DownloadManager downloadManager) {
    if (!isFocusDownload(completedDownloadReference)) {
        return;//from w ww .  j a v  a 2s  .c o m
    }

    final DownloadManager.Query query = new DownloadManager.Query();
    query.setFilterById(completedDownloadReference);
    try (Cursor cursor = downloadManager.query(query)) {
        if (cursor.moveToFirst()) {
            int statusColumnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
            if (DownloadManager.STATUS_SUCCESSFUL == cursor.getInt(statusColumnIndex)) {
                String uriString = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));

                final String localUri = uriString.startsWith(FILE_SCHEME)
                        ? uriString.substring(FILE_SCHEME.length())
                        : uriString;
                final String fileExtension = MimeTypeMap.getFileExtensionFromUrl(localUri);
                final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
                final String fileName = URLUtil.guessFileName(Uri.decode(localUri), null, mimeType);

                final File file = new File(Uri.decode(localUri));
                final Uri uriForFile = FileProvider.getUriForFile(context,
                        BuildConfig.APPLICATION_ID + FILE_PROVIDER_EXTENSION, file);
                final Intent openFileIntent = IntentUtils.createOpenFileIntent(uriForFile, mimeType);
                showSnackbarForFilename(openFileIntent, context, fileName);
            }
        }
    }
    removeFromHashSet(completedDownloadReference);
}

From source file:com.android.xbrowser.FetchUrlMimeType.java

@Override
public void run() {
    // User agent is likely to be null, though the AndroidHttpClient
    // seems ok with that.
    AndroidHttpClient client = AndroidHttpClient.newInstance(mUserAgent);
    HttpHost httpHost = Proxy.getPreferredHttpHost(mContext, mUri);
    if (httpHost != null) {
        ConnRouteParams.setDefaultProxy(client.getParams(), httpHost);
    }/*from  w ww .  j  a  va2 s .c om*/
    HttpHead request = new HttpHead(mUri);

    if (mCookies != null && mCookies.length() > 0) {
        request.addHeader("Cookie", mCookies);
    }

    HttpResponse response;
    String mimeType = null;
    String contentDisposition = null;
    try {
        response = client.execute(request);
        // We could get a redirect here, but if we do lets let
        // the download manager take care of it, and thus trust that
        // the server sends the right mimetype
        if (response.getStatusLine().getStatusCode() == 200) {
            Header header = response.getFirstHeader("Content-Type");
            if (header != null) {
                mimeType = header.getValue();
                final int semicolonIndex = mimeType.indexOf(';');
                if (semicolonIndex != -1) {
                    mimeType = mimeType.substring(0, semicolonIndex);
                }
            }
            Header contentDispositionHeader = response.getFirstHeader("Content-Disposition");
            if (contentDispositionHeader != null) {
                contentDisposition = contentDispositionHeader.getValue();
            }
        }
    } catch (IllegalArgumentException ex) {
        request.abort();
    } catch (IOException ex) {
        request.abort();
    } finally {
        client.close();
    }

    if (mimeType != null) {
        if (mimeType.equalsIgnoreCase("text/plain") || mimeType.equalsIgnoreCase("application/octet-stream")) {
            String newMimeType = MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(mUri));
            if (newMimeType != null) {
                mRequest.setMimeType(newMimeType);
            }
        }
        String filename = URLUtil.guessFileName(mUri, contentDisposition, mimeType);
        mRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
    }

    // Start the download
    DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(mRequest);
}

From source file:com.android.browser.kai.FetchUrlMimeType.java

@Override
public void onPostExecute(String mimeType) {
    if (mimeType != null) {
        String url = mValues.getAsString(Downloads.COLUMN_URI);
        if (mimeType.equalsIgnoreCase("text/plain") || mimeType.equalsIgnoreCase("application/octet-stream")) {
            String newMimeType = MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
            if (newMimeType != null) {
                mValues.put(Downloads.COLUMN_MIME_TYPE, newMimeType);
            }//from  w w w .j  a v a  2 s  .  co  m
        }
        String filename = URLUtil.guessFileName(url, null, mimeType);
        mValues.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
    }

    // Start the download
    final Uri contentUri = mActivity.getContentResolver().insert(Downloads.CONTENT_URI, mValues);
    mActivity.viewDownloads(contentUri);
}

From source file:com.android.erowser.FetchUrlMimeType.java

@Override
public void onPostExecute(String mimeType) {
    if (mimeType != null) {
        String url = mValues.getAsString(Downloads.COLUMN_URI);
        if (mimeType.equalsIgnoreCase("text/plain") || mimeType.equalsIgnoreCase("application/octet-stream")) {
            String newMimeType = MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
            if (newMimeType != null) {
                mValues.put(Downloads.COLUMN_MIME_TYPE, newMimeType);
            }/* w ww.ja v a 2  s.  c  om*/
        }
        String filename = URLUtil.guessFileName(url, null, mimeType);
        mValues.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
    }

    // Start the download
    //shuaiyuan removed ==>
    //final Uri contentUri =
    //    mActivity.getContentResolver().insert(Downloads.CONTENT_URI, mValues);
    //mActivity.viewDownloads(contentUri);
    //shuaiyuan removed <==
}

From source file:org.anoopam.main.thakorjitoday.TempleGalleryActivity.java

public void setDownloadPath(int pos) {
    destinationImageFileName = templeDetail.getAsString("templeID") + "_"
            + URLUtil.guessFileName(templeImages.get(pos).getAsString("image"), null, null);
    destinationImageFilePathPrefix = SmartUtils
            .getAnoopamMissionDailyRefreshImageStorage(templeDetail.getAsString("templeID")) + File.separator;
}

From source file:com.mogoweb.browser.FetchUrlMimeType.java

@Override
public void run() {
    // User agent is likely to be null, though the AndroidHttpClient
    // seems ok with that.
    AndroidHttpClient client = AndroidHttpClient.newInstance(mUserAgent);
    //        HttpHost httpHost;
    //        try {
    //            httpHost = Proxy.getPreferredHttpHost(mContext, mUri);
    //            if (httpHost != null) {
    //                ConnRouteParams.setDefaultProxy(client.getParams(), httpHost);
    //            }
    //        } catch (IllegalArgumentException ex) {
    //            Log.e(LOGTAG,"Download failed: " + ex);
    //            client.close();
    //            return;
    //        }/*w  w  w  .  j a  v  a  2s . c om*/
    HttpHead request = new HttpHead(mUri);

    if (mCookies != null && mCookies.length() > 0) {
        request.addHeader("Cookie", mCookies);
    }

    HttpResponse response;
    String mimeType = null;
    String contentDisposition = null;
    try {
        response = client.execute(request);
        // We could get a redirect here, but if we do lets let
        // the download manager take care of it, and thus trust that
        // the server sends the right mimetype
        if (response.getStatusLine().getStatusCode() == 200) {
            Header header = response.getFirstHeader("Content-Type");
            if (header != null) {
                mimeType = header.getValue();
                final int semicolonIndex = mimeType.indexOf(';');
                if (semicolonIndex != -1) {
                    mimeType = mimeType.substring(0, semicolonIndex);
                }
            }
            Header contentDispositionHeader = response.getFirstHeader("Content-Disposition");
            if (contentDispositionHeader != null) {
                contentDisposition = contentDispositionHeader.getValue();
            }
        }
    } catch (IllegalArgumentException ex) {
        request.abort();
    } catch (IOException ex) {
        request.abort();
    } finally {
        client.close();
    }

    if (mimeType != null) {
        if (mimeType.equalsIgnoreCase("text/plain") || mimeType.equalsIgnoreCase("application/octet-stream")) {
            String newMimeType = MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(mUri));
            if (newMimeType != null) {
                mimeType = newMimeType;
                mRequest.setMimeType(newMimeType);
            }
        }
        String filename = URLUtil.guessFileName(mUri, contentDisposition, mimeType);
        mRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
    }

    // Start the download
    DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(mRequest);
}

From source file:no.digipost.android.gui.metadata.ExternalLinkWebview.java

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ((DigipostApplication) getApplication()).getTracker(DigipostApplication.TrackerName.APP_TRACKER);
    setContentView(R.layout.activity_externallink_webview);
    Bundle bundle = getIntent().getExtras();
    fileUrl = bundle.getString("url", "https://www.digipost.no");

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);//from   w  ww  . ja  v  a  2  s. c  om
    actionBar = getSupportActionBar();
    if (actionBar != null) {
        setActionBarTitle(fileUrl);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setBackgroundDrawable(new ColorDrawable(0xff2E2E2E));

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = this.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(
                    ContextCompat.getColor(this, R.color.metadata_externalbrowser_top_background));
        }
    }

    progressSpinner = (ProgressBar) findViewById(R.id.externallink_spinner);
    webView = (WebView) findViewById(R.id.externallink_webview);
    WebSettings settings = webView.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
    settings.setDomStorageEnabled(true);
    settings.setLoadWithOverviewMode(true);
    settings.setUseWideViewPort(true);
    settings.setSupportZoom(true);
    settings.setBuiltInZoomControls(true);
    settings.setDisplayZoomControls(false);
    settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.setScrollbarFadingEnabled(true);
    enableCookies(webView);
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (firstLoad) {
                progressSpinner.setVisibility(View.GONE);
                webView.setVisibility(View.VISIBLE);
                firstLoad = false;
            }
            setActionBarTitle(view.getUrl());
        }
    });

    webView.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(final String url, final String userAgent, final String content,
                final String mimeType, final long contentLength) {
            fileName = URLUtil.guessFileName(url, content, mimeType);
            fileUrl = url;
            onComplete = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                        showDownloadSuccessDialog(context);
                    }
                }
            };

            registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
            if (!mimeType.equals("text/html")) {
                if (FileUtilities.isStorageWriteAllowed(getApplicationContext())) {
                    showDownloadDialog(userAgent, content, mimeType, contentLength);
                } else {
                    showMissingPermissionsDialog();
                }
            }
        }
    });

    if (FileUtilities.isStorageWriteAllowed(this)) {
        webView.loadUrl(fileUrl);
    } else {
        showPermissionsDialog();
    }
}

From source file:com.android.browser.FetchUrlMimeType.java

@Override
public void onPostExecute(ContentValues values) {
    final String mimeType = values.getAsString("Content-Type");
    final String contentDisposition = values.getAsString("Content-Disposition");
    if (mimeType != null) {
        String url = mValues.getAsString(Downloads.Impl.COLUMN_URI);
        if (mimeType.equalsIgnoreCase("text/plain") || mimeType.equalsIgnoreCase("application/octet-stream")) {
            String newMimeType = MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
            if (newMimeType != null) {
                mValues.put(Downloads.Impl.COLUMN_MIME_TYPE, newMimeType);
            }//from www  . j  a v a 2 s  . c  o m
        }
        String filename = URLUtil.guessFileName(url, contentDisposition, mimeType);
        mValues.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
    }

    // Start the download
    final Uri contentUri = mActivity.getContentResolver().insert(Downloads.Impl.CONTENT_URI, mValues);
}

From source file:de.baumann.hhsmoodle.fragmentsMain.FragmentBrowser.java

@SuppressWarnings("ResultOfMethodCallIgnored")
@SuppressLint("SetJavaScriptEnabled")

@Override/* w  w w .  j  a  v a2  s  .  c  om*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_screen_browser, container, false);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        WebView.enableSlowWholeDocumentDraw();
    }

    PreferenceManager.setDefaultValues(getActivity(), R.xml.user_settings, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
    sharedPref.edit().putString("browserStarted", "true").apply();

    customViewContainer = (FrameLayout) rootView.findViewById(R.id.customViewContainer);
    progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
    viewPager = (ViewPager) getActivity().findViewById(R.id.viewpager);

    SwipeRefreshLayout swipeView = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe);
    assert swipeView != null;
    swipeView.setColorSchemeResources(R.color.colorPrimary, R.color.colorAccent);
    swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mWebView.reload();
        }
    });

    mWebView = (WebView) rootView.findViewById(R.id.webView);
    mWebChromeClient = new myWebChromeClient();
    mWebView.setWebChromeClient(mWebChromeClient);

    imageButton_left = (ImageButton) rootView.findViewById(R.id.imageButton_left);
    imageButton_right = (ImageButton) rootView.findViewById(R.id.imageButton_right);

    if (sharedPref.getBoolean("arrow", false)) {
        imageButton_left.setVisibility(View.VISIBLE);
        imageButton_right.setVisibility(View.VISIBLE);
    } else {
        imageButton_left.setVisibility(View.INVISIBLE);
        imageButton_right.setVisibility(View.INVISIBLE);
    }

    helper_webView.webView_Settings(getActivity(), mWebView);
    helper_webView.webView_WebViewClient(getActivity(), swipeView, mWebView);

    mWebView.setDownloadListener(new DownloadListener() {

        public void onDownloadStart(final String url, String userAgent, final String contentDisposition,
                final String mimetype, long contentLength) {

            final String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);
            Snackbar snackbar = Snackbar
                    .make(mWebView, getString(R.string.toast_download_1) + " " + filename,
                            Snackbar.LENGTH_INDEFINITE)
                    .setAction(getString(R.string.toast_yes), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                            request.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url));
                            request.allowScanningByMediaScanner();
                            request.setNotificationVisibility(
                                    DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                            request.setDestinationInExternalPublicDir(newFileDest(), filename);
                            DownloadManager dm = (DownloadManager) getActivity()
                                    .getSystemService(DOWNLOAD_SERVICE);
                            dm.enqueue(request);

                            Snackbar.make(mWebView, getString(R.string.toast_download) + " " + filename,
                                    Snackbar.LENGTH_LONG).show();
                            getActivity().registerReceiver(onComplete,
                                    new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
                        }
                    });
            snackbar.show();
        }
    });

    String URLtoOpen = sharedPref.getString("loadURL", "");
    if (URLtoOpen.isEmpty()) {
        mWebView.loadUrl(
                sharedPref.getString("favoriteURL", "https://moodle.huebsch.ka.schule-bw.de/moodle/my/"));
    } else {
        mWebView.loadUrl(URLtoOpen);
    }

    setHasOptionsMenu(true);
    return rootView;
}