List of usage examples for org.apache.commons.lang.time DateUtils addDays
public static Date addDays(Date date, int amount)
From source file:com.autentia.tnt.manager.holiday.UserHolidaysStateManager.java
/** * @return Devuelve el nmero de das laborables que hay entre dos fechas *//*from ww w . j av a 2 s .c om*/ public int getWorkingDays(Date fromDate, Date toDate) { int total = 0; // Evitamos un bucle infinito en el bucle que viene a continuacin if (fromDate.before(toDate) || DateUtils.isSameDay(fromDate, toDate)) { HolidaySearch fiestaSearch = new HolidaySearch(); Date current = (Date) fromDate.clone(); fiestaSearch.setStartDate(fromDate); fiestaSearch.setEndDate(toDate); List<Holiday> fiestas = HolidayManager.getDefault().getAllEntities(fiestaSearch, null); while (current.before(toDate) || DateUtils.isSameDay(current, toDate)) { if (!this.isHoliday(fiestas, current)) { total++; } current = DateUtils.addDays(current, 1); } } return total; }
From source file:com.cndatacom.core.orm.PropertyFilter.java
/** * @param filterName ,???. /*from w ww. j a v a 2s . com*/ * eg. LIKES_NAME_OR_LOGIN_NAME * @param value . */ public PropertyFilter(final String filterName, final String value) { this.filterName = filterName; this.value = value; String matchTypeStr = StringUtils.substringBefore(filterName, "_"); //,EQ String matchTypeCode = StringUtils.substring(matchTypeStr, 0, matchTypeStr.length() - 1); //?,S?I String propertyTypeCode = StringUtils.substring(matchTypeStr, matchTypeStr.length() - 1, matchTypeStr.length()); try { matchType = Enum.valueOf(MatchType.class, matchTypeCode); } catch (RuntimeException e) { throw new IllegalArgumentException( "filter??" + filterName + ",.", e); } try { propertyType = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue(); } catch (RuntimeException e) { throw new IllegalArgumentException( "filter??" + filterName + ",.", e); } String propertyNameStr = StringUtils.substringAfter(filterName, "_"); //propertyNames = StringUtils.split(propertyNameStr, PropertyFilter.OR_SEPARATOR); propertyNames = propertyNameStr.split(PropertyFilter.OR_SEPARATOR); Assert.isTrue(propertyNames.length > 0, "filter??" + filterName + ",??."); //entity property. if (propertyNameStr.indexOf(LEFT_JION) != -1) { isLeftJion = true; } // Object value_ = null; if (null == value || value.equals("")) { this.propertyValue = null; } else { this.propertyValue = ReflectionUtils.convertStringToObject(value, propertyType); value_ = propertyValue; //?1 if (propertyType.equals(Date.class) && filterName.indexOf("LTD") > -1) { propertyValue = DateUtils.addDays((Date) propertyValue, 1); } } //request? String key = propertyNames[0].replace(".", "_").replace(":", "_"); // if(propertyType!=Date.class) //// Struts2Utils.getRequest().setAttribute(key, propertyValue); //// else{ //// if(Struts2Utils.getRequest().getAttribute(key)!=null){ //// String time_begin=Struts2Utils.getRequest().getAttribute(key)+""; //// Struts2Utils.getRequest().setAttribute(key, time_begin+"="+com.cndatacom.common.utils.DateUtil.format((Date)value_,"yyyy-MM-dd")); //// }else{ //// Struts2Utils.getRequest().setAttribute(key, com.cndatacom.common.utils.DateUtil.format((Date)value_,"yyyy-MM-dd")); //// } // // } }
From source file:com.haulmont.timesheets.gui.approve.BulkTimeEntriesApprove.java
@Override public void init(Map<String, Object> params) { super.init(params); if (securityAssistant.isSuperUser()) { timeEntriesDs.setQuery("select e from ts$TimeEntry e " + "where e.date >= :component$dateFrom and e.date <= :component$dateTo"); }//from ww w . jav a 2 s . c om timeEntriesTable.getColumn("overtime") .setAggregation(ComponentsHelper.createAggregationInfo( projectsService.getEntityMetaPropertyPath(TimeEntry.class, "overtime"), new TimeEntryOvertimeAggregation())); timeEntriesDs.addCollectionChangeListener(e -> { Multimap<Map<String, Object>, TimeEntry> map = ArrayListMultimap.create(); for (TimeEntry item : timeEntriesDs.getItems()) { Map<String, Object> key = new TreeMap<>(); key.put("user", item.getUser()); key.put("date", item.getDate()); map.put(key, item); } for (Map.Entry<Map<String, Object>, Collection<TimeEntry>> entry : map.asMap().entrySet()) { BigDecimal thisDaysSummary = BigDecimal.ZERO; for (TimeEntry timeEntry : entry.getValue()) { thisDaysSummary = thisDaysSummary.add(timeEntry.getTimeInHours()); } for (TimeEntry timeEntry : entry.getValue()) { BigDecimal planHoursForDay = workdaysTools.isWorkday(timeEntry.getDate()) ? workTimeConfigBean.getWorkHourForDay() : BigDecimal.ZERO; BigDecimal overtime = thisDaysSummary.subtract(planHoursForDay); timeEntry.setOvertimeInHours(overtime); } } }); Date previousMonth = DateUtils.addMonths(timeSource.currentTimestamp(), -1); dateFrom.setValue(DateUtils.truncate(previousMonth, Calendar.MONTH)); dateTo.setValue(DateUtils.addDays(DateUtils.truncate(timeSource.currentTimestamp(), Calendar.MONTH), -1)); approve.addAction(new AbstractAction("approveAll") { @Override public void actionPerform(Component component) { setStatus(timeEntriesDs.getItems(), TimeEntryStatus.APPROVED); } }); approve.addAction(new AbstractAction("approveSelected") { @Override public void actionPerform(Component component) { setStatus(timeEntriesTable.getSelected(), TimeEntryStatus.APPROVED); } }); reject.addAction(new AbstractAction("rejectAll") { @Override public void actionPerform(Component component) { setStatus(timeEntriesDs.getItems(), TimeEntryStatus.REJECTED); } }); reject.addAction(new AbstractAction("rejectSelected") { @Override public void actionPerform(Component component) { setStatus(timeEntriesTable.getSelected(), TimeEntryStatus.REJECTED); } }); status.setOptionsList(Arrays.asList(TimeEntryStatus.values())); user.setOptionsList( projectsService.getManagedUsers(userSession.getCurrentOrSubstitutedUser(), View.MINIMAL)); }
From source file:com.eucalyptus.auth.euare.EuareServerCertificateUtil.java
public static X509Certificate generateVMCertificate(final RSAPublicKey publicKey, final String principal, final int expirationDays) throws AuthException { try {/*from ww w. j a va2 s . co m*/ final X500Principal subjectDn = new X500Principal(principal); final Credentials euareCred = SystemCredentials.lookup(Euare.class); final Principal signer = euareCred.getCertificate().getSubjectDN(); final PrivateKey signingKey = euareCred.getPrivateKey(); final Date notAfter = DateUtils.addDays(Calendar.getInstance().getTime(), expirationDays); final X509Certificate cert = Certs.generateCertificate(publicKey, subjectDn, new X500Principal(signer.getName()), signingKey, notAfter); if (cert == null) { throw new Exception("Null returned"); } return cert; } catch (final Exception ex) { throw new AuthException("failed to generate VM certificate", ex); } }
From source file:it.measureHistory.SincePreviousVersionHistoryTest.java
/** * SONAR-6356//from w w w .j a v a 2 s . com */ @Test public void since_previous_version_should_use_first_analysis_when_no_version_found() { Date now = new Date(); // Analyze project by excluding some files analyzeProject("1.0-SNAPSHOT", "**/*2.xoo", toStringDate(DateUtils.addDays(now, -2))); // No difference measure after first analysis assertThat(getLeakPeriodValue(orchestrator, PROJECT, "files")).isNull(); analyzeProjectWithDate("1.0-SNAPSHOT", toStringDate(DateUtils.addDays(now, -1))); // No new version, first analysis is used -> 2 new files assertThat(getLeakPeriodValue(orchestrator, PROJECT, "files")).isEqualTo(2); analyzeProjectWithDate("1.0-SNAPSHOT", toStringDate(now)); // Still no new version, first analysis is used -> 2 new files assertThat(getLeakPeriodValue(orchestrator, PROJECT, "files")).isEqualTo(2); }
From source file:net.audumla.irrigation.SimpleIrrigationTest.java
@Test public void testEnclosedIrrigation() throws SchedulerException, InterruptedException { ClimateObserver obs1 = createObserver(); IrrigationZone zone = buildZone(createObserver()); zone.setCoverRating(1);//from ww w . j a va2 s. c o m zone.setEnclosureRating(0.8); zone.setShadeRating(0.1); EToCalculator etc = new EToCalculator(); etc.setZone(zone); ClimateObserver obs2 = zone.getClimateObserver(); Date now = DateUtils.addDays(new Date(), -2); ClimateData data1 = obs1.getClimateData(now); ClimateData data2 = obs2.getClimateData(now); if (data2.getAverageWindSpeed() != 0) { Assert.assertNotEquals(data1.getAverageWindSpeed(), data2.getAverageWindSpeed()); } if (data2.getSolarRadiation() != 0) { Assert.assertNotEquals(data1.getSolarRadiation(), data2.getSolarRadiation()); } if (data2.getRainfall() != 0) { Assert.assertNotEquals(data1.getRainfall(), data2.getRainfall()); } if (data2.getMaximumHumidity() != 0) { Assert.assertNotEquals(data1.getMaximumHumidity(), data2.getMaximumHumidity()); } Assert.assertEquals(data1.getDaylightHours(), data2.getDaylightHours(), 0.1); Assert.assertEquals(data1.getSunrise().getTime(), data2.getSunrise().getTime(), 1000); }
From source file:net.audumla.climate.bom.BOMHistoricalClimateObserver.java
protected boolean loadStationDataFile(String stationSubDir, String fileName, String stationName) { try {// w w w . jav a 2 s . c o m String fn = stationSubDir + fileName; if (!fn.equals(lastLoadedFile)) { BufferedReader br = BOMDataLoader.instance().getData(BOMDataLoader.FTP, BOMDataLoader.BOMFTP, BOMDataLoader.BOMBaseFTPDir + fn); String line; while ((line = br.readLine()) != null) { try { String[] data = line.split(","); if (data[0].toLowerCase().equals(stationName)) { // Station Name,JulianDate,EvapoTranspiration,Rain,Pan Evaporation,Maximum Temp,Minimum Temp,Max // Relative Hum,Min Relative Hum,Avg 10m Wind Sp,Solar Radiation // VIEWBANK,12/01/2013,4.5,0.0, ,25.2,15.7,77,43,3.53,16.10 Date date = yearMonthDay.parse(data[1].trim()); Date dateM1 = DateUtils.addDays(date, -1); WritableClimateData cdNow = ClimateDataFactory .convertToWritableClimateData(historicalData.get(date)); if (cdNow == null) { cdNow = ClimateDataFactory.newWritableClimateData(this, getSource()); // now cdNow.setTime(date); historicalData.put(date, ClimateDataFactory.convertToReadOnlyClimateData(cdNow)); } WritableClimateData cdNowM1 = ClimateDataFactory .convertToWritableClimateData(historicalData.get(dateM1)); if (cdNowM1 == null) { cdNowM1 = ClimateDataFactory.newWritableClimateData(this, getSource()); // now cdNowM1.setTime(dateM1); historicalData.put(dateM1, ClimateDataFactory.convertToReadOnlyClimateData(cdNowM1)); } try { cdNow.setEvapotranspiration(SafeParse.parseDouble(data[2].trim())); } catch (Exception ignored) { } try { Double rain = SafeParse.parseDouble(data[3]); if (rain != null) { cdNowM1.setRainfall(rain); cdNowM1.setRainfallProbability(cdNowM1.getRainfall() > 0 ? 100d : 0d); } } catch (Exception ignored) { } try { cdNow.setEvaporation(SafeParse.parseDouble(data[4].trim())); } catch (Exception ignored) { } try { cdNow.setMaximumTemperature(SafeParse.parseDouble(data[5].trim())); } catch (Exception ignored) { } try { cdNow.setMinimumTemperature(SafeParse.parseDouble(data[6].trim())); } catch (Exception ignored) { } try { cdNow.setMaximumHumidity(SafeParse.parseDouble(data[7].trim())); } catch (Exception ignored) { } try { cdNow.setMinimumHumidity(SafeParse.parseDouble(data[8].trim())); } catch (Exception ignored) { } try { cdNow.setAverageWindSpeed(SafeParse.parseDouble(data[9].trim())); cdNow.setWindSpeedHeight(10.0); } catch (Exception ignored) { } try { cdNow.setSolarRadiation(SafeParse.parseDouble(data[10].trim())); } catch (Exception ignored) { } } } catch (Exception e) { e.printStackTrace(); } } lastLoadedFile = fn; } } catch (UnsupportedOperationException ex) { // cannot load the csv file. return false; } catch (Exception ex) { logger.error(ex); } return true; }
From source file:com.ms.app.web.commons.tools.DateViewTools.java
public static String getDayBefore(int before) { Date date = new Date(); date = DateUtils.addDays(date, -before); return getFormat(SIMPLE_DATE_FORMAT_PATTERN).format(date); }
From source file:net.audumla.climate.DataSourceTest.java
@Test public void testRainfallcall() { Date now = new Date(); ClimateData cd = getData(now);//from ww w . j av a2 s.c om cd.getRainfall(); Assert.assertEquals(cd.getDataSource().getType(), ClimateDataSource.ClimateDataSourceType.DAILY_FORECAST); cd = getData(DateUtils.addDays(now, -1)); cd.getRainfall(); Assert.assertEquals(cd.getDataSource().getType(), ClimateDataSource.ClimateDataSourceType.DAILY_OBSERVATION); }
From source file:ch.puzzle.itc.mobiliar.presentation.resourcesedit.EditResourceViewTest.java
@Test public void testExistsForThisRelease() { //given/*from w ww. j a v a 2 s. c o m*/ ResourceGroupEntity group = new ResourceGroupEntity(); ResourceEntity r = ResourceFactory.createNewResource(group); ResourceGroupEntity group2 = new ResourceGroupEntity(); ResourceEntity r2 = ResourceFactory.createNewResource(group2); ReleaseEntity rel = new ReleaseEntity(); rel.setInstallationInProductionAt(new Date()); ReleaseEntity rel2 = new ReleaseEntity(); rel2.setInstallationInProductionAt(DateUtils.addDays(new Date(), 2)); r.setRelease(rel); r2.setRelease(rel2); //when context.resource = r; //then //The second group does only exist for a release later than the first - therefore the method returns false. Assert.assertFalse(context.existsForThisRelease(group2)); //when context.resource = r2; //then //In the inverse direction, the first group already exists... Assert.assertTrue(context.existsForThisRelease(group)); //when r.setRelease(rel2); //if both have the same release, the method also returns true Assert.assertTrue(context.existsForThisRelease(group)); }