/**
   * 返回one和two之间年的差距,以one为基准,每七天+1
   *
   * @param one
   * @param two
   * @return
   */
  public static Long getDiffYears(Date one, Date two) {
    if (one.after(two)) {
      return getDiffYears(two, one);
    }

    LocalDate startDate = one.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    LocalDate endDate = two.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

    return ChronoUnit.YEARS.between(startDate, endDate);
  }
Example #2
0
  @Test
  public void shouldStoreOnlyEffectiveACEs() throws Exception {
    buildAndIndexTree();

    DocumentModelList docs = ess.query(new NxQueryBuilder(session).nxql("select * from Document"));
    Assert.assertEquals(10, docs.totalSize());

    CoreSession restrictedSession = getRestrictedSession("toto");
    try {
      docs = ess.query(new NxQueryBuilder(restrictedSession).nxql("select * from Document"));
      Assert.assertEquals(0, docs.totalSize());

      DocumentRef ref = new PathRef("/folder0");
      ACP acp = new ACPImpl();
      ACL acl = ACPImpl.newACL(ACL.LOCAL_ACL);
      acl.add(ACE.builder("toto", SecurityConstants.READ).build());
      acp.addACL(acl);
      session.setACP(ref, acp, true);

      TransactionHelper.commitOrRollbackTransaction();
      waitForCompletion();

      startTransaction();
      docs =
          ess.query(
              new NxQueryBuilder(restrictedSession)
                  .nxql("select * from Document order by dc:title"));
      Assert.assertEquals(10, docs.totalSize());

      acp = new ACPImpl();
      acl = ACPImpl.newACL(ACL.LOCAL_ACL);
      // make the ACE archived
      Date now = new Date();
      Calendar begin = new GregorianCalendar();
      begin.setTimeInMillis(now.toInstant().minus(10, ChronoUnit.DAYS).toEpochMilli());
      Calendar end = new GregorianCalendar();
      end.setTimeInMillis(now.toInstant().minus(2, ChronoUnit.DAYS).toEpochMilli());
      acl.add(ACE.builder("toto", SecurityConstants.READ).begin(begin).end(end).build());
      acp.addACL(acl);
      session.setACP(ref, acp, true);

      TransactionHelper.commitOrRollbackTransaction();
      waitForCompletion();

      startTransaction();
      docs =
          ess.query(
              new NxQueryBuilder(restrictedSession)
                  .nxql("select * from Document order by dc:title"));
      Assert.assertEquals(0, docs.totalSize());
    } finally {
      restrictedSession.close();
    }
  }
Example #3
0
 @Override
 protected LocalDate doNormalize(Object value, DbAttribute targetAttribute) {
   switch (value.getClass().getName()) {
     case "java.util.Date":
       {
         Date date = (Date) value;
         return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
       }
     case "java.sql.Date":
       {
         java.sql.Date date = (java.sql.Date) value;
         return date.toLocalDate();
       }
     case "java.sql.Time":
       {
         throw new LmRuntimeException(
             "Will not perform lossy conversion from " + getTypeName() + ": " + value);
       }
     case "java.sql.Timestamp":
       {
         Timestamp timestamp = (Timestamp) value;
         return timestamp.toLocalDateTime().toLocalDate();
       }
     default:
       {
         throw new LmRuntimeException(
             "Value can not be mapped to " + getTypeName() + ": " + value);
       }
   }
 }
