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.xbmc.kore.ui.RemoteActivity.java

/**
 * Returns the youtube/vimeo video ID from its URL
 *
 * @param playuri Youtube/Vimeo URL// w  ww.  j  a  v a  2s  .co  m
 * @return Youtube/Vimeo Video ID
 */
private String getVideoId(Uri playuri) {
    if (playuri.getHost().endsWith("youtube.com") || playuri.getHost().endsWith("youtu.be")
            || playuri.getHost().endsWith("vimeo.com")) {
        // We'll need to get the v= parameter from the URL
        final Pattern pattern;
        if (playuri.getHost().endsWith("vimeo.com")) {
            pattern = Pattern.compile(
                    "^(?:https?:\\/\\/)?(?:www\\.|player\\.)?vimeo\\.com\\/(?:.*\\/)?(\\d+)(?:\\?.*)?$",
                    Pattern.CASE_INSENSITIVE);
        } else {
            pattern = Pattern.compile(
                    "^(?:https?:\\/\\/)?(?:www\\.|m\\.)?youtu(?:\\.be\\/|be\\.com\\/watch\\?v=)([\\w-]+)(?:[\\?&].*)?$",
                    Pattern.CASE_INSENSITIVE);
        }
        final Matcher matcher = pattern.matcher(playuri.toString());
        if (matcher.matches()) {
            return matcher.group(1);
        }
    }
    return null;
}

From source file:org.xbmc.kore.ui.sections.remote.RemoteActivity.java

/**
 * Converts a video url to a Kodi plugin URL.
 *
 * @param playuri some URL//  w w w  . j  a  v  a 2 s .co m
 * @return plugin URL
 */
