Comparing BigDecimals using equals

0


One important thing to know when you are comparing BigDecimals in Java is that the equals method returns true only if the objects being compared are equal in value and scale . So 3.14 not equals 3.140 if you are using the equals method .

Alternatives that can be used .

The compareTo method in BigDecimal is the obvious alternative to overcome the issue mentioned above . Another way would be to use the stripTrailingZeros methods on both objects before comparing them with equals .
However ,the stripTrailingZeros method does create a new object , and so might have
an performance overhead .


BigDecimal d1=new BigDecimal("3.14"); BigDecimal d2=new BigDecimal("3.140"); System.out.println(d1.equals(d2)); System.out.println(d1.compareTo(d2)==0); System.out.println(d1.stripTrailingZeros().equals(d2.stripTrailingZeros()));

Read more »
Labels: ,

Customizing a SuggestBox to simulate a Selection Box.

0

This class attempts to combine the features of a SuggestBox and a ListBox .

/** *PUBLIC SOFTWARE * *This source code has been placed in the public domain. You can use, modify, and distribute *the source code and executable programs based on the source code. * *However, note the following: * *DISCLAIMER OF WARRANTY * * This source code is provided "as is" and without warranties as to performance * or merchantability. The author and/or distributors of this source code may * have made statements about this source code. Any such statements do not constitute * warranties and shall not be relied on by the user in deciding whether to use * this source code.This source code is provided without any express or implied * warranties whatsoever. Because of the diversity of conditions and hardware * under which this source code may be used, no warranty of fitness for a * particular purpose is offered. The user is advised to test the source code * thoroughly before relying on it. The user must assume the entire risk of * using the source code. * */ import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.ui.MultiWordSuggestOracle; import com.google.gwt.user.client.ui.SuggestBox; import com.google.gwt.user.client.ui.SuggestOracle; import com.google.gwt.user.client.ui.SuggestOracle.Suggestion; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.TextBoxBase; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Extension of suggestBox simulating a traditional single-select list . * @author amal * @version 1.0 */ public final class MyGwtSuggestBox extends SuggestBox { private String value; private HashMap<String, String> itemValues; private HashMap<String, String> valueItems; private MultiWordSuggestOracle oracle; public MyGwtSuggestBox(String value, HashMap<String, String> itemValues, HashMap<String, String> valueItems, MultiWordSuggestOracle oracle) { this.value = value; this.itemValues = itemValues; this.valueItems = valueItems; this.oracle = oracle; } private ChangeHandler changeHandler = new ChangeHandler() { /** * check if the current value is in set of possible values , else rollback */ public void onChange(ChangeEvent event) { TextBox x = (TextBox) event.getSource(); String text = x.getText().trim(); if (value == null) { value = ""; } if (itemValues.keySet().contains(text)) { value = text; } else { x.setText(value); } } }; private KeyUpHandler keyUpHandler = new KeyUpHandler() { public void onKeyUp(KeyUpEvent event) { MyGwtSuggestBox x = (MyGwtSuggestBox) event.getSource(); if (x.getText().trim().equals("") && event.isDownArrow() && !((DefaultSuggestionDisplay) x. getSuggestionDisplay()).isSuggestionListShowing()) { x.showSuggestionList(); } } }; private SelectionHandler<SuggestOracle.Suggestion> selectionHandler = new SelectionHandler<SuggestOracle.Suggestion>() { public void onSelection(SelectionEvent<Suggestion> event) { SuggestBox x = (SuggestBox) event.getSource(); String text = x.getText().trim(); if (value == null) { value = ""; } if (itemValues.keySet().contains(text)) { value = text; } else { x.setText(value); } } }; private HandlerRegistration regChange = null; private HandlerRegistration regFocus = null; ; private HandlerRegistration regKeyPress = null; private HandlerRegistration regSelection = null; public MyGwtSuggestBox() { this(false); } public MyGwtSuggestBox(boolean enforceInputValidation) { super(); itemValues = new HashMap<String, String>(); valueItems = new HashMap<String, String>(); oracle = (MultiWordSuggestOracle) super.getSuggestOracle(); regKeyPress = super.addKeyUpHandler(keyUpHandler); if (!enforceInputValidation) { regChange = super.getTextBox().addChangeHandler(changeHandler); regSelection = super.addSelectionHandler(selectionHandler); } } public void removeInputValidation() { if (null != regChange) { regChange.removeHandler(); regChange = null; } if (null != regFocus) { regFocus.removeHandler(); regFocus = null; } } public MyGwtSuggestBox(SuggestOracle oracle, TextBoxBase box, SuggestionDisplay suggestDisplay) { throw new UnsupportedOperationException("Not Supported.Yet."); } public MyGwtSuggestBox(SuggestOracle oracle, TextBoxBase box) { throw new UnsupportedOperationException("Not Supported.Yet."); } public MyGwtSuggestBox(SuggestOracle oracle) { throw new UnsupportedOperationException("Not Supported.Yet."); } public void removeAllItems() { itemValues = new HashMap<String, String>(); valueItems = new HashMap<String, String>(); oracle.clear(); } public void addItems(List<String> items) { for (String item : items) { addItem(item); } } public void addItems(String[] items) { for (String item : items) { addItem(item); } } public void addItems(Map<String, String> keyItems) { for (String key : keyItems.keySet()) { addItem(keyItems.get(key), key); } } public void addItem(String item) { if (itemValues.containsKey(item)) { throw new RuntimeException("Duplicate item in list : " + item); } if (valueItems.containsKey(item)) { throw new RuntimeException("Duplicate value in list : " + item); } itemValues.put(item, item); valueItems.put(item, item); oracle.add(item); oracle.setDefaultSuggestionsFromText(itemValues.keySet()); } public void addItem(String item, String key) { if (itemValues.containsKey(item)) { throw new RuntimeException("Duplicate item in list : " + item); } if (valueItems.containsKey(key)) { throw new RuntimeException("Duplicate value in list : " + key); } itemValues.put(item, key); valueItems.put(key, item); oracle.add(item); oracle.setDefaultSuggestionsFromText(itemValues.keySet()); } public String getSelectedValue() { return itemValues.get(super.getText()); } public void setSelectedValue(String key) { super.setText(valueItems.get(key)); } public void clear() { super.setText(""); } }

