@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;
  }
Exemplo n.º 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);
      }
    }
  }
  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;
  }
Exemplo n.º 4
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());
  }
  @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);
  }
Exemplo n.º 6
0
  @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());
  }
Exemplo n.º 7
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()));
  }
  private static ArtifactInformation makeMock(
      final String id,
      final String groupId,
      final String artifactId,
      final String version,
      final String snapshotVersion,
      final String extension,
      final String classifier) {
    final Map<MetaKey, String> md = new HashMap<>();

    if (groupId != null) {
      md.put(MavenLocator.KEY_GROUP_ID, groupId);
    }
    if (artifactId != null) {
      md.put(MavenLocator.KEY_ARTIFACT_ID, artifactId);
    }
    if (version != null) {
      md.put(MavenLocator.KEY_VERSION, version);
    }
    if (snapshotVersion != null) {
      md.put(MavenLocator.KEY_SNAPSHOT_VERSION, snapshotVersion);
    }
    if (extension != null) {
      md.put(MavenLocator.KEY_EXTENSION, extension);
    }
    if (classifier != null) {
      md.put(MavenLocator.KEY_CLASSIFIER, classifier);
    }

    return new ArtifactInformation(
        id, null, null, id, 0L, Instant.now(), emptySet(), emptyList(), emptyMap(), md, null);
  }
Exemplo n.º 9
0
@RunWith(KeywhizTestRunner.class)
public class SessionLogoutResourceTest {
  @Inject ObjectMapper mapper;
  @Inject GCMEncryptor GCMEncryptor;
  @Inject @SessionCookie CookieConfig sessionCookieConfig;

  Clock clock = Clock.fixed(Instant.now(), ZoneId.of("UTC"));
  AuthenticatedEncryptedCookieFactory cookieFactory;
  CookieAuthenticator cookieAuthenticator;
  SessionLogoutResource sessionLogoutResource;

  @Before
  public void setUp() throws Exception {
    cookieFactory =
        new AuthenticatedEncryptedCookieFactory(clock, mapper, GCMEncryptor, sessionCookieConfig);
    cookieAuthenticator = new CookieAuthenticator(mapper, GCMEncryptor);
    sessionLogoutResource = new SessionLogoutResource(cookieAuthenticator, cookieFactory);
  }

  @Test
  public void logoutResourceDeletesSessionCookie() throws Exception {
    NewCookie cookie =
        cookieFactory.getSessionCookie(User.named("Me"), ZonedDateTime.now(clock).plusDays(1));
    Response response = sessionLogoutResource.logout(cookie);

    assertThat(response.getStatus()).isEqualTo(303);

    String resultCookie = response.getMetadata().getFirst("Set-Cookie").toString();
    assertThat(resultCookie)
        .contains("HttpOnly")
        .contains("Secure")
        .contains("Path=/admin;")
        .contains("session=expired;");
  }
}
Exemplo n.º 10
0
  @Test
  public void testInstant() {
    // millisec since epoch
    long timestamp = System.currentTimeMillis();

    // point in time - now!
    Instant instant = Instant.now();
    long secEpoch = instant.getEpochSecond();

    // missing milli so divide by 1000
    Assert.assertEquals(timestamp / 1000, secEpoch);
    Assert.assertEquals(instant.getLong(ChronoField.INSTANT_SECONDS), secEpoch);

    Instant timestampInstant = Instant.ofEpochMilli(timestamp);
    Assert.assertEquals(timestamp, timestampInstant.truncatedTo(ChronoUnit.MILLIS).toEpochMilli());

    // different ways to go into the future
    Instant future1 = instant.plusMillis(1000);
    Instant future2 = instant.plus(1000, ChronoUnit.MILLIS);
    // add Duration instead of Period as this example is dealing with time
    Instant future3 = instant.plus(Duration.ofMillis(1000));
    Instant future4 = instant.plus(Duration.of(1000, ChronoUnit.MILLIS));

    // all futures are the same!
    Assert.assertEquals(future1, future2);
    Assert.assertEquals(future2, future3);
    Assert.assertEquals(future3, future4);
  }
Exemplo n.º 11
0
  @Test
  public void person_missing_in_SPAR() throws Exception {
    Optional<SparResult> existing = fakeSparService.findBy(MISSING_PERSONAL_IDENTIFIER);
    assertThat(existing, isAbsent());

    Map<String, Object> properties = new HashMap<>();
    properties.put("personalIdentifier", MISSING_PERSONAL_IDENTIFIER);
    properties.put("ocr", OCR);

    runtimeService.startProcessInstanceByMessage("create-insurance", OCR, properties);

    when_all_jobs_within_X_days_are_executed(10);

    List<Message> messages = outbox.receivedAfter(Instant.now().minus(Duration.ofHours(1)));

    assertThat(messages, hasSize(1));
    String payload = messages.get(0).getPayload();
    assertThat(payload, isJson(withProperty("messageType", equalTo("\"person-does-not-exist\""))));
    assertThat(
        payload,
        isJson(
            withProperty(
                "personalIdentifier",
                equalTo("\"" + MISSING_PERSONAL_IDENTIFIER.getValue() + "\""))));
    assertThat(payload, isJson(withProperty("ocr", equalTo("\"" + OCR + "\""))));
  }
