Example usage for android.net Uri getHost

List of usage examples for android.net Uri getHost

Introduction

In this page you can find the example usage for android.net Uri getHost.

Prototype

@Nullable
public abstract String getHost();

Source Link

Document

Gets the encoded host from the authority for this URI.

Usage

From source file:org.geometerplus.android.fbreader.network.auth.WebAuthorisationScreen.java

@Override
protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    requestWindowFeature(Window.FEATURE_PROGRESS);
    SQLiteCookieDatabase.init(this);
    CookieSyncManager.createInstance(getApplicationContext());
    CookieManager.getInstance().removeAllCookie();
    final Intent intent = getIntent();
    final Uri data = intent.getData();
    if (data == null || data.getHost() == null) {
        finish();//from  ww  w  .j ava 2  s  .c  o  m
        return;
    }
    final String completeUrl = intent.getStringExtra(COMPLETE_URL_KEY);

    OrientationUtil.setOrientation(this, intent);
    final WebView view = new WebView(this);
    view.getSettings().setJavaScriptEnabled(true);

    view.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int progress) {
            setProgress(progress * 100);
        }
    });
    view.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            setTitle(url);
            if (url != null && url.startsWith(completeUrl)) {
                final HashMap<String, String> cookies = new HashMap<String, String>();
                final String cookieString = CookieManager.getInstance().getCookie(url);
                if (cookieString != null) {
                    // cookieString is a string like NAME=VALUE [; NAME=VALUE]
                    for (String pair : cookieString.split(";")) {
                        final String[] parts = pair.split("=", 2);
                        if (parts.length != 2) {
                            continue;
                        }
                        cookies.put(parts[0].trim(), parts[1].trim());
                    }
                }
                storeCookies(data.getHost(), cookies);
                WebAuthorisationScreen.this.setResult(RESULT_OK);
                finish();
            }
        }

        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            if (android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.ECLAIR_MR1) {
                // hack for auth problem in android 2.1
                handler.proceed();
            } else {
                super.onReceivedSslError(view, handler, error);
            }
        }
    });
    setContentView(view);
    view.loadUrl(intent.getDataString());
}

From source file:com.applozic.mobicommons.file.FileUtils.java

/**
 * Get a file path from a Uri. This will get the the path for Storage Access
 * Framework Documents, as well as the _data field for the MediaStore and
 * other file-based ContentProviders.<br>
 * <br>//from   w w  w. ja v a2 s .  c  o m
 * Callers should check whether the path is local before assuming it
 * represents a local file.
 *
 * @param context The context.
 * @param uri     The Uri to query.
 * @author paulburke
 * @see #isLocal(String)
 * @see #getFile(android.content.Context, android.net.Uri)
 */

