@Override
  public RESULT onTrigger(TYPE iType, ORecord iRecord) {
    // TODO Auto-generated method stub
    if (iRecord instanceof ODocument) {

      switch (iType) {
        case BEFORE_CREATE:
          {
            String instant = Instant.now().toString();

            ((ODocument) iRecord).field("createdAt", instant);
            ((ODocument) iRecord).field("updatedAt", instant);

            return RESULT.RECORD_CHANGED;
          }

        case BEFORE_UPDATE:
          {
            String instant = Instant.now().toString();

            ((ODocument) iRecord).field("updatedAt", instant);

            return RESULT.RECORD_CHANGED;
          }

        default:
          break;
      }
    }
    return RESULT.RECORD_NOT_CHANGED;
  }
Example #2
0
  /** Checks if a player has any activity within a predefined period of time */
  public void checkPlayerActivity() {

    for (Map.Entry<Integer, Instant> entry : timeTagMap.entrySet()) {
      int key = entry.getKey();
      Instant value = entry.getValue();
      // check which player has a time tag older than TIME_DELAY ago
      // kick the player off from the idMap and addressMap
      System.out.println("Key = " + key + ", Value = " + value);
      // each player has its own time tag

      if (value == null) entry.setValue(Instant.now());

      Instant newLogTime = Instant.now();
      long elapsed = java.time.Duration.between(oldLogTime, newLogTime).toMillis() / 1000;

      if (elapsed > TIME_DELAY) {
        // unregister player,
        // clear idMap, addressMap
        centralRegistry.getIdMap().remove(key);
        centralRegistry.getAddressMap().remove(key);
        // Do NOT clear timeTagMap. leave it as it is.
        // send msg to panel
        // sendDisconnect();
        // TODO: where in this class to update new value e.g. entry.setValue(newLogTime);
      }
    }
  }
 /**
  * @param start Start time
  * @return Index sample with time stamp at-or-before start time, or -1.
  */
 private int findSampleLessOrEqual(final Instant start) {
   // Would like to use PlotSampleSearch, but that operates on array
   // of PlotSample[]
   int low = 0;
   int high = samples.size() - 1;
   int cmp = 0;
   int mid = -1;
   while (low <= high) {
     mid = (low + high) / 2;
     // Compare 'mid' sample to goal
     final Instant time = samples.get(mid).getPosition();
     final int compare = time.compareTo(start);
     if (compare > 0) { // 'mid' too big, search lower half
       cmp = 1;
       high = mid - 1;
     } else if (compare < 0) { // 'mid' too small, search upper half
       cmp = -1;
       low = mid + 1;
     } else {
       cmp = 0;
       return mid; // found exact time
     }
   }
   // Didn't find exact match.
   if (cmp < 0) // 'mid' sample is smaller than x, so it's OK
   return mid;
   // cmp > 0, 'mid' sample is greater than x.
   // If there is a sample before, use that
   if (mid > 0) return mid - 1;
   return -1;
 }
Example #4
0
  @Override
  public String toString() {
    final StringBuilder sb = new StringBuilder();
    if (isUDP()) {
      sb.append("U ");
    } else if (isTCP()) {
      sb.append("T ");
    } else {
      // TODO: need WS, SCTP etc as well. but not as common
      // right now so no big deal.
    }

    // final DateTimeFormatter formatter =
    // DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss.SSS");
    final Instant timestamp = Instant.ofEpochMilli(getArrivalTime() / 1000);
    sb.append(timestamp.toString())
        .append(" ")
        .append(getSourceIP())
        .append(":")
        .append(getSourcePort())
        .append(" -> ")
        .append(getDestinationIP())
        .append(":")
        .append(getDestinationPort())
        .append("\n")
        .append(this.msg.toString());
    return sb.toString();
  }
  private Statement createStatementToSaveFollowing(User user, Application app) {
    UUID userId = UUID.fromString(user.userId);
    UUID appId = UUID.fromString(app.applicationId);

    BatchStatement batch = new BatchStatement();

    Statement insertIntoAppFollowersTable =
        QueryBuilder.insertInto(Follow.TABLE_NAME_APP_FOLLOWERS)
            .value(APP_ID, appId)
            .value(USER_ID, userId)
            .value(APP_NAME, app.name)
            .value(USER_FIRST_NAME, user.firstName)
            .value(TIME_OF_FOLLOW, Instant.now().toEpochMilli());

    batch.add(insertIntoAppFollowersTable);

    Statement insertIntoUserFollowingsTable =
        QueryBuilder.insertInto(Follow.TABLE_NAME_USER_FOLLOWING)
            .value(APP_ID, appId)
            .value(USER_ID, userId)
            .value(APP_NAME, app.name)
            .value(USER_FIRST_NAME, user.firstName)
            .value(TIME_OF_FOLLOW, Instant.now().toEpochMilli());

    batch.add(insertIntoUserFollowingsTable);

    return batch;
  }
