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:uk.bowdlerize.service.CensorCensusService.java

private CensorPayload checkURL(String checkURL) throws IllegalArgumentException, URISyntaxException {
    if (!checkURL.startsWith("http"))
        checkURL = "http://" + checkURL;

    CensorPayload censorPayload = new CensorPayload(checkURL);

    Uri mUri = Uri.parse(checkURL);

    if (null == mUri.getEncodedQuery()) {
        checkURL = mUri.getScheme() + "://" + mUri.getHost() + mUri.getPath();
    } else {/*from  ww w .  j a  v  a  2s  .c om*/
        checkURL = mUri.getScheme() + "://" + mUri.getHost() + mUri.getPath() + "?"
                + URLEncoder.encode(mUri.getEncodedQuery());
    }

    Log.e("Checking url", checkURL);

    client = new DefaultHttpClient();

    /*headRequest = new HttpHead(checkURL);
    headRequest.setHeader("User-Agent", "OONI Android Probe");*/

    httpGet = new HttpGet(checkURL);
    httpGet.setHeader("User-Agent", "OONI Android Probe");

    try {
        //response = client.execute(headRequest);
        client.addResponseInterceptor(new HttpResponseInterceptor() {
            @Override
            public void process(HttpResponse httpResponse, HttpContext httpContext)
                    throws HttpException, IOException {
                if (httpResponse.getStatusLine().getStatusCode() == 302
                        || httpResponse.getStatusLine().getStatusCode() == 301) {
                    for (Header hdr : httpResponse.getAllHeaders()) {
                        if (hdr.getName().equals("Location")) {
                            /*if (hdr.getValue().equals("http://ee-outage.s3.amazonaws.com/content-blocked/content-blocked-v1.html") ||
                            hdr.getValue().contains("http://ee-outage.s3.amazonaws.com"))
                            {
                            Log.e("Blocked", "Blocked by EE");
                            throw new CensoredException("Blocked by EE", "EE", 100);
                            }
                            else if (hdr.getValue().contains("http://www.t-mobile.co.uk/service/wnw-mig/entry/") ||
                                 hdr.getValue().contains("http://tmobile.ee.co.uk/common/system_error_pages/outage_wnw.html"))
                            {
                            Log.e("Blocked", "Blocked by TMobile");
                            throw new CensoredException("Blocked by TMobile", "TMobile", 100);
                            }
                            else if (hdr.getValue().contains("http://online.vodafone.co.uk/dispatch/Portal/ContentControlServlet?type=restricted"))
                            {
                            Log.e("Blocked", "Blocked by Vodafone");
                            throw new CensoredException("Blocked by Vodafone", "Vodafone", 100);
                            }
                            else if (hdr.getValue().contains("http://blockpage.bt.com/pcstaticpage/blocked.html"))
                            {
                            Log.e("Blocked", "Blocked by BT");
                            throw new CensoredException("Blocked by BT", "BT", 100);
                            }
                            else if (hdr.getValue().contains("http://www.talktalk.co.uk/notice/parental-controls?accessurl"))
                            {
                            Log.e("Blocked", "Blocked by TalkTalk");
                            throw new CensoredException("Blocked by TalkTalk", "TalkTalk", 100);
                            }
                            else if (hdr.getValue().contains("http://www.plus.net/support/security/abuse/blocked.shtml"))
                            {
                            Log.e("Blocked", "Blocked by PlusNet");
                            throw new CensoredException("Blocked by PlusNet", "PlusNet", 100);
                            }
                            else if (hdr.getValue().contains("http://mobile.three.co.uk/pc/Live/pcreator/live/100004/pin/blocked?"))
                            {
                            Log.e("Blocked", "Blocked by Three");
                            throw new CensoredException("Blocked by Three", "Three", 100);
                            }
                            else if (hdr.getValue().contains("http://m.virginmedia.com/MiscPages/AdultWarning.aspx"))
                            {
                            Log.e("Blocked", "Blocked by VirginMobile");
                            throw new CensoredException("Blocked by VirginMobile", "VirginMobile", 100);
                            }
                            else if (hdr.getValue().contains("http://assets.o2.co.uk/18plusaccess/"))
                            {
                            Log.e("Blocked", "Blocked by O2");
                            throw new CensoredException("Blocked by O2", "O2", 100);
                            }*/
                            api.checkHeader(hdr);
                        }
                    }
                }

                /*Log.e("intercepted return code",httpResponse.getStatusLine().toString());
                        
                for(Header hdr : httpResponse.getAllHeaders())
                {
                Log.e("intercepted header",hdr.getName().toString() + " / " + hdr.getValue().toString());
                }
                Log.e("intercepted header","------------------\r\n------------------\r\n------------------\r\n------------------\r\n------------------\r\n");*/

            }
        });
        response = client.execute(httpGet);
    }
    //This is the best case scenario!
    catch (CensoredException CE) {
        censorPayload.consumeCensoredException(CE);
        return censorPayload;
    } catch (UnknownHostException uhe) {
        uhe.printStackTrace();
        censorPayload.consumeError(uhe.getMessage());
        return censorPayload;
    } catch (ConnectTimeoutException CTE) {
        CTE.printStackTrace();
        censorPayload.consumeError(CTE.getMessage());
        return censorPayload;
    } catch (NoHttpResponseException NHRE) {
        NHRE.printStackTrace();
        censorPayload.consumeError(NHRE.getMessage());
        return censorPayload;
    } catch (IOException ioe) {
        ioe.printStackTrace();
        censorPayload.consumeError(ioe.getMessage());
        return censorPayload;
    } catch (IllegalStateException ise) {
        ise.printStackTrace();
        censorPayload.setCensored(false);
        censorPayload.setConfidence(0);
        return censorPayload;
    } catch (Exception e) {
        e.printStackTrace();
        censorPayload.setCensored(false);
        censorPayload.setConfidence(0);
        return censorPayload;
    }

    int statusCode = response.getStatusLine().getStatusCode();

    censorPayload.setReturnCode(statusCode);

    Log.e("checkURL code", Integer.toString(statusCode));
    if (statusCode == 403 || statusCode == 404) {
        censorPayload.setCensored(true);
        censorPayload.setConfidence(25);
        return censorPayload;
    } else if (statusCode == 504 || statusCode == 503 || statusCode == 500) {
        censorPayload.consumeError("Server Issue " + Integer.toString(statusCode));
        return censorPayload;
    }

    String phrase = response.getStatusLine().getReasonPhrase();

    Log.e("checkURL phrase", phrase);

    if (phrase.contains("orbidden")) {
        censorPayload.setCensored(true);
        censorPayload.setConfidence(50);
        return censorPayload;
    }

    if (phrase.contains("blocked")) {
        censorPayload.setCensored(true);
        censorPayload.setConfidence(100);
        return censorPayload;
    }

    for (Header hdr : response.getAllHeaders()) {
        Log.e("checkURL header", hdr.getName() + " / " + hdr.getValue());
    }

    censorPayload.setCensored(false);
    censorPayload.setConfidence(1);
    return censorPayload;
}

