Example usage for android.webkit MimeTypeMap getFileExtensionFromUrl

List of usage examples for android.webkit MimeTypeMap getFileExtensionFromUrl

Introduction

In this page you can find the example usage for android.webkit MimeTypeMap getFileExtensionFromUrl.

Prototype

public static String getFileExtensionFromUrl(String url) 

Source Link

Document

Returns the file extension or an empty string if there is no extension.

Usage

From source file:com.github.vase4kin.teamcityapp.artifact.router.ArtifactRouterImpl.java

/**
 * {@inheritDoc}/*from  w w  w  . j a  v a 2 s.c o  m*/
 */
@Override
public void startFileActivity(File file) {
    MimeTypeMap map = MimeTypeMap.getSingleton();
    String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());
    String type = map.getMimeTypeFromExtension(ext);

    if (type == null) {
        type = ALL_FILES_TYPE;
    }

    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri data = FileProvider.getUriForFile(mActivity, BuildConfig.APPLICATION_ID + ".provider", file);
    intent.setDataAndType(data, type);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

    //User couldn't have app with type intent
    try {
        mActivity.startActivity(intent);
    } catch (android.content.ActivityNotFoundException e) {
        intent.setDataAndType(data, ALL_FILES_TYPE);
        mActivity.startActivity(intent);
    }
}

From source file:me.kartikarora.transfersh.activities.DownloadActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_download);

    final CoordinatorLayout layout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
    Intent intent = getIntent();//from   w  ww .  j a va  2 s.c o m
    url = intent.getData().toString();
    name = FilenameUtils.getName(url);
    type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
    TransferApplication application = (TransferApplication) getApplication();
    mTracker = application.getDefaultTracker();

    new AlertDialog.Builder(DownloadActivity.this)
            .setMessage(getString(R.string.download_file) + " " + getString(R.string.app_name) + "?")
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    checkForDownload(name, type, url, layout);
                    finish();
                }
            }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    finish();
                }
            }).create().show();

    mTracker.send(new HitBuilders.EventBuilder().setCategory("Activity : " + this.getClass().getSimpleName())
            .setAction("Launched").build());

}

From source file:mil.nga.giat.mage.sdk.utils.MediaUtility.java

public static String getMimeType(String url) {
    String type = null;// w ww .  j a  va 2s . c o  m
    if (StringUtils.isBlank(url)) {
        return type;
    }
    String extension = null;
    try {
        extension = MimeTypeMap.getFileExtensionFromUrl(URLEncoder.encode(url.replaceAll("\\s*", ""), "UTF-8"));
    } catch (UnsupportedEncodingException uee) {
        Log.e(LOG_NAME, "Unable to determine file extension");
    }

    if (StringUtils.isBlank(extension)) {
        int i = url.lastIndexOf('.');
        if (i > 0 && url.length() >= i + 1) {
            extension = url.substring(i + 1);
        }
    }

    if (!StringUtils.isBlank(extension)) {
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        type = mime.getMimeTypeFromExtension(extension);
    }
    return type;
}

From source file:com.mobileuni.helpers.FileManager.java

public void UploadToUrl(String siteUrl, String token, String filepath) {

    String url = siteUrl + "/webservice/upload.php?token=" + token;
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    org.apache.http.client.methods.HttpPost httppost = new org.apache.http.client.methods.HttpPost(url);
    File file = new File(filepath);

    String mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
            MimeTypeMap.getFileExtensionFromUrl(filepath.substring(filepath.lastIndexOf("."))));

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, mimetype);
    mpEntity.addPart("userfile", cbFile);

    httppost.setEntity(mpEntity);//from   www . ja v a  2s .co  m
    Log.d(TAG, "upload executing request " + httppost.getRequestLine());
    try {

        HttpResponse response = httpclient.execute(httppost);

        HttpEntity resEntity = response.getEntity();

        Log.d(TAG, "upload line status " + response.getStatusLine());
        if (resEntity != null) {
            Log.d(TAG, "upload " + EntityUtils.toString(resEntity));
            //JSONObject jObject = new JSONObject(EntityUtils.toString(resEntity));
        } else {
            Log.d(TAG, "upload error: " + EntityUtils.toString(resEntity));
        }

    } catch (Exception ex) {
        Log.d(TAG, "Error: " + ex);
    }

    httpclient.getConnectionManager().shutdown();
}

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

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

    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.vk.sdk.api.httpClient.VKMultipartEntity.java