private String toPluginUrl(Uri playuri) {
    String host = playuri.getHost();
    if (host.endsWith("svtplay.se")) {
        Pattern pattern = Pattern.compile("^(?:https?:\\/\\/)?(?:www\\.)?svtplay\\.se\\/video\\/(\\d+\\/.*)",
                Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(playuri.toString());
        if (matcher.matches()) {
            return "plugin://plugin.video.svtplay/?url=%2Fvideo%2F" + URLEncoder.encode(matcher.group(1))
                    + "&mode=video";
        }
    } else if (host.endsWith("vimeo.com")) {
        String last = playuri.getLastPathSegment();
        if (last.matches("\\d+")) {
            return "plugin://plugin.video.vimeo/play/?video_id=" + last;
        }
    } else if (host.endsWith("youtube.com")) {
        if (playuri.getPathSegments().contains("playlist")) {
            return "plugin://plugin.video.youtube/play/?order=default&playlist_id="
                    + playuri.getQueryParameter("list");
        } else {
            return "plugin://plugin.video.youtube/play/?video_id=" + playuri.getQueryParameter("v");
        }
    } else if (host.endsWith("youtu.be")) {
        return "plugin://plugin.video.youtube/play/?video_id=" + playuri.getLastPathSegment();
    }
    return null;
}

From source file:com.wikitude.virtualhome.AugmentedActivity.java

public ArchitectView.ArchitectUrlListener getUrlListener() {

    Log.e(this.getClass().getName(), " VIRTUALHOME: Called getUrlListener");

    return new ArchitectView.ArchitectUrlListener() {

        @Override//from  w  ww  .ja  v  a  2s. c  o m
        public boolean urlWasInvoked(String uriString) {

            Log.e(this.getClass().getName(), " VIRTUALHOME: uriString: " + uriString);
            Uri invokedUri = Uri.parse(uriString);

            if ("button1".equalsIgnoreCase(invokedUri.getHost())) {
                shareSnapShot();
            }
            return true;
        }
    };
}

From source file:com.playhaven.android.view.HTMLView.java

/**
 * This switches on the host portion of a request prefixed with
 * DISPATCH_PREFIX in order to handle events from the content templates.
 *
 * @TODO this would be a good candidate for factoring out to a cleaner custom WebViewClient
 *
 * @param dispatchUrl//from  w w  w. j  a  va 2 s . c o m
 */
private void handleDispatch(String dispatchUrl) {
    Uri callbackUri = Uri.parse(dispatchUrl);
    String callbackId = callbackUri.getQueryParameter("callback");
    String callbackString = callbackUri.getHost();
    String dispatchContext = callbackUri.getQueryParameter("context");
    PlayHaven.d("Handling dispatch: %s of type %s", dispatchUrl, callbackString);

    switch (Dispatches.valueOf(callbackString)) {
    /**
     * closeButton hides the native emergency close button, and passes
     * notice of whether it was hidden back to the content template
     */
    case closeButton:
        String hidden = "true";
        try {
            hidden = new JSONObject(dispatchContext).getString("hidden");
        } catch (JSONException jse) {
            // Default to NOT hiding the emergency close button
            hidden = "false";
        }

        if ("true".equals(hidden)) {
            ((PlayHavenView) getParent()).setExitVisible(false);
        }

        // Tell the content template that we've hidden the emergency close button.
        this.loadUrl(String.format(CALLBACK_TEMPLATE, callbackId, "{'hidden':'" + hidden + "'}", null));
        break;
    /**
     * dismiss triggers the contentDismissed listener
     */
    case dismiss:
        PlayHavenView.DismissType dismiss = PlayHavenView.DismissType.NoThanks;
        if (mRewards != null)
            dismiss = PlayHavenView.DismissType.Reward;

        if (mDataFields != null)
            dismiss = PlayHavenView.DismissType.OptIn;

        if (mPurchases != null)
            dismiss = PlayHavenView.DismissType.Purchase;

        mPlacement.getListener().contentDismissed(mPlacement, dismiss, generateResponseBundle());

        // Unregister the web view client so that any future dispatches will be ignored.
        HTMLView.this.setWebViewClient(null);

        break;
    /**
     * launch retrieves a URL from the server to be parsed using
     * Intent.ACTION_VIEW
     */
    case launch:
        mPlacement.getListener().contentDismissed(mPlacement, PlayHavenView.DismissType.Launch, null);

        /*
         * We can't get this from the original model because we don't
         * know which one they picked (if this was a more_games template).
         */
        String url;
        try {
            url = new JSONObject(dispatchContext).getString("url");
        } catch (JSONException jse) {
            PlayHaven.e("Could not parse launch URL.");
            return;
        }

        UrlRequest urlRequest = new UrlRequest(url);
        ExecutorService pool = Executors.newSingleThreadExecutor();
        final Future<String> uriFuture = pool.submit(urlRequest);
        final String initialUrl = url;

        new Thread(new Runnable() {
            @Override
            public void run() {
                // Wait for our final link.
                String url = null;
                try {
                    url = uriFuture.get();
                } catch (Exception e) {
                    PlayHaven.v("Could not retrieve launch URL from server. Using initial url.");

                    // If the redirect failed, proceed with the original url.
                    url = initialUrl;
                }

                // Launch whatever it is. It might be a Play, web, or other link
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                try {
                    HTMLView.this.getContext().startActivity(intent);
                } catch (Exception e) {
                    PlayHaven.e("Unable to launch URI from template.");
                    e.printStackTrace();
                }
            }
        }).start();
        break;
    /**
     * loadContext passes the full "context" JSON blob to the
     * content template
     */
    case loadContext:
        this.loadUrl(DISPATCH_PROTOCOL_TEMPLATE);
        net.minidev.json.JSONObject context = JsonUtil.getPath(mPlacement.getModel(), "$.response.context");

        /**
         * @playhaven.apihack KitKat+ changed how the webview is loaded
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            this.evaluateJavascript(String.format(CALLBACK_TEMPLATE, callbackId, context, null), null);
        } else {
            this.loadUrl(String.format(CALLBACK_TEMPLATE, callbackId, context, null));
        }
        break;
    /**
     * purchase stores the purchase object (which is generated by the
     * content template) as mPurchases, for use with dismiss dispatch
     */
    case purchase:
        collectAttachments(dispatchContext);
        break;
    /**
     * reward stores the reward object (which is generated by the
     * content template) as mRewards, for use with dismiss dispatch
     */
    case reward:
        net.minidev.json.JSONObject rewardParam = JsonUtil.getPath(mPlacement.getModel(),
                "$.response.context.content.open_dispatch.parameters");
        if (rewardParam == null || rewardParam.size() == 0) {
            // data_collection template sends a reward dispatch when it submits form data ...
            // @TODO: have templates return more than key/value pairs (eg class, pattern)
            this.loadUrl(COLLECT_FORM_DATA);
        }

        collectAttachments(dispatchContext);
        break;
    /**
     * subcontent takes a JSON blob generated by the content template
     * and uses that to get data for a new impression, currently a
     * more_games widget that follows a featured ad
     */
    case subcontent:
        SubcontentRequest subcontentRequest = new SubcontentRequest(dispatchContext);
        subcontentRequest.send(getContext());
        break;
    /**  @TODO Find out why this dispatch was abandoned in 1.12 */
    case track:
        PlayHaven.d("track callback not implemented.");
        break;
    /**
     * This is one injected to let the Android SDK harvest data from the
     * opt-in data collection form.
     */
    case dcData:
        try {
            mDataFields = DataCollectionField.fromUrl(callbackUri);
        } catch (PlayHavenException e) {
            e.printStackTrace();
        }
        break;
    default:
        break;
    }
}

From source file:com.ruesga.rview.ChangeDetailsActivity.java

@SuppressWarnings("Convert2streamapi")
@Override/* w w w  .ja v a  2s .  c om*/
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mBinding = DataBindingUtil.setContentView(this, R.layout.content);

    // Check we have valid arguments
    if (getIntent() == null) {
        finish();
        return;
    }

    boolean forceSinglePanel = getIntent().getBooleanExtra(EXTRA_FORCE_SINGLE_PANEL, false);
    boolean isTwoPanel = getResources().getBoolean(R.bool.config_is_two_pane);
    if (!forceSinglePanel & isTwoPanel) {
        // Tablets have a two panel layout in landscape, so finish the current activity
        // to show the change in the proper activity
        finish();
        return;
    }

    // Force single panel?
    if (forceSinglePanel) {
        setUseTwoPanel(false);
        setForceSinglePanel(true);
    }

    // Setup the title
    setupActivity();

    if (getIntent().getData() != null) {
        Account account = Preferences.getAccount(this);
        if (account == null) {
            // Not ready to handle it
            notifyInvalidArgsAndFinish();
            return;
        }

        // Check scheme
        Uri data = getIntent().getData();
        String scheme = data.getScheme();
        if (!scheme.equals(getPackageName())) {
            notifyInvalidArgsAndFinish();
            return;
        }

        // Retrieve the host and the request id
        String host = data.getHost();
        String query = StringHelper.getSafeLastPathSegment(data);
        if (TextUtils.isEmpty(query)) {
            notifyInvalidArgsAndFinish();
            return;
        }

        ChangeQuery filter;
        switch (host) {
        case Constants.CUSTOM_URI_CHANGE:
            Pattern pattern = StringHelper.GERRIT_CHANGE;
            if (!pattern.matcher(query).matches()) {
                notifyInvalidArgsAndFinish();
                return;
            }
            filter = new ChangeQuery().change(query);
            performGatherChangeId(filter);
            break;
        case Constants.CUSTOM_URI_CHANGE_ID:
            pattern = StringHelper.GERRIT_CHANGE_ID;
            String[] q = query.split(UriHelper.CUSTOM_URI_TOKENIZER);
            if (!pattern.matcher(q[0]).matches()) {
                notifyInvalidArgsAndFinish();
                return;
            }
            filter = new ChangeQuery().change(q[0]);
            String file = rebuildFileInfo(q);
            String[] revAndBase = extractRevisionAndBase(q);
            performGatherChangeId(filter, revAndBase, file);
            break;

        case Constants.CUSTOM_URI_COMMIT:
            if (!StringHelper.GERRIT_COMMIT.matcher(query).matches()) {
                notifyInvalidArgsAndFinish();
                return;
            }
            filter = new ChangeQuery().commit(query);
            performGatherChangeId(filter);
            break;

        default:
            try {
                int legacyChangeId = Integer.valueOf(query);
                filter = new ChangeQuery().change(String.valueOf(legacyChangeId));
                performGatherChangeId(filter);
                return;
            } catch (NumberFormatException ex) {
                // Ignore. Not a valid change-id
            }

            notifyInvalidArgsAndFinish();
            break;
        }
    } else {
        // Set the account if requested
        String accountId = getIntent().getStringExtra(Constants.EXTRA_ACCOUNT_HASH);
        if (!TextUtils.isEmpty(accountId)) {
            Preferences.setAccount(this, ModelHelper.getAccountFromHash(this, accountId));
        }

        // Open the change directly
        int legacyChangeId = getIntent().getIntExtra(Constants.EXTRA_LEGACY_CHANGE_ID, -1);
        if (legacyChangeId == -1) {
            finish();
            return;
        }
        String changeId = getIntent().getStringExtra(Constants.EXTRA_CHANGE_ID);
        performShowChange(savedInstanceState, legacyChangeId, changeId, null, null);
    }
}

