Ejemplo n.º 1
0
  public static void main(String[] args) {

    // Current Date
    LocalDateTime today = LocalDateTime.now();
    System.out.println("Current DateTime=" + today);

    // Current Date using LocalDate and LocalTime
    today = LocalDateTime.of(LocalDate.now(), LocalTime.now());
    System.out.println("Current DateTime=" + today);

    // Creating LocalDateTime by providing input arguments
    LocalDateTime specificDate = LocalDateTime.of(2014, Month.JANUARY, 1, 10, 10, 30);
    System.out.println("Specific Date=" + specificDate);

    // Try creating date by providing invalid inputs
    // LocalDateTime feb29_2014 = LocalDateTime.of(2014, Month.FEBRUARY, 28,
    // 25,1,1);
    // Exception in thread "main" java.time.DateTimeException:
    // Invalid value for HourOfDay (valid values 0 - 23): 25

    // Current date in "Asia/Kolkata", you can get it from ZoneId javadoc
    LocalDateTime todayKolkata = LocalDateTime.now(ZoneId.of("Asia/Kolkata"));
    System.out.println("Current Date in IST=" + todayKolkata);

    // java.time.zone.ZoneRulesException: Unknown time-zone ID: IST
    // LocalDateTime todayIST = LocalDateTime.now(ZoneId.of("IST"));

    // Getting date from the base date i.e 01/01/1970
    LocalDateTime dateFromBase = LocalDateTime.ofEpochSecond(10000, 0, ZoneOffset.UTC);
    System.out.println("10000th second time from 01/01/1970= " + dateFromBase);
  }
Ejemplo n.º 2
0
 @RequestMapping(value = "/{templateName}/{cmsName}", method = POST)
 public String sendEmail(
     DownloadRequest downloadRequest,
     @PathVariable String templateName,
     @PathVariable String cmsName) {
   downloadRequest.setTemplateName(templateName);
   downloadRequest.setCms(cmsName);
   downloadRequest.setCreated(LocalDateTime.now());
   logger.info("New download request: {}", downloadRequest);
   downloadRequest = downloadRequestRepository.save(downloadRequest);
   long timestamp = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
   String hash =
       downloadRequestParamsHasher.getHash(
           Template.valueOf(templateName).getDownloadName(),
           Cms.valueOf(cmsName).getNamePl(),
           timestamp);
   HtmlEmailMessage htmlEmailMessage =
       new HtmlEmailMessage(
           "*****@*****.**",
           downloadRequest.getAdministrativeEmail(),
           "Szablon CMS ze strony PWD",
           getEmailMessageTemplate(),
           getEmailMessageModelMap(
               templateName,
               Template.valueOf(templateName).getDownloadName(),
               Cms.valueOf(cmsName).getNamePl(),
               hash,
               timestamp));
   if (mailgunClient.sendEmail(htmlEmailMessage)) {
     return "email_download";
   }
   return "error";
 }
  private boolean isInSuggestedChangeRange(Event e) {
    LocalDateTime max =
        LocalDateTime.now()
            .minusHours(LocalDateTime.now().getHour())
            .plusDays(ServiceVariables.SUGGESTED_CHANGE_RANGE_DAYS_BEFORE_START + 1);

    return e.getStart().isBefore(max);
  }
 @Override
 public void generateToken(VerificationToken verificationToken) {
   verificationToken.setExpiredTime(
       LocalDateTime.now().plusSeconds(VerificationToken.EXPIRED_PERIOD));
   String unhashedToken =
       verificationToken.getEmail() + verificationToken.getType() + LocalDateTime.now();
   String token = VerificationTokenUtil.getHash(unhashedToken, VerificationTokenUtil.SHA_256);
   verificationToken.setToken(token);
 }