Read more »
Labels: ,

A custom confirm dialog using GWT

2

Ever grew frustrated by the lack of customizations available of the window.confirm() dialog ? Here's a customizable confirm dialog for gwt apps.


/** *PUBLIC SOFTWARE * *This source code has been placedin the public domain. You can use, modify, and distribute *the source code and executable programs based on the source code. * *However, note the following: * *DISCLAIMER OF WARRANTY * * This source code is provided "as is" and without warranties as to performance * or merchantability. The author and/or distributors of this source code may * have made statements about this source code. Any such statements do not constitute * warranties and shall not be relied on by the user in deciding whether to use * this source code.This source code is provided without any express or implied * warranties whatsoever. Because of the diversity of conditions and hardware * under which this source code may be used, no warranty of fitness for a * particular purpose is offered. The user is advised to test the source code * thoroughly before relying on it. The user must assume the entire risk of * using the source code. * */ import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.CloseHandler; import com.google.gwt.user.client.ui.*; /** * @author amal * @version 1.0 */ public final class MyGwtConfirmDialog extends DialogBox { private Button primaryBtn; private Button secondaryBtn; private VerticalPanel mainPanel; private HorizontalPanel btnPanel; private HTML messageLbl; private boolean primaryActionFired = false; private boolean secondaryActionFired = false; public boolean primaryActionFired() { return primaryActionFired; } public boolean secondaryActionFired() { return secondaryActionFired; } /** * * @param title * @param message * @param primaryActionText * @param secondaryActionText * @param closeHandler * * sample usage - retrieving the confirmation status * <pre> * CloseHandler<PopupPanel> closeHandler=new CloseHandler<PopupPanel>() * { * * public void onClose(CloseEvent<PopupPanel> event) * { * MyGwtConfirmDialog x=(MyGwtConfirmDialog)event.getSource(); * Window.alert("primary "+x.primaryActionFired()+" ; secondary "+x.secondaryActionFired()); * } * }; * MyGwtConfirmDialog dia=new MyGwtConfirmDialog(<title>,<message>,<okText>,<cancelText>,closeHandler); * </pre> */ public MyGwtConfirmDialog(String title, String message, String primaryActionText, String secondaryActionText, CloseHandler<PopupPanel> closeHandler) { super(false, true); super.addCloseHandler(closeHandler); super.setText(title); mainPanel = new VerticalPanel(); messageLbl = new HTML(message); btnPanel = new HorizontalPanel(); mainPanel.add(messageLbl); mainPanel.add(btnPanel); primaryBtn = new Button(primaryActionText, new ClickHandler() { public void onClick(ClickEvent event) { primaryActionFired = true; MyGwtConfirmDialog.this.hide(); } }); secondaryBtn = new Button(secondaryActionText, new ClickHandler() { public void onClick(ClickEvent event) { secondaryActionFired = true; MyGwtConfirmDialog.this.hide(); } }); btnPanel.add(primaryBtn); btnPanel.add(secondaryBtn); btnPanel.setCellHorizontalAlignment(primaryBtn, HorizontalPanel.ALIGN_RIGHT); btnPanel.setCellHorizontalAlignment(secondaryBtn, HorizontalPanel.ALIGN_LEFT); super.setWidget(mainPanel); mainPanel.setHeight("100px"); mainPanel.setWidth("300px"); btnPanel.setHeight("30px"); btnPanel.setVerticalAlignment(HorizontalPanel.ALIGN_BOTTOM); btnPanel.addStyleName("dia-btnPanel"); primaryBtn.addStyleName("dia-primaryBtn"); secondaryBtn.addStyleName("dia-secondaryBtn"); messageLbl.addStyleName("dia-message"); super.setGlassEnabled(true); super.setAnimationEnabled(true); } /** * * @param message * @param closeHandler * @see MyGwtConfirmDialog#MyGwtConfirmDialog(java.lang.String, java.lang.String, java.lang.String, java.lang.String, com.google.gwt.event.logical.shared.CloseHandler) */ public MyGwtConfirmDialog(String message, CloseHandler<PopupPanel> closeHandler) { this("Confirmation", message, "Ok", "Cancel", closeHandler); } /** * should be used for displaying the dialog . */ public void paint() { primaryActionFired = false; secondaryActionFired = false; super.center(); primaryBtn.setFocus(true); } /** * * @param width */ public void setMainPanelWidth(String width) { mainPanel.setWidth(width); } }

