Example usage for java.lang NoSuchMethodException printStackTrace

List of usage examples for java.lang NoSuchMethodException printStackTrace

Introduction

In this page you can find the example usage for java.lang NoSuchMethodException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.jaspersoft.studio.server.protocol.restv2.RestV2ConnectionJersey.java

private CookieStore getCookieStore() {
    if (cookieStore == null) {
        Connector c = ((ClientConfig) target.getConfiguration()).getConnector();

        try {/*from w  w  w  .  j a v  a2 s . c  o m*/
            Method m = c.getClass().getMethod("getCookieStore", null);
            if (m != null)
                m.setAccessible(true);
            cookieStore = (CookieStore) m.invoke(c, null);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    return cookieStore;
}

From source file:org.objectweb.proactive.core.body.ft.protocols.cic.managers.FTManagerCIC.java

@Override
public synchronized int onServeRequestBefore(Request request) {
    if (multiactiveLogger.isDebugEnabled()) {
        multiactiveLogger.debug("#onServeRequestBefore " + request.getMethodName());
    }//from w  w  w . j  ava2 s . c o  m
    if (!request.getMethodName().equals(FTManager.CHECKPOINT_METHOD_NAME)) {
        boolean checkpoint = false;
        // checkpoint if needed
        if (this.haveToCheckpoint()) {
            int gap = this.nextMax - this.checkpointIndex;
            if (nbEnqueuedCheckpoints.get() < gap || (gap < 1 && nbEnqueuedCheckpoints.get() < 1)) {
                checkpoint = true;
                // we will checkpoint, so current request service is postponed
                synchronized (this.owner.getRequestQueue()) {
                    this.owner.getRequestQueue().addToFrontWithoutNotif(request);
                    do {
                        // Request does not need to be specified since it is in queue already
                        try {
                            this.owner.getRequestQueue()
                                    .addToFront(new RequestImpl(new MethodCall(
                                            this.getClass().getDeclaredMethod(FTManager.CHECKPOINT_METHOD_NAME,
                                                    new Class<?>[] { Request.class }),
                                            null, new Object[] { null }), true));
                            nbEnqueuedCheckpoints.incrementAndGet();
                        } catch (NoSuchMethodException e) {
                            multiactiveLogger.error("FTManager does not have " + ""
                                    + FTManager.CHECKPOINT_METHOD_NAME + " request any more. Aborting.");
                        } catch (SecurityException e) {
                            e.printStackTrace();
                        }
                        gap = gap - 1;
                    } while (gap > 0);
                }
            }
        }
        // update the last served request index only if needed
        if (FTManagerCIC.isOCEnable) {
            MessageInfo mi = request.getMessageInfo();
            if (mi != null) {
                long requestIndex = ((MessageInfoCIC) (mi)).positionInHistory;
                if (this.lastServedRequestIndex.getValue() < requestIndex) {
                    this.lastServedRequestIndex.setValue(requestIndex);
                }
            }
        }
        // inform caller that current request service must be postponed 
        if (checkpoint) {
            return FTManager.CHECKPOINT_CODE;
        }
    }
    return 0;
}

From source file:com.alibaba.dubboadmin.web.mvc.RouterController.java

@RequestMapping("/governance/applications/{app}/services/{service}/{type}/{id}/{action}")
public String appActionWithIdandAction(@PathVariable("app") String app, @PathVariable("service") String service,
        @PathVariable("type") String type, @PathVariable("id") String id, @PathVariable("action") String action,
        HttpServletRequest request, HttpServletResponse response, Model model) {
    if (app != null) {
        model.addAttribute("app", app);
    }//from  w  ww  .j  a  va 2  s  .  co m
    model.addAttribute("service", service);
    String name = WebConstants.mapper.get(type);
    if (name != null) {
        Object controller = SpringUtil.getBean(name);
        if (controller != null) {
            try {
                Object result = null;
                if (StringUtils.isNumeric(id)) {
                    //single id
                    Method m = null;
                    try {
                        m = controller.getClass().getDeclaredMethod(action, Long.class,
                                HttpServletRequest.class, HttpServletResponse.class, Model.class);
                        result = m.invoke(controller, Long.valueOf(id), request, response, model);
                    } catch (NoSuchMethodException e) {
                        m = controller.getClass().getDeclaredMethod(action, Long[].class,
                                HttpServletRequest.class, HttpServletResponse.class, Model.class);
                        result = m.invoke(controller, new Long[] { Long.valueOf(id) }, request, response,
                                model);

                    }
                } else {
                    //id array
                    String[] array = id.split(",");
                    Long[] ids = new Long[array.length];
                    for (int i = 0; i < array.length; i++) {
                        ids[i] = Long.valueOf(array[i]);
                    }

                    Method m = controller.getClass().getDeclaredMethod(action, Long[].class,
                            HttpServletRequest.class, HttpServletResponse.class, Model.class);

                    result = m.invoke(controller, ids, request, response, model);
                }
                return (String) result;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return "";

}

From source file:hu.sztaki.lpds.pgportal.portlets.asm.ClientError.java

/**
 * Handling generic actions// w w w. ja  v a  2  s.c o m
 */
public void processAction(ActionRequest request, ActionResponse response) throws PortletException {
    asm_service.init();

    System.out.println("processaction called..." + selected_wf);
    String action = "";
    action = request.getParameter("action");

    boolean isMultipart = PortletFileUpload.isMultipartContent(request);
    if (isMultipart) {

        doUploadLigands(request, response);
        //       doUpload(request,response);
        /*
                 // PARSE MULTIPART HTML POST
                 Hashtable<String,String> itemParameters=new Hashtable<String, String>();
                 List<FileItem> items=null;
                
                 ActionRequest temp_req=request;
                 try {
        items = new PortletFileUpload(new DiskFileItemFactory()).parseRequest(temp_req);
                 } catch (FileUploadException ex) {
        Logger.getLogger(ASM_SamplePortlet.class.getName()).log(Level.SEVERE, null, ex);
                 }
                
                 for (FileItem item : items) {
        if (item.isFormField()) {
            String fieldname = item.getFieldName();
            String fieldvalue = item.getString();
            itemParameters.put(fieldname, fieldvalue);
        }
                 }
                 action=itemParameters.get("action");
                 if (action.equals("doUpload"))
                 {
                    // doUpload(request,response);
                 }
                 if (action.equals("doUploadLigands"))
                 {
                    // doUploadLigands(request,response);
                 }
             */
        action = null;

    }
    if ((request.getParameter("action") != null) && (!request.getParameter("action").equals(""))) {
        action = request.getParameter("action");
    }
    System.out.println("*************" + action + "::" + request.getParameter("action"));
    if (action != null) {
        try {
            Method method = this.getClass().getMethod(action,
                    new Class[] { ActionRequest.class, ActionResponse.class });
            method.invoke(this, new Object[] { request, response });
        } catch (NoSuchMethodException e) {
            System.out.println("-----------------------No such method");//+(""+request.getAttribute(SportletProperties.ACTION_EVENT)).split("=")[1]);
        } catch (IllegalAccessException e) {
            System.out.println("----------------------Illegal access");
        } catch (InvocationTargetException e) {
            System.out.println("-------------------Invoked function failed");
            e.printStackTrace();
        }
    } else {
        System.out.println("[ERROR] Wrong request format");
    }

}

From source file:org.cowboycoders.cyclismo.turbo.TurboService.java

private synchronized void updateLocation(LatLongAlt pos) {
    try {// w w  w . java  2  s . c om
        float locSpeed = (float) (lastRecordedSpeed / UnitConversions.MS_TO_KMH);
        final long timestamp = System.currentTimeMillis();
        Log.v(TAG, "location timestamp: " + timestamp);
        Location loc = new Location(MOCK_LOCATION_PROVIDER);
        Log.d(TAG, "alt: " + pos.getAltitude());
        Log.d(TAG, "lat: " + pos.getLatitude());
        Log.d(TAG, "long: " + pos.getLongitude());
        loc.setLatitude(pos.getLatitude());
        loc.setLongitude(pos.getLongitude());
        loc.setAltitude(pos.getAltitude());
        // TODO(dszumski) one possible way to correct
        // long timeCorrection = (long) (1000.0 * (delta / lastRecordedSpeed));
        // loc.setTime(timestamp - timeCorrection);
        loc.setTime(timestamp);
        loc.setSpeed(locSpeed);
        loc.setAccuracy(gpsAccuracy);
        Method locationJellyBeanFixMethod = null;
        try {
            locationJellyBeanFixMethod = Location.class.getMethod("makeComplete");
        } catch (NoSuchMethodException e) {
            // ignore
        }
        if (locationJellyBeanFixMethod != null) {
            locationJellyBeanFixMethod.invoke(loc);
        }
        unpauseRecording(); // automatically resume on location updates
        broadcastLocation(loc);
        Log.d(TAG, "updated location");
    } catch (SecurityException e) {
        // is this possible now we aren't using mock locations?
        handleException(e, "Error updating location", true, NOTIFCATION_ID_STARTUP);
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

From source file:com.mantz_it.rfanalyzer.ui.activity.MainActivity.java

/**
 * Reflection-based source settings updater
 *
 * @param clazz desired class of source//from  w w w .ja  v a 2  s .  com
 * @return current source with updated settings, or new source if current source type isn't instance of desired source.
 */
protected void updateSourcePreferences(final Class<?> clazz) {
    // if src is of desired class -- just update
    if (clazz.isInstance(this.source)) {
        setSource(this.source.updatePreferences(this, preferences));
        analyzerSurface.setSource(this.source);
    } else {
        // create new
        this.source.close();
        final String msg;
        try {
            // we can't force sources to implement constructor with needed parameters,
            // to drop need of tracking all sources that could be added later just use reflection
            // to call constructor with current Context and SharedPreferences and let source configure itself
            Constructor ctor = clazz.getDeclaredConstructor(Context.class, SharedPreferences.class);
            ctor.setAccessible(true);
            setSource((IQSource) ctor.newInstance(this, preferences));
            analyzerSurface.setSource(this.source);
            return;
        } catch (NoSuchMethodException e) {
            Log.e(LOGTAG, "updateSourcePreferences: "
                    + (msg = "selected source doesn't have constructor with demanded parameters (Context, SharedPreferences)"));
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            Log.e(LOGTAG, "updateSourcePreferences: "
                    + (msg = "selected source doesn't have accessible constructor with demanded parameters (Context, SharedPreferences)"));
            e.printStackTrace();
        } catch (InstantiationException e) {
            Log.e(LOGTAG, "updateSourcePreferences: "
                    + (msg = "selected source doesn't have accessible for MainActivity constructor with demanded parameters (Context, SharedPreferences)"));
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            Log.e(LOGTAG, "updateSourcePreferences: "
                    + (msg = "source's constructor thrown exception: " + e.getMessage()));
            e.printStackTrace();
        }
        stopAnalyzer();
        this.runOnUiThread(
                () -> toaster.showLong("Error with instantiating source [" + clazz.getName() + "]: "));
        setSource(null);
    }
}

From source file:br.gov.jfrj.siga.vraptor.ExDocumentoController.java

@SuppressWarnings("rawtypes")
private void obterMetodoPorString(final String metodo, final ExDocumento doc)
        throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    if (metodo != null) {
        final Class[] classes = new Class[] { ExDocumento.class };

        Method method;// w w  w .j a v a2  s  .com
        try {
            method = Ex.getInstance().getBL().getClass().getDeclaredMethod(metodo, classes);
        } catch (NoSuchMethodException e1) {
            e1.printStackTrace();
            return;
        }
        method.invoke(Ex.getInstance().getBL(), new Object[] { doc });
    }
}

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

/**
 * Initializing user interface/*  w ww .  j a va  2s.  c o m*/
 */
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);
}

From source file:com.alibaba.android.layoutmanager.ExposeLinearLayoutManagerEx.java

/**
 * @param context       Current context, will be used to access resources.
 * @param orientation   Layout orientation. Should be {@link #HORIZONTAL} or {@link
 *                      #VERTICAL}.//from  www.j  a va  2s.  com
 * @param reverseLayout When set to true, layouts from end to start.
 */
public ExposeLinearLayoutManagerEx(Context context, int orientation, boolean reverseLayout) {
    super(context, orientation, reverseLayout);
    mAnchorInfo = new AnchorInfo();
    setOrientation(orientation);
    setReverseLayout(reverseLayout);
    mChildHelperWrapper = new ChildHelperWrapper(this);

    try {
        mEnsureLayoutStateMethod = LinearLayoutManager.class.getDeclaredMethod("ensureLayoutState");
        mEnsureLayoutStateMethod.setAccessible(true);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    try {
        // FIXME in the future
        Method setItemPrefetchEnabledMethod = RecyclerView.LayoutManager.class
                .getDeclaredMethod("setItemPrefetchEnabled", boolean.class);
        if (setItemPrefetchEnabledMethod != null) {
            setItemPrefetchEnabledMethod.invoke(this, false);
        }
    } catch (NoSuchMethodException e) {
        /* this method is added in 25.1.0, official release still has bug, see
         * https://code.google.com/p/android/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Status%20Priority%20Owner%20Summary%20Stars%20Reporter%20Opened&groupby=&sort=&id=230295
         **/
    } catch (InvocationTargetException e) {
    } catch (IllegalAccessException e) {
    }
    //        setItemPrefetchEnabled(false);
}

From source file:com.snipme.record.Record.java

/**
 * Creates a JSONObject that represents a File from the Uri
 *
 * @param data the Uri of the audio/image/video
 * @return a JSONObject that represents a File
 * @throws IOException/*from w ww . ja  v a  2  s .c o m*/
 */
private JSONObject createMediaFile(Uri data) {
    File fp = webView.getResourceApi().mapUriToFile(data);
    JSONObject obj = new JSONObject();

    Class webViewClass = webView.getClass();
    PluginManager pm = null;
    try {
        Method gpm = webViewClass.getMethod("getPluginManager");
        pm = (PluginManager) gpm.invoke(webView);
    } catch (NoSuchMethodException e) {
    } catch (IllegalAccessException e) {
    } catch (InvocationTargetException e) {
    }
    if (pm == null) {
        try {
            Field pmf = webViewClass.getField("pluginManager");
            pm = (PluginManager) pmf.get(webView);
        } catch (NoSuchFieldException e) {
        } catch (IllegalAccessException e) {
        }
    }
    FileUtils filePlugin = (FileUtils) pm.getPlugin("File");
    LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(fp.getAbsolutePath());

    try {
        // File properties
        obj.put("name", fp.getName());
        obj.put("fullPath", fp.toURI().toString());
        if (url != null) {
            obj.put("localURL", url.toString());
        }
        // Because of an issue with MimeTypeMap.getMimeTypeFromExtension() all .3gpp files
        // are reported as video/3gpp. I'm doing this hacky check of the URI to see if it
        // is stored in the audio or video content store.
        if (fp.getAbsoluteFile().toString().endsWith(".3gp")
                || fp.getAbsoluteFile().toString().endsWith(".3gpp")) {
            if (data.toString().contains("/audio/")) {
                obj.put("type", AUDIO_3GPP);
            } else {
                obj.put("type", VIDEO_3GPP);
            }
        } else {
            obj.put("type", FileHelper.getMimeType(Uri.fromFile(fp), cordova));
        }

        obj.put("lastModifiedDate", fp.lastModified());
        obj.put("size", fp.length());
    } catch (JSONException e) {
        // this will never happen
        e.printStackTrace();
    }
    return obj;
}