From source file:free.yhc.netmbuddy.model.NetLoader.java

public HttpRespContent getHttpContent(Uri uri, boolean source) throws LocalException {
    if (null == mHttpClient) {
        if (DBG)/* w  w  w  . ja va  2  s  . c  o m*/
            P.v("NetLoader Fail to get HttpClient");
        throw new LocalException(Err.UNKNOWN);
    }

    if (!Utils.isNetworkAvailable())
        throw new LocalException(Err.IO_NET);

    String uriString = uri.toString();
    if (source)
        uriString = uriString.replace(uri.getScheme() + "://" + uri.getHost(), "");

    int retry = Policy.NETOWRK_CONN_RETRY;
    while (0 < retry--) {
        try {
            HttpGet httpGet = new HttpGet(uriString);
            HttpHost httpTarget = new HttpHost(uri.getHost());

            if (DBG)
                P.v("executing request: " + httpGet.getRequestLine().toString());
            //logI("uri: " + httpGet.getURI().toString());
            //logI("target: " + httpTarget.getHostName());

            HttpResponse httpResp = mHttpClient.execute(httpTarget, httpGet);
            if (DBG)
                P.v("NetLoader HTTP response status line : " + httpResp.getStatusLine().toString());

            // TODO
            // Need more case-handling-code.
            // Ex. Redirection etc.
            int statusCode = httpResp.getStatusLine().getStatusCode();
            switch (statusCode) {
            case HttpUtils.SC_OK:
            case HttpUtils.SC_NO_CONTENT:
                ;// expected response. let's move forward
                break;

            default:
                // Unexpected response
                if (DBG)
                    P.w("Unexpected Response  status code : " + httpResp.getStatusLine().getStatusCode());
                throw new LocalException(Err.HTTPGET, statusCode);
            }

            InputStream contentStream = null;
            String contentType = null;
            if (HttpUtils.SC_NO_CONTENT == statusCode) {
                ;
            } else {
                HttpEntity httpEntity = httpResp.getEntity();

                if (null == httpEntity) {
                    if (DBG)
                        P.w("Unexpected NULL entity");
                    throw new LocalException(Err.HTTPGET, statusCode);
                }
                contentStream = httpEntity.getContent();
                try {
                    contentType = httpResp.getFirstHeader("Content-Type").getValue().toLowerCase();
                } catch (NullPointerException e) {
                    // Unexpected response data.
                    if (DBG)
                        P.v("NetLoader IOException : " + e.getMessage());
                    throw new LocalException(Err.IO_NET);
                }
            }

            return new HttpRespContent(statusCode, contentStream, contentType);
        } catch (ClientProtocolException e) {
            if (DBG)
                P.v("NetLoader ClientProtocolException : " + e.getMessage());
            throw new LocalException(Err.UNKNOWN);
        } catch (IllegalArgumentException e) {
            if (DBG)
                P.v("Illegal Argument Exception : " + e.getMessage() + "\n" + "URI : " + uriString);
            throw new LocalException(Err.IO_NET);
        } catch (UnknownHostException e) {
            if (DBG)
                P.v("NetLoader UnknownHostException : Maybe timeout?" + e.getMessage());
            if (mUserClose)
                throw new LocalException(Err.INTERRUPTED);

            if (0 >= retry)
                throw new LocalException(Err.IO_NET);

            ; // continue next retry after some time.
            try {
                Thread.sleep(300);
            } catch (InterruptedException ie) {
                throw new LocalException(Err.INTERRUPTED);
            }
            throw new LocalException(Err.IO_NET);
        } catch (IOException e) {
            if (DBG)
                P.v("NetLoader IOException : " + e.getMessage());
            throw new LocalException(Err.IO_NET);
        } catch (IllegalStateException e) {
            if (DBG)
                P.v("NetLoader IllegalStateException : " + e.getMessage());
            throw new LocalException(Err.UNKNOWN);
        }
    }
    eAssert(false);
    return null;
}