From source file:com.appunite.websocket.WebSocket.java

/**
 * Write websocket headers to outputStream (not thread safe)
 * /*from  w  w  w  .  j  a  v  a 2 s .com*/
 * @param uri uri
 * @param secret secret that is written to headers
 * @throws IOException
 */
private void writeHeaders(Uri uri, String secret) throws IOException {
    mOutputStream.writeLine("GET " + uri.getPath() + " HTTP/1.1");
    mOutputStream.writeLine("Upgrade: websocket");
    mOutputStream.writeLine("Connection: Upgrade");
    mOutputStream.writeLine("Host: " + uri.getHost());
    mOutputStream.writeLine("Origin: " + uri);
    mOutputStream.writeLine("Sec-WebSocket-Key: " + secret);
    mOutputStream.writeLine("Sec-WebSocket-Protocol: chat");
    mOutputStream.writeLine("Sec-WebSocket-Version: 13");
    mOutputStream.writeNewLine();
    mOutputStream.flush();
}

From source file:tv.acfun.a63.ArticleActivity.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override//from w w w .j  a v  a2  s  .  c om
protected void initView(Bundle savedInstanceState) {
    ARTICLE_PATH = AcApp.getExternalCacheDir("article").getAbsolutePath();

    Uri data = getIntent().getData();
    if (Intent.ACTION_VIEW.equalsIgnoreCase(getIntent().getAction()) && data != null) {
        String scheme = data.getScheme();
        if (scheme.equals("ac")) {
            // ac://ac000000
            aid = Integer.parseInt(getIntent().getDataString().substring(7));
        } else if (scheme.equals("http")) {
            // http://www.acfun.tv/v/ac123456
            Matcher matcher;
            String path = data.getPath();
            if (path == null) {
                finish();
                return;
            }
            if ((matcher = sVreg.matcher(path)).find() || (matcher = sAreg.matcher(path)).find()) {
                aid = Integer.parseInt(matcher.group(1));
            }
        }
        if (aid != 0)
            title = "ac" + aid;
        isWebMode = getIntent().getBooleanExtra("webmode", false) && aid == 0;
    } else {
        aid = getIntent().getIntExtra("aid", 0);
        title = getIntent().getStringExtra("title");
    }
    if (!isWebMode) {
        if (aid == 0)
            throw new IllegalArgumentException(" id");
        getSupportActionBar().setTitle("ac" + aid);
        MobclickAgent.onEvent(this, "view_article");
        db = new DB(this);
        isFaved = db.isFav(aid);
    }
    mWeb.getSettings().setAppCachePath(ARTICLE_PATH);
    mWeb.addJavascriptInterface(new ACJSObject(), "AC");
    // Set a chrome client to handle the MediaResource on web page
    // like video,video loading progress, etc.
    mWeb.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            setTitle(title);
        }
    });
    mWeb.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Matcher matcher = sAreg.matcher(url);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            if (matcher.find() || (matcher = sLiteAreg.matcher(url)).find()
                    || (matcher = sVreg.matcher(url)).find() || (matcher = sLiteVreg.matcher(url)).find()) {
                String acId = matcher.group(1);
                try {
                    intent.setData(Uri.parse("ac://ac" + acId));
                    startActivity(intent);
                    return true;
                } catch (Exception e) {
                    // nothing
                }

            } else if (Pattern.matches(sAppReg, url)) {
                String appLink = getString(R.string.app_ac_video_link);
                try {
                    intent.setData(Uri.parse(appLink));
                    startActivity(intent);
                    return true;
                } catch (Exception e) {
                    view.loadUrl(appLink);
                    return true;
                }

            }
            if (!isWebMode) {
                start(ArticleActivity.this, url);
                return true;
            } else {
                Uri uri = Uri.parse(url);
                if (uri.getHost() != null && !uri.getHost().contains("acfun")) {
                    try {
                        intent.setData(uri);
                        startActivity(intent);
                        return true;
                    } catch (ActivityNotFoundException ignored) {
                    }
                }
            }
            return false;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            setSupportProgressBarIndeterminateVisibility(true);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            setSupportProgressBarIndeterminateVisibility(false);
            if (isWebMode || imgUrls == null || imgUrls.isEmpty() || url.startsWith("file:///android_asset")
                    || AcApp.getViewMode() == Constants.MODE_NO_PIC) // ?
                return;
            //                    Log.d(TAG, "on finished:" + url);
            if ((url.equals(getBaseUrl()) || url.contains(NAME_ARTICLE_HTML)) && imgUrls.size() > 0
                    && !isDownloaded) {
                String[] arr = new String[imgUrls.size()];
                mDownloadTask = new DownloadImageTask();
                mDownloadTask.execute(imgUrls.toArray(arr));
            }

        }

    });
    mWeb.getSettings().setSupportZoom(true);
    mWeb.getSettings().setBuiltInZoomControls(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        mWeb.getSettings().setDisplayZoomControls(false);
    setTextZoom(AcApp.getConfig().getInt("text_size", 0));
}