Ejemplo n.º 5
0
  @Test
  public void testLocalDateTime() {
    System.out.println(LocalDateTime.now());
    System.out.println(LocalDateTime.of(1994, Month.MAY, 15, 11, 30));
    System.out.println(LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault()));
    System.out.println(LocalDateTime.ofEpochSecond(1450749600, 0, ZoneOffset.ofHours(8)));

    System.out.printf("6 months from now: %s%n", LocalDateTime.now().plusMonths(6));
    System.out.printf("6 days ago: %s%n", LocalDateTime.now().minusDays(6));

    System.out.println(DateTimeFormatter.ISO_DATE_TIME.format(LocalDateTime.now()));
    System.out.println(DateTimeFormatter.ofPattern("MM-dd HH:mm").format(LocalDateTime.now()));
  }
Ejemplo n.º 6
0
  public int checkToken(String s) {
    Token token = tokenMap.get(s);
    if (token == null) {
      return -1; // 无此token
    }
    if (token.expiredTime.isBefore(LocalDateTime.now())) { // token过期
      tokenMap.remove(s);
      return -1;
    }
    token.expiredTime = LocalDateTime.now().plusHours(TOKEN_LIVE_HOURS); // 更新token过期时间

    return token.userId;
  }
Ejemplo n.º 7
0
 @Override
 public boolean solve(final Object solver, long res) {
   if ((res < (1L << 52)) && (solver != null)) {
     {
       final IDMap<Object> solvers = MappedDatabase.this.solvers;
       final int sid;
       synchronized (solvers) {
         if (solvers.containsKey(solver)) sid = solvers.get(solver);
         else {
           sid = solvers.map(solver);
           final LocalDateTime now = LocalDateTime.now();
           solverLog.printf(
               "%04d-%02d-%02d %02d:%02d SOLVER #%4d: %s\n",
               now.getYear(),
               now.getMonthValue(),
               now.getDayOfMonth(),
               now.getHour(),
               now.getMinute(),
               sid,
               solver);
         }
       }
       res |= (long) sid << 52;
     }
     final long spec = (getSpec() << 20) | timestamp(LocalDateTime.now());
     final LongBuffer db = MappedDatabase.this.db;
     final int idx = this.idx;
     synchronized (db) {
       if (((db.get(idx) ^ spec) >> 20) == 0L) {
         if (db.get(idx + 1) == 0L) {
           db.put(idx, spec);
           db.put(idx + 1, res);
         } else {
           final DataOutput dupStream = MappedDatabase.this.dupStream;
           if (dupStream != null) {
             try {
               dupStream.writeLong(spec);
               dupStream.writeLong(res);
             } catch (final Exception e) {
               System.err.printf(
                   "Duplicate result: %010X: %013X by %s\n", spec >>> 25, res, solver);
             }
           }
         }
         return true;
       }
     }
   }
   System.err.printf("Result report error: %010X: %013X by %s\n", getSpec() >>> 5, res, solver);
   return false;
 } // solve()
