Example usage for java.lang String compareToIgnoreCase

List of usage examples for java.lang String compareToIgnoreCase

Introduction

In this page you can find the example usage for java.lang String compareToIgnoreCase.

Prototype

public int compareToIgnoreCase(String str) 

Source Link

Document

Compares two strings lexicographically, ignoring case differences.

Usage

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

/**
 * Initializing user interface/*from   w w  w  .j a va2 s.co 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.inverse2.ajaxtoaster.AjaxToasterServlet.java

/**
 * Processes requests from the client for both HTTP <code>GET</code>
 * and <code>POST</code> methods.
 *
 * @param request servlet request//www .j  av  a2 s.com
 * @param response servlet response
 */
protected void processRequest(String requestType, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String responseFormat = response_format_prop;
    // flags that the user has not set the response format
    boolean defaultResponseFormat = response_format_prop.equals("XML") ? true : false;
    ServiceOperationInterface service = null;
    String callbackFunction = null;

    log.info(">> Start processRequest(" + requestType + ") at " + new Date());

    try {
        ServletContext context = getServletContext();

        String scriptName = request.getParameter(PARAM_SCRIPTNAME1); // look for "service=xxxx"
        String contextPath = "";

        /* If the service parameter is not specified then use the URL to get the service name... */

        if (scriptName == null) {
            scriptName = request.getPathInfo();
            contextPath = request.getContextPath();

            /*
            //Put this in for debugging...
            System.out.println("****** -> pathInfo       [" + request.getPathInfo() + "]");
            System.out.println("****** -> pathTranslated [" + request.getPathTranslated() + "]");
            System.out.println("****** -> contextPath    [" + request.getContextPath() + "]");
            System.out.println("****** -> localAddr      [" + request.getLocalAddr() + "]");
            System.out.println("****** -> localName      [" + request.getLocalName() + "]");
            System.out.println("****** -> requestURI     [" + request.getRequestURI() + "]");//*****
            System.out.println("****** -> servletPath    [" + request.getServletPath() + "]");
            */

            if (scriptName == null) {
                scriptName = "UNSPECIFIED_SERVICE";
            }
        }

        /* See if the URI is mapped to another service... */
        ServiceMapping serviceMapping;
        serviceMapping = serviceMapper.getURIMapping(""/*contextPath*/, scriptName, requestType);

        if (serviceMapping != null) {
            log.info("Redirect URI to [" + serviceMapping.getServiceName() + "]");

            scriptName = serviceMapping.getServiceName();

            /* If the URI has been mapped then see if the "Accept" header specifies the return type required... */
            String accept = request.getHeader("Accept");

            if (accept.indexOf("text/xml") != -1) {
                responseFormat = "XML";
                defaultResponseFormat = false;
            }
            if (accept.indexOf("text/json") != -1) {
                responseFormat = "JSON";
                defaultResponseFormat = false;
            }

        }

        if (scriptName.startsWith("/")) {
            scriptName = scriptName.substring(1, scriptName.length());
        }

        /**
         * If "log" service invoked then process it...
         */
        if (scriptName.equals("log")) {
            returnHTMLLog(response);
            return;
        }

        /**
         * If "health" service invoked then process it...
         */
        if (scriptName.equals("health")) {
            returnHealth(response);
            return;
        }

        /* Check for the flag to return XML or JSON objects... */

        if (request.getParameter(PARAM_RETURNXML) != null) {
            println(">> Servlet will return XML object.");
            responseFormat = "XML";
            defaultResponseFormat = false;
        } else if (request.getParameter(PARAM_RETURNJSON) != null) {
            println(">> Servlet will return XML object.");
            responseFormat = "JSON";
            defaultResponseFormat = false;
        } else if (request.getParameter(PARAM_RETURNRAW) != null) {
            println(">> Servlet will return raw text object.");
            responseFormat = "RAW";
            defaultResponseFormat = false;
        }

        /* Check for the callback function parameter... */

        callbackFunction = request.getParameter(PARAM_CALLBACK);

        /**
         * Check to see if the client wants a "Service Mapping Description" (SMD) for the 'service'...
         */

        if (request.getParameter(PARAM_SMD) != null) {

            log.info("Client wants SMD for [" + scriptName + "]");

            try {
                ServicePool pool = null;
                Map availableServices = null;
                ServiceMappingDescription smd = null;
                ServiceScriptPool serviceScriptPool = null;
                String serviceScriptName = null;
                String returnString = null;

                pool = (ServicePool) context.getAttribute(ATTRIB_SERVICE_POOL);
                availableServices = pool.getAvailableServices();
                smd = new ServiceMappingDescription(request.getRequestURL().toString(),
                        request.getRequestURL().toString() + "?smd", null);

                for (Iterator it = availableServices.values().iterator(); it.hasNext();) {

                    serviceScriptPool = (ServiceScriptPool) it.next();

                    serviceScriptName = serviceScriptPool.getPoolName();

                    /**
                     * If the service script name begins with the passed in script name then add it to the
                     * service mapping description...
                     */

                    log.debug("scriptName = [" + scriptName + "], serviceScriptName = [" + serviceScriptName
                            + "]");

                    if (scriptName.equals("") || serviceScriptName.startsWith(scriptName + "/")
                            || serviceScriptName.equals(scriptName)) {

                        smd.addOperation(serviceScriptName);

                        service = serviceScriptPool.getService();

                        smd.setOperationDescription(service.getScriptDescription());
                        smd.setOperationTransport(service.getHTTPMethods());
                        smd.setOperationEnvelope("URL");
                        smd.setOperationContentType(service.getResponseFormat());
                        smd.setOperationParameters(serviceScriptPool.getServiceParameters());
                        smd.setOperationReturns(serviceScriptPool.getServiceReturns());

                    }

                }

                returnString = smd.getSMDJSONString();

                writeResponse(returnString, "JSONRAW", callbackFunction, response);

            } catch (Exception ex) {
                log.error("Exception getting SMD: " + ex.toString());
                ex.printStackTrace();
            }

            return;
        }

        /**
         * Get the service and run it...
         */

        println(">> Client wants to invoke the service [" + scriptName + "]");

        try {
            service = getServiceScript(scriptName);
        } catch (Exception ex) {
            errorResponse(response,
                    "Could not get an instance of the service [" + scriptName + "]: " + ex.toString(),
                    responseFormat, callbackFunction);
            return;
        }

        if (service == null) {
            errorResponse(response, "Service [" + scriptName + "] not found.", responseFormat,
                    callbackFunction);
            return;
        }

        /**
         * If the script exists in the toaster pool then invoke it
         */

        println(">> Checking login required");

        try {
            if (service.getLoginRequired().equals("true")) {

                HttpSession session = request.getSession(false);
                Object loggedIn = null;

                if (session != null) {
                    loggedIn = session.getAttribute(ATTRIB_LOGGED_IN);
                }

                log.trace("**** SESSION   = " + session);
                log.trace("**** Logged In = " + loggedIn);

                if (session == null || loggedIn == null || loggedIn.equals("true") == false) {
                    errorResponse(response,
                            "The service " + scriptName + " requires you to be logged in to run it.",
                            responseFormat, callbackFunction);
                    freeServiceScript(service);
                    return;
                }

                /* Check that the logged in user is authorised to run the service... */

                String validUsers;
                String[] validUsersArray;
                String user;
                String loggedInUser;
                boolean validUser;

                validUsers = service.getValidUsers();
                validUsersArray = validUsers.split("[,]");

                loggedInUser = (String) session.getAttribute(ATTRIB_LOGGED_IN_USER);

                validUser = false;

                for (int idx = 0; idx < validUsersArray.length; idx++) {
                    user = validUsersArray[idx].trim();
                    if (user.equals("*")) {
                        validUser = true;
                        break;
                    }
                    if (user.equals(loggedInUser)) {
                        validUser = true;
                        break;
                    }
                }

                if (validUser == false) {
                    log.error("The user [" + loggedInUser + "] is not authorised to invoke the service ["
                            + scriptName + "]");
                    errorResponse(response, "You are not authorised to invoke the service [" + scriptName + "]",
                            responseFormat, callbackFunction);
                    freeServiceScript(service);
                    return;
                }

            }
        } catch (Exception ex) {
            errorResponse(response, "Could not check if login required for this service. " + ex.toString(),
                    responseFormat, callbackFunction);
            return;
        }

        boolean scriptInputSet = false;

        /*
         * Go through the set of parameters passed to us and set them up in the service instance...
         */
        for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {

            String parameterName = (String) e.nextElement();

            if (parameterName.equals(PARAM_SCRIPTNAME1) == true
                    || parameterName.equals(PARAM_SCRIPTNAME2) == true
                    || parameterName.equals(PARAM_RETURNXML) == true
                    || parameterName.equals(PARAM_RETURNJSON) == true
                    || parameterName.equals(PARAM_CALLBACK) == true) {
                continue;
            }

            String parameterValue = (String) request.getParameter(parameterName);

            if (parameterName.equals(PARAM_INPUTXML) == true) {
                service.setInputXML(parameterValue);
                scriptInputSet = true;
                continue;
            }

            if (parameterName.equals(PARAM_INPUTJSON) == true) {

                try {
                    // The input object is a JSON object... so convert it into XML...
                    JSONObject json = new JSONObject(parameterValue);

                    service.setInputXML(XML.toString(json));
                    scriptInputSet = true;
                    println("JSON converted to \n" + XML.toString(json));
                } catch (JSONException ex) {
                    errorResponse(response,
                            "Could not create JSON object." + ex.toString() + ". " + ex.getStackTrace(),
                            responseFormat, callbackFunction);
                    freeServiceScript(service);
                    return;
                }
                continue;
            }

            /* Any leftover parameters are query parameters. */
            println("Query Parameter found... Setting " + parameterName + " to " + parameterValue);
            service.setParameter(parameterName, parameterValue);

        } // End of parameters for loop

        /* If there is content in the request then, unless we have already set it, this is the input to the script... */

        if (requestType.equals("POST") && scriptInputSet == false) {

            try {
                BufferedReader reader = request.getReader();
                StringBuffer buf = new StringBuffer();
                String line;
                String postData;

                while ((line = reader.readLine()) != null) {
                    buf.append(line);
                }

                postData = buf.toString();

                log.debug("POST DATA: " + postData);

                if (postData.startsWith("<")) {
                    service.setInputXML(postData);
                    scriptInputSet = true;
                } else {
                    try {
                        // The input object is a JSON object... so convert it into XML...
                        JSONObject json = new JSONObject(postData);

                        service.setInputXML(XML.toString(json));
                        scriptInputSet = true;
                        log.debug("POST JSON converted to \n" + XML.toString(json));
                    } catch (JSONException ex) {
                        errorResponse(response, "Could not convert POSTed JSON object." + ex.toString() + ". "
                                + ex.getStackTrace(), responseFormat, callbackFunction);
                        freeServiceScript(service);
                        return;
                    }
                }

            } catch (Exception ex) {
                log.warn("Exception getting posted data: " + ex.toString());
                errorResponse(response, "Could not convert posted data.", responseFormat, callbackFunction);
                freeServiceScript(service);
                return;
            }

        }

        /* If the service name has been redirected then set any parameters that where embedded in the URI... */
        if (serviceMapping != null) {
            Properties serviceParameters = serviceMapping.getParameters();
            String paramName;
            String paramValue;
            for (Enumeration<Object> en = serviceParameters.keys(); en.hasMoreElements();) {
                paramName = (String) en.nextElement();
                paramValue = (String) serviceParameters.get(paramName);
                service.setParameter(paramName, paramValue);
            }
        }

        String serviceResultString = null;

        /**
         * Run the service script...
         */

        service.setSessionRequest(request);
        service.setSessionResponse(response);
        service.setCallbackFunction(callbackFunction);

        /* Check if the service has a predefined output format... */
        /* If the user has specified a format then that is used.. */

        String operationResponseFormat;

        operationResponseFormat = service.getResponseFormat();

        if (defaultResponseFormat == true && operationResponseFormat != null
                && operationResponseFormat.equals("") == false) {
            responseFormat = operationResponseFormat;
        }

        service.setInvokeResponseFormat(responseFormat);

        /* If this is a priviledged operation then pass in a reference to the servlet... */

        String priviledgedOperation = service.getPriviledged();

        if (priviledgedOperation.compareToIgnoreCase("true") == 0
                || priviledgedOperation.compareToIgnoreCase("yes") == 0
                || priviledgedOperation.compareToIgnoreCase("y") == 0) {

            service.setPriviledgedHelper(this);
        }

        serviceResultString = service.invokeOperation();

        if (serviceResultString == null) {
            errorResponse(response,
                    "Error invoking the operation.<br><b>" + service.getScriptMessage() + "</b>",
                    responseFormat, callbackFunction);
            freeServiceScript(service);
            return;
        }

        /* Return the results... */

        if (serviceResultString != null && serviceResultString.equals("") == false) {
            writeResponse(serviceResultString, responseFormat, callbackFunction, response);
        }

        println(">> Service script executed successfully.");

        /* Free the service instance... */

        freeServiceScript(service);

    } catch (Exception ex) {
        errorResponse(response, "Exception processing request: " + ex.toString(), responseFormat,
                callbackFunction);
        ex.printStackTrace();
        try {
            freeServiceScript(service);
        } catch (Exception x) {
            log.warn("Exception freeing a service instance: " + x.toString());
        }
        return;
    }

    println(">> Finished processRequest() at " + new Date());

}

