Example usage for android.webkit SslErrorHandler proceed

List of usage examples for android.webkit SslErrorHandler proceed

Introduction

In this page you can find the example usage for android.webkit SslErrorHandler proceed.

Prototype

public void proceed() 

Source Link

Document

Proceed with the SSL certificate.

Usage

From source file:org.apache.cordova.AndroidWebViewClient.java

/**
 * Notify the host application that an SSL error occurred while loading a resource.
 * The host application must call either handler.cancel() or handler.proceed().
 * Note that the decision may be retained for use in response to future SSL errors.
 * The default behavior is to cancel the load.
 *
 * @param view          The WebView that is initiating the callback.
 * @param handler       An SslErrorHandler object that will handle the user's response.
 * @param error         The SSL error object.
 *//*from   www  .j av a 2s  .c o m*/
@TargetApi(8)
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {

    final String packageName = this.cordova.getActivity().getPackageName();
    final PackageManager pm = this.cordova.getActivity().getPackageManager();

    ApplicationInfo appInfo;
    try {
        appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
        if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
            // debug = true
            handler.proceed();
            return;
        } else {
            // debug = false
            super.onReceivedSslError(view, handler, error);
        }
    } catch (NameNotFoundException e) {
        // When it doubt, lock it out!
        super.onReceivedSslError(view, handler, error);
    }
}

From source file:com.near.chimerarevo.fragments.CommentsFragment.java

@SuppressLint("SetJavaScriptEnabled")
private void loadDisqusOAuth() {
    if (getActivity().getSharedPreferences(Constants.PREFS_TAG, Context.MODE_PRIVATE)
            .getString(Constants.KEY_REFRESH_TOKEN, "").length() > 1) {

        RequestBody formBody = new FormEncodingBuilder().add("grant_type", "refresh_token")
                .add("client_id", Constants.DISQUS_API_KEY).add("client_secret", Constants.DISQUS_API_SECRET)
                .add("refresh_token",
                        getActivity().getSharedPreferences(Constants.PREFS_TAG, Context.MODE_PRIVATE)
                                .getString(Constants.KEY_REFRESH_TOKEN, ""))
                .build();//w  w  w  .ja  v a  2s  . com

        Request request = new Request.Builder().url(Constants.DISQUS_TOKEN_URL).post(formBody).tag(FRAGMENT_TAG)
                .build();

        if (mDialog == null)
            mDialog = ProgressDialogUtils.getInstance(getActivity(), R.string.text_login);
        else
            mDialog = ProgressDialogUtils.modifyInstance(mDialog, R.string.text_login);

        mDialog.show();
        OkHttpUtils.getInstance().newCall(request).enqueue(new PostAccessTokenCallback());

        return;
    }

    final Dialog dialog = new Dialog(getActivity());

    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.webview_layout);
    dialog.setCancelable(true);

    dialog.setOnCancelListener(new OnCancelListener() {
        @Override
        public void onCancel(DialogInterface arg0) {
            isDialogOpen = false;
            mFab.show();
        }
    });
    dialog.setOnDismissListener(new OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface arg0) {
            isDialogOpen = false;
            mFab.show();
        }
    });

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT)
        CookieManager.getInstance().removeAllCookies(null);
    else {
        CookieSyncManager.createInstance(getActivity());
        CookieManager.getInstance().removeAllCookie();
    }

    WebView wv = (WebView) dialog.findViewById(R.id.webview);
    wv.getSettings().setJavaScriptEnabled(true);
    wv.getSettings().setSaveFormData(false);
    wv.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            dialog.findViewById(R.id.progressContainer).setVisibility(View.GONE);
            dialog.findViewById(R.id.webViewContainer).setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            dialog.findViewById(R.id.progressContainer).setVisibility(View.VISIBLE);
            dialog.findViewById(R.id.webViewContainer).setVisibility(View.GONE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            boolean state = super.shouldOverrideUrlLoading(view, url);
            if (url.contains(Constants.SITE_URL)) {
                String code = url.split("code=")[1];

                RequestBody formBody = new FormEncodingBuilder().add("grant_type", "authorization_code")
                        .add("client_id", Constants.DISQUS_API_KEY)
                        .add("client_secret", Constants.DISQUS_API_SECRET)
                        .add("redirect_uri", Constants.SITE_URL).add("code", code).build();

                Request request = new Request.Builder().url(Constants.DISQUS_TOKEN_URL).post(formBody)
                        .tag(FRAGMENT_TAG).build();

                if (mDialog == null)
                    mDialog = ProgressDialogUtils.getInstance(getActivity(), R.string.text_login);
                else
                    mDialog = ProgressDialogUtils.modifyInstance(mDialog, R.string.text_login);

                dialog.dismiss();
                mDialog.show();

                OkHttpUtils.getInstance().newCall(request).enqueue(new PostAccessTokenCallback());
            }
            return state;
        }

        @Override
        public void onReceivedSslError(WebView view, @NonNull SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

    });
    wv.loadUrl(URLUtils.getDisqusAuthUrl());

    isDialogOpen = true;
    mFab.hide();
    dialog.show();
}