Ejemplo n.º 8
0
  @Around("execution(@com.marcolenzo.gameboard.annotations.ActionLoggable * *(..))")
  public Object around(ProceedingJoinPoint point) throws Throwable {
    long start = System.currentTimeMillis();
    Object result = point.proceed();

    User currentUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    Action action = new Action();
    action.setName(MethodSignature.class.cast(point.getSignature()).getMethod().getName());

    // Parse args
    List<String> jsonStrings = Lists.newArrayList();
    for (Object obj : point.getArgs()) {

      jsonStrings.add(mapper.writeValueAsString(obj));
    }
    action.setArgs(jsonStrings);
    action.setResult(mapper.writeValueAsString(result));

    action.setUserId(currentUser.getId());
    action.setDatetime(LocalDateTime.now());

    repository.save(action);

    LOGGER.info(
        "#{}({}): in {} ms by {}",
        MethodSignature.class.cast(point.getSignature()).getMethod().getName(),
        point.getArgs(),
        System.currentTimeMillis() - start,
        currentUser.getId() + " " + currentUser.getEmail());

    return result;
  }
  @Test
  public void testSigning()
      throws IOException, URISyntaxException, StorageException, InvalidKeyException {
    CloudBlobContainer container = binaryManager.container;
    Binary binary = binaryManager.getBinary(Blobs.createBlob(CONTENT));
    assertNotNull(binary);

    CloudBlockBlob blockBlobReference = container.getBlockBlobReference(CONTENT_MD5);
    SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
    policy.setPermissionsFromString("r");

    // rscd content-dispositoon
    // rsct content-type

    Instant endDateTime =
        LocalDateTime.now().plusHours(1).atZone(ZoneId.systemDefault()).toInstant();
    policy.setSharedAccessExpiryTime(Date.from(endDateTime));

    SharedAccessBlobHeaders headers = new SharedAccessBlobHeaders();
    headers.setContentDisposition("attachment; filename=\"blabla.txt\"");
    headers.setContentType("text/plain");

    String something = blockBlobReference.generateSharedAccessSignature(policy, headers, null);
    System.out.println(something);

    CloudBlockBlob blob =
        new CloudBlockBlob(
            blockBlobReference.getUri(), new StorageCredentialsSharedAccessSignature(something));

    System.out.println(blob.getQualifiedUri());
  }
Ejemplo n.º 10
0
 @Override
 public void process(TimedAction<TimedEvent> action) {
   scheduledExecutorService.schedule(
       () -> targetActionProcessor.process(action.getTargetAction()),
       Duration.between(LocalDateTime.now(), action.getDateTime()).toMillis(),
       TimeUnit.MILLISECONDS);
 }
Ejemplo n.º 11
0
 /**
  * The main method.
  *
  * @param args the arguments
  */
 public static void main(String[] args) {
   try {
     FEMultiplayer game = new FEMultiplayer();
     //			SoundTrack.enabled = false;
     game.init(480, 320, "Fire Emblem Multiplayer");
     /* Testing code */
     //			game.testFightStage();
     //			game.testOverworldStage();
     //			game.testDraftStage();
     game.loop();
   } catch (Exception e) {
     System.err.println("Exception occurred, writing to logs...");
     e.printStackTrace();
     try {
       File errLog =
           new File(
               "error_log_client"
                   + LocalDateTime.now().toString().replace("T", "@").replace(":", "-")
                   + ".log");
       PrintWriter pw = new PrintWriter(errLog);
       e.printStackTrace(pw);
       pw.close();
     } catch (IOException e2) {
       e2.printStackTrace();
     }
     System.exit(0);
   }
 }
Ejemplo n.º 12
0
  @Test
  public void timeout() {
    Jcl jcl =
        JclFactory.compileJcl(
            JOB
                + "## run at 2016-2-10 18:24 timeout 1 minute\n"
                + "## run at 2016/2/10 18:24 timeout 1 hour\n"
                + "## run every minute timeout minute\n"
                + "## run every 10 minutes timeout 5 minutes\n");
    test(jcl);

    System.out.println(jcl.getSchedule().replace("><", ">\n<"));

    assertSame(JclType.SCHEDULABLE, jcl.getType());

    LocalDateTime dt = LocalDateTime.now().truncatedTo(ChronoUnit.MINUTES);
    String now = dt.toLocalDate().toString() + " " + dt.toLocalTime().toString();

    assertEquals(
        "Schedule",
        "<schedule>"
            + "<once at=\"2016-02-10 18:24\" timeout=\"1 minute\"/>"
            + "<once at=\"2016-02-10 18:24\" timeout=\"1 hour\"/>"
            + "<repeat next=\""
            + now
            + "\" step=\"1 minute\" timeout=\"1 minute\"/>"
            + "<repeat next=\""
            + now
            + "\" step=\"10 minute\" timeout=\"5 minute\"/>"
            + "</schedule>",
        jcl.getSchedule());
  }
