List of usage examples for java.util Calendar roll
public void roll(int field, int amount)
From source file:org.exoplatform.wiki.jpa.JPADataStorageTest.java
@Test public void testDeleteDraftPageOfUserByNameAndTargetPage() throws WikiException { // Given//from ww w. jav a2 s. c om Wiki wiki = new Wiki(); wiki.setType("portal"); wiki.setOwner("wiki1"); wiki = storage.createWiki(wiki); Page page = new Page(); page.setWikiId(wiki.getId()); page.setWikiType(wiki.getType()); page.setWikiOwner(wiki.getOwner()); page.setName("page1"); page.setTitle("Page 1"); page.setContent("Content Page 1"); Page createdPage = storage.createPage(wiki, wiki.getWikiHome(), page); Calendar calendar = Calendar.getInstance(); Date now = calendar.getTime(); calendar.roll(Calendar.YEAR, -1); Date oneYearAgo = calendar.getTime(); DraftPage draftPage1 = new DraftPage(); draftPage1.setAuthor("user1"); draftPage1.setName("DraftPage1"); draftPage1.setTitle("DraftPage 1"); draftPage1.setContent("Content Page 1 User1"); draftPage1.setTargetPageId(createdPage.getId()); draftPage1.setTargetPageRevision("1"); draftPage1.setCreatedDate(oneYearAgo); draftPage1.setUpdatedDate(oneYearAgo); DraftPage draftPage2 = new DraftPage(); draftPage2.setAuthor("user2"); draftPage2.setName("DraftPage2"); draftPage2.setTitle("DraftPage 2"); draftPage2.setContent("Content Page 1 User 2"); draftPage2.setTargetPageId(createdPage.getId()); draftPage2.setTargetPageRevision("1"); draftPage2.setCreatedDate(now); draftPage2.setUpdatedDate(now); // When storage.createDraftPageForUser(draftPage1, "user1"); storage.createDraftPageForUser(draftPage2, "user2"); DraftPage initialDraftPageUser1 = storage.getDraft(new WikiPageParams("portal", "wiki1", "page1"), "user1"); DraftPage initialDraftPageUser2 = storage.getDraft(new WikiPageParams("portal", "wiki1", "page1"), "user2"); storage.deleteDraftOfPage(createdPage, "user1"); DraftPage updatedDraftPageUser1 = storage.getDraft(new WikiPageParams("portal", "wiki1", "page1"), "user1"); DraftPage updatedDraftPageUser2 = storage.getDraft(new WikiPageParams("portal", "wiki1", "page1"), "user2"); // Then assertNotNull(initialDraftPageUser1); assertNotNull(initialDraftPageUser2); assertNull(updatedDraftPageUser1); assertNotNull(updatedDraftPageUser2); }
From source file:org.exoplatform.wiki.jpa.JPADataStorageTest.java
@Test public void testDeleteDraftPageOfUserByName() throws WikiException { // Given// w w w . j a v a2 s . com Wiki wiki = new Wiki(); wiki.setType("portal"); wiki.setOwner("wiki1"); wiki = storage.createWiki(wiki); Page page = new Page(); page.setWikiId(wiki.getId()); page.setWikiType(wiki.getType()); page.setWikiOwner(wiki.getOwner()); page.setName("page1"); page.setTitle("Page 1"); page.setContent("Content Page 1"); Page createdPage = storage.createPage(wiki, wiki.getWikiHome(), page); Calendar calendar = Calendar.getInstance(); Date now = calendar.getTime(); calendar.roll(Calendar.YEAR, -1); Date oneYearAgo = calendar.getTime(); DraftPage draftPage1 = new DraftPage(); draftPage1.setAuthor("user1"); draftPage1.setName("DraftPage1"); draftPage1.setTitle("DraftPage 1"); draftPage1.setContent("Content Page 1 User1"); draftPage1.setTargetPageId(createdPage.getId()); draftPage1.setTargetPageRevision("1"); draftPage1.setUpdatedDate(oneYearAgo); draftPage1.setCreatedDate(oneYearAgo); DraftPage draftPage2 = new DraftPage(); draftPage2.setAuthor("user2"); draftPage2.setName("DraftPage2"); draftPage2.setTitle("DraftPage 2"); draftPage2.setContent("Content Page 1 User 2"); draftPage2.setTargetPageId(createdPage.getId()); draftPage2.setTargetPageRevision("1"); draftPage2.setUpdatedDate(now); draftPage2.setCreatedDate(now); // When storage.createDraftPageForUser(draftPage1, "user1"); storage.createDraftPageForUser(draftPage2, "user2"); DraftPage initialDraftPageUser1 = storage.getDraft(new WikiPageParams("portal", "wiki1", "page1"), "user1"); DraftPage initialDraftPageUser2 = storage.getDraft(new WikiPageParams("portal", "wiki1", "page1"), "user2"); storage.deleteDraftByName("DraftPage1", "user1"); DraftPage updatedDraftPageUser1 = storage.getDraft(new WikiPageParams("portal", "wiki1", "page1"), "user1"); DraftPage updatedDraftPageUser2 = storage.getDraft(new WikiPageParams("portal", "wiki1", "page1"), "user2"); // Then assertNotNull(initialDraftPageUser1); assertNotNull(initialDraftPageUser2); assertNull(updatedDraftPageUser1); assertNotNull(updatedDraftPageUser2); }
From source file:com.cloud.server.StatsCollector.java
private void init(Map<String, String> configs) { _executor = Executors.newScheduledThreadPool(6, new NamedThreadFactory("StatsCollector")); hostOutOfBandManagementStatsInterval = OutOfBandManagementService.SyncThreadInterval.value(); hostStatsInterval = NumbersUtil.parseLong(configs.get("host.stats.interval"), 60000L); hostAndVmStatsInterval = NumbersUtil.parseLong(configs.get("vm.stats.interval"), 60000L); storageStatsInterval = NumbersUtil.parseLong(configs.get("storage.stats.interval"), 60000L); volumeStatsInterval = NumbersUtil.parseLong(configs.get("volume.stats.interval"), -1L); autoScaleStatsInterval = NumbersUtil.parseLong(configs.get("autoscale.stats.interval"), 60000L); vmDiskStatsInterval = NumbersUtil.parseInt(configs.get("vm.disk.stats.interval"), 0); /* URI to send statistics to. Currently only Graphite is supported */ String externalStatsUri = configs.get("stats.output.uri"); if (externalStatsUri != null && !externalStatsUri.equals("")) { try {// w w w . ja v a2s . com URI uri = new URI(externalStatsUri); String scheme = uri.getScheme(); try { externalStatsType = ExternalStatsProtocol.valueOf(scheme.toUpperCase()); } catch (IllegalArgumentException e) { s_logger.info(scheme + " is not a valid protocol for external statistics. No statistics will be send."); } if (!StringUtils.isEmpty(uri.getHost())) { externalStatsHost = uri.getHost(); } externalStatsPort = uri.getPort(); if (!StringUtils.isEmpty(uri.getPath())) { externalStatsPrefix = uri.getPath().substring(1); } /* Append a dot (.) to the prefix if it is set */ if (!StringUtils.isEmpty(externalStatsPrefix)) { externalStatsPrefix += "."; } else { externalStatsPrefix = ""; } externalStatsEnabled = true; } catch (URISyntaxException e) { s_logger.debug("Failed to parse external statistics URI: " + e.getMessage()); } } if (hostStatsInterval > 0) { _executor.scheduleWithFixedDelay(new HostCollector(), 15000L, hostStatsInterval, TimeUnit.MILLISECONDS); } if (hostOutOfBandManagementStatsInterval > 0) { _executor.scheduleWithFixedDelay(new HostOutOfBandManagementStatsCollector(), 15000L, hostOutOfBandManagementStatsInterval, TimeUnit.MILLISECONDS); } if (hostAndVmStatsInterval > 0) { _executor.scheduleWithFixedDelay(new VmStatsCollector(), 15000L, hostAndVmStatsInterval, TimeUnit.MILLISECONDS); } if (storageStatsInterval > 0) { _executor.scheduleWithFixedDelay(new StorageCollector(), 15000L, storageStatsInterval, TimeUnit.MILLISECONDS); } if (autoScaleStatsInterval > 0) { _executor.scheduleWithFixedDelay(new AutoScaleMonitor(), 15000L, autoScaleStatsInterval, TimeUnit.MILLISECONDS); } if (vmDiskStatsInterval > 0) { if (vmDiskStatsInterval < 300) vmDiskStatsInterval = 300; _executor.scheduleAtFixedRate(new VmDiskStatsTask(), vmDiskStatsInterval, vmDiskStatsInterval, TimeUnit.SECONDS); } //Schedule disk stats update task _diskStatsUpdateExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("DiskStatsUpdater")); String aggregationRange = configs.get("usage.stats.job.aggregation.range"); _usageAggregationRange = NumbersUtil.parseInt(aggregationRange, 1440); _usageTimeZone = configs.get("usage.aggregation.timezone"); if (_usageTimeZone == null) { _usageTimeZone = "GMT"; } TimeZone usageTimezone = TimeZone.getTimeZone(_usageTimeZone); Calendar cal = Calendar.getInstance(usageTimezone); cal.setTime(new Date()); long endDate = 0; int HOURLY_TIME = 60; final int DAILY_TIME = 60 * 24; if (_usageAggregationRange == DAILY_TIME) { cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.roll(Calendar.DAY_OF_YEAR, true); cal.add(Calendar.MILLISECOND, -1); endDate = cal.getTime().getTime(); _dailyOrHourly = true; } else if (_usageAggregationRange == HOURLY_TIME) { cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.roll(Calendar.HOUR_OF_DAY, true); cal.add(Calendar.MILLISECOND, -1); endDate = cal.getTime().getTime(); _dailyOrHourly = true; } else { endDate = cal.getTime().getTime(); _dailyOrHourly = false; } if (_usageAggregationRange < UsageUtils.USAGE_AGGREGATION_RANGE_MIN) { s_logger.warn("Usage stats job aggregation range is to small, using the minimum value of " + UsageUtils.USAGE_AGGREGATION_RANGE_MIN); _usageAggregationRange = UsageUtils.USAGE_AGGREGATION_RANGE_MIN; } _diskStatsUpdateExecutor.scheduleAtFixedRate(new VmDiskStatsUpdaterTask(), (endDate - System.currentTimeMillis()), (_usageAggregationRange * 60 * 1000), TimeUnit.MILLISECONDS); }
From source file:com.zimbra.cs.mailbox.calendar.ZRecur.java
private List<Calendar> expandYearDayList(List<Calendar> list) { // this func ONLY works for expanding, NOT for contracting assert (mFreq == Frequency.YEARLY); if (mByYearDayList.size() <= 0) return list; List<Calendar> toRet = new LinkedList<Calendar>(); Set<Integer> years = new HashSet<Integer>(); for (Calendar cur : list) { int curYear = cur.get(Calendar.YEAR); if (!years.contains(curYear)) { years.add(curYear);//from w w w. java 2 s . c o m for (Integer yearDay : mByYearDayList) { if (yearDay > 0) cur.set(Calendar.DAY_OF_YEAR, yearDay); else { cur.set(Calendar.DAY_OF_YEAR, 1); cur.roll(Calendar.DAY_OF_YEAR, yearDay); } toRet.add((Calendar) (cur.clone())); } } // year already seen? } return toRet; }
From source file:com.zimbra.cs.mailbox.calendar.ZRecur.java
private List<Calendar> expandMonthDayList(List<Calendar> list) { // this func ONLY works for expanding, NOT for contracting assert (mFreq == Frequency.MONTHLY || mFreq == Frequency.YEARLY); if (mByMonthDayList.size() <= 0) return list; List<Calendar> toRet = new LinkedList<Calendar>(); for (Calendar cur : list) { int curMonth = cur.get(Calendar.MONTH); int lastMonthDay = cur.getActualMaximum(Calendar.DAY_OF_MONTH); boolean seenLastMonthDay = false; for (Integer moday : mByMonthDayList) { if (moday != 0) { if (moday > 0) { if (moday >= lastMonthDay) { if (seenLastMonthDay) continue; seenLastMonthDay = true; moday = lastMonthDay; }//from w w w . j av a 2 s . co m cur.set(Calendar.DAY_OF_MONTH, moday); } else { if (moday == -1) { if (seenLastMonthDay) continue; seenLastMonthDay = true; } cur.set(Calendar.DAY_OF_MONTH, 1); cur.roll(Calendar.DAY_OF_MONTH, moday); } assert (cur.get(Calendar.MONTH) == curMonth); toRet.add((Calendar) (cur.clone())); } } } return toRet; }
From source file:com.projity.contrib.calendar.JXXMonthView.java
/** * {@inheritDoc}/*from ww w.jav a 2 s.c om*/ */ protected void paintComponent(Graphics g) { Object oldAAValue = null; Graphics2D g2 = (g instanceof Graphics2D) ? (Graphics2D) g : null; if (g2 != null && _antiAlias) { oldAAValue = g2.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } Rectangle clip = g.getClipBounds(); updateIfNecessary(); if (isOpaque()) { g.setColor(getBackground()); g.fillRect(clip.x, clip.y, clip.width, clip.height); } g.setColor(getForeground()); Color shadowColor = g.getColor(); shadowColor = new Color(shadowColor.getRed(), shadowColor.getGreen(), shadowColor.getBlue(), (int) (.20 * 255)); FontMetrics fm = g.getFontMetrics(); // Reset the calendar. _cal.setTimeInMillis(_firstDisplayedDate); // Center the calendars vertically in the available space. int y = _startY; for (int row = 0; row < _numCalRows; row++) { // Center the calendars horizontally in the available space. int x = _startX; int tmpX, tmpY; // Check if this row falls in the clip region. _bounds.x = 0; _bounds.y = _startY + row * (_calendarHeight + CALENDAR_SPACING); _bounds.width = getWidth(); _bounds.height = _calendarHeight; if (!_bounds.intersects(clip)) { _cal.add(Calendar.MONTH, _numCalCols); y += _calendarHeight + CALENDAR_SPACING; continue; } for (int column = 0; column < _numCalCols; column++) { String monthName = _monthsOfTheYear[_cal.get(Calendar.MONTH)]; monthName = monthName + " " + _cal.get(Calendar.YEAR); _bounds.x = _ltr ? x : x - _calendarWidth; _bounds.y = y + _boxPaddingY; _bounds.width = _calendarWidth; _bounds.height = _boxHeight; if (_bounds.intersects(clip)) { // Paint month name background. paintMonthStringBackground(g, _bounds.x, _bounds.y, _bounds.width, _bounds.height); // Paint month name. g.setColor(getForeground()); tmpX = _ltr ? x + (_calendarWidth / 2) - (fm.stringWidth(monthName) / 2) : x - (_calendarWidth / 2) - (fm.stringWidth(monthName) / 2) - 1; tmpY = y + _boxPaddingY + _boxHeight - fm.getDescent(); g.drawString(monthName, tmpX, tmpY); if ((_dropShadowMask & MONTH_DROP_SHADOW) != 0) { g.setColor(shadowColor); g.drawString(monthName, tmpX + 1, tmpY + 1); g.setColor(getForeground()); } } _bounds.x = _ltr ? x : x - _calendarWidth; _bounds.y = y + _boxPaddingY + _boxHeight + _boxPaddingY + _boxPaddingY; _bounds.width = _calendarWidth; _bounds.height = _boxHeight; if (_bounds.intersects(clip)) { _cal.set(Calendar.DAY_OF_MONTH, _cal.getActualMinimum(Calendar.DAY_OF_MONTH)); Calendar weekCal = (Calendar) _cal.clone(); // Paint short representation of day of the week. int dayIndex = _firstDayOfWeek - 1; int month = weekCal.get(Calendar.MONTH); // dayIndex = (_cal.get(Calendar.DAY_OF_WEEK) -1) %7; for (int i = 0; i < DAYS_IN_WEEK; i++) { // PROJITY_MODIFICATION // set the week calendar to the current day of week and make sure it's still in this month weekCal.set(Calendar.DAY_OF_WEEK, dayIndex + 1); if (weekCal.get(Calendar.MONTH) != month) weekCal.roll(Calendar.DAY_OF_YEAR, 7); // make sure in this month tmpX = _ltr ? x + (i * (_boxPaddingX + _boxWidth + _boxPaddingX)) + _boxPaddingX + (_boxWidth / 2) - (fm.stringWidth(_daysOfTheWeek[dayIndex]) / 2) : x - (i * (_boxPaddingX + _boxWidth + _boxPaddingX)) - _boxPaddingX - (_boxWidth / 2) - (fm.stringWidth(_daysOfTheWeek[dayIndex]) / 2); tmpY = y + _boxPaddingY + _boxHeight + _boxPaddingY + _boxPaddingY + fm.getAscent(); boolean flagged = _flaggedWeekDates[dayIndex]; boolean colored = _coloredWeekDates[dayIndex]; calculateBoundsForDay(_bounds, weekCal, true); drawDay(colored, flagged, false, g, _daysOfTheWeek[dayIndex], tmpX, tmpY); // if ((_dropShadowMask & WEEK_DROP_SHADOW) != 0) { // calculateBoundsForDay(_bounds,weekCal,true); // add shadow arg // drawDay(colored,flagged,false,g,_daysOfTheWeek[dayIndex], tmpX + 1, // tmpY + 1); // } if (_selectedWeekDays[dayIndex]) { paintSelectedDayBackground(g, _bounds.x, _bounds.y, _bounds.width, _bounds.height); } dayIndex++; if (dayIndex == 7) { dayIndex = 0; } } int lineOffset = 2; // Paint a line across bottom of days of the week. g.drawLine(_ltr ? x + 2 : x - 3, lineOffset + y + (_boxPaddingY * 3) + (_boxHeight * 2), _ltr ? x + _calendarWidth - 3 : x - _calendarWidth + 2, lineOffset + y + (_boxPaddingY * 3) + (_boxHeight * 2)); if ((_dropShadowMask & MONTH_LINE_DROP_SHADOW) != 0) { g.setColor(shadowColor); g.drawLine(_ltr ? x + 3 : x - 2, y + (_boxPaddingY * 3) + (_boxHeight * 2) + 1, _ltr ? x + _calendarWidth - 2 : x - _calendarWidth + 3, y + (_boxPaddingY * 3) + (_boxHeight * 2) + 1); g.setColor(getForeground()); } } // Check if the month to paint falls in the clip. _bounds.x = _startX + (_ltr ? column * (_calendarWidth + CALENDAR_SPACING) : -(column * (_calendarWidth + CALENDAR_SPACING) + _calendarWidth)); _bounds.y = _startY + row * (_calendarHeight + CALENDAR_SPACING); _bounds.width = _calendarWidth; _bounds.height = _calendarHeight; // Paint the month if it intersects the clip. If we don't move // the calendar forward a month as it would have if paintMonth // was called. if (_bounds.intersects(clip)) { paintMonth(g, column, row); } else { _cal.add(Calendar.MONTH, 1); } x += _ltr ? _calendarWidth + CALENDAR_SPACING : -(_calendarWidth + CALENDAR_SPACING); } y += _calendarHeight + CALENDAR_SPACING; } // Restore the calendar. _cal.setTimeInMillis(_firstDisplayedDate); if (g2 != null && _antiAlias) { g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, oldAAValue); } }
From source file:org.alfresco.web.forms.xforms.Schema2XForms.java
/** * Creates a form control for an XML Schema simple atomic type. * <p/>// www. j a va 2s . c o m * This method is called when the form builder determines a form control is required for * an atomic type. * The implementation of this method is responsible for creating an XML element of the * appropriate type to receive a value for <b>controlType</b>. The caller is responsible * for adding the returned element to the form and setting caption, bind, and other * standard elements and attributes. * * @param xformsDocument The XForm document. * @param controlType The XML Schema type for which the form control is to be created. * @return The element for the form control. */ public Element createControlForAtomicType(final Document xformsDocument, final XSSimpleTypeDefinition controlType, final XSObject owner, final String caption, final ResourceBundle resourceBundle) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("[createControlForAtomicType] {name: " + controlType.getName() + ", numeric: " + controlType.getNumeric() + ", bounded: " + controlType.getBounded() + ", finite: " + controlType.getFinite() + ", ordered: " + controlType.getOrdered() + ", final: " + controlType.getFinal() + ", minInc: " + controlType.getLexicalFacetValue(XSSimpleTypeDefinition.FACET_MININCLUSIVE) + ", maxInc: " + controlType.getLexicalFacetValue(XSSimpleTypeDefinition.FACET_MAXINCLUSIVE) + ", minExc: " + controlType.getLexicalFacetValue(XSSimpleTypeDefinition.FACET_MINEXCLUSIVE) + ", maxExc: " + controlType.getLexicalFacetValue(XSSimpleTypeDefinition.FACET_MAXEXCLUSIVE) + ", totalDigits: " + controlType.getLexicalFacetValue(XSSimpleTypeDefinition.FACET_TOTALDIGITS) + ", length: " + controlType.getLexicalFacetValue(XSSimpleTypeDefinition.FACET_LENGTH) + ", minLength: " + controlType.getLexicalFacetValue(XSSimpleTypeDefinition.FACET_MINLENGTH) + ", maxLength: " + controlType.getLexicalFacetValue(XSSimpleTypeDefinition.FACET_MAXLENGTH) + ", fractionDigits: " + controlType.getLexicalFacetValue(XSSimpleTypeDefinition.FACET_FRACTIONDIGITS) + ", builtInTypeName: " + SchemaUtil.getBuiltInTypeName(controlType) + ", builtInType: " + SchemaUtil.getBuiltInType(controlType) + "}"); } String appearance = extractPropertyFromAnnotation(NamespaceService.ALFRESCO_URI, "appearance", this.getAnnotation(owner), resourceBundle); Element result = null; if (controlType.getNumeric()) { if (controlType.getBounded() && controlType.getLexicalFacetValue(XSSimpleTypeDefinition.FACET_MAXINCLUSIVE) != null && controlType.getLexicalFacetValue(XSSimpleTypeDefinition.FACET_MININCLUSIVE) != null) { result = xformsDocument.createElementNS(NamespaceConstants.XFORMS_NS, NamespaceConstants.XFORMS_PREFIX + ":range"); result.setAttributeNS(NamespaceConstants.XFORMS_NS, NamespaceConstants.XFORMS_PREFIX + ":start", controlType.getLexicalFacetValue(XSSimpleTypeDefinition.FACET_MININCLUSIVE)); result.setAttributeNS(NamespaceConstants.XFORMS_NS, NamespaceConstants.XFORMS_PREFIX + ":end", controlType.getLexicalFacetValue(XSSimpleTypeDefinition.FACET_MAXINCLUSIVE)); } else { result = xformsDocument.createElementNS(NamespaceConstants.XFORMS_NS, NamespaceConstants.XFORMS_PREFIX + ":input"); } if (controlType.isDefinedFacet(XSSimpleTypeDefinition.FACET_FRACTIONDIGITS)) { String fractionDigits = controlType .getLexicalFacetValue(XSSimpleTypeDefinition.FACET_FRACTIONDIGITS); if (fractionDigits == null || fractionDigits.length() == 0) { final short builtInType = SchemaUtil.getBuiltInType(controlType); fractionDigits = (builtInType >= XSConstants.INTEGER_DT && builtInType <= XSConstants.POSITIVEINTEGER_DT ? "0" : null); } if (fractionDigits != null) { result.setAttributeNS(NamespaceService.ALFRESCO_URI, NamespaceService.ALFRESCO_PREFIX + ":fractionDigits", fractionDigits); } } if (controlType.isDefinedFacet(XSSimpleTypeDefinition.FACET_TOTALDIGITS)) { result.setAttributeNS(NamespaceService.ALFRESCO_URI, NamespaceService.ALFRESCO_PREFIX + ":totalDigits", controlType.getLexicalFacetValue(XSSimpleTypeDefinition.FACET_TOTALDIGITS)); } } else { switch (SchemaUtil.getBuiltInType(controlType)) { case XSConstants.BOOLEAN_DT: { result = xformsDocument.createElementNS(NamespaceConstants.XFORMS_NS, NamespaceConstants.XFORMS_PREFIX + ":select1"); final String[] values = { "true", "false" }; for (String v : values) { final Element item = this.createXFormsItem(xformsDocument, v, v); result.appendChild(item); } break; } case XSConstants.STRING_DT: { result = xformsDocument.createElementNS(NamespaceConstants.XFORMS_NS, NamespaceConstants.XFORMS_PREFIX + ":textarea"); if (appearance == null || appearance.length() == 0) { appearance = "compact"; } break; } case XSConstants.ANYURI_DT: { result = xformsDocument.createElementNS(NamespaceConstants.XFORMS_NS, NamespaceConstants.XFORMS_PREFIX + ":upload"); final Element e = xformsDocument.createElementNS(NamespaceConstants.XFORMS_NS, NamespaceConstants.XFORMS_PREFIX + ":filename"); this.setXFormsId(e); result.appendChild(e); e.setAttributeNS(NamespaceConstants.XFORMS_NS, NamespaceConstants.XFORMS_PREFIX + ":ref", "."); break; } default: { result = xformsDocument.createElementNS(NamespaceConstants.XFORMS_NS, NamespaceConstants.XFORMS_PREFIX + ":input"); if ((appearance == null || appearance.length() == 0) && SchemaUtil.getBuiltInType(controlType) == XSConstants.NORMALIZEDSTRING_DT) { appearance = "full"; } if (controlType.isDefinedFacet(XSSimpleTypeDefinition.FACET_LENGTH)) { result.setAttributeNS(NamespaceService.ALFRESCO_URI, NamespaceService.ALFRESCO_PREFIX + ":length", controlType.getLexicalFacetValue(XSSimpleTypeDefinition.FACET_LENGTH)); } else if (controlType.isDefinedFacet(XSSimpleTypeDefinition.FACET_MINLENGTH) || controlType.isDefinedFacet(XSSimpleTypeDefinition.FACET_MAXLENGTH)) { if (controlType.isDefinedFacet(XSSimpleTypeDefinition.FACET_MINLENGTH)) { result.setAttributeNS(NamespaceService.ALFRESCO_URI, NamespaceService.ALFRESCO_PREFIX + ":minLength", controlType.getLexicalFacetValue(XSSimpleTypeDefinition.FACET_MINLENGTH)); } if (controlType.isDefinedFacet(XSSimpleTypeDefinition.FACET_MAXLENGTH)) { result.setAttributeNS(NamespaceService.ALFRESCO_URI, NamespaceService.ALFRESCO_PREFIX + ":maxLength", controlType.getLexicalFacetValue(XSSimpleTypeDefinition.FACET_MAXLENGTH)); } } if (SchemaUtil.getBuiltInType(controlType) == XSConstants.DATE_DT) { String minInclusive = null; String maxInclusive = null; final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); final Calendar calendar = Calendar.getInstance(); if (controlType.isDefinedFacet(XSSimpleTypeDefinition.FACET_MAXEXCLUSIVE)) { minInclusive = controlType.getLexicalFacetValue(XSSimpleTypeDefinition.FACET_MINEXCLUSIVE); try { final Date d = sdf.parse(minInclusive); calendar.setTime(d); } catch (ParseException pe) { LOGGER.error(pe); } calendar.roll(Calendar.DATE, true); minInclusive = sdf.format(calendar.getTime()); } else if (controlType.isDefinedFacet(XSSimpleTypeDefinition.FACET_MININCLUSIVE)) { minInclusive = controlType.getLexicalFacetValue(XSSimpleTypeDefinition.FACET_MININCLUSIVE); } if (controlType.isDefinedFacet(XSSimpleTypeDefinition.FACET_MAXEXCLUSIVE)) { maxInclusive = controlType.getLexicalFacetValue(XSSimpleTypeDefinition.FACET_MAXEXCLUSIVE); try { final Date d = sdf.parse(maxInclusive); calendar.setTime(d); } catch (ParseException pe) { LOGGER.error(pe); } calendar.roll(Calendar.DATE, false); maxInclusive = sdf.format(calendar.getTime()); } else if (controlType.isDefinedFacet(XSSimpleTypeDefinition.FACET_MAXINCLUSIVE)) { maxInclusive = controlType.getLexicalFacetValue(XSSimpleTypeDefinition.FACET_MAXINCLUSIVE); } if (minInclusive != null) { result.setAttributeNS(NamespaceService.ALFRESCO_URI, NamespaceService.ALFRESCO_PREFIX + ":minInclusive", minInclusive); } if (maxInclusive != null) { result.setAttributeNS(NamespaceService.ALFRESCO_URI, NamespaceService.ALFRESCO_PREFIX + ":maxInclusive", maxInclusive); } } } } } this.setXFormsId(result); result.appendChild(this.createLabel(xformsDocument, caption)); if (appearance != null && appearance.length() != 0) { result.setAttributeNS(NamespaceConstants.XFORMS_NS, NamespaceConstants.XFORMS_PREFIX + ":appearance", appearance); } return result; }
From source file:org.mifos.accounts.loan.business.LoanBOIntegrationTest.java
public void testDisbursalLoanRegeneteRepaymentScheduleWithInvalidDisbDate() throws Exception { // Allowing loan disbursal dates to become independent of meeting // schedules. Date startDate = new Date(System.currentTimeMillis()); accountBO = getLoanAccount(AccountState.LOAN_APPROVED, startDate, 3); // disburse loan Calendar disbDate = new GregorianCalendar(); disbDate.setTimeInMillis(startDate.getTime()); disbDate.roll(Calendar.DATE, 1); Date disbursalDate = new Date(disbDate.getTimeInMillis()); try {//www . j av a 2 s .c o m ((LoanBO) accountBO).disburseLoan("1234", disbursalDate, Short.valueOf("1"), accountBO.getPersonnel(), startDate, Short.valueOf("1")); Assert.assertEquals(true, true); } catch (ApplicationException rse) { Assert.assertEquals(true, false); } finally { Session session = StaticHibernateUtil.getSessionTL(); StaticHibernateUtil.startTransaction(); ((LoanBO) accountBO).setLoanMeeting(null); session.update(accountBO); StaticHibernateUtil.getTransaction().commit(); } }
From source file:com.nest5.businessClient.Initialactivity.java
private void makeDailyTable(int TABLE_TYPE) { dailyTable.removeAllViews();//from w w w .j av a2 s . c om Double total = 0.0; DecimalFormat dec = new DecimalFormat("$###,###,###"); TextView tv = new TextView(mContext); tv.setBackgroundColor(Color.parseColor("#80808080")); tv.setHeight(2); TableRow tr1 = (TableRow) getLayoutInflater().inflate(R.layout.daily_table_row, null); TextView tDate1 = (TextView) tr1.findViewById(R.id.cell_date); TextView tItem1 = (TextView) tr1.findViewById(R.id.cell_item); TextView tAccount1 = (TextView) tr1.findViewById(R.id.cell_account); TextView tVal1 = (TextView) tr1.findViewById(R.id.cell_value); TextView tTot1 = (TextView) tr1.findViewById(R.id.cell_total); tDate1.setText("FECHA"); tAccount1.setText("CUENTA"); tItem1.setText("ITEM"); tVal1.setText("VALOR"); tTot1.setText("TOTAL"); tr1.setBackgroundColor(Color.CYAN); dailyTable.addView(tr1); dailyTable.addView(tv); //actualizar sales de hoy Calendar today = Calendar.getInstance(); Calendar tomorrow = Calendar.getInstance(); today.set(Calendar.HOUR, 0); today.set(Calendar.HOUR_OF_DAY, 0); today.set(Calendar.MINUTE, 0); today.set(Calendar.SECOND, 0); today.set(Calendar.MILLISECOND, 0); tomorrow.roll(Calendar.DATE, 1); tomorrow.set(Calendar.HOUR, 0); tomorrow.set(Calendar.HOUR_OF_DAY, 0); tomorrow.set(Calendar.MINUTE, 0); tomorrow.set(Calendar.SECOND, 0); tomorrow.set(Calendar.MILLISECOND, 0); init = today.getTimeInMillis(); end = tomorrow.getTimeInMillis(); Log.d("GUARDANDOVENTA", today.toString()); Log.d("GUARDANDOVENTA", tomorrow.toString()); Calendar now = Calendar.getInstance(); now.setTimeInMillis(System.currentTimeMillis()); Log.d(TAG, now.toString()); Log.d(TAG, "Diferencia entre tiempos: " + String.valueOf(end - init)); salesFromToday = saleDataSource.getAllSalesWithin(init, end); List<Sale> usingSales = salesFromToday; switch (TABLE_TYPE) { case TABLE_TYPE_TODAY: usingSales = salesFromToday; break; case TABLE_TYPE_ALL: usingSales = saleList; break; } for (Sale currentSale : usingSales) { double totalLocal = 0.0; LinkedHashMap<Combo, Double> combos = currentSale.getCombos(); LinkedHashMap<Product, Double> products = currentSale.getProducts(); LinkedHashMap<Ingredient, Double> ingredients = currentSale.getIngredients(); Log.w("DAYILETABLES", " " + combos.size() + " " + products.size() + " " + ingredients.size()); Iterator<Entry<Combo, Double>> it = combos.entrySet().iterator(); Calendar date = Calendar.getInstance(); date.setTimeInMillis(currentSale.getDate()); String fecha = date.get(Calendar.MONTH) + "/" + date.get(Calendar.DAY_OF_MONTH) + "/" + date.get(Calendar.YEAR) + "\n" + date.get(Calendar.HOUR_OF_DAY) + ":" + date.get(Calendar.MINUTE) + ":" + date.get(Calendar.SECOND); String account = currentSale.getPaymentMethod(); while (it.hasNext()) { TableRow tr = (TableRow) getLayoutInflater().inflate(R.layout.daily_table_row, null); TextView tDate = (TextView) tr.findViewById(R.id.cell_date); TextView tItem = (TextView) tr.findViewById(R.id.cell_item); TextView tAccount = (TextView) tr.findViewById(R.id.cell_account); TextView tVal = (TextView) tr.findViewById(R.id.cell_value); TextView tTot = (TextView) tr.findViewById(R.id.cell_total); Map.Entry<Combo, Double> pair = (Map.Entry<Combo, Double>) it.next(); Double value = pair.getValue() * pair.getKey().getPrice(); tDate.setText(fecha); tAccount.setText(account); tItem.setText(pair.getKey().getName() + " en Combo"); tVal.setText(dec.format(value)); tTot.setText("----"); total += value; totalLocal += value; dailyTable.addView(tr); // Log.d("INGREDIENTES","INGREDIENTE: "+ingrediente.getKey().getName()+" "+ingrediente.getValue()); } Iterator<Entry<Product, Double>> it2 = products.entrySet().iterator(); while (it2.hasNext()) { Map.Entry<Product, Double> pair = (Map.Entry<Product, Double>) it2.next(); TableRow tr = (TableRow) getLayoutInflater().inflate(R.layout.daily_table_row, null); TextView tDate = (TextView) tr.findViewById(R.id.cell_date); TextView tItem = (TextView) tr.findViewById(R.id.cell_item); TextView tAccount = (TextView) tr.findViewById(R.id.cell_account); TextView tVal = (TextView) tr.findViewById(R.id.cell_value); TextView tTot = (TextView) tr.findViewById(R.id.cell_total); Double value = pair.getValue() * pair.getKey().getPrice(); tDate.setText(fecha); tAccount.setText(account); tItem.setText(pair.getKey().getName()); tVal.setText(dec.format(value)); tTot.setText("----"); total += value; totalLocal += value; dailyTable.addView(tr); // Log.d("INGREDIENTES","INGREDIENTE: "+ingrediente.getKey().getName()+" "+ingrediente.getValue()); } Iterator<Entry<Ingredient, Double>> it3 = ingredients.entrySet().iterator(); while (it3.hasNext()) { Map.Entry<Ingredient, Double> pair = (Map.Entry<Ingredient, Double>) it3.next(); TableRow tr = (TableRow) getLayoutInflater().inflate(R.layout.daily_table_row, null); TextView tDate = (TextView) tr.findViewById(R.id.cell_date); TextView tItem = (TextView) tr.findViewById(R.id.cell_item); TextView tAccount = (TextView) tr.findViewById(R.id.cell_account); TextView tVal = (TextView) tr.findViewById(R.id.cell_value); TextView tTot = (TextView) tr.findViewById(R.id.cell_total); Double value = pair.getValue() * pair.getKey().getPrice(); tDate.setText(fecha); tAccount.setText(account); tItem.setText(pair.getKey().getName()); tVal.setText(dec.format(value)); tTot.setText("----"); total += value; totalLocal += value; dailyTable.addView(tr); // Log.d("INGREDIENTES","INGREDIENTE: "+ingrediente.getKey().getName()+" "+ingrediente.getValue()); } TableRow tr = (TableRow) getLayoutInflater().inflate(R.layout.daily_table_row, null); TextView tDate = (TextView) tr.findViewById(R.id.cell_date); TextView tItem = (TextView) tr.findViewById(R.id.cell_item); TextView tAccount = (TextView) tr.findViewById(R.id.cell_account); TextView tVal = (TextView) tr.findViewById(R.id.cell_value); TextView tTot = (TextView) tr.findViewById(R.id.cell_total); tDate.setText(fecha); tAccount.setText("-------"); tItem.setText("Ingreso por Ventas"); tVal.setText("----"); tTot.setText(dec.format(totalLocal)); tr.setBackgroundColor(Color.LTGRAY); dailyTable.addView(tr); TableRow tr2 = (TableRow) getLayoutInflater().inflate(R.layout.daily_table_row, null); TextView tDate2 = (TextView) tr2.findViewById(R.id.cell_date); TextView tItem2 = (TextView) tr2.findViewById(R.id.cell_item); TextView tAccount2 = (TextView) tr2.findViewById(R.id.cell_account); TextView tVal2 = (TextView) tr2.findViewById(R.id.cell_value); TextView tTot2 = (TextView) tr2.findViewById(R.id.cell_total); tDate2.setText(fecha); tAccount2.setText("-------"); tItem2.setText("Acumulado por Ventas"); tVal2.setText("----"); tTot2.setText(dec.format(total)); tr2.setBackgroundColor(Color.GRAY); dailyTable.addView(tr2); } }
From source file:com.nest5.businessClient.Initialactivity.java
/** * Begins the activity.//from w w w.jav a 2s . com */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.savedInstanceState = savedInstanceState; getWindow().setFormat(PixelFormat.RGBA_8888); getWindow().addFlags(WindowManager.LayoutParams.FLAG_DITHER); BugSenseHandler.initAndStartSession(Initialactivity.this, "1a5a6af1"); setContentView(R.layout.swipe_view); checkLogin(); // add necessary intent values to be matched. intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION); intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION); intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION); intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION); manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE); channel = manager.initialize(this, getMainLooper(), null); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); dbHelper = new MySQLiteHelper(this); ingredientCategoryDatasource = new IngredientCategoryDataSource(dbHelper); db = ingredientCategoryDatasource.open(); ingredientCategories = ingredientCategoryDatasource.getAllIngredientCategory(); // ingredientCategoryDatasource.close(); productCategoryDatasource = new ProductCategoryDataSource(dbHelper); productCategoryDatasource.open(db); productsCategories = productCategoryDatasource.getAllProductCategory(); taxDataSource = new TaxDataSource(dbHelper); taxDataSource.open(db); taxes = taxDataSource.getAllTax(); unitDataSource = new UnitDataSource(dbHelper); unitDataSource.open(db); units = unitDataSource.getAllUnits(); ingredientDatasource = new IngredientDataSource(dbHelper); ingredientDatasource.open(db); ingredientes = ingredientDatasource.getAllIngredient(); productDatasource = new ProductDataSource(dbHelper); productDatasource.open(db); productos = productDatasource.getAllProduct(); comboDatasource = new ComboDataSource(dbHelper); comboDatasource.open(db); combos = comboDatasource.getAllCombos(); saleDataSource = new SaleDataSource(dbHelper); saleDataSource.open(db); saleList = saleDataSource.getAllSales(); syncRowDataSource = new SyncRowDataSource(dbHelper); syncRowDataSource.open(db); Calendar today = Calendar.getInstance(); Calendar tomorrow = Calendar.getInstance(); today.set(Calendar.HOUR, 0); today.set(Calendar.HOUR_OF_DAY, 0); today.set(Calendar.MINUTE, 0); today.set(Calendar.SECOND, 0); today.set(Calendar.MILLISECOND, 0); tomorrow.roll(Calendar.DATE, 1); tomorrow.set(Calendar.HOUR, 0); tomorrow.set(Calendar.HOUR_OF_DAY, 0); tomorrow.set(Calendar.MINUTE, 0); tomorrow.set(Calendar.SECOND, 0); tomorrow.set(Calendar.MILLISECOND, 0); init = today.getTimeInMillis(); end = tomorrow.getTimeInMillis(); //Log.d(TAG, today.toString()); //Log.d(TAG, tomorrow.toString()); Calendar now = Calendar.getInstance(); now.setTimeInMillis(System.currentTimeMillis()); //Log.d(TAG, now.toString()); //Log.d(TAG, "Diferencia entre tiempos: " + String.valueOf(end - init)); salesFromToday = saleDataSource.getAllSalesWithin(init, end); updateRegistrables(); // ingredientDatasource.close(); mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager()); mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mDemoCollectionPagerAdapter); mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { // When swiping between pages, select the // corresponding tab. getActionBar().setSelectedNavigationItem(position); } }); final ActionBar actionBar = getActionBar(); // Specify that tabs should be displayed in the action bar. actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Create a tab listener that is called when the user changes tabs. ActionBar.TabListener tabListener = new ActionBar.TabListener() { @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub } }; Tab homeTab = actionBar.newTab().setText("Inicio").setTabListener(tabListener); Tab ordersTab = actionBar.newTab().setText("rdenes").setTabListener(tabListener); /*Tab dailyTab = actionBar.newTab().setText("Registros") .setTabListener(tabListener); Tab inventoryTab = actionBar.newTab().setText("Inventarios") .setTabListener(tabListener);*/ Tab nest5ReadTab = actionBar.newTab().setText("Nest5").setTabListener(tabListener); actionBar.addTab(homeTab, true); actionBar.addTab(ordersTab, false); //actionBar.addTab(dailyTab, false); //actionBar.addTab(inventoryTab, false); actionBar.addTab(nest5ReadTab, false); currentOrder = new LinkedHashMap<Registrable, Integer>(); inTableRegistrable = new ArrayList<Registrable>(); savedOrders = new LinkedHashMap<String, LinkedHashMap<Registrable, Integer>>(); cookingOrders = new LinkedList<LinkedHashMap<Registrable, Integer>>(); //cookingOrdersMethods = new LinkedHashMap<LinkedHashMap<Registrable, Integer>, String>(); cookingOrdersDelivery = new LinkedHashMap<LinkedHashMap<Registrable, Integer>, Integer>(); cookingOrdersTogo = new LinkedHashMap<LinkedHashMap<Registrable, Integer>, Integer>(); //cookingOrdersTip = new LinkedHashMap<LinkedHashMap<Registrable, Integer>, Integer>(); //cookingOrdersDiscount = new LinkedHashMap<LinkedHashMap<Registrable, Integer>, Double>(); cookingOrdersTimes = new LinkedHashMap<LinkedHashMap<Registrable, Integer>, Long>(); cookingOrdersTable = new LinkedHashMap<LinkedHashMap<Registrable, Integer>, CurrentTable<Table, Integer>>(); openTables = new LinkedList<CurrentTable<Table, Integer>>(); //cookingOrdersReceived = new LinkedHashMap<LinkedHashMap<Registrable, Integer>, Double>(); frases = getResources().getStringArray(R.array.phrases); timer = new Timer(); deviceID = DeviceID.getDeviceId(mContext); //////Log.i("AACCCAAAID",deviceID); BebasFont = Typeface.createFromAsset(getAssets(), "fonts/BebasNeue.otf"); VarelaFont = Typeface.createFromAsset(getAssets(), "fonts/Varela-Regular.otf"); // Lector de tarjetas magnticas mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); //mReader = new ACR31Reader(mAudioManager); /* Initialize the reset progress dialog */ mResetProgressDialog = new ProgressDialog(mContext); // ACR31 RESET CALLBACK /*mReader.setOnResetCompleteListener(new ACR31Reader.OnResetCompleteListener() { //hola como estas @Override public void onResetComplete(ACR31Reader reader) { if (mSettingSleepTimeout) { mGettingStatus = true; mReader.setSleepTimeout(mSleepTimeout); mSettingSleepTimeout = false; } runOnUiThread(new Runnable() { @Override public void run() { mResetProgressDialog.dismiss(); }; }); } });*/ /* Set the raw data callback. */ /*mReader.setOnRawDataAvailableListener(new ACR31Reader.OnRawDataAvailableListener() { @Override public void onRawDataAvailable(ACR31Reader reader, byte[] rawData) { ////Log.i("MISPRUEBAS", "setOnRawDataAvailableListener"); final String hexString = toHexString(rawData) + (reader.verifyData(rawData) ? " (Checksum OK)" : " (Checksum Error)"); ////Log.i("MISPRUEBAS", hexString); if (reader.verifyData(rawData)) { runOnUiThread(new Runnable() { @Override public void run() { mResetProgressDialog .setMessage("Solicitando Informacin al Servidor..."); mResetProgressDialog.setCancelable(false); mResetProgressDialog.setIndeterminate(true); mResetProgressDialog.show(); } }); SharedPreferences prefs = Util .getSharedPreferences(mContext); restService = new RestService(recievePromoandUserHandler, mContext, Setup.PROD_URL + "/company/initMagneticStamp"); restService.addParam("company", prefs.getString(Setup.COMPANY_ID, "0")); restService.addParam("magnetic5", hexString); restService.setCredentials("apiadmin", Setup.apiKey); try { restService.execute(RestService.POST); } catch (Exception e) { e.printStackTrace(); ////Log.i("MISPRUEBAS", "Error empezando request"); } } } });*/ }