From source file:org.telegram.ui.Cells.SharedLinkCell.java

@SuppressLint("DrawAllocation")
@Override/*  w w w.jav  a2s  . c  o  m*/
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    drawLinkImageView = false;
    descriptionLayout = null;
    titleLayout = null;
    descriptionLayout2 = null;
    description2Y = descriptionY;
    linkLayout.clear();
    links.clear();

    int maxWidth = MeasureSpec.getSize(widthMeasureSpec) - AndroidUtilities.dp(AndroidUtilities.leftBaseline)
            - AndroidUtilities.dp(8);

    String title = null;
    String description = null;
    String description2 = null;
    String webPageLink = null;
    boolean hasPhoto = false;

    if (message.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage
            && message.messageOwner.media.webpage instanceof TLRPC.TL_webPage) {
        TLRPC.WebPage webPage = message.messageOwner.media.webpage;
        if (message.photoThumbs == null && webPage.photo != null) {
            message.generateThumbs(true);
        }
        hasPhoto = webPage.photo != null && message.photoThumbs != null;
        title = webPage.title;
        if (title == null) {
            title = webPage.site_name;
        }
        description = webPage.description;
        webPageLink = webPage.url;
    }
    if (message != null && !message.messageOwner.entities.isEmpty()) {
        for (int a = 0; a < message.messageOwner.entities.size(); a++) {
            TLRPC.MessageEntity entity = message.messageOwner.entities.get(a);
            if (entity.length <= 0 || entity.offset < 0
                    || entity.offset >= message.messageOwner.message.length()) {
                continue;
            } else if (entity.offset + entity.length > message.messageOwner.message.length()) {
                entity.length = message.messageOwner.message.length() - entity.offset;
            }
            if (a == 0 && webPageLink != null
                    && !(entity.offset == 0 && entity.length == message.messageOwner.message.length())) {
                if (message.messageOwner.entities.size() == 1) {
                    if (description == null) {
                        description2 = message.messageOwner.message;
                    }
                } else {
                    description2 = message.messageOwner.message;
                }
            }
            try {
                String link = null;
                if (entity instanceof TLRPC.TL_messageEntityTextUrl
                        || entity instanceof TLRPC.TL_messageEntityUrl) {
                    if (entity instanceof TLRPC.TL_messageEntityUrl) {
                        link = message.messageOwner.message.substring(entity.offset,
                                entity.offset + entity.length);
                    } else {
                        link = entity.url;
                    }
                    if (title == null || title.length() == 0) {
                        title = link;
                        Uri uri = Uri.parse(title);
                        title = uri.getHost();
                        if (title == null) {
                            title = link;
                        }
                        int index;
                        if (title != null && (index = title.lastIndexOf('.')) >= 0) {
                            title = title.substring(0, index);
                            if ((index = title.lastIndexOf('.')) >= 0) {
                                title = title.substring(index + 1);
                            }
                            title = title.substring(0, 1).toUpperCase() + title.substring(1);
                        }
                        if (entity.offset != 0 || entity.length != message.messageOwner.message.length()) {
                            description = message.messageOwner.message;
                        }
                    }
                } else if (entity instanceof TLRPC.TL_messageEntityEmail) {
                    if (title == null || title.length() == 0) {
                        link = "mailto:" + message.messageOwner.message.substring(entity.offset,
                                entity.offset + entity.length);
                        title = message.messageOwner.message.substring(entity.offset,
                                entity.offset + entity.length);
                        if (entity.offset != 0 || entity.length != message.messageOwner.message.length()) {
                            description = message.messageOwner.message;
                        }
                    }
                }
                if (link != null) {
                    if (link.toLowerCase().indexOf("http") != 0 && link.toLowerCase().indexOf("mailto") != 0) {
                        links.add("http://" + link);
                    } else {
                        links.add(link);
                    }
                }
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
        }
    }
    if (webPageLink != null && links.isEmpty()) {
        links.add(webPageLink);
    }

    if (title != null) {
        try {
            int width = (int) Math.ceil(titleTextPaint.measureText(title));
            CharSequence titleFinal = TextUtils.ellipsize(title.replace('\n', ' '), titleTextPaint,
                    Math.min(width, maxWidth), TextUtils.TruncateAt.END);
            titleLayout = new StaticLayout(titleFinal, titleTextPaint, maxWidth, Layout.Alignment.ALIGN_NORMAL,
                    1.0f, 0.0f, false);
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
        letterDrawable.setTitle(title);
    }

    if (description != null) {
        try {
            descriptionLayout = ChatMessageCell.generateStaticLayout(description, descriptionTextPaint,
                    maxWidth, maxWidth, 0, 3);
            if (descriptionLayout.getLineCount() > 0) {
                description2Y = descriptionY
                        + descriptionLayout.getLineBottom(descriptionLayout.getLineCount() - 1)
                        + AndroidUtilities.dp(1);
            }
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
    }

    if (description2 != null) {
        try {
            descriptionLayout2 = ChatMessageCell.generateStaticLayout(description2, descriptionTextPaint,
                    maxWidth, maxWidth, 0, 3);
            int height = descriptionLayout2.getLineBottom(descriptionLayout2.getLineCount() - 1);
            if (descriptionLayout != null) {
                description2Y += AndroidUtilities.dp(10);
            }
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
    }

    if (!links.isEmpty()) {
        for (int a = 0; a < links.size(); a++) {
            try {
                String link = links.get(a);
                int width = (int) Math.ceil(descriptionTextPaint.measureText(link));
                CharSequence linkFinal = TextUtils.ellipsize(link.replace('\n', ' '), descriptionTextPaint,
                        Math.min(width, maxWidth), TextUtils.TruncateAt.MIDDLE);
                StaticLayout layout = new StaticLayout(linkFinal, descriptionTextPaint, maxWidth,
                        Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
                linkY = description2Y;
                if (descriptionLayout2 != null && descriptionLayout2.getLineCount() != 0) {
                    linkY += descriptionLayout2.getLineBottom(descriptionLayout2.getLineCount() - 1)
                            + AndroidUtilities.dp(1);
                }
                linkLayout.add(layout);
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
        }
    }

    int maxPhotoWidth = AndroidUtilities.dp(52);
    int x = LocaleController.isRTL
            ? MeasureSpec.getSize(widthMeasureSpec) - AndroidUtilities.dp(10) - maxPhotoWidth
            : AndroidUtilities.dp(10);
    letterDrawable.setBounds(x, AndroidUtilities.dp(10), x + maxPhotoWidth, AndroidUtilities.dp(62));

    if (hasPhoto) {
        TLRPC.PhotoSize currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(message.photoThumbs,
                maxPhotoWidth, true);
        TLRPC.PhotoSize currentPhotoObjectThumb = FileLoader.getClosestPhotoSizeWithSize(message.photoThumbs,
                80);
        if (currentPhotoObjectThumb == currentPhotoObject) {
            currentPhotoObjectThumb = null;
        }
        currentPhotoObject.size = -1;
        if (currentPhotoObjectThumb != null) {
            currentPhotoObjectThumb.size = -1;
        }
        linkImageView.setImageCoords(x, AndroidUtilities.dp(10), maxPhotoWidth, maxPhotoWidth);
        String fileName = FileLoader.getAttachFileName(currentPhotoObject);
        boolean photoExist = true;
        File cacheFile = FileLoader.getPathToAttach(currentPhotoObject, true);
        if (!cacheFile.exists()) {
            photoExist = false;
        }
        String filter = String.format(Locale.US, "%d_%d", maxPhotoWidth, maxPhotoWidth);
        if (photoExist
                || MediaController.getInstance().canDownloadMedia(MediaController.AUTODOWNLOAD_MASK_PHOTO)
                || FileLoader.getInstance().isLoadingFile(fileName)) {
            linkImageView.setImage(currentPhotoObject.location, filter,
                    currentPhotoObjectThumb != null ? currentPhotoObjectThumb.location : null,
                    String.format(Locale.US, "%d_%d_b", maxPhotoWidth, maxPhotoWidth), 0, null, false);
        } else {
            if (currentPhotoObjectThumb != null) {
                linkImageView.setImage(null, null, currentPhotoObjectThumb.location,
                        String.format(Locale.US, "%d_%d_b", maxPhotoWidth, maxPhotoWidth), 0, null, false);
            } else {
                linkImageView.setImageBitmap((Drawable) null);
            }
        }
        drawLinkImageView = true;
    }

    int height = 0;
    if (titleLayout != null && titleLayout.getLineCount() != 0) {
        height += titleLayout.getLineBottom(titleLayout.getLineCount() - 1);
    }
    if (descriptionLayout != null && descriptionLayout.getLineCount() != 0) {
        height += descriptionLayout.getLineBottom(descriptionLayout.getLineCount() - 1);
    }
    if (descriptionLayout2 != null && descriptionLayout2.getLineCount() != 0) {
        height += descriptionLayout2.getLineBottom(descriptionLayout2.getLineCount() - 1);
        if (descriptionLayout != null) {
            height += AndroidUtilities.dp(10);
        }
    }
    for (int a = 0; a < linkLayout.size(); a++) {
        StaticLayout layout = linkLayout.get(a);
        if (layout.getLineCount() > 0) {
            height += layout.getLineBottom(layout.getLineCount() - 1);
        }
    }
    if (hasPhoto) {
        height = Math.max(AndroidUtilities.dp(48), height);
    }
    checkBox.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(22), MeasureSpec.EXACTLY),
            MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(22), MeasureSpec.EXACTLY));
    setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),
            Math.max(AndroidUtilities.dp(72), height + AndroidUtilities.dp(16)) + (needDivider ? 1 : 0));
}