Ejemplo n.º 13
0
  static LocalDateTime parse(String endDateTimeString) {

    String endDateString = null;
    String endTimeString = null;

    Pattern pattern = Pattern.compile(DATE_TIME_PATTERN);
    Matcher matcher = pattern.matcher(endDateTimeString);

    matcher.find();
    endDateString = matcher.group(1);
    endTimeString = matcher.group(2);

    if (endDateString == null) {
      endDateString = "today";
    }

    if (endTimeString == null) {
      endTimeString = END_TIME_DEFAULT;
    }

    LocalDate endDate = DateParser.parse(endDateString);
    LocalTime endTime = TimeParser.parse(endTimeString);

    LocalDateTime endDateTime = endDate.atTime(endTime);

    if (endDateTime.isBefore(LocalDateTime.now())) {
      endDateTime = endDateTime.plusDays(1);
    }

    return endDateTime;
  }
Ejemplo n.º 14
0
  @CacheEvict(value = "users", allEntries = true)
  public User updateProfile(ProfileUpdateRequest request, AuthorizedUser updatedBy) {
    User user = userRepository.findByIdForUpdate(request.getUserId());
    if (user == null) {
      throw new IllegalArgumentException("The user does not exist");
    }

    User duplicate;
    if (!ObjectUtils.nullSafeEquals(request.getEmail(), user.getEmail())) {
      duplicate = userRepository.findByEmail(request.getEmail());
      if (duplicate != null) {
        throw new DuplicateEmailException(request.getEmail());
      }
    }
    if (!ObjectUtils.nullSafeEquals(request.getLoginId(), user.getLoginId())) {
      duplicate = userRepository.findByLoginId(request.getLoginId());
      if (duplicate != null) {
        throw new DuplicateLoginIdException(request.getLoginId());
      }
    }

    user.setEmail(request.getEmail());
    user.setLoginId(request.getLoginId());
    user.setName(request.getName());
    user.setUpdatedAt(LocalDateTime.now());
    user.setUpdatedBy(updatedBy.toString());
    return userRepository.saveAndFlush(user);
  }