public static String getPath(final Context context, final Uri uri) {

    if (DEBUG)
        Log.d(TAG + " File -",
                "Authority: " + uri.getAuthority() + ", Fragment: " + uri.getFragment() + ", Port: "
                        + uri.getPort() + ", Query: " + uri.getQuery() + ", Scheme: " + uri.getScheme()
                        + ", Host: " + uri.getHost() + ", Segments: " + uri.getPathSegments().toString());

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // LocalStorageProvider
        if (isLocalStorageDocument(uri)) {
            // The path is the id
            return DocumentsContract.getDocumentId(uri);
        }
        // ExternalStorageProvider
        else if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] { split[1] };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {

        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.webview.GBWebClient.java

private WebResourceResponse mimicReply(Uri requestedUri) {
    if (requestedUri.getHost() != null && (org.apache.commons.lang3.StringUtils
            .indexOfAny(requestedUri.getHost(), AllowedDomains) != -1)) {
        if (internetHelperBound) {
            LOG.debug("WEBVIEW forwarding request to the internet helper");
            Bundle bundle = new Bundle();
            bundle.putString("URL", requestedUri.toString());
            Message webRequest = Message.obtain();
            webRequest.replyTo = internetHelperListener;
            webRequest.setData(bundle);/*from ww  w  .  j  av a 2  s  .c o m*/
            try {
                latch = new CountDownLatch(1); //the messenger should run on a single thread, hence we don't need to be worried about concurrency. This approach however is certainly not ideal.
                internetHelper.send(webRequest);
                latch.await();
                return internetResponse;

            } catch (RemoteException | InterruptedException e) {
                LOG.warn("Error downloading data from " + requestedUri, e);
            }

        } else {
            LOG.debug("WEBVIEW request to openweathermap.org detected of type: " + requestedUri.getPath()
                    + " params: " + requestedUri.getQuery());
            return mimicOpenWeatherMapResponse(requestedUri.getPath(), requestedUri.getQueryParameter("units"));
        }
    } else {
        LOG.debug("WEBVIEW request:" + requestedUri.toString() + " not intercepted");
    }
    return null;
}

From source file:cgeo.geocaching.connector.oc.OCApiConnector.java

/**
 * get the OC1234 geocode from an internal cache id, for URLs like host.tld/viewcache.php?cacheid
 *///from w w  w . j av  a  2 s.  c o m
@Nullable
protected String getGeocodeFromCacheId(final String url, final String host) {
    final Uri uri = Uri.parse(url);
    if (!StringUtils.containsIgnoreCase(uri.getHost(), host)) {
        return null;
    }

    // host.tld/viewcache.php?cacheid=cacheid
    final String id = uri.getPath().startsWith("/viewcache.php") ? uri.getQueryParameter("cacheid") : "";
    if (StringUtils.isNotBlank(id)) {
        final String geocode = Maybe.fromCallable(new Callable<String>() {
            @Override
            public String call() throws Exception {
                final String normalizedUrl = StringUtils.replaceIgnoreCase(url, getShortHost(), getShortHost());
                return OkapiClient.getGeocodeByUrl(OCApiConnector.this, normalizedUrl);
            }
        }).subscribeOn(AndroidRxUtils.networkScheduler).blockingGet();

        if (geocode != null && canHandle(geocode)) {
            return geocode;
        }
    }
    return null;
}

From source file:org.mobiledeeplinking.android.MobileDeepLinking.java

private void routeUsingUrl(Uri deeplink) throws JSONException {
    // base case/*w  ww .  jav a 2 s .c om*/
    if (TextUtils.isEmpty(deeplink.getHost()) && (TextUtils.isEmpty(deeplink.getPath()))) {
        MDLLog.e("MobileDeepLinking", "No Routes Match.");
        routeToDefault();
        return;
    }

    Iterator<String> keys = config.getRoutes().keys();
    while (keys.hasNext()) {
        String route = keys.next();
        JSONObject routeOptions = (JSONObject) config.getRoutes().get(route);
        try {
            Map<String, String> routeParameters = new HashMap<String, String>();
            routeParameters = DeeplinkMatcher.match(route, routeOptions, routeParameters, deeplink);
            if (routeParameters != null) {
                handleRoute(routeOptions, routeParameters);
                return;
            }
        } catch (JSONException e) {
            MDLLog.e("MobileDeepLinking", "Error parsing JSON!", e);
            break;
        } catch (Exception e) {
            MDLLog.e("MobileDeepLinking", "Error matching and handling route", e);
            break;
        }
    }

    // deeplink trimmer
    routeUsingUrl(trimDeeplink(deeplink));
}

From source file:com.cuddlesoft.norilib.service.ServiceTypeDetectionService.java

@Override
protected void onHandleIntent(Intent intent) {
    // Extract SearchClient.Settings from the received Intent.
    final Uri uri = Uri.parse(intent.getStringExtra(ENDPOINT_URL));
    final Intent broadcastIntent = new Intent(ACTION_DONE);

    if (uri.getHost() == null || uri.getScheme() == null) {
        // The URL supplied is invalid.
        sendBroadcast(broadcastIntent.putExtra(RESULT_CODE, RESULT_FAIL_INVALID_URL));
        return;//from www. j ava 2s. c o m
    }

    // Create the HTTP client.
    final OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setConnectTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS);
    okHttpClient.setReadTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS);

    // Iterate over supported URI schemes for given URL.
    for (String uriScheme : (TLS_SUPPORT.contains(uri.getHost()) ? URI_SCHEMES_PREFER_SSL : URI_SCHEMES)) {
        String baseUri = uriScheme + uri.getHost();
        // Iterate over each endpoint path.
        for (Map.Entry<SearchClient.Settings.APIType, String> entry : API_ENDPOINT_PATHS.entrySet()) {
            // Create a HTTP request object.
            final Request request = new Request.Builder().url(baseUri + entry.getValue()).build();

            try {
                // Fetch response.
                final Response response = okHttpClient.newCall(request).execute();
                // Make sure the response code was OK and that the HTTP client wasn't redirected along the way.
                if (response.code() == HttpStatus.SC_OK && response.priorResponse() == null) {
                    // Found an API endpoint.
                    broadcastIntent.putExtra(RESULT_CODE, RESULT_OK);
                    broadcastIntent.putExtra(ENDPOINT_URL, baseUri);
                    broadcastIntent.putExtra(API_TYPE, entry.getKey().ordinal());
                    sendBroadcast(broadcastIntent);
                    return;
                }
            } catch (IOException e) {
                // Network error. Notify the listeners and return.
                sendBroadcast(broadcastIntent.putExtra(RESULT_CODE, RESULT_FAIL_NETWORK));
                return;
            }
        }
    }

    // End of the loop was reached without finding an API endpoint. Send error code to the BroadcastReceiver.
    sendBroadcast(broadcastIntent.putExtra(RESULT_CODE, RESULT_FAIL_NO_API));
}

