public static String formatDuration(long duration) { // Using Joda Time DateTime now = new DateTime(); // Now DateTime plus = now.plus(new Duration(duration * 1000)); // Define and calculate the interval of time Interval interval = new Interval(now.getMillis(), plus.getMillis()); Period period = interval.toPeriod(PeriodType.time()); // Define the period formatter for pretty printing String ampersand = " & "; PeriodFormatter pf = new PeriodFormatterBuilder().appendHours().appendSuffix(ds("hour"), ds("hours")) .appendSeparator(" ", ampersand).appendMinutes().appendSuffix(ds("minute"), ds("minutes")) .appendSeparator(ampersand).appendSeconds().appendSuffix(ds("second"), ds("seconds")).toFormatter(); return pf.print(period).trim(); }
private TrainStop parseLiveboardStop(Station stop, JSONObject item) throws JSONException { Station destination = stationProvider.getStationById(item.getJSONObject("stationinfo").getString("id")); OccupancyLevel occupancyLevel = OccupancyLevel.UNKNOWN; if (item.has("occupancy")) { occupancyLevel = OccupancyLevel.valueOf(item.getJSONObject("occupancy").getString("name").toUpperCase()); } return new TrainStop( stop, destination, new TrainStub(item.getString("vehicle"), destination, item.getJSONObject("vehicleinfo").getString("@id")), item.getString("platform"), item.getJSONObject("platforminfo").getInt("normal") == 1, timestamp2date(item.getString("time")), new Duration(item.getInt("delay") * 1000), item.getInt("canceled") != 0, (item.has("left")) && (item.getInt("left") == 1), item.getString("departureConnection"), occupancyLevel ); }
/** * * @param date1 first event date * @param date2 second event date * @param unit time unit * @return duration duration (default millisecond) */ private long calculateDuration(DateTime date1, DateTime date2, TimeUnit unit){ if (unit == TimeUnit.SECONDS) { return Math.abs(new Duration(date1, date2).getStandardSeconds()); } else if (unit == TimeUnit.MINUTES) { return Math.abs(new Duration(date1, date2).getStandardMinutes()); } else if (unit == TimeUnit.HOURS) { return Math.abs(new Duration(date1, date2).getStandardHours()); } else if (unit == TimeUnit.DAYS) { return Math.abs(new Duration(date1, date2).getStandardDays()); } return 0; }
@Before public void setUp() throws ComponentInitializationException { // Note: the private key and the encrypting credential need to be from the same keypair PrivateKey privateKey = new PrivateKeyStoreFactory().create(TestEntityIds.TEST_RP).getEncryptionPrivateKeys().get(0); encryptionCredentialFactory = new TestCredentialFactory(TEST_RP_PUBLIC_ENCRYPTION_CERT, TEST_RP_PRIVATE_ENCRYPTION_KEY); testRpSigningCredential = new TestCredentialFactory(TEST_RP_PUBLIC_SIGNING_CERT, TEST_RP_PRIVATE_SIGNING_KEY).getSigningCredential(); hubMetadataResolver = mock(MetadataResolver.class); ResponseFactory responseFactory = new ResponseFactory(privateKey, privateKey); DateTimeComparator dateTimeComparator = new DateTimeComparator(Duration.standardSeconds(5)); TimeRestrictionValidator timeRestrictionValidator = new TimeRestrictionValidator(dateTimeComparator); SamlAssertionsSignatureValidator samlAssertionsSignatureValidator = mock(SamlAssertionsSignatureValidator.class); InstantValidator instantValidator = new InstantValidator(dateTimeComparator); SubjectValidator subjectValidator = new SubjectValidator(timeRestrictionValidator); ConditionsValidator conditionsValidator = new ConditionsValidator(timeRestrictionValidator, new AudienceRestrictionValidator()); AssertionValidator assertionValidator = new AssertionValidator(instantValidator, subjectValidator, conditionsValidator); AssertionTranslator assertionTranslator = new AssertionTranslator(samlAssertionsSignatureValidator, assertionValidator); responseService = responseFactory.createResponseService( hubMetadataResolver, assertionTranslator, dateTimeComparator ); }
public Transfer(Station station, TrainStub arrivingTrain, TrainStub departingTrain, String arrivalPlatform, boolean arrivalNormal, boolean arrived, boolean departureNormal, boolean left, String departurePlatform, Duration arrivalDelay, boolean arrivalCanceled, Duration departureDelay, boolean departureCanceled, DateTime arrivalTime, DateTime departureTime, String departureConnectionSemanticId, OccupancyLevel departureOccupancy) { this.station = station; this.arrivingTrain = arrivingTrain; this.departingTrain = departingTrain; this.arrived = arrived; this.left = left; this.arrivalTime = arrivalTime; this.departureTime = departureTime; this.departurePlatform = departurePlatform; this.arrivalPlatform = arrivalPlatform; this.arrivalDelay = arrivalDelay; this.departureDelay = departureDelay; this.arrivalCanceled = arrivalCanceled; this.departureCanceled = departureCanceled; this.isDeparturePlatformNormal = departureNormal; this.isArrivalPlatformNormal = arrivalNormal; this.departureConnectionSemanticId = departureConnectionSemanticId; this.departureOccupancy = departureOccupancy; }
@Before public void setUp() throws Exception { validator = new EidasAttributeQueryValidator( verifyMetadataResolver, countryMetadataResolver, verifyCertificateValidator, countryCertificateValidator, certificateExtractor, x509CertificateFactory, new DateTimeComparator(Duration.ZERO), assertionDecrypter, HUB_CONNECTOR_ENTITY_ID); when(verifyMetadataResolver.resolveSingle(any(CriteriaSet.class))).thenReturn(entityDescriptor); when(countryMetadataResolver.resolveSingle(any(CriteriaSet.class))).thenReturn((entityDescriptor)); when(certificateExtractor.extractHubSigningCertificates(entityDescriptor)) .thenReturn(Arrays.asList(new Certificate(HUB_ENTITY_ID, TestCertificateStrings.HUB_TEST_PUBLIC_SIGNING_CERT, Certificate.KeyUse.Signing))); when(certificateExtractor.extractIdpSigningCertificates(entityDescriptor)) .thenReturn(Arrays.asList(new Certificate(TEST_ENTITY_ID, TestCertificateStrings.TEST_PUBLIC_CERT, Certificate.KeyUse.Signing))); }
public CertificateExpiryStatus getExpiryStatus(Duration warningPeriod) { try { Date notAfter = getNotAfter(); LocalDateTime now = LocalDateTime.now(); Date notBefore = getNotBefore(); if (now.toDate().after(notAfter) || now.toDate().before(notBefore)) { return CertificateExpiryStatus.CRITICAL; } if (now.plus(warningPeriod).toDate().after(notAfter)) { return CertificateExpiryStatus.WARNING; } return CertificateExpiryStatus.OK; } catch (CertificateException e) { return CertificateExpiryStatus.CRITICAL; } }
/** Run a batch or streaming pipeline. */ public static void main(String[] args) throws Exception { Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); Pipeline pipeline = Pipeline.create(options); TableReference tableRef = new TableReference(); tableRef.setDatasetId(options.as(Options.class).getOutputDataset()); tableRef.setProjectId(options.as(GcpOptions.class).getProject()); tableRef.setTableId(options.getOutputTableName()); // Read events from either a CSV file or PubSub stream. pipeline .apply(new ReadGameEvents(options)) .apply("WindowedTeamScore", new Exercise2.WindowedTeamScore(Duration.standardMinutes(60))) // Write the results to BigQuery. .apply(ParDo.named("FormatTeamScoreSums").of(new Exercise2.FormatTeamScoreSumsFn())) .apply( BigQueryIO.Write.to(tableRef) .withSchema(Exercise2.FormatTeamScoreSumsFn.getSchema()) .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_APPEND)); pipeline.run(); }
Route(Station departureStation, Station arrivalStation, DateTime departureTime, Duration departureDelay, String departurePlatform, boolean isDeparturePlatformNormal, DateTime arrivalTime, Duration arrivalDelay, String arrivalPlatform, boolean isArrivalDeparturePlatformNormal, TrainStub[] trains, Transfer[] transfers, Message[] alerts, Message[][] trainalerts, Message[] remarks) { this.departureStation = departureStation; this.arrivalStation = arrivalStation; this.departureTime = departureTime; this.departureDelay = departureDelay; this.isDeparturePlatformNormal = isDeparturePlatformNormal; this.arrivalTime = arrivalTime; this.arrivalDelay = arrivalDelay; this.departurePlatform = departurePlatform; this.arrivalPlatform = arrivalPlatform; this.isArrivalDeparturePlatformNormal = isArrivalDeparturePlatformNormal; this.trains = trains; this.transfers = transfers; this.alerts = alerts; this.trainalerts = trainalerts; this.remarks = remarks; }
private TrainStop parseTrainStop(Station destination, TrainStub t, JSONObject item) throws JSONException { Station stop = stationProvider.getStationById(item.getJSONObject("stationinfo").getString("id")); OccupancyLevel occupancyLevel = OccupancyLevel.UNKNOWN; if (item.has("occupancy")) { occupancyLevel = OccupancyLevel.valueOf(item.getJSONObject("occupancy").getString("name").toUpperCase()); } return new TrainStop( stop, destination, t, item.getString("platform"), item.getJSONObject("platforminfo").getInt("normal") == 1, timestamp2date(item.getString("scheduledDepartureTime")), timestamp2date(item.getString("scheduledArrivalTime")), new Duration(item.getInt("departureDelay") * 1000), new Duration(item.getInt("arrivalDelay") * 1000), item.getInt("departureCanceled") != 0, item.getInt("arrivalCanceled") != 0, item.getInt("left") == 1, item.getString("departureConnection"), occupancyLevel ); }
/** * Format a duration (Quantity of time) to human readable string * * @param duration The period to format * @param targetUnit The target unit * @return A string formatted as [amount] [i18n scalar descriptor] */ public String timeQuantity(Duration duration, TimeUnit targetUnit) { switch (targetUnit) { case DAYS: long days = duration.getStandardDays(); return days + " " + i18n.getIfElse(MathUtils.isPlural(days), TIMEUNIT_DAYS, TIMEUNIT_DAY); case HOURS: long hours = duration.getStandardHours(); return hours + " " + i18n.getIfElse(MathUtils.isPlural(hours), TIMEUNIT_HOURS, TIMEUNIT_HOUR); case MINUTES: long minutes = duration.getStandardMinutes(); return minutes + " " + i18n.getIfElse(MathUtils.isPlural(minutes), TIMEUNIT_MINUTES, TIMEUNIT_MINUTE); case SECONDS: long seconds = duration.getStandardSeconds(); return seconds + " " + i18n.getIfElse(MathUtils.isPlural(seconds), TIMEUNIT_SECONDS, TIMEUNIT_SECOND); default: throw new UnsupportedOperationException("Quantifying " + targetUnit.toString() + " is not supported"); } }
/** * The sub command for setting payout intervals * Usage: !pointssettings interval [online|offline] [minutes (5 at minimum)] */ @SubCommandRoute(parentCommand = "pointssettings", command = "interval") public boolean pointsSettingsCommandInterval(User user, Arguments arguments) { StreamState when = EnumUtils.toEnum(arguments.get(0), StreamState.class); Integer intervalMinutes = NumberConverter.asNumber(arguments.getSafe(1)).toInteger(); if (when == null || intervalMinutes == null || intervalMinutes < 5) { chat.whisper(user, i18n.get("ChatCommand.pointsSettingsCommand.interval.usage")); return false; } Duration duration = new Duration(intervalMinutes, 60000); if (StreamState.ONLINE.equals(when)) { settings.setOnlinePayoutInterval(duration.getMillis()); } else { settings.setOfflinePayoutInterval(duration.getMillis()); } settingsService.save(settings); chat.whisper(user, i18n.get("ChatCommand.pointsSettingsCommand.interval.set") .add("streamstate", i18n.getStreamState(when)) .add("interval", timeFormatter.timeQuantity(duration.getMillis()))); return true; }
@Before public void setUp() throws Exception { PrivateKey privateKey = new PrivateKeyStoreFactory().create(TestEntityIds.TEST_RP).getEncryptionPrivateKeys().get(0); ResponseFactory responseFactory = new ResponseFactory(privateKey, privateKey); EntityDescriptor entityDescriptor = anEntityDescriptor() .withIdpSsoDescriptor(anIdpSsoDescriptor() .addKeyDescriptor(aKeyDescriptor() .withX509ForSigning(TEST_RP_MS_PUBLIC_SIGNING_CERT) .build()) .build()) .build(); MetadataResolver msaMetadataResolver = mock(MetadataResolver.class); DateTimeComparator dateTimeComparator = new DateTimeComparator(Duration.standardSeconds(5)); when(msaMetadataResolver.resolve(any())).thenReturn(ImmutableList.of(entityDescriptor)); translator = responseFactory.createAssertionTranslator(msaMetadataResolver, dateTimeComparator); }
/** * Returns a copy of this {@link FluentBackoff} that instead uses the specified initial backoff * duration. * * <p>Does not modify this object. * * @see FluentBackoff */ public FluentBackoff withInitialBackoff(Duration initialBackoff) { checkArgument( initialBackoff.isLongerThan(Duration.ZERO), "initialBackoff %s must be at least 1 millisecond", initialBackoff); return new FluentBackoff( exponent, initialBackoff, maxBackoff, maxCumulativeBackoff, maxRetries); }
@Provides @Singleton public Optional<EidasMatchingService> getEidasMatchingService( @Named(COUNTRY_METADATA_RESOLVER) Optional<MetadataResolver> countryMetadataResolver, @Named(VERIFY_METADATA_RESOLVER) MetadataResolver verifyMetadataResolver, @Named("VerifyCertificateValidator") CertificateValidator verifyCertificateValidator, @Named("CountryCertificateValidator") Optional<CertificateValidator> countryCertificateValidator, X509CertificateFactory x509CertificateFactory, MatchingServiceAdapterConfiguration configuration, AssertionDecrypter assertionDecrypter, UserIdHashFactory userIdHashFactory, MatchingServiceProxy matchingServiceClient, MatchingServiceResponseDtoToOutboundResponseFromMatchingServiceMapper responseMapper) { return countryMetadataResolver.map(countryMetadataResolverValue -> new EidasMatchingService( new EidasAttributeQueryValidator( verifyMetadataResolver, countryMetadataResolverValue, verifyCertificateValidator, countryCertificateValidator.get(), new CertificateExtractor(), x509CertificateFactory, new DateTimeComparator(Duration.ZERO), assertionDecrypter, configuration.getCountry().getHubConnectorEntityId() ), new EidasMatchingRequestToMSRequestTransformer(userIdHashFactory), matchingServiceClient, responseMapper)); }
@Override public long nextBackOffMillis() { // Maximum number of retries reached. if (currentRetry >= backoffConfig.maxRetries) { return BackOff.STOP; } // Maximum cumulative backoff reached. if (currentCumulativeBackoff.compareTo(backoffConfig.maxCumulativeBackoff) >= 0) { return BackOff.STOP; } double currentIntervalMillis = Math.min( backoffConfig.initialBackoff.getMillis() * Math.pow(backoffConfig.exponent, currentRetry), backoffConfig.maxBackoff.getMillis()); double randomOffset = (Math.random() * 2 - 1) * DEFAULT_RANDOMIZATION_FACTOR * currentIntervalMillis; long nextBackoffMillis = Math.round(currentIntervalMillis + randomOffset); // Cap to limit on cumulative backoff Duration remainingCumulative = backoffConfig.maxCumulativeBackoff.minus(currentCumulativeBackoff); nextBackoffMillis = Math.min(nextBackoffMillis, remainingCumulative.getMillis()); // Update state and return backoff. currentCumulativeBackoff = currentCumulativeBackoff.plus(nextBackoffMillis); currentRetry += 1; return nextBackoffMillis; }
public UserInviteLink(String code, AppUser issuer, String email, Roles roles) { this.hashedCode = hash(code); this.email = email; this.roles = roles == null ? Collections.<String>emptySet() : roles.getRoles(); this.issuedBy = Ref.create(issuer); this.redeemed = false; this.created = DateTime.now(); this.expires = created.plus(Duration.standardDays(2)); }
/** * Filters a message to make sure that it was not sent too soon before the last message. * * @param message The message that should be instead sent. This may be a modified message, the unchanged message, or * <code>null</code>, if the message is to be cancelled. * @param player The player that sent the message. * @param type The {@link tc.oc.chatmoderator.zones.ZoneType} relating to where the message originated from. * * @return The state of the message after running this filter. */ @Override public @Nullable FixedMessage filter(FixedMessage message, Player player, ZoneType type, Event event) { if (player.hasPermission(this.getExemptPermission())) { return message; } PlayerViolationManager violationSet = this.getPlayerManager().getViolationSet(player); if (violationSet.getLastMessage() == null) { return message; // Let the overarching filter handle the setting of the new message } Instant now = Instant.now(); Instant lastMessage = violationSet.getLastMessageTime(); Duration difference = new Duration(lastMessage, now); boolean shouldAddViolation = false; if (lastMessage.withDurationAdded(this.delay, 1).isAfter(now)) { shouldAddViolation = true; } else if (lastMessage.withDurationAdded(this.sameMessageDelay, 1).isAfter(now) && this.isSameMessage(violationSet.getLastMessage(), message)) { shouldAddViolation = true; } if (shouldAddViolation) { DuplicateMessageViolation violation = new DuplicateMessageViolation(message.getTimeSent(), player, message, difference, type, event); violation.setForceNoSend(true); violationSet.addViolation(violation); } return message; }
@Test public void testHandleRequestFromTransaction_logsToEventSink() throws Exception { final SamlResponseWithAuthnRequestInformationDto samlResponseWithAuthnRequestInformationDto = SamlResponseWithAuthnRequestInformationDtoBuilder.aSamlResponseWithAuthnRequestInformationDto().build(); final String ipAddress = "ipaddress"; final URI assertionConsumerServiceUri = URI.create("blah"); final Optional<String> relayState = fromNullable("relaystate"); when(policyConfiguration.getSessionLength()).thenReturn(Duration.standardHours(1)); when(transactionsConfigProxy.getLevelsOfAssurance(samlResponseWithAuthnRequestInformationDto.getIssuer())).thenReturn(asList(LevelOfAssurance.LEVEL_1, LevelOfAssurance.LEVEL_1)); authnRequestFromTransactionHandler.handleRequestFromTransaction(samlResponseWithAuthnRequestInformationDto, relayState, ipAddress, assertionConsumerServiceUri, false); verify(eventSinkHubEventLogger, times(1)).logSessionStartedEvent(Matchers.<SamlResponseWithAuthnRequestInformationDto>any(), anyString(), Matchers.<DateTime>any(), Matchers.<SessionId>any(), Matchers.<LevelOfAssurance>any(), Matchers.<LevelOfAssurance>any()); }
@Test public void shouldMoveFromAwaitingC3StateToCycle3DataSentStateWhenCycle3DataIsReceived() throws Exception { final String requestId = "requestId"; final SessionId sessionId = SessionId.createNewSessionId(); Cycle3MatchRequestSentState state = aCycle3MatchRequestSentState().withSessionId(sessionId).withRequestId(requestId).build(); Cycle3MatchRequestSentStateController controller = new Cycle3MatchRequestSentStateController(state, eventSinkHubEventLogger, stateTransitionAction, policyConfiguration, null, null, transactionsConfigProxy, matchingServiceConfigProxy, assertionRestrictionFactory, attributeQueryService); when(policyConfiguration.getMatchingServiceResponseWaitPeriod()).thenReturn(Duration.standardMinutes(5)); ResponseProcessingDetails responseProcessingDetails = controller.getResponseProcessingDetails(); assertThat(responseProcessingDetails.getResponseProcessingStatus()).isEqualTo(ResponseProcessingStatus.WAIT); assertThat(responseProcessingDetails.getSessionId()).isEqualTo(sessionId); }
@Test public void shouldReturnErrorResponseWhenAskedAndInCycle3MatchRequestSentState() throws Exception { final String requestId = "requestId"; final SessionId sessionId = SessionId.createNewSessionId(); Cycle3MatchRequestSentState state = aCycle3MatchRequestSentState().withSessionId(sessionId).withRequestId(requestId).build(); Cycle3MatchRequestSentStateController controller = new Cycle3MatchRequestSentStateController(state, eventSinkHubEventLogger, stateTransitionAction, policyConfiguration, null, responseFromHubFactory, transactionsConfigProxy, matchingServiceConfigProxy, assertionRestrictionFactory, attributeQueryService); when(policyConfiguration.getMatchingServiceResponseWaitPeriod()).thenReturn(Duration.standardMinutes(5)); final ResponseFromHub responseFromHub = controller.getErrorResponse(); assertThat(responseFromHub.getStatus()).isEqualTo(TransactionIdaStatus.NoAuthenticationContext); }
@Test public void shouldMoveFromAwaitingC3StateToCycle3DataSentStateWhenCycle3DataIsReceived() throws Exception { final SessionId sessionId = SessionId.createNewSessionId(); AwaitingCycle3DataState state = anAwaitingCycle3DataState().withSessionId(sessionId).build(); AwaitingCycle3DataStateController controller = new AwaitingCycle3DataStateController(state, eventSinkHubEventLogger, stateTransitionAction, transactionsConfigProxy, responseFromHubFactory, policyConfiguration, assertionRestrictionsFactory, matchingServiceConfigProxy); when(policyConfiguration.getMatchingServiceResponseWaitPeriod()).thenReturn(Duration.standardMinutes(5)); ArgumentCaptor<Cycle3MatchRequestSentState> argumentCaptor = ArgumentCaptor.forClass(Cycle3MatchRequestSentState.class); when(matchingServiceConfigProxy.getMatchingService(state.getMatchingServiceEntityId())).thenReturn(aMatchingServiceConfigEntityDataDto().build()); controller.handleCycle3DataSubmitted("principalIpAsSeenByHub"); verify(stateTransitionAction, times(1)).transitionTo(argumentCaptor.capture()); final Cycle3MatchRequestSentState cycle3MatchRequestSentState = argumentCaptor.getValue(); assertThat(cycle3MatchRequestSentState.getEncryptedMatchingDatasetAssertion()).isEqualTo(state.getEncryptedMatchingDatasetAssertion()); }
@Test public void createAttributeQuery() { final Cycle3Dataset cycle3Dataset = Cycle3Dataset.createFromData("attribute", "attributeValue"); final MatchingServiceConfigEntityDataDto matchingServiceConfigEntityDataDto = aMatchingServiceConfigEntityDataDto() .withEntityId(state.getMatchingServiceEntityId()) .build(); when(matchingServiceConfigProxy.getMatchingService(state.getMatchingServiceEntityId())).thenReturn(matchingServiceConfigEntityDataDto); when(policyConfiguration.getMatchingServiceResponseWaitPeriod()).thenReturn(Duration.standardMinutes(60)); when(assertionRestrictionsFactory.getAssertionExpiry()).thenReturn(DateTime.now().plusHours(2)); final EidasAttributeQueryRequestDto expectedDto = new EidasAttributeQueryRequestDto( state.getRequestId(), state.getRequestIssuerEntityId(), state.getAssertionConsumerServiceUri(), assertionRestrictionsFactory.getAssertionExpiry(), state.getMatchingServiceEntityId(), matchingServiceConfigEntityDataDto.getUri(), DateTime.now().plus(policyConfiguration.getMatchingServiceResponseWaitPeriod()), matchingServiceConfigEntityDataDto.isOnboarding(), state.getLevelOfAssurance(), state.getPersistentId(), Optional.of(cycle3Dataset), Optional.absent(), state.getEncryptedIdentityAssertion() ); EidasAttributeQueryRequestDto actualDto = controller.createAttributeQuery(cycle3Dataset); assertThat(actualDto).isEqualTo(expectedDto); }
/** * Sleeps without explicitly throwing an InterruptedException * * @param duration Sleep time in milliseconds. * * @throws RuntimeException wrapping an InterruptedException if one gets thrown */ public static void pauseFor( final Duration duration ) { try { sleep( duration.getMillis() ); } catch ( InterruptedException e ) { logger.warn( "Wait interrupted:" + e.getMessage() ); Thread.currentThread().interrupt(); } }
/** * Sleeps for the specified duration, throwing an IosDeviceException and re-interrupts the thread * if an InterruptedException is thrown. */ private void sleep(Duration duration) throws IosDeviceException { try { Thread.sleep(duration.getMillis()); } catch (InterruptedException e) { throw propagateInterrupt(e); } }
@Override public WebElement getWrappedElement() { try { rootElement.getTagName(); return rootElement; } catch( StaleElementReferenceException e ) { e.printStackTrace(); Sleeper.pauseFor( Duration.millis( 2000 ) ); this.rootElement = sync.wait10().until( ExpectedConditions.presenceOfElementLocated( rootBy ) ); return rootElement; } }
public static String convertMillisecondToMinutesAndSecond(long milliseconds) { Duration duration = new Duration(milliseconds); Period period = duration.toPeriod(); PeriodFormatter minutesAndSeconds = new PeriodFormatterBuilder() .printZeroAlways() .appendMinutes() .appendSeparator(":") .appendSeconds() .toFormatter(); return minutesAndSeconds.print(period); }
protected TrainStop(Station station, Station destination, TrainStub train, String platform, boolean isPlatformNormal, DateTime departureTime, DateTime arrivalTime, Duration departureDelay, Duration arrivalDelay, boolean departureCanceled, boolean arrivalCanceled, boolean hasLeft, String semanticDepartureConnection, OccupancyLevel occupancyLevel) { this(station, destination, train, platform, isPlatformNormal, departureTime, departureDelay, departureCanceled, hasLeft, semanticDepartureConnection, occupancyLevel); this.arrivalTime = arrivalTime; this.arrivalDelay = arrivalDelay; this.arrivalCanceled = arrivalCanceled; }
/** Run a batch pipeline. */ public static void main(String[] args) throws Exception { Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); Pipeline pipeline = Pipeline.create(options); TableReference tableRef = new TableReference(); tableRef.setDatasetId(options.as(Options.class).getOutputDataset()); tableRef.setProjectId(options.as(GcpOptions.class).getProject()); tableRef.setTableId(options.getOutputTableName()); // Read events from a CSV file and parse them. pipeline .apply(TextIO.Read.from(options.getInput())) .apply(ParDo.named("ParseGameEvent").of(new ParseEventFn())) .apply( "AddEventTimestamps", WithTimestamps.of((GameEvent i) -> new Instant(i.getTimestamp()))) .apply("WindowedTeamScore", new WindowedTeamScore(Duration.standardMinutes(60))) // Write the results to BigQuery. .apply(ParDo.named("FormatTeamScoreSums").of(new FormatTeamScoreSumsFn())) .apply( BigQueryIO.Write.to(tableRef) .withSchema(FormatTeamScoreSumsFn.getSchema()) .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_APPEND)); pipeline.run(); }
@Test public void canHandle() throws Exception { assertTrue(converter.canHandle("2017-09-03", TypeToken.of(LocalTime.class))); assertTrue(converter.canHandle("2017-09-03", TypeToken.of(LocalDate.class))); assertTrue(converter.canHandle("2017-09-03", TypeToken.of(LocalDateTime.class))); assertFalse(converter.canHandle("2017-09-03", TypeToken.of(Duration.class))); assertFalse(converter.canHandle(new Date(), TypeToken.of(LocalDate.class))); }
public static String getDiffFormatted(Date from, Date to) { Duration duration = new Duration(to.getTime() - from.getTime()); // in // milliseconds PeriodFormatter formatter = new PeriodFormatterBuilder().printZeroNever()// .appendWeeks().appendSuffix("w").appendSeparator(" ")// .appendDays().appendSuffix("d").appendSeparator(" ")// .appendHours().appendSuffix("h").appendSeparator(" ")// .appendMinutes().appendSuffix("m").appendSeparator(" ")// .appendSeconds().appendSuffix("s")// .toFormatter(); String fullTimeAgo = formatter.print(duration.toPeriod(PeriodType.yearMonthDayTime())); return Arrays.stream(fullTimeAgo.split(" ")).limit(2).collect(Collectors.joining(" ")); }
@Test public void canHandle() throws Exception { assertTrue(converter.canHandle(new Date(), TypeToken.of(LocalTime.class))); assertTrue(converter.canHandle(new Date(), TypeToken.of(LocalDate.class))); assertTrue(converter.canHandle(new Date(), TypeToken.of(LocalDateTime.class))); assertFalse(converter.canHandle(new Date(), TypeToken.of(Duration.class))); assertFalse(converter.canHandle("2017-09-03", TypeToken.of(LocalDate.class))); }
@Override public EquellaAttachmentBean serialize(Attachment attachment) { CustomAttachment cattach = (CustomAttachment) attachment; YoutubeAttachmentBean ybean = new YoutubeAttachmentBean(); ybean.setVideoId((String) cattach.getData(YoutubeUtils.PROPERTY_ID)); ybean.setTitle((String) cattach.getData(YoutubeUtils.PROPERTY_TITLE)); ybean.setTags((String) cattach.getData(YoutubeUtils.PROPERTY_TAGS)); ybean.setThumbUrl((String) cattach.getData(YoutubeUtils.PROPERTY_THUMB_URL)); ybean.setViewUrl((String) cattach.getData(YoutubeUtils.PROPERTY_PLAY_URL)); ybean.setCustomParameters((String) cattach.getData(YoutubeUtils.PROPERTY_PARAMETERS)); final Long date = (Long) cattach.getData(YoutubeUtils.PROPERTY_DATE); if( date != null ) { ybean.setUploadedDate(new Date(date)); } ybean.setUploader((String) cattach.getData(YoutubeUtils.PROPERTY_AUTHOR)); final Object durationData = cattach.getData(YoutubeUtils.PROPERTY_DURATION); String duration = null; if( durationData instanceof String ) { duration = (String) durationData; } else if( durationData instanceof Long ) { long oldDuration = (long) durationData; duration = Duration.standardSeconds(oldDuration).toPeriod().toString(); } if( duration != null ) { ybean.setDuration(duration); } return ybean; }
public static String formatDuration(String duration) { Duration d = ISOPeriodFormat.standard().parsePeriod(duration).toStandardDuration(); long hours = d.getStandardHours(); Duration minusHours = d.minus(Duration.standardHours(hours)); long minutes = minusHours.getStandardMinutes(); long seconds = minusHours.minus(Duration.standardMinutes(minutes)).getStandardSeconds(); String format = hours > 0 ? "%3$d:%2$02d:%1$02d" : "%2$d:%1$02d"; return String.format(format, seconds, minutes, hours); }
/** * Creates a event in this calendar. * * @param summary the summary of event * @param from Startdate of event * @param to Enddate of event * @return a uuid of the created events. * @throws IOException If the underlying process was failed. */ public String createEvent(final String summary, final DateTime from, final DateTime to) throws IOException { List<String> subCommands = new ArrayList<>(); subCommands.add("calendar"); subCommands.add("add"); final Duration duration = new Interval(from, to).toDuration(); final StringBuilder eventTime = new StringBuilder(); eventTime.append(from.toString("yyyy-MM-dd'T'HH:mm")); eventTime.append("+"); eventTime.append(duration.getStandardMinutes()); eventTime.append("m"); subCommands.add(eventTime.toString()); subCommands.add(summary); final String rawOutput = execute(subCommands); final String uid; final Matcher matcher = eventUUID.matcher(rawOutput); if(matcher.find()) { uid = matcher.group(1); }else{ uid = "<unknown>"; } return uid; }
@Override public void restart() throws IosDeviceException { await(idevice.diagnostics("restart")); restarting = true; try { // Device should take at least 30 seconds to reboot. sleep(Duration.standardSeconds(30)); // Now check periodically for the device to become responsive again. retryResponsiveAfterReboot.call(); } finally { restarting = false; } }
@Override public CertificateCredentialImpl<T> withStartDate(DateTime startDate) { DateTime original = startDate(); inner().withStartDate(startDate); // Adjust end time withDuration(Duration.millis(endDate().getMillis() - original.getMillis())); return this; }
private RetryCallable( CheckedCallable<? extends V, ? extends X> task, int maxAttempts, Duration delay, boolean delayedFirstAttempt, ExceptionHandler<? super X> exceptionHandler) { this.task = checkNotNull(task); checkArgument(maxAttempts > 0); this.maxAttempts = maxAttempts; this.delay = checkNotNull(delay); this.delayedFirstAttempt = delayedFirstAttempt; this.exceptionHandler = checkNotNull(exceptionHandler); }