Example usage for android.webkit MimeTypeMap getExtensionFromMimeType

List of usage examples for android.webkit MimeTypeMap getExtensionFromMimeType

Introduction

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

Prototype

@Nullable
public String getExtensionFromMimeType(String mimeType) 

Source Link

Document

Return the registered extension for the given MIME type.

Usage

From source file:com.doplgangr.secrecy.FileSystem.Vault.java

public String addFile(final Context context, final Uri uri) {
    String filename = uri.getLastPathSegment();
    try {//from   w  w w  . jav  a2  s .co m
        String realPath = getPath(context, uri);
        Util.log(realPath, filename);
        filename = new java.io.File(realPath).getName();
        // If we can use real path, better use one.
    } catch (Exception ignored) {
        // Leave it.
    }
    if (!filename.contains("_thumb") && !filename.contains(".nomedia")) {
        ContentResolver cR = context.getContentResolver();
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        String type = mime.getExtensionFromMimeType(cR.getType(uri));
        if (type != null)
            filename = Base64Coder.encodeString(FilenameUtils.removeExtension(filename)) + "." + type;
    }
    InputStream is = null;
    OutputStream out = null;
    try {
        InputStream stream = context.getContentResolver().openInputStream(uri);
        java.io.File addedFile = new java.io.File(path + "/" + filename);
        addedFile.delete();
        addedFile.createNewFile();
        is = new BufferedInputStream(stream);
        byte buffer[] = new byte[Config.bufferSize];
        int count;
        AES_Encryptor enc = new AES_Encryptor(key);
        out = new CipherOutputStream(new FileOutputStream(addedFile), enc.encryptstream());
        while ((count = is.read(buffer)) != -1)
            out.write(buffer, 0, count);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return filename;
}

From source file:com.waz.zclient.pages.main.conversation.views.row.message.views.FileMessageViewController.java

private String getFileExtension(Asset asset) {
    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
    return mimeTypeMap.getExtensionFromMimeType(asset.getMimeType());
}

From source file:net.henryco.opalette.application.StartUpActivity.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == Utils.activity.REQUEST_PICK_IMAGE) {
            Intent intent = new Intent(this, MainActivity.class);
            BitmapPack.pushUpBitmap = Utils.loadIntentBitmap(this, data);

            ContentResolver cR = getContentResolver();
            MimeTypeMap mime = MimeTypeMap.getSingleton();
            if (!checkImgType(mime.getExtensionFromMimeType(cR.getType(data.getData()))))
                wrongTypeDialog.run();//w  w w. j a  v a2 s  .  c  o  m
            else {
                closeAction();
                startActivity(intent);
                close();
            }
        }
    }
}

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  . j a  v  a2s  . c o  m
            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.github.developerpaul123.filepickerlibrary.FilePickerActivity.java

/**
 * Initializes all the views in the layout of the activity.
 *///from  ww w.java 2  s .  co  m
private void initializeViews() {
    directoryTitle = (TextView) findViewById(R.id.file_directory_title);
    addButton = (MaterialFloatingActionButton) findViewById(R.id.file_picker_add_button);
    addButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            NameFileDialog nfd = NameFileDialog.newInstance();
            nfd.show(getFragmentManager(), "NameDialog");
        }
    });

    if (fabColorId != -1) {
        addButton.setButtonColor(getResources().getColor(fabColorId));
    }
    selectButton = (Button) findViewById(R.id.select_button);
    selectButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (requestCode == Request.DIRECTORY) {
                if (currentFile.isDirectory()) {
                    curDirectory = currentFile;
                    data = new Intent();
                    data.putExtra(FILE_EXTRA_DATA_PATH, currentFile.getAbsolutePath());
                    setResult(RESULT_OK, data);
                    finish();
                } else {
                    Snackbar.make(getWindow().getDecorView(),
                            R.string.file_picker_snackbar_select_directory_message, Snackbar.LENGTH_SHORT)
                            .show();
                }
            } else { //request code is for a file
                if (currentFile.isDirectory()) {
                    curDirectory = currentFile;
                    new UpdateFilesTask(FilePickerActivity.this).execute(curDirectory);
                } else {
                    if (!TextUtils.isEmpty(mimeType)) {
                        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
                        String requiredExtension = "." + mimeTypeMap.getExtensionFromMimeType(mimeType);
                        if (requiredExtension.equalsIgnoreCase(fileExt(currentFile.toString()))) {
                            data = new Intent();
                            data.putExtra(FILE_EXTRA_DATA_PATH, currentFile.getAbsolutePath());
                            setResult(RESULT_OK, data);
                            finish();
                        } else {
                            Snackbar.make(getWindow().getDecorView(),
                                    String.format(
                                            getString(R.string.file_picker_snackbar_select_file_ext_message),
                                            requiredExtension),
                                    Snackbar.LENGTH_SHORT).show();
                        }
                    } else {
                        data = new Intent();
                        data.putExtra(FILE_EXTRA_DATA_PATH, currentFile.getAbsolutePath());
                        setResult(RESULT_OK, data);
                        finish();
                    }
                }
            }
        }
    });

    openButton = (Button) findViewById(R.id.open_button);
    openButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (currentFile.isDirectory()) {
                curDirectory = currentFile;
                directoryTitle.setText(curDirectory.getName());

                new UpdateFilesTask(FilePickerActivity.this).execute(curDirectory);
            } else {
                Intent newIntent = new Intent(Intent.ACTION_VIEW);
                String file = currentFile.toString();
                if (file != null) {
                    newIntent.setDataAndType(Uri.fromFile(currentFile), mimeType);
                    newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    try {
                        startActivity(newIntent);
                    } catch (ActivityNotFoundException e) {
                        Snackbar.make(getWindow().getDecorView(),
                                R.string.file_picker_snackbar_no_file_type_handler, Snackbar.LENGTH_SHORT)
                                .show();
                    }
                } else {
                    Snackbar.make(getWindow().getDecorView(), R.string.file_picker_snackbar_no_read_type,
                            Snackbar.LENGTH_SHORT).show();
                }

            }
        }
    });

    buttonContainer = (LinearLayout) findViewById(R.id.button_container);
    buttonContainer.setVisibility(View.INVISIBLE);

    header = (RelativeLayout) findViewById(R.id.header_container);
}