From source file:au.id.micolous.frogjump.LoginActivity.java

private boolean resolveIntent(Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_VIEW)) {
        final Uri intentUri = intent.getData();

        if (intentUri.getHost().endsWith("frjmp.xyz")) {
            // Known host, figure out our action!
            List<String> pathSegments = intentUri.getPathSegments();
            if (pathSegments.get(0).equalsIgnoreCase("g")) {
                // Join Group (G)
                // Parameter 1 is the group number, prefill the box with it.

                // Make sure it is a number
                int group_id;
                try {
                    group_id = Integer.valueOf(pathSegments.get(1));
                } catch (NumberFormatException ex) {
                    return false;
                }/*from   w ww. j a  va 2s .  co m*/

                // Now set the text field
                txtGroupId.setText(String.format("%1$09d", group_id));

                // Make sure futures are set to auto-join
                auto_join = true;
            }
        }

    }

    return false;
}

From source file:com.silverpop.engage.deeplinking.EngageDeepLinkManager.java

Uri trimDeeplink(Uri deeplink) {
    String host = deeplink.getHost();
    List<String> pathSegments = new LinkedList<String>(deeplink.getPathSegments());
    if (pathSegments.isEmpty()) {
        // trim off host
        if (!TextUtils.isEmpty(host)) {
            host = null;/*from   www.jav  a 2 s. co m*/
        }
    }

    for (int i = pathSegments.size() - 1; i >= 0; i--) {
        // remove trailing slashes
        if (pathSegments.get(i).equals("/")) {
            pathSegments.remove(i);
        } else {
            pathSegments.remove(i);
            break;
        }
    }

    String pathString = "";
    for (int i = 0; i < pathSegments.size(); i++) {
        pathString += "/";
        pathString += pathSegments.get(i);
    }

    Uri.Builder builder = new Uri.Builder();
    builder.scheme(deeplink.getScheme());
    builder.path(pathString);
    builder.query(deeplink.getQuery());

    return builder.build();
}

From source file:com.onecase.chatroom.service.DataLayerService.java

private void handleDataEvent(DataEvent event) {
    String path = event.getDataItem().getUri().getPath();
    Log.d(TAG, "handleDataEvent path=%s", path);
    if (path.equals(ChatroomConstants.DataLayer.HEART_BIT_PATH)) {
        Uri uri = event.getDataItem().getUri();
        String nodeId = uri.getHost();
        byte[] payload = uri.toString().getBytes();
        if (sendDataHandler != null) {
            sendDataHandler.post(new SendMessageTask(nodeId, payload));
        }/*  ww w . j a  v a  2 s  . c  o m*/
    } else if (path.startsWith(ChatroomConstants.DataLayer.DATA_PHAT_PREFIX)) {
        DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem());
        String dataString = new String(
                dataMapItem.getDataMap().getByteArray(ChatroomConstants.DataLayer.KEY_DATA));
        Log.d(TAG, "handleDataEvent dataString=%s", dataString);
        if (path.equals(ChatroomConstants.DataLayer.NOTIFICATION_PATH)) {
            NotificationData notificationData = Util.toJSONObject(dataString, NotificationData.class);
            notify(notificationData);
        }
    }
}