From source file:io.ionic.links.IonicDeeplink.java

public void handleIntent(Intent intent) {
    final String intentString = intent.getDataString();

    // read intent
    String action = intent.getAction();
    Uri url = intent.getData();
    JSONObject bundleData = this._bundleToJson(intent.getExtras());
    Log.d(TAG, "Got a new intent: " + intentString + " " + intent.getScheme() + " " + action + " " + url);

    // if app was not launched by the url - ignore
    if (!Intent.ACTION_VIEW.equals(action) || url == null) {
        return;/*  w ww  . j a v a2  s. co  m*/
    }

    // store message and try to consume it
    try {
        lastEvent = new JSONObject();
        lastEvent.put("url", url.toString());
        lastEvent.put("path", url.getPath());
        lastEvent.put("queryString", url.getQuery());
        lastEvent.put("scheme", url.getScheme());
        lastEvent.put("host", url.getHost());
        lastEvent.put("fragment", url.getFragment());
        lastEvent.put("extra", bundleData);
        consumeEvents();
    } catch (JSONException ex) {
        Log.e(TAG, "Unable to process URL scheme deeplink", ex);
    }
}

From source file:com.irccloud.android.activity.VideoPlayerActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(R.style.ImageViewerTheme);//from  w w w .  jav  a  2 s  .co  m
    if (savedInstanceState == null)
        overridePendingTransition(R.anim.slide_in_right, R.anim.fade_out);
    setContentView(R.layout.activity_video_player);
    toolbar = findViewById(R.id.toolbar);
    try {
        setSupportActionBar(toolbar);
    } catch (Throwable t) {
    }
    if (Build.VERSION.SDK_INT < 21) {
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
    } else if (Build.VERSION.SDK_INT >= 21) {
        Bitmap cloud = BitmapFactory.decodeResource(getResources(), R.drawable.splash_logo);
        if (cloud != null) {
            setTaskDescription(new ActivityManager.TaskDescription(getResources().getString(R.string.app_name),
                    cloud, getResources().getColor(android.R.color.black)));
        }
        getWindow().setStatusBarColor(getResources().getColor(android.R.color.black));
        getWindow().setNavigationBarColor(getResources().getColor(android.R.color.black));
        if (Build.VERSION.SDK_INT >= 23) {
            getWindow().getDecorView().setSystemUiVisibility(
                    getWindow().getDecorView().getSystemUiVisibility() & ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    if (Build.VERSION.SDK_INT > 16) {
        getWindow().getDecorView()
                .setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
                    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                    @Override
                    public void onSystemUiVisibilityChange(int visibility) {
                        if ((visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) {
                            toolbar.setAlpha(0);
                            toolbar.animate().alpha(1);
                            controls.setAlpha(0);
                            controls.animate().alpha(1);
                            hide_actionbar();
                        } else {
                            toolbar.setAlpha(1);
                            toolbar.animate().alpha(0);
                            controls.setAlpha(1);
                            controls.animate().alpha(0);
                        }
                    }
                });
    }

    controls = findViewById(R.id.controls);
    mProgress = findViewById(R.id.progress);

    rew = findViewById(R.id.rew);
    rew.setEnabled(false);
    rew.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                handler.removeCallbacks(mHideRunnable);
                handler.post(rewindRunnable);
            }
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                handler.removeCallbacks(rewindRunnable);
                hide_actionbar();
            }
            return false;
        }
    });
    play = findViewById(R.id.play);
    play.setEnabled(false);
    play.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            video.start();
            handler.post(mUpdateRunnable);
            hide_actionbar();
        }
    });
    pause = findViewById(R.id.pause);
    pause.setEnabled(false);
    pause.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            video.pause();
            handler.post(mUpdateRunnable);
            handler.removeCallbacks(mHideRunnable);
        }
    });
    ffwd = findViewById(R.id.ffwd);
    ffwd.setEnabled(false);
    ffwd.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                handler.removeCallbacks(mHideRunnable);
                handler.post(ffwdRunnable);
            }
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                handler.removeCallbacks(ffwdRunnable);
                hide_actionbar();
            }
            return false;
        }
    });
    time_current = findViewById(R.id.time_current);
    time = findViewById(R.id.time);
    seekBar = findViewById(R.id.mediacontroller_progress);
    seekBar.setEnabled(false);
    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                video.seekTo(progress);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            if (video.isPlaying())
                video.pause();
            handler.removeCallbacks(mHideRunnable);
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            hide_actionbar();
        }
    });

    video = findViewById(R.id.video);
    video.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (Build.VERSION.SDK_INT > 16) {
                if ((getWindow().getDecorView().getSystemUiVisibility()
                        & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) {
                    getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                            | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
                } else {
                    getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
                    hide_actionbar();
                }
            } else {
                if (toolbar.getVisibility() == View.VISIBLE) {
                    toolbar.setVisibility(View.GONE);
                    controls.setVisibility(View.GONE);
                } else {
                    toolbar.setVisibility(View.VISIBLE);
                    controls.setVisibility(View.VISIBLE);
                    hide_actionbar();
                }
            }
            return false;
        }
    });
    video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            mediaPlayer.start();
            mProgress.setVisibility(View.GONE);
            rew.setEnabled(true);
            pause.setEnabled(true);
            play.setEnabled(true);
            ffwd.setEnabled(true);
            seekBar.setEnabled(true);
            handler.post(mUpdateRunnable);
            hide_actionbar();
        }
    });
    video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            video.pause();
            video.seekTo(video.getDuration());
            handler.removeCallbacks(mHideRunnable);
            if (Build.VERSION.SDK_INT > 16) {
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
            } else {
                toolbar.setVisibility(View.VISIBLE);
                controls.setVisibility(View.VISIBLE);
            }
        }
    });
    video.setOnErrorListener(new MediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
            AlertDialog d = new AlertDialog.Builder(VideoPlayerActivity.this).setTitle("Playback Failed")
                    .setMessage("An error occured while trying to play this video")
                    .setPositiveButton("Download", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if (Build.VERSION.SDK_INT >= 16 && ActivityCompat.checkSelfPermission(
                                    VideoPlayerActivity.this,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                                ActivityCompat.requestPermissions(VideoPlayerActivity.this,
                                        new String[] { Manifest.permission.READ_EXTERNAL_STORAGE,
                                                Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                        0);
                            } else {
                                DownloadManager d = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                                if (d != null) {
                                    DownloadManager.Request r = new DownloadManager.Request(
                                            Uri.parse(getIntent().getDataString().replace(
                                                    getResources().getString(R.string.VIDEO_SCHEME), "http")));
                                    r.setNotificationVisibility(
                                            DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                    r.allowScanningByMediaScanner();
                                    d.enqueue(r);
                                }
                            }
                        }
                    }).setNegativeButton("Close", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            finish();
                        }
                    }).create();
            d.show();
            return true;
        }
    });

    if (getIntent() != null && getIntent().getDataString() != null) {
        Uri url = Uri.parse(
                getIntent().getDataString().replace(getResources().getString(R.string.VIDEO_SCHEME), "http"));
        if (url.getHost().endsWith("facebook.com")) {
            new FacebookTask().execute(url);
        } else {
            video.setVideoURI(url);
        }
        Answers.getInstance().logContentView(new ContentViewEvent().putContentType("Video"));
    } else {
        finish();
    }
}

