Example usage for android.webkit MimeTypeMap getMimeTypeFromExtension

List of usage examples for android.webkit MimeTypeMap getMimeTypeFromExtension

Introduction

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

Prototype

@Nullable
public String getMimeTypeFromExtension(String extension) 

Source Link

Document

Return the MIME type for the given extension.

Usage

From source file:nya.miku.wishmaster.api.AbstractLynxChanModule.java

public String sendPost(SendPostModel model, ProgressListener listener, CancellableTask task) throws Exception {
    String url = getUsingUrl() + ".api/" + (model.threadNumber == null ? "newThread" : "replyThread");

    JSONObject jsonPayload = new JSONObject();
    JSONObject jsonParameters = new JSONObject();
    jsonPayload.put("captchaId", lastCaptchaId);
    jsonParameters.put("name", model.name);
    jsonParameters.put("password", model.password);
    jsonParameters.put("subject", model.subject);
    jsonParameters.put("message", model.comment);
    jsonParameters.put("boardUri", model.boardName);
    jsonParameters.put("email", model.sage ? "sage" : model.email);
    if (model.threadNumber != null)
        jsonParameters.put("threadId", model.threadNumber);
    if (model.captchaAnswer != null && model.captchaAnswer.length() > 0)
        jsonParameters.put("captcha", model.captchaAnswer);
    if (model.icon > 0)
        jsonParameters.put("flag", flagsMap.get(model.boardName).get(model.icon - 1));
    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
    if (model.attachments != null && model.attachments.length > 0) {
        JSONArray files = new JSONArray();
        for (int i = 0; i < model.attachments.length; ++i) {
            String ext = MimeTypeMap.getFileExtensionFromUrl(model.attachments[i].toURI().toString());
            String mime = mimeTypeMap.getMimeTypeFromExtension(ext);
            String md5 = checkFileIdentifier(model.attachments[i], mime, listener, task);
            JSONObject file = new JSONObject();
            file.put("name", model.attachments[i].getName());
            if (md5 != null) {
                file.put("md5", md5);
                file.put("mime", mime);
            } else {
                file.put("content", "data:" + mime + ";base64," + base64EncodeFile(model.attachments[i]));
            }/*w  ww  .j a  v  a  2 s . co m*/
            file.put("spoiler", model.custommark);
            files.put(file);
        }
        jsonParameters.put("files", files);
    }
    jsonPayload.put("parameters", jsonParameters);
    JSONEntry payload = new JSONEntry(jsonPayload);
    HttpRequestModel request = HttpRequestModel.builder().setPOST(payload).setNoRedirect(true).build();
    String response = HttpStreamer.getInstance().getStringFromUrl(url, request, httpClient, null, task, true);
    lastCaptchaId = null;
    JSONObject result = new JSONObject(response);
    String status = result.optString("status");
    if ("ok".equals(status)) {
        UrlPageModel urlPageModel = new UrlPageModel();
        urlPageModel.type = UrlPageModel.TYPE_THREADPAGE;
        urlPageModel.chanName = getChanName();
        urlPageModel.boardName = model.boardName;
        urlPageModel.threadNumber = model.threadNumber;
        if (model.threadNumber == null) {
            urlPageModel.threadNumber = Integer.toString(result.optInt("data"));
        } else {
            urlPageModel.postNumber = Integer.toString(result.optInt("data"));
        }
        return buildUrl(urlPageModel);
    } else if (status.contains("error") || status.contains("blank")) {
        String errorMessage = result.optString("data");
        if (errorMessage.length() > 0) {
            throw new Exception(errorMessage);
        }
    }
    throw new Exception("Unknown Error");
}

From source file:com.bitants.wally.activities.ImageDetailsActivity.java

private void setImageAsWallpaperPicker(Uri path) {
    Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
    intent.setType("image/*");

    MimeTypeMap map = MimeTypeMap.getSingleton();
    String mimeType = map.getMimeTypeFromExtension("png");
    intent.setDataAndType(path, mimeType);
    intent.putExtra("mimeType", mimeType);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    startActivity(Intent.createChooser(intent, getString(R.string.action_set_as)));
}

From source file:org.zywx.wbpalmstar.engine.universalex.EUExWidget.java