From source file:com.jtechme.apphub.FDroid.java

private void handleSearchOrAppViewIntent(Intent intent) {
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        performSearch(query);/*from  ww  w .jav a2s  .com*/
        return;
    }

    final Uri data = intent.getData();
    if (data == null) {
        return;
    }

    final String scheme = data.getScheme();
    final String path = data.getPath();
    String packageName = null;
    String query = null;
    if (data.isHierarchical()) {
        final String host = data.getHost();
        if (host == null) {
            return;
        }
        switch (host) {
        case "f-droid.org":
            if (path.startsWith("/repository/browse")) {
                // http://f-droid.org/repository/browse?fdfilter=search+query
                query = UriCompat.getQueryParameter(data, "fdfilter");

                // http://f-droid.org/repository/browse?fdid=packageName
                packageName = UriCompat.getQueryParameter(data, "fdid");
            } else if (path.startsWith("/app")) {
                // http://f-droid.org/app/packageName
                packageName = data.getLastPathSegment();
                if ("app".equals(packageName)) {
                    packageName = null;
                }
            }
            break;
        case "details":
            // market://details?id=app.id
            packageName = UriCompat.getQueryParameter(data, "id");
            break;
        case "search":
            // market://search?q=query
            query = UriCompat.getQueryParameter(data, "q");
            break;
        case "play.google.com":
            if (path.startsWith("/store/apps/details")) {
                // http://play.google.com/store/apps/details?id=app.id
                packageName = UriCompat.getQueryParameter(data, "id");
            } else if (path.startsWith("/store/search")) {
                // http://play.google.com/store/search?q=foo
                query = UriCompat.getQueryParameter(data, "q");
            }
            break;
        case "apps":
        case "amazon.com":
        case "www.amazon.com":
            // amzn://apps/android?p=app.id
            // http://amazon.com/gp/mas/dl/android?s=app.id
            packageName = UriCompat.getQueryParameter(data, "p");
            query = UriCompat.getQueryParameter(data, "s");
            break;
        }
    } else if ("fdroid.app".equals(scheme)) {
        // fdroid.app:app.id
        packageName = data.getSchemeSpecificPart();
    } else if ("fdroid.search".equals(scheme)) {
        // fdroid.search:query
        query = data.getSchemeSpecificPart();
    }

    if (!TextUtils.isEmpty(query)) {
        // an old format for querying via packageName
        if (query.startsWith("pname:"))
            packageName = query.split(":")[1];

        // sometimes, search URLs include pub: or other things before the query string
        if (query.contains(":"))
            query = query.split(":")[1];
    }

    if (!TextUtils.isEmpty(packageName)) {
        Utils.debugLog(TAG, "FDroid launched via app link for '" + packageName + "'");
        Intent intentToInvoke = new Intent(this, AppDetails.class);
        intentToInvoke.putExtra(AppDetails.EXTRA_APPID, packageName);
        startActivity(intentToInvoke);
    } else if (!TextUtils.isEmpty(query)) {
        Utils.debugLog(TAG, "FDroid launched via search link for '" + query + "'");
        performSearch(query);
    }
}

