Java Code Examples for java.util.Date#equals()

The following examples show how to use java.util.Date#equals() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EPPolicyManager.java    From olat with Apache License 2.0 6 votes vote down vote up
private EPMapPolicy getWrapperWithSamePolicy(final Policy policy, final List<EPMapPolicy> policyWrappers) {
    final Date to = policy.getTo();
    final Date from = policy.getFrom();
    final String permission = policy.getPermission();

    a_a: for (final EPMapPolicy wrapper : policyWrappers) {
        for (final Policy p : wrapper.getPolicies()) {
            if (!permission.equals(p.getPermission())) {
                continue a_a;
            }
            if (from == null && p.getFrom() == null || (from != null && p.getFrom() != null && from.equals(p.getFrom()))) {
                if (to == null && p.getTo() == null || (to != null && p.getTo() != null && to.equals(p.getTo()))) {
                    return wrapper;
                }
            }
        }
    }
    return null;
}
 
Example 2
Source File: ReportGenerator.java    From RepoSense with MIT License 6 votes vote down vote up
/**
 * Generates the authorship and commits JSON file for each repo in {@code configs} at {@code outputPath}, as
 * well as the summary JSON file of all the repos.
 *
 * @return the list of file paths that were generated.
 * @throws IOException if templateZip.zip does not exists in jar file.
 */
public static List<Path> generateReposReport(List<RepoConfiguration> configs, String outputPath,
        String generationDate, Date cliSinceDate, Date untilDate,
        boolean isSinceDateProvided, boolean isUntilDateProvided,
        Supplier<String> reportGenerationTimeProvider) throws IOException {
    prepareTemplateFile(outputPath);

    earliestSinceDate = null;
    progressTracker = new ProgressTracker(configs.size());

    List<Path> reportFoldersAndFiles = cloneAndAnalyzeRepos(configs, outputPath);

    Date reportSinceDate = (cliSinceDate.equals(SinceDateArgumentType.ARBITRARY_FIRST_COMMIT_DATE))
            ? earliestSinceDate : cliSinceDate;

    Optional<Path> summaryPath = FileUtil.writeJsonFile(
            new SummaryJson(configs, generationDate, reportSinceDate, untilDate, isSinceDateProvided,
                    isUntilDateProvided, RepoSense.getVersion(), ErrorSummary.getInstance().getErrorList(),
                    reportGenerationTimeProvider.get()),
            getSummaryResultPath(outputPath));
    summaryPath.ifPresent(reportFoldersAndFiles::add);

    logger.info(String.format(MESSAGE_REPORT_GENERATED, outputPath));

    return reportFoldersAndFiles;
}
 
Example 3
Source File: DateRangeSQLEqualClause.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void applyDateRange(JRQueryClauseContext queryContext,
		String column, DateRange dateRange)
{
	StringBuffer queryBuffer = queryContext.queryBuffer();
	if (dateRange == null || dateRange.getStart() == null || dateRange.getEnd() == null)
	{
		queryBuffer.append(column).append(" IS NULL");
	}
	else
	{
		Date start = dateRange.getStart();
		Date end = dateRange.getEnd();
		if (start.equals(end))
		{
			queryBuffer.append(column).append(" = ?");
			queryContext.addQueryParameter(null, start);
		}
		else
		{
			queryBuffer.append(column).append(" >= ? AND ").append(column).append(" <= ?");
			queryContext.addQueryParameter(null, start);
			queryContext.addQueryParameter(null, end);
		}
	}
}
 
Example 4
Source File: TimeParsing.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static  void checkUTC(Date d0, byte[] b, String text) throws Exception {
  Date d1 = decodeUTC(b);
  if( !d0.equals(d1) ) {
    throw new Exception("UTCTime " + text + " failed: " + d1.toGMTString());
  } else {
    System.out.println("UTCTime " + text + " ok");
  }
}
 
Example 5
Source File: RAMJobStore.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected boolean applyMisfire(TriggerWrapper tw) {

        long misfireTime = System.currentTimeMillis();
        if (getMisfireThreshold() > 0) {
            misfireTime -= getMisfireThreshold();
        }

        Date tnft = tw.trigger.getNextFireTime();
        if (tnft == null || tnft.getTime() > misfireTime 
                || tw.trigger.getMisfireInstruction() == Trigger.MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY) { 
            return false; 
        }

        Calendar cal = null;
        if (tw.trigger.getCalendarName() != null) {
            cal = retrieveCalendar(tw.trigger.getCalendarName());
        }

        signaler.notifyTriggerListenersMisfired((OperableTrigger)tw.trigger.clone());

        tw.trigger.updateAfterMisfire(cal);

        if (tw.trigger.getNextFireTime() == null) {
            tw.state = TriggerWrapper.STATE_COMPLETE;
            signaler.notifySchedulerListenersFinalized(tw.trigger);
            synchronized (lock) {
                timeTriggers.remove(tw);
            }
        } else if (tnft.equals(tw.trigger.getNextFireTime())) {
            return false;
        }

        return true;
    }
 