Read more »
Labels:

GWT Custom Datebox

0

Here's an implemenation of a DateBox in GWT , specially designed for keyboard users . Like the ones who cant bother to maneuver a mouse .

The field recognizes multiple date formats , and even some real shorthands - like type in 010203 , and the date is set to Jan 01,2003 .


/** *PUBLIC SOFTWARE * *This source code has been placed in the public domain. You can use, modify, and distribute *the source code and executable programs based on the source code. * *However, note the following: * *DISCLAIMER OF WARRANTY * * This source code is provided "as is" and without warranties as to performance * or merchantability. The author and/or distributors of this source code may * have made statements about this source code. Any such statements do not constitute * warranties and shall not be relied on by the user in deciding whether to use * this source code.This source code is provided without any express or implied * warranties whatsoever. Because of the diversity of conditions and hardware * under which this source code may be used, no warranty of fitness for a * particular purpose is offered. The user is advised to test the source code * thoroughly before relying on it. The user must assume the entire risk of * using the source code. * */ import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.user.client.ui.*; import java.util.Date; /** * DateBox implemenation for keyboard power users. * @author * @version 1.0 */ public final class MyGwtDateBox extends TextBox { private static final long MS_PER_SEC = 1000; private static final long MS_PER_MIN = MS_PER_SEC * 60; private static final long MS_PER_HOUR = MS_PER_MIN * 60; private static final long MS_PER_DAY = MS_PER_HOUR * 24; /** * date formats recognized . */ private static String[] formats = new String[] { "dd-MM-yyyy", "dd-MMM-yyyy", "dd.MM.yyyy", "dd.MMM.yyyy", "dd/MM/yyyy", "dd/MMM/yyyy", "dd MM yyyy", "dd MMM yyyy", "dd-MMMM-yyyy", "dd.MMMM.yyyy", "dd/MMMM/yyyy", "dd MMMM yyyy", "MMM dd yyyy", "MMMM dd yyyy", "MMM dd,yyyy", "MMMM dd,yyyy" }; /** * output dateFormat */ private static DateTimeFormat dtf = DateTimeFormat.getFormat("dd-MMM-yyyy"); public static DateTimeFormat getDateTimeFormat() { return dtf; } private DateTimeFormat fullWeekDay = DateTimeFormat.getFormat("EEEE"); private DateTimeFormat shortWeekDay = DateTimeFormat.getFormat("EEE"); private Date today = today(); private Date yesterday = yesterday(); private Date tommorrow = tommorrow(); private Date value; boolean nullAllowed = false; /** * */ private ChangeHandler changeHandler = new ChangeHandler() { /** * try inferring the date from the enterd String , if not possible rollback to previous value. */ public void onChange(ChangeEvent event) { MyGwtDateBox x = (MyGwtDateBox) event.getSource(); String text = x.getText(); if (nullAllowed) { if (null == text || text.trim().equals("")) { return; } } if (text == null) { text = dtf.format(new Date()); } text = text.trim(); text.replaceAll("\\s+", "\\s"); text = handleNoSpacesString(text); try { text = handleShortHands(text); text = adjustYear(text); text = dtf.format(DateTimeFormat.getFormat(inferFormat(text)). parse(text)); value = dtf.parse(text); x.setText(text); } catch (Exception e) { x.setText(dtf.format(value)); } } }; private HandlerRegistration regChange; public MyGwtDateBox(int maxLength, int visibleLength) { throw new UnsupportedOperationException("not supported"); } public MyGwtDateBox(String text, int maxLength, int visibleLength) { throw new UnsupportedOperationException("not supported"); } public MyGwtDateBox(int maxLength) { throw new UnsupportedOperationException("not supported"); } public MyGwtDateBox(String text, int maxLength) { throw new UnsupportedOperationException("not supported"); } public MyGwtDateBox(String text) { throw new UnsupportedOperationException("not supported"); } public MyGwtDateBox() { this(new Date()); } public MyGwtDateBox(Date d) { super(); super.setText(dtf.format(d)); value = d; regChange = super.addChangeHandler(changeHandler); } public void setNullAllowed(boolean nullAllowed) { this.nullAllowed = nullAllowed; } String handleNoSpacesString(String x) { if (x.matches("^\\d+$")) { if (x.length() == 6 || x.length() == 8) { return x.substring(0, 2) + " " + x.substring(2, 4) + " " + x. substring(4); } } return x; } /** * the short-hand evaluation done in accordance with the values entered in AppMessages.properties * @param x * @return */ String handleShortHands(String x) { boolean previousFlag = false; if (x.equalsIgnoreCase(MESSAGES.today())) { return dtf.format(today); } if (x.equalsIgnoreCase(MESSAGES.tommorrow())) { return dtf.format(tommorrow); } if (x.equalsIgnoreCase(MESSAGES.yesterday())) { return dtf.format(yesterday); } if (x.startsWith(MESSAGES.previous())) { previousFlag = true; x = x.split("\\s")[1]; } if (x.startsWith(MESSAGES.next())) { x = x.split("\\s")[1]; } if (!x.trim().equals("") && MESSAGES.weekdaysString(). contains(x + ";")) { Date dt = previousFlag ? new Date(yesterday.getTime()) : new Date(tommorrow. getTime()); long increment = previousFlag ? MS_PER_DAY * -1 : MS_PER_DAY; while (!fullWeekDay.format(dt).equalsIgnoreCase(x)) { dt.setTime(dt.getTime() + increment); } return dtf.format(dt); } if (!x.trim().equals("") && MESSAGES.weekdaysStringShort(). contains(x + ";")) { Date dt = previousFlag ? new Date(yesterday.getTime()) : new Date(tommorrow. getTime()); long increment = previousFlag ? MS_PER_DAY * -1 : MS_PER_DAY; while (!shortWeekDay.format(dt).equalsIgnoreCase(x)) { dt.setTime(dt.getTime() + increment); } return dtf.format(dt); } return x; } /** * example transformations * 19 -> 2019 * 20 -> 2020 * 21 -> 1921 * @param x * @return */ String adjustYear(String x) { if (x.matches("^.*\\D\\d\\d$")) { int year = Integer.parseInt(x.substring(x.length() - 2, x.length())); x = x.substring(0, x.length() - 2) + (year < 21 ? "20" : "19") + x. substring(x.length() - 2, x.length()); } return x; } String inferFormat(String x) { for (String format : formats) { try { DateTimeFormat.getFormat(format).parse(x); return format; } catch (Exception e) { //ignore } } throw new RuntimeException("Unparseable date , " + x); } static Date today() { return new Date(); } static Date yesterday() { Date tmp = new Date(); tmp.setTime(tmp.getTime() - MS_PER_DAY); return new Date(tmp.getTime()); } static Date tommorrow() { Date tmp = new Date(); tmp.setTime(tmp.getTime() + MS_PER_DAY); return new Date(tmp.getTime()); } public Date getDate() { return dtf.parse(super.getText()); } public void setDate(Date x) { super.setText(dtf.format(x)); } } class MESSAGES { static String today() { return "today"; } static String tommorrow() { return "tomm"; } static String yesterday() { return "yesterday"; } static String next() { return "next"; } static String previous() { return "previous"; } static String weekdaysString() { return "sunday;monday;tuesday;wednesday;thursday;friday;saturday;"; } static String weekdaysStringShort() { return "sun;mon;tue;wed;thu;fri;sat;"; } }

Read more »
Labels: ,
© Zone817. Powered by Blogger.