List of usage examples for java.util Calendar AM_PM
int AM_PM
To view the source code for java.util Calendar AM_PM.
Click Source Link
get
and set
indicating whether the HOUR
is before or after noon. From source file:com.l2jfree.gameserver.model.olympiad.Olympiad.java
protected void setNewOlympiadEnd() { SystemMessage sm = new SystemMessage(SystemMessageId.OLYMPIAD_PERIOD_S1_HAS_STARTED); sm.addNumber(_currentCycle);/* w w w . j a v a 2 s . c o m*/ Announcements.getInstance().announceToAll(sm); Calendar currentTime = Calendar.getInstance(); currentTime.add(Calendar.MONTH, 1); currentTime.set(Calendar.DAY_OF_MONTH, 1); currentTime.set(Calendar.AM_PM, Calendar.AM); currentTime.set(Calendar.HOUR, 12); currentTime.set(Calendar.MINUTE, 0); currentTime.set(Calendar.SECOND, 0); _olympiadEnd = currentTime.getTimeInMillis(); Calendar nextChange = Calendar.getInstance(); _nextWeeklyChange = nextChange.getTimeInMillis() + WEEKLY_PERIOD; scheduleWeeklyChange(); }
From source file:com.icesoft.faces.component.selectinputdate.SelectInputDateRenderer.java
public void encodeEnd(FacesContext facesContext, UIComponent uiComponent) throws IOException { validateParameters(facesContext, uiComponent, SelectInputDate.class); DOMContext domContext = DOMContext.attachDOMContext(facesContext, uiComponent); SelectInputDate selectInputDate = (SelectInputDate) uiComponent; Date value;/*from w w w. jav a 2s. c o m*/ boolean actuallyHaveTime = false; if (selectInputDate.isNavEvent()) { if (log.isTraceEnabled()) { log.trace("Rendering Nav Event"); } value = selectInputDate.getNavDate(); //System.out.println("navDate: " + value); } else if (selectInputDate.isRenderAsPopup() && !selectInputDate.isEnterKeyPressed(facesContext)) { value = selectInputDate.getPopupDate(); if (value != null) { actuallyHaveTime = true; } } else { if (log.isTraceEnabled()) { log.trace("Logging non nav event"); } value = CustomComponentUtils.getDateValue(selectInputDate); if (value != null) { actuallyHaveTime = true; } //System.out.println("CustomComponentUtils.getDateValue: " + value); } DateTimeConverter converter = selectInputDate.resolveDateTimeConverter(facesContext); TimeZone tz = selectInputDate.resolveTimeZone(facesContext); Locale currentLocale = selectInputDate.resolveLocale(facesContext); DateFormatSymbols symbols = new DateFormatSymbols(currentLocale); //System.out.println("SIDR.encodeEnd() timezone: " + tz); //System.out.println("SIDR.encodeEnd() locale: " + currentLocale); Calendar timeKeeper = Calendar.getInstance(tz, currentLocale); timeKeeper.setTime(value != null ? value : new Date()); // get the parentForm UIComponent parentForm = findForm(selectInputDate); // if there is no parent form - ERROR if (parentForm == null) { log.error("SelectInputDate::must be in a FORM"); return; } String clientId; if (!domContext.isInitialized()) { Element root = domContext.createRootElement(HTML.DIV_ELEM); boolean popupState = selectInputDate.isShowPopup(); clientId = uiComponent.getClientId(facesContext); if (uiComponent.getId() != null) root.setAttribute("id", clientId + ROOT_DIV); Element table = domContext.createElement(HTML.TABLE_ELEM); if (selectInputDate.isRenderAsPopup()) { if (log.isTraceEnabled()) { log.trace("Render as popup"); } // ICE-2492 root.setAttribute(HTML.CLASS_ATTR, Util.getQualifiedStyleClass(uiComponent, CSS_DEFAULT.DEFAULT_CALENDARPOPUP_CLASS, false)); Element dateText = domContext.createElement(HTML.INPUT_ELEM); //System.out.println("value: " + selectInputDate.getValue()); dateText.setAttribute(HTML.TYPE_ATTR, HTML.INPUT_TYPE_TEXT); // ICE-2302 dateText.setAttribute(HTML.VALUE_ATTR, selectInputDate.getTextToRender()); dateText.setAttribute(HTML.ID_ATTR, clientId + SelectInputDate.CALENDAR_INPUTTEXT); dateText.setAttribute(HTML.NAME_ATTR, clientId + SelectInputDate.CALENDAR_INPUTTEXT); dateText.setAttribute(HTML.CLASS_ATTR, selectInputDate.getCalendarInputClass()); dateText.setAttribute(HTML.ONFOCUS_ATTR, "setFocus('');"); dateText.setAttribute("onkeypress", this.ICESUBMIT); boolean withinSingleSubmit = org.icefaces.impl.util.Util.withinSingleSubmit(selectInputDate); if (withinSingleSubmit) { JavascriptContext.addJavascriptCall(facesContext, "ice.cancelSingleSubmit('" + clientId + ROOT_DIV + "');"); } String singleSubmitCall = "ice.fullSubmit('@this', '@all', event, this, function(p) { p('ice.submit.type', 'ice.se'); p('ice.submit.serialization', 'form');});"; String onblur = combinedPassThru("setFocus('');", selectInputDate.getPartialSubmit() ? ICESUBMITPARTIAL : withinSingleSubmit ? singleSubmitCall : null); dateText.setAttribute(HTML.ONBLUR_ATTR, onblur); if (selectInputDate.getTabindex() != null) { dateText.setAttribute(HTML.TABINDEX_ATTR, selectInputDate.getTabindex()); } if (selectInputDate.getAutocomplete() != null && "off".equalsIgnoreCase(selectInputDate.getAutocomplete())) { dateText.setAttribute(HTML.AUTOCOMPLETE_ATTR, "off"); } String tooltip = null; tooltip = selectInputDate.getInputTitle(); if (tooltip == null || tooltip.length() == 0) { // extract the popupdate format and use it as a tooltip tooltip = getMessageWithParamFromResource(facesContext, INPUT_TEXT_TITLE, selectInputDate.getSpecifiedPopupDateFormat()); } if (tooltip != null && tooltip.length() > 0) { dateText.setAttribute(HTML.TITLE_ATTR, tooltip); } if (selectInputDate.isDisabled()) { dateText.setAttribute(HTML.DISABLED_ATTR, HTML.DISABLED_ATTR); } if (selectInputDate.isReadonly()) { dateText.setAttribute(HTML.READONLY_ATTR, HTML.READONLY_ATTR); } int maxlength = selectInputDate.getMaxlength(); if (maxlength > 0) { dateText.setAttribute(HTML.MAXLENGTH_ATTR, String.valueOf(maxlength)); } root.appendChild(dateText); Element calendarButton = domContext.createElement(HTML.INPUT_ELEM); calendarButton.setAttribute(HTML.ID_ATTR, clientId + CALENDAR_BUTTON); calendarButton.setAttribute(HTML.NAME_ATTR, clientId + CALENDAR_BUTTON); calendarButton.setAttribute(HTML.TYPE_ATTR, "image"); calendarButton.setAttribute(HTML.ONFOCUS_ATTR, "setFocus('');"); calendarButton.setAttribute(HTML.ONMOUSEDOWN_ATTR, "if (Event.isLeftClick(event)) this.selfClick = true;"); calendarButton.setAttribute(HTML.ONKEYDOWN_ATTR, "if (event.keyCode == 13 || event.keyCode == 32) this.selfClick = true;"); // render onclick to set value of hidden field to true String formClientId = parentForm.getClientId(facesContext); String hiddenValue1 = "document.forms['" + formClientId + "']['" + this.getLinkId(facesContext, uiComponent) + "'].value='"; String hiddenValue2 = "document.forms['" + formClientId + "']['" + getHiddenFieldName(facesContext, uiComponent) + "'].value='"; String onClick = "if (!this.selfClick) return false; this.selfClick = false; " + hiddenValue1 + clientId + CALENDAR_BUTTON + "';" + hiddenValue2 + "toggle';" + "iceSubmitPartial( document.forms['" + formClientId + "'], this,event);" + hiddenValue1 + "';" + hiddenValue2 + "';" + "Ice.Calendar.addCloseListener('" + clientId + "','" + formClientId + "','" + this.getLinkId(facesContext, uiComponent) + "','" + getHiddenFieldName(facesContext, uiComponent) + "');" + "return false;"; calendarButton.setAttribute(HTML.ONCLICK_ATTR, onClick); if (selectInputDate.getTabindex() != null) { try { int tabIndex = Integer.valueOf(selectInputDate.getTabindex()).intValue(); tabIndex += 1; calendarButton.setAttribute(HTML.TABINDEX_ATTR, String.valueOf(tabIndex)); } catch (NumberFormatException e) { if (log.isInfoEnabled()) { log.info("NumberFormatException on tabindex"); } } } if (selectInputDate.isDisabled()) { calendarButton.setAttribute(HTML.DISABLED_ATTR, HTML.DISABLED_ATTR); } if (selectInputDate.isReadonly()) { calendarButton.setAttribute(HTML.READONLY_ATTR, HTML.READONLY_ATTR); } root.appendChild(calendarButton); // render a hidden field to manage the popup state; visible || hidden FormRenderer.addHiddenField(facesContext, getHiddenFieldName(facesContext, uiComponent)); String resolvedSrc; if (popupState) { JavascriptContext.addJavascriptCall(facesContext, "Ice.util.adjustMyPosition('" + clientId + CALENDAR_TABLE + "', '" + clientId + ROOT_DIV + "');"); if (selectInputDate.isImageDirSet()) { resolvedSrc = CoreUtils.resolveResourceURL(facesContext, selectInputDate.getImageDir() + selectInputDate.getClosePopupImage()); } else { // ICE-2127: allow override of button images via CSS calendarButton.setAttribute(HTML.CLASS_ATTR, selectInputDate.getClosePopupClass()); // without this Firefox would display a default text on top of the image resolvedSrc = CoreUtils.resolveResourceURL(facesContext, selectInputDate.getImageDir() + "spacer.gif"); } calendarButton.setAttribute(HTML.SRC_ATTR, resolvedSrc); addAttributeToElementFromResource(facesContext, CLOSE_POPUP_ALT, calendarButton, HTML.ALT_ATTR); addAttributeToElementFromResource(facesContext, CLOSE_POPUP_TITLE, calendarButton, HTML.TITLE_ATTR); } else { if (selectInputDate.isImageDirSet()) { resolvedSrc = CoreUtils.resolveResourceURL(facesContext, selectInputDate.getImageDir() + selectInputDate.getOpenPopupImage()); } else { // ICE-2127: allow override of button images via CSS calendarButton.setAttribute(HTML.CLASS_ATTR, selectInputDate.getOpenPopupClass()); // without this Firefox would display a default text on top of the image resolvedSrc = CoreUtils.resolveResourceURL(facesContext, selectInputDate.getImageDir() + "spacer.gif"); } calendarButton.setAttribute(HTML.SRC_ATTR, resolvedSrc); addAttributeToElementFromResource(facesContext, OPEN_POPUP_ALT, calendarButton, HTML.ALT_ATTR); addAttributeToElementFromResource(facesContext, OPEN_POPUP_TITLE, calendarButton, HTML.TITLE_ATTR); FormRenderer.addHiddenField(facesContext, formClientId + UINamingContainer.getSeparatorChar(FacesContext.getCurrentInstance()) + "j_idcl"); FormRenderer.addHiddenField(facesContext, clientId + CALENDAR_CLICK); PassThruAttributeRenderer.renderHtmlAttributes(facesContext, uiComponent, passThruAttributesWithoutTabindex); domContext.stepOver(); return; } Text br = domContext.createTextNodeUnescaped("<br/>"); root.appendChild(br); Element calendarDiv = domContext.createElement(HTML.DIV_ELEM); calendarDiv.setAttribute(HTML.ID_ATTR, clientId + CALENDAR_POPUP); calendarDiv.setAttribute(HTML.NAME_ATTR, clientId + CALENDAR_POPUP); calendarDiv.setAttribute(HTML.STYLE_ELEM, "position:absolute;z-index:10;"); addAttributeToElementFromResource(facesContext, POPUP_CALENDAR_TITLE, calendarDiv, HTML.TITLE_ATTR); table.setAttribute(HTML.ID_ATTR, clientId + CALENDAR_TABLE); table.setAttribute(HTML.NAME_ATTR, clientId + CALENDAR_TABLE); table.setAttribute(HTML.CLASS_ATTR, selectInputDate.getStyleClass()); table.setAttribute(HTML.STYLE_ATTR, "position:absolute;"); table.setAttribute(HTML.CELLPADDING_ATTR, "0"); table.setAttribute(HTML.CELLSPACING_ATTR, "0"); // set mouse events on table bug 372 String mouseOver = selectInputDate.getOnmouseover(); table.setAttribute(HTML.ONMOUSEOVER_ATTR, mouseOver); String mouseOut = selectInputDate.getOnmouseout(); table.setAttribute(HTML.ONMOUSEOUT_ATTR, mouseOut); String mouseMove = selectInputDate.getOnmousemove(); table.setAttribute(HTML.ONMOUSEMOVE_ATTR, mouseMove); addAttributeToElementFromResource(facesContext, POPUP_CALENDAR_SUMMARY, table, HTML.SUMMARY_ATTR); Element positionDiv = domContext.createElement(HTML.DIV_ELEM); positionDiv.appendChild(table); calendarDiv.appendChild(positionDiv); Text iframe = domContext.createTextNodeUnescaped("<!--[if lte IE" + " 6.5]><iframe src='" + CoreUtils.resolveResourceURL(FacesContext.getCurrentInstance(), "/xmlhttp/blank") + "' class=\"iceSelInpDateIFrameFix\"></iframe><![endif]-->"); calendarDiv.appendChild(iframe); root.appendChild(calendarDiv); } else { if (log.isTraceEnabled()) { log.trace("Select input Date Normal"); } table.setAttribute(HTML.ID_ATTR, clientId + CALENDAR_TABLE); table.setAttribute(HTML.NAME_ATTR, clientId + CALENDAR_TABLE); table.setAttribute(HTML.CLASS_ATTR, selectInputDate.getStyleClass()); addAttributeToElementFromResource(facesContext, CALENDAR_TITLE, table, HTML.TITLE_ATTR); table.setAttribute(HTML.CELLPADDING_ATTR, "0"); table.setAttribute(HTML.CELLSPACING_ATTR, "0"); // set mouse events on table bug 372 String mouseOver = selectInputDate.getOnmouseover(); table.setAttribute(HTML.ONMOUSEOVER_ATTR, mouseOver); String mouseOut = selectInputDate.getOnmouseout(); table.setAttribute(HTML.ONMOUSEOUT_ATTR, mouseOut); String mouseMove = selectInputDate.getOnmousemove(); table.setAttribute(HTML.ONMOUSEMOVE_ATTR, mouseMove); addAttributeToElementFromResource(facesContext, CALENDAR_SUMMARY, table, HTML.SUMMARY_ATTR); root.appendChild(table); Element dateText = domContext.createElement(HTML.INPUT_ELEM); dateText.setAttribute(HTML.TYPE_ATTR, HTML.INPUT_TYPE_HIDDEN); dateText.setAttribute(HTML.VALUE_ATTR, selectInputDate.getTextToRender()); dateText.setAttribute(HTML.ID_ATTR, clientId + SelectInputDate.CALENDAR_INPUTTEXT); dateText.setAttribute(HTML.NAME_ATTR, clientId + SelectInputDate.CALENDAR_INPUTTEXT); root.appendChild(dateText); } } clientId = uiComponent.getClientId(facesContext); String[] weekdays = mapWeekdays(symbols); String[] weekdaysLong = mapWeekdaysLong(symbols); String[] months = mapMonths(symbols); // use the currentDay to set focus - do not set int lastDayInMonth = timeKeeper.getActualMaximum(Calendar.DAY_OF_MONTH); int currentDay = timeKeeper.get(Calendar.DAY_OF_MONTH); // starts at 1 if (currentDay > lastDayInMonth) { currentDay = lastDayInMonth; } timeKeeper.set(Calendar.DAY_OF_MONTH, 1); int weekDayOfFirstDayOfMonth = mapCalendarDayToCommonDay(timeKeeper.get(Calendar.DAY_OF_WEEK)); int weekStartsAtDayIndex = mapCalendarDayToCommonDay(timeKeeper.getFirstDayOfWeek()); // do not require a writer - clean out all methods that reference a writer ResponseWriter writer = facesContext.getResponseWriter(); Element root = (Element) domContext.getRootNode(); Element table = null; if (selectInputDate.isRenderAsPopup()) { if (log.isTraceEnabled()) { log.trace("SelectInputDate as Popup"); } // assumption input text is first child Element dateText = (Element) root.getFirstChild(); //System.out.println("dateText currentValue: " + currentValue); dateText.setAttribute(HTML.TYPE_ATTR, HTML.INPUT_TYPE_TEXT); // ICE-2302 dateText.setAttribute(HTML.VALUE_ATTR, selectInputDate.getTextToRender()); int maxlength = selectInputDate.getMaxlength(); if (maxlength > 0) { dateText.setAttribute(HTML.MAXLENGTH_ATTR, String.valueOf(maxlength)); } // get tables , our table is the first and only one NodeList tables = root.getElementsByTagName(HTML.TABLE_ELEM); // assumption we want the first table in tables. there should only be one table = (Element) tables.item(0); PassThruAttributeRenderer.renderHtmlAttributes(facesContext, uiComponent, passThruAttributesWithoutTabindex); Element tr1 = domContext.createElement(HTML.TR_ELEM); table.appendChild(tr1); writeMonthYearHeader(domContext, facesContext, writer, selectInputDate, timeKeeper, currentDay, tr1, selectInputDate.getMonthYearRowClass(), currentLocale, months, weekdays, weekdaysLong, converter); Element tr2 = domContext.createElement(HTML.TR_ELEM); table.appendChild(tr2); writeWeekDayNameHeader(domContext, weekStartsAtDayIndex, weekdays, facesContext, writer, selectInputDate, tr2, selectInputDate.getWeekRowClass(), timeKeeper, months, weekdaysLong, converter); writeDays(domContext, facesContext, writer, selectInputDate, timeKeeper, currentDay, weekStartsAtDayIndex, weekDayOfFirstDayOfMonth, lastDayInMonth, table, months, weekdays, weekdaysLong, converter, (actuallyHaveTime ? value : null)); } else { if (log.isTraceEnabled()) { log.trace("renderNormal::endcodeEnd"); } // assume table is the first child table = (Element) root.getFirstChild(); PassThruAttributeRenderer.renderHtmlAttributes(facesContext, uiComponent, passThruAttributes); Element tr1 = domContext.createElement(HTML.TR_ELEM); table.appendChild(tr1); writeMonthYearHeader(domContext, facesContext, writer, selectInputDate, timeKeeper, currentDay, tr1, selectInputDate.getMonthYearRowClass(), currentLocale, months, weekdays, weekdaysLong, converter); Element tr2 = domContext.createElement(HTML.TR_ELEM); writeWeekDayNameHeader(domContext, weekStartsAtDayIndex, weekdays, facesContext, writer, selectInputDate, tr2, selectInputDate.getWeekRowClass(), timeKeeper, months, weekdaysLong, converter); table.appendChild(tr2); writeDays(domContext, facesContext, writer, selectInputDate, timeKeeper, currentDay, weekStartsAtDayIndex, weekDayOfFirstDayOfMonth, lastDayInMonth, table, months, weekdays, weekdaysLong, converter, (actuallyHaveTime ? value : null)); } //System.out.println("SIDR.encodeEnd() isTime? " + SelectInputDate.isTime(converter)); if (SelectInputDate.isTime(converter)) { Element tfoot = domContext.createElement(HTML.TFOOT_ELEM); Element tr = domContext.createElement(HTML.TR_ELEM); Element td = domContext.createElement(HTML.TD_ELEM); td.setAttribute(HTML.COLSPAN_ATTR, selectInputDate.isRenderWeekNumbers() ? "8" : "7"); td.setAttribute(HTML.CLASS_ATTR, selectInputDate.getTimeClass()); Element tbl = domContext.createElement(HTML.TABLE_ELEM); Element tr2 = domContext.createElement(HTML.TR_ELEM); Element tdHours = domContext.createElement(HTML.TD_ELEM); Element hours = domContext.createElement(HTML.SELECT_ELEM); hours.setAttribute(HTML.ID_ATTR, clientId + SELECT_HOUR); hours.setAttribute(HTML.NAME_ATTR, clientId + SELECT_HOUR); hours.setAttribute(HTML.CLASS_ATTR, selectInputDate.getTimeDropDownClass()); hours.setAttribute(HTML.ONCHANGE_ATTR, DomBasicRenderer.ICESUBMITPARTIAL); // Convert from an hour to an index into the list of hours int hrs[] = selectInputDate.getHours(facesContext); //System.out.println("SIDR.encodeEnd() hrs: " + hrs[0] + ", " + hrs[hrs.length-1]); int hourIndex; int min; int sec; int amPm; //System.out.println("SIDR.encodeEnd() actuallyHaveTime: " + actuallyHaveTime); if (!actuallyHaveTime && selectInputDate.getHoursSubmittedValue() != null && selectInputDate.getMinutesSubmittedValue() != null) { //System.out.println("SIDR.encodeEnd() Using submitted hours and minutes"); hourIndex = selectInputDate.getHoursSubmittedValue().intValue(); //System.out.println("SIDR.encodeEnd() hour: " + hourIndex); min = selectInputDate.getMinutesSubmittedValue().intValue(); //System.out.println("SIDR.encodeEnd() min: " + min); String amPmStr = selectInputDate.getAmPmSubmittedValue(); //System.out.println("SIDR.encodeEnd() amPmStr: " + amPmStr); if (amPmStr != null) { amPm = amPmStr.equalsIgnoreCase("PM") ? 1 : 0; } else { amPm = (hourIndex >= 12) ? 1 : 0; } //System.out.println("SIDR.encodeEnd() amPm: " + amPm); if (hrs[0] == 1) { hourIndex--; if (hourIndex < 0) { hourIndex = hrs.length - 1; } } //System.out.println("SIDR.encodeEnd() hourIndex: " + hourIndex); } else { if (hrs.length > 12) { hourIndex = timeKeeper.get(Calendar.HOUR_OF_DAY); //System.out.println("SIDR.encodeEnd() hour 24: " + hourIndex); } else { hourIndex = timeKeeper.get(Calendar.HOUR); //System.out.println("SIDR.encodeEnd() hour 12: " + hourIndex); } if (hrs[0] == 1) { hourIndex--; if (hourIndex < 0) { hourIndex = hrs.length - 1; } } //System.out.println("SIDR.encodeEnd() hourIndex: " + hourIndex); min = timeKeeper.get(Calendar.MINUTE); amPm = timeKeeper.get(Calendar.AM_PM); //System.out.println("SIDR.encodeEnd() amPm: " + amPm); } if (!actuallyHaveTime && selectInputDate.getSecondsSubmittedValue() != null) { sec = selectInputDate.getSecondsSubmittedValue().intValue(); } else { sec = timeKeeper.get(Calendar.SECOND); } for (int i = 0; i < hrs.length; i++) { Element hoursOption = domContext.createElement(HTML.OPTION_ELEM); hoursOption.setAttribute(HTML.VALUE_ATTR, String.valueOf(hrs[i])); Text hourText = domContext.createTextNode(String.valueOf(hrs[i])); hoursOption.appendChild(hourText); if (i == hourIndex) { hoursOption.setAttribute(HTML.SELECTED_ATTR, "true"); } hours.appendChild(hoursOption); } Element tdColon = domContext.createElement(HTML.TD_ELEM); Element tdMinutes = domContext.createElement(HTML.TD_ELEM); Element minutes = domContext.createElement(HTML.SELECT_ELEM); minutes.setAttribute(HTML.ID_ATTR, clientId + SELECT_MIN); minutes.setAttribute(HTML.NAME_ATTR, clientId + SELECT_MIN); minutes.setAttribute(HTML.CLASS_ATTR, selectInputDate.getTimeDropDownClass()); minutes.setAttribute(HTML.ONCHANGE_ATTR, DomBasicRenderer.ICESUBMITPARTIAL); for (int i = 0; i < 60; i++) { Element minutesOption = domContext.createElement(HTML.OPTION_ELEM); minutesOption.setAttribute(HTML.VALUE_ATTR, String.valueOf(i)); String digits = String.valueOf(i); if (i < 10) { digits = "0" + digits; } Text minuteText = domContext.createTextNode(digits); minutesOption.appendChild(minuteText); if (i == min) { minutesOption.setAttribute(HTML.SELECTED_ATTR, "true"); } minutes.appendChild(minutesOption); } Text colon = domContext.createTextNode(":"); tfoot.appendChild(tr); tr.appendChild(td); td.appendChild(tbl); tbl.appendChild(tr2); tdHours.appendChild(hours); tr2.appendChild(tdHours); tdColon.appendChild(colon); tdMinutes.appendChild(minutes); tr2.appendChild(tdColon); tr2.appendChild(tdMinutes); if (selectInputDate.isSecond(facesContext)) { Element tdSeconds = domContext.createElement(HTML.TD_ELEM); Element tdSecColon = domContext.createElement(HTML.TD_ELEM); Element seconds = domContext.createElement(HTML.SELECT_ELEM); seconds.setAttribute(HTML.ID_ATTR, clientId + SELECT_SEC); seconds.setAttribute(HTML.NAME_ATTR, clientId + SELECT_SEC); seconds.setAttribute(HTML.CLASS_ATTR, selectInputDate.getTimeDropDownClass()); seconds.setAttribute(HTML.ONCHANGE_ATTR, DomBasicRenderer.ICESUBMITPARTIAL); for (int i = 0; i < 60; i++) { Element secondsOption = domContext.createElement(HTML.OPTION_ELEM); secondsOption.setAttribute(HTML.VALUE_ATTR, String.valueOf(i)); String digits = String.valueOf(i); if (i < 10) { digits = "0" + digits; } Text secondText = domContext.createTextNode(digits); secondsOption.appendChild(secondText); if (i == sec) { secondsOption.setAttribute(HTML.SELECTED_ATTR, "true"); } seconds.appendChild(secondsOption); } Text secondColon = domContext.createTextNode(":"); tdSecColon.appendChild(secondColon); tdSeconds.appendChild(seconds); tr2.appendChild(tdSecColon); tr2.appendChild(tdSeconds); } if (selectInputDate.isAmPm(facesContext)) { Element tdAamPm = domContext.createElement(HTML.TD_ELEM); Element amPmElement = domContext.createElement(HTML.SELECT_ELEM); amPmElement.setAttribute(HTML.ID_ATTR, clientId + SELECT_AM_PM); amPmElement.setAttribute(HTML.NAME_ATTR, clientId + SELECT_AM_PM); amPmElement.setAttribute(HTML.CLASS_ATTR, selectInputDate.getTimeDropDownClass()); amPmElement.setAttribute(HTML.ONCHANGE_ATTR, DomBasicRenderer.ICESUBMITPARTIAL); String[] symbolsAmPm = symbols.getAmPmStrings(); Element amPmElementOption = domContext.createElement(HTML.OPTION_ELEM); amPmElementOption.setAttribute(HTML.VALUE_ATTR, "AM"); Text amPmElementText = domContext.createTextNode(symbolsAmPm[0]); amPmElementOption.appendChild(amPmElementText); Element amPmElementOption2 = domContext.createElement(HTML.OPTION_ELEM); amPmElementOption2.setAttribute(HTML.VALUE_ATTR, "PM"); Text amPmElementText2 = domContext.createTextNode(symbolsAmPm[1]); amPmElementOption2.appendChild(amPmElementText2); if (amPm == 0) { amPmElementOption.setAttribute(HTML.SELECTED_ATTR, "true"); } else { amPmElementOption2.setAttribute(HTML.SELECTED_ATTR, "true"); } amPmElement.appendChild(amPmElementOption); amPmElement.appendChild(amPmElementOption2); tdAamPm.appendChild(amPmElement); tr2.appendChild(tdAamPm); } table.appendChild(tfoot); } // purge child components as they have been encoded no need to keep them around selectInputDate.getChildren().clear(); // steps to the position where the next sibling should be rendered domContext.stepOver(); }
From source file:DateUtil.java
/** * Returns true if the two calendars represent dates that fall in the same * morning or evening, as defined by [midnight,noon) and [noon,midnight), else * false./*w ww .j ava2s . com*/ * * @param c1 * Calendar one. * @param c2 * Calendar two. * @return boolean. */ public static boolean inSameAMPM(Calendar c1, Calendar c2) { if (inSameDay(c1, c2) && (c1.get(Calendar.AM_PM) == c2.get(Calendar.AM_PM))) return true; return false; }
From source file:org.openbravo.service.json.JsonToDataConverter.java
/** * The json conversion looses precision in milliseconds and seconds. This comparison method only * compares the other parts of the date object. Depending if a date or a date time is set. * //from ww w . ja va2 s .c o m * @param d1 * the first date to compare * @param d2 * the second date to compare * @param isDatetime * is it a datetime * @return true if d1 and d2 have equal values for year, month and day and for date time also same * values for hour, minutes and seconds. */ protected boolean areDatesEqual(Date d1, Date d2, boolean isDatetime, boolean isTime) { final Calendar c1 = Calendar.getInstance(); c1.setTime(d1); final Calendar c2 = Calendar.getInstance(); c2.setTime(d2); if (isTime) { c2.set(Calendar.MILLISECOND, 0); c1.set(Calendar.MILLISECOND, 0); } else if (isDatetime) { c2.set(Calendar.MILLISECOND, 0); c1.set(Calendar.MILLISECOND, 0); } else { c2.set(Calendar.MILLISECOND, 0); c1.set(Calendar.MILLISECOND, 0); c2.set(Calendar.SECOND, 0); c1.set(Calendar.SECOND, 0); c2.set(Calendar.MINUTE, 0); c1.set(Calendar.MINUTE, 0); c2.set(Calendar.HOUR, 0); c1.set(Calendar.HOUR, 0); c1.set(Calendar.AM_PM, Calendar.AM); c2.set(Calendar.AM_PM, Calendar.AM); } return c2.getTimeInMillis() == c1.getTimeInMillis(); }
From source file:com.wso2telco.core.dbutils.DbService.java
public SpendLimitDAO getGroupTotalDayAmount(String groupName, String operator, String msisdn) throws DBUtilException { Connection con = null;//from www . ja va 2 s . c om PreparedStatement ps = null; ResultSet rs = null; SpendLimitDAO spendLimitDAO = null; try { con = DbUtils.getDBConnection(); Calendar calendarFrom = Calendar.getInstance(); calendarFrom.set(Calendar.AM_PM, Calendar.AM); calendarFrom.set(Calendar.HOUR, 00); calendarFrom.set(Calendar.MINUTE, 00); calendarFrom.set(Calendar.SECOND, 00); calendarFrom.set(Calendar.MILLISECOND, 00); Calendar calendarTo = Calendar.getInstance(); calendarTo.set(Calendar.AM_PM, Calendar.PM); calendarTo.set(Calendar.HOUR, 11); calendarTo.set(Calendar.MINUTE, 59); calendarTo.set(Calendar.SECOND, 59); calendarTo.set(Calendar.MILLISECOND, 999); String sql = "SELECT SUM(amount) AS amount " + "FROM spendlimitdata " + "where effectiveTime between ? and ? " + "and groupName=? " + "and operatorId=? " + "and msisdn=? " + "group by groupName, operatorId, msisdn"; ps = con.prepareStatement(sql); ps.setLong(1, calendarFrom.getTimeInMillis()); ps.setLong(2, calendarTo.getTimeInMillis()); ps.setString(3, groupName); ps.setString(4, operator); ps.setString(5, msisdn); rs = ps.executeQuery(); if (rs.next()) { spendLimitDAO = new SpendLimitDAO(); spendLimitDAO.setAmount(rs.getDouble("amount")); } } catch (Exception e) { DbUtils.handleException("Error while checking Operator Spend Limit. ", e); } finally { DbUtils.closeAllConnections(ps, con, rs); } return spendLimitDAO; }
From source file:com.mb.framework.util.DateTimeUtil.java
/** * This method is used for checking the target date is in AM * //from w w w . j a v a 2 s.c om * @param date * @return */ public static boolean isAM(Date date) { boolean isAM = false; Calendar calendar = Calendar.getInstance(); calendar.setTime(date); if (Calendar.AM == calendar.get(Calendar.AM_PM)) isAM = true; return isAM; }
From source file:DateUtil.java
/** * Sets the date/time of the Calendar object to the beginning of the Period by * setting all fields smaller than the specified period to the minimum value. * //from ww w. j a v a 2 s . c om * @param c * The calendar to set. * @param p * The DateUtil.Period to set. */ public static void setToPeriodStart(Calendar c, Period p) { switch (p) { case YEAR: c.set(Calendar.MONTH, 0); case MONTH: c.set(Calendar.DAY_OF_MONTH, 1); case DAY: c.set(Calendar.HOUR_OF_DAY, 0); case HOUR: c.set(Calendar.MINUTE, 0); case MINUTE: c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); break; case WEEK: c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); break; case AMPM: if (c.get(Calendar.AM_PM) == Calendar.AM) c.set(Calendar.HOUR_OF_DAY, 0); else c.set(Calendar.HOUR_OF_DAY, 12); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); break; case QUARTER: int month = c.get(Calendar.MONTH); if (month >= 9) c.set(Calendar.MONTH, 9); else if (month >= 9) c.set(Calendar.MONTH, 6); else if (month >= 9) c.set(Calendar.MONTH, 3); else c.set(Calendar.MONTH, 0); c.set(Calendar.DAY_OF_MONTH, 0); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); break; } return; }
From source file:DateFormatUtils.java
/** * <p>Returns a list of Rules given a pattern.</p> * // w ww . j a v a 2s. c o m * @return a <code>List</code> of Rule objects * @throws IllegalArgumentException if pattern is invalid */ protected List parsePattern() { DateFormatSymbols symbols = new DateFormatSymbols(mLocale); List rules = new ArrayList(); String[] ERAs = symbols.getEras(); String[] months = symbols.getMonths(); String[] shortMonths = symbols.getShortMonths(); String[] weekdays = symbols.getWeekdays(); String[] shortWeekdays = symbols.getShortWeekdays(); String[] AmPmStrings = symbols.getAmPmStrings(); int length = mPattern.length(); int[] indexRef = new int[1]; for (int i = 0; i < length; i++) { indexRef[0] = i; String token = parseToken(mPattern, indexRef); i = indexRef[0]; int tokenLen = token.length(); if (tokenLen == 0) { break; } Rule rule; char c = token.charAt(0); switch (c) { case 'G': // era designator (text) rule = new TextField(Calendar.ERA, ERAs); break; case 'y': // year (number) if (tokenLen >= 4) { rule = selectNumberRule(Calendar.YEAR, tokenLen); } else { rule = TwoDigitYearField.INSTANCE; } break; case 'M': // month in year (text and number) if (tokenLen >= 4) { rule = new TextField(Calendar.MONTH, months); } else if (tokenLen == 3) { rule = new TextField(Calendar.MONTH, shortMonths); } else if (tokenLen == 2) { rule = TwoDigitMonthField.INSTANCE; } else { rule = UnpaddedMonthField.INSTANCE; } break; case 'd': // day in month (number) rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen); break; case 'h': // hour in am/pm (number, 1..12) rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen)); break; case 'H': // hour in day (number, 0..23) rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen); break; case 'm': // minute in hour (number) rule = selectNumberRule(Calendar.MINUTE, tokenLen); break; case 's': // second in minute (number) rule = selectNumberRule(Calendar.SECOND, tokenLen); break; case 'S': // millisecond (number) rule = selectNumberRule(Calendar.MILLISECOND, tokenLen); break; case 'E': // day in week (text) rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays); break; case 'D': // day in year (number) rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen); break; case 'F': // day of week in month (number) rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen); break; case 'w': // week in year (number) rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen); break; case 'W': // week in month (number) rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen); break; case 'a': // am/pm marker (text) rule = new TextField(Calendar.AM_PM, AmPmStrings); break; case 'k': // hour in day (1..24) rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen)); break; case 'K': // hour in am/pm (0..11) rule = selectNumberRule(Calendar.HOUR, tokenLen); break; case 'z': // time zone (text) if (tokenLen >= 4) { rule = new TimeZoneNameRule(mTimeZone, mTimeZoneForced, mLocale, TimeZone.LONG); } else { rule = new TimeZoneNameRule(mTimeZone, mTimeZoneForced, mLocale, TimeZone.SHORT); } break; case 'Z': // time zone (value) if (tokenLen == 1) { rule = TimeZoneNumberRule.INSTANCE_NO_COLON; } else { rule = TimeZoneNumberRule.INSTANCE_COLON; } break; case '\'': // literal text String sub = token.substring(1); if (sub.length() == 1) { rule = new CharacterLiteral(sub.charAt(0)); } else { rule = new StringLiteral(sub); } break; default: throw new IllegalArgumentException("Illegal pattern component: " + token); } rules.add(rule); } return rules; }
From source file:org.akaza.openclinica.control.managestudy.UpdateStudyEventServlet.java
@Override public void processRequest() throws Exception { ctx = WebApplicationContextUtils.getWebApplicationContext(context); FormDiscrepancyNotes discNotes = null; FormProcessor fp = new FormProcessor(request); int studyEventId = fp.getInt(EVENT_ID, true); int studySubjectId = fp.getInt(STUDY_SUBJECT_ID, true); String module = fp.getString(MODULE); request.setAttribute(MODULE, module); String fromResolvingNotes = fp.getString("fromResolvingNotes", true); if (StringUtil.isBlank(fromResolvingNotes)) { session.removeAttribute(ViewNotesServlet.WIN_LOCATION); session.removeAttribute(ViewNotesServlet.NOTES_TABLE); checkStudyLocked(Page.MANAGE_STUDY, respage.getString("current_study_locked")); checkStudyFrozen(Page.MANAGE_STUDY, respage.getString("current_study_frozen")); }//from w w w . jav a2 s . c o m if (studyEventId == 0 || studySubjectId == 0) { addPageMessage(respage.getString("choose_a_study_event_to_edit")); request.setAttribute("id", new Integer(studySubjectId).toString()); forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET); return; } StudySubjectDAO ssdao = new StudySubjectDAO(sm.getDataSource()); StudySubjectBean ssub = null; if (studySubjectId > 0) { ssub = (StudySubjectBean) ssdao.findByPK(studySubjectId); request.setAttribute("studySubject", ssub); request.setAttribute("id", studySubjectId + "");// for the workflow // box, so it can // link back to view // study subject } // YW 11-07-2007, a study event could not be updated if its study // subject has been removed // Status s = ((StudySubjectBean)new // StudySubjectDAO(sm.getDataSource()).findByPK(studySubjectId)).getStatus(); Status s = ssub.getStatus(); if ("removed".equalsIgnoreCase(s.getName()) || "auto-removed".equalsIgnoreCase(s.getName())) { addPageMessage(resword.getString("study_event") + resterm.getString("could_not_be") + resterm.getString("updated") + "." + respage.getString("study_subject_has_been_deleted")); request.setAttribute("id", new Integer(studySubjectId).toString()); forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET); } // YW request.setAttribute(STUDY_SUBJECT_ID, new Integer(studySubjectId).toString()); StudyEventDAO sedao = new StudyEventDAO(sm.getDataSource()); EventCRFDAO ecrfdao = new EventCRFDAO(sm.getDataSource()); StudyEventBean studyEvent = (StudyEventBean) sedao.findByPK(studyEventId); studyEvent.setEventCRFs(ecrfdao.findAllByStudyEvent(studyEvent)); // only owner, admins, and study director/coordinator can update // if (ub.getId() != studyEvent.getOwnerId()) { // if (!ub.isSysAdmin() && // !currentRole.getRole().equals(Role.STUDYDIRECTOR) // && !currentRole.getRole().equals(Role.COORDINATOR)) { // addPageMessage(respage.getString("no_have_correct_privilege_current_study") // + respage.getString("change_study_contact_sysadmin")); // request.setAttribute("id", new Integer(studySubjectId).toString()); // forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET); // return; // } // } // above removed tbh 11162007 ArrayList statuses = SubjectEventStatus.toArrayList(); // remove more statuses here, tbh, 092007 // ### updates to status setting, below added tbh 102007 // following pieces of logic to be added: /* * REMOVED can happen at any step, COMPLETED can happen if the Subject * Event is already complete, COMPLETED can also happen if all required * CRFs in the Subject Event are completed, LOCKED can occur when all * Event CRFs are completed, or not started, or removed, LOCKED/REMOVED * are only options, however, when the user is study director or study * coordinator SKIPPED/STOPPED? Additional rules spelled out on Nov 16 * 2007: STOPPED should only be in the list of choices after IDE has * been started, i.e. not when SCHEDULED SKIPPED should only be in the * list before IDE has been started, i.e. when SCHEDULED reminder about * LOCKED happening only when CRFs are completed (not as in the * above...) if a status is LOCKED already, it should allow a user to * set the event back to COMPLETED */ StudyDAO sdao = new StudyDAO(this.sm.getDataSource()); StudyBean studyBean = (StudyBean) sdao.findByPK(ssub.getStudyId()); checkRoleByUserAndStudy(ub, studyBean, sdao); // To remove signed status from the list EventDefinitionCRFDAO edcdao = new EventDefinitionCRFDAO(sm.getDataSource()); boolean removeSign = false; // DiscrepancyNoteDAO discDao = new // DiscrepancyNoteDAO(sm.getDataSource()); ArrayList eventCrfs = studyEvent.getEventCRFs(); for (int i = 0; i < eventCrfs.size(); i++) { EventCRFBean ecrf = (EventCRFBean) eventCrfs.get(i); EventDefinitionCRFBean edcBean = edcdao.findByStudyEventIdAndFormLayoutId(studyBean, studyEventId, ecrf.getFormLayoutId()); if (ecrf.getStage().equals(DataEntryStage.INITIAL_DATA_ENTRY) || ecrf.getStage().equals(DataEntryStage.INITIAL_DATA_ENTRY_COMPLETE) && edcBean.isDoubleEntry() == true) { removeSign = true; break; } } if (currentRole.isResearchAssistant()) { removeSign = true; } if (currentRole.isResearchAssistant2()) { removeSign = true; } if (removeSign == true || !currentRole.isInvestigator()) { statuses.remove(SubjectEventStatus.SIGNED); } // ///End of remove signed status from the list // BWP: 2735>>keep the DATA_ENTRY_STARTED status /* * if(!studyEvent.getSubjectEventStatus().equals(SubjectEventStatus. * DATA_ENTRY_STARTED)) { * statuses.remove(SubjectEventStatus.DATA_ENTRY_STARTED); * //statuses.remove(SubjectEventStatus.SKIPPED); // per new rule * 11-2007 } */ if (!studyEvent.getSubjectEventStatus().equals(SubjectEventStatus.NOT_SCHEDULED)) { statuses.remove(SubjectEventStatus.NOT_SCHEDULED); } if (!studyEvent.getSubjectEventStatus().equals(SubjectEventStatus.SCHEDULED)) { // can't lock a non-completed CRF, but removed above statuses.remove(SubjectEventStatus.SCHEDULED); // statuses.remove(SubjectEventStatus.SKIPPED); // addl rule: skipped should only be present before data starts // being entered } if (studyEvent.getSubjectEventStatus().equals(SubjectEventStatus.DATA_ENTRY_STARTED)) { statuses.remove(SubjectEventStatus.SKIPPED); } if ((studyEvent.getSubjectEventStatus().equals(SubjectEventStatus.SCHEDULED) || studyEvent.getSubjectEventStatus().equals(SubjectEventStatus.DATA_ENTRY_STARTED)) && currentRole.isInvestigator()) { statuses.remove(SubjectEventStatus.SIGNED); } ArrayList getECRFs = studyEvent.getEventCRFs(); // above removed tbh 102007, require to get all definitions, no matter // if they are filled in or now EventDefinitionCRFDAO edefcrfdao = new EventDefinitionCRFDAO(sm.getDataSource()); ArrayList getAllECRFs = (ArrayList) edefcrfdao.findAllByDefinition(studyBean, studyEvent.getStudyEventDefinitionId()); // does the study event have all complete CRFs which are required? logger.debug("found number of ecrfs: " + getAllECRFs.size()); // may not be populated, only entered crfs seem to ping the list for (int u = 0; u < getAllECRFs.size(); u++) { EventDefinitionCRFBean ecrfBean = (EventDefinitionCRFBean) getAllECRFs.get(u); // logger.debug("found number of existing ecrfs: " + getECRFs.size()); if (getECRFs.size() == 0) { statuses.remove(SubjectEventStatus.COMPLETED); statuses.remove(SubjectEventStatus.LOCKED); } // otherwise... for (int uv = 0; uv < getECRFs.size(); uv++) { EventCRFBean existingBean = (EventCRFBean) getECRFs.get(uv); logger.debug("***** found: " + existingBean.getCRFVersionId() + " " + existingBean.getCrf().getId() + " " + existingBean.getCrfVersion().getName() + " " + existingBean.getStatus().getName() + " " + existingBean.getStage().getName()); logger.debug( "***** comparing above to ecrfBean.DefaultVersionID: " + ecrfBean.getDefaultVersionId()); // if (existingBean.getCRFVersionId() == // ecrfBean.getDefaultVersionId()) { // OK. this only works if we go ahead and remove the drop down // will this match up? Do we need to pull it out of // studyEvent.getEventCRFs()? // only case that this will screw up is if there are no crfs // whatsoever // this is addressed in the if-clause above if (!existingBean.getStatus().equals(Status.UNAVAILABLE) && edefcrfdao.isRequiredInDefinition(existingBean.getCRFVersionId(), studyEvent)) { logger.debug("found that " + existingBean.getCrfVersion().getName() + " is required..."); // that is, it's not completed but required to complete statuses.remove(SubjectEventStatus.COMPLETED); statuses.remove(SubjectEventStatus.LOCKED); // per new rule above 11-16-2007 } // } } } // below added 092007, tbh, task #1390 if (!ub.isSysAdmin() && !currentRole.getRole().equals(Role.STUDYDIRECTOR) && !currentRole.getRole().equals(Role.COORDINATOR)) { statuses.remove(SubjectEventStatus.LOCKED); } // also, if data entry is started, can't move back to scheduled or not // scheduled if (studyEvent.getSubjectEventStatus().equals(SubjectEventStatus.DATA_ENTRY_STARTED)) { statuses.remove(SubjectEventStatus.NOT_SCHEDULED); statuses.remove(SubjectEventStatus.SCHEDULED); } // ### tbh, above modified 102007 request.setAttribute("statuses", statuses); String action = fp.getString("action"); StudyEventDefinitionDAO seddao = new StudyEventDefinitionDAO(sm.getDataSource()); StudyEventDefinitionBean sed = (StudyEventDefinitionBean) seddao .findByPK(studyEvent.getStudyEventDefinitionId()); request.setAttribute(EVENT_DEFINITION_BEAN, sed); String start_date = fp.getDateTimeInputString(INPUT_STARTDATE_PREFIX); String end_date = fp.getDateTimeInputString(INPUT_ENDDATE_PREFIX); SimpleDateFormat dteFormat = new SimpleDateFormat( ResourceBundleProvider.getFormatBundle().getString("date_format_string")); Date start = null; Date end = null; if (!StringUtils.isEmpty(start_date)) { start = fp.getDateTime(INPUT_STARTDATE_PREFIX); start_date = dteFormat.format(start); } if (!StringUtils.isEmpty(end_date)) { end = fp.getDateTime(INPUT_ENDDATE_PREFIX); end_date = dteFormat.format(end); } if (action.equalsIgnoreCase("submit")) { discNotes = (FormDiscrepancyNotes) session .getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME); DiscrepancyValidator v = new DiscrepancyValidator(request, discNotes); SubjectEventStatus ses = SubjectEventStatus.get(fp.getInt(SUBJECT_EVENT_STATUS_ID)); studyEvent.setSubjectEventStatus(ses); EventCRFDAO ecdao = new EventCRFDAO(sm.getDataSource()); ArrayList<EventCRFBean> eventCRFs = ecdao.findAllByStudyEvent(studyEvent); if (ses.equals(SubjectEventStatus.SKIPPED) || ses.equals(SubjectEventStatus.STOPPED)) { studyEvent.setStatus(Status.UNAVAILABLE); for (int i = 0; i < eventCRFs.size(); i++) { EventCRFBean ecb = eventCRFs.get(i); ecb.setOldStatus(ecb.getStatus()); ecb.setStatus(Status.UNAVAILABLE); ecb.setUpdater(ub); ecb.setUpdatedDate(new Date()); ecdao.update(ecb); } } else { for (int i = 0; i < eventCRFs.size(); i++) { EventCRFBean ecb = eventCRFs.get(i); ecb.setUpdater(ub); ecb.setUpdatedDate(new Date()); ecdao.update(ecb); } } // YW 3-12-2008, 2220 fix String strEnd = fp.getDateTimeInputString(INPUT_ENDDATE_PREFIX); String strEndScheduled = fp.getDateTimeInputString(INPUT_ENDDATE_PREFIX); String strStartScheduled = fp.getDateTimeInputString(INPUT_STARTDATE_PREFIX); if (!strStartScheduled.equals("")) { v.addValidation(INPUT_STARTDATE_PREFIX, Validator.IS_DATE_TIME); v.alwaysExecuteLastValidation(INPUT_STARTDATE_PREFIX); } if (!strEndScheduled.equals("")) { v.addValidation(INPUT_ENDDATE_PREFIX, Validator.IS_DATE_TIME); v.alwaysExecuteLastValidation(INPUT_ENDDATE_PREFIX); } // v.addValidation(INPUT_LOCATION, Validator.NO_BLANKS); Disable validation on location, location can be // empty when updating a study event HashMap errors = v.validate(); // YW, 3-12-2008, 2220 fix << if (!strEnd.equals("") && !errors.containsKey(INPUT_STARTDATE_PREFIX) && !errors.containsKey(INPUT_ENDDATE_PREFIX)) { end = fp.getDateTime(INPUT_ENDDATE_PREFIX); if (!fp.getString(INPUT_STARTDATE_PREFIX + "Date") .equals(fp.getString(INPUT_ENDDATE_PREFIX + "Date"))) { if (end.before(start)) { v.addError(errors, INPUT_ENDDATE_PREFIX, resexception.getString("input_provided_not_occure_after_previous_start_date_time")); } } else { // if in same date, only check when both had time entered if (fp.timeEntered(INPUT_STARTDATE_PREFIX) && fp.timeEntered(INPUT_ENDDATE_PREFIX)) { if (end.before(start) || end.equals(start)) { v.addError(errors, INPUT_ENDDATE_PREFIX, resexception .getString("input_provided_not_occure_after_previous_start_date_time")); } } } } // YW >> if (!errors.isEmpty()) { setInputMessages(errors); String prefixes[] = { INPUT_STARTDATE_PREFIX, INPUT_ENDDATE_PREFIX }; fp.setCurrentDateTimeValuesAsPreset(prefixes); setPresetValues(fp.getPresetValues()); studyEvent.setLocation(fp.getString(INPUT_LOCATION)); request.setAttribute("changeDate", fp.getString("changeDate")); request.setAttribute(EVENT_BEAN, studyEvent); forwardPage(Page.UPDATE_STUDY_EVENT); } else if (studyEvent.getSubjectEventStatus().isSigned()) { // Checks if the status is signed // ----------------- request.setAttribute(STUDY_SUBJECT_ID, new Integer(studySubjectId).toString()); if (fp.getString(INPUT_STARTDATE_PREFIX + "Hour").equals("-1") && fp.getString(INPUT_STARTDATE_PREFIX + "Minute").equals("-1") && fp.getString(INPUT_STARTDATE_PREFIX + "Half").equals("")) { studyEvent.setStartTimeFlag(false); } else { studyEvent.setStartTimeFlag(true); } studyEvent.setDateStarted(start); if (!strEnd.equals("")) { studyEvent.setDateEnded(end); if (fp.getString(INPUT_ENDDATE_PREFIX + "Hour").equals("-1") && fp.getString(INPUT_ENDDATE_PREFIX + "Minute").equals("-1") && fp.getString(INPUT_ENDDATE_PREFIX + "Half").equals("")) { studyEvent.setEndTimeFlag(false); } else { studyEvent.setEndTimeFlag(true); } } studyEvent.setLocation(fp.getString(INPUT_LOCATION)); studyEvent.setStudyEventDefinition(sed); // ------------------- ssdao = new StudySubjectDAO(sm.getDataSource()); StudySubjectBean ssb = (StudySubjectBean) ssdao.findByPK(studyEvent.getStudySubjectId()); ecdao = new EventCRFDAO(sm.getDataSource()); eventCRFs = ecdao.findAllByStudyEvent(studyEvent); ArrayList<Boolean> doRuleSetsExist = new ArrayList<Boolean>(); RuleSetDAO ruleSetDao = new RuleSetDAO(sm.getDataSource()); StudyBean study = (StudyBean) sdao.findByPK(ssb.getStudyId()); ArrayList eventDefinitionCRFs = (ArrayList) edcdao.findAllActiveByEventDefinitionId(study, studyEvent.getStudyEventDefinitionId()); ArrayList uncompletedEventDefinitionCRFs = getUncompletedCRFs(eventDefinitionCRFs, eventCRFs); populateUncompletedCRFsWithCRFAndVersions(uncompletedEventDefinitionCRFs); ArrayList displayEventCRFs = ViewStudySubjectServlet.getDisplayEventCRFs(sm.getDataSource(), eventCRFs, eventDefinitionCRFs, ub, currentRole, studyEvent.getSubjectEventStatus(), study); request.setAttribute("studySubject", ssb); request.setAttribute("uncompletedEventDefinitionCRFs", uncompletedEventDefinitionCRFs); request.setAttribute("displayEventCRFs", displayEventCRFs); request.setAttribute(EVENT_BEAN, studyEvent); session.setAttribute("eventSigned", studyEvent); DiscrepancyNoteUtil discNoteUtil = new DiscrepancyNoteUtil(); DisplayStudyEventBean displayEvBean = new DisplayStudyEventBean(); List<DisplayStudyEventBean> displayEvents = new ArrayList<DisplayStudyEventBean>(); // Set up a Map for the JSP view, mapping the eventCRFId to // another Map: the // inner Map maps the resolution status name to the number of // notes for that // eventCRF id, as in New --> 2 displayEvBean.setDisplayEventCRFs(displayEventCRFs); displayEvBean.setStudyEvent(studyEvent); displayEvents.add(displayEvBean); // Don't filter for res status or disc note type; disc note // beans are returned with eventCRFId set discNoteUtil.injectParentDiscNotesIntoDisplayStudyEvents(displayEvents, new HashSet(), sm.getDataSource(), 0); Map discNoteByEventCRFid = discNoteUtil.createDiscNoteMapByEventCRF(displayEvents); request.setAttribute("discNoteByEventCRFid", discNoteByEventCRFid); session.setAttribute("signatureURL", request.getRequestURL()); String originationUrl = "UpdateStudyEvent?action=" + action + "%26event_id=" + studyEventId + "%26ss_id=" + studySubjectId + "%26startDate=" + start_date + "%26startHour=" + fp.getString(INPUT_STARTDATE_PREFIX + "Hour") + "%26startMinute=" + fp.getString(INPUT_STARTDATE_PREFIX + "Minute") + "%26startHalf=" + fp.getString(INPUT_STARTDATE_PREFIX + "Half") + "%26endDate=" + end_date + "%26endHour=" + fp.getString(INPUT_ENDDATE_PREFIX + "Hour") + "%26endMinute=" + fp.getString(INPUT_ENDDATE_PREFIX + "Minute") + "%26endHalf=" + fp.getString(INPUT_ENDDATE_PREFIX + "Half") + "%26statusId=" + studyEvent.getSubjectEventStatus().getId(); request.setAttribute(ORIGINATING_PAGE, originationUrl); // response.sendRedirect(request.getContextPath() + "/pages/userSignature"); forwardPage(Page.UPDATE_STUDY_EVENT_SIGNED); } else { logger.debug("no validation error"); // YW 08-17-2007 << update start_time_flag column if (fp.getString(INPUT_STARTDATE_PREFIX + "Hour").equals("-1") && fp.getString(INPUT_STARTDATE_PREFIX + "Minute").equals("-1") && fp.getString(INPUT_STARTDATE_PREFIX + "Half").equals("")) { studyEvent.setStartTimeFlag(false); } else { studyEvent.setStartTimeFlag(true); } // YW >> studyEvent.setDateStarted(start); // YW, 3-12-2008, 2220 fix which adding End datetime << if (!strEnd.equals("")) { studyEvent.setDateEnded(end); if (fp.getString(INPUT_ENDDATE_PREFIX + "Hour").equals("-1") && fp.getString(INPUT_ENDDATE_PREFIX + "Minute").equals("-1") && fp.getString(INPUT_ENDDATE_PREFIX + "Half").equals("")) { studyEvent.setEndTimeFlag(false); } else { studyEvent.setEndTimeFlag(true); } } // YW >> studyEvent.setLocation(fp.getString(INPUT_LOCATION)); logger.debug("update study event and discrepancy notes..."); studyEvent.setUpdater(ub); studyEvent.setUpdatedDate(new Date()); updateClosedQueriesForUpdatedStudySubjectFields(studyEvent); StudyEventBean updatedStudyEvent = (StudyEventBean) sedao.update(studyEvent); // save discrepancy notes into DB FormDiscrepancyNotes fdn = (FormDiscrepancyNotes) session .getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME); DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(sm.getDataSource()); AddNewSubjectServlet.saveFieldNotes(INPUT_LOCATION, fdn, dndao, studyEvent.getId(), "studyEvent", currentStudy); AddNewSubjectServlet.saveFieldNotes(INPUT_STARTDATE_PREFIX, fdn, dndao, studyEvent.getId(), "studyEvent", currentStudy); AddNewSubjectServlet.saveFieldNotes(INPUT_ENDDATE_PREFIX, fdn, dndao, studyEvent.getId(), "studyEvent", currentStudy); // getRuleSetService().runRulesInBeanProperty(createRuleSet(ssub,sed),currentStudy,ub,request,ssub); addPageMessage(respage.getString("study_event_updated")); request.setAttribute("id", new Integer(studySubjectId).toString()); session.removeAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME); forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET); // FORWARD SHOULD BE TO THE NEW PAGE } } else if (action.equalsIgnoreCase("confirm")) {// confirming the signed // status String username = request.getParameter("j_user"); String password = request.getParameter("j_pass"); if (username == null) username = ""; if (password == null) password = ""; // tring encodedUserPass = // org.akaza.openclinica.core.SecurityManager.getInstance().encrytPassword(password); UserAccountBean ub = (UserAccountBean) session.getAttribute("userBean"); StudyEventBean seb = (StudyEventBean) session.getAttribute("eventSigned"); Auth0UserService auth0UserService = ctx.getBean("auth0UserService", Auth0UserServiceImpl.class); boolean isAuthenticated = auth0UserService.authenticateAuth0User(username, password); if (isAuthenticated && ub.getName().equals(username)) { Date date = new Date(); seb.setUpdater(ub); seb.setUpdatedDate(date); seb.setAttestation("The eCRFs that are part of this event were signed by " + ub.getFirstName() + " " + ub.getLastName() + " (" + ub.getName() + ") " + "on Date Time " + date + " under the following attestation:\n\n" + resword.getString("sure_to_sign_subject3")); sedao.update(seb); // If all the StudyEvents become signed we will make the // StudySubject signed as well List studyEvents = sedao.findAllByStudySubject(ssub); boolean allSigned = true; for (Iterator iterator = studyEvents.iterator(); iterator.hasNext();) { StudyEventBean temp = (StudyEventBean) iterator.next(); if (!temp.getSubjectEventStatus().equals(SubjectEventStatus.SIGNED)) { allSigned = false; break; } } if (allSigned) { logger.debug("Signing StudySubject [" + ssub.getSubjectId() + "]"); ssub.setStatus(Status.SIGNED); ssub.setUpdater(ub); ssdao.update(ssub); } // save discrepancy notes into DB FormDiscrepancyNotes fdn = (FormDiscrepancyNotes) session .getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME); DiscrepancyNoteDAO dndao = new DiscrepancyNoteDAO(sm.getDataSource()); AddNewSubjectServlet.saveFieldNotes(INPUT_LOCATION, fdn, dndao, studyEvent.getId(), "studyEvent", currentStudy); AddNewSubjectServlet.saveFieldNotes(INPUT_STARTDATE_PREFIX, fdn, dndao, studyEvent.getId(), "studyEvent", currentStudy); AddNewSubjectServlet.saveFieldNotes(INPUT_ENDDATE_PREFIX, fdn, dndao, studyEvent.getId(), "studyEvent", currentStudy); session.removeAttribute("eventSigned"); request.setAttribute("id", new Integer(studySubjectId).toString()); addPageMessage(respage.getString("study_event_updated")); forwardPage(Page.VIEW_STUDY_SUBJECT_SERVLET); } else { request.setAttribute(STUDY_SUBJECT_ID, new Integer(studySubjectId).toString()); request.setAttribute("studyEvent", seb); // ------------------- ssdao = new StudySubjectDAO(sm.getDataSource()); StudySubjectBean ssb = (StudySubjectBean) ssdao.findByPK(studyEvent.getStudySubjectId()); // prepare to figure out what the display should look like EventCRFDAO ecdao = new EventCRFDAO(sm.getDataSource()); ArrayList<EventCRFBean> eventCRFs = ecdao.findAllByStudyEvent(studyEvent); ArrayList<Boolean> doRuleSetsExist = new ArrayList<Boolean>(); RuleSetDAO ruleSetDao = new RuleSetDAO(sm.getDataSource()); StudyBean study = (StudyBean) sdao.findByPK(ssb.getStudyId()); ArrayList eventDefinitionCRFs = (ArrayList) edcdao.findAllActiveByEventDefinitionId(study, studyEvent.getStudyEventDefinitionId()); ArrayList uncompletedEventDefinitionCRFs = getUncompletedCRFs(eventDefinitionCRFs, eventCRFs); populateUncompletedCRFsWithCRFAndVersions(uncompletedEventDefinitionCRFs); ArrayList<DisplayEventCRFBean> displayEventCRFs = ViewStudySubjectServlet.getDisplayEventCRFs( sm.getDataSource(), eventCRFs, eventDefinitionCRFs, ub, currentRole, studyEvent.getSubjectEventStatus(), study); DiscrepancyNoteUtil discNoteUtil = new DiscrepancyNoteUtil(); DisplayStudyEventBean displayEvBean = new DisplayStudyEventBean(); List<DisplayStudyEventBean> displayEvents = new ArrayList<DisplayStudyEventBean>(); displayEvBean.setDisplayEventCRFs(displayEventCRFs); displayEvBean.setStudyEvent(studyEvent); displayEvents.add(displayEvBean); discNoteUtil.injectParentDiscNotesIntoDisplayStudyEvents(displayEvents, new HashSet(), sm.getDataSource(), 0); Map discNoteByEventCRFid = discNoteUtil.createDiscNoteMapByEventCRF(displayEvents); request.setAttribute("discNoteByEventCRFid", discNoteByEventCRFid); request.setAttribute("studySubject", ssb); request.setAttribute("uncompletedEventDefinitionCRFs", uncompletedEventDefinitionCRFs); request.setAttribute("displayEventCRFs", displayEventCRFs); // ------------------ request.setAttribute("studyEvent", session.getAttribute("eventSigned")); addPageMessage(restext.getString("password_match")); String originationUrl = "UpdateStudyEvent?action=" + action + "%26event_id=" + studyEventId + "%26ss_id=" + studySubjectId + "%26startDate=" + start_date + "%26startHour=" + fp.getString(INPUT_STARTDATE_PREFIX + "Hour") + "%26startMinute=" + fp.getString(INPUT_STARTDATE_PREFIX + "Minute") + "%26startHalf=" + fp.getString(INPUT_STARTDATE_PREFIX + "Half") + "%26endDate=" + end_date + "%26endHour=" + fp.getString(INPUT_ENDDATE_PREFIX + "Hour") + "%26endMinute=" + fp.getString(INPUT_ENDDATE_PREFIX + "Minute") + "%26endHalf=" + fp.getString(INPUT_ENDDATE_PREFIX + "Half") + "%26statusId=" + studyEvent.getSubjectEventStatus().getId(); request.setAttribute(ORIGINATING_PAGE, originationUrl); forwardPage(Page.UPDATE_STUDY_EVENT_SIGNED); } } else { logger.debug("no action, go to update page"); DiscrepancyNoteDAO discrepancyNoteDAO = new DiscrepancyNoteDAO(sm.getDataSource()); StudySubjectBean studySubjectBean = (StudySubjectBean) ssdao.findByPK(studyEvent.getStudySubjectId()); int studyId = studySubjectBean.getStudyId(); boolean subjectStudyIsCurrentStudy = studyId == currentStudy.getId(); boolean isParentStudy = studyBean.getParentStudyId() < 1; ArrayList<DiscrepancyNoteBean> allNotesforSubjectAndEvent = new ArrayList<DiscrepancyNoteBean>(); allNotesforSubjectAndEvent = discrepancyNoteDAO.findExistingNoteForStudyEvent(studyEvent); if (!allNotesforSubjectAndEvent.isEmpty()) { setRequestAttributesForNotes(allNotesforSubjectAndEvent); } HashMap presetValues = new HashMap(); // YW 08-17-2007 << if (studyEvent.getDateStarted() != null) { if (studyEvent.getStartTimeFlag() == true) { Calendar c = new GregorianCalendar(); c.setTime(studyEvent.getDateStarted()); presetValues.put(INPUT_STARTDATE_PREFIX + "Hour", new Integer(c.get(Calendar.HOUR_OF_DAY))); presetValues.put(INPUT_STARTDATE_PREFIX + "Minute", new Integer(c.get(Calendar.MINUTE))); // Later it could be put to somewhere as a static method if // necessary. switch (c.get(Calendar.AM_PM)) { case 0: presetValues.put(INPUT_STARTDATE_PREFIX + "Half", "am"); break; case 1: presetValues.put(INPUT_STARTDATE_PREFIX + "Half", "pm"); break; default: presetValues.put(INPUT_STARTDATE_PREFIX + "Half", ""); break; } } else { presetValues.put(INPUT_STARTDATE_PREFIX + "Hour", new Integer(-1)); presetValues.put(INPUT_STARTDATE_PREFIX + "Minute", new Integer(-1)); presetValues.put(INPUT_STARTDATE_PREFIX + "Half", ""); } // YW >> String dateValue = local_df.format(studyEvent.getDateStarted()); presetValues.put(INPUT_STARTDATE_PREFIX + "Date", dateValue); // YW 3-12-2008, add end datetime for 2220 fix<< presetValues.put(INPUT_ENDDATE_PREFIX + "Hour", new Integer(-1)); presetValues.put(INPUT_ENDDATE_PREFIX + "Minute", new Integer(-1)); presetValues.put(INPUT_ENDDATE_PREFIX + "Half", ""); } if (studyEvent.getDateEnded() != null) { if (studyEvent.getEndTimeFlag() == true) { Calendar c = new GregorianCalendar(); c.setTime(studyEvent.getDateEnded()); presetValues.put(INPUT_ENDDATE_PREFIX + "Hour", new Integer(c.get(Calendar.HOUR_OF_DAY))); presetValues.put(INPUT_ENDDATE_PREFIX + "Minute", new Integer(c.get(Calendar.MINUTE))); // Later it could be put to somewhere as a static method if // necessary. switch (c.get(Calendar.AM_PM)) { case 0: presetValues.put(INPUT_ENDDATE_PREFIX + "Half", "am"); break; case 1: presetValues.put(INPUT_ENDDATE_PREFIX + "Half", "pm"); break; default: presetValues.put(INPUT_ENDDATE_PREFIX + "Half", ""); break; } } presetValues.put(INPUT_ENDDATE_PREFIX + "Date", local_df.format(studyEvent.getDateEnded())); } // YW >> setPresetValues(presetValues); request.setAttribute("studyEvent", studyEvent); request.setAttribute("studySubject", studySubjectBean); discNotes = new FormDiscrepancyNotes(); session.setAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME, discNotes); forwardPage(Page.UPDATE_STUDY_EVENT); } // else }
From source file:com.s3d.webapps.util.time.DateUtils.java
/** * <p>Internal calculation method.</p> * // w w w.j a va 2 s. c om * @param val the calendar * @param field the field constant * @param modType type to truncate, round or ceiling * @throws ArithmeticException if the year is over 280 million */ private static void modify(Calendar val, int field, int modType) { if (val.get(Calendar.YEAR) > 280000000) { throw new ArithmeticException("Calendar value too large for accurate calculations"); } if (field == Calendar.MILLISECOND) { return; } // ----------------- Fix for LANG-59 ---------------------- START --------------- // see http://issues.apache.org/jira/browse/LANG-59 // // Manually truncate milliseconds, seconds and minutes, rather than using // Calendar methods. Date date = val.getTime(); long time = date.getTime(); boolean done = false; // truncate milliseconds int millisecs = val.get(Calendar.MILLISECOND); if (MODIFY_TRUNCATE == modType || millisecs < 500) { time = time - millisecs; } if (field == Calendar.SECOND) { done = true; } // truncate seconds int seconds = val.get(Calendar.SECOND); if (!done && (MODIFY_TRUNCATE == modType || seconds < 30)) { time = time - (seconds * 1000L); } if (field == Calendar.MINUTE) { done = true; } // truncate minutes int minutes = val.get(Calendar.MINUTE); if (!done && (MODIFY_TRUNCATE == modType || minutes < 30)) { time = time - (minutes * 60000L); } // reset time if (date.getTime() != time) { date.setTime(time); val.setTime(date); } // ----------------- Fix for LANG-59 ----------------------- END ---------------- boolean roundUp = false; for (int i = 0; i < fields.length; i++) { for (int j = 0; j < fields[i].length; j++) { if (fields[i][j] == field) { //This is our field... we stop looping if (modType == MODIFY_CEILING || (modType == MODIFY_ROUND && roundUp)) { if (field == DateUtils.SEMI_MONTH) { //This is a special case that's hard to generalize //If the date is 1, we round up to 16, otherwise // we subtract 15 days and add 1 month if (val.get(Calendar.DATE) == 1) { val.add(Calendar.DATE, 15); } else { val.add(Calendar.DATE, -15); val.add(Calendar.MONTH, 1); } // ----------------- Fix for LANG-440 ---------------------- START --------------- } else if (field == Calendar.AM_PM) { // This is a special case // If the time is 0, we round up to 12, otherwise // we subtract 12 hours and add 1 day if (val.get(Calendar.HOUR_OF_DAY) == 0) { val.add(Calendar.HOUR_OF_DAY, 12); } else { val.add(Calendar.HOUR_OF_DAY, -12); val.add(Calendar.DATE, 1); } // ----------------- Fix for LANG-440 ---------------------- END --------------- } else { //We need at add one to this field since the // last number causes us to round up val.add(fields[i][0], 1); } } return; } } //We have various fields that are not easy roundings int offset = 0; boolean offsetSet = false; //These are special types of fields that require different rounding rules switch (field) { case DateUtils.SEMI_MONTH: if (fields[i][0] == Calendar.DATE) { //If we're going to drop the DATE field's value, // we want to do this our own way. //We need to subtrace 1 since the date has a minimum of 1 offset = val.get(Calendar.DATE) - 1; //If we're above 15 days adjustment, that means we're in the // bottom half of the month and should stay accordingly. if (offset >= 15) { offset -= 15; } //Record whether we're in the top or bottom half of that range roundUp = offset > 7; offsetSet = true; } break; case Calendar.AM_PM: if (fields[i][0] == Calendar.HOUR_OF_DAY) { //If we're going to drop the HOUR field's value, // we want to do this our own way. offset = val.get(Calendar.HOUR_OF_DAY); if (offset >= 12) { offset -= 12; } roundUp = offset >= 6; offsetSet = true; } break; } if (!offsetSet) { int min = val.getActualMinimum(fields[i][0]); int max = val.getActualMaximum(fields[i][0]); //Calculate the offset from the minimum allowed value offset = val.get(fields[i][0]) - min; //Set roundUp if this is more than half way between the minimum and maximum roundUp = offset > ((max - min) / 2); } //We need to remove this field if (offset != 0) { val.set(fields[i][0], val.get(fields[i][0]) - offset); } } throw new IllegalArgumentException("The field " + field + " is not supported"); }