From source file:com.company.millenium.iwannask.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //GPS//from   ww w  .  j a  v  a 2  s . c  o m
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            if (ActivityCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // Check Permissions Now
                final int REQUEST_LOCATION = 2;

                if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {
                    // Display UI and wait for user interaction
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION);
                }
            } else {
                locationManager.removeUpdates(this);
            }
        }

        public void onStatusChanged(String string, int integer, Bundle bundle) {

        }

        public void onProviderEnabled(String string) {

        }

        public void onProviderDisabled(String string) {

        }
    };

    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // Check Permissions Now
        final int REQUEST_LOCATION = 2;

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Display UI and wait for user interaction
        } else {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                    REQUEST_LOCATION);
        }
    } else {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1000, locationListener);
    }

    int delay = 30000; // delay for 30 sec.
    int period = 3000000; // repeat every 5.3min.
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            if (ActivityCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // Check Permissions Now
                final int REQUEST_LOCATION = 2;

                if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {
                    // Display UI and wait for user interaction
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION);
                }
            } else {
                locationManager.removeUpdates(locationListener);
            }
        }
    }, delay, period);

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

    Intent mIntent = getIntent();
    URL = Constants.SERVER_URL;
    if (mIntent.hasExtra("url")) {
        myWebView = null;
        startActivity(getIntent());
        String url = mIntent.getStringExtra("url");
        URL = Constants.SERVER_URL + url;
    }

    CookieSyncManager.createInstance(this);
    CookieSyncManager.getInstance().startSync();
    myWebView = (WebView) findViewById(R.id.webview);
    myWebView.getSettings().setGeolocationDatabasePath(this.getFilesDir().getPath());
    myWebView.getSettings().setGeolocationEnabled(true);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setUseWideViewPort(false);
    if (!DetectConnection.checkInternetConnection(this)) {
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        showNoConnectionDialog(this);
    } else {
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
    }
    webSettings.setJavaScriptEnabled(true);
    myWebView.addJavascriptInterface(new webappinterface(this), "android");
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setUseWideViewPort(true);
    myWebView.setOverScrollMode(View.OVER_SCROLL_NEVER);

    //location test
    webSettings.setAppCacheEnabled(true);
    webSettings.setDatabaseEnabled(true);
    webSettings.setDomStorageEnabled(true);

    myWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            CookieSyncManager.getInstance().sync();
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed(); // Ignore SSL certificate errors
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Uri.parse(url).getHost().equals(Constants.HOST)
                    || Uri.parse(url).getHost().equals(Constants.WWWHOST)) {
                // This is my web site, so do not override; let my WebView load
                // the page
                return false;
            }
            // Otherwise, the link is not for a page on my site, so launch
            // another Activity that handles URLs
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }
    });
    myWebView.setWebChromeClient(new WebChromeClient() {
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }

        @Override
        public void onPermissionRequest(final PermissionRequest request) {
            Log.d(TAG, "onPermissionRequest");
            runOnUiThread(new Runnable() {
                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void run() {
                    if (request.getOrigin().toString().equals("https://apprtc-m.appspot.com/")) {
                        request.grant(request.getResources());
                    } else {
                        request.deny();
                    }
                }
            });
        }

        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                WebChromeClient.FileChooserParams fileChooserParams) {

            // Double check that we don't have any existing callbacks
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;

            // Set up the take picture intent
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Log.e(TAG, "Unable to create Image File", ex);
                }

                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            // Set up the intent to get an existing image
            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            // Set up the intents for the Intent chooser
            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }

    });
    // setContentView(myWebView);
    //        myWebView.loadUrl(URL);
    myWebView.loadUrl(URL);
    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //                mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
        }
    };

    //CookieManager mCookieManager = CookieManager.getInstance();
    //Boolean hasCookies = mCookieManager.hasCookies();
    //while(!hasCookies);

    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(this, RegistrationIntentService.class);
        //intent.putExtra("session", session);
        startService(intent);
    }

    Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("isFirstRun", true);

    if (isFirstRun) {
        //show start activity
        startActivity(new Intent(MainActivity.this, MyIntro.class));
    }
    //if (!isOnline())
    //    showNoConnectionDialog(this);
    getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("isFirstRun", false).commit();

    //Pull-to-refresh
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.container);
    mSwipeRefreshLayout.setOnRefreshListener(this);
}

From source file:com.ibuildapp.romanblack.WebPlugin.WebPlugin.java