From source file:com.bekwam.resignator.ResignatorAppMainViewController.java

private void addToProfileBrowser(String newProfileName) {
    if (!lvProfiles.getItems().contains(newProfileName)) {
        int pos = 0;
        for (; pos < CollectionUtils.size(lvProfiles.getItems()); pos++) {
            String pn = lvProfiles.getItems().get(pos);
            if (pn.compareToIgnoreCase(newProfileName) > 0) {
                break;
            }//from w w w  . j  a  v  a2s. c o  m
        }
        lvProfiles.getItems().add(pos, newProfileName);
        lvProfiles.getSelectionModel().select(pos);
    }
}

From source file:gov.nih.nci.evs.browser.utils.MappingSearchUtils.java

public HashMap getMappingRelationshipHashMap(String scheme, String version, String code, int direction) {

    SearchContext searchContext = SearchContext.SOURCE_OR_TARGET_CODES;
    if (direction == 1)
        searchContext = SearchContext.SOURCE_CODES;
    else if (direction == -1)
        searchContext = SearchContext.TARGET_CODES;
    LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
    LexBIGServiceConvenienceMethods lbscm = new DataUtils().createLexBIGServiceConvenienceMethods(lbSvc);

    CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
    if (version != null)
        csvt.setVersion(version);//from  www.ja v  a2s  .  c o  m

    ResolvedConceptReferencesIteratorWrapper wrapper = searchByCode(scheme, version, code, "exactMatch",
            searchContext, -1);

    if (wrapper == null)
        return null;
    ResolvedConceptReferencesIterator iterator = wrapper.getIterator();
    if (iterator == null)
        return null;

    HashMap hmap = new HashMap();
    ArrayList list = new ArrayList();
    try {
        while (iterator.hasNext()) {
            ResolvedConceptReference ref = (ResolvedConceptReference) iterator.next();

            AssociationList asso_of = ref.getSourceOf();
            //KLO, 030811
            if (direction == -1)
                asso_of = ref.getTargetOf();

            if (asso_of != null) {
                Association[] associations = asso_of.getAssociation();

                if (associations != null) {

                    for (int i = 0; i < associations.length; i++) {
                        Association assoc = associations[i];
                        String associationName = null;
                        try {
                            associationName = lbscm.getAssociationNameFromAssociationCode(scheme, csvt,
                                    assoc.getAssociationName());
                        } catch (Exception ex) {
                            associationName = assoc.getAssociationName();
                        }

                        AssociatedConcept[] acl = assoc.getAssociatedConcepts().getAssociatedConcept();

                        for (int j = 0; j < acl.length; j++) {
                            AssociatedConcept ac = acl[j];

                            EntityDescription ed = ac.getEntityDescription();

                            String name = "No Description";
                            if (ed != null)
                                name = ed.getContent();
                            String pt = name;

                            if (associationName.compareToIgnoreCase("equivalentClass") != 0
                                    && ac.getConceptCode().indexOf("@") == -1) {

                                /*
                                                           String relaValue =
                                                              replaceAssociationNameByRela(
                                                                 ac, associationName);
                                */
                                String relaValue = associationName;

                                String s = relaValue + "|" + pt + "|" + ac.getConceptCode() + "|"
                                        + ac.getCodingSchemeName();

                                if (direction == -1) {

                                    EntityDescription ref_ed = ref.getEntityDescription();

                                    String ref_name = "No Description";
                                    if (ref_ed != null)
                                        ref_name = ref_ed.getContent();

                                    s = relaValue + "|" + ref_name + "|" + ref.getCode() + "|"
                                            + ref.getCodingSchemeName();

                                }

                                StringBuffer buf = new StringBuffer();
                                buf.append(s);

                                if (ac.getAssociationQualifiers() != null) {
                                    String qualifiers = "";
                                    for (NameAndValue qual : ac.getAssociationQualifiers().getNameAndValue()) {
                                        String qualifier_name = qual.getName();
                                        String qualifier_value = qual.getContent();
                                        qualifiers = qualifiers + (qualifier_name + ":" + qualifier_value)
                                                + "$";
                                    }
                                    //s = s + "|" + qualifiers;
                                    buf.append("|" + qualifiers);
                                }

                                if (direction == -1) {
                                    //s = s + "|" + ref.getCodeNamespace();
                                    buf.append("|" + ref.getCodeNamespace());
                                } else {
                                    //s = s + "|" + ac.getCodeNamespace();
                                    buf.append("|" + ac.getCodeNamespace());
                                }
                                s = buf.toString();
                                list.add(s);

                            }
                        }
                    }
                }
            }
        }
        if (list.size() > 0) {
            Collections.sort(list);
        }

        if (direction == 1) {
            hmap.put(TYPE_ASSOCIATION, list);
        } else {
            hmap.put(TYPE_INVERSE_ASSOCIATION, list);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return hmap;

}

From source file:org.ow2.aspirerfid.reader.rp.hal.impl.intermecif5.IntermecIF5Controller.java

private ArrayList<String> read(String prefix, String antennas) throws HardwareException {
    ArrayList<String> tags = new ArrayList<String>();
    try {/*from ww  w  .j  a  v a2 s . c  o m*/
        String charsRead;
        connect();
        synchronized (out) {
            if (antennas != null) {
                // antennas = antennas.trim().replace(' ', ',');
                out.writeBytes("ATTRIBUTE ANTS=" + antennas + "\n");
            } else {
                out.writeBytes("ATTRIBUTE ANTS=" + "1,2,3,4" + eol);
            }
            // log.debug("Read Error:"+in.readLine());
            log.debug(133 + in.readLine());

            out.writeBytes("READ ANT ");
            if (prefix != null && !prefix.trim().equals("")) {
                out.writeBytes(" WHERE EPCID=" + prefix);
                // log.debug("Read Error:"+in.readLine());
                log.debug(" WHERE EPCID=" + prefix);
            }
            out.writeBytes("\n");

            while (true) {
                charsRead = in.readLine();
                if (charsRead.equalsIgnoreCase("ERR")) {
                    throw new Exception("ERR: Error while reading");
                }
                if (charsRead.compareToIgnoreCase("OK>") == 0)
                    break;
                if (charsRead.startsWith("H")) {
                    charsRead = charsRead.substring(1);
                }
                if (!(charsRead.compareToIgnoreCase("NOTAG") == 0))
                    tags.add(charsRead);
            }
        } // synchronized
        return tags;
    } catch (Exception ex) {
        ex.printStackTrace();
        log.error(ex);
        throw new HardwareException(ex.getMessage());
    }
}

From source file:de.ub0r.android.websms.WebSMS.java

/**
 * Add or update a {@link ConnectorSpec}.
 *
 * @param connector connector//  ww w.ja va  2  s. c o m
 */
static void addConnector(final ConnectorSpec connector, final ConnectorCommand command) {
    synchronized (CONNECTORS) {
        if (connector == null || connector.getPackage() == null || connector.getName() == null) {
            return;
        }
        ConnectorSpec c = getConnectorByID(connector.getPackage());
        if (c != null) {
            Log.d(TAG, "update connector with id: " + c.getPackage());
            Log.d(TAG, "update connector with name: " + c.getName());
            c.setErrorMessage((String) null); // fix sticky error status
            short wasRunningStatus = c.getRunningStatus();
            c.update(connector);
            if (command.getType() == ConnectorCommand.TYPE_NONE && wasRunningStatus != 0
                    && c.hasStatus(ConnectorSpec.STATUS_ENABLED)) {
                // if this info is not a response to a command then preserve the running status
                // unless we've learnt that this connector got disabled
                Log.d(TAG, "preserving running status");
                c.addStatus(wasRunningStatus);
            }
            if (me != null) {
                final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(me);
                final String em = c.getErrorMessage();
                if (em != null) {
                    if (command.getType() != ConnectorCommand.TYPE_SEND) {
                        Toast.makeText(me, em, Toast.LENGTH_LONG).show();
                    }
                } else if (p.getBoolean(PREFS_SHOW_BALANCE_TOAST, false)
                        && !TextUtils.isEmpty(c.getBalance())) {
                    Toast.makeText(me, c.getName() + ": " + c.getBalance(), Toast.LENGTH_LONG).show();
                }
            }
        } else {
            --newConnectorsExpected;
            final String pkg = connector.getPackage();
            final String name = connector.getName();
            if (connector.getSubConnectorCount() == 0 || name == null || pkg == null) {
                Log.w(TAG, "skipped adding defect connector: " + pkg);
                return;
            }
            Log.d(TAG, "add connector with id: " + pkg);
            Log.d(TAG, "add connector with name: " + name);
            boolean added = false;
            final int l = CONNECTORS.size();
            ConnectorSpec cs;
            try {
                for (int i = 0; i < l; i++) {
                    cs = CONNECTORS.get(i);
                    if (name.compareToIgnoreCase(cs.getName()) < 0) {
                        CONNECTORS.add(i, connector);
                        added = true;
                        break;
                    }
                }
            } catch (NullPointerException e) {
                Log.e(TAG, "error while sorting", e);
            }
            if (!added) {
                CONNECTORS.add(connector);
            }
            c = connector;
            if (me != null) {
                final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(me);

                // update connectors balance if needed
                if (c.getBalance() == null && c.isReady() && !c.isRunning()
                        && c.hasCapabilities(ConnectorSpec.CAPABILITIES_UPDATE)
                        && p.getBoolean(PREFS_AUTOUPDATE, true)) {
                    final String defPrefix = p.getString(PREFS_DEFPREFIX, "+49");
                    final String defSender = p.getString(PREFS_SENDER, "");
                    runCommand(me, c, ConnectorCommand.update(defPrefix, defSender));
                }
            }
        }

        if (me != null) {
            if (prefsConnectorSpec == null) {
                final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(me);
                final String prefsConnectorID = p.getString(PREFS_CONNECTOR_ID, "");

                if (prefsConnectorID.equals(connector.getPackage())) {
                    prefsConnectorSpec = connector;

                    final String prefsSubConnectorID = p.getString(PREFS_SUBCONNECTOR_ID, "");
                    prefsSubConnectorSpec = connector.getSubConnector(prefsSubConnectorID);
                    if (prefsSubConnectorSpec == null) {
                        prefsSubConnectorSpec = connector.getSubConnectors()[0];
                    }

                    me.setButtons();
                }
            }

            final String b = c.getBalance();
            final String ob = c.getOldBalance();
            if (b != null && (ob == null || !b.equals(ob))) {
                me.updateBalance();
            }
            updateProgressBar();
            if (prefsConnectorSpec != null && prefsConnectorSpec.equals(c)) {
                me.setButtons();
            }
        }
        me.invalidateOptionsMenu();
    }
}

From source file:org.sakaiproject.tool.assessment.ui.listener.delivery.SubmitToGradingActionListener.java

/**
 * Invoke submission and return the grading data
 * //from  www. j  ava  2s. co  m
 * @param publishedAssessment
 * @param delivery
 * @return
 */
private synchronized AssessmentGradingData submitToGradingService(ActionEvent ae,
        PublishedAssessmentFacade publishedAssessment, DeliveryBean delivery, HashMap invalidFINMap,
        ArrayList invalidSALengthList) throws FinFormatException {
    log.debug("****1a. inside submitToGradingService ");
    String submissionId = "";
    HashSet<ItemGradingData> itemGradingHash = new HashSet<ItemGradingData>();
    // daisyf decoding: get page contents contains SectionContentsBean, a
    // wrapper for SectionDataIfc
    Iterator<SectionContentsBean> iter = delivery.getPageContents().getPartsContents().iterator();
    log.debug("****1b. inside submitToGradingService, iter= " + iter);
    HashSet<ItemGradingData> adds = new HashSet<ItemGradingData>();
    HashSet<ItemGradingData> removes = new HashSet<ItemGradingData>();

    // we go through all the answer collected from JSF form per each
    // publsihedItem and
    // work out which answer is an new addition and in cases like
    // MC/MCMR/Survey, we will
    // discard any existing one and just save the new one. For other
    // question type, we
    // simply modify the publishedText or publishedAnswer of the existing
    // ones.
    while (iter.hasNext()) {
        SectionContentsBean part = iter.next();
        log.debug("****1c. inside submitToGradingService, part " + part);
        Iterator<ItemContentsBean> iter2 = part.getItemContents().iterator();
        while (iter2.hasNext()) { // go through each item from form
            ItemContentsBean item = iter2.next();
            log.debug("****** before prepareItemGradingPerItem");
            prepareItemGradingPerItem(ae, delivery, item, adds, removes);
            log.debug("****** after prepareItemGradingPerItem");
        }
    }

    AssessmentGradingData adata = persistAssessmentGrading(ae, delivery, itemGradingHash, publishedAssessment,
            adds, removes, invalidFINMap, invalidSALengthList);

    StringBuffer redrawAnchorName = new StringBuffer("p");
    String tmpAnchorName = "";

    Iterator<SectionContentsBean> iterPart = delivery.getPageContents().getPartsContents().iterator();
    while (iterPart.hasNext()) {
        SectionContentsBean part = iterPart.next();
        String partSeq = part.getNumber();
        Iterator<ItemContentsBean> iterItem = part.getItemContents().iterator();
        while (iterItem.hasNext()) { // go through each item from form
            ItemContentsBean item = iterItem.next();
            String itemSeq = item.getSequence();
            Long itemId = item.getItemData().getItemId();
            if (item.getItemData().getTypeId() == 5) {
                if (invalidSALengthList.contains(itemId)) {
                    item.setIsInvalidSALengthInput(true);
                    redrawAnchorName.append(partSeq);
                    redrawAnchorName.append("q");
                    redrawAnchorName.append(itemSeq);
                    if (tmpAnchorName.equals("")
                            || tmpAnchorName.compareToIgnoreCase(redrawAnchorName.toString()) > 0) {
                        tmpAnchorName = redrawAnchorName.toString();
                    }
                } else {
                    item.setIsInvalidSALengthInput(false);
                }
            } else if (item.getItemData().getTypeId() == 11) {
                if (invalidFINMap.containsKey(itemId)) {
                    item.setIsInvalidFinInput(true);
                    redrawAnchorName.append(partSeq);
                    redrawAnchorName.append("q");
                    redrawAnchorName.append(itemSeq);
                    if (tmpAnchorName.equals("")
                            || tmpAnchorName.compareToIgnoreCase(redrawAnchorName.toString()) > 0) {
                        tmpAnchorName = redrawAnchorName.toString();
                    }
                    ArrayList list = (ArrayList) invalidFINMap.get(itemId);
                    List<FinBean> finArray = item.getFinArray();
                    Iterator<FinBean> iterFin = finArray.iterator();
                    while (iterFin.hasNext()) {
                        FinBean finBean = iterFin.next();
                        if (finBean.getItemGradingData() != null) {
                            Long itemGradingId = finBean.getItemGradingData().getItemGradingId();
                            if (list.contains(itemGradingId)) {
                                finBean.setIsCorrect(false);
                            }
                        }
                    }
                } else {
                    item.setIsInvalidFinInput(false);
                }
            }
        }
    }

    if (tmpAnchorName != null && !tmpAnchorName.equals("")) {
        delivery.setRedrawAnchorName(tmpAnchorName.toString());
    } else {
        delivery.setRedrawAnchorName("");
    }

    delivery.setSubmissionId(submissionId);
    delivery.setSubmissionTicket(submissionId);// is this the same thing?
    // hmmmm
    delivery.setSubmissionDate(new Date());
    delivery.setSubmitted(true);
    return adata;
}

From source file:org.kuali.rice.kew.routeheader.DocumentRouteHeaderValue.java

/**
 *
 * This method sets the appDocStatus.//  w  w w  .  j ava  2s  .c  om
 * It firsts validates the new value against the defined acceptable values, if defined.
 * It also updates the AppDocStatus date, and saves the status transition information
 *
 * @param appDocStatus
 * @throws WorkflowRuntimeException
 */
public void updateAppDocStatus(java.lang.String appDocStatus) throws WorkflowRuntimeException {
    //validate against allowable values if defined
    if (appDocStatus != null && appDocStatus.length() > 0
            && !appDocStatus.equalsIgnoreCase(this.appDocStatus)) {
        DocumentType documentType = KEWServiceLocator.getDocumentTypeService()
                .findById(this.getDocumentTypeId());
        if (documentType.getValidApplicationStatuses() != null
                && documentType.getValidApplicationStatuses().size() > 0) {
            Iterator<ApplicationDocumentStatus> iter = documentType.getValidApplicationStatuses().iterator();
            boolean statusValidated = false;
            while (iter.hasNext()) {
                ApplicationDocumentStatus myAppDocStat = iter.next();
                if (appDocStatus.compareToIgnoreCase(myAppDocStat.getStatusName()) == 0) {
                    statusValidated = true;
                    break;
                }
            }
            if (!statusValidated) {
                WorkflowRuntimeException xpee = new WorkflowRuntimeException(
                        "AppDocStatus value " + appDocStatus + " not allowable.");
                LOG.error("Error validating nextAppDocStatus name: " + appDocStatus
                        + " against acceptable values.", xpee);
                throw xpee;
            }
        }

        // set the status value
        String oldStatus = this.appDocStatus;
        this.appDocStatus = appDocStatus;

        // update the timestamp
        setAppDocStatusDate(new Timestamp(System.currentTimeMillis()));

        // save the status transition
        this.appDocStatusHistory.add(new DocumentStatusTransition(documentId, oldStatus, appDocStatus));
    }

}

From source file:org.roda.core.common.LdapUtility.java

/**
 * Reset {@link User}'s password given a previously generated token.
 *
 * @param username/*from w w  w  .j a  v a 2s  .co m*/
 *          the {@link User}'s username.
 * @param password
 *          the {@link User}'s password.
 * @param resetPasswordToken
 *          the token to reset {@link User}'s password.
 *
 * @return the modified {@link User}.
 *
 * @throws NotFoundException
 *           if a {@link User} with the same name already exists.
 * @throws InvalidTokenException
 *           if the specified token doesn't exist, has already expired or it
 *           doesn't correspond to the stored token.
 * @throws IllegalOperationException
 *           if the username corresponds to a protected {@link User}.
 * @throws GenericException
 *           if something goes wrong with the operation.
 */
public User resetUserPassword(final String username, final String password, final String resetPasswordToken)
        throws NotFoundException, InvalidTokenException, IllegalOperationException, GenericException {

    final User user = getUser(username);

    if (user == null) {

        throw new NotFoundException(userMessage(username, " doesn't exist"));

    } else {

        if (user.getResetPasswordToken() == null) {

            throw new InvalidTokenException("There's no active password reset token.");

        } else if (!user.getResetPasswordToken().equals(resetPasswordToken)
                || user.getResetPasswordTokenExpirationDate() == null) {

            // Token argument is not equal to stored token, or
            // expiration date is null.
            throw new InvalidTokenException("Password reset token is invalid.");

        } else {
            final String currentIsoDate = DateParser.getIsoDateNoMillis(Calendar.getInstance().getTime());
            if (currentIsoDate.compareToIgnoreCase(user.getResetPasswordTokenExpirationDate()) > 0) {
                throw new InvalidTokenException(
                        "Password reset token expired in " + user.getResetPasswordTokenExpirationDate());
            }
        }

        try {

            setUserPassword(username, password);

            user.setResetPasswordToken(null);
            user.setResetPasswordTokenExpirationDate(null);

            return modifyUser(user);

        } catch (final IllegalOperationException | EmailAlreadyExistsException e) {
            throw new GenericException("Error reseting user password - " + e.getMessage(), e);
        }
    }
}

From source file:org.roda.core.common.LdapUtility.java

/**
 * Confirms the {@link User} email using the token supplied at register time
 * and activate the {@link User}.//w ww.j  av  a  2  s. c  o  m
 * <p>
 * The <code>username</code> and <code>email</code> are used to identify the
 * user. One of them can be <code>null</code>, but not both at the same time.
 * </p>
 *
 * @param username
 *          the name of the {@link User}.
 * @param email
 *          the email address of the {@link User}.
 * @param emailConfirmationToken
 *          the email confirmation token.
 *
 * @return the {@link User} whose email has been confirmed.
 *
 * @throws NotFoundException
 *           if the username and email don't exist.
 * @throws IllegalArgumentException
 *           if username and email are <code>null</code>.
 * @throws InvalidTokenException
 *           if the specified token doesn't exist, has already expired or it
 *           doesn't correspond to the stored token.
 * @throws GenericException
 *           if something goes wrong with the operation.
 */
public User confirmUserEmail(final String username, final String email, final String emailConfirmationToken)
        throws NotFoundException, InvalidTokenException, GenericException {

    final User user = getUserByNameOrEmail(username, email);

    if (user == null) {

        final String message;
        if (username != null) {
            message = userMessage(username, " doesn't exist");
        } else {
            message = "Email " + email + " is not registered by any user";
        }

        throw new NotFoundException(message);

    } else {

        if (user.getEmailConfirmationToken() == null) {

            throw new InvalidTokenException("There's no active email confirmation token.");

        } else if (!user.getEmailConfirmationToken().equals(emailConfirmationToken)
                || user.getEmailConfirmationTokenExpirationDate() == null) {

            // Token argument is not equal to stored token, or
            // No expiration date
            throw new InvalidTokenException("Email confirmation token is invalid.");

        } else {

            final String currentIsoDate = DateParser.getIsoDateNoMillis(Calendar.getInstance().getTime());

            if (currentIsoDate.compareToIgnoreCase(user.getEmailConfirmationTokenExpirationDate()) > 0) {

                throw new InvalidTokenException("Email confirmation token expired in "
                        + user.getEmailConfirmationTokenExpirationDate());

            }

        }

        user.setActive(true);
        user.setEmailConfirmationToken(null);
        user.setEmailConfirmationTokenExpirationDate(null);

        try {

            return modifyUser(user);

        } catch (final IllegalOperationException | EmailAlreadyExistsException e) {
            throw new GenericException("Error confirming user email - " + e.getMessage(), e);
        }
    }
}