Example usage for android.webkit MimeTypeMap getSingleton

List of usage examples for android.webkit MimeTypeMap getSingleton

Introduction

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

Prototype

public static MimeTypeMap getSingleton() 

Source Link

Document

Get the singleton instance of MimeTypeMap.

Usage

From source file:com.owncloud.android.utils.BitmapUtils.java

/**
 * Checks if file passed is an image// ww w  . j a  v  a 2s .c  o m
 * @param file
 * @return true/false
 */
public static boolean isImage(File file) {
    final Uri selectedUri = Uri.fromFile(file);
    final String fileExtension = MimeTypeMap.getFileExtensionFromUrl(selectedUri.toString().toLowerCase());
    final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);

    return (mimeType != null && mimeType.startsWith("image/"));
}

From source file:bg.fourweb.android.rss.RssHandler.java

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
        throws SAXException {
    super.startElement(uri, localName, qName, attributes);
    checkStopCondition();/*w w  w .  j a v  a2s.  co m*/

    boolean createValueB = false;

    currentElt = elements.containsKey(localName) ? elements.get(localName) : ELT_INVALID;
    // @formatter:off
    switch (currentElt) {
    // case ELT_CHANNEL: inChannel = true; break;
    case ELT_ITEM:
        inItems = true;
        currentItemB = new ItemBuilder();
        break;
    case ELT_IMAGE:
        inImage = true;
        break; // channel
    // ---
    // tags that contain value only
    case ELT_TITLE: // channel & image & item
    case ELT_LINK: // channel & image & item
    case ELT_DESCRIPTION: // channel & item
    case ELT_LANGUAGE: // channel
    case ELT_COPYRIGHT: // channel
    case ELT_MANAGINGEDITOR: // channel
    case ELT_WEBMASTER: // channel
    case ELT_PUBDATE: // channel & item
    case ELT_LASTBUILDDATE: // channel
    case ELT_GENERATOR: // channel
    case ELT_DOCS: // channel
    case ELT_CLOUD: // channel
    case ELT_TTL: // channel
    case ELT_IMAGE_URL: // image
    case ELT_IMAGE_WIDTH: // image
    case ELT_IMAGE_HEIGHT: // image
    case ELT_RATING: // channel
    case ELT_SKIPHOURS: // channel
    case ELT_SKIPDAYS: // channel
    case ELT_AUTHOR: // item
    case ELT_COMMENTS: // item
        createValueB = true;
        break;
    // ---
    // tags that contain both values and attributes
    case ELT_CATEGORY:
        categoryDomain = attributes.getValue("domain");
        createValueB = true;
        break; // channel & item
    case ELT_GUID:
        currentItemB.guidIsPermaLink(attributes.getValue("isPermaLink"));
        createValueB = true;
        break; // item
    case ELT_SOURCE:
        currentItemB.sourceUrl(attributes.getValue("url"));
        createValueB = true;
        break; // item    
    // ---
    // tags that contain attributes only
    case ELT_ENCLOSURE: {// item
        final String url = attributes.getValue("url");
        int length;
        try {
            length = Integer.parseInt(attributes.getValue("length"));
        } catch (NumberFormatException e) {
            length = 0;
        }
        final String mimeType = attributes.getValue("type");
        currentItemB.addEnclosureUrl(url, length, mimeType);
        break;
    }
    case ELT_THUMBNAIL: {
        final String url = attributes.getValue("url");
        final String mimeType = StringUtils.isEmpty(url) ? ""
                : MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
        int width;
        try {
            width = Integer.parseInt(attributes.getValue("width"));
        } catch (NumberFormatException e) {
            width = 0;
        }
        int height;
        try {
            height = Integer.parseInt(attributes.getValue("height"));
        } catch (NumberFormatException e) {
            height = 0;
        }
        final Thumbnail t = new Thumbnail(url, mimeType, width, height);
        if (largestThumbnail == null || largestThumbnail.compareTo(t) < 0) {
            largestThumbnail = t;
        }
    }
    }

    // @formatter:on
    if (createValueB) {
        valueB = new StringBuilder(63);
    }
}