Example #4
0
  private static void conversionOldDateToNewDate() {
    System.out.println("Conversion old to new Date");
    Date oldDate = new Date();

    LocalDate newDate =
        LocalDateTime.ofInstant(oldDate.toInstant(), ZoneId.systemDefault()).toLocalDate();

    System.out.println("Old Date: " + oldDate);
    System.out.println("New Date: " + newDate);
  }
  @Test
  public void shouldParseHL7DateTypeStringToCorrectDate() {

    String hl7Date = "20150818130436.710";
    String hl7DateZulu = "20150818130436.710Z";
    String hl7DatePlusZeroOffset = "20150818130436.710+0000";
    String hl7DatePlusOneOffset = "20150818130436.710+0100";
    String hl7DateMinusOneOffset = "20150818130436.710-0100";

    Date actualDate = T5FHIRUtils.convertHL7DateTypeToDate(hl7Date);
    Date actualDateZulu = T5FHIRUtils.convertHL7DateTypeToDate(hl7DateZulu);
    Date actualDatePlusZeroOffset = T5FHIRUtils.convertHL7DateTypeToDate(hl7DatePlusZeroOffset);
    Date actualDatePlusOneOffset = T5FHIRUtils.convertHL7DateTypeToDate(hl7DatePlusOneOffset);
    Date actualDateMinusOneOffset = T5FHIRUtils.convertHL7DateTypeToDate(hl7DateMinusOneOffset);

    long expected = 1439903076710L;

    assertEquals(expected, actualDate.toInstant().toEpochMilli());
    assertEquals(expected, actualDateZulu.toInstant().toEpochMilli());
    assertEquals(expected, actualDatePlusZeroOffset.toInstant().toEpochMilli());
    assertNotEquals(expected, actualDatePlusOneOffset.toInstant().toEpochMilli());
    assertNotEquals(expected, actualDateMinusOneOffset.toInstant().toEpochMilli());
  }
  private void getLicenseWithNewState(License license) throws IOException, MessagingException {
    Date validFrom = license.getValidFrom();
    Date validTill = license.getValidTill();

    if (validFrom != null && validTill != null) {
      Instant now = Instant.now();
      Instant lastValid = validTill.toInstant();
      Instant lastActive = lastValid.minus(2, ChronoUnit.DAYS);
      if (now.isBefore(lastActive)) {
        license.setState(State.ACTIVE);
      }
      if (now.isAfter(lastActive) && now.isBefore(lastValid)) {
        license.setState(State.EXPIRATION_NEARING);
        // send mail to Admin notifying about soon expiring license
        mailService.sendExpirationNearingMail(license);
      }
      if (now.isAfter(lastValid)) {
        license.setState(State.TERMINATED);
      }
    }
  }
 @Override
 public LocalDateTime convert(Date source) {
   return source == null
       ? null
       : LocalDateTime.ofInstant(source.toInstant(), ZoneId.systemDefault());
 }
 public static LocalDate asLocalDateIn(Date date, ZoneId timeZone) {
   return date.toInstant().atZone(timeZone).toLocalDate();
 }
 public static LocalDate asLocalDateInUTC(Date date) {
   return date.toInstant().atZone(UTC).toLocalDate();
 }
