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:android.webkit.cts.CtsTestServer.java

/**
 * Generate a response to the given request.
 * @throws InterruptedException// w ww.j a  v  a2  s . c  o  m
 * @throws IOException
 */
private HttpResponse getResponse(HttpRequest request) throws Exception {
    RequestLine requestLine = request.getRequestLine();
    HttpResponse response = null;
    String uriString = requestLine.getUri();
    Log.i(TAG, requestLine.getMethod() + ": " + uriString);

    synchronized (this) {
        mQueries.add(uriString);
        mLastRequestMap.put(uriString, request);
        if (request instanceof HttpEntityEnclosingRequest) {
            mRequestEntities.add(((HttpEntityEnclosingRequest) request).getEntity());
        }
    }

    if (requestLine.getMethod().equals("POST")) {
        HttpResponse responseOnPost = onPost(request);
        if (responseOnPost != null) {
            return responseOnPost;
        }
    }

    URI uri = URI.create(uriString);
    String path = uri.getPath();
    String query = uri.getQuery();
    if (path.equals(FAVICON_PATH)) {
        path = FAVICON_ASSET_PATH;
    }
    if (path.startsWith(DELAY_PREFIX)) {
        String delayPath = path.substring(DELAY_PREFIX.length() + 1);
        String delay = delayPath.substring(0, delayPath.indexOf('/'));
        path = delayPath.substring(delay.length());
        try {
            Thread.sleep(Integer.valueOf(delay));
        } catch (InterruptedException ignored) {
            // ignore
        }
    }
    if (path.startsWith(AUTH_PREFIX)) {
        // authentication required
        Header[] auth = request.getHeaders("Authorization");
        if ((auth.length > 0 && auth[0].getValue().equals(AUTH_CREDENTIALS))
                // This is a hack to make sure that loads to this url's will always
                // ask for authentication. This is what the test expects.
                && !path.endsWith("embedded_image.html")) {
            // fall through and serve content
            path = path.substring(AUTH_PREFIX.length());
        } else {
            // request authorization
            response = createResponse(HttpStatus.SC_UNAUTHORIZED);
            response.addHeader("WWW-Authenticate", "Basic realm=\"" + AUTH_REALM + "\"");
        }
    }
    if (path.startsWith(BINARY_PREFIX)) {
        List<NameValuePair> args = URLEncodedUtils.parse(uri, "UTF-8");
        int length = 0;
        String mimeType = null;
        try {
            for (NameValuePair pair : args) {
                String name = pair.getName();
                if (name.equals("type")) {
                    mimeType = pair.getValue();
                } else if (name.equals("length")) {
                    length = Integer.parseInt(pair.getValue());
                }
            }
            if (length > 0 && mimeType != null) {
                ByteArrayEntity entity = new ByteArrayEntity(new byte[length]);
                entity.setContentType(mimeType);
                response = createResponse(HttpStatus.SC_OK);
                response.setEntity(entity);
                response.addHeader("Content-Disposition", "attachment; filename=test.bin");
                response.addHeader("Content-Type", mimeType);
                response.addHeader("Content-Length", "" + length);
            } else {
                // fall through, return 404 at the end
            }
        } catch (Exception e) {
            // fall through, return 404 at the end
            Log.w(TAG, e);
        }
    } else if (path.startsWith(ASSET_PREFIX)) {
        path = path.substring(ASSET_PREFIX.length());
        // request for an asset file
        try {
            InputStream in;
            if (path.startsWith(RAW_PREFIX)) {
                String resourceName = path.substring(RAW_PREFIX.length());
                int id = mResources.getIdentifier(resourceName, "raw", mContext.getPackageName());
                if (id == 0) {
                    Log.w(TAG, "Can't find raw resource " + resourceName);
                    throw new IOException();
                }
                in = mResources.openRawResource(id);
            } else {
                in = mAssets.open(path);
            }
            response = createResponse(HttpStatus.SC_OK);
            InputStreamEntity entity = new InputStreamEntity(in, in.available());
            String mimeType = mMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(path));
            if (mimeType == null) {
                mimeType = "text/html";
            }
            entity.setContentType(mimeType);
            response.setEntity(entity);
            if (query == null || !query.contains(NOLENGTH_POSTFIX)) {
                response.setHeader("Content-Length", "" + entity.getContentLength());
            }
        } catch (IOException e) {
            response = null;
            // fall through, return 404 at the end
        }
    } else if (path.startsWith(REDIRECT_PREFIX)) {
        response = createResponse(HttpStatus.SC_MOVED_TEMPORARILY);
        String location = getBaseUri() + path.substring(REDIRECT_PREFIX.length());
        Log.i(TAG, "Redirecting to: " + location);
        response.addHeader("Location", location);
    } else if (path.equals(QUERY_REDIRECT_PATH)) {
        String location = Uri.parse(uriString).getQueryParameter("dest");
        if (location != null) {
            Log.i(TAG, "Redirecting to: " + location);
            response = createResponse(HttpStatus.SC_MOVED_TEMPORARILY);
            response.addHeader("Location", location);
        }
    } else if (path.startsWith(COOKIE_PREFIX)) {
        /*
         * Return a page with a title containing a list of all incoming cookies,
         * separated by '|' characters. If a numeric 'count' value is passed in a cookie,
         * return a cookie with the value incremented by 1. Otherwise, return a cookie
         * setting 'count' to 0.
         */
        response = createResponse(HttpStatus.SC_OK);
        Header[] cookies = request.getHeaders("Cookie");
        Pattern p = Pattern.compile("count=(\\d+)");
        StringBuilder cookieString = new StringBuilder(100);
        cookieString.append(cookies.length);
        int count = 0;
        for (Header cookie : cookies) {
            cookieString.append("|");
            String value = cookie.getValue();
            cookieString.append(value);
            Matcher m = p.matcher(value);
            if (m.find()) {
                count = Integer.parseInt(m.group(1)) + 1;
            }
        }

        response.addHeader("Set-Cookie", "count=" + count + "; path=" + COOKIE_PREFIX);
        response.setEntity(createPage(cookieString.toString(), cookieString.toString()));
    } else if (path.startsWith(SET_COOKIE_PREFIX)) {
        response = createResponse(HttpStatus.SC_OK);
        Uri parsedUri = Uri.parse(uriString);
        String key = parsedUri.getQueryParameter("key");
        String value = parsedUri.getQueryParameter("value");
        String cookie = key + "=" + value;
        response.addHeader("Set-Cookie", cookie);
        response.setEntity(createPage(cookie, cookie));
    } else if (path.startsWith(LINKED_SCRIPT_PREFIX)) {
        response = createResponse(HttpStatus.SC_OK);
        String src = Uri.parse(uriString).getQueryParameter("url");
        String scriptTag = "<script src=\"" + src + "\"></script>";
        response.setEntity(createPage("LinkedScript", scriptTag));
    } else if (path.equals(USERAGENT_PATH)) {
        response = createResponse(HttpStatus.SC_OK);
        Header agentHeader = request.getFirstHeader("User-Agent");
        String agent = "";
        if (agentHeader != null) {
            agent = agentHeader.getValue();
        }
        response.setEntity(createPage(agent, agent));
    } else if (path.equals(TEST_DOWNLOAD_PATH)) {
        response = createTestDownloadResponse(Uri.parse(uriString));
    } else if (path.equals(SHUTDOWN_PREFIX)) {
        response = createResponse(HttpStatus.SC_OK);
        // We cannot close the socket here, because we need to respond.
        // Status must be set to OK, or else the test will fail due to
        // a RunTimeException.
    } else if (path.equals(APPCACHE_PATH)) {
        response = createResponse(HttpStatus.SC_OK);
        response.setEntity(createEntity("<!DOCTYPE HTML>" + "<html manifest=\"appcache.manifest\">" + "  <head>"
                + "    <title>Waiting</title>" + "    <script>"
                + "      function updateTitle(x) { document.title = x; }"
                + "      window.applicationCache.onnoupdate = "
                + "          function() { updateTitle(\"onnoupdate Callback\"); };"
                + "      window.applicationCache.oncached = "
                + "          function() { updateTitle(\"oncached Callback\"); };"
                + "      window.applicationCache.onupdateready = "
                + "          function() { updateTitle(\"onupdateready Callback\"); };"
                + "      window.applicationCache.onobsolete = "
                + "          function() { updateTitle(\"onobsolete Callback\"); };"
                + "      window.applicationCache.onerror = "
                + "          function() { updateTitle(\"onerror Callback\"); };" + "    </script>" + "  </head>"
                + "  <body onload=\"updateTitle('Loaded');\">AppCache test</body>" + "</html>"));
    } else if (path.equals(APPCACHE_MANIFEST_PATH)) {
        response = createResponse(HttpStatus.SC_OK);
        try {
            StringEntity entity = new StringEntity("CACHE MANIFEST");
            // This entity property is not used when constructing the response, (See
            // AbstractMessageWriter.write(), which is called by
            // AbstractHttpServerConnection.sendResponseHeader()) so we have to set this header
            // manually.
            // TODO: Should we do this for all responses from this server?
            entity.setContentType("text/cache-manifest");
            response.setEntity(entity);
            response.setHeader("Content-Type", "text/cache-manifest");
        } catch (UnsupportedEncodingException e) {
            Log.w(TAG, "Unexpected UnsupportedEncodingException");
        }
    }
    if (response == null) {
        response = createResponse(HttpStatus.SC_NOT_FOUND);
    }
    StatusLine sl = response.getStatusLine();
    Log.i(TAG, sl.getStatusCode() + "(" + sl.getReasonPhrase() + ")");
    setDateHeaders(response);
    return response;
}

