static CassieqCredentials key( final AccountName accountName, final AccountKey accountKey, final Clock requestClock) { return request -> { final Instant now = requestClock.now(); final SignedRequestSignatureGenerator requestParameters = new SignedRequestSignatureGenerator( accountName, request.method(), request.url().getPath(), now.toDateTime(DateTimeZone.UTC)); final String signature = requestParameters.computeSignature(MacProviders.HmacSha256(accountKey)); final String requestTime = SignatureGenerator.formatDateTime(now); return request .newBuilder() .header("Authorization", "Signed " + signature) .header(StandardAuthHeaders.RequestTime.getHeaderName(), requestTime) .build(); }; }
@Override public int hashCode() { int result = hostname.hashCode(); result = 31 * result + from.hashCode(); result = 31 * result + to.hashCode(); return result; }
// Get a beginning-of-week time for consistent tariff evaluation private Instant getNextSunday() { Instant result = getNowInstant(); int hour = result.get(DateTimeFieldType.hourOfDay()); if (hour > 0) result = result.plus((24 - hour) * TimeService.HOUR); int day = result.get(DateTimeFieldType.dayOfWeek()); result = result.plus((7 - day) * TimeService.DAY); return result; }
/** Advance the watermark to the specified time, firing any timers that should fire. */ public void advanceWatermark(Instant newWatermark) throws Exception { Preconditions.checkState( !newWatermark.isBefore(watermark), "Cannot move watermark time backwards from %s to %s", watermark.getMillis(), newWatermark.getMillis()); logInteraction("Advancing watermark to %d", newWatermark.getMillis()); watermark = newWatermark; timerInternals.advanceWatermark(runner, newWatermark); }
/** Advance the processing time to the specified time, firing any timers that should fire. */ public void advanceProcessingTime(Instant newProcessingTime) throws Exception { Preconditions.checkState( !newProcessingTime.isBefore(processingTime), "Cannot move processing time backwards from %s to %s", processingTime.getMillis(), newProcessingTime.getMillis()); logInteraction("Advancing processing time to %d", newProcessingTime.getMillis()); processingTime = newProcessingTime; timerInternals.advanceProcessingTime(runner, newProcessingTime); }
public Instant minimumWatermarkHold() { Instant minimum = null; for (State storage : inMemoryState.values()) { if (storage instanceof WatermarkStateInternal) { Instant hold = ((WatermarkStateInternal) storage).get().read(); if (minimum == null || (hold != null && hold.isBefore(minimum))) { minimum = hold; } } } return minimum; }
/** * Handle an account state warning produced by ldaptive account state machinery. * * <p>Override this method to provide custom warning message handling. * * @param warning the account state warning messages. * @param response Ldaptive authentication response. * @param configuration Password policy configuration. * @param messages Container for messages produced by account state warning handling. */ protected void handleWarning( final AccountState.Warning warning, final AuthenticationResponse response, final LdapPasswordPolicyConfiguration configuration, final List<Message> messages) { logger.debug("Handling warning {}", warning); if (warning == null) { logger.debug("Account state warning not defined"); return; } final Calendar expDate = warning.getExpiration(); final Days ttl = Days.daysBetween(Instant.now(), new Instant(expDate)); logger.debug( "Password expires in {} days. Expiration warning threshold is {} days.", ttl.getDays(), configuration.getPasswordWarningNumberOfDays()); if (configuration.isAlwaysDisplayPasswordExpirationWarning() || ttl.getDays() < configuration.getPasswordWarningNumberOfDays()) { messages.add( new PasswordExpiringWarningMessage( "Password expires in {0} days. Please change your password at <href=\"{1}\">{1}</a>", ttl.getDays(), configuration.getPasswordPolicyUrl())); } if (warning.getLoginsRemaining() > 0) { messages.add( new Message( "password.expiration.loginsRemaining", "You have {0} logins remaining before you MUST change your password.", warning.getLoginsRemaining())); } }
public void pause() { if (!isActive()) { throw new IllegalStateException("already non-active"); } intervals.add(new Interval(starttime, Instant.now())); starttime = null; }
@Override public void addField(TemporalElementaryDataItem di, Instant t) throws IOException { writeSeparator(); if (t != null) { addRawData(Long.toString(t.getMillis())); } }
public void setDate(Instant date) { if (date == null) { this.date = null; } else { this.date = date.toString(DATE_FORMAT); } }
// Returns the next date/time when the given shift index will occur Instant indexToInstant(int index) { Instant now = getNowInstant(); int probe = index; // get the probe within the shift schedule while (probe < 0) { probe += shiftSchedule.length; } while (probe > shiftSchedule.length) { probe -= shiftSchedule.length; } int nowIndex = indexOfShift(now); if (nowIndex <= index) { return (now.plus(TimeService.HOUR * (index - nowIndex))); } return (now.plus(TimeService.HOUR * (shiftSchedule.length + index - nowIndex))); }
@Transactional @Override public LoadResponse loadGoods(final GoodPayload payload) { final long timeInMillis = Instant.now().getMillis(); LoadResponse response = new LoadResponse(timeInMillis); for (final Map.Entry<Long, Integer> entry : payload.getGoods().entrySet()) { namedJdbcTemplate .getJdbcOperations() .batchUpdate( QUERY_INSERT_GOOD, new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement ps, int i) throws SQLException { ps.setTimestamp(1, new Timestamp(timeInMillis), tzUTC); ps.setLong(2, entry.getKey()); ps.setBoolean(3, false); } @Override public int getBatchSize() { return entry.getValue(); } }); } return response; }
// Check production transactions @Test public void testProduction() { Instant exp = now.plus(TimeService.WEEK * 10); TariffSpecification tariffSpec = new TariffSpecification(broker, PowerType.PRODUCTION) .withExpiration(exp) .withMinDuration(TimeService.WEEK * 4) .withSignupPayment(-34.2) .withEarlyWithdrawPayment(35.0) .addRate(new Rate().withValue(0.102)); tariff = new Tariff(tariffSpec); tariff.init(); // subscribe and consume in the first timeslot TariffSubscription tsub = tariffMarketService.subscribeToTariff(tariff, customer, 4); assertEquals("four customers committed", 4, tsub.getCustomersCommitted()); tsub.usePower(-244.6); // production assertEquals("correct total usage", -244.6 / 4, tsub.getTotalUsage(), 1e-6); assertEquals("correct realized price", 0.102, tariff.getRealizedPrice(), 1e-6); // def txs = TariffTransaction.findAllByPostedTime(timeService.currentTime); // assertEquals("two transactions", 2, txs.size()) // TariffTransaction ttx = TariffTransaction.findByPostedTimeAndTxType(timeService.currentTime, // TariffTransactionType.SIGNUP) // assertNotNull("found signup tx", ttx) // assertEquals("correct charge", -34.2 * 4, ttx.charge, 1e-6) // ttx = TariffTransaction.findByPostedTimeAndTxType(timeService.currentTime, // TariffTransactionType.PRODUCE) // assertNotNull("found production tx", ttx) // assertEquals("correct amount", -244.6, ttx.quantity) // assertEquals("correct charge", -0.102 * 244.6, ttx.charge, 1e-6) }
@Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { // inflate the layout LayoutInflater inflater = ((Activity) mContext).getLayoutInflater(); convertView = inflater.inflate(layoutResourceId, parent, false); } // object item based on the position final Event event = data.get(position); final TextView userNameView = (TextView) convertView.findViewById(R.id.user_text); cloudStore.lookUpUserByUid( event.getUser(), new Callback<User>() { @Override public void receive(User user) { userNameView.setText(user.getGivenName()); } }); TextView time = (TextView) convertView.findViewById(R.id.time_text); time.setText( PeriodicalFormatter.printFriendlyDate(new Instant(event.getMillis()), Instant.now())); return convertView; }
/** * behaviour undefined if interval list is unsorted any {@code null} input is interpreted as a * non-bound in that direction * * @param focusStart * @param focusEnd * @return */ public Duration getTimeSpentInInterval(LocalDate focusStart, LocalDate focusEnd) { Instant startInst, endInst; if (intervals.size() == 0 && !isActive()) { // # return Duration.ZERO; } if (focusStart == null) { startInst = intervals.size() == 0 ? starttime // != null because # : intervals.get(0).getStart().toInstant(); } else { startInst = focusStart.toDateTimeAtStartOfDay().toInstant(); } if (focusEnd == null) { endInst = isActive() ? Instant.now() // v intervals.size() != 0 because # : intervals.get(intervals.size() - 1).getEnd().toInstant(); // TODO } else { endInst = focusEnd.toDateTimeAtStartOfDay().toInstant(); } Interval focus = new Interval(startInst, endInst); return getTimeSpentInInterval(focus); }
// reduce duration by one on each tick of the clock void tick() { duration -= 1; if (duration < 0) { log.error( getName() + "SE start at " + start.toString() + " ticked past duration " + duration); } usageIndex += 1; }
public void setDonity(boolean done) { if (!isDone() && done) { this.done = Instant.now(); } if (isDone() && !done) { this.done = null; } }
protected boolean isPersonProtected(Person person) { if (person.getNavnebeskyttelsestartdato() == null) return false; // We have to make the guard above to avoid null being passed into the // Instant // it is converted to the beginning of the era. Preconditions.checkState( person.getNavnebeskyttelseslettedato() != null, "The protection end date was not present. This is most unexpected and a programming error."); Instant protectionStart = new Instant(person.getNavnebeskyttelsestartdato()); Instant protectionEnd = new Instant(person.getNavnebeskyttelseslettedato()); return protectionStart.isEqualNow() || (protectionStart.isBeforeNow() && protectionEnd.isAfterNow()); }
// subscription withdrawal without and with penalty @Test public void testEarlyWithdraw() { Instant exp = now.plus(TimeService.WEEK * 10); TariffSpecification tariffSpec = new TariffSpecification(broker, PowerType.CONSUMPTION) .withExpiration(exp) .withMinDuration(TimeService.WEEK * 4) .withSignupPayment(-33.2) .withEarlyWithdrawPayment(42.1) .addRate(new Rate().withValue(0.121)); tariff = new Tariff(tariffSpec); tariff.init(); TariffSubscription tsub = tariffMarketService.subscribeToTariff(tariff, customer, 5); // move time forward 2 weeks, withdraw 2 customers Instant wk2 = now.plus(TimeService.WEEK * 2); timeService.setCurrentTime(wk2); tsub.unsubscribe(2); verify(mockAccounting) .addTariffTransaction( TariffTransaction.Type.WITHDRAW, tariff, customer.getCustomerInfo(), 2, 0.0, 42.1 * 2); // def txs = TariffTransaction.findAllByPostedTime(wk2) // assertEquals("one transaction", 1, txs.size()) // assertEquals("correct txType", TariffTransactionType.WITHDRAW, txs[0].txType) // assertEquals("correct charge", 42.1*2, txs[0].charge) assertEquals("three customers committed", 3, tsub.getCustomersCommitted()); // move time forward another week, add 4 customers and drop 1 Instant wk3 = now.plus(TimeService.WEEK * 2 + TimeService.HOUR * 6); timeService.setCurrentTime(wk3); TariffSubscription tsub1 = tariffMarketService.subscribeToTariff(tariff, customer, 4); assertEquals("same subscription", tsub, tsub1); tsub1.unsubscribe(1); // txs = TariffTransaction.findAllByPostedTime(wk3) // assertEquals("two transactions", 2, txs.size()) // TariffTransaction ttx = TariffTransaction.findByPostedTimeAndTxType(timeService.currentTime, // // TariffTransactionType.SIGNUP) // assertNotNull("found signup tx", ttx) // assertEquals("correct charge", -33.2 * 4, ttx.charge) // ttx = TariffTransaction.findByPostedTimeAndTxType(timeService.currentTime, // TariffTransactionType.WITHDRAW) // assertNotNull("found withdraw tx", ttx) // assertEquals("correct charge", 42.1, ttx.charge) assertEquals("six customers committed", 6, tsub1.getCustomersCommitted()); }
// Check consumption transactions @Test public void testConsumption() { Instant exp = now.plus(TimeService.WEEK * 10); TariffSpecification tariffSpec = new TariffSpecification(broker, PowerType.CONSUMPTION) .withExpiration(exp) .withMinDuration(TimeService.WEEK * 4) .withSignupPayment(-33.2) .addRate(new Rate().withValue(0.121)); tariff = new Tariff(tariffSpec); tariff.init(); // subscribe and consume in the first timeslot TariffSubscription tsub = tariffMarketService.subscribeToTariff(tariff, customer, 4); assertEquals("four customers committed", 4, tsub.getCustomersCommitted()); tsub.usePower(24.4); // consumption assertEquals("correct total usage", 24.4 / 4, tsub.getTotalUsage(), 1e-6); assertEquals("correct realized price", 0.121, tariff.getRealizedPrice(), 1e-6); // def txs = TariffTransaction.findAllByPostedTime(timeService.getCurrentTime()); // assertEquals("two transactions", 2, txs.size()) // TariffTransaction ttx = // TariffTransaction.findByPostedTimeAndTxType(timeService.currentTime, // TariffTransactionType.SIGNUP) // assertNotNull("found signup tx", ttx) // assertEquals("correct charge", -33.2 * 4, ttx.charge, 1e-6) // ttx = TariffTransaction.findByPostedTimeAndTxType(timeService.currentTime, // TariffTransactionType.CONSUME) // assertNotNull("found consumption tx", ttx) // assertEquals("correct amount", 24.4, ttx.quantity) // assertEquals("correct charge", 0.121 * 24.4, ttx.charge, 1e-6) // just consume in the second timeslot Instant hour = now.plus(TimeService.HOUR); timeService.setCurrentTime(hour); tsub.usePower(32.8); // consumption assertEquals("correct total usage", (24.4 + 32.8) / 4, tsub.getTotalUsage(), 1e-6); assertEquals("correct realized price", 0.121, tariff.getRealizedPrice(), 1e-6); // txs = TariffTransaction.findAllByPostedTime(timeService.getCurrentTime()) // assertEquals("one transaction", 1, txs.size()) // ttx = TariffTransaction.findByPostedTimeAndTxType(timeService.getCurrentTime(), // TariffTransactionType.CONSUME) // assertNotNull("found consumption tx", ttx) // assertEquals("correct amount", 32.8, ttx.quantity) // assertEquals("correct charge", 0.121 * 32.8, ttx.charge, 1e-6) }
public void injectElement(InputT value, Instant timestamp) throws Exception { Collection<W> windows = windowFn.assignWindows( new TriggerTester.StubAssignContext<W>( windowFn, value, timestamp, Arrays.asList(GlobalWindow.INSTANCE))); logInteraction( "Element %s at time %d put in windows %s", value, timestamp.getMillis(), windows); runner.processElement(WindowedValue.of(value, timestamp, windows, PaneInfo.NO_FIRING)); }
// Returns the ShiftEnergy instance for the current time // Note that for this to work, the ShiftEnergy.tick() method // must be called once/timeslot. ShiftEnergy getCurrentNeed(Instant when) { if (null == needs) return null; for (int i = 0; i < needs.length; i++) { // if it's the last one, return it. if ((i == needs.length - 1) || (needs[i + 1].getStart().isAfter(when))) { return needs[i]; } } // should never get here log.error( getName() + " at " + when.toString() + " ran off end of plan length " + size + " starting " + start.toString()); return null; }
@Override public void flatMap(IN value, Collector<WindowedValue<OUT>> out) throws Exception { @SuppressWarnings("unchecked") OUT voidValue = (OUT) VoidCoderTypeSerializer.VoidValue.INSTANCE; for (byte[] element : elements) { ByteArrayInputStream bai = new ByteArrayInputStream(element); OUT outValue = coder.decode(bai, Coder.Context.OUTER); if (outValue == null) { out.collect( WindowedValue.of(voidValue, Instant.now(), GlobalWindow.INSTANCE, PaneInfo.NO_FIRING)); } else { out.collect( WindowedValue.of(outValue, Instant.now(), GlobalWindow.INSTANCE, PaneInfo.NO_FIRING)); } } out.close(); }
public void testSimpleStore() throws SQLException { SessionFactory factory = getSessionFactory(); Session session = factory.openSession(); for (int i = 0; i < writeReadTimes.length; i++) { Instant writeReadTime = writeReadTimes[i]; ThingWithInstant thing = new ThingWithInstant(); thing.setId(i); thing.setInstant(writeReadTime); session.save(thing); } session.flush(); session.connection().commit(); session.close(); for (int i = 0; i < writeReadTimes.length; i++) { Instant writeReadTime = writeReadTimes[i]; session = factory.openSession(); ThingWithInstant thingReread = (ThingWithInstant) session.get(ThingWithInstant.class, new Integer(i)); assertNotNull("get failed - thing#'" + i + "'not found", thingReread); assertNotNull("get failed - returned null", thingReread.getInstant()); Instant reReadTime = thingReread.getInstant(); if (writeReadTime.getMillis() != reReadTime.getMillis()) { fail( "get failed - returned different date. expected " + writeReadTime + " was " + thingReread.getInstant()); } } session.close(); }
protected void checkTimestamp(WindowedValue<IN> ref, Instant timestamp) { if (timestamp.isBefore(ref.getTimestamp().minus(doFn.getAllowedTimestampSkew()))) { throw new IllegalArgumentException( String.format( "Cannot output with timestamp %s. Output timestamps must be no earlier than the " + "timestamp of the current input (%s) minus the allowed skew (%s). See the " + "DoFn#getAllowedTimestmapSkew() Javadoc for details on changing the allowed skew.", timestamp, ref.getTimestamp(), PeriodFormat.getDefault().print(doFn.getAllowedTimestampSkew().toPeriod()))); } }
// set commitment leadtime to a larger number and make sure ordering // behavior is correct @Test public void testGenerateOrders2() { // set up the genco with commitment leadtime=3 PluginConfig config = new PluginConfig("Genco", "").addConfiguration("commitmentLeadtime", "3"); genco.configure(config); // all defaults // capture orders final ArrayList<Order> orderList = new ArrayList<Order>(); doAnswer( new Answer() { public Object answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); orderList.add((Order) args[0]); return null; } }) .when(mockProxy) .routeMessage(isA(Order.class)); // set up some timeslots Timeslot ts0 = timeslotRepo.makeTimeslot(start); ts0.disable(); assertEquals("first ts has sn=0", 0, ts0.getSerialNumber()); timeslotRepo.makeTimeslot(start.plus(TimeService.HOUR)); timeslotRepo.makeTimeslot(start.plus(TimeService.HOUR * 2)); timeslotRepo.makeTimeslot(start.plus(TimeService.HOUR * 3)); timeslotRepo.makeTimeslot(start.plus(TimeService.HOUR * 4)); assertEquals("4 enabled timeslots", 4, timeslotRepo.enabledTimeslots().size()); // generate orders and check genco.generateOrders(start, timeslotRepo.enabledTimeslots()); assertEquals("two orders", 2, orderList.size()); Order first = orderList.get(0); assertEquals("first order for ts3", 3, first.getTimeslot().getSerialNumber()); assertEquals("first order price", 1.0, first.getLimitPrice(), 1e-6); assertEquals("first order for 50 mwh", -100.0, first.getMWh(), 1e-6); Order second = orderList.get(1); assertEquals("second order for ts4", 4, second.getTimeslot().getSerialNumber()); assertEquals("second order price", 1.0, second.getLimitPrice(), 1e-6); assertEquals("second order for 100 mwh", -100.0, second.getMWh(), 1e-6); }
@Test public void testGenerateOrders() { // set up the genco PluginConfig config = new PluginConfig("Genco", ""); genco.configure(config); // all defaults // capture orders final ArrayList<Order> orderList = new ArrayList<Order>(); doAnswer( new Answer() { public Object answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); orderList.add((Order) args[0]); return null; } }) .when(mockProxy) .routeMessage(isA(Order.class)); // set up some timeslots Timeslot ts1 = timeslotRepo.makeTimeslot(start); ts1.disable(); Timeslot ts2 = timeslotRepo.makeTimeslot(start.plus(TimeService.HOUR)); Timeslot ts3 = timeslotRepo.makeTimeslot(start.plus(TimeService.HOUR * 2)); assertEquals("2 enabled timeslots", 2, timeslotRepo.enabledTimeslots().size()); // 50 mwh already sold in ts2 MarketPosition posn2 = new MarketPosition(genco, ts2, -50.0); genco.addMarketPosition(posn2, ts2); // generate orders and check genco.generateOrders(start, timeslotRepo.enabledTimeslots()); assertEquals("two orders", 2, orderList.size()); Order first = orderList.get(0); assertEquals("first order for ts2", ts2, first.getTimeslot()); assertEquals("first order price", 1.0, first.getLimitPrice(), 1e-6); assertEquals("first order for 50 mwh", -50.0, first.getMWh(), 1e-6); Order second = orderList.get(1); assertEquals("second order for ts3", ts3, second.getTimeslot()); assertEquals("second order price", 1.0, second.getLimitPrice(), 1e-6); assertEquals("second order for 100 mwh", -100.0, second.getMWh(), 1e-6); }
@Override protected QuartzBatchJobMetrics mmrBatchExecuteInternal(JobDataMap mergedDataMap) { Instant startInstant = Instant.now(); ExecutionResultDetails executionDetails = executeJob(); Instant endInstant = Instant.now(); Duration duration = new Duration(startInstant, endInstant); QuartzBatchJobMetrics jobMetrics = new BaseQuartzBatchJobMetrics( startInstant, endInstant, duration, executionDetails.getNumberOfProcessedItems(), executionDetails.getNumberOfErroredItems(), executionDetails.getErrorItems()); logger.info( "Finished {} finished in {} time", getJobDetailName(), ISODateTimeFormat.basicTime().print(duration.getMillis())); return jobMetrics; }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Key key = (Key) o; if (!from.equals(key.from)) { return false; } if (!hostname.equals(key.hostname)) { return false; } if (!to.equals(key.to)) { return false; } return true; }
@Before public void setUp() { broker = new Broker("Joe"); now = new DateTime(2011, 1, 10, 0, 0, 0, 0, DateTimeZone.UTC).toInstant(); timeService.setCurrentTime(now); Instant exp = now.plus(TimeService.WEEK * 10); TariffSpecification tariffSpec = new TariffSpecification(broker, PowerType.CONSUMPTION) .withExpiration(exp) .withMinDuration(TimeService.WEEK * 8) .addRate(new Rate().withValue(0.121)); tariff = new Tariff(tariffSpec); tariff.init(); customerInfo = new CustomerInfo("Charley", 100); customer = new AbstractCustomer(customerInfo); reset(mockAccounting); }