Example #10
0
  public static void main(String[] args) throws Throwable {

    int N = 10000;
    long t1970 = new java.util.Date(70, 0, 01).getTime();
    Random r = new Random();
    for (int i = 0; i < N; i++) {
      int days = r.nextInt(50) * 365 + r.nextInt(365);
      long secs = t1970 + days * 86400 + r.nextInt(86400);
      int nanos = r.nextInt(NANOS_PER_SECOND);
      int nanos_ms = nanos / 1000000 * 1000000; // millis precision
      long millis = secs * 1000 + r.nextInt(1000);
      LocalDateTime ldt = LocalDateTime.ofEpochSecond(secs, nanos, ZoneOffset.UTC);
      LocalDateTime ldt_ms = LocalDateTime.ofEpochSecond(secs, nanos_ms, ZoneOffset.UTC);
      Instant inst = Instant.ofEpochSecond(secs, nanos);
      Instant inst_ms = Instant.ofEpochSecond(secs, nanos_ms);
      ///////////// java.util.Date /////////////////////////
      Date jud = new java.util.Date(millis);
      Instant inst0 = jud.toInstant();
      if (jud.getTime() != inst0.toEpochMilli() || !jud.equals(Date.from(inst0))) {
        System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
        throw new RuntimeException("FAILED: j.u.d -> instant -> j.u.d");
      }
      // roundtrip only with millis precision
      Date jud0 = Date.from(inst_ms);
      if (jud0.getTime() != inst_ms.toEpochMilli() || !inst_ms.equals(jud0.toInstant())) {
        System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
        throw new RuntimeException("FAILED: instant -> j.u.d -> instant");
      }
      //////////// java.util.GregorianCalendar /////////////
      GregorianCalendar cal = new GregorianCalendar();
      // non-roundtrip of tz name between j.u.tz and j.t.zid
      cal.setTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
      cal.setGregorianChange(new java.util.Date(Long.MIN_VALUE));
      cal.setFirstDayOfWeek(Calendar.MONDAY);
      cal.setMinimalDaysInFirstWeek(4);
      cal.setTimeInMillis(millis);
      ZonedDateTime zdt0 = cal.toZonedDateTime();
      if (cal.getTimeInMillis() != zdt0.toInstant().toEpochMilli()
          || !cal.equals(GregorianCalendar.from(zdt0))) {
        System.out.println("cal:" + cal);
        System.out.println("zdt:" + zdt0);
        System.out.println("calNew:" + GregorianCalendar.from(zdt0));
        System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
        throw new RuntimeException("FAILED: gcal -> zdt -> gcal");
      }
      inst0 = cal.toInstant();
      if (cal.getTimeInMillis() != inst0.toEpochMilli()) {
        System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
        throw new RuntimeException("FAILED: gcal -> zdt");
      }
      ZonedDateTime zdt = ZonedDateTime.of(ldt_ms, ZoneId.systemDefault());
      GregorianCalendar cal0 = GregorianCalendar.from(zdt);
      if (zdt.toInstant().toEpochMilli() != cal0.getTimeInMillis()
          || !zdt.equals(GregorianCalendar.from(zdt).toZonedDateTime())) {
        System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
        throw new RuntimeException("FAILED: zdt -> gcal -> zdt");
      }
    }

    ///////////// java.util.TimeZone /////////////////////////
    for (String zidStr : TimeZone.getAvailableIDs()) {
      // TBD: tzdt intergration
      if (zidStr.startsWith("SystemV")
          || zidStr.contains("Riyadh8")
          || zidStr.equals("US/Pacific-New")
          || zidStr.equals("EST")
          || zidStr.equals("HST")
          || zidStr.equals("MST")) {
        continue;
      }
      ZoneId zid = ZoneId.of(zidStr, ZoneId.SHORT_IDS);
      if (!zid.equals(TimeZone.getTimeZone(zid).toZoneId())) {
        throw new RuntimeException("FAILED: zid -> tz -> zid :" + zidStr);
      }
      TimeZone tz = TimeZone.getTimeZone(zidStr);
      // no round-trip for alias and "GMT"
      if (!tz.equals(TimeZone.getTimeZone(tz.toZoneId()))
          && !ZoneId.SHORT_IDS.containsKey(zidStr)
          && !zidStr.startsWith("GMT")) {
        throw new RuntimeException("FAILED: tz -> zid -> tz :" + zidStr);
      }
    }
    System.out.println("Passed!");
  }
 @Override
 public LocalDate convert(Date value) {
   return value.toInstant().atZone(ZoneOffset.UTC).toLocalDate();
 }
 @Override
 public LocalDateTime convertToEntityAttribute(Date date) {
   Instant instant = date.toInstant();
   return LocalDateTime.from(instant);
 }
  /**
   * Test {@link FileUtilities#generateSnapshotFileContent(VSnapshot)} and {@link
   * FileUtilities#readFromSnapshot(java.io.InputStream)}.
   *
   * @throws IOException
   * @throws ParseException
   */
  @Test
  public void testSnapshotData() throws IOException, ParseException {
    SaveSet set =
        new SaveSet(
            new Branch(), Optional.empty(), new String[] {"first", "second", "third"}, "someId");
    Snapshot snapshot = new Snapshot(set, Instant.now(), "comment", "owner");
    Date d = new Date(1455296909369L);
    Date d2 = new Date(1455296909379L);
    Alarm alarmNone = ValueFactory.alarmNone();
    Alarm alarm = ValueFactory.newAlarm(AlarmSeverity.MINOR, "HIGH");
    Display display = ValueFactory.displayNone();
    Time time = ValueFactory.newTime(d.toInstant());
    Time time2 = ValueFactory.newTime(d2.toInstant());

    VDouble val1 = ValueFactory.newVDouble(5d, alarm, time, display);
    VDoubleArray val2 =
        ValueFactory.newVDoubleArray(new ArrayDouble(1, 2, 3), alarmNone, time2, display);
    VDouble rval1 = ValueFactory.newVDouble(6d, alarmNone, time, display);
    VDoubleArray rval2 =
        ValueFactory.newVDoubleArray(new ArrayDouble(1, 1, 1), alarmNone, time, display);

    VSnapshot vs =
        new VSnapshot(
            snapshot,
            Arrays.asList(
                new SnapshotEntry("pv1", val1, true, "rb1", rval1, "50", true),
                new SnapshotEntry("pv2", val2, false, "rb2", rval2, "Math.min(x,3)", false)),
            time.getTimestamp());

    String content = FileUtilities.generateSnapshotFileContent(vs);
    String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(d);
    String CONTENT =
        "# Date: "
            + date
            + "\n"
            + "PV,SELECTED,TIMESTAMP,STATUS,SEVERITY,VALUE_TYPE,VALUE,READBACK,READBACK_VALUE,DELTA,READ_ONLY\n"
            + "pv1,1,1455296909.369000000,HIGH,MINOR,double,\"5.0\",rb1,\"6.0\",50,true\n"
            + "pv2,0,1455296909.379000000,NONE,NONE,double_array,\"[1.0;2.0;3.0]\",rb2,\"[1.0;1.0;1.0]\",\"Math.min(x,3)\",false\n";
    assertEquals(CONTENT, content);

    SnapshotContent sc =
        FileUtilities.readFromSnapshot(
            new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)));
    assertEquals(time.getTimestamp(), sc.getDate());
    List<SnapshotEntry> entries = sc.getEntries();
    assertArrayEquals(
        new String[] {"pv1", "pv2"},
        entries.stream().map(e -> e.getPVName()).toArray(String[]::new));
    assertArrayEquals(
        new String[] {"rb1", "rb2"},
        entries.stream().map(e -> e.getReadbackName()).toArray(String[]::new));
    assertArrayEquals(
        new String[] {"50", "Math.min(x,3)"},
        entries.stream().map(e -> e.getDelta()).toArray(String[]::new));
    assertArrayEquals(
        new Boolean[] {true, false},
        entries.stream().map(e -> e.isSelected()).toArray(Boolean[]::new));
    assertArrayEquals(
        new Boolean[] {true, false},
        entries.stream().map(e -> e.isReadOnly()).toArray(Boolean[]::new));

    // compare values
    List<VType> data = sc.getEntries().stream().map(e -> e.getValue()).collect(Collectors.toList());
    assertEquals(2, data.size());
    VDouble v1 = (VDouble) data.get(0);
    assertEquals(val1.getValue(), v1.getValue());
    assertEquals(val1.getTimestamp(), v1.getTimestamp());
    assertEquals(val1.getAlarmSeverity(), v1.getAlarmSeverity());
    assertEquals(val1.getAlarmName(), v1.getAlarmName());
    VDoubleArray v2 = (VDoubleArray) data.get(1);
    ListDouble ld1 = val2.getData();
    ListDouble ld2 = v2.getData();
    assertEquals(ld1.size(), ld2.size());
    for (int i = 0; i < ld1.size(); i++) {
      assertEquals(ld1.getDouble(i), ld2.getDouble(i), 0);
    }
    assertEquals(val2.getTimestamp(), v2.getTimestamp());
    assertEquals(val2.getAlarmSeverity(), v2.getAlarmSeverity());
    assertEquals(val2.getAlarmName(), v2.getAlarmName());

    // compare readbacks
    data = sc.getEntries().stream().map(e -> e.getReadbackValue()).collect(Collectors.toList());
    assertEquals(2, data.size());
    v1 = (VDouble) data.get(0);
    assertEquals(rval1.getValue(), v1.getValue());
    v2 = (VDoubleArray) data.get(1);
    ld1 = rval2.getData();
    ld2 = v2.getData();
    assertEquals(ld1.size(), ld2.size());
    for (int i = 0; i < ld1.size(); i++) {
      assertEquals(ld1.getDouble(i), ld2.getDouble(i), 0);
    }
  }
 public void setThresholdDate(Date thresholdDate) {
   this.thresholdDate =
       thresholdDate != null
           ? thresholdDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate()
           : null;
 }