From source file:com.devpaul.filepickerlibrary.FilePickerActivity.java

/**
 * Initializes all the views in the layout of the activity.
 *//* w ww .  j ava 2  s  .c  om*/
private void initializeViews() {
    directoryTitle = (TextView) findViewById(R.id.file_directory_title);
    addButton = (MaterialFloatingActionButton) findViewById(R.id.file_picker_add_button);
    addButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            NameFileDialog nfd = NameFileDialog.newInstance();
            nfd.show(getFragmentManager(), "NameDialog");
        }
    });

    if (fabColorId != -1) {
        addButton.setButtonColor(getResources().getColor(fabColorId));
    }
    selectButton = (Button) findViewById(R.id.select_button);
    selectButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (requestCode == REQUEST_DIRECTORY) {
                if (currentFile.isDirectory()) {
                    curDirectory = currentFile;
                    data = new Intent();
                    data.putExtra(FILE_EXTRA_DATA_PATH, currentFile.getAbsolutePath());
                    setResult(RESULT_OK, data);
                    finish();
                } else {
                    SnackbarManager.show(Snackbar.with(FilePickerActivity.this)
                            .text(R.string.file_picker_snackbar_select_directory_message).duration(1500));
                }
            } else { //request code is for a file
                if (currentFile.isDirectory()) {
                    curDirectory = currentFile;
                    new UpdateFilesTask(FilePickerActivity.this).execute(curDirectory);
                } else {
                    if (mimeType != null) {
                        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
                        String requiredExtension = "." + mimeTypeMap.getExtensionFromMimeType(mimeType);
                        if (requiredExtension.equalsIgnoreCase(fileExt(currentFile.toString()))) {
                            data = new Intent();
                            data.putExtra(FILE_EXTRA_DATA_PATH, currentFile.getAbsolutePath());
                            setResult(RESULT_OK, data);
                            finish();
                        } else {
                            SnackbarManager.show(Snackbar.with(FilePickerActivity.this)
                                    .text(String.format(
                                            getString(R.string.file_picker_snackbar_select_file_ext_message),
                                            requiredExtension))
                                    .duration(1500));
                        }
                    } else {
                        data = new Intent();
                        data.putExtra(FILE_EXTRA_DATA_PATH, currentFile.getAbsolutePath());
                        setResult(RESULT_OK, data);
                        finish();
                    }
                }
            }
        }
    });

    openButton = (Button) findViewById(R.id.open_button);
    openButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (currentFile.isDirectory()) {
                curDirectory = currentFile;
                directoryTitle.setText(curDirectory.getName());

                new UpdateFilesTask(FilePickerActivity.this).execute(curDirectory);
            } else {
                Intent newIntent = new Intent(android.content.Intent.ACTION_VIEW);
                String file = currentFile.toString();
                if (file != null) {
                    newIntent.setDataAndType(Uri.fromFile(currentFile), mimeType);
                    newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    try {
                        startActivity(newIntent);
                    } catch (android.content.ActivityNotFoundException e) {
                        SnackbarManager.show(Snackbar.with(FilePickerActivity.this)
                                .text(R.string.file_picker_snackbar_no_file_type_handler));
                    }
                } else {
                    SnackbarManager.show(Snackbar.with(FilePickerActivity.this)
                            .text(R.string.file_picker_snackbar_no_read_type));
                }

            }
        }
    });

    buttonContainer = (LinearLayout) findViewById(R.id.button_container);
    buttonContainer.setVisibility(View.INVISIBLE);

    header = (RelativeLayout) findViewById(R.id.header_container);
}