From source file:org.fdroid.fdroid.FDroid.java

private void handleSearchOrAppViewIntent(Intent intent) {
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        performSearch(query);//  ww  w  . ja va  2 s . c  o m
        return;
    }

    final Uri data = intent.getData();
    if (data == null) {
        return;
    }

    final String scheme = data.getScheme();
    final String path = data.getPath();
    String packageName = null;
    String query = null;
    if (data.isHierarchical()) {
        final String host = data.getHost();
        if (host == null) {
            return;
        }
        switch (host) {
        case "f-droid.org":
            if (path.startsWith("/repository/browse")) {
                // http://f-droid.org/repository/browse?fdfilter=search+query
                query = UriCompat.getQueryParameter(data, "fdfilter");

                // http://f-droid.org/repository/browse?fdid=packageName
                packageName = UriCompat.getQueryParameter(data, "fdid");
            } else if (path.startsWith("/app")) {
                // http://f-droid.org/app/packageName
                packageName = data.getLastPathSegment();
                if ("app".equals(packageName)) {
                    packageName = null;
                }
            }
            break;
        case "details":
            // market://details?id=app.id
            packageName = UriCompat.getQueryParameter(data, "id");
            break;
        case "search":
            // market://search?q=query
            query = UriCompat.getQueryParameter(data, "q");
            break;
        case "play.google.com":
            if (path.startsWith("/store/apps/details")) {
                // http://play.google.com/store/apps/details?id=app.id
                packageName = UriCompat.getQueryParameter(data, "id");
            } else if (path.startsWith("/store/search")) {
                // http://play.google.com/store/search?q=foo
                query = UriCompat.getQueryParameter(data, "q");
            }
            break;
        case "apps":
        case "amazon.com":
        case "www.amazon.com":
            // amzn://apps/android?p=app.id
            // http://amazon.com/gp/mas/dl/android?s=app.id
            packageName = UriCompat.getQueryParameter(data, "p");
            query = UriCompat.getQueryParameter(data, "s");
            break;
        }
    } else if ("fdroid.app".equals(scheme)) {
        // fdroid.app:app.id
        packageName = data.getSchemeSpecificPart();
    } else if ("fdroid.search".equals(scheme)) {
        // fdroid.search:query
        query = data.getSchemeSpecificPart();
    }

    if (!TextUtils.isEmpty(query)) {
        // an old format for querying via packageName
        if (query.startsWith("pname:")) {
            packageName = query.split(":")[1];
        }

        // sometimes, search URLs include pub: or other things before the query string
        if (query.contains(":")) {
            query = query.split(":")[1];
        }
    }

    if (!TextUtils.isEmpty(packageName)) {
        Utils.debugLog(TAG, "FDroid launched via app link for '" + packageName + "'");
        Intent intentToInvoke = new Intent(this, AppDetails.class);
        intentToInvoke.putExtra(AppDetails.EXTRA_APPID, packageName);
        startActivity(intentToInvoke);
        finish();
    } else if (!TextUtils.isEmpty(query)) {
        Utils.debugLog(TAG, "FDroid launched via search link for '" + query + "'");
        performSearch(query);
    }
}