Example 6
Source File: ImageSaver.java    From pasm-yolov3-Android with GNU General Public License v3.0 5 votes vote down vote up
public boolean save(Mat mat) {
    Mat ultimate = new Mat();
    Imgproc.cvtColor(mat, ultimate, Imgproc.COLOR_RGB2BGR);

    Date currentTime = Calendar.getInstance().getTime();
    String strProg = "";
    if (currentTime.equals(previousTime)) {
        strProg = String.valueOf(++previousProg);
    }else{
        previousProg = 0;
    }
    String fullPath = String.format("%s/recognition_%s%s.jpg", dir.getAbsolutePath(), df.format(currentTime), strProg);
    previousTime = currentTime;
    return Imgcodecs.imwrite(fullPath, ultimate);
}
 
Example 7
Source File: CronExpression.java    From freeacs with MIT License 5 votes vote down vote up
/**
 * Indicates whether the given date satisfies the cron expression. Note that milliseconds are
 * ignored, so two Dates falling on different milliseconds of the same second will always have the
 * same result here.
 *
 * @param date the date to evaluate
 * @return a boolean indicating whether the given date satisfies the cron expression
 */
public boolean isSatisfiedBy(Date date) {
  Calendar testDateCal = Calendar.getInstance(getTimeZone());
  testDateCal.setTime(date);
  testDateCal.set(Calendar.MILLISECOND, 0);
  Date originalDate = testDateCal.getTime();

  testDateCal.add(Calendar.SECOND, -1);

  Date timeAfter = getTimeAfter(testDateCal.getTime());

  return ((timeAfter != null) && (timeAfter.equals(originalDate)));
}
 
Example 8
Source File: StudentSectioningStatus.java    From unitime with Apache License 2.0 5 votes vote down vote up
public boolean isPast() {
	Calendar cal = Calendar.getInstance(Localization.getJavaLocale());
	int slot = 12 * cal.get(Calendar.HOUR_OF_DAY) + cal.get(Calendar.MINUTE) / 5;
	cal.set(Calendar.HOUR_OF_DAY, 0);
	cal.set(Calendar.MINUTE, 0);
	cal.set(Calendar.SECOND, 0);
	cal.set(Calendar.MILLISECOND, 0);
	Date today = cal.getTime();
	if (getEffectiveStopDate() != null && today.after(getEffectiveStopDate())) return true;
	if (getEffectiveStopPeriod() != null && (getEffectiveStopPeriod() == null || today.equals(getEffectiveStopDate())) && slot >= getEffectiveStopPeriod()) return true;
	return false;
}
 
Example 9
Source File: TaskImpl.java    From ganttproject with GNU General Public License v3.0 5 votes vote down vote up
private void recalculateActivities() {
  if (myLength == null || myManager == null) {
    return;
  }
  if (isMilestone) {
    myMilestoneActivity = ImmutableList.<TaskActivity>of(new MilestoneTaskFakeActivity(this));
    return;
  }

  final Date startDate = myStart.getTime();
  final Date endDate = getEnd().getTime();

  myActivities.clear();
  if (startDate.equals(endDate)) {
    myActivities.add(new MilestoneTaskFakeActivity(this));
    return;
  }

  recalculateActivities(myManager.getConfig().getCalendar(), this, myActivities, startDate, endDate);
  int length = 0;
  for (TaskActivity activity : myActivities) {
    if (activity.getIntensity() > 0) {
      length += activity.getDuration().getLength(getDuration().getTimeUnit());
    }
  }
  myLength = getManager().createLength(myLength.getTimeUnit(), length);
}
 
Example 10
Source File: AppraiseRepositoryConnector.java    From git-appraise-eclipse with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean hasTaskChanged(TaskRepository taskRepository, ITask task, TaskData taskData) {
  Date repositoryDate = getTaskMapping(taskData).getModificationDate();
  Date localDate = task.getModificationDate();

  if (repositoryDate == null)
    return false;

  return !repositoryDate.equals(localDate);
}
 
Example 11
Source File: RAMJobStore.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
protected boolean applyMisfire(TriggerWrapper tw) {

        long misfireTime = System.currentTimeMillis();
        if (getMisfireThreshold() > 0) {
            misfireTime -= getMisfireThreshold();
        }

        Date tnft = tw.trigger.getNextFireTime();
        if (tnft == null || tnft.getTime() > misfireTime) { 
            return false; 
        }

        Calendar cal = null;
        if (tw.trigger.getCalendarName() != null) {
            cal = retrieveCalendar(null, tw.trigger.getCalendarName());
        }

        signaler.notifyTriggerListenersMisfired((Trigger)tw.trigger.clone());

        tw.trigger.updateAfterMisfire(cal);

        if (tw.trigger.getNextFireTime() == null) {
            tw.state = TriggerWrapper.STATE_COMPLETE;
            signaler.notifySchedulerListenersFinalized(tw.trigger);
            synchronized (lock) {
                timeTriggers.remove(tw);
            }
        } else if (tnft.equals(tw.trigger.getNextFireTime())) {
            return false;
        }

        return true;
    }
 