Example #6
0
  public static void main(String[] args) {
    Instant start = Instant.now();

    Instant end = Instant.now();
    Duration length = Duration.between(end, start);
    System.out.println(length.toNanos());
  }
 @Override
 public ScheduleStatus map(int index, ResultSet r, StatementContext ctx) throws SQLException {
   return ScheduleStatus.of(
       ScheduleTime.of(
           Instant.ofEpochSecond(r.getLong("next_schedule_time")),
           Instant.ofEpochSecond(r.getLong("next_run_time"))),
       getOptionalLong(r, "last_session_time").transform(it -> Instant.ofEpochSecond(it)));
 }
Example #8
0
 public Optional<MetricSet> getValues(String metricName, Interval interval) {
   Instant now = Clock.systemUTC().instant();
   Optional<RetentionLevel> accessLevel =
       environment.retentions().findAccessLevelForMetric(metricName);
   Optional<MetricSet> setWithHighestQoS = Optional.empty();
   double highestAvailableQoS = 0;
   if (!accessLevel.isPresent()) {
     return Optional.empty();
   }
   EvictionStrategy evictionStrategy = findEvictionStrategyForAccessLevel(accessLevel.get()).get();
   evictionStrategy.accessing(metricName);
   while (accessLevel.isPresent() && caches.containsKey(accessLevel.get().name())) {
     log.trace("Found accessLevel " + accessLevel.get().name());
     Optional<CachingLevel> cachingLevel =
         environment.cachingConfiguration().findLevelForLevelName(accessLevel.get().name());
     if (cachingLevel.isPresent()) {
       long cachingLevelStart =
           now.minusSeconds(cachingLevel.get().cacheLineWidth() * accessLevel.get().frequency())
               .getEpochSecond();
       if (cachingLevelStart < interval.start()) {
         Optional<MetricSet> metricSet = doGetValues(metricName, interval, cachingLevel.get());
         if (!metricSet.isPresent()) {
           try {
             createNewCacheLines(metricName).get();
           } catch (InterruptedException | ExecutionException e) {
             log.warn("Exception while waiting for threads loading metrics", e);
           }
           metricSet = doGetValues(metricName, interval, cachingLevel.get());
         }
         if (metricSet.isPresent()) {
           log.trace("metricSet contains {} timestamps", metricSet.get().size());
           log.trace("accesslevel: {} | metricSet: {}", accessLevel.get().name(), metricSet.get());
           OptionalDouble serviceAvailable = calculateQoS(interval, metricSet.get());
           if (serviceAvailable.isPresent()
               && serviceAvailable.getAsDouble()
                   >= environment.cachingConfiguration().qualityOfService()) {
             log.trace("returning metricSet");
             return metricSet;
           } else if (serviceAvailable.isPresent()
               && serviceAvailable.getAsDouble() > highestAvailableQoS) {
             log.trace("new highestAvailable set");
             highestAvailableQoS = serviceAvailable.getAsDouble();
             setWithHighestQoS = metricSet;
           }
         } else {
           log.debug(
               "no metricSet for cacheLevel {} metric {} found!",
               accessLevel.get().name(),
               metricName);
         }
       }
     }
     accessLevel = environment.retentions().getNextLevel(accessLevel.get());
   }
   log.trace("service requested not available, returning highest available");
   return setWithHighestQoS;
 }
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public List<ResultEntity> search(
      @QueryParam("query") String query,
      @QueryParam("taxonomyPosition") String position,
      @QueryParam("spaceId") String spaceId,
      @QueryParam("appId") String appId,
      @QueryParam("startDate") String startDate,
      @QueryParam("endDate") String endDate) {
    QueryDescription queryDescription = new QueryDescription(query);
    queryDescription.setTaxonomyPosition(position);

    if (StringUtil.isDefined(startDate)) {
      try {
        String date =
            Instant.ofEpochMilli(Long.valueOf(startDate))
                .atZone(ZoneId.systemDefault())
                .toLocalDate()
                .format(formatter);
        queryDescription.setRequestedCreatedAfter(date);
      } catch (Exception e) {
        SilverLogger.getLogger(this)
            .info("Can't parse start date as Long : {0}", new String[] {startDate}, e);
      }
    }

    if (StringUtil.isDefined(endDate)) {
      try {
        String date =
            Instant.ofEpochMilli(Long.valueOf(endDate))
                .atZone(ZoneId.systemDefault())
                .toLocalDate()
                .format(formatter);
        queryDescription.setRequestedCreatedBefore(date);
      } catch (Exception e) {
        SilverLogger.getLogger(this)
            .info("Can't parse end date as Long : {0}", new String[] {endDate}, e);
      }
    }

    // determine where to search
    setComponents(queryDescription, spaceId, appId);

    SearchService searchService = SearchService.get();
    List<ResultEntity> entities = new ArrayList<>();
    try {
      List<SearchResult> results = searchService.search(queryDescription);
      for (SearchResult result : results) {
        entities.add(ResultEntity.fromSearchResult(result));
      }
    } catch (Exception e) {
      SilverLogger.getLogger(this).error("Error during search...", e);
      throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }

    return entities;
  }