public void installApp(String[] parm) {
    if (parm.length < 1) {
        return;/* w  w w .ja va  2 s. c o  m*/
    }
    EBrowserWindow curWind = mBrwView.getBrowserWindow();
    if (null == curWind) {
        return;
    }
    String inAppPath = parm[0];
    if (null == inAppPath || 0 == inAppPath.trim().length()) {
        return;
    }
    inAppPath = BUtility.makeRealPath(inAppPath, mBrwView.getCurrentWidget().m_widgetPath,
            curWind.getWidgetType());
    if (inAppPath.contains("wgtRes")) {
        InputStream is;
        try {
            // String tPath = m_eContext.getCacheDir().getAbsolutePath() +
            // "/temp.apk";
            String tPath = Environment.getExternalStorageDirectory().getPath() + "/temp.apk";
            is = mContext.getAssets().open(inAppPath);
            File file = new File(tPath);
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            byte[] temp = new byte[8 * 1024];
            int i = 0;
            while ((i = is.read(temp)) > 0) {
                fos.write(temp, 0, i);
            }
            fos.close();
            is.close();
            inAppPath = tPath;
            // modify permission
            // String command = "chmod777" + " " + inAppPath;
            // Runtime.getRuntime().exec(command);
        } catch (IOException e) {
            Toast.makeText(mContext,
                    ResoureFinder.getInstance().getString(mContext, "error_sdcard_is_not_available"),
                    Toast.LENGTH_SHORT).show();
            return;
        }
    }
    // install apk.
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    MimeTypeMap type = MimeTypeMap.getSingleton();
    String mime = type.getMimeTypeFromExtension("apk");
    intent.setDataAndType(Uri.parse("file://" + inAppPath), mime);
    mContext.startActivity(intent);
}

From source file:net.sf.xfd.provider.ProviderBase.java

private void addNameCandidates(CharSequence filepath, ObjectSet<String> mimeCandidates) {
    // XXX suspect conversion
    final String filepathStr = filepath.toString();

    final String name = extractName(filepathStr);

    if (TextUtils.isEmpty(name)) {
        return;//from   w w  w  .java  2 s  .c o m
    }

    final int dot = name.lastIndexOf('.');

    if (dot == -1 || dot == name.length() - 1) {
        return;
    }

    final String extension = name.substring(dot + 1, name.length());

    mimeCandidates.add("application/x-" + extension);

    final MimeTypeMap map = MimeTypeMap.getSingleton();

    final String foundMime = map.getMimeTypeFromExtension(extension);

    if (!TextUtils.isEmpty(foundMime) && !DEFAULT_MIME.equals(foundMime)) {
        mimeCandidates.add(foundMime);
    }
}

From source file:org.zywx.wbpalmstar.engine.universalex.EUExWidget.java

public void openFile(String path) {
    if (null == path || path.trim().length() == 0) {
        return;//from w ww .  ja v a  2s  . co m
    }
    Intent in = new Intent(Intent.ACTION_VIEW);
    MimeTypeMap type = MimeTypeMap.getSingleton();
    String mime = MimeTypeMap.getFileExtensionFromUrl(path);
    mime = type.getMimeTypeFromExtension(mime);
    if (null != mime && mime.length() != 0) {
        File file = new File(path);
        Uri ri = Uri.fromFile(file);
        in.setDataAndType(ri, mime);
    }
    if (appExist(in)) {
        mContext.startActivity(Intent.createChooser(in, "choose one:"));
    } else {
        ;
    }
}

From source file:com.peppe130.fireinstaller.core.CustomFileChooser.java

boolean fileIsMimeType(File file, String mimeType, MimeTypeMap mimeTypeMap) {

    if (mimeType == null || mimeType.equals("*/*")) {

        return true;

    } else {/*from  www  . j  av  a  2s.c o  m*/

        String filename = file.toURI().toString();

        int dotPos = filename.lastIndexOf('.');

        if (dotPos == -1) {

            return false;

        }

        String fileExtension = filename.substring(dotPos + 1);

        String fileType = mimeTypeMap.getMimeTypeFromExtension(fileExtension);

        if (fileType == null) {

            return false;

        }

        if (fileType.equals(mimeType)) {

            return true;

        }

        int mimeTypeDelimiter = mimeType.lastIndexOf('/');

        if (mimeTypeDelimiter == -1) {

            return false;

        }

        String mimeTypeMainType = mimeType.substring(0, mimeTypeDelimiter);

        String mimeTypeSubtype = mimeType.substring(mimeTypeDelimiter + 1);

        if (!mimeTypeSubtype.equals("*")) {

            return false;

        }

        int fileTypeDelimiter = fileType.lastIndexOf('/');

        if (fileTypeDelimiter == -1) {

            return false;

        }

        String fileTypeMainType = fileType.substring(0, fileTypeDelimiter);

        if (fileTypeMainType.equals(mimeTypeMainType)) {

            return true;

        }

    }

    return false;

}