Example 12
Source File: TimeParsing.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static  void checkUTC(Date d0, byte[] b, String text) throws Exception {
  Date d1 = decodeUTC(b);
  if( !d0.equals(d1) ) {
    throw new Exception("UTCTime " + text + " failed: " + d1.toGMTString());
  } else {
    System.out.println("UTCTime " + text + " ok");
  }
}
 
Example 13
Source File: ConfigFetchHandler.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the last successfully fetched configs are not stale, or if developer mode is
 * on.
 */
private boolean areCachedFetchConfigsValid(long cacheExpirationInSeconds, Date newFetchTime) {
  Date lastSuccessfulFetchTime = frcMetadata.getLastSuccessfulFetchTime();
  // RC always fetches if the client has not previously had a successful fetch.

  if (lastSuccessfulFetchTime.equals(LAST_FETCH_TIME_NO_FETCH_YET)) {
    return false;
  }

  Date cacheExpirationTime =
      new Date(lastSuccessfulFetchTime.getTime() + SECONDS.toMillis(cacheExpirationInSeconds));

  return newFetchTime.before(cacheExpirationTime);
}
 
Example 14
Source File: JodaTime.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
private static boolean checkParseIso8601Date() throws ParseException {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat(
            "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
    String formatted = sdf.format(date);
    String alternative = DateUtils.iso8601DateFormat.print(date.getTime());
    if (formatted.equals(alternative)) {
        Date expectedDate = sdf.parse(formatted);
        Date actualDate = DateUtils.doParseISO8601Date(formatted);
        return expectedDate.equals(actualDate);
    }
    return false;
}
 
Example 15
Source File: TimeParsing.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private static  void checkUTC(Date d0, byte[] b, String text) throws Exception {
  Date d1 = decodeUTC(b);
  if( !d0.equals(d1) ) {
    throw new Exception("UTCTime " + text + " failed: " + d1.toGMTString());
  } else {
    System.out.println("UTCTime " + text + " ok");
  }
}
 
Example 16
Source File: JavatimeTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
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!");
    }
 
Example 17
Source File: Renew.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        // Three test cases:
        // 1. renewTGT=false
        // 2. renewTGT=true with a short life time, renew will happen
        // 3. renewTGT=true with a long life time, renew won't happen
        int test = Integer.parseInt(args[0]);

        OneKDC k = new OneKDC(null);
        KDC.saveConfig(OneKDC.KRB5_CONF, k,
                "renew_lifetime = 1d",
                "ticket_lifetime = " + (test == 2? "10s": "8h"));
        Config.refresh();
        k.writeJAASConf();

        // KDC would save ccache in a file
        System.setProperty("test.kdc.save.ccache", "cache.here");

        Files.write(Paths.get(OneKDC.JAAS_CONF), Arrays.asList(
                "first {",
                "   com.sun.security.auth.module.Krb5LoginModule required;",
                "};",
                "second {",
                "   com.sun.security.auth.module.Krb5LoginModule required",
                "   doNotPrompt=true",
                "   renewTGT=" + (test != 1),
                "   useTicketCache=true",
                "   ticketCache=cache.here;",
                "};"
        ));

        Context c;

        // The first login uses username and password
        c = Context.fromUserPass(OneKDC.USER, OneKDC.PASS, false);
        Date d1 = c.s().getPrivateCredentials(KerberosTicket.class).iterator().next().getAuthTime();

        // 6s is longer than half of 10s
        Thread.sleep(6000);

        // The second login uses the cache
        c = Context.fromJAAS("second");
        Date d2 = c.s().getPrivateCredentials(KerberosTicket.class).iterator().next().getAuthTime();

        if (test == 2) {
            if (d1.equals(d2)) {
                throw new Exception("Ticket not renewed");
            }
        } else {
            if (!d1.equals(d2)) {
                throw new Exception("Ticket renewed");
            }
        }
    }
 
Example 18
Source File: JavatimeTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
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!");
    }
 
Example 19
Source File: JavatimeTest.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
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!");
    }
 
Example 20
Source File: ExternalResourceMetaDataCompare.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static boolean isDefinitelyUnchanged(@Nullable ExternalResourceMetaData local, Factory<ExternalResourceMetaData> remoteFactory) {
    if (local == null) {
        return false;
    }

    String localEtag = local.getEtag();

    Date localLastModified = local.getLastModified();
    if (localEtag == null && localLastModified == null) {
        return false;
    }

    long localContentLength = local.getContentLength();
    if (localEtag == null && localContentLength < 1) {
        return false;
    }

    // We have enough local data to make a comparison, get the remote metadata
    ExternalResourceMetaData remote = remoteFactory.create();
    if (remote == null) {
        return false;
    }

    String remoteEtag = remote.getEtag();
    if (localEtag != null && remoteEtag != null) {
        return localEtag.equals(remoteEtag);
    }

    Date remoteLastModified = remote.getLastModified();
    if (remoteLastModified == null) {
        return false;
    }

    long remoteContentLength = remote.getContentLength();
    //noinspection SimplifiableIfStatement
    if (remoteContentLength < 1) {
        return false;
    }

    return localContentLength == remoteContentLength && remoteLastModified.equals(localLastModified);
}