List of usage examples for org.joda.time DateTime minusDays
public DateTime minusDays(int days)
From source file:org.jasig.cas.adaptors.ldap.LdapPasswordPolicyEnforcer.java
License:Apache License
/** * Calculates the number of days left to the expiration date based on the * {@code expireDate} parameter.//w ww. j ava 2s . c o m * @param expireDate * @param userId * @return number of days left to the expiration date, or {@value #PASSWORD_STATUS_PASS} */ private long getDaysToExpirationDate(final String userId, final DateTime expireDate) throws LdapPasswordPolicyEnforcementException { log.debug("Calculating number of days left to the expiration date for user {}", userId); final DateTime currentTime = new DateTime(DEFAULT_TIME_ZONE); log.info("Current date is {}, expiration date is {}", currentTime.toString(), expireDate.toString()); final Days d = Days.daysBetween(currentTime, expireDate); int daysToExpirationDate = d.getDays(); if (expireDate.equals(currentTime) || expireDate.isBefore(currentTime)) { String msgToLog = "Authentication failed because account password has expired with " + daysToExpirationDate + " to expiration date. "; msgToLog += "Verify the value of the " + this.dateAttribute + " attribute and make sure it's not before the current date, which is " + currentTime.toString(); final LdapPasswordPolicyEnforcementException exc = new LdapPasswordPolicyEnforcementException(msgToLog); log.error(msgToLog, exc); throw exc; } /* * Warning period begins from X number of ways before the expiration date */ DateTime warnPeriod = new DateTime(DateTime.parse(expireDate.toString()), DEFAULT_TIME_ZONE); warnPeriod = warnPeriod.minusDays(this.warningDays); log.info("Warning period begins on {}", warnPeriod.toString()); if (this.warnAll) { log.info("Warning all. The password for {} will expire in {} days.", userId, daysToExpirationDate); } else if (currentTime.equals(warnPeriod) || currentTime.isAfter(warnPeriod)) { log.info("Password will expire in {} days.", daysToExpirationDate); } else { log.info("Password is not expiring. {} days left to the warning", daysToExpirationDate); daysToExpirationDate = PASSWORD_STATUS_PASS; } return daysToExpirationDate; }
From source file:org.jmxtrans.embedded.samples.graphite.BasicAppMetricsSimulator.java
License:Open Source License
public void generateLoad(GraphiteDataInjector graphiteDataInjector) throws Exception { int dataPointIntervalInSeconds = 30; int scaleFactor = 2; TimeSeries timeSeries = new TimeSeries("www.requestsCounter"); DateTime now = new DateTime(); DateTime end = now.plusDays(2);//from w ww . j a va2 s. co m DateTime date = now.minusDays(1); int integratedValue = 0; while (date.isBefore(end)) { integratedValue += dataPointIntervalInSeconds * scaleFactor; timeSeries.add(new Second(date.toDate()), integratedValue); date = date.plusSeconds(dataPointIntervalInSeconds); } graphiteDataInjector.exportMetrics(timeSeries); }
From source file:org.jmxtrans.embedded.samples.graphite.CocktailAppMetricsSimulator.java
License:Open Source License
public void generateLoad(GraphiteDataInjector graphiteDataInjector) throws Exception { TimeSeries rawIntegratedTimeSeries = new TimeSeries("sales.integrated.raw"); TimeSeries rawTimeSeries = new TimeSeries("sales.raw"); DateTime now = new DateTime(); DateTime end = now.plusDays(3);/* w ww . j a v a 2 s . c o m*/ DateTime date = now.minusDays(15); DateTime twoDaysAfterBegin = date.plusDays(2); double serverFairness = 1.05; int integratedValue = 0; MathContext mathContext = new MathContext(1, RoundingMode.CEILING); int randomFactor = 0; while (date.isBefore(end)) { if (rawIntegratedTimeSeries.getItemCount() % 120 == 0) { randomFactor = 10 + random.nextInt(2); } int weekGrowthFactor = 6 - (now.getWeekOfWeekyear() - date.getWeekOfWeekyear()); int value = new BigDecimal(randomFactor) // random factor .multiply(new BigDecimal(10)) // go to cents of USD .multiply(new BigDecimal(weekGrowthFactor)) .multiply(new BigDecimal(hourlyDistribution[date.getHourOfDay()])) .multiply(new BigDecimal(weeklyDistribution[date.getDayOfWeek()])) .divide(new BigDecimal(20), mathContext).intValue(); // split hourly value in minutes integratedValue += value; for (int i1 = 0; i1 < 3; i1++) { Second period = new Second(date.toDate()); rawTimeSeries.add(period, value); rawIntegratedTimeSeries.add(period, integratedValue); date = date.plusSeconds(30); } } rawIntegratedTimeSeries = MovingAverage.createMovingAverage(rawIntegratedTimeSeries, rawIntegratedTimeSeries.getKey().toString(), 60 * 7, 0); rawTimeSeries = MovingAverage.createMovingAverage(rawTimeSeries, rawTimeSeries.getKey().toString(), 60 * 7, 0); // SALES - REVENUE TimeSeries salesRevenueInCentsCounter = new TimeSeries("sales.revenueInCentsCounter"); TimeSeries salesRevenueInCentsCounterSrv1 = new TimeSeries("srv1.sales.revenueInCentsCounter"); TimeSeries salesRevenueInCentsCounterSrv2 = new TimeSeries("srv2.sales.revenueInCentsCounter"); int resetValue2ToZeroOffset = 0; // reset value 2 after 3 days of metrics for (int i = 0; i < rawIntegratedTimeSeries.getItemCount(); i++) { TimeSeriesDataItem dataItem = rawIntegratedTimeSeries.getDataItem(i); int value = dataItem.getValue().intValue(); // value1 is 5% higher to value2 due to a 'weirdness' in the load balancing int value1 = Math.min((int) (value * serverFairness / 2), value); { // simulate srv2 restart DateTime currentDate = new DateTime(dataItem.getPeriod().getStart()); boolean shouldResetValue2 = resetValue2ToZeroOffset == 0 && currentDate.getDayOfYear() == twoDaysAfterBegin.getDayOfYear(); if (shouldResetValue2) { resetValue2ToZeroOffset = value - value1; System.out.println("reset value2 of " + resetValue2ToZeroOffset + " at " + currentDate); } } int value2 = value - value1 - resetValue2ToZeroOffset; salesRevenueInCentsCounter.add(dataItem.getPeriod(), value); salesRevenueInCentsCounterSrv1.add(dataItem.getPeriod(), value1); salesRevenueInCentsCounterSrv2.add(dataItem.getPeriod(), value2); } graphiteDataInjector.exportMetrics(salesRevenueInCentsCounter, salesRevenueInCentsCounterSrv1, salesRevenueInCentsCounterSrv2); // SALES - ITEMS TimeSeries salesItemsCounter = new TimeSeries("sales.itemsCounter"); TimeSeries salesItemsCounterSrv1 = new TimeSeries("srv1.sales.itemsCounter"); TimeSeries salesItemsCounterSrv2 = new TimeSeries("srv2.sales.itemsCounter"); for (int i = 0; i < rawIntegratedTimeSeries.getItemCount(); i++) { RegularTimePeriod period = salesRevenueInCentsCounter.getDataItem(i).getPeriod(); int ordersPriceInCents1 = salesRevenueInCentsCounterSrv1.getDataItem(i).getValue().intValue(); int ordersPriceInCents2 = salesRevenueInCentsCounterSrv2.getDataItem(i).getValue().intValue(); int value1 = ordersPriceInCents1 / 600; int value2 = ordersPriceInCents2 / 600; salesItemsCounter.add(period, value1 + value2); salesItemsCounterSrv1.add(period, value1); salesItemsCounterSrv2.add(period, value2); } graphiteDataInjector.exportMetrics(salesItemsCounter, salesItemsCounterSrv1, salesItemsCounterSrv2); // WEBSITE - VISITORS TimeSeries newVisitorsCounterSrv1 = new TimeSeries("srv1.website.visitors.newVisitorsCounter"); TimeSeries newVisitorsCounterSrv2 = new TimeSeries("srv1.website.visitors.newVisitorsCounter"); TimeSeries activeVisitorsGaugeSrv1 = new TimeSeries("srv1.website.visitors.activeGauge"); TimeSeries activeVisitorsGaugeSrv2 = new TimeSeries("srv2.website.visitors.activeGauge"); int integratedValue1 = 0; int integratedValue2 = 0; float activeVisitorsFactor = 1; for (int i = 0; i < rawTimeSeries.getItemCount(); i++) { TimeSeriesDataItem dataItem = rawTimeSeries.getDataItem(i); RegularTimePeriod period = dataItem.getPeriod(); int value = dataItem.getValue().intValue() / 20; integratedValue += value; int value1 = Math.min((int) (value * serverFairness / 2), value); integratedValue1 += value1; int value2 = value - value1; integratedValue2 += value2; newVisitorsCounterSrv1.add(period, integratedValue1); newVisitorsCounterSrv2.add(period, integratedValue2); if (i % 120 == 0) { activeVisitorsFactor = (10 + random.nextInt(3)) / 10; } activeVisitorsGaugeSrv1.add(period, Math.floor(value1 * activeVisitorsFactor)); activeVisitorsGaugeSrv2.add(period, Math.floor(value2 * activeVisitorsFactor)); } graphiteDataInjector.exportMetrics(newVisitorsCounterSrv1, newVisitorsCounterSrv2, activeVisitorsGaugeSrv1, activeVisitorsGaugeSrv2); }
From source file:org.jmxtrans.samples.graphite.GraphiteDataInjector.java
License:Open Source License
public void generateLoad() throws Exception { System.out.println("Inject data on Graphite server " + this.graphiteHost); TimeSeries timeSeries = new TimeSeries("shopping-cart.raw"); DateTime now = new DateTime(); DateTime end = now.plusDays(1);/* w w w.j a v a2s .c o m*/ DateTime date = now.minusDays(15); DateTime twoDaysAfterBegin = date.plusDays(2); int integratedValue = 0; MathContext mathContext = new MathContext(1, RoundingMode.CEILING); int randomFactor = 0; while (date.isBefore(end)) { if (timeSeries.getItemCount() % 120 == 0) { randomFactor = 10 + random.nextInt(2); } int weekGrowthFactor = 6 - (now.getWeekOfWeekyear() - date.getWeekOfWeekyear()); int value = new BigDecimal(randomFactor) // random factor .multiply(new BigDecimal(10)) // go to cents of USD .multiply(new BigDecimal(weekGrowthFactor)) .multiply(new BigDecimal(hourlyDistribution[date.getHourOfDay()])) .multiply(new BigDecimal(weeklyDistribution[date.getDayOfWeek()])) .divide(new BigDecimal(20), mathContext).intValue(); // split hourly value in minutes integratedValue += value; for (int i1 = 0; i1 < 3; i1++) { timeSeries.add(new Minute(date.toDate()), integratedValue); date = date.plusMinutes(1); } } TimeSeries ordersPriceInCentsTimeSeries = MovingAverage.createMovingAverage(timeSeries, "shopping-cart.OrdersPriceInCents", 60 * 7, 0); TimeSeries ordersPriceInCentsSrv1TimeSeries = new TimeSeries("srv1.shopping-cart.OrdersPriceInCents"); TimeSeries ordersPriceInCentsSrv2TimeSeries = new TimeSeries("srv2.shopping-cart.OrdersPriceInCents"); int resetValue2ToZeroOffset = 0; // reset value 2 after 3 days of metrics for (int i = 0; i < ordersPriceInCentsTimeSeries.getItemCount(); i++) { TimeSeriesDataItem dataItem = ordersPriceInCentsTimeSeries.getDataItem(i); int value = dataItem.getValue().intValue(); // value1 is 5% higher to value2 due to a 'weirdness' in the load balancing int value1 = Math.min((int) (value * 1.05 / 2), value); { // simulate srv2 restart DateTime currentDate = new DateTime(dataItem.getPeriod().getStart()); boolean shouldResetValue2 = resetValue2ToZeroOffset == 0 && currentDate.getDayOfYear() == twoDaysAfterBegin.getDayOfYear(); if (shouldResetValue2) { resetValue2ToZeroOffset = value - value1; System.out.println("reset value2 of " + resetValue2ToZeroOffset + " at " + currentDate); } } int value2 = value - value1 - resetValue2ToZeroOffset; // System.out.println("value=" + value + ", value1=" + value1 + ", value2=" + value2); ordersPriceInCentsSrv1TimeSeries.add(dataItem.getPeriod(), value1); ordersPriceInCentsSrv2TimeSeries.add(dataItem.getPeriod(), value2); } TimeSeries orderItemsCountTimeSeries = new TimeSeries("shopping-cart.OrderItemsCount"); TimeSeries orderItemsCountSrv1TimeSeries = new TimeSeries("srv1.shopping-cart.OrderItemsCount"); TimeSeries orderItemsCountSrv2TimeSeries = new TimeSeries("srv2.shopping-cart.OrderItemsCount"); for (int i = 0; i < ordersPriceInCentsTimeSeries.getItemCount(); i++) { RegularTimePeriod period = ordersPriceInCentsTimeSeries.getDataItem(i).getPeriod(); int ordersPriceInCents1 = ordersPriceInCentsSrv1TimeSeries.getDataItem(i).getValue().intValue(); int ordersPriceInCents2 = ordersPriceInCentsSrv2TimeSeries.getDataItem(i).getValue().intValue(); int value1 = ordersPriceInCents1 / 600; int value2 = ordersPriceInCents2 / 600; orderItemsCountTimeSeries.add(period, value1 + value2); orderItemsCountSrv1TimeSeries.add(period, value1); orderItemsCountSrv2TimeSeries.add(period, value2); } exportMetrics(ordersPriceInCentsTimeSeries, ordersPriceInCentsSrv1TimeSeries, ordersPriceInCentsSrv2TimeSeries, ordersPriceInCentsTimeSeries, orderItemsCountTimeSeries, orderItemsCountSrv1TimeSeries, orderItemsCountSrv2TimeSeries); TimeSeries activeSrv1Visitors = new TimeSeries("srv1.visitors.currentActive"); TimeSeries activeSrv2Visitors = new TimeSeries("srv1.visitors.currentActive"); }
From source file:org.jpos.qi.components.DateRange.java
License:Open Source License
private static Map<String, Date> createStartDateMap() { QI app = (QI) UI.getCurrent();/*from w w w. j a v a 2 s . c om*/ DateTime dt = DateTime.now().millisOfDay().withMinimumValue(); Map<String, Date> map = new HashMap<>(); map.put(LAST_HOUR, DateTime.now().minusHours(1).toDate()); map.put(TODAY, dt.toDate()); map.put(YESTERDAY, dt.minusDays(1).toDate()); map.put(THIS_WEEK, dt.dayOfWeek().withMinimumValue().toDate()); map.put(LAST_WEEK, dt.dayOfWeek().withMinimumValue().minusWeeks(1).toDate()); map.put(THIS_MONTH, dt.dayOfMonth().withMinimumValue().toDate()); map.put(LAST_MONTH, dt.dayOfMonth().withMinimumValue().minusMonths(1).toDate()); map.put(THIS_YEAR, dt.dayOfYear().withMinimumValue().toDate()); map.put(ALL_TIME, null); return map; }
From source file:org.jpos.qi.components.DateRange.java
License:Open Source License
private static Map<String, Date> createEndDateMap() { QI app = (QI) UI.getCurrent();/*w w w. j a v a2 s . c om*/ DateTime dt = DateTime.now().millisOfDay().withMaximumValue(); Map<String, Date> map = new HashMap<>(); map.put(LAST_HOUR, DateTime.now().toDate()); map.put(TODAY, dt.toDate()); map.put(YESTERDAY, dt.minusDays(1).toDate()); map.put(THIS_WEEK, dt.dayOfWeek().withMaximumValue().toDate()); map.put(LAST_WEEK, dt.dayOfWeek().withMaximumValue().minusWeeks(1).toDate()); map.put(THIS_MONTH, dt.dayOfMonth().withMaximumValue().toDate()); map.put(LAST_MONTH, dt.dayOfMonth().withMaximumValue().minusMonths(1).toDate()); map.put(THIS_YEAR, dt.dayOfYear().withMaximumValue().toDate()); map.put(ALL_TIME, null); return map; }
From source file:org.jtotus.database.NetworkGoogle.java
License:Open Source License
public BigDecimal fetchDataInternal(String stockName, DateTime endDate, int type) { DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = null;/*from w ww . j ava2 s .com*/ DateTime startDate = endDate.minusDays(5); BigDecimal retValue = null; try { DateTimeFormatter formatterOUT = DateTimeFormat.forPattern(timePatternForWrite); DateTimeFormatter formatterIN = DateTimeFormat.forPattern(timePatternForRead); String query = url + "?q=" + names.getHexName(stockName) + "&" + "startdate=" + formatterOUT.print(startDate) + "&" + "enddate=" + formatterOUT.print(endDate) + "&" + "&num=30&output=csv"; System.out.printf("HttpGet:%s : date:%s\n", query, formatterOUT.print(startDate)); httpGet = new HttpGet(query); HttpResponse response = client.execute(httpGet); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { throw new IOException("Invalid response from server: " + status.toString()); } HttpEntity entity = response.getEntity(); BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); // Date, Open,High,Low,Close,Volume String line = reader.readLine(); //Header while ((line = reader.readLine()) != null) { String[] values = line.split(","); double value = Double.parseDouble(values[type]); retValue = BigDecimal.valueOf(value); } } catch (IOException ex) { System.err.printf("Unable to find market data for: %s - %s\n", names.getHexName(stockName), stockName); } catch (IllegalArgumentException ex) { System.err.printf("Unable to find market data for: %s - %s\n", names.getHexName(stockName), stockName); } finally { if (httpGet != null) { //FIXME: what to do ? } } return retValue; }
From source file:org.jtotus.network.StockType.java
License:Open Source License
public BigDecimal fetchCurrentClosingPrice() { DateTime cal = new DateTime(); BigDecimal retValue = null;/*from ww w .j a v a2 s . c om*/ help.debug("StockType", "Fetching:%s: Time:" + cal.toDate() + "\n", stockName); while ((retValue = fetcher.fetchData(stockName, cal, "CLOSE")) == null) { //TODO:check end cal = cal.minusDays(1); } return retValue; }
From source file:org.killbill.billing.subscription.alignment.BaseAligner.java
License:Apache License
private DateTime addOrRemoveDuration(final DateTime input, final Duration duration, boolean add) { DateTime result = input; switch (duration.getUnit()) { case DAYS:/*from w w w . j ava 2s . c o m*/ result = add ? result.plusDays(duration.getNumber()) : result.minusDays(duration.getNumber()); ; break; case MONTHS: result = add ? result.plusMonths(duration.getNumber()) : result.minusMonths(duration.getNumber()); break; case YEARS: result = add ? result.plusYears(duration.getNumber()) : result.minusYears(duration.getNumber()); break; case UNLIMITED: default: throw new RuntimeException("Trying to move to unlimited time period"); } return result; }
From source file:org.kuali.kpme.core.assignment.service.AssignmentServiceImpl.java
License:Educational Community License
public List<Assignment> getAssignmentsByPayEntry(String principalId, CalendarEntry payCalendarEntry) { DateTime entryEndDate = payCalendarEntry.getEndPeriodLocalDateTime().toDateTime(); if (entryEndDate.getHourOfDay() == 0) { entryEndDate = entryEndDate.minusDays(1); }//from w w w .j av a 2s .c om List<Assignment> beginPeriodAssign = getAssignments(principalId, payCalendarEntry.getBeginPeriodFullDateTime().toLocalDate()); List<Assignment> endPeriodAssign = getAssignments(principalId, entryEndDate.toLocalDate()); List<Assignment> assignsWithPeriod = getAssignments(principalId, payCalendarEntry.getBeginPeriodFullDateTime().toLocalDate(), entryEndDate.toLocalDate()); List<Assignment> finalAssignments = new ArrayList<Assignment>(); Map<String, Assignment> assignKeyToAssignmentMap = new HashMap<String, Assignment>(); for (Assignment assign : endPeriodAssign) { assignKeyToAssignmentMap.put( TKUtils.formatAssignmentKey(assign.getJobNumber(), assign.getWorkArea(), assign.getTask()), assign); finalAssignments.add(assign); } //Compare the begin and end and add any assignments to the end thats are not there for (Assignment assign : beginPeriodAssign) { String assignKey = TKUtils.formatAssignmentKey(assign.getJobNumber(), assign.getWorkArea(), assign.getTask()); if (!assignKeyToAssignmentMap.containsKey(assignKey)) { finalAssignments.add(assign); } } // Add the assignments within the pay period for (Assignment assign : assignsWithPeriod) { String assignKey = TKUtils.formatAssignmentKey(assign.getJobNumber(), assign.getWorkArea(), assign.getTask()); if (!assignKeyToAssignmentMap.containsKey(assignKey)) { finalAssignments.add(assign); } } return finalAssignments; }