From source file:com.stfalcon.contentmanager.ContentManager.java

private String guessFileExtensionFromUrl(String url) {
    ContentResolver cR = activity.getContentResolver();
    MimeTypeMap mime = MimeTypeMap.getSingleton();
    String type = mime.getExtensionFromMimeType(cR.getType(Uri.parse(url)));
    cR.getType(Uri.parse(url));/*w  ww . j  a v a 2s .c  o m*/
    return type;
}

From source file:com.ibuildapp.romanblack.WebPlugin.WebPlugin.java

public void processResult(Intent data, int resultCode) {
    if (null == mUploadMessage)
        nullValueHandler();/*from w ww. ja va 2s .  c o m*/

    Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();

    String filePath = result.getPath();

    Uri fileUri = Uri.fromFile(new File(filePath));
    if (isMedia) {
        ContentResolver cR = WebPlugin.this.getContentResolver();
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        String type = mime.getExtensionFromMimeType(cR.getType(result));
        fileUri = Uri.parse(fileUri.toString() + "." + type);

        data.setData(fileUri);
        isMedia = false;
    }

    mUploadMessage.onReceiveValue(fileUri);
    mUploadMessage = null;
}

From source file:com.keylesspalace.tusky.activity.ComposeActivity.java

private void uploadMedia(final QueuedMedia item) {
    item.readyStage = QueuedMedia.ReadyStage.UPLOADING;

    final String mimeType = getContentResolver().getType(item.uri);
    MimeTypeMap map = MimeTypeMap.getSingleton();
    String fileExtension = map.getExtensionFromMimeType(mimeType);
    final String filename = String.format("%s_%s_%s.%s", getString(R.string.app_name),
            String.valueOf(new Date().getTime()), randomAlphanumericString(10), fileExtension);

    byte[] content = item.content;

    if (content == null) {
        InputStream stream;//  ww  w.jav a  2s .c  o m

        try {
            stream = getContentResolver().openInputStream(item.uri);
        } catch (FileNotFoundException e) {
            return;
        }

        content = inputStreamGetBytes(stream);
        IOUtils.closeQuietly(stream);

        if (content == null) {
            return;
        }
    }

    RequestBody requestFile = RequestBody.create(MediaType.parse(mimeType), content);
    MultipartBody.Part body = MultipartBody.Part.createFormData("file", filename, requestFile);

    item.uploadRequest = mastodonAPI.uploadMedia(body);

    item.uploadRequest.enqueue(new Callback<Media>() {
        @Override
        public void onResponse(Call<Media> call, retrofit2.Response<Media> response) {
            if (response.isSuccessful()) {
                item.id = response.body().id;
                waitForMediaLatch.countDown();
            } else {
                Log.d(TAG, "Upload request failed. " + response.message());
                onUploadFailure(item, call.isCanceled());
            }
        }

        @Override
        public void onFailure(Call<Media> call, Throwable t) {
            Log.d(TAG, t.getMessage());
            onUploadFailure(item, false);
        }
    });
}

From source file:com.fa.mastodon.activity.ComposeActivity.java

private void uploadMedia(final QueuedMedia item) {
    item.readyStage = QueuedMedia.ReadyStage.UPLOADING;

    final String mimeType = getContentResolver().getType(item.uri);
    MimeTypeMap map = MimeTypeMap.getSingleton();
    String fileExtension = map.getExtensionFromMimeType(mimeType);
    final String filename = String.format("%s_%s_%s.%s", getString(R.string.app_name),
            String.valueOf(new Date().getTime()), randomAlphanumericString(10), fileExtension);

    byte[] content = item.content;

    if (content == null) {
        InputStream stream;/*from   w  w  w  .jav  a  2  s  .  c  o  m*/

        try {
            stream = getContentResolver().openInputStream(item.uri);
        } catch (FileNotFoundException e) {
            return;
        }

        content = inputStreamGetBytes(stream);
        IOUtils.closeQuietly(stream);

        if (content == null) {
            return;
        }
    }

    RequestBody requestFile = RequestBody.create(MediaType.parse(mimeType), content);
    MultipartBody.Part body = MultipartBody.Part.createFormData("file", filename, requestFile);

    item.uploadRequest = mastodonAPI.uploadMedia(body);

    item.uploadRequest.enqueue(new Callback<Media>() {
        @Override
        public void onResponse(Call<Media> call, retrofit2.Response<Media> response) {
            if (response.isSuccessful()) {
                onUploadSuccess(item, response.body());
            } else {
                Log.d(TAG, "Upload request failed. " + response.message());
                onUploadFailure(item, call.isCanceled());
            }
        }

        @Override
        public void onFailure(Call<Media> call, Throwable t) {
            Log.d(TAG, t.getMessage());
            onUploadFailure(item, false);
        }
    });
}