From source file:net.wequick.small.webkit.WebView.java

private void initSettings() {
    WebSettings webSettings = this.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setUserAgentString(webSettings.getUserAgentString() + " Native");
    this.addJavascriptInterface(new SmallJsBridge(), "_Small");

    this.setWebChromeClient(new WebChromeClient() {
        @Override/*w  w w.  j  a v  a 2s .co  m*/
        public void onReceivedTitle(android.webkit.WebView view, String title) {
            // Call if html title is set
            super.onReceivedTitle(view, title);
            mTitle = title;
            WebActivity activity = (WebActivity) WebViewPool.getContext(view);
            if (activity != null) {
                activity.setTitle(title);
            }
            // May receive head meta at the same time
            initMetas();
        }

        @Override
        public boolean onJsAlert(android.webkit.WebView view, String url, String message,
                final android.webkit.JsResult result) {
            Context context = WebViewPool.getContext(view);
            if (context == null)
                return false;

            AlertDialog.Builder dlg = new AlertDialog.Builder(context);
            dlg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mConfirmed = true;
                    result.confirm();
                }
            });
            dlg.setMessage(message);
            AlertDialog alert = dlg.create();
            alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (!mConfirmed) {
                        result.cancel();
                    }
                }
            });
            mConfirmed = false;
            alert.show();
            return true;
        }

        @Override
        public boolean onJsConfirm(android.webkit.WebView view, String url, String message,
                final android.webkit.JsResult result) {
            Context context = WebViewPool.getContext(view);
            AlertDialog.Builder dlg = new AlertDialog.Builder(context);
            dlg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mConfirmed = true;
                    result.confirm();
                }
            });
            dlg.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mConfirmed = true;
                    result.cancel();
                }
            });
            dlg.setMessage(message);
            AlertDialog alert = dlg.create();
            alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (!mConfirmed) {
                        result.cancel();
                    }
                }
            });
            mConfirmed = false;
            alert.show();
            return true;
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            String msg = consoleMessage.message();
            if (msg == null)
                return false;
            Uri uri = Uri.parse(msg);
            if (uri != null && null != uri.getScheme() && uri.getScheme().equals(SMALL_SCHEME)) {
                String host = uri.getHost();
                String ret = uri.getQueryParameter(SMALL_QUERY_KEY_RET);
                if (host.equals(SMALL_HOST_POP)) {
                    WebActivity activity = (WebActivity) WebViewPool.getContext(WebView.this);
                    activity.finish(ret);
                } else if (host.equals(SMALL_HOST_EXEC)) {
                    if (mOnResultListener != null) {
                        mOnResultListener.onResult(ret);
                    }
                }
                return true;
            }
            Log.d(consoleMessage.sourceId(),
                    "line" + consoleMessage.lineNumber() + ": " + consoleMessage.message());
            return true;
        }

        @Override
        public void onCloseWindow(android.webkit.WebView window) {
            super.onCloseWindow(window);
            close(new OnResultListener() {
                @Override
                public void onResult(String ret) {
                    if (ret.equals("false"))
                        return;

                    WebActivity activity = (WebActivity) WebViewPool.getContext(WebView.this);
                    activity.finish(ret);
                }
            });
        }
    });

    this.setWebViewClient(new android.webkit.WebViewClient() {

        private final String ANCHOR_SCHEME = "anchor";

        @Override
        public boolean shouldOverrideUrlLoading(android.webkit.WebView view, String url) {
            if (mLoadingUrl != null && mLoadingUrl.equals(url)) {
                // reload by window.location.reload or something
                return super.shouldOverrideUrlLoading(view, url);
            }

            Boolean hasStarted = mHasStartedUrl.get(url);
            if (hasStarted != null && hasStarted) {
                // location redirected before page finished
                return super.shouldOverrideUrlLoading(view, url);
            }

            HitTestResult hit = view.getHitTestResult();
            if (hit != null) {
                Uri uri = Uri.parse(url);
                if (uri.getScheme().equals(ANCHOR_SCHEME)) {
                    // Scroll to anchor
                    int anchorY = Integer.parseInt(uri.getHost());
                    view.scrollTo(0, anchorY);
                } else {
                    Small.openUri(uri, WebViewPool.getContext(view));
                }
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageStarted(android.webkit.WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mHasStartedUrl.put(url, true);

            if (mLoadingUrl != null && mLoadingUrl.equals(url)) {
                // reload by window.location.reload or something
                mInjected = false;
            }
            if (sWebViewClient != null && url.equals(mLoadingUrl)) {
                sWebViewClient.onPageStarted(WebViewPool.getContext(view), (WebView) view, url, favicon);
            }
        }

        @Override
        public void onPageFinished(android.webkit.WebView view, String url) {
            super.onPageFinished(view, url);
            mHasStartedUrl.remove(url);

            HitTestResult hit = view.getHitTestResult();
            if (hit != null && hit.getType() == HitTestResult.SRC_ANCHOR_TYPE) {
                // Triggered by user clicked
                Uri uri = Uri.parse(url);
                String anchor = uri.getFragment();
                if (anchor != null) {
                    // If is an anchor, calculate the content offset by DOM
                    // and call native to adjust WebView's offset
                    view.loadUrl(JS_PREFIX + "var y=document.body.scrollTop;"
                            + "var e=document.getElementsByName('" + anchor + "')[0];" + "while(e){"
                            + "y+=e.offsetTop-e.scrollTop+e.clientTop;e=e.offsetParent;}" + "location='"
                            + ANCHOR_SCHEME + "://'+y;");
                }
            }

            if (!mInjected) {
                // Re-inject Small Js
                loadJs(SMALL_INJECT_JS);
                initMetas();
                mInjected = true;
            }

            if (sWebViewClient != null && url.equals(mLoadingUrl)) {
                sWebViewClient.onPageFinished(WebViewPool.getContext(view), (WebView) view, url);
            }
        }

        @Override
        public void onReceivedError(android.webkit.WebView view, int errorCode, String description,
                String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            Log.e("Web", "error: " + description);
            if (sWebViewClient != null && failingUrl.equals(mLoadingUrl)) {
                sWebViewClient.onReceivedError(WebViewPool.getContext(view), (WebView) view, errorCode,
                        description, failingUrl);
            }
        }
    });
}

From source file:org.gaeproxy.GAEProxyService.java

private boolean parseProxyURL(String url) {
    if (proxyType.equals("PaaS")) {
        Uri uri = Uri.parse(url);
        if (uri == null) {
            return false;
        }//  w  w w  .  j av  a2 s. c o  m
        appId = uri.getHost();
        appPath = url;
        return true;
    }
    if (url == null)
        return false;
    String[] proxyString = url.split("\\/");
    if (proxyString.length < 4)
        return false;
    appPath = proxyString[3];
    String[] ids = proxyString[2].split("\\.");
    if (ids.length < 3)
        return false;
    appId = ids[0];
    return true;
}

From source file:com.yeldi.yeldibazaar.AppDetails.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("lightTheme", false))
        setTheme(R.style.AppThemeLight);

    super.onCreate(savedInstanceState);
    ActionBarCompat abCompat = ActionBarCompat.create(this);
    abCompat.setDisplayHomeAsUpEnabled(true);

    setContentView(R.layout.appdetails);

    Intent i = getIntent();/*from   w  w  w  .  j a va  2s. com*/
    appid = "";
    Uri data = getIntent().getData();
    if (data != null) {
        if (data.isHierarchical()) {
            if (data.getHost().equals("details")) {
                // market://details?id=app.id
                appid = data.getQueryParameter("id");
            } else {
                // https://f-droid.org/app/app.id
                appid = data.getLastPathSegment();
            }
        } else {
            // fdroid.app:app.id (old scheme)
            appid = data.getEncodedSchemeSpecificPart();
        }
        Log.d("FDroid", "AppDetails launched from link, for '" + appid + "'");
    } else if (!i.hasExtra("appid")) {
        Log.d("FDroid", "No application ID in AppDetails!?");
    } else {
        appid = i.getStringExtra("appid");
    }

    // Set up the list...
    headerView = new LinearLayout(this);
    ListView lv = (ListView) findViewById(android.R.id.list);
    lv.addHeaderView(headerView);
    ApkListAdapter la = new ApkListAdapter(this, null);
    setListAdapter(la);

    mPm = getPackageManager();
    // Get the preferences we're going to use in this Activity...
    AppDetails old = (AppDetails) getLastNonConfigurationInstance();
    if (old != null) {
        copyState(old);
    } else {
        if (!reset()) {
            finish();
            return;
        }
        resetRequired = false;
    }
    startViews();

}