@Override
public void create() {
    try {//from w w w  .j  av  a  2  s.  c o m

        setContentView(R.layout.romanblack_html_main);
        root = (FrameLayout) findViewById(R.id.romanblack_root_layout);
        webView = new ObservableWebView(this);
        webView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT));
        root.addView(webView);

        webView.setHorizontalScrollBarEnabled(false);
        setTitle("HTML");

        Intent currentIntent = getIntent();
        Bundle store = currentIntent.getExtras();
        widget = (Widget) store.getSerializable("Widget");
        if (widget == null) {
            handler.sendEmptyMessageDelayed(INITIALIZATION_FAILED, 100);
            return;
        }
        appName = widget.getAppName();

        if (widget.getPluginXmlData().length() == 0) {
            if (currentIntent.getStringExtra("WidgetFile").length() == 0) {
                handler.sendEmptyMessageDelayed(INITIALIZATION_FAILED, 100);
                return;
            }
        }

        if (widget.getTitle() != null && widget.getTitle().length() > 0) {
            setTopBarTitle(widget.getTitle());
        } else {
            setTopBarTitle(getResources().getString(R.string.romanblack_html_web));
        }

        currentUrl = (String) getSession();
        if (currentUrl == null) {
            currentUrl = "";
        }

        ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null && ni.isConnectedOrConnecting()) {
            isOnline = true;
        }

        // topbar initialization
        setTopBarLeftButtonText(getString(R.string.common_home_upper), true, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

        if (isOnline) {
            webView.getSettings().setJavaScriptEnabled(true);
        }

        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.getSettings().setGeolocationEnabled(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setUseWideViewPort(false);
        webView.getSettings().setSavePassword(false);
        webView.clearHistory();
        webView.invalidate();

        if (Build.VERSION.SDK_INT >= 19) {
        }
        webView.getSettings().setUserAgentString(
                "Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; Nexus One Build/FRG83) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");

        webView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.invalidate();

                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                }
                    break;
                case MotionEvent.ACTION_UP: {
                    if (!v.hasFocus()) {
                        v.requestFocus();
                    }
                }
                    break;

                case MotionEvent.ACTION_MOVE: {
                }
                    break;

                }
                return false;
            }
        });

        webView.setBackgroundColor(Color.WHITE);
        try {
            if (widget.getBackgroundColor() != Color.TRANSPARENT) {
                webView.setBackgroundColor(widget.getBackgroundColor());
            }
        } catch (IllegalArgumentException e) {
        }

        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition,
                    String mimetype, long contentLength) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                startActivity(intent);
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {

            FrameLayout.LayoutParams LayoutParameters = new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);

            @Override
            public void onGeolocationPermissionsShowPrompt(final String origin,
                    final GeolocationPermissions.Callback callback) {
                AlertDialog.Builder builder = new AlertDialog.Builder(WebPlugin.this);
                builder.setTitle(R.string.location_dialog_title);
                builder.setMessage(R.string.location_dialog_description);
                builder.setCancelable(true);

                builder.setPositiveButton(R.string.location_dialog_allow,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                callback.invoke(origin, true, false);
                            }
                        });

                builder.setNegativeButton(R.string.location_dialog_not_allow,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                callback.invoke(origin, false, false);
                            }
                        });

                AlertDialog alert = builder.create();
                alert.show();
            }

            @Override
            public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
                if (customView != null) {
                    customViewCallback.onCustomViewHidden();
                    return;
                }

                view.setBackgroundColor(Color.BLACK);
                view.setLayoutParams(LayoutParameters);
                root.addView(view);
                customView = view;
                customViewCallback = callback;
                webView.setVisibility(View.GONE);
            }

            @Override
            public void onHideCustomView() {
                if (customView == null) {
                    return;
                } else {
                    closeFullScreenVideo();
                }
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg) {

                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);//Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                isMedia = true;
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);

            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
            }

            //For Android 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                isMedia = true;
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);

            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                    FileChooserParams fileChooserParams) {
                isV21 = true;
                mUploadMessageV21 = filePathCallback;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
                return true;
            }

            @Override
            public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) {
                super.onReceivedTouchIconUrl(view, url, precomposed);
            }
        });

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

                if (state == states.EMPTY) {
                    currentUrl = url;
                    setSession(currentUrl);
                    state = states.LOAD_START;
                    handler.sendEmptyMessage(SHOW_PROGRESS);
                }
            }

            @Override
            public void onLoadResource(WebView view, String url) {

                if (!alreadyLoaded
                        && (url.startsWith("http://www.youtube.com/get_video_info?")
                                || url.startsWith("https://www.youtube.com/get_video_info?"))
                        && Build.VERSION.SDK_INT < 11) {
                    try {
                        String path = url.contains("https://www.youtube.com/get_video_info?")
                                ? url.replace("https://www.youtube.com/get_video_info?", "")
                                : url.replace("http://www.youtube.com/get_video_info?", "");

                        String[] parqamValuePairs = path.split("&");

                        String videoId = null;

                        for (String pair : parqamValuePairs) {
                            if (pair.startsWith("video_id")) {
                                videoId = pair.split("=")[1];
                                break;
                            }
                        }

                        if (videoId != null) {
                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"))
                                    .setData(Uri.parse("http://www.youtube.com/watch?v=" + videoId)));
                            needRefresh = true;
                            alreadyLoaded = !alreadyLoaded;

                            return;
                        }
                    } catch (Exception ex) {
                    }
                } else {
                    super.onLoadResource(view, url);
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (hideProgress) {
                    if (TextUtils.isEmpty(WebPlugin.this.url)) {
                        state = states.LOAD_COMPLETE;
                        handler.sendEmptyMessage(HIDE_PROGRESS);
                        super.onPageFinished(view, url);
                    } else {
                        view.loadUrl("javascript:(function(){" + "l=document.getElementById('link');"
                                + "e=document.createEvent('HTMLEvents');" + "e.initEvent('click',true,true);"
                                + "l.dispatchEvent(e);" + "})()");
                        hideProgress = false;
                    }
                } else {
                    state = states.LOAD_COMPLETE;
                    handler.sendEmptyMessage(HIDE_PROGRESS);
                    super.onPageFinished(view, url);
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                if (errorCode == WebViewClient.ERROR_BAD_URL) {
                    startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(url)),
                            DOWNLOAD_REQUEST_CODE);
                }
            }

            @Override
            public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(WebPlugin.this);
                builder.setMessage(R.string.notification_error_ssl_cert_invalid);
                builder.setPositiveButton(WebPlugin.this.getResources().getString(R.string.wp_continue),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                handler.proceed();
                            }
                        });
                builder.setNegativeButton(WebPlugin.this.getResources().getString(R.string.wp_cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                handler.cancel();
                            }
                        });
                final AlertDialog dialog = builder.create();
                dialog.show();
            }

            @Override
            public void onFormResubmission(WebView view, Message dontResend, Message resend) {
                super.onFormResubmission(view, dontResend, resend);
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return super.shouldInterceptRequest(view, request);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                try {

                    if (url.contains("youtube.com/watch")) {
                        if (Build.VERSION.SDK_INT < 11) {
                            try {
                                startActivity(
                                        new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"))
                                                .setData(Uri.parse(url)));
                                return true;
                            } catch (Exception ex) {
                                return false;
                            }
                        } else {
                            return false;
                        }
                    } else if (url.contains("paypal.com")) {
                        if (url.contains("&bn=ibuildapp_SP")) {
                            return false;
                        } else {
                            url = url + "&bn=ibuildapp_SP";

                            webView.loadUrl(url);

                            return true;
                        }
                    } else if (url.contains("sms:")) {
                        try {
                            Intent smsIntent = new Intent(Intent.ACTION_VIEW);
                            smsIntent.setData(Uri.parse(url));
                            startActivity(smsIntent);
                            return true;
                        } catch (Exception ex) {
                            Log.e("", ex.getMessage());
                            return false;
                        }
                    } else if (url.contains("tel:")) {
                        Intent callIntent = new Intent(Intent.ACTION_CALL);
                        callIntent.setData(Uri.parse(url));
                        startActivity(callIntent);
                        return true;
                    } else if (url.contains("mailto:")) {
                        MailTo mailTo = MailTo.parse(url);

                        Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
                        emailIntent.setType("plain/text");
                        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                                new String[] { mailTo.getTo() });

                        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, mailTo.getSubject());
                        emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, mailTo.getBody());
                        WebPlugin.this.startActivity(Intent.createChooser(emailIntent,
                                getString(R.string.romanblack_html_send_email)));
                        return true;
                    } else if (url.contains("rtsp:")) {
                        Uri address = Uri.parse(url);
                        Intent intent = new Intent(Intent.ACTION_VIEW, address);

                        final PackageManager pm = getPackageManager();
                        final List<ResolveInfo> matches = pm.queryIntentActivities(intent, 0);
                        if (matches.size() > 0) {
                            startActivity(intent);
                        } else {
                            Toast.makeText(WebPlugin.this, getString(R.string.romanblack_html_no_video_player),
                                    Toast.LENGTH_SHORT).show();
                        }

                        return true;
                    } else if (url.startsWith("intent:") || url.startsWith("market:")
                            || url.startsWith("col-g2m-2:")) {
                        Intent it = new Intent();
                        it.setData(Uri.parse(url));
                        startActivity(it);

                        return true;
                    } else if (url.contains("//play.google.com/")) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                        return true;
                    } else {
                        if (url.contains("ibuildapp.com-1915109")) {
                            String param = Uri.parse(url).getQueryParameter("widget");
                            finish();
                            if (param != null && param.equals("1001"))
                                com.appbuilder.sdk.android.Statics.launchMain();
                            else if (param != null && !"".equals(param)) {
                                View.OnClickListener widget = Statics.linkWidgets.get(Integer.valueOf(param));
                                if (widget != null)
                                    widget.onClick(view);
                            }
                            return false;
                        }

                        currentUrl = url;
                        setSession(currentUrl);
                        if (!isOnline) {
                            handler.sendEmptyMessage(HIDE_PROGRESS);
                            handler.sendEmptyMessage(STOP_LOADING);
                        } else {
                            String pageType = "application/html";
                            if (!url.contains("vk.com")) {
                                getPageType(url);
                            }
                            if (pageType.contains("application") && !pageType.contains("html")
                                    && !pageType.contains("xml")) {
                                startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(url)),
                                        DOWNLOAD_REQUEST_CODE);
                                return super.shouldOverrideUrlLoading(view, url);
                            } else {
                                view.getSettings().setLoadWithOverviewMode(true);
                                view.getSettings().setUseWideViewPort(true);
                                view.setBackgroundColor(Color.WHITE);
                            }
                        }
                        return false;
                    }

                } catch (Exception ex) { // Error Logging
                    return false;
                }
            }
        });

        handler.sendEmptyMessage(SHOW_PROGRESS);

        new Thread() {
            @Override
            public void run() {

                EntityParser parser;
                if (widget.getPluginXmlData() != null) {
                    if (widget.getPluginXmlData().length() > 0) {
                        parser = new EntityParser(widget.getPluginXmlData());
                    } else {
                        String xmlData = readXmlFromFile(getIntent().getStringExtra("WidgetFile"));
                        parser = new EntityParser(xmlData);
                    }
                } else {
                    String xmlData = readXmlFromFile(getIntent().getStringExtra("WidgetFile"));
                    parser = new EntityParser(xmlData);
                }

                parser.parse();

                url = parser.getUrl();
                html = parser.getHtml();

                if (url.length() > 0 && !isOnline) {
                    handler.sendEmptyMessage(NEED_INTERNET_CONNECTION);
                } else {
                    if (isOnline) {
                    } else {
                        if (html.length() == 0) {
                        }
                    }
                    if (html.length() > 0 || url.length() > 0) {
                        handler.sendEmptyMessageDelayed(SHOW_HTML, 700);
                    } else {
                        handler.sendEmptyMessage(HIDE_PROGRESS);
                        handler.sendEmptyMessage(INITIALIZATION_FAILED);
                    }
                }
            }
        }.start();

    } catch (Exception ex) {
    }
}