private String getFileDescription(File uploadFile, int i) {
    String fileName = String.format(Locale.US, "file%d", i + 1);
    String extension = MimeTypeMap.getFileExtensionFromUrl(uploadFile.getAbsolutePath());
    return String.format("\r\n--%s\r\n", mBoundary)
            + String.format("Content-Disposition: form-data; name=\"%s\"; filename=\"%s.%s\"\r\n", fileName,
                    fileName, extension)
            + String.format("Content-Type: %s\r\n\r\n", getMimeType(uploadFile.getAbsolutePath()));
}

From source file:com.vk.sdk.api.httpClient.VKMultipartEntity.java

protected static String getMimeType(String url) {
    String type = null;/*w  w  w. jav  a2 s. c o m*/
    String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    if (extension != null) {
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        type = mime.getMimeTypeFromExtension(extension);
    }
    return type;
}

From source file:mobisocial.musubi.objects.FileObj.java

public static Obj from(Context context, Uri dataUri) throws IOException {
    //TODO: is this the proper way to do it?
    if (dataUri == null) {
        throw new NullPointerException();
    }/*from  w ww.  j  a  v a  2  s.co  m*/
    ContentResolver cr = context.getContentResolver();
    InputStream in = cr.openInputStream(dataUri);
    long length = in.available();

    String ext;
    String mimeType;
    String filename;

    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
    if ("content".equals(dataUri.getScheme())) {
        ContentResolver resolver = context.getContentResolver();
        mimeType = resolver.getType(dataUri);
        ext = mimeTypeMap.getExtensionFromMimeType(mimeType);
        filename = "Musubi-" + sDateFormat.format(new Date());
    } else {
        ext = MimeTypeMap.getFileExtensionFromUrl(dataUri.toString());
        mimeType = mimeTypeMap.getMimeTypeFromExtension(ext);
        filename = Uri.parse(dataUri.toString()).getLastPathSegment();
        if (filename == null) {
            filename = "Musubi-" + sDateFormat.format(new Date());
        }
    }

    if (mimeType == null || mimeType.isEmpty()) {
        throw new IOException("Unidentified mime type");
    }

    if (ext == null || ext.isEmpty()) {
        ext = mimeTypeMap.getExtensionFromMimeType(mimeType);
    }

    if (!ext.isEmpty() && !filename.endsWith(ext)) {
        filename = filename + "." + ext;
    }

    if (mimeType.startsWith("video/")) {
        return VideoObj.from(context, dataUri, mimeType);
    } else if (mimeType.startsWith("image/")) {
        return PictureObj.from(context, dataUri, true);
    }

    if (length > EMBED_SIZE_LIMIT) {
        if (length > CORRAL_SIZE_LIMIT) {
            throw new IOException("file too large for push");
        } else {
            return fromCorral(context, mimeType, filename, length, dataUri);
        }
    } else {
        in = cr.openInputStream(dataUri);
        return from(mimeType, filename, length, IOUtils.toByteArray(in));
    }
}

From source file:mobisocial.bento.anyshare.ui.FeedItemListActivity.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent ret) {
    if (requestCode == REQUEST_PICK) {
        if (resultCode == RESULT_OK) {
            Log.d(TAG, ret.toString());//from   w ww . ja  v a 2 s.  c  om
            Uri uri = ret.getData();
            Intent intent = new Intent(this, PostActivity.class);
            intent.setAction(Intent.ACTION_SEND);
            String mimetype = getContentResolver().getType(uri);
            String ext = MimeTypeMap.getFileExtensionFromUrl(uri.toString());

            MimeTypeMap mime = MimeTypeMap.getSingleton();
            if (mimetype == null || mimetype.isEmpty()) {
                if (!ext.isEmpty()) {
                    mimetype = mime.getMimeTypeFromExtension(ext);
                }
            }

            String fname = uri.getLastPathSegment();
            if (ext.isEmpty()) {
                fname += "." + mime.getExtensionFromMimeType(mimetype);
            }

            intent.setType(mimetype);
            intent.putExtra(Intent.EXTRA_SUBJECT, fname);
            intent.putExtra(Intent.EXTRA_TEXT, "");
            intent.putExtra(Intent.EXTRA_STREAM, uri);

            startActivityForResult(intent, HomeActivity.REQUEST_VIEW);

        }
    }
    super.onActivityResult(requestCode, resultCode, ret);
}

From source file:com.ugedal.weeklyschedule.ListFragment.java

public static String getMimeType(String url) {
    String type = null;/*from www  .j  av  a  2 s  . c o  m*/
    String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    if (extension != null) {
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }
    return type;
}