From source file:com.osama.cryptofm.tasks.DecryptTask.java

@Override
protected void onPostExecute(String s) {
    SharedData.CURRENT_RUNNING_OPERATIONS.clear();

    if (singleFileMode) {
        if (s.equals(DECRYPTION_SUCCESS_MESSAGE)) {
            singleModeDialog.dismiss();//from  w  w  w.j  a  v  a2  s.c o m
            Log.d(TAG, "onPostExecute: destination filename is: " + destFilename);
            //open file
            String mimeType = MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(FileUtils.getExtension(destFilename));

            Intent intent = new Intent();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

                Uri uri = null;
                try {
                    uri = FileProvider.getUriForFile(mContext,
                            mContext.getApplicationContext().getPackageName() + ".provider",
                            TasksFileUtils.getFile(destFilename));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                intent.setDataAndType(uri, mimeType);
            } else {
                try {
                    intent.setDataAndType(Uri.fromFile(TasksFileUtils.getFile(destFilename)), mimeType);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            intent.setAction(Intent.ACTION_VIEW);
            Intent x = Intent.createChooser(intent, "Open with: ");
            mContext.startActivity(x);
        } else {
            singleModeDialog.dismiss();
            Toast.makeText(mContext, s, Toast.LENGTH_LONG).show();
        }
    } else {
        mProgressDialog.dismiss("Decryption completed");
        SharedData.CURRENT_RUNNING_OPERATIONS.clear();
        Toast.makeText(mContext, s, Toast.LENGTH_LONG).show();
        UiUtils.reloadData(mContext, mAdapter);
    }

}

From source file:com.osama.cryptofm.filemanager.listview.FileSelectionManagement.java

void openFile(final String filename) {
    if (SharedData.IS_IN_COPY_MODE) {
        return;/*from  w  w  w .j  a  v a  2 s . c o  m*/
    }
    if (FileUtils.getExtension(filename).equals("pgp")) {
        Log.d(TAG, "openFile: File name is: " + filename);
        if (SharedData.KEY_PASSWORD == null) {
            final Dialog dialog = new Dialog(mContext);
            dialog.setCancelable(false);
            dialog.setContentView(R.layout.password_dialog_layout);
            dialog.show();
            dialog.findViewById(R.id.cancel_decrypt_button).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismiss();
                }
            });
            final EditText editText = (EditText) dialog.findViewById(R.id.key_password);
            dialog.findViewById(R.id.decrypt_file_button).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (editText.getText().length() < 1) {
                        editText.setError("please give me your encryption password");
                        return;
                    } else {
                        SharedData.KEY_PASSWORD = editText.getText().toString();
                        dialog.dismiss();
                        new DecryptTask(mContext, mFileListAdapter, SharedData.DB_PASSWWORD,
                                SharedData.USERNAME, FileUtils.CURRENT_PATH + filename, SharedData.KEY_PASSWORD)
                                        .execute();
                    }

                }
            });
        } else {
            new DecryptTask(mContext, mFileListAdapter, SharedData.DB_PASSWWORD, SharedData.USERNAME,
                    FileUtils.CURRENT_PATH + filename, SharedData.KEY_PASSWORD).execute();
        }

    } else {
        //open file
        if (SharedData.EXTERNAL_SDCARD_ROOT_PATH != null
                && FileUtils.CURRENT_PATH.contains(SharedData.EXTERNAL_SDCARD_ROOT_PATH)) {
            //open the document file
            DocumentFile file = FileDocumentUtils.getDocumentFile(FileUtils.getFile(filename));
            Intent intent = new Intent();
            intent.setDataAndType(file.getUri(), file.getType());
            intent.setAction(Intent.ACTION_VIEW);
            Intent x = Intent.createChooser(intent, "Open with");
            mContext.startActivity(x);
            return;
        }
        String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(FileUtils.getExtension(filename));

        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            Uri uri = FileProvider.getUriForFile(mContext,
                    mContext.getApplicationContext().getPackageName() + ".provider",
                    FileUtils.getFile(filename));
            intent.setDataAndType(uri, mimeType);
        } else {
            intent.setDataAndType(Uri.fromFile(FileUtils.getFile(filename)), mimeType);
        }
        intent.setAction(Intent.ACTION_VIEW);
        Intent x = Intent.createChooser(intent, "Open with: ");
        mContext.startActivity(x);
    }
}

