List of usage examples for java.time Duration between
public static Duration between(Temporal startInclusive, Temporal endExclusive)
From source file:fi.hsl.parkandride.itest.PredictionITest.java
private static void assertIsNear(DateTime expected, DateTime actual) { Instant i1 = Instant.ofEpochMilli(expected.getMillis()); Instant i2 = Instant.ofEpochMilli(actual.getMillis()); Duration d = Duration.between(i1, i2).abs(); assertThat(d.toMinutes()).as("distance to " + expected + " in minutes") .isLessThanOrEqualTo(PredictionRepository.PREDICTION_RESOLUTION.getMinutes()); }
From source file:nu.yona.server.analysis.service.AnalysisEngineService.java
private boolean isBeyondSkipWindowAfterLastRegisteredActivity(ActivityPayload payload, ActivityDto lastRegisteredActivity) { return Duration.between(lastRegisteredActivity.getEndTime(), payload.endTime) .compareTo(yonaProperties.getAnalysisService().getUpdateSkipWindow()) >= 0; }
From source file:org.apache.nifi.avro.AvroTypeUtil.java
@SuppressWarnings("unchecked") private static Object convertToAvroObject(final Object rawValue, final Schema fieldSchema, final String fieldName, final Charset charset) { if (rawValue == null) { return null; }//from w ww . j av a 2 s . c om switch (fieldSchema.getType()) { case INT: { final LogicalType logicalType = fieldSchema.getLogicalType(); if (logicalType == null) { return DataTypeUtils.toInteger(rawValue, fieldName); } if (LOGICAL_TYPE_DATE.equals(logicalType.getName())) { final String format = AvroTypeUtil.determineDataType(fieldSchema).getFormat(); final Date date = DataTypeUtils.toDate(rawValue, () -> DataTypeUtils.getDateFormat(format), fieldName); final Duration duration = Duration.between(new Date(0L).toInstant(), new Date(date.getTime()).toInstant()); final long days = duration.toDays(); return (int) days; } else if (LOGICAL_TYPE_TIME_MILLIS.equals(logicalType.getName())) { final String format = AvroTypeUtil.determineDataType(fieldSchema).getFormat(); final Time time = DataTypeUtils.toTime(rawValue, () -> DataTypeUtils.getDateFormat(format), fieldName); final Date date = new Date(time.getTime()); final Duration duration = Duration.between(date.toInstant().truncatedTo(ChronoUnit.DAYS), date.toInstant()); final long millisSinceMidnight = duration.toMillis(); return (int) millisSinceMidnight; } return DataTypeUtils.toInteger(rawValue, fieldName); } case LONG: { final LogicalType logicalType = fieldSchema.getLogicalType(); if (logicalType == null) { return DataTypeUtils.toLong(rawValue, fieldName); } if (LOGICAL_TYPE_TIME_MICROS.equals(logicalType.getName())) { final long longValue = getLongFromTimestamp(rawValue, fieldSchema, fieldName); final Date date = new Date(longValue); final Duration duration = Duration.between(date.toInstant().truncatedTo(ChronoUnit.DAYS), date.toInstant()); return duration.toMillis() * 1000L; } else if (LOGICAL_TYPE_TIMESTAMP_MILLIS.equals(logicalType.getName())) { final String format = AvroTypeUtil.determineDataType(fieldSchema).getFormat(); Timestamp t = DataTypeUtils.toTimestamp(rawValue, () -> DataTypeUtils.getDateFormat(format), fieldName); return getLongFromTimestamp(rawValue, fieldSchema, fieldName); } else if (LOGICAL_TYPE_TIMESTAMP_MICROS.equals(logicalType.getName())) { return getLongFromTimestamp(rawValue, fieldSchema, fieldName) * 1000L; } return DataTypeUtils.toLong(rawValue, fieldName); } case BYTES: case FIXED: final LogicalType logicalType = fieldSchema.getLogicalType(); if (logicalType != null && LOGICAL_TYPE_DECIMAL.equals(logicalType.getName())) { final LogicalTypes.Decimal decimalType = (LogicalTypes.Decimal) logicalType; final BigDecimal rawDecimal; if (rawValue instanceof BigDecimal) { rawDecimal = (BigDecimal) rawValue; } else if (rawValue instanceof Double) { rawDecimal = BigDecimal.valueOf((Double) rawValue); } else if (rawValue instanceof String) { rawDecimal = new BigDecimal((String) rawValue); } else if (rawValue instanceof Integer) { rawDecimal = new BigDecimal((Integer) rawValue); } else if (rawValue instanceof Long) { rawDecimal = new BigDecimal((Long) rawValue); } else { throw new IllegalTypeConversionException("Cannot convert value " + rawValue + " of type " + rawValue.getClass() + " to a logical decimal"); } // If the desired scale is different than this value's coerce scale. final int desiredScale = decimalType.getScale(); final BigDecimal decimal = rawDecimal.scale() == desiredScale ? rawDecimal : rawDecimal.setScale(desiredScale, BigDecimal.ROUND_HALF_UP); return new Conversions.DecimalConversion().toBytes(decimal, fieldSchema, logicalType); } if (rawValue instanceof byte[]) { return ByteBuffer.wrap((byte[]) rawValue); } if (rawValue instanceof String) { return ByteBuffer.wrap(((String) rawValue).getBytes(charset)); } if (rawValue instanceof Object[]) { return AvroTypeUtil.convertByteArray((Object[]) rawValue); } else { throw new IllegalTypeConversionException("Cannot convert value " + rawValue + " of type " + rawValue.getClass() + " to a ByteBuffer"); } case MAP: if (rawValue instanceof Record) { final Record recordValue = (Record) rawValue; final Map<String, Object> map = new HashMap<>(); for (final RecordField recordField : recordValue.getSchema().getFields()) { final Object v = recordValue.getValue(recordField); if (v != null) { map.put(recordField.getFieldName(), v); } } return map; } else if (rawValue instanceof Map) { final Map<String, Object> objectMap = (Map<String, Object>) rawValue; final Map<String, Object> map = new HashMap<>(objectMap.size()); for (final String s : objectMap.keySet()) { final Object converted = convertToAvroObject(objectMap.get(s), fieldSchema.getValueType(), fieldName + "[" + s + "]", charset); map.put(s, converted); } return map; } else { throw new IllegalTypeConversionException( "Cannot convert value " + rawValue + " of type " + rawValue.getClass() + " to a Map"); } case RECORD: final GenericData.Record avroRecord = new GenericData.Record(fieldSchema); final Record record = (Record) rawValue; for (final RecordField recordField : record.getSchema().getFields()) { final Object recordFieldValue = record.getValue(recordField); final String recordFieldName = recordField.getFieldName(); final Field field = fieldSchema.getField(recordFieldName); if (field == null) { continue; } final Object converted = convertToAvroObject(recordFieldValue, field.schema(), fieldName + "/" + recordFieldName, charset); avroRecord.put(recordFieldName, converted); } return avroRecord; case UNION: return convertUnionFieldValue(rawValue, fieldSchema, schema -> convertToAvroObject(rawValue, schema, fieldName, charset), fieldName); case ARRAY: final Object[] objectArray = (Object[]) rawValue; final List<Object> list = new ArrayList<>(objectArray.length); int i = 0; for (final Object o : objectArray) { final Object converted = convertToAvroObject(o, fieldSchema.getElementType(), fieldName + "[" + i + "]", charset); list.add(converted); i++; } return list; case BOOLEAN: return DataTypeUtils.toBoolean(rawValue, fieldName); case DOUBLE: return DataTypeUtils.toDouble(rawValue, fieldName); case FLOAT: return DataTypeUtils.toFloat(rawValue, fieldName); case NULL: return null; case ENUM: return new GenericData.EnumSymbol(fieldSchema, rawValue); case STRING: return DataTypeUtils.toString(rawValue, (String) null, charset); } return rawValue; }
From source file:org.eclipse.hono.service.amqp.AmqpServiceBase.java
/** * Processes a peer's AMQP <em>open</em> frame. * <p>//from www. java 2 s. co m * This default implementation * <ol> * <li>adds a unique connection identifier to the connection's attachments * under key {@link Constants#KEY_CONNECTION_ID}</li> * <li>invokes {@link #processDesiredCapabilities(ProtonConnection, Symbol[])}</li> * <li>sets a timer that closes the connection once the client's token * has expired</li> * <li>sends the AMQP <em>open</em> frame to the peer</li> * </ol> * * @param connection The connection to open. */ protected void processRemoteOpen(final ProtonConnection connection) { final HonoUser clientPrincipal = Constants.getClientPrincipal(connection); LOG.debug("client [container: {}, user: {}] connected", connection.getRemoteContainer(), clientPrincipal.getName()); // attach an ID so that we can later inform downstream components when connection is closed connection.attachments().set(Constants.KEY_CONNECTION_ID, String.class, UUID.randomUUID().toString()); processDesiredCapabilities(connection, connection.getRemoteDesiredCapabilities()); final Duration delay = Duration.between(Instant.now(), clientPrincipal.getExpirationTime()); final WeakReference<ProtonConnection> conRef = new WeakReference<>(connection); vertx.setTimer(delay.toMillis(), timerId -> { if (conRef.get() != null) { closeExpiredConnection(conRef.get()); } }); connection.open(); }
From source file:net.di2e.ecdr.describe.generator.DescribeGeneratorImpl.java
protected void setRecordRate(MetricsType metrics, Map<String, TemporalCoverageHolder> timeMap) { TemporalCoverageHolder tc = timeMap.containsKey("modified") ? (TemporalCoverageHolder) timeMap.get("modified") : (timeMap.containsKey("effective") ? (TemporalCoverageHolder) timeMap.get("effective") : (TemporalCoverageHolder) timeMap.get("created")); try {/* w w w .j ava 2 s .c o m*/ if (tc != null) { Date startDate = tc.getStartDate(); if (startDate != null) { long totalHits = metrics.getCount(); LocalDateTime start = LocalDateTime.ofInstant(startDate.toInstant(), ZoneId.systemDefault()); Duration duration = Duration.between(start, LocalDateTime.now()); RecordRateType rate = new RecordRateType(); metrics.setRecordRate(rate); long dur = totalHits / duration.toHours(); if (dur < 15L) { dur = totalHits / duration.toDays(); if (dur < 4L) { dur = totalHits * 30L / duration.toDays(); if (dur < 10L) { dur = totalHits * 365L / duration.toDays(); rate.setFrequency("Yearly"); } else { rate.setFrequency("Monthly"); } } else { rate.setFrequency("Daily"); } } else if (totalHits > 1000L) { dur = duration.toMinutes(); if (totalHits > 1000L) { dur = duration.toMillis() / 1000L; rate.setFrequency("Second"); } else { rate.setFrequency("Minute"); } } else { rate.setFrequency("Hourly"); } rate.setValue((int) dur); } } } catch (Exception e) { LOGGER.warn("Could not set record rate: {}", e.getMessage(), e); } }
From source file:com.intuit.wasabi.repository.cassandra.impl.CassandraAssignmentsRepository.java
List<Date> getUserAssignmentPartitions(Date fromTime, Date toTime) { final LocalDateTime startTime = LocalDateTime.ofInstant(fromTime.toInstant(), ZoneId.systemDefault()) .withMinute(0).withSecond(0).withNano(0); final LocalDateTime endTime = LocalDateTime.ofInstant(toTime.toInstant(), ZoneId.systemDefault()) .withMinute(0).withSecond(0).withNano(0); final long hours = Duration.between(startTime, endTime).toHours(); return LongStream.rangeClosed(0, hours).mapToObj(startTime::plusHours) .map(t -> Date.from(t.atZone(ZoneId.systemDefault()).toInstant())).collect(Collectors.toList()); }
From source file:com.vmware.vchs.base.DbaasApi.java
protected int loadDataBySize(MsSqlDataLoader msSqlDataLoader, String dbName, String tableName, long totalSizeInMB) throws Exception { msSqlDataLoader.useDatabase(dbName); msSqlDataLoader.createTable(tableName); int i = 1;//from ww w . ja v a 2 s . c o m Instant totalStart = Instant.now(); while (msSqlDataLoader.getDBSize() * 8 / 1024 < totalSizeInMB) { Instant start = Instant.now(); msSqlDataLoader.insert(tableName, configuration.getTestFile()); Duration duration = Duration.between(start, Instant.now()); logger.info("Blob " + i + " took " + duration.getSeconds() + " seconds."); i++; } Duration totalDuration = Duration.between(totalStart, Instant.now()); logger.info("Totally took " + totalDuration.getSeconds() + " seconds."); return i; }
From source file:org.openhab.binding.modbus.internal.handler.ModbusDataThingHandler.java
private void updateStatusIfChanged(ThingStatus status, ThingStatusDetail statusDetail, @Nullable String description) { ThingStatusInfo newStatusInfo = new ThingStatusInfo(status, statusDetail, description); Duration durationSinceLastUpdate = Duration.between(lastStatusInfoUpdate, LocalDateTime.now()); boolean intervalElapsed = MIN_STATUS_INFO_UPDATE_INTERVAL.minus(durationSinceLastUpdate).isNegative(); if (statusInfo.getStatus() == ThingStatus.UNKNOWN || !statusInfo.equals(newStatusInfo) || intervalElapsed) { statusInfo = newStatusInfo;//from w w w .ja v a 2s.c o m lastStatusInfoUpdate = LocalDateTime.now(); updateStatus(newStatusInfo); } }
From source file:me.ryanhamshire.griefprevention.command.CommandHelper.java
public static void displayClaimBankInfo(CommandSource src, GPClaim claim, boolean checkTown, boolean returnToClaimInfo) { final EconomyService economyService = GriefPreventionPlugin.instance.economyService.orElse(null); if (economyService == null) { GriefPreventionPlugin.sendMessage(src, GriefPreventionPlugin.instance.messageData.economyNotInstalled.toText()); return;//from w ww . j av a 2s. c o m } if (checkTown && !claim.isInTown()) { GriefPreventionPlugin.sendMessage(src, GriefPreventionPlugin.instance.messageData.townNotIn.toText()); return; } if (!checkTown && (claim.isSubdivision() || claim.isAdminClaim())) { return; } final GPClaim town = claim.getTownClaim(); Account bankAccount = checkTown ? town.getEconomyAccount().orElse(null) : claim.getEconomyAccount().orElse(null); if (bankAccount == null) { GriefPreventionPlugin.sendMessage(src, GriefPreventionPlugin.instance.messageData.economyVirtualNotSupported.toText()); return; } final GPPlayerData playerData = GriefPreventionPlugin.instance.dataStore.getPlayerData(claim.getWorld(), claim.getOwnerUniqueId()); final double claimBalance = bankAccount.getBalance(economyService.getDefaultCurrency()).doubleValue(); double taxOwed = -1; final double playerTaxRate = GPOptionHandler.getClaimOptionDouble(playerData.getPlayerSubject(), claim, GPOptions.Type.TAX_RATE, playerData); if (checkTown) { if (!town.getOwnerUniqueId().equals(playerData.playerID)) { for (Claim playerClaim : playerData.getInternalClaims()) { GPClaim playerTown = (GPClaim) playerClaim.getTown().orElse(null); if (!playerClaim.isTown() && playerTown != null && playerTown.getUniqueId().equals(claim.getUniqueId())) { taxOwed += (playerTown.getClaimBlocks() / 256) * playerTaxRate; } } } else { taxOwed = town.getClaimBlocks() * playerTaxRate; } } else { taxOwed = claim.getClaimBlocks() * playerTaxRate; } final GriefPreventionConfig<?> activeConfig = GriefPreventionPlugin .getActiveConfig(claim.getWorld().getProperties()); final ZonedDateTime withdrawDate = TaskUtils .getNextTargetZoneDate(activeConfig.getConfig().claim.taxApplyHour, 0, 0); Duration duration = Duration.between(Instant.now().truncatedTo(ChronoUnit.SECONDS), withdrawDate.toInstant()); final long s = duration.getSeconds(); final String timeLeft = String.format("%d:%02d:%02d", s / 3600, (s % 3600) / 60, (s % 60)); final Text message = GriefPreventionPlugin.instance.messageData.claimBankInfo .apply(ImmutableMap.of("balance", claimBalance, "amount", taxOwed, "time_remaining", timeLeft, "tax_balance", claim.getData().getEconomyData().getTaxBalance())) .build(); Text transactions = Text.builder().append(Text.of(TextStyles.ITALIC, TextColors.AQUA, "Bank Transactions")) .onClick(TextActions .executeCallback(createBankTransactionsConsumer(src, claim, checkTown, returnToClaimInfo))) .onHover(TextActions.showText(Text.of("Click here to view bank transactions"))).build(); List<Text> textList = new ArrayList<>(); if (returnToClaimInfo) { textList.add(Text.builder() .append(Text.of(TextColors.WHITE, "\n[", TextColors.AQUA, "Return to claim info", TextColors.WHITE, "]\n")) .onClick(TextActions.executeCallback(CommandHelper.createCommandConsumer(src, "claiminfo", ""))) .build()); } textList.add(message); textList.add(transactions); PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get(); PaginationList.Builder paginationBuilder = paginationService.builder() .title(Text.of(TextColors.AQUA, "Bank Info")).padding(Text.of(TextStyles.STRIKETHROUGH, "-")) .contents(textList); paginationBuilder.sendTo(src); }
From source file:me.ryanhamshire.griefprevention.command.CommandHelper.java
public static Consumer<CommandSource> createBankTransactionsConsumer(CommandSource src, GPClaim claim, boolean checkTown, boolean returnToClaimInfo) { return settings -> { final String name = "Bank Transactions"; List<String> bankTransactions = new ArrayList<>( claim.getData().getEconomyData().getBankTransactionLog()); Collections.reverse(bankTransactions); List<Text> textList = new ArrayList<>(); textList.add(//from w w w . ja v a2 s.co m Text.builder().append(Text.of(TextColors.WHITE, "\n[", TextColors.AQUA, "Return to bank info", TextColors.WHITE, "]\n")).onClick(TextActions.executeCallback(consumer -> { displayClaimBankInfo(src, claim, checkTown, returnToClaimInfo); })).build()); Gson gson = new Gson(); for (String transaction : bankTransactions) { GPBankTransaction bankTransaction = gson.fromJson(transaction, GPBankTransaction.class); final Duration duration = Duration.between(bankTransaction.timestamp, Instant.now().truncatedTo(ChronoUnit.SECONDS)); final long s = duration.getSeconds(); final User user = GriefPreventionPlugin.getOrCreateUser(bankTransaction.source); final String timeLeft = String.format("%dh %02dm %02ds", s / 3600, (s % 3600) / 60, (s % 60)) + " ago"; textList.add(Text.of(getTransactionColor(bankTransaction.type), bankTransaction.type.name(), TextColors.BLUE, " | ", TextColors.WHITE, bankTransaction.amount, TextColors.BLUE, " | ", TextColors.GRAY, timeLeft, user == null ? "" : Text.of(TextColors.BLUE, " | ", TextColors.LIGHT_PURPLE, user.getName()))); } textList.add(Text.builder() .append(Text.of(TextColors.WHITE, "\n[", TextColors.AQUA, "Return to bank info", TextColors.WHITE, "]\n")) .onClick(TextActions.executeCallback(CommandHelper.createCommandConsumer(src, "claimbank", ""))) .build()); PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get(); PaginationList.Builder paginationBuilder = paginationService.builder() .title(Text.of(TextColors.AQUA, name)).padding(Text.of(TextStyles.STRIKETHROUGH, "-")) .contents(textList); paginationBuilder.sendTo(src); }; }