From source file:net.sf.xfd.provider.ProviderBase.java

public String getTypeFast(@CanonPath String path, String name, Stat stat) throws FileNotFoundException {
    if ("/".equals(path)) {
        return MIME_TYPE_DIR;
    }//from  w  w w . j  av  a  2 s  .  c o m

    final OS os = getOS();
    if (os == null) {
        return DEFAULT_MIME;
    }

    try {
        @Fd
        int fd = Fd.NIL;

        @DirFd
        int parentFd = os.opendir(extractParent(path));
        try {
            int flags = 0;

            if (!os.faccessat(parentFd, name, OS.F_OK)) {
                flags = OS.AT_SYMLINK_NOFOLLOW;
            }

            os.fstatat(parentFd, name, stat, flags);

            if (stat.type == null) {
                return DEFAULT_MIME;
            }

            switch (stat.type) {
            case LINK:
                return LINK_MIME;
            case DIRECTORY:
                return MIME_TYPE_DIR;
            case CHAR_DEV:
                return CHAR_DEV_MIME;
            default:
            }

            final String extension = getExtensionFast(name);

            final MimeTypeMap mimeMap = MimeTypeMap.getSingleton();

            final String foundMime = mimeMap.getMimeTypeFromExtension(extension);
            if (foundMime != null) {
                return foundMime;
            }

            final boolean canSniffContent = stat.type == FsType.FILE
                    && (stat.st_size != 0 || isPossiblySpecial(stat));

            if (flags == 0) {
                os.fstatat(parentFd, name, stat, OS.AT_SYMLINK_NOFOLLOW);

                if (stat.type == FsType.LINK) {
                    CharSequence resolved = null;

                    if (canSniffContent) {
                        try {
                            fd = os.openat(parentFd, name, OS.O_RDONLY, 0);

                            resolved = os.readlinkat(DirFd.NIL, fdPath(fd));
                        } catch (IOException ioe) {
                            LogUtil.logCautiously("Unable to open target of " + name, ioe);
                        }
                    }

                    if (resolved == null) {
                        resolved = os.readlinkat(parentFd, name);

                        if (resolved.charAt(0) == '/') {
                            resolved = canonString(resolved);
                        }
                    }

                    final String linkTargetExtension = getExtensionFromPath(resolved);

                    if (linkTargetExtension != null && !linkTargetExtension.equals(extension)) {
                        final String sortaFastMime = mimeMap.getMimeTypeFromExtension(linkTargetExtension);
                        if (sortaFastMime != null) {
                            return sortaFastMime;
                        }
                    }
                }
            }

            if (canSniffContent) {
                if (fd < 0) {
                    fd = os.openat(parentFd, name, OS.O_RDONLY, 0);
                }

                final String contentInfo = magic.guessMime(fd);

                if (contentInfo != null) {
                    return contentInfo;
                }
            }

            switch (stat.type) {
            case LINK:
                return LINK_MIME;
            case DOMAIN_SOCKET:
                return SOCK_MIME;
            case NAMED_PIPE:
                return FIFO_MIME;
            case FILE:
                if (stat.st_size == 0) {
                    return EMPTY_MIME;
                }
            default:
                return DEFAULT_MIME;
            }
        } finally {
            if (fd > 0) {
                os.dispose(fd);
            }

            os.dispose(parentFd);
        }
    } catch (IOException e) {
        LogUtil.logCautiously("Encountered IO error during mime sniffing", e);

        throw new FileNotFoundException("Failed to stat " + name);
    }
}

From source file:org.mozilla.gecko.GeckoAppShell.java

static String getMimeTypeFromExtensions(String aFileExt) {
    MimeTypeMap mtm = MimeTypeMap.getSingleton();
    StringTokenizer st = new StringTokenizer(aFileExt, "., ");
    String type = null;/*from   w w  w  .  j  av a 2 s  . com*/
    String subType = null;
    while (st.hasMoreElements()) {
        String ext = st.nextToken();
        String mt = mtm.getMimeTypeFromExtension(ext);
        if (mt == null)
            continue;
        int slash = mt.indexOf('/');
        String tmpType = mt.substring(0, slash);
        if (!tmpType.equalsIgnoreCase(type))
            type = type == null ? tmpType : "*";
        String tmpSubType = mt.substring(slash + 1);
        if (!tmpSubType.equalsIgnoreCase(subType))
            subType = subType == null ? tmpSubType : "*";
    }
    if (type == null)
        type = "*";
    if (subType == null)
        subType = "*";
    return type + "/" + subType;
}