From source file:com.laurencedawson.image_management.ImageManager.java

/**
 * Given an image URL, check if the cached image is a GIF
 * @param url The URL of the image/*from ww w  .  j ava  2  s.c o  m*/
 * @return True if the image is a GIF
 */
public boolean isGif(String url) {
    if (url == null) {
        return false;
    }

    // First try to grab the mime from the options
    Options options = new Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(getFullCacheFileName(mContext, url), options);
    if (options.outMimeType != null && options.outMimeType.equals(ImageManager.GIF_MIME)) {
        return true;
    }

    // Next, try to grab the mime type from the url
    final String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    if (extension != null) {
        String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        if (mimeType != null) {
            return mimeType.equals(ImageManager.GIF_MIME);
        }
    }

    return false;
}

From source file:android.webkit.cts.CtsTestServer.java

/**
 * Create and start a local HTTP server instance.
 * @param context The application context to use for fetching assets.
 * @param sslMode Whether to use SSL, and if so, what client auth (if any) to use.
 * @param trustManager the trustManager//from ww  w  .ja  v a  2  s . c o m
 * @throws Exception
 */
public CtsTestServer(Context context, SslMode sslMode, X509TrustManager trustManager) throws Exception {
    mContext = context;
    mAssets = mContext.getAssets();
    mResources = mContext.getResources();
    mSsl = sslMode;
    mRequestEntities = new ArrayList<HttpEntity>();
    mMap = MimeTypeMap.getSingleton();
    mQueries = new Vector<String>();
    mTrustManager = trustManager;
    mServerThread = new ServerThread(this, mSsl);
    if (mSsl == SslMode.INSECURE) {
        mServerUri = "http:";
    } else {
        mServerUri = "https:";
    }
    mServerUri += "//localhost:" + mServerThread.mSocket.getLocalPort();
    mServerThread.start();
}

From source file:com.phonegap.FileUtils.java

/**
 * Read content of text file and return as base64 encoded data url.
 * /*from   w  w w  .  j  ava 2  s.  c  o  m*/
 * @param filename         The name of the file.
 * @return               Contents of file = data:<media type>;base64,<data>
 * @throws FileNotFoundException, IOException
 */
public String readAsDataURL(String filename) throws FileNotFoundException, IOException {
    byte[] bytes = new byte[1000];
    BufferedInputStream bis = new BufferedInputStream(getPathFromUri(filename), 1024);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    int numRead = 0;
    while ((numRead = bis.read(bytes, 0, 1000)) >= 0) {
        bos.write(bytes, 0, numRead);
    }

    // Determine content type from file name
    String contentType = null;
    if (filename.startsWith("content:")) {
        Uri fileUri = Uri.parse(filename);
        contentType = this.ctx.getContentResolver().getType(fileUri);
    } else {
        MimeTypeMap map = MimeTypeMap.getSingleton();
        contentType = map.getMimeTypeFromExtension(map.getFileExtensionFromUrl(filename));
    }

    byte[] base64 = Base64.encodeBase64(bos.toByteArray());
    String data = "data:" + contentType + ";base64," + new String(base64);
    return data;
}

From source file:com.radicaldynamic.groupinform.tasks.DownloadFormsTask.java