Ejemplo n.º 15
0
  private static void executeJob(String jobId) {
    long execID = 0;
    // ジョブの開始時はXML読み込みなど同時実行されるとおかしくなる処理があるので、ジョブID単位で同期化しておく。
    JobOperator jobOperator = BatchRuntime.getJobOperator();
    synchronized (jobId) {
      Properties props = new Properties();
      props.setProperty(
          "date", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
      execID = jobOperator.start(jobId, props);
      System.out.println("job stated id:" + execID);
    }
    JobExecution jobExec = null;
    // ジョブが終了するまでポーリング
    while (true) {
      jobExec = jobOperator.getJobExecution(execID);

      if (jobExec.getEndTime() != null) {
        break;
      }

      try {
        Thread.sleep(1000L);
      } catch (InterruptedException ex) {
      }
    }
    System.out.println("JOB END:Status is " + jobExec.getExitStatus());
  }
Ejemplo n.º 16
0
  /**
   * Build method for a request
   *
   * @param reference
   * @param customer
   * @param goods
   * @param departure
   * @param arrival
   * @param ruleVersion
   * @return
   */
  public static Request build(
      Long id,
      String reference,
      Customer customer,
      Goods goods,
      Destination departure,
      Destination arrival,
      AgreementRuleAud ruleVersion) {
    Request r = new Request();
    r.id = id;
    r.version = 1;
    r.reference = reference;
    r.customer = customer;
    r.goods = goods;
    r.departure = departure;
    r.arrival = arrival;
    r.ruleAud = ruleVersion;
    r.overallStatus = RequestOverallStatus.WAITING_FOR_VALIDATION;
    r.agreementStatus = RequestAgreementStatus.PENDING;
    r.nextAgreementVisaRank = 0;
    r.agreementVisas = new ArrayList<>();

    LocalDateTime date = LocalDateTime.now();
    r.creationDate = date;
    r.updateDate = date;

    String customerUid = customer == null ? null : customer.getUid();
    r.creationUser = customerUid;
    r.updateUser = customerUid;

    r.checkValues();

    return r;
  }
Ejemplo n.º 17
0
 public void updateBettingMatch(UpdateBettingMatchInfo updateBettingMatchInfo) {
   BettingMatch bettingMatch =
       bettingMatchRepo.findOne(updateBettingMatchInfo.getBettingMatchId());
   if (!bettingMatch.isActivated()) {
     if (updateBettingMatchInfo.getExpiredTime().isAfter(LocalDateTime.now())) {
       Group group = groupRepo.findOne(updateBettingMatchInfo.getGroupId());
       Match match = matchRepo.findOne(updateBettingMatchInfo.getMatchId());
       if (balanceIsValid(updateBettingMatchInfo.getBalance1())
           && balanceIsValid(updateBettingMatchInfo.getBalance2())) {
         if (isExistedInTournament(match, group)) {
           bettingMatch.setBalance1(updateBettingMatchInfo.getBalance1());
           bettingMatch.setBalance2(updateBettingMatchInfo.getBalance2());
           bettingMatch.setExpiredTime(updateBettingMatchInfo.getExpiredTime());
           bettingMatch.setBetAmount(updateBettingMatchInfo.getBetAmount());
           bettingMatch.setMatch(match);
           bettingMatch.setGroup(group);
           bettingMatch.setDescription(updateBettingMatchInfo.getDecription());
           bettingMatch.setActivated(updateBettingMatchInfo.isActivated());
           bettingMatchRepo.save(bettingMatch);
         } else {
           throw new DataInvalidException("exception.match.group.invalid");
         }
       } else {
         throw new DataInvalidException("exception.balance.in.valid");
       }
     } else {
       throw new DataInvalidException("exception.expiredTime.invalid");
     }
   } else {
     throw new DataInvalidException("exception.betting.match.is.actived");
   }
 }
Ejemplo n.º 18
0
 public boolean isBettingMatchNotExpired(Long bettingMatchId) {
   BettingMatch bettingMatch = bettingMatchRepo.findOne(bettingMatchId);
   if (bettingMatch.getExpiredTime().isAfter(LocalDateTime.now())) {
     return true;
   }
   return false;
 }
Ejemplo n.º 19
0
  @Test
  @WithMockUser(roles = "Tutor")
  public void currentMonthBalanceMultipleAppointments() throws Exception {
    Appointment testAppointment1 = new Appointment();
    Appointment testAppointment2 = new Appointment();

    LocalDateTime dateTime = LocalDateTime.now();

    testAppointment1.setAvailability(Availability.ARRANGED);
    testAppointment1.setTutor(TestUtility.testUser);
    testAppointment1.setStudent(TestUtility.testUserTwo);
    testAppointment1.setWage(BigDecimal.TEN);
    testAppointment1.setDay(dateTime.getDayOfWeek());
    testAppointment1.setTimestamp(Timestamp.valueOf(dateTime));

    appointmentDao.save(testAppointment1);

    testAppointment2.setAvailability(Availability.ARRANGED);
    testAppointment2.setTutor(TestUtility.testUser);
    testAppointment2.setStudent(TestUtility.testUserTwo);
    testAppointment2.setWage(BigDecimal.TEN);
    testAppointment2.setDay(dateTime.getDayOfWeek());
    testAppointment2.setTimestamp(Timestamp.valueOf(dateTime.minusHours(1)));

    appointmentDao.save(testAppointment2);

    BigDecimal reference = BigDecimal.TEN.multiply(ConstantVariables.PERCENTAGE);
    reference = reference.add(BigDecimal.TEN.multiply(ConstantVariables.PERCENTAGE));

    mockMvc
        .perform(get("/bill").principal(this.authUser))
        .andExpect(model().attribute("balance", reference.setScale(2)));
  }
Ejemplo n.º 20
0
 public GameTablePlayer(GameTable table, Player player, Integer seat) {
   this.gameTable = table;
   this.player = player;
   this.seat = seat;
   this.entryDate = LocalDateTime.now();
   this.playerStatus = PlayerStatusEnumeration.SITTING;
 }
  @Override
  public String convert(LocalDateTime dateTime) {
    LocalDateTime now = LocalDateTime.now();
    Duration duration = Duration.between(dateTime, now);

    Period period = Period.between(dateTime.toLocalDate(), now.toLocalDate());

    if (duration.toMinutes() < 1) {
      return String.format("%s secs ago", duration.getSeconds());
    }

    if (duration.toHours() < 1) {
      return String.format("%s mins ago", duration.toMinutes());
    }

    if (duration.toDays() < 1) {
      return String.format("%s hrs ago", duration.toHours());
    }

    if (period.getYears() > 0) {
      return DateTimeFormatter.ISO_LOCAL_DATE.format(dateTime);
    }

    if (period.getMonths() > 0) {
      return String.format("%s months ago", period.getMonths());
    }

    return String.format("%s days ago", period.getDays());
  }
Ejemplo n.º 22
0
  public void localDateTimeTest() {
    LocalDateTime currentTime = LocalDateTime.now();

    System.out.println(currentTime);

    System.out.println(currentTime.format(formatter));
  }
 private void updateExchangeDetails(
     DirectBookExchange directBookExchange, Book bookRequestedInExchange) {
   directBookExchange.setBookOfferedInExchange(bookRequestedInExchange);
   directBookExchange.setOver(true);
   directBookExchange.setSuccessful(true);
   directBookExchange.setDateCompleted(LocalDateTime.now());
 }
Ejemplo n.º 24
0
  @Override
  public void update(NoticeRequestDTO noticeDTO) throws OperationalException {
    LocalDateTime currentTime = LocalDateTime.now();
    Notice notice = findById(noticeDTO.getNoticeId());
    if (notice == null) {
      throw new OperationalException(
          HttpConstants.NOT_FOUND, ResponseConstants.INVALID_NOTICE_ID, HttpStatus.NOT_FOUND);
    }
    assertEnum(noticeDTO.getStatus(), NoticeStatus.class, ResponseConstants.INVALID_STATUS);
    loadNoticeDetails(noticeDTO, notice);

    User user;
    if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() != null) {
      user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    } else {
      user = userDao.getActiveUserDetails(noticeDTO.getModifiedBy());
      if (user == null) {
        throw new OperationalException(
            HttpConstants.NOT_FOUND, ResponseConstants.INVALID_MODIFIED_BY, HttpStatus.NOT_FOUND);
      }
    }

    String status = noticeDTO.getStatus();
    if (!StringUtils.isBlank(status) && status.equals(NoticeStatus.ACTIVE.name())) {
      notice.setApprovedDate(currentTime);
      notice.setApprovedBy(user);
    }
    NoticeHistory history =
        new NoticeHistory(notice, notice.getStatus(), noticeDTO.getNotes(), currentTime, user);
    notice.getHistory().add(history);
    super.update(notice);
  }
 @Override
 public void SendDMX(byte[] data) {
   lastDMX = data;
   lastUpdateTime = LocalDateTime.now();
   SendDMXInternal();
   SendLastUpdateTime();
 }