From source file:ca.rmen.android.poetassistant.main.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    if (BuildConfig.DEBUG && ActivityManager.isUserAMonkey()) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }/*from  w ww.j  a  va2  s .c o m*/
    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate() called with: " + "savedInstanceState = [" + savedInstanceState + "]");
    mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
    setSupportActionBar(mBinding.toolbar);
    Intent intent = getIntent();
    Uri data = intent.getData();
    mPagerAdapter = new PagerAdapter(this, getSupportFragmentManager(), intent);
    mPagerAdapter.registerDataSetObserver(mAdapterChangeListener);

    // Set up the ViewPager with the sections adapter.
    mBinding.viewPager.setAdapter(mPagerAdapter);
    mBinding.viewPager.setOffscreenPageLimit(5);
    mBinding.viewPager.addOnPageChangeListener(mOnPageChangeListener);

    mBinding.tabs.setupWithViewPager(mBinding.viewPager);
    AppBarLayoutHelper.enableAutoHide(mBinding);
    mAdapterChangeListener.onChanged();

    // If the app was launched with a query for the a particular tab, focus on that tab.
    if (data != null && data.getHost() != null) {
        Tab tab = Tab.parse(data.getHost());
        if (tab == null)
            tab = Tab.DICTIONARY;
        mBinding.viewPager.setCurrentItem(mPagerAdapter.getPositionForTab(tab));
    } else if (Intent.ACTION_SEND.equals(intent.getAction())) {
        mBinding.viewPager.setCurrentItem(mPagerAdapter.getPositionForTab(Tab.READER));
    }

    mSearch = new Search(this, mBinding.viewPager);
    loadDictionaries();
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
}

