List of usage examples for java.time.temporal ChronoUnit SECONDS
ChronoUnit SECONDS
To view the source code for java.time.temporal ChronoUnit SECONDS.
Click Source Link
From source file:msi.gama.util.GamaDate.java
/** * returns the complete number of seconds since the starting_date of the model (equivalent to a duration) * //from w w w .jav a 2s . com * @param scope * the current scope from which the simulation can be obtained * @return the duration in seconds since this starting date */ public double floatValue(final IScope scope) { final SimulationAgent sim = scope.getSimulation(); if (sim == null) { return Dates.DATES_STARTING_DATE.getValue().until(this, ChronoUnit.SECONDS); } return sim.getStartingDate().until(this, ChronoUnit.SECONDS); }
From source file:com.github.aptd.simulation.elements.train.CTrain.java
@Override protected final synchronized boolean updatecontinuous(final Duration p_elapsed) { switch (m_state) { case DRIVING: m_positionontrack += p_elapsed.get(ChronoUnit.SECONDS) * DRIVING_SPEED; return true; default://from w ww . j a v a2 s . c o m // making checkstyle happy } return false; }
From source file:com.ikanow.aleph2.data_model.utils.TimeUtils.java
/** Returns a date from a human readable date - can be in the future or past * @param human_readable_date - the date expressed in words, eg "next wednesday".. Uses some simple regexes (1h,d, 1month etc), and Natty (try examples http://natty.joestelmach.com/try.jsp#) * @param base_date - for relative date, locks the date to this origin * @return the machine readable date, or an error *//*from w w w . j a v a 2s .co m*/ public static Validation<String, Date> getSchedule(final String human_readable_date, Optional<Date> base_date) { try { // just read the first - note can ignore all the error checking here, just fail out using the try/catch final Date adjusted_date = base_date.orElse(new Date()); CalendarSource.setBaseDate(adjusted_date); final Parser parser = new Parser(); final List<DateGroup> l = parser.parse(human_readable_date); final DateGroup d = l.get(0); if (!d.getText().matches("^.*[a-zA-Z]+.*$")) { // only matches numbers, not allowed - must have missed a prefix return Validation.fail(ErrorUtils.get(ErrorUtils.INVALID_DATETIME_FORMAT, human_readable_date)); } final List<Date> l2 = d.getDates(); return Validation.success(l2.get(0)); } catch (Exception e) { final Pattern numChronoPattern = Pattern.compile("^([\\d]+)(.*)"); final Matcher m = numChronoPattern.matcher(human_readable_date); return m.find() ? getTimePeriod(m.group(2)).map(c -> c.getDuration().get(ChronoUnit.SECONDS)) .map(l -> new Date(base_date.orElse(new Date()).getTime() + Long.parseLong(m.group(1)) * l * 1000L)) : getTimePeriod(human_readable_date).map(c -> c.getDuration().get(ChronoUnit.SECONDS)) .map(l -> new Date(base_date.orElse(new Date()).getTime() + l * 1000L)); } }
From source file:com.github.aptd.simulation.elements.passenger.CPassenger.java
@Override protected boolean updatecontinuous(final Duration p_elapsed) { switch (m_state) { case MOVING_THROUGH_STATION: m_distancewalked += p_elapsed.get(ChronoUnit.SECONDS) * m_speedatstation; return true; case ENTERING_TRAIN: case LEAVING_TRAIN: m_dooruse += p_elapsed.get(ChronoUnit.SECONDS); return true; default:// w ww.j av a 2 s.c o m return false; } }
From source file:dk.dbc.rawrepo.oai.OAIWorker.java
/** * Take an OAIIdentifier list and convert into a Record list, with the * content formattet as medataPrefix/*w ww . ja va 2s . co m*/ * * @param collection identifiers to fetch * @param metadataPrefix fetch to get content in * @return list of records */ private List<RecordType> fetchRecordContent(List<OAIIdentifier> collection, String metadataPrefix) { List<RecordFormatter.RecordWithContent> records = collection.stream() .map(id -> recordFormatter.fetch(id, metadataPrefix, allowedSets)).collect(Collectors.toList()); log.debug("futures = " + records); try { Instant timeout = Instant.now().plus(config.getFetchRecordsTimeout(), ChronoUnit.SECONDS); List<RecordType> recordsWithContent = records.stream().map(rec -> { try { long waitFor = Math.max(0, Instant.now().until(timeout, ChronoUnit.SECONDS)); log.debug("waitFor (sec) = " + waitFor); rec.complete(waitFor); RecordType record = rec.getOAIIdentifier().toRecord(); if (!rec.getOAIIdentifier().isDeleted()) { MetadataType metadata = OBJECT_FACTORY.createMetadataType(); String content = rec.getContent(); if (content == null) { log.error("Cannot get content for: " + rec.getOAIIdentifier().getIdentifier()); throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR, "Internal Error"); } Element element = stringToElement(content); fixXmlNamespacePrefix(element, metadataPrefix); metadata.setAny(element); record.setMetadata(metadata); } return record; } catch (InterruptedException | ExecutionException ex) { log.error("Exception: " + ex.getMessage()); log.debug("Exception: ", ex); throw new ServerErrorException(Response.Status.REQUEST_TIMEOUT, "Error retrieving record"); } catch (TimeoutException ex) { log.error("Exception: " + ex.getMessage()); log.debug("Exception: ", ex); throw new ServerErrorException(Response.Status.REQUEST_TIMEOUT, "Error waiting for record formatting"); } }).collect(Collectors.toList()); return recordsWithContent; } catch (Exception e) { records.stream().forEach(record -> { try { record.cancel(true); } catch (Exception ex) { log.debug("Error canceling request: " + ex.getMessage()); } }); throw e; } }
From source file:msi.gama.util.GamaDate.java
@Override public long getLong(final TemporalField field) { if (internal.isSupported(field)) { return internal.getLong(field); }/*ww w . j a va 2 s. c o m*/ if (field.equals(ChronoField.OFFSET_SECONDS)) { // If no offset or time zone is supplied, we assume it is the zone of the modeler return GamaDateType.DEFAULT_OFFSET_IN_SECONDS.getTotalSeconds(); } if (field.equals(ChronoField.INSTANT_SECONDS)) { return GamaDateType.EPOCH.until(internal, ChronoUnit.SECONDS); } return 0l; }
From source file:com.github.aptd.simulation.elements.train.CDoor.java
@Override protected boolean updatecontinuous(final Duration p_elapsed) { switch (m_state) { case OPENING: case OPENING_SHALL_CLOSE: m_openwidth += p_elapsed.get(ChronoUnit.SECONDS) * m_openingspeed; return true; case OPEN_FREE: case OPEN_CLOSEABLE: case OPEN_FREE_SHALL_CLOSE: m_freetime += p_elapsed.get(ChronoUnit.SECONDS); return true; case CLOSING: case CLOSING_LOCKED: m_openwidth -= p_elapsed.get(ChronoUnit.SECONDS) * m_closingspeed; return true; default:/*from w w w .j a va 2s .co m*/ // making checkstyle happy } return false; }
From source file:com.ikanow.aleph2.shared.crud.elasticsearch.services.TestElasticsearchCrudService.java
@Test public void test_CreateMultipleObjects_JSON_batch() throws InterruptedException, ExecutionException { final ElasticsearchCrudService<JsonNode> service = getTestService("testCreateMultipleObjects_json_batch", TestBean.class).getRawService(); @SuppressWarnings("unchecked") final ElasticsearchCrudService<JsonNode>.ElasticsearchBatchSubsystem batch_service = service .getUnderlyingPlatformDriver(ElasticsearchBatchSubsystem.class, Optional.empty()).get(); batch_service.setBatchProperties(Optional.empty(), Optional.empty(), Optional.of(Duration.of(2, ChronoUnit.SECONDS)), Optional.of(10)); // 1) Insertion without ids assertEquals(0, service.countObjects().get().intValue()); final List<JsonNode> l = IntStream.rangeClosed(1, 10).boxed().map( i -> BeanTemplateUtils.build(TestBean.class).with("test_string", "test_string" + i).done().get()) .map(o -> BeanTemplateUtils.toJson(o)).collect(Collectors.toList()); batch_service.storeObjects(l, false); //Sleep for 5s to let it flush try {//from w ww . j a v a 2 s . co m Thread.sleep(5000L); } catch (Exception e) { } assertEquals(10, service.countObjects().get().intValue()); // Check all the expected objects exist: IntStream.rangeClosed(1, 10).boxed().map(i -> "test_string" + i).forEach(Lambdas.wrap_consumer_u(field -> { Optional<JsonNode> obj = service.getObjectBySpec(CrudUtils.allOf().when("test_string", field)).get(); assertTrue("NEeds to find: " + field, obj.isPresent()); })); // 2) Insertion with ids service.deleteDatastore().get(); batch_service.setBatchProperties(Optional.of(30), Optional.empty(), Optional.empty(), Optional.of(0)); final List<JsonNode> l2 = IntStream.rangeClosed(51, 100).boxed() .map(i -> BeanTemplateUtils.build(TestBean.class).with("_id", "id" + i) .with("test_string", "test_string" + i).done().get()) .map(o -> BeanTemplateUtils.toJson(o)).collect(Collectors.toList()); batch_service.storeObjects(l2, false); try { Thread.sleep(1500L); } catch (Exception e) { } assertEquals(30, service.countObjects().get().intValue()); //Sleep for total 5s to let it flush try { Thread.sleep(3500L); } catch (Exception e) { } assertEquals(50, service.countObjects().get().intValue()); IntStream.rangeClosed(51, 100).boxed().map(i -> "test_string" + i) .forEach(Lambdas.wrap_consumer_u(field -> { Optional<JsonNode> obj = service.getObjectBySpec(CrudUtils.allOf().when("test_string", field)) .get(); assertTrue("NEeds to find: " + field, obj.isPresent()); })); // 4) Insertion with dups - fail on insert dups batch_service.setBatchProperties(Optional.empty(), Optional.of(10000L), Optional.empty(), Optional.of(5)); final List<JsonNode> l4 = IntStream.rangeClosed(21, 120).boxed() .map(i -> BeanTemplateUtils.build(TestBean.class).with("_id", "id" + i) .with("test_string", "test_string2" + i).done().get()) .map(o -> BeanTemplateUtils.toJson(o)).collect(Collectors.toList()); batch_service.storeObjects(l4, false); //Sleep for total 5s to let it flush try { Thread.sleep(5000L); } catch (Exception e) { } assertEquals(100, service.countObjects().get().intValue()); // 5) Insertion with dups - overwrite batch_service.setBatchProperties(Optional.of(20), Optional.empty(), Optional.of(Duration.of(4, ChronoUnit.SECONDS)), Optional.empty()); try { Thread.sleep(100L); } catch (Exception e) { } final List<JsonNode> l5_1 = IntStream.rangeClosed(21, 59).boxed() .map(i -> BeanTemplateUtils.build(TestBean.class).with("_id", "id" + i) .with("test_string", "test_string5" + i).done().get()) .map(o -> BeanTemplateUtils.toJson(o)).collect(Collectors.toList()); final List<JsonNode> l5_2 = IntStream.rangeClosed(60, 120).boxed() .map(i -> BeanTemplateUtils.build(TestBean.class).with("_id", "id" + i) .with("test_string", "test_string5" + i).done().get()) .map(o -> BeanTemplateUtils.toJson(o)).collect(Collectors.toList()); batch_service.storeObjects(l5_1, true); // (wait for it to refresh) try { Thread.sleep(1100L); } catch (Exception e) { } assertEquals(100, service.countObjects().get().intValue()); // first batch // Check only some objects are overwritten IntStream.rangeClosed(21, 40).boxed().map(i -> "test_string5" + i) .forEach(Lambdas.wrap_consumer_u(field -> { Optional<JsonNode> obj = service.getObjectBySpec(CrudUtils.allOf().when("test_string", field)) .get(); assertTrue("NEeds to find: " + field, obj.isPresent()); })); IntStream.rangeClosed(41, 50).boxed().map(i -> "test_string2" + i) .forEach(Lambdas.wrap_consumer_u(field -> { Optional<JsonNode> obj = service.getObjectBySpec(CrudUtils.allOf().when("test_string", field)) .get(); assertTrue("NEeds to find: " + field, obj.isPresent()); })); IntStream.rangeClosed(51, 100).boxed().map(i -> "test_string" + i) .forEach(Lambdas.wrap_consumer_u(field -> { Optional<JsonNode> obj = service.getObjectBySpec(CrudUtils.allOf().when("test_string", field)) .get(); assertTrue("NEeds to find: " + field, obj.isPresent()); })); batch_service.storeObjects(l5_2, true); //Sleep for total 1s to let it flush try { Thread.sleep(5000L); } catch (Exception e) { } assertEquals(100, service.countObjects().get().intValue()); // Check all objects are overwritten IntStream.rangeClosed(21, 120).boxed().map(i -> "test_string5" + i) .forEach(Lambdas.wrap_consumer_u(field -> { Optional<JsonNode> obj = service.getObjectBySpec(CrudUtils.allOf().when("test_string", field)) .get(); assertTrue("NEeds to find: " + field, obj.isPresent()); })); }
From source file:at.ac.ait.ariadne.routeformat.example.IntermodalRouteExample.java
private IntermediateStop createIntermediateStopNeueDonau() { ZonedDateTime arrivalTime = ZonedDateTime.parse("2016-01-01T15:22:30+01:00"); ZonedDateTime departureTime = arrivalTime.plus(60, ChronoUnit.SECONDS); return IntermediateStop.builder().withStop(neueDonauSubwayStop).withPlannedArrivalTime(arrivalTime) .withPlannedDepartureTime(departureTime).withEstimatedArrivalTime(arrivalTime) .withEstimatedDepartureTime(departureTime).build(); }
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 a v a2s.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); }