@Override
protected HashMap<String, String> doInBackground(ArrayList<FormDetails>... values) {
    ArrayList<FormDetails> toDownload = values[0];

    int total = toDownload.size();
    int count = 1;

    HashMap<String, String> result = new HashMap<String, String>();

    for (int i = 0; i < total; i++) {
        FormDetails fd = toDownload.get(i);
        publishProgress(fd.formName, Integer.valueOf(count).toString(), Integer.valueOf(total).toString());

        String message = "";

        try {//from   www .  ja v a2  s .c  o  m
            // get the xml file
            // if we've downloaded a duplicate, this gives us the file
            File dl = downloadXform(fd.formName, fd.downloadUrl);

            // BEGIN custom
            //                String[] projection = {
            //                        FormsColumns._ID, FormsColumns.FORM_FILE_PATH
            //                };
            //                String[] selectionArgs = {
            //                    dl.getAbsolutePath()
            //                };
            //                String selection = FormsColumns.FORM_FILE_PATH + "=?";
            //                Cursor alreadyExists =
            //                    Collect.getInstance()
            //                            .getContentResolver()
            //                            .query(FormsColumns.CONTENT_URI, projection, selection, selectionArgs,
            //                                null);
            //
            //                Uri uri = null;
            //                if (alreadyExists.getCount() <= 0) {
            //                    // doesn't exist, so insert it
            //                    ContentValues v = new ContentValues();
            //                    v.put(FormsColumns.FORM_FILE_PATH, dl.getAbsolutePath());
            //
            //                    HashMap<String, String> formInfo = FileUtils.parseXML(dl);
            //                    v.put(FormsColumns.DISPLAY_NAME, formInfo.get(FileUtils.TITLE));
            //                    v.put(FormsColumns.MODEL_VERSION, formInfo.get(FileUtils.MODEL));
            //                    v.put(FormsColumns.UI_VERSION, formInfo.get(FileUtils.UI));
            //                    v.put(FormsColumns.JR_FORM_ID, formInfo.get(FileUtils.FORMID));
            //                    v.put(FormsColumns.SUBMISSION_URI, formInfo.get(FileUtils.SUBMISSIONURI));
            //                    uri =
            //                        Collect.getInstance().getContentResolver()
            //                                .insert(FormsColumns.CONTENT_URI, v);
            //                } else {
            //                    alreadyExists.moveToFirst();
            //                    uri =
            //                        Uri.withAppendedPath(FormsColumns.CONTENT_URI,
            //                            alreadyExists.getString(alreadyExists.getColumnIndex(FormsColumns._ID)));
            //                }
            // END custom

            if (fd.manifestUrl != null) {
                // BEGIN custom
                //                    Cursor c =
                //                        Collect.getInstance().getContentResolver()
                //                                .query(uri, null, null, null, null);
                //                    if (c.getCount() > 0) {
                //                        // should be exactly 1
                //                        c.moveToFirst();
                //
                //                        String error =
                //                            downloadManifestAndMediaFiles(
                //                                c.getString(c.getColumnIndex(FormsColumns.FORM_MEDIA_PATH)), fd,
                //                                count, total);
                //                        if (error != null) {
                //                            message += error;
                //                        }
                //                    }
                String error = downloadManifestAndMediaFiles(dl.getParent(), fd, count, total);

                if (error != null) {
                    message += error;
                }
                // END custom
            } else {
                // TODO: manifest was null?
                Log.e(t, "Manifest was null.  PANIC");
            }

            // BEGIN custom
            HashMap<String, String> formInfo = FileUtils.parseXML(dl);

            // Create form document and add attachments; commit to database
            FormDefinition fDoc = new FormDefinition();
            fDoc.setName(formInfo.get(FileUtils.TITLE));
            fDoc.setModelVersion(formInfo.get(FileUtils.MODEL));
            fDoc.setUiVersion(formInfo.get(FileUtils.UI));
            fDoc.setJavaRosaId(formInfo.get(FileUtils.FORMID));
            fDoc.setSubmissionUri(formInfo.get(FileUtils.SUBMISSIONURI));
            fDoc.setStatus(FormDefinition.Status.active);
            fDoc.setXmlHash(FileUtils.getMd5Hash(dl));
            Collect.getInstance().getDbService().getDb().create(fDoc);

            String revision = fDoc.getRevision();

            for (File f : dl.getParentFile().listFiles()) {
                String fileName = f.getName();
                String attachmentName = fileName;

                if (Collect.Log.VERBOSE)
                    Log.v(Collect.LOGTAG, t + ": attaching " + fileName + " to " + fDoc.getId());

                if (fileName.equals(dl.getName()))
                    attachmentName = "xml";

                String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
                String contentType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);

                FileInputStream fis = new FileInputStream(f);
                AttachmentInputStream ais = new AttachmentInputStream(attachmentName, fis, contentType,
                        f.length());
                revision = Collect.getInstance().getDbService().getDb().createAttachment(fDoc.getId(), revision,
                        ais);
                fis.close();
            }

            // Remove temporary download directory
            FileUtilsExtended.deleteFolder(dl.getParent());
            // END custom
        } catch (SocketTimeoutException se) {
            se.printStackTrace();
            message += se.getMessage();
            // BEGIN custom
        } catch (DuplicateXFormFile e) {
            message = " SKIPPED (duplicate)";
            // END custom
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getCause() != null) {
                message += e.getCause().getMessage();
            } else {
                message += e.getMessage();
            }
        }
        count++;
        if (message.equalsIgnoreCase("")) {
            message = Collect.getInstance().getString(R.string.success);
        }
        result.put(fd.formName, message);
    }

    return result;
}