Exemplo n.º 12
0
  @Test
  public void testMixinIcon() throws Exception {
    byte[] data = Resources.toByteArray(getClass().getResource("mixinicon.png"));
    final Icon icon = Icon.from(data, "image/png", Instant.now());

    Mixin mixin =
        Mixin.create()
            .name("myapplication:postal_code")
            .displayName("My content type")
            .icon(icon)
            .addFormItem(
                Input.create()
                    .name("postal_code")
                    .label("Postal code")
                    .inputType(InputTypeName.TEXT_LINE)
                    .build())
            .build();
    setupMixin(mixin);

    // exercise
    final Response response = this.resource.getIcon("myapplication:postal_code", 20, null);
    final BufferedImage mixinIcon = (BufferedImage) response.getEntity();

    // verify
    assertImage(mixinIcon, 20);
  }
Exemplo n.º 13
0
 void storeTimestampOfLastExport(ODocument workItem) {
   store.setFields(
       workItem, //
       of(
           FieldNames.JIRA_EXPORT_TIMESTAMP,
           StorageQuery.getField(workItem, FieldNames.MODIFIED, Date.from(Instant.now()))));
 }
Exemplo n.º 14
0
 public void dispose() throws SaslException {
   previousHash = null;
   previousSeed = null;
   if (locked && (Instant.now().getEpochSecond() < (time + LOCK_TIMEOUT))) {
     updateTimeout(0);
   }
 }
  @Test
  public void testDomainEventEntry_WrapEventsCorrectly() {
    Serializer serializer = new XStreamSerializer();

    String payload = "Payload";
    MetaData metaData = new MetaData(Collections.singletonMap("Key", "Value"));
    DomainEventMessage<String> event =
        new GenericDomainEventMessage<>(
            "type",
            randomUUID().toString(),
            2L,
            payload,
            metaData,
            randomUUID().toString(),
            Instant.now());

    DomainEventEntry eventEntry = new DomainEventEntry(event, serializer);

    assertEquals(event.getAggregateIdentifier(), eventEntry.getAggregateIdentifier());
    assertEquals(event.getSequenceNumber(), eventEntry.getSequenceNumber());
    assertEquals(event.getTimestamp(), eventEntry.getTimestamp());
    assertEquals(payload, serializer.deserialize(eventEntry.getPayload()));
    assertEquals(metaData, serializer.deserialize(eventEntry.getMetaData()));
    assertEquals(byte[].class, eventEntry.getPayload().getContentType());
  }
  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};
  }
Exemplo n.º 17
0
 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);
 }
  @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);
  }
  @Test
  public void testGetTrackerDataDailyAgg() {
    List<TrackerData> trackerDataList =
        Arrays.asList(
            new TrackerData(Instant.now().minus(Duration.ofDays(2)), 9),
            new TrackerData(Instant.now(), 11),
            new TrackerData(Instant.now(), 12));
    when(trackerDAO.findTrackerData()).thenReturn(trackerDataList);

    Map<LocalDate, Integer> expectedResult = new HashMap<>();
    expectedResult.put(LocalDate.now().minusDays(2), 9);
    expectedResult.put(LocalDate.now(), 23);

    Map<LocalDate, Integer> result = trackerService.getTrackerDailyDataAgg();
    assertEquals(2, result.size());
    assertEquals(expectedResult, result);
  }
Exemplo n.º 20
0
  public static void main(String[] args) {
    Instant before = Instant.now();

    langDetection = new LangDetection();
    File filesdir = new File("/Users/ruben/Desktop/lang");

    int total = getFilesCount(filesdir);
    int welldetected = getFilesWellDetected(filesdir.listFiles());

    System.out.println(
        "total: "
            + total
            + " well detected: "
            + welldetected
            + " in "
            + Duration.between(before, Instant.now()));
  }
 private TodoItem createTodoItem() {
   return new TodoItem.Builder()
       .id(TodoItemId.generate())
       .title("some todo")
       .completed(false)
       .created(Instant.now().toEpochMilli())
       .build();
 }
Exemplo n.º 22
0
 private TradeReport report(ArrayTable<Integer, Integer, Result<?>> table) {
   return TradeReport.builder()
       .columnHeaders("col0", "col1")
       .data(table)
       .valuationDate(LocalDate.now())
       .runInstant(Instant.now())
       .build();
 }