From source file:com.entertailion.android.overlaynews.Downloader.java

private synchronized void updateFeeds() {
    Log.d(LOG_TAG, "updateFeeds");
    updateTime = System.currentTimeMillis();
    try {//from  ww w.j a va 2 s  . c  om
        // iterate through feeds in database
        ArrayList<RssFeed> feeds = FeedsTable.getFeeds(context);
        Log.d(LOG_TAG, "feeds=" + feeds);
        if (feeds != null) {
            for (RssFeed feed : feeds) {
                // Check if TTL set for feed
                if (feed.getTtl() != -1) {
                    if (System.currentTimeMillis()
                            - (feed.getDate().getTime() + feed.getTtl() * 60 * 1000) < 0) {
                        // too soon
                        Log.d(LOG_TAG, "TTL not reached: " + feed.getTitle());
                        break;
                    }
                }
                String rss = Utils.getRssFeed(feed.getLink(), context, true);
                RssHandler rh = new RssHandler();
                RssFeed rssFeed = rh.getFeed(rss);
                if (rssFeed.getTitle() == null) {
                    try {
                        Uri uri = Uri.parse(feed.getLink());
                        rssFeed.setTitle(uri.getHost());
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "get host", e);
                    }
                }
                Uri uri = Uri.parse(feed.getLink());
                Log.d(LOG_TAG, "host=" + uri.getScheme() + "://" + uri.getHost());
                String icon = Utils.getWebSiteIcon(context, "http://" + uri.getHost());
                Log.d(LOG_TAG, "icon1=" + icon);
                if (icon == null) {
                    // try base host address
                    int count = StringUtils.countMatches(uri.getHost(), ".");
                    if (count > 1) {
                        int index = uri.getHost().indexOf('.');
                        String baseHost = uri.getHost().substring(index + 1);
                        icon = Utils.getWebSiteIcon(context, "http://" + baseHost);
                        Log.d(LOG_TAG, "icon2=" + icon);
                    }
                }
                if (icon != null) {
                    try {
                        FileInputStream fis = context.openFileInput(icon);
                        Bitmap bitmap = BitmapFactory.decodeStream(fis);
                        fis.close();
                        rssFeed.setImage(icon);
                        rssFeed.setBitmap(bitmap);
                    } catch (Exception e) {
                        Log.d(LOG_TAG, "updateFeeds", e);
                    }
                }
                if (rssFeed.getBitmap() == null && rssFeed.getLogo() != null) {
                    Log.d(LOG_TAG, "logo=" + rssFeed.getLogo());
                    Bitmap bitmap = Utils.getBitmapFromURL(rssFeed.getLogo());
                    if (bitmap != null) {
                        icon = Utils.WEB_SITE_ICON_PREFIX + Utils.clean(rssFeed.getLogo()) + ".png";
                        Utils.saveToFile(context, bitmap, bitmap.getWidth(), bitmap.getHeight(), icon);
                        rssFeed.setImage(icon);
                        rssFeed.setBitmap(bitmap);
                    }
                }
                // update database
                long time = 0;
                if (rssFeed.getDate() != null) {
                    time = rssFeed.getDate().getTime();
                }
                FeedsTable.updateFeed(context, feed.getId(), rssFeed.getTitle(), feed.getLink(),
                        rssFeed.getDescription(), time, rssFeed.getViewDate().getTime(), rssFeed.getLogo(),
                        rssFeed.getImage(), rssFeed.getTtl());
                ItemsTable.deleteItems(context, feed.getId());
                for (RssItem item : rssFeed.getItems()) {
                    if (item.getTitle() != null) {
                        time = 0;
                        if (item.getDate() != null) {
                            time = item.getDate().getTime();
                        }
                        ItemsTable.insertItem(context, feed.getId(), item.getTitle(), item.getLink(),
                                item.getDescription(), item.getContent(), time);
                    }
                }
                // release resources
                Bitmap bitmap = rssFeed.getBitmap();
                if (bitmap != null) {
                    rssFeed.setBitmap(null);
                    bitmap.recycle();
                    bitmap = null;
                }
            }
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "updateFeeds", e);
    }
}