Example #10
0
 private App() {
   running = true;
   String lastTickFromDb = AppStateController.singleton().getState(AppState.LAST_TICK);
   if (lastTickFromDb == null) {
     lastTick = Instant.now();
   } else {
     lastTick = Instant.ofEpochMilli(Long.parseLong(lastTickFromDb));
   }
 }
 @Override
 public Instant parse(String text, Locale locale) throws ParseException {
   if (text.length() > 0 && Character.isDigit(text.charAt(0))) {
     // assuming UTC instant a la "2007-12-03T10:15:30.00Z"
     return Instant.parse(text);
   } else {
     // assuming RFC-1123 value a la "Tue, 3 Jun 2008 11:05:30 GMT"
     return Instant.from(DateTimeFormatter.RFC_1123_DATE_TIME.parse(text));
   }
 }
Example #12
0
 public static String formatFileName(String taskName, Instant firstLogTime, String agentId) {
   return String.format(
           ENGLISH,
           "%s@%08x%08x.%s",
           taskName,
           firstLogTime.getEpochSecond(),
           firstLogTime.getNano(),
           agentId)
       + LOG_GZ_FILE_SUFFIX;
 }
Example #13
0
 private static LocalDate parse(final DateTimeFormatter formatter, final String value) {
   try {
     Instant epoch = Instant.ofEpochMilli(Long.parseLong(value));
     ZonedDateTime zonedDate =
         epoch.atZone(Optional.ofNullable(formatter.getZone()).orElse(ZoneId.systemDefault()));
     return zonedDate.toLocalDate();
   } catch (NumberFormatException ex) {
     return LocalDate.parse(value, formatter);
   }
 }
 @Test
 public void test() {
   ReqTimeLineRequest req = new ReqTimeLineRequest(1, "btccny");
   req.setFrom(Instant.ofEpochMilli(1));
   req.setTo(Instant.ofEpochMilli(2));
   String json = gson.toJson(req);
   assertEquals(
       "{\"from\":1,\"to\":2,\"symbolId\":\"btccny\",\"version\":1,\"msgType\":\"reqTimeLine\",\"requestIndex\":0}",
       json);
 }
  @Test
  public void test_findByFechaBetween_out_range() throws Exception {
    Retiro retiro =
        new Retiro(100.0, "efectivo", Instant.parse("2015-12-30T09:50:00Z"), "username1");
    retiroRepository.save(retiro);
    List<Retiro> retiroList =
        retiroRepository.findByFechaBetween(
            Instant.parse("2015-12-29T00:00:00Z"), Instant.parse("2015-12-29T23:59:59Z"));

    Assert.assertThat(retiroList, hasSize(0));
  }
Example #16
0
  private void mainLoop() {
    while (running) {
      Instant tickStart = Instant.now();
      elapsedSinceLastTick = Duration.between(lastTick, tickStart);
      lastTick = tickStart;

      AppStateController.singleton()
          .updateState(AppState.LAST_TICK, Long.toString(tickStart.toEpochMilli()));
      sleepForRestOfTick(tickStart);
    }
  }
  @Test
  public void testGetTrackerData() {
    List<TrackerData> trackerDataList =
        Arrays.asList(
            new TrackerData(Instant.now(), 9),
            new TrackerData(Instant.now(), 11),
            new TrackerData(Instant.now(), 12));
    when(trackerDAO.findTrackerData()).thenReturn(trackerDataList);

    List<TrackerData> actualTrackerDataList = trackerService.getTrackerData();
    assertEquals(trackerDataList, actualTrackerDataList);
  }