Ejemplo n.º 26
0
  @Test
  public void testCookieBuilder() {
    // given
    LocalDateTime now = LocalDateTime.now();

    // when
    Cookie cookie =
        CookieBuilder.create()
            .name("foo")
            .value("bar")
            .path("/foobar")
            .domain("www.foo.com")
            .maxAge(1223)
            .expires(now)
            .discard(true)
            .secure(true)
            .httpOnly(true)
            .build();

    // then
    assertThat(cookie, not(nullValue()));
    assertThat("foo", equalTo(cookie.getName()));
    assertThat("bar", equalTo(cookie.getValue()));
    assertThat("/foobar", equalTo(cookie.getPath()));
    assertThat("www.foo.com", equalTo(cookie.getDomain()));
    assertThat(
        Date.from(now.atZone(ZoneId.systemDefault()).toInstant()), equalTo(cookie.getExpires()));
    assertThat(cookie.getMaxAge(), equalTo(1223));
    assertThat(cookie.isDiscard(), equalTo(true));
    assertThat(cookie.isSecure(), equalTo(true));
    assertThat(cookie.isHttpOnly(), equalTo(true));
  }
Ejemplo n.º 27
0
  public Optional<String> toImageBlock(Image image) {

    if (!current.currentPath().isPresent()) asciiDocController.saveDoc();

    Path currentPath = current.currentPath().map(Path::getParent).get();
    IOHelper.createDirectories(currentPath.resolve("images"));

    List<String> buffer = new LinkedList<>();
    DateTimeFormatter dateTimeFormatter =
        DateTimeFormatter.ofPattern(asciiDocController.getClipboardImageFilePattern());
    Path path = Paths.get(dateTimeFormatter.format(LocalDateTime.now()));

    Path targetImage = currentPath.resolve("images").resolve(path.getFileName());

    try {
      BufferedImage fromFXImage = SwingFXUtils.fromFXImage(image, null);
      ImageIO.write(fromFXImage, "png", targetImage.toFile());

    } catch (Exception e) {
      logger.error("Problem occured while saving clipboard image {}", targetImage);
    }

    buffer.add(String.format("image::images/%s[]", path.getFileName()));

    if (buffer.size() > 0) return Optional.of(String.join("\n", buffer));

    return Optional.empty();
  }
