List of usage examples for java.util Calendar clone
@Override
public Object clone()
From source file:com.heliumv.api.production.ProductionApi.java
private int daysBetween(Calendar startDate, Calendar endDate) { Calendar date = (Calendar) startDate.clone(); int daysBetween = 0; while (date.before(endDate)) { date.add(Calendar.DAY_OF_MONTH, 1); daysBetween++;//from www . j ava 2 s.c om } return daysBetween; }
From source file:org.apache.oozie.command.coord.CoordMaterializeTransitionXCommand.java
/** * Get materialization for window for catch-up jobs. for current jobs,it reruns currentMatdate, For catch-up, end * Mataterilized Time = startMatdTime + MatThrottling * frequency; unless LAST_ONLY execution order is set, in which * case it returns now (to materialize all actions in the past) * * @param currentMatTime/* w w w. ja v a 2s . com*/ * @return * @throws CommandException * @throws JDOMException */ private Date getMaterializationTimeForCatchUp(Date currentMatTime) throws CommandException { if (currentMatTime.after(new Date())) { return currentMatTime; } if (coordJob.getExecutionOrder().equals(CoordinatorJob.Execution.LAST_ONLY) || coordJob.getExecutionOrder().equals(CoordinatorJob.Execution.NONE)) { return new Date(); } int frequency = 0; try { frequency = Integer.parseInt(coordJob.getFrequency()); } catch (NumberFormatException e) { return currentMatTime; } TimeZone appTz = DateUtils.getTimeZone(coordJob.getTimeZone()); TimeUnit freqTU = TimeUnit.valueOf(coordJob.getTimeUnitStr()); Calendar startInstance = Calendar.getInstance(appTz); startInstance.setTime(startMatdTime); Calendar endMatInstance = null; Calendar previousInstance = startInstance; for (int i = 1; i <= coordJob.getMatThrottling(); i++) { endMatInstance = (Calendar) startInstance.clone(); endMatInstance.add(freqTU.getCalendarUnit(), i * frequency); if (endMatInstance.getTime().compareTo(new Date()) >= 0) { if (previousInstance.getTime().after(currentMatTime)) { return previousInstance.getTime(); } else { return currentMatTime; } } previousInstance = endMatInstance; } if (endMatInstance == null) { return currentMatTime; } else { return endMatInstance.getTime(); } }
From source file:mx.edu.um.mateo.rh.dao.impl.EmpleadoDaoHibernate.java
private Criterion getQueryByMonth(Calendar gc) { Criterion cr = null;//www . j a va 2s. c o m gc.add(Calendar.YEAR, 1); gc.set(Calendar.DAY_OF_MONTH, 1); Date fechaI = gc.getTime(); gc.set(Calendar.DAY_OF_MONTH, gc.getMaximum(Calendar.DAY_OF_MONTH)); Date fechaF = gc.getTime(); cr = Restrictions.between("fechaNacimiento", fechaI, fechaF); Calendar tmp = (Calendar) gc.clone(); tmp.clear(); tmp.setTime(new Date()); tmp.add(Calendar.YEAR, -17); if (gc.compareTo(tmp) <= 0) { return Restrictions.or(cr, getQueryByMonth(gc)); } else { return cr; } }
From source file:com.square.adherent.noyau.service.test.EspaceClientInternetServiceTest.java
/** * Test unitaire du service de cration d'espace client partir d'un DTO pr-rempli. *//*from w w w. j a v a 2 s. c om*/ @Test public void testCreerEspaceClientDtoPreRempli() { // On cr l'espace client de la personne final Long uidPersonne = 2L; final EspaceClientInternetDto espaceClientDto = new EspaceClientInternetDto(uidPersonne); espaceClientDto.setEid("30"); espaceClientDto.setActive(false); final Calendar dateCreation = Calendar.getInstance(); dateCreation.add(Calendar.YEAR, -1); espaceClientDto.setDateCreation(dateCreation); final Calendar dateModification = Calendar.getInstance(); dateModification.add(Calendar.MONTH, -1); espaceClientDto.setDateModification(dateModification); final Calendar dateDerniereDematerialisation = (Calendar) dateCreation.clone(); dateDerniereDematerialisation.add(Calendar.MONTH, 2); espaceClientDto.setDateDerniereDematerialisation(dateDerniereDematerialisation); final Calendar dateDerniereVisite = Calendar.getInstance(); dateDerniereVisite.add(Calendar.DAY_OF_MONTH, -1); espaceClientDto.setDateDerniereVisite(dateDerniereVisite); espaceClientDto.setDateDesactivation(dateModification); final Calendar datePremiereVisite = (Calendar) dateCreation.clone(); datePremiereVisite.add(Calendar.DAY_OF_MONTH, 7); espaceClientDto.setDatePremiereVisite(datePremiereVisite); espaceClientDto.setDateReactivation(dateModification); espaceClientDto.setLogin("loginPersonne" + uidPersonne); espaceClientDto.setMotDePasse("blabla"); espaceClientDto.setNature(new IdentifiantLibelleDto(1L)); espaceClientDto.setNbVisites(CINQUANTE); espaceClientDto.setPremiereVisite(false); final EspaceClientInternetDto espaceClientCree = espaceClientInternetService .creerEspaceClient(espaceClientDto); assertEquals(Messages.getString("EspaceClientInternetServiceTest.30"), espaceClientDto.getEid(), espaceClientCree.getEid()); assertEquals(Messages.getString("EspaceClientInternetServiceTest.31"), espaceClientDto.getLogin(), espaceClientCree.getLogin()); assertEquals(Messages.getString("EspaceClientInternetServiceTest.32"), espaceClientDto.getMotDePasse(), espaceClientCree.getMotDePasse()); assertEquals(Messages.getString("EspaceClientInternetServiceTest.33"), uidPersonne, espaceClientCree.getUidPersonne()); assertEquals(Messages.getString("EspaceClientInternetServiceTest.34"), espaceClientDto.getActive(), espaceClientCree.getActive()); assertEquals(Messages.getString("EspaceClientInternetServiceTest.35"), espaceClientDto.getPremiereVisite(), espaceClientCree.getPremiereVisite()); assertEquals(Messages.getString("EspaceClientInternetServiceTest.36"), 0, espaceClientCree.getNbVisites()); assertEquals(Messages.getString("EspaceClientInternetServiceTest.37"), espaceClientDto.getNature().getIdentifiant(), espaceClientCree.getNature().getIdentifiant()); assertEquals(Messages.getString("EspaceClientInternetServiceTest.38"), espaceClientDto.getDateCreation(), espaceClientCree.getDateCreation()); assertEquals(Messages.getString("EspaceClientInternetServiceTest.39"), espaceClientDto.getDateModification(), espaceClientCree.getDateModification()); assertEquals(Messages.getString("EspaceClientInternetServiceTest.40"), espaceClientDto.getDateDerniereDematerialisation(), espaceClientCree.getDateDerniereDematerialisation()); assertEquals(Messages.getString("EspaceClientInternetServiceTest.41"), espaceClientDto.getDatePremiereVisite(), espaceClientCree.getDatePremiereVisite()); assertEquals(Messages.getString("EspaceClientInternetServiceTest.42"), espaceClientDto.getDateDerniereVisite(), espaceClientCree.getDateDerniereVisite()); assertEquals(Messages.getString("EspaceClientInternetServiceTest.43"), espaceClientDto.getDateDesactivation(), espaceClientCree.getDateDesactivation()); assertEquals(Messages.getString("EspaceClientInternetServiceTest.44"), espaceClientDto.getDateReactivation(), espaceClientCree.getDateReactivation()); }
From source file:nl.strohalm.cyclos.services.transactions.LoanServiceImpl.java
@Override public LoanRepaymentAmountsDTO getLoanPaymentAmount(final LoanPaymentDTO dto) { final LoanRepaymentAmountsDTO ret = new LoanRepaymentAmountsDTO(); Calendar date = dto.getDate(); if (date == null) { date = Calendar.getInstance(); }/*from w w w .ja v a 2s.com*/ final Loan loan = fetchService.fetch(dto.getLoan(), Loan.Relationships.TRANSFER, Loan.Relationships.PAYMENTS); LoanPayment payment = fetchService.fetch(dto.getLoanPayment()); if (payment == null) { payment = loan.getFirstOpenPayment(); } ret.setLoanPayment(payment); // Update the dto with fetched values dto.setLoan(loan); dto.setLoanPayment(payment); if (payment != null) { payment = fetchService.fetch(payment, LoanPayment.Relationships.TRANSFERS); final BigDecimal paymentAmount = payment.getAmount(); BigDecimal remainingAmount = paymentAmount; Calendar expirationDate = payment.getExpirationDate(); Calendar lastPaymentDate = (Calendar) expirationDate.clone(); expirationDate = DateUtils.truncate(expirationDate, Calendar.DATE); final LoanParameters parameters = loan.getParameters(); Collection<Transfer> transfers = payment.getTransfers(); if (transfers == null) { transfers = Collections.emptyList(); } final BigDecimal expirationDailyInterest = CoercionHelper.coerce(BigDecimal.class, parameters.getExpirationDailyInterest()); final LocalSettings localSettings = settingsService.getLocalSettings(); final MathContext mathContext = localSettings.getMathContext(); for (final Transfer transfer : transfers) { Calendar trfDate = transfer.getDate(); trfDate = DateUtils.truncate(trfDate, Calendar.DATE); final BigDecimal trfAmount = transfer.getAmount(); BigDecimal actualAmount = trfAmount; final int diffDays = (int) ((trfDate.getTimeInMillis() - expirationDate.getTimeInMillis()) / DateUtils.MILLIS_PER_DAY); if (diffDays > 0 && expirationDailyInterest != null) { // Apply interest actualAmount = actualAmount.subtract(remainingAmount.multiply(new BigDecimal(diffDays)) .multiply(expirationDailyInterest.divide(new BigDecimal(100), mathContext))); } remainingAmount = remainingAmount.subtract(actualAmount); lastPaymentDate = (Calendar) trfDate.clone(); } date = DateHelper.truncate(date); BigDecimal remainingAmountAtDate = remainingAmount; final int diffDays = (int) ((date.getTimeInMillis() - (expirationDate.before(lastPaymentDate) ? lastPaymentDate.getTimeInMillis() : expirationDate.getTimeInMillis())) / DateUtils.MILLIS_PER_DAY); if (diffDays > 0 && expirationDailyInterest != null) { // Apply interest remainingAmountAtDate = remainingAmountAtDate.add(remainingAmount.multiply(new BigDecimal(diffDays)) .multiply(expirationDailyInterest.divide(new BigDecimal(100), mathContext))); } final Amount expirationFee = parameters.getExpirationFee(); if (expirationFee != null && (remainingAmountAtDate.compareTo(BigDecimal.ZERO) == 1) && expirationDate.before(date) && (expirationFee.getValue().compareTo(BigDecimal.ZERO) == 1)) { // Apply expiration fee remainingAmountAtDate = remainingAmountAtDate.add(expirationFee.apply(remainingAmount)); } // Round the result ret.setRemainingAmountAtExpirationDate(localSettings.round(remainingAmount)); ret.setRemainingAmountAtDate(localSettings.round(remainingAmountAtDate)); } return ret; }
From source file:com.s3d.webapps.util.time.DateUtils.java
/** * <p>Ceil this date, leaving the field specified as the most * significant field.</p>/* ww w.j av a2 s .c o m*/ * * <p>For example, if you had the datetime of 28 Mar 2002 * 13:45:01.231, if you passed with HOUR, it would return 28 Mar * 2002 13:00:00.000. If this was passed with MONTH, it would * return 1 Mar 2002 0:00:00.000.</p> * * @param date the date to work with * @param field the field from <code>Calendar</code> * or <code>SEMI_MONTH</code> * @return the rounded date (a different object) * @throws IllegalArgumentException if the date is <code>null</code> * @throws ArithmeticException if the year is over 280 million * @since 2.5 */ public static Calendar ceiling(Calendar date, int field) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } Calendar ceiled = (Calendar) date.clone(); modify(ceiled, field, MODIFY_CEILING); return ceiled; }
From source file:com.s3d.webapps.util.time.DateUtils.java
/** * <p>Round this date, leaving the field specified as the most * significant field.</p>/*from www.jav a 2s . c o m*/ * * <p>For example, if you had the datetime of 28 Mar 2002 * 13:45:01.231, if this was passed with HOUR, it would return * 28 Mar 2002 14:00:00.000. If this was passed with MONTH, it * would return 1 April 2002 0:00:00.000.</p> * * <p>For a date in a timezone that handles the change to daylight * saving time, rounding to Calendar.HOUR_OF_DAY will behave as follows. * Suppose daylight saving time begins at 02:00 on March 30. Rounding a * date that crosses this time would produce the following values: * <ul> * <li>March 30, 2003 01:10 rounds to March 30, 2003 01:00</li> * <li>March 30, 2003 01:40 rounds to March 30, 2003 03:00</li> * <li>March 30, 2003 02:10 rounds to March 30, 2003 03:00</li> * <li>March 30, 2003 02:40 rounds to March 30, 2003 04:00</li> * </ul> * </p> * * @param date the date to work with * @param field the field from <code>Calendar</code> * or <code>SEMI_MONTH</code> * @return the rounded date (a different object) * @throws IllegalArgumentException if the date is <code>null</code> * @throws ArithmeticException if the year is over 280 million */ public static Calendar round(Calendar date, int field) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } Calendar rounded = (Calendar) date.clone(); modify(rounded, field, MODIFY_ROUND); return rounded; }
From source file:com.s3d.webapps.util.time.DateUtils.java
/** * <p>Truncate this date, leaving the field specified as the most * significant field.</p>//from w w w. j a v a2 s .com * * <p>For example, if you had the datetime of 28 Mar 2002 * 13:45:01.231, if you passed with HOUR, it would return 28 Mar * 2002 13:00:00.000. If this was passed with MONTH, it would * return 1 Mar 2002 0:00:00.000.</p> * * @param date the date to work with * @param field the field from <code>Calendar</code> * or <code>SEMI_MONTH</code> * @return the rounded date (a different object) * @throws IllegalArgumentException if the date is <code>null</code> * @throws ArithmeticException if the year is over 280 million */ public static Calendar truncate(Calendar date, int field) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } Calendar truncated = (Calendar) date.clone(); modify(truncated, field, MODIFY_TRUNCATE); return truncated; }
From source file:info.raack.appliancelabeler.machinelearning.DefaultApplianceDetectionManager.java
public void trainPredictionModelsForMonitors(List<EnergyMonitor> energyMonitors) { // get a year worth of data to train upon List<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>(); // for each energy monitor for (final EnergyMonitor monitor : energyMonitors) { monitor.pollLock();//from w w w . j a v a2 s . co m logger.info("Starting training for " + monitor); try { // do training for model for (final ApplianceEnergyConsumptionDetectionAlgorithm algorithm : applianceStateTransitionDetectionAlgorithms) { String className = algorithm.getAlgorithmName(); if (activeAlgorithms.contains(className)) { Callable<Integer> task = new Callable<Integer>() { @Override public Integer call() { // purge current energy predictions and appliance state transitions logger.debug("Removing previous state transition and energy predictions for " + monitor + "; " + algorithm); database.removeStateTransitionAndEnergyPredictionsForAlgorithmAndMonitor(algorithm, monitor); logger.info("Training " + algorithm); ItemReader<SecondData> dataReader = null; try { //Calendar now = new GregorianCalendar(); Date lastMeasurementTime = database .getLastMeasurementTimeForEnergyMonitor(monitor); if (lastMeasurementTime == null) { logger.debug("No data points for monitor " + monitor + "; not doing any retraining"); return null; } Calendar finalMeasurementTime = new GregorianCalendar(); finalMeasurementTime.setTimeInMillis(lastMeasurementTime.getTime()); finalMeasurementTime = dateUtils .getPreviousFiveMinuteIncrement(finalMeasurementTime); // now go one year backward from the last measurement Calendar first = (Calendar) finalMeasurementTime.clone(); first.add(Calendar.YEAR, -1); long measurements = (finalMeasurementTime.getTimeInMillis() - first.getTimeInMillis()) / 1000; logger.info("Training algorithms with data from " + first.getTime() + " to " + finalMeasurementTime.getTime()); dataReader = database.getEnergyMeasurementReaderForMonitor(monitor, first.getTime(), finalMeasurementTime.getTime(), (int) measurements); // 1) generate a model to create predictions AlgorithmResult result = algorithm.train(monitor, dataReader); // 2) save the model if (result != null) { logger.debug("Saving algorithm model for " + result.getAlgorithm()); database.saveAlgorithmResult(result); } // 3) use the model to generate predicted state transitions and energy predictions logger.info( "Re-predicting appliance state transitions and energy consumption for " + algorithm); // move the final time back to the last five minute boundary dataReader.moveToBeginning(); final AlgorithmPredictions algorithmPredictions = algorithm .calculateApplianceEnergyUsePredictions(monitor, first, finalMeasurementTime, dataReader); // 4) save the predictions database.storeAlgorithmPredictions(monitor, new HashMap<Integer, AlgorithmPredictions>() { { put(algorithm.getId(), algorithmPredictions); } }); lastTimeIncludedInTraining.put(monitor.getId(), lastMeasurementTime); logger.info("Done training " + monitor + " with " + algorithm); } catch (Exception e) { logger.error("Could not train models", e); errorService.reportError("Could not train models", URGENCY.REGULAR, e); } finally { if (dataReader != null) { dataReader.close(); } } return null; } }; tasks.add(task); } } } finally { monitor.pollUnlock(); } } try { executorService.invokeAll(tasks); } catch (InterruptedException e) { throw new RuntimeException("Retraining executor was interrupted", e); } logger.info("Done with all retraining"); }
From source file:org.richfaces.component.UICalendar.java
public Date[] getPreloadDateRange() { Date dateRangeBegin = getAsDate(this.getPreloadDateRangeBegin()); Date dateRangeEnd = getAsDate(this.getPreloadDateRangeEnd()); if (dateRangeBegin == null && dateRangeEnd == null) { return null; } else {/*from w w w . ja va2 s. com*/ if (dateRangeBegin.after(dateRangeEnd)) { // XXX add message FacesMessage message = new FacesMessage( "preloadDateRangeBegin is greater than preloadDateRangeEnd"); message.setSeverity(FacesMessage.SEVERITY_ERROR); FacesContext context = FacesContext.getCurrentInstance(); context.addMessage(getClientId(context), message); throw new IllegalArgumentException(); } List<Date> dates = new ArrayList<Date>(); Calendar calendar = Calendar.getInstance(this.getTimeZone(), getAsLocale(this.getLocale())); Calendar calendar2 = (Calendar) calendar.clone(); calendar.setTime(dateRangeBegin); calendar2.setTime(dateRangeEnd); do { dates.add(calendar.getTime()); calendar.add(Calendar.DATE, 1); } while (!calendar.after(calendar2)); return (Date[]) dates.toArray(new Date[dates.size()]); } }