@RunWith(MockitoJUnitRunner.class)
public class UpdateMessageListenerTest {

  @Mock private TextMessage textMessage;
  @Mock private MapMessage mapMessage;
  @Mock private DateTimeProvider dateTimeProvider;

  private Services services = new Services();
  private ReportMessages messages = new ReportMessages();
  private UpdateMessageListener sut;
  private Instant now = Instant.parse("2015-12-03T10:15:30.00Z");
  private Instant sendTime = now.minus(4, ChronoUnit.SECONDS);

  @Before
  public void setup() {
    sut = new UpdateMessageListener(services, messages, dateTimeProvider);
  }

  @Test
  public void serviceUpdateMessage_shouldBeReflectedInServicesObject_whenTextMessageReceived()
      throws JMSException {
    Mockito.when(textMessage.getStringProperty("sender")).thenReturn("service");
    Mockito.when(dateTimeProvider.now()).thenReturn(now);
    sut.onMessage(textMessage);

    List<Service> allServices = services.getAllServices();
    assertEquals(1, allServices.size());
    assertEquals("service - 2015-12-03T10:15:30Z", allServices.get(0).getServiceDetails());
  }

  @Test
  public void reportMessage_shouldBeReflectedInReportMessagesObject_whenMapMessageReceived()
      throws JMSException {
    Mockito.when(mapMessage.getStringProperty("sender")).thenReturn("service");
    Mockito.when(mapMessage.getString("message")).thenReturn("db load error");
    Mockito.when(mapMessage.getString("timestamp")).thenReturn("999");
    Mockito.when(mapMessage.getString("severity")).thenReturn("error");

    Mockito.when(dateTimeProvider.now()).thenReturn(now);
    Mockito.when(dateTimeProvider.stringToInstant("999")).thenReturn(sendTime);
    sut.onMessage(mapMessage);

    List<ReportMessage> reportMessages = messages.getMessages();
    assertEquals(1, reportMessages.size());

    ReportMessage reportMessage = reportMessages.get(0);
    assertEquals("service", reportMessage.getSender());
    assertEquals("db load error", reportMessage.getMessage());
    assertEquals("error", reportMessage.getSeverity());
    assertEquals(now, reportMessage.getReceivedOn());
    assertEquals(sendTime, reportMessage.getTimestamp());
  }
}
  @Test
  public void test_insert_new_retiro() throws Exception {
    Retiro retiro =
        new Retiro(100.0, "efectivo", Instant.parse("2015-12-30T09:50:00Z"), "username1");
    retiroRepository.save(retiro);
    List<Retiro> retiroList = retiroRepository.findAll();

    Assert.assertThat(retiroList, hasSize(1));
    Assert.assertThat(retiroList.get(0).getMonto(), is(100.0));
    Assert.assertThat(retiroList.get(0).getDescripcion(), is("efectivo"));
    Assert.assertThat(retiroList.get(0).getFecha(), is(Instant.parse("2015-12-30T09:50:00Z")));
    Assert.assertThat(retiroList.get(0).getUsername(), is("username1"));
  }
  @Override
  public synchronized void run() {
    instant.set(Instant.now());
    System.out.println(Thread.currentThread().getName() + " share  start time : " + instant.get());
    try {
      TimeUnit.SECONDS.sleep((int) Math.random() * 10);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    instant.set(Instant.now());

    System.out.println(Thread.currentThread().getName() + "share  end time : " + instant.get());
  }
  private String[] setStandardTime(String requestUid, String time, User user) {

    final ZonedDateTime proposedDateTime;
    final String dateTimePrompt = getMessage(thisSection, "confirm", "time." + time, user);

    ZonedDateTime zonedNow = Instant.now().atZone(DateTimeUtil.getSAST());

    switch (time) {
      case "instant":
        proposedDateTime = zonedNow.plusMinutes(7L).truncatedTo(ChronoUnit.SECONDS);
        break;
      case "hour":
        proposedDateTime = zonedNow.plusHours(1L);
        break;
      case "day":
        proposedDateTime = zonedNow.plusDays(1L);
        break;
      case "week":
        proposedDateTime = zonedNow.plusWeeks(1L);
        break;
      default:
        // this should never be called, but need it else Java throws error -- defaulting to instant
        proposedDateTime = zonedNow.plusMinutes(7L);
        break;
    }

    eventRequestBroker.updateEventDateTime(
        user.getUid(), requestUid, proposedDateTime.toLocalDateTime());
    EventRequest voteRequest = eventRequestBroker.load(requestUid);
    return new String[] {voteRequest.getName(), dateTimePrompt};
  }
  @RequestMapping(value = path + "change-vote")
  @ResponseBody
  public Request changeVoteDo(
      @RequestParam(value = phoneNumber) String inputNumber,
      @RequestParam(value = entityUidParam) String eventUid,
      @RequestParam(value = "response") String response)
      throws URISyntaxException {

    final User user = userManager.findByInputNumber(inputNumber, null);
    final Event vote = eventBroker.load(eventUid);

    USSDMenu menu;
    if (vote.getEventStartDateTime().isBefore(Instant.now())) {
      menu = new USSDMenu(getMessage(thisSection, "change", "error", user));
    } else {
      // todo: replace this hack once responses are handled better
      EventRSVPResponse voteResponse =
          "abstain".equals(response)
              ? EventRSVPResponse.MAYBE
              : EventRSVPResponse.fromString(response);
      eventLogBroker.rsvpForEvent(vote.getUid(), user.getUid(), voteResponse);
      menu = new USSDMenu(getMessage(thisSection, "change", "done", response, user));
    }

    menu.addMenuOption(
        voteMenus + "details" + entityUidUrlSuffix + eventUid + "&back=open",
        getMessage(thisSection, "change", optionsKey + "back", user));
    menu.addMenuOptions(optionsHomeExit(user));

    return menuBuilder(menu);
  }
 private void refreshTimeoutOnEvade(User user, Server server) {
   ServerTimeout timeout =
       SafeNav.of(serverStorage.get(server.getId()))
           .next(TempServerConfig::getServerTimeouts)
           .next(ServerTimeoutStorage::getTimeouts)
           .next(timeouts -> timeouts.get(user.getId()))
           .get();
   if (timeout == null) {
     LOGGER.warn(
         "Attempted to refresh a timeout on a user who was not timed out! {} ({})",
         user.getUsername(),
         user.getId());
     return;
   }
   LOGGER.info(
       "User {} ({}) attempted to evade a timeout on {} ({})!",
       user.getUsername(),
       user.getId(),
       server.getName(),
       server.getId());
   Channel channel = apiClient.getChannelById(server.getId(), server);
   apiClient.sendMessage(
       loc.localize(
           "listener.mod.timeout.on_evasion",
           user.getId(),
           formatDuration(Duration.between(Instant.now(), timeout.getEndTime())),
           formatInstant(timeout.getEndTime())),
       channel);
   applyTimeoutRole(user, server, channel);
 }
Example #24
0
  @Override
  public boolean equals(final Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    final NodeBranchEntry that = (NodeBranchEntry) o;

    if (nodeVersionId != null
        ? !nodeVersionId.equals(that.nodeVersionId)
        : that.nodeVersionId != null) {
      return false;
    }
    if (nodeState != that.nodeState) {
      return false;
    }
    if (nodePath != null ? !nodePath.equals(that.nodePath) : that.nodePath != null) {
      return false;
    }
    if (timestamp != null ? !timestamp.equals(that.timestamp) : that.timestamp != null) {
      return false;
    }
    return !(nodeId != null ? !nodeId.equals(that.nodeId) : that.nodeId != null);
  }
  @Test
  public void testAddOnPrivateChatMessageListener() throws Exception {
    CompletableFuture<String> usernameFuture = new CompletableFuture<>();
    CompletableFuture<ChatMessage> chatMessageFuture = new CompletableFuture<>();
    instance.addOnPrivateChatMessageListener(
        (username, chatMessage) -> {
          usernameFuture.complete(username);
          chatMessageFuture.complete(chatMessage);
        });

    String message = "private message";

    User user = mock(User.class);
    when(user.getNick()).thenReturn(chatUser1.getUsername());

    Channel channel = mock(Channel.class);
    when(channel.getName()).thenReturn(DEFAULT_CHANNEL_NAME);

    UserHostmask userHostMask = mock(UserHostmask.class);
    instance.onEvent(new PrivateMessageEvent(pircBotX, userHostMask, user, message));

    assertThat(chatMessageFuture.get().getMessage(), is(message));
    assertThat(chatMessageFuture.get().getUsername(), is(chatUser1.getUsername()));
    assertThat(
        chatMessageFuture.get().getTime(),
        is(greaterThan(Instant.ofEpochMilli(System.currentTimeMillis() - 1000))));
    assertThat(chatMessageFuture.get().isAction(), is(false));
  }
Example #26
0
  @Test
  public void testBasic() {
    System.out.println(Year.now());
    System.out.println(Year.of(2015));
    System.out.println(Year.isLeap(2016));

    Locale locale = Locale.getDefault();
    System.out.println(Month.DECEMBER.getDisplayName(TextStyle.FULL, locale));
    System.out.println(Month.DECEMBER.getDisplayName(TextStyle.SHORT, locale));
    System.out.println(Month.DECEMBER.getDisplayName(TextStyle.NARROW, locale));
    System.out.println(Month.DECEMBER.getDisplayName(TextStyle.FULL_STANDALONE, locale));
    System.out.println(Month.of(8).ordinal());
    System.out.println(Month.AUGUST.minus(2));

    System.out.println(YearMonth.now());
    System.out.println(MonthDay.now());

    System.out.println(DayOfWeek.FRIDAY.plus(2));
    System.out.println(DayOfWeek.of(1));
    System.out.println(
        DayOfWeek.from(LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault())));

    System.out.println(Period.between(Year.now().atDay(1), LocalDate.now()));
    System.out.println(ChronoUnit.DAYS.between(Year.now().atDay(1), LocalDate.now()));
  }
 /**
  * Check time zones on the IANA time and zone database
  *
  * @param args
  */
 public static void main(String[] args) {
   ZoneId casaZone = ZoneId.of("Africa/Casablanca");
   ZoneId defaultZone = TimeZone.getDefault().toZoneId();
   LocalDate rightNow = LocalDate.now();
   ZonedDateTime zoneDateTime = rightNow.atStartOfDay(casaZone);
   ZoneId parisZone = ZoneId.of("Europe/Paris");
   LocalDateTime rightNowInTime = LocalDateTime.now();
   ZonedDateTime rightNowInTimeInParis = rightNowInTime.atZone(parisZone);
   Instant thisMoment = Instant.now();
   ZonedDateTime thisMomentInCasa = thisMoment.atZone(casaZone);
   ZoneId tokyoZone = ZoneId.of("Asia/Tokyo");
   LocalDate thisInstantInTokyo = rightNowInTime.toLocalDate();
   LocalDateTime timeFromThisMomentInTokyo = LocalDateTime.ofInstant(thisMoment, tokyoZone);
   System.out.println(
       String.format("In Tokyo right now is %s", timeFromThisMomentInTokyo.toString()));
 }