From source file:com.github.chenxiaolong.dualbootpatcher.pathchooser.PathChooserDialog.java

@Nullable
private static File[] listFilesWithFilter(@NonNull File directory, @Nullable String mimeType,
        @NonNull Comparator<File> comparator) {
    File[] contents = directory.listFiles();
    ArrayList<File> results = new ArrayList<>();

    if (contents != null) {
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        for (File file : contents) {
            if (file.isDirectory() || isMimeType(file, mimeType, mimeTypeMap)) {
                results.add(file);/*  www  . j  av  a  2s .  co  m*/
            }
        }

        Collections.sort(results, comparator);
        return results.toArray(new File[results.size()]);
    }

    return null;
}

From source file:org.alfresco.mobile.android.application.fragments.fileexplorer.LibraryFragment.java

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    mediaTypeId = (Integer) getArguments().get(ARGUMENT_MEDIATYPE_ID);

    // String selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "=?";
    StringBuilder selection = new StringBuilder(MediaStore.Files.FileColumns.MEDIA_TYPE + "=?");
    String selectionFinal = selection.toString();
    List<String> argumentsList = new ArrayList<String>();
    argumentsList.add(Integer.toString(mediaTypeId));
    if (mediaTypeId == 0) {
        String mimeType = null;/*from   w ww  .j  a v  a2 s  .co m*/
        selection.append(" AND " + MediaStore.Files.FileColumns.MIME_TYPE + " IN (");
        for (String extension : OFFICE_EXTENSION) {
            mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            argumentsList.add(mimeType);
            selection.append(" ? ,");
        }
        selectionFinal = selection.toString().substring(0, selection.lastIndexOf(",")) + ")";
    }
    String[] arguments = new String[argumentsList.size()];
    arguments = argumentsList.toArray(arguments);

    setListShown(false);
    String[] projection = new String[] { MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.TITLE,
            MediaStore.Files.FileColumns.DISPLAY_NAME, MediaStore.Files.FileColumns.MIME_TYPE,
            MediaStore.Files.FileColumns.DATA };
    Uri baseUri = MediaStore.Files.getContentUri("external");
    return new CursorLoader(getActivity(), baseUri, projection, selectionFinal, arguments,
            MediaStore.Files.FileColumns.DATA + " ASC");
}