Ejemplo n.º 28
0
  @Override
  public Data process(Data data) {

    Data item = DataFactory.create();
    item.put("time", LocalDateTime.now().toString());

    String[] evKeys = {"@stream"};
    for (String key : evKeys) {
      if (data.containsKey(key)) {
        item.put(key, data.get(key));
      }
    }

    // add objects by specified keys to data item
    for (String key : keys) {
      item.put(key, data.get(key));
    }

    try {
      if (writeBlock && !firstLine) {
        bw.write(",");
      }
      bw.write(gson.toJson(item));

      bw.newLine();
      bw.flush();
      firstLine = false;
    } catch (IOException ioex) {
      ioex.printStackTrace();
    }
    return data;
  }
Ejemplo n.º 29
0
 public Task(String description) {
   mDescription = description;
   mCompleted = false;
   mCreatedAt = LocalDateTime.now();
   instances.add(this);
   mId = instances.size(); // total size of the array( 5 tasks = size 5) not indiv. objects
 } // constructor has all the instructions for making a new instance of the class task
Ejemplo n.º 30
0
  public static String getTimeUntilNow(String time) {
    LocalDateTime now = LocalDateTime.now();
    now = now.plusMinutes(1);

    int hours = Integer.parseInt(time.split(":")[0]);
    int minutes = Integer.parseInt(time.split(":")[1]);

    LocalDateTime tocheck =
        LocalDateTime.of(
            now.getYear(),
            now.getMonth(),
            now.getDayOfMonth(),
            hours,
            minutes,
            now.getSecond(),
            now.getNano());

    if (tocheck.isBefore(now)) {
      tocheck = tocheck.plusDays(1);
    }

    Duration remaining = Duration.between(now, tocheck);

    int rh = (int) remaining.toHours();
    int rm = (int) remaining.toMinutes();
    rm %= 60;

    int ht = rh / 10;
    int hs = rh % 10;
    int mt = rm / 10;
    int ms = rm % 10;

    return ht + "" + hs + ":" + mt + "" + ms;
  }