Example #28
0
 void storeTimestampOfLastExport(ODocument workItem) {
   store.setFields(
       workItem, //
       of(
           FieldNames.JIRA_EXPORT_TIMESTAMP,
           StorageQuery.getField(workItem, FieldNames.MODIFIED, Date.from(Instant.now()))));
 }
 public void dispose() throws SaslException {
   previousHash = null;
   previousSeed = null;
   if (locked && (Instant.now().getEpochSecond() < (time + LOCK_TIMEOUT))) {
     updateTimeout(0);
   }
 }
Example #30
0
  /**
   * Gets the offset applicable at the specified instant in these rules.
   *
   * <p>The mapping from an instant to an offset is simple, there is only one valid offset for each
   * instant. This method returns that offset.
   *
   * @param instant the instant to find the offset for, not null, but null may be ignored if the
   *     rules have a single offset for all instants
   * @return the offset, not null
   */
  public ZoneOffset getOffset(Instant instant) {
    if (savingsInstantTransitions.length == 0) {
      return standardOffsets[0];
    }
    long epochSec = instant.getEpochSecond();
    // check if using last rules
    if (lastRules.length > 0
        && epochSec > savingsInstantTransitions[savingsInstantTransitions.length - 1]) {
      int year = findYear(epochSec, wallOffsets[wallOffsets.length - 1]);
      ZoneOffsetTransition[] transArray = findTransitionArray(year);
      ZoneOffsetTransition trans = null;
      for (int i = 0; i < transArray.length; i++) {
        trans = transArray[i];
        if (epochSec < trans.toEpochSecond()) {
          return trans.getOffsetBefore();
        }
      }
      return trans.getOffsetAfter();
    }

    // using historic rules
    int index = Arrays.binarySearch(savingsInstantTransitions, epochSec);
    if (index < 0) {
      // switch negative insert position to start of matched range
      index = -index - 2;
    }
    return wallOffsets[index + 1];
  }