List of usage examples for org.joda.time Days daysBetween
public static Days daysBetween(ReadablePartial start, ReadablePartial end)
Days
representing the number of whole days between the two specified partial datetimes. From source file:com.eucalyptus.portal.Ec2ReportsService.java
License:Open Source License
public ViewInstanceUsageReportResponseType viewInstanceUsageReport(final ViewInstanceUsageReportType request) throws Ec2ReportsServiceException { final ViewInstanceUsageReportResponseType response = request.getReply(); final Context context = checkAuthorized(); try {/*from www. ja va 2 s . c om*/ final Function<ViewInstanceUsageReportType, Optional<Ec2ReportsServiceException>> requestVerifier = ( req) -> { if (req.getGranularity() == null) return Optional.of(new Ec2ReportsInvalidParameterException("Granularity must be specified")); final String granularity = req.getGranularity().toLowerCase(); if (request.getTimeRangeStart() == null || request.getTimeRangeEnd() == null) return Optional.of( new Ec2ReportsInvalidParameterException("time range start and end must be specified")); if (!Sets.newHashSet("hourly", "hour", "daily", "day", "monthly", "month").contains(granularity)) { return Optional.of(new Ec2ReportsInvalidParameterException( "Can't recognize granularity. Valid values are hourly, daily and monthly")); } if (granularity.equals("hourly") || granularity.equals("hour")) { // AWS: time range up to 7 days when using an hourly data granularity if (Days.daysBetween(new DateTime(request.getTimeRangeStart().getTime()), new DateTime(request.getTimeRangeEnd().getTime())).getDays() > 7) { return Optional.of(new Ec2ReportsInvalidParameterException( "time range is allowed up to 7 days when using an hourly data granularity")); } } else if (granularity.equals("daily") || granularity.equals("day")) { // AWS: time range up to 3 months when using a daily data granularity if (Months.monthsBetween(new DateTime(request.getTimeRangeStart().getTime()), new DateTime(request.getTimeRangeEnd().getTime())).getMonths() > 3) { return Optional.of(new Ec2ReportsInvalidParameterException( "time range is allowed up to 3 months when using a daily data granularity")); } } else { // AWS: time range up to 3 years when using a monthly data granularity. if (Years.yearsBetween(new DateTime(request.getTimeRangeStart().getTime()), new DateTime(request.getTimeRangeEnd().getTime())).getYears() > 3) { return Optional.of(new Ec2ReportsInvalidParameterException( "time range is allowed up to 3 years when using a monthly data granularity")); } } if (request.getGroupBy() != null) { if (request.getGroupBy().getType() == null) return Optional.of(new Ec2ReportsInvalidParameterException( "In group by parameter, type must be specified")); final String groupType = request.getGroupBy().getType().toLowerCase(); final String groupKey = request.getGroupBy().getKey(); if (!Sets.newHashSet("tag", "tags", "instancetype", "instance_type", "platform", "platforms", "availabilityzone", "availability_zone").contains(groupType)) { return Optional.of(new Ec2ReportsInvalidParameterException( "supported types in group by parameter are: tag, instance_type, platform, and availability_zone")); } if ("tag".equals(groupType) || "tags".equals(groupType)) { if (groupKey == null) { return Optional.of(new Ec2ReportsInvalidParameterException( "tag type in group by parameter must also include tag key")); } } } return Optional.empty(); }; final Optional<Ec2ReportsServiceException> error = requestVerifier.apply(request); if (error.isPresent()) { throw error.get(); } final String granularity = request.getGranularity().toLowerCase(); final List<InstanceHourLog> logs = Lists.newArrayList(); if (granularity.equals("hourly") || granularity.equals("hour")) { logs.addAll(InstanceLogs.getInstance().queryHourly(context.getAccountNumber(), request.getTimeRangeStart(), request.getTimeRangeEnd(), request.getFilters())); } else if (granularity.equals("daily") || granularity.equals("day")) { logs.addAll(InstanceLogs.getInstance().queryDaily(context.getAccountNumber(), request.getTimeRangeStart(), request.getTimeRangeEnd(), request.getFilters())); } else { logs.addAll(InstanceLogs.getInstance().queryMonthly(context.getAccountNumber(), request.getTimeRangeStart(), request.getTimeRangeEnd(), request.getFilters())); } Collector<InstanceHourLog, ?, Map<String, List<InstanceHourLog>>> collector = null; Comparator<String> keySorter = String::compareTo; // determines which column appear first if (request.getGroupBy() != null) { final String groupType = request.getGroupBy().getType().toLowerCase(); final String groupKey = request.getGroupBy().getKey(); if ("instancetype".equals(groupType) || "instance_type".equals(groupType)) { collector = groupingBy((log) -> log.getInstanceType(), toList()); keySorter = String::compareTo; // sort by type name is natural } else if ("platform".equals(groupType) || "platforms".equals(groupType)) { collector = groupingBy((log) -> log.getPlatform(), toList()); keySorter = String::compareTo; // linux comes before windows } else if ("availabilityzone".equals(groupType) || "availability_zone".equals(groupType)) { collector = groupingBy((log) -> log.getAvailabilityZone(), toList()); keySorter = String::compareTo; } else if ("tag".equals(groupType) || "tags".equals(groupType)) { // map instanceId to tag value where tag key = group key final Map<String, String> tagValueMap = logs.stream() .collect(groupingBy((log) -> log.getInstanceId(), toList())).entrySet().stream() .map(e -> e.getValue().get(0)) .filter(l -> l.getTags().stream().filter(t -> groupKey.equals(t.getKey())).findAny() .isPresent()) .collect(Collectors.toMap(l -> l.getInstanceId(), l -> l.getTags().stream() .filter(t -> groupKey.equals(t.getKey())).findAny().get().getValue())); logs.stream().forEach(l -> { if (!tagValueMap.containsKey(l.getInstanceId())) tagValueMap.put(l.getInstanceId(), "[UNTAGGED]"); }); collector = groupingBy((log) -> tagValueMap.get(log.getInstanceId()), toList()); keySorter = (s1, s2) -> { if ("[UNTAGGED]".equals(s1) && "[UNTAGGED]".equals(s2)) return 0; else if ("[UNTAGGED]".equals(s1)) return -1; else if ("[UNTAGGED]".equals(s2)) return 1; else return s1.compareTo(s2); }; } else { throw new Ec2ReportsInvalidParameterException( "supported types in group by parameter are: tag, instance_type, platform, and availability_zone"); } } else { collector = groupingBy((log) -> "[INSTANCE HOURS]", toList()); } final Function<Date, AbstractMap.SimpleEntry<Date, Date>> ranger = (logTime) -> { final Calendar start = Calendar.getInstance(); final Calendar end = Calendar.getInstance(); start.setTime(logTime); end.setTime(logTime); if (granularity.equals("hourly") || granularity.equals("hour")) { end.set(Calendar.HOUR_OF_DAY, end.get(Calendar.HOUR_OF_DAY) + 1); } else if (granularity.equals("daily") || granularity.equals("day")) { end.set(Calendar.DAY_OF_MONTH, start.get(Calendar.DAY_OF_MONTH) + 1); start.set(Calendar.HOUR_OF_DAY, 0); end.set(Calendar.HOUR_OF_DAY, 0); } else { end.set(Calendar.MONTH, start.get(Calendar.MONTH) + 1); start.set(Calendar.DAY_OF_MONTH, 1); start.set(Calendar.HOUR_OF_DAY, 0); end.set(Calendar.DAY_OF_MONTH, 1); end.set(Calendar.HOUR_OF_DAY, 0); } for (final int flag : new int[] { Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND }) { start.set(flag, 0); end.set(flag, 0); } return new AbstractMap.SimpleEntry<Date, Date>(start.getTime(), end.getTime()); }; // sum over instance hours whose log_time is the same /* e.g., INPUT: m1.small -> [(i-1d9eb607,2017-03-16 12:00:00), (i-1d9eb607,2017-03-16 13:00:00), (i-fe4a9384,2017-03-16 13:00:00)] OUTPUT: m1.small -> [2017-03-16 12:00:00: 1, 2017-03-16 13:00:00: 2] */ final Map<String, List<InstanceHourLog>> logsByGroupKey = logs.stream().collect(collector); final Map<String, Map<Date, Long>> hoursAtLogTimeByGroupKey = logsByGroupKey.entrySet().stream() .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().stream() .collect(groupingBy(l -> l.getLogTime(), summingLong(l -> l.getHours())) // -> Map<String, Map<Date, Long> ))); // key -> [(log_time, hours)...] final Map<String, List<AbstractMap.SimpleEntry<Date, Long>>> instanceHoursAtLogTime = hoursAtLogTimeByGroupKey .entrySet().stream() .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().entrySet().stream() .map(e1 -> new AbstractMap.SimpleEntry<Date, Long>(e1.getKey(), e1.getValue())) .collect(toList()))); final StringBuilder sb = new StringBuilder(); sb.append("Start Time,End Time"); for (final String key : instanceHoursAtLogTime.keySet().stream().sorted(keySorter).collect(toList())) { sb.append(String.format(",%s", key)); } // fill-in missing logs (with 0 hours) in the table final Set<Date> distinctLogs = instanceHoursAtLogTime.values().stream().flatMap(e -> e.stream()) .map(kv -> kv.getKey()).distinct().collect(toSet()); for (final String groupKey : instanceHoursAtLogTime.keySet()) { final List<AbstractMap.SimpleEntry<Date, Long>> hours = instanceHoursAtLogTime.get(groupKey); final Set<Date> currentLogs = hours.stream().map(kv -> kv.getKey()).collect(toSet()); final List<AbstractMap.SimpleEntry<Date, Long>> normalized = Lists.newArrayList(hours); for (final Date missing : Sets.difference(distinctLogs, currentLogs)) { normalized.add(new AbstractMap.SimpleEntry<Date, Long>(missing, 0L)); } instanceHoursAtLogTime.put(groupKey, normalized); } final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); final Map<Date, String> lines = Maps.newHashMap(); for (final String groupKey : instanceHoursAtLogTime.keySet().stream().sorted(keySorter) .collect(toList())) { for (final AbstractMap.SimpleEntry<Date, Long> hl : instanceHoursAtLogTime.get(groupKey)) { final Date logTime = hl.getKey(); final Long hours = hl.getValue(); if (!lines.containsKey(logTime)) { lines.put(logTime, String.format("%s,%s,%d", df.format(ranger.apply(logTime).getKey()), df.format(ranger.apply(logTime).getValue()), hours)); } else { lines.put(logTime, String.format("%s,%d", lines.get(logTime), hours)); } } } lines.entrySet().stream().sorted((e1, e2) -> e1.getKey().compareTo(e2.getKey())) // order by log time .map(e -> e.getValue()).forEach(s -> sb.append(String.format("\n%s", s))); final ViewInstanceUsageResult result = new ViewInstanceUsageResult(); result.setUsageReport(sb.toString()); response.setResult(result); } catch (final Ec2ReportsServiceException ex) { throw ex; } catch (final Exception ex) { handleException(ex); } return response; }
From source file:com.firmansyah.imam.sewa.kendaraan.FormSewa.java
private void btnSimpanTransaksiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSimpanTransaksiActionPerformed SimpleDateFormat ft = new SimpleDateFormat("YYYY-MM-dd"); Date tgl_mulai = inputTanggalMulai.getDate(); Date tgl_akhir = inputTanggalAkhir.getDate(); String id_pelaggan = String.valueOf(inputIdPelanggan.getSelectedItem()); String id_kendaraan = String.valueOf(inputIdKendaraan.getSelectedItem()); int days = Days.daysBetween(new DateTime(tgl_mulai), new DateTime(tgl_akhir)).getDays(); System.out.println("Days Between " + tgl_mulai + " : " + tgl_akhir + " - " + days); if (id_pelaggan.equals("ID Pelanggan")) { id_pelaggan = ""; }//ww w .j a va2s . c o m if (id_kendaraan.equals("ID Kendaraan")) { id_kendaraan = " "; } if (tgl_mulai == null || tgl_akhir == null || id_pelaggan.isEmpty() || id_kendaraan.isEmpty()) { JOptionPane.showMessageDialog(this, "Data Tidak Boleh Kosong", "Informasi", JOptionPane.ERROR_MESSAGE); } else if (days <= 0) { JOptionPane.showMessageDialog(this, "Masukan Tanggal dengan Benar", "Informasi", JOptionPane.ERROR_MESSAGE); } else { String tanggal_mulai = ft.format(tgl_mulai); String tanggal_akhir = ft.format(tgl_akhir); String url = Path.serverURL + "/sewa/create/" + id_pelaggan + "/" + tanggal_mulai + "/" + tanggal_akhir + "/" + id_kendaraan; getDataURL dataurl = new getDataURL(); try { String data = dataurl.getData(url); System.out.println(data); inputTanggalMulai.setDate(null); inputTanggalAkhir.setDate(null); JOptionPane.showMessageDialog(this, "Data Berhasil disimpan", "Informasi", JOptionPane.INFORMATION_MESSAGE); } catch (IOException ex) { Logger.getLogger(FormSewa.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:com.firmansyah.imam.sewa.kendaraan.FormTransaksi.java
public void detailTransaksi(String id_transaksi) throws ParseException { System.out.println("Set ID nya : " + id_transaksi); try {// w w w . ja va 2 s.c o m getDataURL dataurl = new getDataURL(); String url = Path.serverURL + "/sewa/show/" + id_transaksi; String data = dataurl.getData(url); Object obj = JSONValue.parse(data); JSONArray dataArray = (JSONArray) obj; JSONObject getData = (JSONObject) dataArray.get(0); Object id_sewa = getData.get("id"); Object dari_tanggal = getData.get("tanggal_mulai"); Object sampai_tanggal = getData.get("tanggal_akhir"); Object tanggal_sewa = getData.get("tanggal_sewa"); Object kendaraan = getData.get("kendaraan"); Object pelanggan = getData.get("pelanggan"); Object status_sewa = getData.get("status"); if (status_sewa.equals("1")) { btnSelesai.setEnabled(false); } JSONObject getJsonKendaraan = (JSONObject) new JSONParser().parse(kendaraan.toString()); JSONObject getJsonPelanggan = (JSONObject) new JSONParser().parse(pelanggan.toString()); Object nama_kendaraan = getJsonKendaraan.get("nama_kendaraan"); Object no_polisi = getJsonKendaraan.get("no_polisi"); Object tahun_kendaraan = getJsonKendaraan.get("tahun_kendaraan"); Object biaya_sewa = getJsonKendaraan.get("biaya_sewa"); Object nama_pelanggan = getJsonPelanggan.get("nama_pelanggan"); Object alamat = getJsonPelanggan.get("alamat"); Object no_telp = getJsonPelanggan.get("no_telp"); Object no_identitas = getJsonPelanggan.get("no_identitas"); String tgl_mulai = dari_tanggal.toString(); String tgl_akhir = sampai_tanggal.toString(); int days = Days.daysBetween(new DateTime(tgl_mulai), new DateTime(tgl_akhir)).getDays() + 1; int total_biaya_sewa = Integer.parseInt(biaya_sewa.toString()) * days; DecimalFormat df = new DecimalFormat("###,###.###"); String biaya_sewaConvert = df.format(Integer.parseInt(biaya_sewa.toString())); String total_biayaConvert = df.format(total_biaya_sewa); inputNoSewa.setText(id_sewa.toString()); inputDariTanggal.setText(dari_tanggal.toString()); inputSampai.setText(sampai_tanggal.toString()); inputHari.setText(String.valueOf(days)); inputHariSewa.setText(String.valueOf(days)); inputNamaKendaraan.setText(nama_kendaraan.toString()); inputNoPolisi.setText(no_polisi.toString()); inputTahunKendaraan.setText(tahun_kendaraan.toString()); inputNamaPelanggan.setText(nama_pelanggan.toString()); inputAlamat.setText(alamat.toString()); inputNoTelp.setText(no_telp.toString()); inputNoIdentitas.setText(no_identitas.toString()); labelTanggalTransaksi.setText(tanggal_sewa.toString()); inputBiayaSewa.setText(biaya_sewaConvert); inputBiayaTotal.setText(total_biayaConvert); } catch (IOException ex) { Logger.getLogger(FormTransaksi.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.fpt.mic.micweb.model.dto.form.CreateCompensationDto.java
@AssertTrue(message = "Khng th gi yu cu bi th?ng cho hp ng b hy qu th?i hn cp nht thng tin") private boolean isValidUpdateDueDate() { ContractDao contractDao = new ContractDao(); ContractEntity contractEntity = contractDao.read(contractCode); if (contractEntity != null && contractEntity.getStatus().equalsIgnoreCase(Constants.ContractStatus.CANCELLED)) { LocalDate cancelDate = new LocalDate(contractEntity.getCancelDate()); int durationFromCurrentToCancel = Days.daysBetween(cancelDate, new LocalDate()).getDays(); ConfigUtils configUtils = new ConfigUtils(); return durationFromCurrentToCancel <= configUtils.getUpdateContractDueDate(); } else {/*from w w w .jav a 2 s. com*/ return true; } }
From source file:com.github.flawedbliss.dicebotr3.DicebotR3.java
License:Open Source License
private void checkPremiumExpired(String uid, int clId) { Connection connect = null;//from ww w . j av a 2 s . c o m PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connect = cp.getConnection(); preparedStatement = connect.prepareStatement("SELECT * FROM premium WHERE used_by=?"); preparedStatement.setString(1, uid); resultSet = preparedStatement.executeQuery(); DateTime today = new DateTime(new Date()); DateTime latest = new DateTime(new Date()); latest = latest.minusYears(1); if (resultSet.isBeforeFirst()) { while (resultSet.next()) { DateTime resultSetDate = new DateTime(resultSet.getDate("date_used")); if (resultSetDate.isAfter(latest)) { latest = resultSetDate; } } Days d = Days.daysBetween(latest, today); if (d.getDays() > cfg.getPremiumDays()) { myApi.removeClientFromServerGroup(cfg.getPremiumGID(), myApi.getClientByUId(uid).getDatabaseId()); myApi.sendPrivateMessage(clId, "Your premium has expired."); } } } catch (SQLException ex) { log.warning("SQLException when trying to check premium of" + uid); ex.printStackTrace(); } }
From source file:com.github.flawedbliss.dicebotr3.DicebotR3.java
License:Open Source License
private boolean checkInactivity(String uid, int days) { if (cfg.getInactiveGID() == -1) { return false; }//from w w w.j a va 2 s . c o m Connection connect = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connect = cp.getConnection(); preparedStatement = connect.prepareStatement("SELECT * FROM lastlogin WHERE uid=?"); preparedStatement.setString(1, uid); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { DateTime today = new DateTime(new Date()); DateTime lastlogin = new DateTime(resultSet.getDate("lastlogin")); Days d = Days.daysBetween(today, lastlogin); if (d.getDays() > days) { myApi.addClientToServerGroup(cfg.getInactiveGID(), myApi.getClientByUId(uid).getDatabaseId()); return true; } } resultSet.close(); preparedStatement.close(); connect.close(); } catch (SQLException ex) { log.warning("SQLException while checking inactivity of " + uid); } return false; }
From source file:com.github.flawedbliss.dicebotr4.DicebotR4.java
License:Open Source License
/** * * @param uid Unique Id of the user you want to check * @return returns the number of days since a user last connected * @throws DicebotException//from ww w.j a v a 2 s . com */ private int getClientInactivityDays(String uid) throws DicebotException { DateTime lastlogin = sqlManager.getLastLogin(uid); if (lastlogin != null) { return Days.daysBetween(new DateTime(new Date()), lastlogin).getDays(); } else { return 0; } }
From source file:com.github.flawedbliss.dicebotr4.DicebotR4.java
License:Open Source License
/** * * @param CI ClientInfo of the client to be checked * @return Returns true if it was more days ago than set in the * configuration.//w w w . ja v a 2 s.c o m */ private boolean isPremiumExpired(ClientInfo CI) { try { return Days.daysBetween(sqlManager.getPremiumBegin(CI.getUniqueIdentifier()), new DateTime(new Date())) .getDays() > config.getPremiumDays(); } catch (DicebotException ex) { log.warning(ex.getMessage()); return false; } }
From source file:com.github.serddmitry.jodainterval.LocalDateIntervalImpl.java
License:Apache License
LocalDateIntervalImpl(LocalDate first, LocalDate last) { this.first = checkNotNull(first, "lower bound of the interval cannot be null"); this.last = checkNotNull(last, "upper bound of the interval cannot be null"); checkArgument(!first.isAfter(last), "lower bound %s cannot be after upper bound %s", first, last); this.days = Days.daysBetween(first, last).getDays() + 1; // interval includes 'last' date, therefore, adding 1 }
From source file:com.google.android.apps.paco.NonESMSignalGenerator.java
License:Open Source License
private DateTime nextRepeatDaily(DateTime midnightTomorrow) { if (schedule.getRepeatRate() == 1) { return midnightTomorrow; }/*from w w w . j av a 2 s. c om*/ int distanceBetweenStartAndTomorrow = Days .daysBetween(new DateTime(schedule.getBeginDate()).toDateMidnight(), midnightTomorrow).getDays(); if (distanceBetweenStartAndTomorrow == 0 || distanceBetweenStartAndTomorrow == schedule.getRepeatRate()) { return midnightTomorrow; } else if (distanceBetweenStartAndTomorrow > schedule.getRepeatRate()) { int remainder = distanceBetweenStartAndTomorrow % schedule.getRepeatRate(); return midnightTomorrow.plusDays(schedule.getRepeatRate() - remainder); } else { return midnightTomorrow.plusDays(schedule.getRepeatRate() - distanceBetweenStartAndTomorrow); } }