From source file:com.breadwallet.tools.security.RequestHandler.java

public static void processBitIdResponse(final Activity app) {
    final byte[] phrase;
    final byte[] nulTermPhrase;
    final byte[] seed;
    if (app == null) {
        Log.e(TAG, "processBitIdResponse: app is null");
        return;/*w  w w .j  a va 2  s  .  c  om*/
    }
    if (_bitUri == null) {
        Log.e(TAG, "processBitIdResponse: _bitUri is null");
        return;
    }

    final Uri uri = Uri.parse(_bitUri);
    try {
        phrase = KeyStoreManager.getKeyStorePhrase(app, REQUEST_PHRASE_BITID);
    } catch (BRKeystoreErrorException e) {
        Log.e(TAG, "processBitIdResponse: failed to getKeyStorePhrase: " + e.getCause().getMessage());
        return;
    }
    nulTermPhrase = TypesConverter.getNullTerminatedPhrase(phrase);
    seed = BRWalletManager.getSeedFromPhrase(nulTermPhrase);
    if (seed == null) {
        Log.e(TAG, "processBitIdResponse: seed is null!");
        return;
    }

    //run the callback
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                if (_strToSign == null) {
                    //meaning it's a link handling
                    String nonce = null;
                    String scheme = "https";
                    String query = uri.getQuery();
                    if (query == null) {
                        Log.e(TAG, "run: Malformed URI");
                        return;
                    }

                    String u = uri.getQueryParameter("u");
                    if (u != null && u.equalsIgnoreCase("1")) {
                        scheme = "http";
                    }

                    String x = uri.getQueryParameter("x");
                    if (Utils.isNullOrEmpty(x)) {

                        nonce = newNonce(app, uri.getHost() + uri.getPath()); // we are generating our own nonce
                    } else {
                        nonce = x; // service is providing a nonce
                    }

                    String callbackUrl = String.format("%s://%s%s", scheme, uri.getHost(), uri.getPath());

                    // build a payload consisting of the signature, address and signed uri

                    String uriWithNonce = String.format("bitid://%s%s?x=%s", uri.getHost(), uri.getPath(),
                            nonce);

                    final byte[] key = BRBIP32Sequence.getInstance().bip32BitIDKey(seed, _index, callbackUrl);

                    if (key == null) {
                        Log.d(TAG, "processBitIdResponse: key is null!");
                        return;
                    }

                    //                    Log.e(TAG, "run: uriWithNonce: " + uriWithNonce);

                    final String sig = BRBitId.signMessage(_strToSign == null ? uriWithNonce : _strToSign,
                            new BRKey(key));
                    final String address = new BRKey(key).address();

                    JSONObject postJson = new JSONObject();
                    try {
                        postJson.put("address", address);
                        postJson.put("signature", sig);
                        if (_strToSign == null)
                            postJson.put("uri", uriWithNonce);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    RequestBody requestBody = RequestBody.create(null, postJson.toString());
                    Request request = new Request.Builder().url(callbackUrl + "?x=" + nonce).post(requestBody)
                            .header("Content-Type", "application/json").build();
                    Response res = APIClient.getInstance(app).sendRequest(request, true, 0);
                    Log.e(TAG, "processBitIdResponse: res.code: " + res.code());
                    Log.e(TAG, "processBitIdResponse: res.code: " + res.message());
                    try {
                        Log.e(TAG, "processBitIdResponse: body: " + res.body().string());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    //meaning its the wallet plugin, glidera auth
                    String biUri = uri.getHost() == null ? uri.toString() : uri.getHost();
                    final byte[] key = BRBIP32Sequence.getInstance().bip32BitIDKey(seed, _index, biUri);
                    if (key == null) {
                        Log.d(TAG, "processBitIdResponse: key is null!");
                        return;
                    }

                    //                    Log.e(TAG, "run: uriWithNonce: " + uriWithNonce);
                    final String sig = BRBitId.signMessage(_strToSign, new BRKey(key));
                    final String address = new BRKey(key).address();

                    JSONObject postJson = new JSONObject();
                    try {
                        postJson.put("address", address);
                        postJson.put("signature", sig);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    WalletPlugin.handleBitId(postJson);
                }

            } finally {
                //release everything
                _bitUri = null;
                _strToSign = null;
                _bitCallback = null;
                _authString = null;
                _index = 0;
                if (phrase != null)
                    Arrays.fill(phrase, (byte) 0);
                if (nulTermPhrase != null)
                    Arrays.fill(nulTermPhrase, (byte) 0);
                if (seed != null)
                    Arrays.fill(seed, (byte) 0);
            }
        }
    }).start();

}