From source file:com.ibuildapp.romanblack.CataloguePlugin.ProductDetails.java

/**
 * Initializing user interface/*from  ww  w  .  j a  v a 2s.c om*/
 */
private void initializeUI() {
    setContentView(R.layout.details_layout);
    hideTopBar();

    navBarHolder = (RelativeLayout) findViewById(R.id.navbar_holder);
    List<String> imageUrls = new ArrayList<>();
    imageUrls.add(product.imageURL);
    imageUrls.addAll(product.imageUrls);

    final float density = getResources().getDisplayMetrics().density;
    int topBarHeight = (int) (TOP_BAR_HEIGHT * density);
    TextView apply_button = (TextView) findViewById(R.id.apply_button);
    View basket = findViewById(R.id.basket);
    View bottomSeparator = findViewById(R.id.bottom_separator);
    quantity = (EditText) findViewById(R.id.quantity);

    roundsList = (RecyclerView) findViewById(R.id.details_recyclerview);
    if (imageUrls.size() <= 1)
        roundsList.setVisibility(View.GONE);

    LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);

    roundsList.setLayoutManager(layoutManager);
    pager = (ViewPager) findViewById(R.id.viewpager);

    if (!"".equals(imageUrls.get(0))) {

        final RoundAdapter rAdapter = new RoundAdapter(this, imageUrls);
        roundsList.setAdapter(rAdapter);

        float width = getResources().getDisplayMetrics().widthPixels;
        float height = getResources().getDisplayMetrics().heightPixels;
        height -= 2 * topBarHeight;
        height -= com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.getStatusBarHeight(this);
        pager.getLayoutParams().width = (int) width;
        pager.getLayoutParams().height = (int) height;
        newCurrentItem = 0;
        pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                oldCurrentItem = newCurrentItem;
                newCurrentItem = position;

                rAdapter.setCurrentItem(newCurrentItem);
                rAdapter.notifyItemChanged(newCurrentItem);

                if (oldCurrentItem != -1)
                    rAdapter.notifyItemChanged(oldCurrentItem);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        pager.setPageTransformer(true, new InnerPageTransformer());
        adapter = new DetailsViewPagerAdapter(getSupportFragmentManager(), imageUrls);
        roundsList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int totalWidth = (int) (adapter.getCount() * 21 * density);
                int screenWidth = getResources().getDisplayMetrics().widthPixels;
                int position = parent.getChildAdapterPosition(view);

                if ((totalWidth < screenWidth) && position == 0)
                    outRect.left = (screenWidth - totalWidth) / 2;
            }
        });

        pager.setAdapter(adapter);
    } else {
        roundsList.setVisibility(View.GONE);
        pager.setVisibility(View.GONE);
    }
    buyLayout = (RelativeLayout) findViewById(R.id.details_buy_layout);

    if (product.itemType.equals(ProductItemType.EXTERNAL))
        quantity.setVisibility(View.GONE);
    else
        quantity.setVisibility(View.VISIBLE);

    if (Statics.isBasket) {
        buyLayout.setVisibility(View.VISIBLE);
        onShoppingCartItemAdded();
        apply_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hideKeyboard();
                quantity.setText(StringUtils.isBlank(quantity.getText().toString()) ? "1"
                        : quantity.getText().toString());
                quantity.clearFocus();

                String message = "";
                int quant = Integer.valueOf(quantity.getText().toString());
                List<ShoppingCart.Product> products = ShoppingCart.getProducts();
                int count = 0;

                for (ShoppingCart.Product product : products)
                    count += product.getQuantity();

                try {
                    message = new PluralResources(getResources()).getQuantityString(R.plurals.items_to_cart,
                            count + quant, count + quant);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }

                int index = products.indexOf(new ShoppingCart.Product.Builder().setId(product.id).build());
                ShoppingCart.insertProduct(new ShoppingCart.Product.Builder().setId(product.id)
                        .setQuantity((index == -1 ? 0 : products.get(index).getQuantity()) + quant).build());
                onShoppingCartItemAdded();
                com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.showDialog(ProductDetails.this,
                        R.string.shopping_cart_dialog_title, message, R.string.shopping_cart_dialog_continue,
                        R.string.shopping_cart_dialog_view_cart,
                        new com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.OnDialogButtonClickListener() {
                            @Override
                            public void onPositiveClick(DialogInterface dialog) {
                                dialog.dismiss();
                            }

                            @Override
                            public void onNegativeClick(DialogInterface dialog) {
                                Intent intent = new Intent(ProductDetails.this, ShoppingCartPage.class);
                                ProductDetails.this.startActivity(intent);
                            }
                        });
            }
        });
        if (product.itemType.equals(ProductItemType.EXTERNAL)) {
            basket.setVisibility(View.GONE);
            apply_button.setText(product.itemButtonText);
            apply_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ProductDetails.this, ExternalProductDetailsActivity.class);
                    intent.putExtra("itemUrl", product.itemUrl);
                    startActivity(intent);
                }
            });
        } else {
            basket.setVisibility(View.VISIBLE);
            apply_button.setText(R.string.shopping_cart_add_to_cart);
        }
    } else {
        if (product.itemType.equals(ProductItemType.EXTERNAL))
            buyLayout.setVisibility(View.VISIBLE);
        else
            buyLayout.setVisibility(View.GONE);

        apply_button.setText(R.string.buy_now);
        basket.setVisibility(View.GONE);
        findViewById(R.id.cart_items).setVisibility(View.GONE);
        /*apply_button_padding_left = 0;
        apply_button.setGravity(Gravity.CENTER);
        apply_button.setPadding(apply_button_padding_left, 0, 0, 0);*/

        if (TextUtils.isEmpty(Statics.PAYPAL_CLIENT_ID) || product.price == 0) {
            bottomSeparator.setVisibility(View.GONE);
            apply_button.setVisibility(View.GONE);
            basket.setVisibility(View.GONE);

        } else {
            apply_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    payer.singlePayment(new Payer.Item.Builder().setPrice(product.price)
                            .setCurrencyCode(Payer.CurrencyCode.valueOf(Statics.uiConfig.currency))
                            .setName(product.name).setEndpoint(Statics.ENDPOINT).setAppId(Statics.appId)
                            .setWidgetId(Statics.widgetId).setItemId(product.item_id).build());
                }
            });
        }

        if (product.itemType.equals(ProductItemType.EXTERNAL)) {
            basket.setVisibility(View.GONE);
            apply_button.setText(product.itemButtonText);
            apply_button.setVisibility(View.VISIBLE);
            apply_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ProductDetails.this, ExternalProductDetailsActivity.class);
                    intent.putExtra("itemUrl", product.itemUrl);
                    startActivity(intent);
                }
            });
        }
    }

    backBtn = (LinearLayout) findViewById(R.id.back_btn);
    backBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
    title = (TextView) findViewById(R.id.title_text);
    title.setMaxWidth((int) (screenWidth * 0.55));
    if (category != null && !TextUtils.isEmpty(category.name))
        title.setText(category.name);

    View basketBtn = findViewById(R.id.basket_view_btn);
    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(ProductDetails.this, ShoppingCartPage.class);
            startActivity(intent);
        }
    };
    basketBtn.setOnClickListener(listener);
    View hamburgerView = findViewById(R.id.hamburger_view_btn);
    hamburgerView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            animateRootContainer();
        }
    });
    if (!showSideBar) {
        hamburgerView.setVisibility(View.GONE);
        basketBtn.setVisibility(View.VISIBLE);
        basketBtn.setVisibility(Statics.isBasket ? View.VISIBLE : View.GONE);
        findViewById(R.id.cart_items).setVisibility(View.VISIBLE);
    } else {
        hamburgerView.setVisibility(View.VISIBLE);
        findViewById(R.id.cart_items).setVisibility(View.INVISIBLE);
        basketBtn.setVisibility(View.GONE);
        if (Statics.isBasket)
            shopingCartIndex = setTopBarRightButton(basketBtn, getResources().getString(R.string.shopping_cart),
                    listener);
    }

    productTitle = (TextView) findViewById(R.id.product_title);
    productTitle.setText(product.name);

    product_sku = (TextView) findViewById(R.id.product_sku);

    if (TextUtils.isEmpty(product.sku)) {
        product_sku.setVisibility(View.GONE);
        product_sku.setText("");
    } else {
        product_sku.setVisibility(View.VISIBLE);
        product_sku.setText(getString(R.string.item_sku) + " " + product.sku);
    }

    productDescription = (WebView) findViewById(R.id.product_description);
    productDescription.getSettings().setJavaScriptEnabled(true);
    productDescription.getSettings().setDomStorageEnabled(true);
    productDescription.setWebChromeClient(new WebChromeClient());
    productDescription.setWebViewClient(new WebViewClient() {
        @Override
        public void onLoadResource(WebView view, String url) {
            if (!alreadyLoaded
                    && (url.startsWith("http://www.youtube.com/get_video_info?")
                            || url.startsWith("https://www.youtube.com/get_video_info?"))
                    && Build.VERSION.SDK_INT <= 11) {
                try {
                    String path = url.contains("https://www.youtube.com/get_video_info?")
                            ? url.replace("https://www.youtube.com/get_video_info?", "")
                            : url.replace("http://www.youtube.com/get_video_info?", "");

                    String[] parqamValuePairs = path.split("&");

                    String videoId = null;

                    for (String pair : parqamValuePairs) {
                        if (pair.startsWith("video_id")) {
                            videoId = pair.split("=")[1];
                            break;
                        }
                    }

                    if (videoId != null) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"))
                                .setData(Uri.parse("http://www.youtube.com/watch?v=" + videoId)));

                        alreadyLoaded = !alreadyLoaded;
                    }
                } catch (Exception ex) {
                }
            } else {
                super.onLoadResource(view, url);
            }
        }

        @Override
        public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(ProductDetails.this);
            builder.setMessage(R.string.catalog_notification_error_ssl_cert_invalid);
            builder.setPositiveButton(ProductDetails.this.getResources().getString(R.string.catalog_continue),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            handler.proceed();
                        }
                    });
            builder.setNegativeButton(ProductDetails.this.getResources().getString(R.string.catalog_cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            handler.cancel();
                        }
                    });
            final AlertDialog dialog = builder.create();
            dialog.show();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (url.contains("youtube.com/embed")) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"))
                        .setData(Uri.parse(url)));
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("tel:")) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
                startActivity(intent);

                return true;
            } else if (url.startsWith("mailto:")) {
                Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(url));
                startActivity(intent);

                return true;
            } else if (url.contains("youtube.com")) {
                try {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"))
                            .setData(Uri.parse(url)));

                    return true;
                } catch (Exception ex) {
                    return false;
                }
            } else if (url.contains("goo.gl") || url.contains("maps") || url.contains("maps.yandex")
                    || url.contains("livegpstracks")) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setData(Uri.parse(url)));
                return true;
            } else {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setData(Uri.parse(url)));
                return true;
            }
        }
    });
    productDescription.loadDataWithBaseURL(null, product.description, "text/html", "UTF-8", null);

    productPrice = (TextView) findViewById(R.id.product_price);
    productPrice.setVisibility(
            "0.00".equals(String.format(Locale.US, "%.2f", product.price)) ? View.GONE : View.VISIBLE);
    String result = com.ibuildapp.romanblack.CataloguePlugin.utils.Utils
            .currencyToPosition(Statics.uiConfig.currency, product.price);
    if (result.contains(getResources().getString(R.string.rest_number_pattern)))
        result = result.replace(getResources().getString(R.string.rest_number_pattern), "");
    productPrice.setText(result);

    likeCount = (TextView) findViewById(R.id.like_count);
    likeImage = (ImageView) findViewById(R.id.like_image);

    if (!TextUtils.isEmpty(product.imageURL)) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String token = FacebookAuthorizationActivity.getFbToken(
                        com.appbuilder.sdk.android.Statics.FACEBOOK_APP_ID,
                        com.appbuilder.sdk.android.Statics.FACEBOOK_APP_SECRET);
                if (TextUtils.isEmpty(token))
                    return;

                List<String> urls = new ArrayList<String>();
                urls.add(product.imageURL);
                final Map<String, String> res = FacebookAuthorizationActivity.getLikesForUrls(urls, token);
                if (res != null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            likeCount.setText(res.get(product.imageURL));
                        }
                    });
                }
                Log.e("", "");
            }
        }).start();
    }

    shareBtn = (LinearLayout) findViewById(R.id.share_button);
    if (Statics.uiConfig.showShareButton)
        shareBtn.setVisibility(View.VISIBLE);
    else
        shareBtn.setVisibility(View.GONE);

    shareBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            showDialogSharing(new DialogSharing.Configuration.Builder()
                    .setFacebookSharingClickListener(new DialogSharing.Item.OnClickListener() {
                        @Override
                        public void onClick() {
                            // checking Internet connection
                            if (!Utils.networkAvailable(ProductDetails.this))
                                Toast.makeText(ProductDetails.this,
                                        getResources().getString(R.string.alert_no_internet),
                                        Toast.LENGTH_SHORT).show();
                            else {
                                if (Authorization
                                        .getAuthorizedUser(Authorization.AUTHORIZATION_TYPE_FACEBOOK) != null) {
                                    shareFacebook();
                                } else {
                                    Authorization.authorize(ProductDetails.this,
                                            FACEBOOK_AUTHORIZATION_ACTIVITY,
                                            Authorization.AUTHORIZATION_TYPE_FACEBOOK);
                                }
                            }
                        }
                    }).setTwitterSharingClickListener(new DialogSharing.Item.OnClickListener() {
                        @Override
                        public void onClick() {
                            // checking Internet connection
                            if (!Utils.networkAvailable(ProductDetails.this))
                                Toast.makeText(ProductDetails.this,
                                        getResources().getString(R.string.alert_no_internet),
                                        Toast.LENGTH_SHORT).show();
                            else {
                                if (Authorization
                                        .getAuthorizedUser(Authorization.AUTHORIZATION_TYPE_TWITTER) != null) {
                                    shareTwitter();
                                } else {
                                    Authorization.authorize(ProductDetails.this, TWITTER_AUTHORIZATION_ACTIVITY,
                                            Authorization.AUTHORIZATION_TYPE_TWITTER);
                                }
                            }
                        }
                    }).setEmailSharingClickListener(new DialogSharing.Item.OnClickListener() {
                        @Override
                        public void onClick() {
                            Intent intent = chooseEmailClient();
                            intent.setType("text/html");

                            // *************************************************************************************************
                            // preparing sharing message
                            String downloadThe = getString(R.string.directoryplugin_email_download_this);
                            String androidIphoneApp = getString(
                                    R.string.directoryplugin_email_android_iphone_app);
                            String postedVia = getString(R.string.directoryplugin_email_posted_via);
                            String foundThis = getString(R.string.directoryplugin_email_found_this);

                            // prepare content
                            String downloadAppUrl = String.format(
                                    "http://%s/projects.php?action=info&projectid=%s",
                                    com.appbuilder.sdk.android.Statics.BASE_DOMEN, Statics.appId);

                            String adPart = String.format(
                                    downloadThe + " %s " + androidIphoneApp + ": <a href=\"%s\">%s</a><br>%s",
                                    Statics.appName, downloadAppUrl, downloadAppUrl,
                                    postedVia + " <a href=\"http://ibuildapp.com\">www.ibuildapp.com</a>");

                            // content part
                            String contentPath = String.format(
                                    "<!DOCTYPE html><html><body><b>%s</b><br><br>%s<br><br>%s</body></html>",
                                    product.name, product.description,
                                    com.ibuildapp.romanblack.CataloguePlugin.Statics.hasAd ? adPart : "");

                            contentPath = contentPath.replaceAll("\\<img.*?>", "");

                            // prepare image to attach
                            // FROM ASSETS
                            InputStream stream = null;
                            try {
                                if (!TextUtils.isEmpty(product.imageRes)) {
                                    stream = manager.open(product.imageRes);

                                    String fileName = inputStreamToFile(stream);
                                    File copyTo = new File(fileName);
                                    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(copyTo));
                                }
                            } catch (IOException e) {
                                // from cache
                                File copyTo = new File(product.imagePath);
                                if (copyTo.exists()) {
                                    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(copyTo));
                                }
                            }

                            intent.putExtra(Intent.EXTRA_SUBJECT, product.name);
                            intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(contentPath));
                            startActivity(intent);
                        }
                    }).build());

            //                openOptionsMenu();
        }
    });

    likeBtn = (LinearLayout) findViewById(R.id.like_button);
    if (Statics.uiConfig.showLikeButton)
        likeBtn.setVisibility(View.VISIBLE);
    else
        likeBtn.setVisibility(View.GONE);

    likeBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (Utils.networkAvailable(ProductDetails.this)) {
                if (!TextUtils.isEmpty(product.imageURL)) {
                    if (Authorization.isAuthorized(Authorization.AUTHORIZATION_TYPE_FACEBOOK)) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {

                                List<String> userLikes = null;
                                try {
                                    userLikes = FacebookAuthorizationActivity.getUserOgLikes();
                                    for (String likeUrl : userLikes) {
                                        if (likeUrl.compareToIgnoreCase(product.imageURL) == 0) {
                                            likedbyMe = true;
                                            break;
                                        }
                                    }

                                    if (!likedbyMe) {
                                        if (FacebookAuthorizationActivity.like(product.imageURL)) {
                                            String likeCountStr = likeCount.getText().toString();
                                            try {
                                                final int res = Integer.parseInt(likeCountStr);

                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        likeCount.setText(Integer.toString(res + 1));
                                                        enableLikeButton(false);
                                                        Toast.makeText(ProductDetails.this,
                                                                getString(R.string.like_success),
                                                                Toast.LENGTH_SHORT).show();
                                                    }
                                                });
                                            } catch (NumberFormatException e) {
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        Toast.makeText(ProductDetails.this,
                                                                getString(R.string.like_error),
                                                                Toast.LENGTH_SHORT).show();
                                                    }
                                                });
                                            }
                                        }
                                    } else {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                enableLikeButton(false);
                                                Toast.makeText(ProductDetails.this,
                                                        getString(R.string.already_liked), Toast.LENGTH_SHORT)
                                                        .show();
                                            }
                                        });
                                    }
                                } catch (FacebookAuthorizationActivity.FacebookNotAuthorizedException e) {
                                    if (!Utils.networkAvailable(ProductDetails.this)) {
                                        Toast.makeText(ProductDetails.this,
                                                getString(R.string.alert_no_internet), Toast.LENGTH_SHORT)
                                                .show();
                                        return;
                                    }
                                    Authorization.authorize(ProductDetails.this, AUTHORIZATION_FB,
                                            Authorization.AUTHORIZATION_TYPE_FACEBOOK);
                                } catch (FacebookAuthorizationActivity.FacebookAlreadyLiked facebookAlreadyLiked) {
                                    facebookAlreadyLiked.printStackTrace();
                                }

                            }
                        }).start();
                    } else {
                        if (!Utils.networkAvailable(ProductDetails.this)) {
                            Toast.makeText(ProductDetails.this, getString(R.string.alert_no_internet),
                                    Toast.LENGTH_SHORT).show();
                            return;
                        }
                        Authorization.authorize(ProductDetails.this, AUTHORIZATION_FB,
                                Authorization.AUTHORIZATION_TYPE_FACEBOOK);
                    }
                } else
                    Toast.makeText(ProductDetails.this, getString(R.string.nothing_to_like), Toast.LENGTH_SHORT)
                            .show();
            } else
                Toast.makeText(ProductDetails.this, getString(R.string.alert_no_internet), Toast.LENGTH_SHORT)
                        .show();
        }
    });

    if (TextUtils.isEmpty(product.imageURL)) {
        enableLikeButton(false);
    } else {
        if (Authorization.isAuthorized(Authorization.AUTHORIZATION_TYPE_FACEBOOK)) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    List<String> userLikes = null;
                    try {
                        userLikes = FacebookAuthorizationActivity.getUserOgLikes();
                        for (String likeUrl : userLikes) {
                            if (likeUrl.compareToIgnoreCase(product.imageURL) == 0) {
                                likedbyMe = true;
                                break;
                            }
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                enableLikeButton(!likedbyMe);
                            }
                        });
                    } catch (FacebookAuthorizationActivity.FacebookNotAuthorizedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    // product bitmap rendering
    image = (AlphaImageView) findViewById(R.id.product_image);
    image.setVisibility(View.GONE);
    if (!TextUtils.isEmpty(product.imageRes)) {
        try {
            InputStream input = manager.open(product.imageRes);
            Bitmap btm = BitmapFactory.decodeStream(input);
            if (btm != null) {
                int ratio = btm.getWidth() / btm.getHeight();
                image.setLayoutParams(new LinearLayout.LayoutParams(screenWidth, screenWidth / ratio));

                image.setImageBitmapWithAlpha(btm);
                //image.setImageBitmap(btm);
                return;
            }
        } catch (IOException e) {
        }
    }

    if (!TextUtils.isEmpty(product.imagePath)) {
        Bitmap btm = BitmapFactory.decodeFile(product.imagePath);
        if (btm != null) {
            if (btm.getWidth() != 0 && btm.getHeight() != 0) {
                float ratio = (float) btm.getWidth() / (float) btm.getHeight();
                image.setLayoutParams(new LinearLayout.LayoutParams(screenWidth, (int) (screenWidth / ratio)));
                image.setImageBitmapWithAlpha(btm);
                image.setVisibility(View.GONE);
                return;
            }
        }
    }

    if (!TextUtils.isEmpty(product.imageURL)) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                product.imagePath = com.ibuildapp.romanblack.CataloguePlugin.utils.Utils
                        .downloadFile(product.imageURL);
                if (!TextUtils.isEmpty(product.imagePath)) {
                    SqlAdapter.updateProduct(product);
                    final Bitmap btm = BitmapFactory.decodeFile(product.imagePath);

                    if (btm != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (btm.getWidth() != 0 && btm.getHeight() != 0) {
                                    float ratio = (float) btm.getWidth() / (float) btm.getHeight();
                                    image.setLayoutParams(new LinearLayout.LayoutParams(screenWidth,
                                            (int) (screenWidth / ratio)));
                                    image.setImageBitmapWithAlpha(btm);
                                    image.setVisibility(View.GONE);
                                }
                            }
                        });
                    }
                }
            }
        }).start();
    }

    image.setVisibility(View.GONE);
}