From source file:com.orange.ocara.ui.activity.ResultAuditActivity.java

/**
 * To share a document by its path.<br/>
 * This will send a share intent.// ww w.j a  va 2 s .  c  om
 *
 * @param path the file path to share
 */
private void shareDocument(String path) {
    // create an intent, so the user can choose which application he/she wants to use to share this file
    final Intent intent = ShareCompat.IntentBuilder.from(this)
            .setType(MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(path)))
            .setStream(FileProvider.getUriForFile(this, "com.orange.ocara", exportFile))
            .setChooserTitle("How do you want to share?").createChooserIntent()
            .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)
            .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    startActivityForResult(intent, ACTION_SHARE_DOCUMENT);
}

From source file:com.orange.ocara.ui.activity.ResultAuditActivity.java

/**
 * To savge a document by its path.<br/>
 *
 * @param path the file path to share/*from w w  w  . j a va2s.c o  m*/
 */
private void saveDocument(String path) {
    Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType(
            MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(path)));
    startActivityForResult(intent, ACTION_SAVE_DOCUMENT);
}

From source file:net.gsantner.opoc.util.ContextUtils.java

/**
 * Detect MimeType of given file/*from   www .  j ava2  s. c  om*/
 * Android/Java's own MimeType map is very very small and detection barely works at all
 * Hence use custom map for some file extensions
 */