From source file:net.sf.xfd.provider.ProviderBase.java

@NonNull
public String getTypeFastest(int dirFd, CharSequence name, Stat stat) {
    if (stat.type != null) {
        switch (stat.type) {
        case DIRECTORY:
            return MIME_TYPE_DIR;
        case CHAR_DEV:
            return CHAR_DEV_MIME;
        }//w  w w.ja v a 2  s.  c  o  m
    }

    final OS os = getOS();
    if (os == null) {
        return DEFAULT_MIME;
    }

    // Do we have an option to open the file? Does it even make sense?
    // It is a bad idea to open sockets, special files and, especially, pipes
    // (this can cause block, take some time or have other unwelcome side-effects).
    // Trying to content-sniff ordinary zero-sized files also does not make sense
    // Unless they are on some special filesystem (such as procfs), that incorrectly
    // reports zero sizes to stat().

    boolean canSniffContent = stat.type == FsType.FILE;

    int fd = Fd.NIL;

    try {
        final boolean isLink = stat.type == FsType.LINK;

        if (isLink) {
            // we must exclude the possibility that this is a symlink to directory

            if (!os.faccessat(dirFd, name, OS.F_OK)) {
                // the link is broken or target is inaccessible, bail
                return LINK_MIME;
            }

            try {
                os.fstatat(dirFd, name, stat, 0);

                switch (stat.type) {
                case DIRECTORY:
                    return MIME_TYPE_DIR;
                case CHAR_DEV:
                    return CHAR_DEV_MIME;
                }
            } catch (IOException ioe) {
                LogUtil.logCautiously("Unable to stat target of " + name, ioe);
            }
        } else {
            try {
                if (canSniffContent) {
                    fd = os.openat(dirFd, name, OS.O_RDONLY, 0);

                    os.fstat(fd, stat);
                } else {
                    os.fstatat(dirFd, name, stat, 0);
                }
            } catch (IOException ioe) {
                LogUtil.logCautiously("Unable to directly stat " + name, ioe);
            }
        }

        final String extension = getExtensionFast(name);

        final MimeTypeMap mimeMap = MimeTypeMap.getSingleton();

        final String foundMime = mimeMap.getMimeTypeFromExtension(extension);
        if (foundMime != null) {
            return foundMime;
        }

        canSniffContent = canSniffContent && (stat.st_size != 0 || isPossiblySpecial(stat));

        if (isLink) {
            // check if link target has a usable extension
            CharSequence resolved = null;

            // Some filesystem (procfs, you!!) do export files as symlinks, but don't allow them
            // to be open via these symlinks. Gotta be careful here.
            if (canSniffContent) {
                try {
                    fd = os.openat(dirFd, name, OS.O_RDONLY, 0);

                    resolved = os.readlinkat(DirFd.NIL, fdPath(fd));
                } catch (IOException ioe) {
                    LogUtil.logCautiously("Unable to open target of " + name, ioe);
                }
            }

            if (resolved == null) {
                try {
                    resolved = os.readlinkat(dirFd, name);

                    if (resolved.charAt(0) == '/') {
                        resolved = canonString(resolved);
                    }
                } catch (IOException linkErr) {
                    return LINK_MIME;
                }
            }

            final String linkTargetExtension = getExtensionFromPath(resolved);

            if (linkTargetExtension != null && !linkTargetExtension.equals(extension)) {
                final String sortaFastMime = mimeMap.getMimeTypeFromExtension(linkTargetExtension);
                if (sortaFastMime != null) {
                    return sortaFastMime;
                }
            }

            // let's try to open by resolved name too, see above
            name = resolved;
        }

        if (canSniffContent) {
            if (fd < 0) {
                fd = os.openat(dirFd, name, OS.O_RDONLY, 0);
            }

            final String contentInfo = magic.guessMime(fd);

            if (contentInfo != null) {
                return contentInfo;
            }
        }
    } catch (IOException ioe) {
        LogUtil.logCautiously("Failed to guess type of " + name, ioe);
    } finally {
        if (fd > 0) {
            os.dispose(fd);
        }
    }

    if (stat.type == null) {
        return DEFAULT_MIME;
    }

    switch (stat.type) {
    case LINK:
        return LINK_MIME;
    case DOMAIN_SOCKET:
        return SOCK_MIME;
    case NAMED_PIPE:
        return FIFO_MIME;
    case FILE:
        if (stat.st_size == 0) {
            return EMPTY_MIME;
        }
    default:
        return DEFAULT_MIME;
    }
}