Exemplo n.º 23
0
 @Test
 public void shouldValidateTokenWithLeewayCheck() {
   // given
   final JsonObject jsonObject = new JsonObject();
   jsonObject.addProperty(JWTConstants.EXPIRATION, Instant.now().plusSeconds(7).getEpochSecond());
   // when
   expirationChecker.check(jsonObject);
 }
Exemplo n.º 24
0
 /**
  * Get a JdbConnection object either by the ones available in the queue or replace the first
  * expired connection. When a connection is given to a client, it is tagged with the current time.
  * This enables us to check the duration it has been out and replace if required.
  *
  * @return JDBConnection This contains the actual jdbc connection object to db.
  * @throws ConnectionPoolException Throws if no available connections
  */
 public synchronized JdbConnection borrow() throws ConnectionPoolException {
   if (pooled.size() > 0) {
     borrowed.put(pooled.peek(), Instant.now());
     return pooled.removeFirst();
   } else {
     return createReplacementIfExpiredConnFound();
   }
 }
Exemplo n.º 25
0
 public boolean applyTimeout(
     User issuingUser, Channel noticeChannel, Server server, User user, Duration duration) {
   String serverId = server.getId();
   if (duration != null && !duration.isNegative() && !duration.isZero()) {
     ServerTimeout timeout =
         new ServerTimeout(
             duration,
             Instant.now(),
             user.getId(),
             serverId,
             user.getUsername(),
             issuingUser.getId());
     TempServerConfig serverConfig = serverStorage.get(serverId);
     if (serverConfig == null) {
       serverConfig = new TempServerConfig(serverId);
       serverStorage.put(serverId, serverConfig);
     }
     ServerTimeoutStorage storage = serverConfig.getServerTimeouts();
     if (storage == null) {
       storage = new ServerTimeoutStorage();
       serverConfig.setServerTimeouts(storage);
     }
     if (applyTimeoutRole(user, server, noticeChannel)) {
       storage.getTimeouts().put(user.getId(), timeout);
       ScheduledFuture future =
           timeoutService.schedule(
               () -> onTimeoutExpire(user, server), duration.getSeconds(), TimeUnit.SECONDS);
       timeout.setTimerFuture(future);
       saveServerConfig(serverConfig);
       String durationStr = formatDuration(duration);
       String instantStr = formatInstant(timeout.getEndTime());
       String msg =
           loc.localize(
               "commands.mod.timeout.response",
               user.getUsername(),
               user.getId(),
               durationStr,
               instantStr);
       apiClient.sendMessage(msg, noticeChannel);
       LOGGER.info(
           "[{}] '{}': Timing out {} ({}) for {} (until {}), issued by {} ({})",
           serverId,
           server.getName(),
           user.getUsername(),
           user.getId(),
           durationStr,
           instantStr,
           issuingUser.getUsername(),
           issuingUser.getId());
     }
     //  No else with error - applyTimeoutRole does that for us
     return true;
   } else {
     LOGGER.warn("Invalid duration format");
   }
   return false;
 }
Exemplo n.º 26
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));
   }
 }
Exemplo n.º 27
0
  private Media createMedia(
      final String id, final String contentPath, final Attachment... attachments) {
    final PropertyTree data = new PropertyTree();
    data.addString("media", attachments[0].getName());

    return Media.create()
        .id(ContentId.from(id))
        .path(contentPath)
        .createdTime(Instant.now())
        .type(ContentTypeName.imageMedia())
        .owner(PrincipalKey.from("user:myStore:me"))
        .displayName("My Content")
        .modifiedTime(Instant.now())
        .modifier(PrincipalKey.from("user:system:admin"))
        .data(data)
        .attachments(Attachments.from(attachments))
        .build();
  }
Exemplo n.º 28
0
 @Test
 public void createValidThing() throws Exception {
   Thing thing = new Thing();
   thing.setName("simon");
   thing.setAmount(6);
   thing.setDueDate(Date.from(Instant.now().plus(1, ChronoUnit.DAYS)));
   thing.setTags(Collections.singletonList("super"));
   thingManager.create(thing);
 }
Exemplo n.º 29
0
 @Override
 public void createOrUpdateItem(ODocument item) throws Exception {
   String workItemId = item.field(FieldNames.ID);
   ensureWorkItemWithId(Integer.parseInt(workItemId));
   Date modified = StorageQuery.getField(item, FieldNames.MODIFIED, Date.from(Instant.now()));
   Date lastExport = StorageQuery.getField(item, FieldNames.JIRA_EXPORT_TIMESTAMP, new Date(0));
   if (modified.compareTo(lastExport) > 0) {
     updateItem(item);
   }
 }
Exemplo n.º 30
0
 @Test
 public void shouldFailForExpiredToken() {
   // expect
   expectedException.expect(ExpiredTokenException.class);
   // given
   final JsonObject jsonObject = new JsonObject();
   jsonObject.addProperty(JWTConstants.EXPIRATION, Instant.now().minusSeconds(7).getEpochSecond());
   // when
   expirationChecker.check(jsonObject);
 }