public String getMimeType(Uri uri) {
    String mimeType = null;
    if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
        ContentResolver cr = _context.getContentResolver();
        mimeType = cr.getType(uri);
    } else {
        String ext = MimeTypeMap.getFileExtensionFromUrl(uri.toString());
        mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext.toLowerCase());

        // Try to guess if the recommended methods fail
        if (TextUtils.isEmpty(mimeType)) {
            switch (ext) {
            case "md":
            case "markdown":
            case "mkd":
            case "mdown":
            case "mkdn":
            case "mdwn":
            case "rmd":
                mimeType = "text/markdown";
                break;
            case "yaml":
            case "yml":
                mimeType = "text/yaml";
                break;
            case "json":
                mimeType = "text/json";
                break;
            case "txt":
                mimeType = "text/plain";
                break;
            }
        }
    }

    if (TextUtils.isEmpty(mimeType)) {
        mimeType = "*/*";
    }
    return mimeType;
}

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

public void openFile(String path) {
    if (null == path || path.trim().length() == 0) {
        return;//www .j a va  2s . c  om
    }
    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.vuze.android.remote.fragment.FilesFragment.java

@SuppressWarnings("unused")
protected boolean reallyStreamFile(Map<?, ?> selectedFile) {
    final String contentURL = getContentURL(selectedFile);
    if (contentURL != null && contentURL.length() > 0) {
        Uri uri = Uri.parse(contentURL);

        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        String name = MapUtils.getMapString(selectedFile, "name", "video");
        intent.putExtra("title", name);

        String extension = MimeTypeMap.getFileExtensionFromUrl(contentURL).toLowerCase(Locale.US);
        String mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        if (mimetype != null && tryLaunchWithMimeFirst) {
            intent.setType(mimetype);//w  ww.j ava  2s  .co  m
        }
        Class<?> fallBackIntentClass = VideoViewer.class;
        if (mimetype != null && mimetype.startsWith("image")) {
            fallBackIntentClass = ImageViewer.class;
        }

        final PackageManager packageManager = getActivity().getPackageManager();
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        if (AndroidUtils.DEBUG) {
            Log.d(TAG, "num intents " + list.size());
            for (ResolveInfo info : list) {
                ComponentInfo componentInfo = AndroidUtils.getComponentInfo(info);
                Log.d(TAG, info.toString() + "/"
                        + (componentInfo == null ? "null" : (componentInfo.name + "/" + componentInfo)));
            }
        }
        if (list.size() == 0) {
            // Intent will launch, but show message to the user:
            // "Opening web browser links is not supported"
            intent.setClass(getActivity(), fallBackIntentClass);
        }
        if (list.size() == 1) {
            ResolveInfo info = list.get(0);
            ComponentInfo componentInfo = AndroidUtils.getComponentInfo(info);
            if (componentInfo != null && componentInfo.name != null) {
                if ("com.amazon.unifiedshare.actionchooser.BuellerShareActivity".equals(componentInfo.name)
                        || componentInfo.name.startsWith("com.google.android.tv.frameworkpackagestubs.Stubs")) {
                    intent.setClass(getActivity(), fallBackIntentClass);
                }
            }
        }

        try {
            startActivity(intent);
            if (AndroidUtils.DEBUG) {
                Log.d(TAG, "Started " + uri + " MIME: " + intent.getType());
            }
        } catch (java.lang.SecurityException es) {
            if (AndroidUtils.DEBUG) {
                Log.d(TAG, "ERROR launching. " + es.toString());
            }

            if (mimetype != null) {
                try {
                    Intent intent2 = new Intent(Intent.ACTION_VIEW, uri);
                    intent2.putExtra("title", name);
                    if (!tryLaunchWithMimeFirst) {
                        intent2.setType(mimetype);
                    }

                    list = packageManager.queryIntentActivities(intent2, PackageManager.MATCH_DEFAULT_ONLY);
                    if (AndroidUtils.DEBUG) {
                        Log.d(TAG, "num intents " + list.size());
                        for (ResolveInfo info : list) {
                            ComponentInfo componentInfo = AndroidUtils.getComponentInfo(info);
                            Log.d(TAG, info.toString() + "/" + (componentInfo == null ? "null"
                                    : (componentInfo.name + "/" + componentInfo)));
                        }
                    }

                    startActivity(intent2);
                    if (AndroidUtils.DEBUG) {
                        Log.d(TAG,
                                "Started with" + (intent2.getType() == null ? " no" : " ") + " mime: " + uri);
                    }
                    return true;
                } catch (Throwable ex2) {
                    if (AndroidUtils.DEBUG) {
                        Log.d(TAG, "no intent for view. " + ex2.toString());
                    }
                }
            }

            Toast.makeText(getActivity().getApplicationContext(),
                    getActivity().getResources().getString(R.string.intent_security_fail), Toast.LENGTH_LONG)
                    .show();
        } catch (android.content.ActivityNotFoundException ex) {
            if (AndroidUtils.DEBUG) {
                Log.d(TAG, "no intent for view. " + ex.toString());
            }

            if (mimetype != null) {
                try {
                    Intent intent2 = new Intent(Intent.ACTION_VIEW, uri);
                    intent2.putExtra("title", name);
                    if (!tryLaunchWithMimeFirst) {
                        intent2.setType(mimetype);
                    }
                    startActivity(intent2);
                    if (AndroidUtils.DEBUG) {
                        Log.d(TAG, "Started (no mime set) " + uri);
                    }
                    return true;
                } catch (android.content.ActivityNotFoundException ex2) {
                    if (AndroidUtils.DEBUG) {
                        Log.d(TAG, "no intent for view. " + ex2.toString());
                    }
                }
            }

            Toast.makeText(getActivity().getApplicationContext(),
                    getActivity().getResources().getString(R.string.no_intent), Toast.LENGTH_SHORT).show();
        }
        return true;
    }

    return true;
}

From source file:com.MustacheMonitor.MustacheMonitor.FileUtils.java

/**
 * Looks up the mime type of a given file name.
 *
 * @param filename/*from ww  w.  jav  a 2  s .  co  m*/
 * @return a mime type
 */
public static String getMimeType(String filename) {
    MimeTypeMap map = MimeTypeMap.getSingleton();
    return map.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(filename));
}