From source file:com.platform.APIClient.java

public Response sendRequest(Request locRequest, boolean needsAuth, int retryCount) {
    if (retryCount > 1)
        throw new RuntimeException("sendRequest: Warning retryCount is: " + retryCount);
    boolean isTestVersion = BREAD_BUY.equalsIgnoreCase("bread-buy-staging");
    boolean isTestNet = BuildConfig.BITCOIN_TESTNET;
    Request request = locRequest.newBuilder().header("X-Testflight", isTestVersion ? "1" : "0")
            .header("X-Bitcoin-Testnet", isTestNet ? "1" : "0").build();
    if (needsAuth) {
        Request.Builder modifiedRequest = request.newBuilder();
        String base58Body = "";
        RequestBody body = request.body();
        try {//from w  ww .  j av a2  s.  c o  m
            if (body != null && body.contentLength() != 0) {
                BufferedSink sink = new Buffer();
                try {
                    body.writeTo(sink);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String bodyString = sink.buffer().readUtf8();
                base58Body = CryptoHelper.base58ofSha256(bodyString.getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        String httpDate = sdf.format(new Date());

        request = modifiedRequest.header("Date", httpDate.substring(0, httpDate.length() - 6)).build();

        String queryString = request.url().encodedQuery();

        String requestString = createRequest(request.method(), base58Body, request.header("Content-Type"),
                request.header("Date"), request.url().encodedPath()
                        + ((queryString != null && !queryString.isEmpty()) ? ("?" + queryString) : ""));
        String signedRequest = signRequest(requestString);
        String token = new String(KeyStoreManager.getToken(ctx));
        if (token.isEmpty())
            token = getToken();
        if (token == null || token.isEmpty()) {
            Log.e(TAG, "sendRequest: failed to retrieve token");
            return null;
        }
        String authValue = "bread " + token + ":" + signedRequest;
        //            Log.e(TAG, "sendRequest: authValue: " + authValue);
        modifiedRequest = request.newBuilder();

        request = modifiedRequest.header("Authorization", authValue).build();

    }
    Response response = null;
    byte[] data = new byte[0];
    try {
        OkHttpClient client = new OkHttpClient.Builder().followRedirects(false)
                /*.addInterceptor(new LoggingInterceptor())*/.build();
        //            Log.e(TAG, "sendRequest: before executing the request: " + request.headers().toString());
        response = client.newCall(request).execute();
        try {
            data = response.body().bytes();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!response.isSuccessful())
            Log.e(TAG,
                    "sendRequest: "
                            + String.format(Locale.getDefault(), "url (%s), code (%d), mess (%s), body (%s)",
                                    request.url(), response.code(), response.message(), new String(data)));
        if (response.isRedirect()) {
            String newLocation = request.url().scheme() + "://" + request.url().host()
                    + response.header("location");
            Uri newUri = Uri.parse(newLocation);
            if (newUri == null) {
                Log.e(TAG, "sendRequest: redirect uri is null");
            } else if (!newUri.getHost().equalsIgnoreCase(HOST)
                    || !newUri.getScheme().equalsIgnoreCase(PROTO)) {
                Log.e(TAG, "sendRequest: WARNING: redirect is NOT safe: " + newLocation);
            } else {
                Log.w(TAG, "redirecting: " + request.url() + " >>> " + newLocation);
                return sendRequest(new Request.Builder().url(newLocation).get().build(), needsAuth, 0);
            }
            return new Response.Builder().code(500).request(request)
                    .body(ResponseBody.create(null, new byte[0])).protocol(Protocol.HTTP_1_1).build();
        }
    } catch (IOException e) {
        e.printStackTrace();
        return new Response.Builder().code(599).request(request).body(ResponseBody.create(null, new byte[0]))
                .protocol(Protocol.HTTP_1_1).build();
    }

    if (response.header("content-encoding") != null
            && response.header("content-encoding").equalsIgnoreCase("gzip")) {
        Log.d(TAG, "sendRequest: the content is gzip, unzipping");
        byte[] decompressed = gZipExtract(data);
        ResponseBody postReqBody = ResponseBody.create(null, decompressed);

        return response.newBuilder().body(postReqBody).build();
    }
    ResponseBody postReqBody = ResponseBody.create(null, data);
    if (needsAuth && isBreadChallenge(response)) {
        Log.e(TAG, "sendRequest: got authentication challenge from API - will attempt to get token");
        getToken();
        if (retryCount < 1) {
            sendRequest(request, true, retryCount + 1);
        }
    }

    return response.newBuilder().body(postReqBody).build();
}