From source file:android.webkit.LoadListener.java

/**
 * guess MIME type based on the file extension.
 */// ww w  .j  a  v  a  2 s . co  m
private String guessMimeTypeFromExtension() {
    // PENDING: need to normalize url
    if (Config.LOGV) {
        Log.v(LOGTAG, "guessMimeTypeFromExtension: mURL = " + mUrl);
    }

    String mimeType = MimeTypeMap.getSingleton()
            .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(mUrl));

    if (mimeType != null) {
        // XXX: Until the servers send us either correct xhtml or
        // text/html, treat application/xhtml+xml as text/html.
        if (mimeType.equals("application/xhtml+xml")) {
            mimeType = "text/html";
        }
    }

    return mimeType;
}

From source file:org.deviceconnect.android.deviceplugin.host.HostDeviceService.java

/**
 * ?MIME Type?./*w w w .j  a  va  2s.co m*/
 * 
 * @param path 
 * @return MineType
 */
public String getMIMEType(final String path) {

    // , , ??String?
    String mFilename = new File(path).getName();
    int dotPos = mFilename.lastIndexOf(".");
    String mFormat = mFilename.substring(dotPos, mFilename.length());

    // ??
    String mExt = MimeTypeMap.getFileExtensionFromUrl(mFormat);
    // ???
    mExt = mExt.toLowerCase();
    // MIME Type?
    return MimeTypeMap.getSingleton().getMimeTypeFromExtension(mExt);
}

From source file:com.codename1.impl.android.AndroidImplementation.java

private String getMimeType(String url) {
    String type = null;//from   w w w. java2 s. co m
    String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    if (extension != null) {
        MimeTypeMap mime = MimeTypeMap.getSingleton();

        type = mime.getMimeTypeFromExtension(extension);
    }
    if (type == null) {
        try {
            Uri uri = Uri.parse(url);
            ContentResolver cr = getContext().getContentResolver();
            type = cr.getType(uri);
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
    return type;
}