java.util.GregorianCalendar#add ( )源码实例Demo

下面列出了java.util.GregorianCalendar#add ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

/**
 * Test generation of lucene date ranges
 *
 */
public void testLuceneDateRangeFunction()
{
    GregorianCalendar cal = new GregorianCalendar();
    cal.set(Calendar.YEAR, 2001);
    cal.set(Calendar.MONTH, 1);
    cal.set(Calendar.DAY_OF_MONTH, 1);
    String isoStartDate = ISO8601DateFormat.format(cal.getTime());
    cal.add(Calendar.DAY_OF_MONTH, 1);
    String isoEndDate = ISO8601DateFormat.format(cal.getTime());
    String template = "${luceneDateRange(\""+isoStartDate+"\", \"P1D\")}";
    FreeMarkerWithLuceneExtensionsModelFactory mf = new FreeMarkerWithLuceneExtensionsModelFactory();
    mf.setServiceRegistry(serviceRegistry);
    String result = serviceRegistry.getTemplateService().processTemplateString("freemarker", template, mf.getModel());
    assertEquals(result, "["+isoStartDate+" TO "+isoEndDate+"]");
}
 
源代码2 项目: hottub   文件: TestIsoChronoImpl.java
@Test(dataProvider = "RangeVersusCalendar")
public void test_IsoChrono_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) {
    GregorianCalendar cal = new GregorianCalendar();
    assertEquals(cal.getCalendarType(), "gregory", "Unexpected calendar type");
    LocalDate isoDate = IsoChronology.INSTANCE.date(isoStartDate);

    cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
    cal.set(Calendar.YEAR, isoDate.get(YEAR));
    cal.set(Calendar.MONTH, isoDate.get(MONTH_OF_YEAR) - 1);
    cal.set(Calendar.DAY_OF_MONTH, isoDate.get(DAY_OF_MONTH));

    while (isoDate.isBefore(isoEndDate)) {
        assertEquals(isoDate.get(DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + isoDate + ";  cal: " + cal);
        assertEquals(isoDate.get(MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + isoDate);
        assertEquals(isoDate.get(YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + isoDate);

        isoDate = isoDate.plus(1, ChronoUnit.DAYS);
        cal.add(Calendar.DAY_OF_MONTH, 1);
    }
}
 
源代码3 项目: openjdk-jdk8u   文件: TestIsoChronoImpl.java
@Test(dataProvider = "RangeVersusCalendar")
public void test_IsoChrono_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) {
    GregorianCalendar cal = new GregorianCalendar();
    assertEquals(cal.getCalendarType(), "gregory", "Unexpected calendar type");
    LocalDate isoDate = IsoChronology.INSTANCE.date(isoStartDate);

    cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
    cal.set(Calendar.YEAR, isoDate.get(YEAR));
    cal.set(Calendar.MONTH, isoDate.get(MONTH_OF_YEAR) - 1);
    cal.set(Calendar.DAY_OF_MONTH, isoDate.get(DAY_OF_MONTH));

    while (isoDate.isBefore(isoEndDate)) {
        assertEquals(isoDate.get(DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + isoDate + ";  cal: " + cal);
        assertEquals(isoDate.get(MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + isoDate);
        assertEquals(isoDate.get(YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + isoDate);

        isoDate = isoDate.plus(1, ChronoUnit.DAYS);
        cal.add(Calendar.DAY_OF_MONTH, 1);
    }
}
 
源代码4 项目: astor   文件: DateUtilsTest.java
@Test
public void testIsSameDay_Cal() {
    GregorianCalendar cal1 = new GregorianCalendar(2004, 6, 9, 13, 45);
    GregorianCalendar cal2 = new GregorianCalendar(2004, 6, 9, 13, 45);
    assertTrue(DateUtils.isSameDay(cal1, cal2));
    cal2.add(Calendar.DAY_OF_YEAR, 1);
    assertFalse(DateUtils.isSameDay(cal1, cal2));
    cal1.add(Calendar.DAY_OF_YEAR, 1);
    assertTrue(DateUtils.isSameDay(cal1, cal2));
    cal2.add(Calendar.YEAR, 1);
    assertFalse(DateUtils.isSameDay(cal1, cal2));
    try {
        DateUtils.isSameDay((Calendar) null, (Calendar) null);
        fail();
    } catch (IllegalArgumentException ex) {}
}
 
源代码5 项目: jdk8u60   文件: TestIsoChronoImpl.java
@Test(dataProvider = "RangeVersusCalendar")
public void test_IsoChrono_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) {
    GregorianCalendar cal = new GregorianCalendar();
    assertEquals(cal.getCalendarType(), "gregory", "Unexpected calendar type");
    LocalDate isoDate = IsoChronology.INSTANCE.date(isoStartDate);

    cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
    cal.set(Calendar.YEAR, isoDate.get(YEAR));
    cal.set(Calendar.MONTH, isoDate.get(MONTH_OF_YEAR) - 1);
    cal.set(Calendar.DAY_OF_MONTH, isoDate.get(DAY_OF_MONTH));

    while (isoDate.isBefore(isoEndDate)) {
        assertEquals(isoDate.get(DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + isoDate + ";  cal: " + cal);
        assertEquals(isoDate.get(MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + isoDate);
        assertEquals(isoDate.get(YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + isoDate);

        isoDate = isoDate.plus(1, ChronoUnit.DAYS);
        cal.add(Calendar.DAY_OF_MONTH, 1);
    }
}
 
源代码6 项目: ranger   文件: MiscUtil.java
public static Date getUTCDate() {
	TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT+0");
    Calendar local  = Calendar.getInstance();
    int      offset = local.getTimeZone().getOffset(local.getTimeInMillis());
    GregorianCalendar utc = new GregorianCalendar(gmtTimeZone);
    utc.setTimeInMillis(local.getTimeInMillis());
    utc.add(Calendar.MILLISECOND, -offset);
    return utc.getTime();
}
 
源代码7 项目: ranger   文件: DateUtil.java
public static Date getLocalDateForUTCDate(Date date) {
	Calendar local  = Calendar.getInstance();
	int      offset = local.getTimeZone().getOffset(local.getTimeInMillis());
	GregorianCalendar utc = new GregorianCalendar();
	utc.setTimeInMillis(date.getTime());
	utc.add(Calendar.MILLISECOND, offset);
	return utc.getTime();
}
 
源代码8 项目: kafka-monitor   文件: DateUtils.java
/**
 * 获得上周星期一的Date,具体为周一的00:00:00
 *
 * @param weeks 表示上一周还是上两周,-2:上两周,-1:上一周,0:本周,1:下周,2:下两周
 * @return
 */
public static Date getPreviousMonday(int weeks)
{
    int mondayPlus = DateUtils.getMondayPlus();
    GregorianCalendar currentDate = new GregorianCalendar();
    currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks);
    currentDate.set(GregorianCalendar.HOUR_OF_DAY, 0);
    currentDate.set(GregorianCalendar.MINUTE, 0);
    currentDate.set(GregorianCalendar.SECOND, 0);
    Date monday = currentDate.getTime();
    return monday;
}
 
源代码9 项目: jadira   文件: TestCloner.java
@Test
public void testMinimal() throws DatatypeConfigurationException {

    GregorianCalendar cal = new GregorianCalendar();
    cal.add(Calendar.YEAR, 10);
    XMLGregorianCalendar xmlCal = DatatypeFactory.newInstance().newXMLGregorianCalendar((GregorianCalendar) cal);
    cal.add(Calendar.MONTH, 3);

    DeepCopyHolder source = new DeepCopyHolder();
    source.value = new IdHolder();
    source.value.setId("A Sample Value to Copy");
    source.timestamp = new Timestamp(System.currentTimeMillis() + 10000000);
    source.calendar = cal;
    source.xmlCalendar = xmlCal;

    MinimalCloner mcloner = new MinimalCloner();
    DeepCopyHolder dest = mcloner.clone(source);

    Assert.assertEquals(source.value, dest.value);
    Assert.assertNotSame(source.value, dest.value);
    Assert.assertEquals(source.timestamp, dest.timestamp);
    Assert.assertNotSame(source.timestamp, dest.timestamp);
    Assert.assertEquals(source.calendar, dest.calendar);
    Assert.assertNotSame(source.calendar, dest.calendar);
    Assert.assertEquals(source.xmlCalendar, dest.xmlCalendar);
    Assert.assertNotSame(source.xmlCalendar, dest.xmlCalendar);
}
 
源代码10 项目: flowable-engine   文件: JobExecutorTest.java
@Test
public void testBasicJobExecutorOperation() throws Exception {
    CommandExecutor commandExecutor = processEngineConfiguration.getCommandExecutor();
    commandExecutor.execute(new Command<Void>() {
        @Override
        public Void execute(CommandContext commandContext) {
            JobServiceConfiguration jobServiceConfiguration = (JobServiceConfiguration) processEngineConfiguration.getServiceConfigurations().get(EngineConfigurationConstants.KEY_JOB_SERVICE_CONFIG);
            JobManager jobManager = jobServiceConfiguration.getJobManager();
            jobManager.execute(createTweetMessage("message-one"));
            jobManager.execute(createTweetMessage("message-two"));
            jobManager.execute(createTweetMessage("message-three"));
            jobManager.execute(createTweetMessage("message-four"));

            TimerJobEntityManager timerJobManager = jobServiceConfiguration.getTimerJobEntityManager();
            timerJobManager.insert(createTweetTimer("timer-one", new Date()));
            timerJobManager.insert(createTweetTimer("timer-one", new Date()));
            timerJobManager.insert(createTweetTimer("timer-two", new Date()));
            return null;
        }
    });

    GregorianCalendar currentCal = new GregorianCalendar();
    currentCal.add(Calendar.MINUTE, 1);
    processEngineConfiguration.getClock().setCurrentTime(currentCal.getTime());

    waitForJobExecutorToProcessAllJobsAndExecutableTimerJobs(12500L, 200L);

    Set<String> messages = new HashSet<>(tweetHandler.getMessages());
    Set<String> expectedMessages = new HashSet<>();
    expectedMessages.add("message-one");
    expectedMessages.add("message-two");
    expectedMessages.add("message-three");
    expectedMessages.add("message-four");
    expectedMessages.add("timer-one");
    expectedMessages.add("timer-two");

    assertThat(new TreeSet<>(messages)).isEqualTo(new TreeSet<>(expectedMessages));
}
 
源代码11 项目: oxAuth   文件: KeyGeneratorTimer.java
private JSONObject updateKeys(JSONObject jwks) throws Exception {
    JSONObject jsonObject = AbstractCryptoProvider.generateJwks(cryptoProvider, appConfiguration.getKeyRegenerationInterval(),
            appConfiguration.getIdTokenLifetime(), appConfiguration);

    JSONArray keys = jwks.getJSONArray(JSON_WEB_KEY_SET);
    for (int i = 0; i < keys.length(); i++) {
        JSONObject key = keys.getJSONObject(i);

        if (key.has(EXPIRATION_TIME) && !key.isNull(EXPIRATION_TIME)) {
            GregorianCalendar now = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
            GregorianCalendar expirationDate = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
            expirationDate.setTimeInMillis(key.getLong(EXPIRATION_TIME));

            if (expirationDate.before(now)) {
                // The expired key is not added to the array of keys
                log.trace("Removing JWK: {}, Expiration date: {}", key.getString(KEY_ID),
                        key.getLong(EXPIRATION_TIME));
                cryptoProvider.deleteKey(key.getString(KEY_ID));
            } else if (cryptoProvider.containsKey(key.getString(KEY_ID))) {
                log.trace("Contains kid: {}", key.getString(KEY_ID));
                jsonObject.getJSONArray(JSON_WEB_KEY_SET).put(key);
            }
        } else if (cryptoProvider.containsKey(key.getString(KEY_ID))) {
            GregorianCalendar expirationTime = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
            expirationTime.add(GregorianCalendar.HOUR, appConfiguration.getKeyRegenerationInterval());
            expirationTime.add(GregorianCalendar.SECOND, appConfiguration.getIdTokenLifetime());
            key.put(EXPIRATION_TIME, expirationTime.getTimeInMillis());

            log.trace("Contains kid {} without exp {}", key.getString(KEY_ID), expirationTime);

            jsonObject.getJSONArray(JSON_WEB_KEY_SET).put(key);
        }
    }

    return jsonObject;
}
 
源代码12 项目: openemm   文件: DynamicTagDaoImpl.java
@Override
@DaoUpdateReturnValueCheck
public void deleteDynamicTagsMarkAsDeleted(int retentionTime) {
	// Determine threshold for date
	GregorianCalendar threshold = new GregorianCalendar();
	threshold.add(Calendar.DAY_OF_MONTH, -retentionTime);

	// Deleted marked and outdated records
	update(logger, "DELETE FROM dyn_content_tbl WHERE dyn_name_id IN (SELECT dyn_name_id FROM dyn_name_tbl WHERE deleted = 1 AND deletion_date IS NOT NULL AND deletion_date < ?)", threshold);
	update(logger, "DELETE FROM dyn_name_tbl WHERE deleted = 1 AND deletion_date IS NOT NULL AND deletion_date < ?", threshold);
}
 
源代码13 项目: oodt   文件: PathUtils.java
public static String doDynamicDateReplacement(String string,
        Metadata metadata) throws CasMetadataException, CommonsException {
    Pattern datePattern = Pattern
            .compile("\\[\\s*DATE\\s*(?:[+-]{1}[^\\.]{1,}?){0,1}\\.\\s*(?:(?:DAY)|(?:MONTH)|(?:YEAR)|(?:UTC)|(?:TAI)){1}\\s*\\]");
    Matcher dateMatcher = datePattern.matcher(string);
    while (dateMatcher.find()) {
        String dateString = string.substring(dateMatcher.start(),
                dateMatcher.end());
        GregorianCalendar gc = new GregorianCalendar();

        // roll the date if roll days was specfied
        int plusMinusIndex;
        if ((plusMinusIndex = dateString.indexOf('-')) != -1
                || (plusMinusIndex = dateString.indexOf('+')) != -1) {
            int dotIndex;
            if ((dotIndex = dateString.indexOf('.', plusMinusIndex)) != -1) {
                int rollDays = Integer.parseInt(PathUtils
                        .replaceEnvVariables(
                                dateString.substring(plusMinusIndex,
                                        dotIndex), metadata).replaceAll(
                                "[\\+\\s]", ""));
                gc.add(GregorianCalendar.DAY_OF_YEAR, rollDays);
            } else {
                throw new CasMetadataException(
                    "Malformed dynamic date replacement specified (no dot separator) - '"
                    + dateString + "'");
            }
        }

        // determine type and make the appropriate replacement
        String[] splitDate = dateString.split("\\.");
        if (splitDate.length < 2) {
            throw new CasMetadataException("No date type specified - '" + dateString
                                           + "'");
        }
        String dateType = splitDate[1].replaceAll("[\\[\\]\\s]", "");
        String replacement;
        if (dateType.equals("DAY")) {
            replacement = StringUtils.leftPad(gc
                    .get(GregorianCalendar.DAY_OF_MONTH)
                    + "", 2, "0");
        } else if (dateType.equals("MONTH")) {
            replacement = StringUtils.leftPad((gc
                    .get(GregorianCalendar.MONTH) + 1)
                    + "", 2, "0");
        } else if (dateType.equals("YEAR")) {
            replacement = gc.get(GregorianCalendar.YEAR) + "";
        } else if (dateType.equals("UTC")) {
            replacement = DateUtils.toString(DateUtils.toUtc(gc));
        } else if (dateType.equals("TAI")) {
            replacement = DateUtils.toString(DateUtils.toTai(gc));
        } else {
            throw new CasMetadataException("Invalid date type specified '"
                    + dateString + "'");
        }

        string = StringUtils.replace(string, dateString, replacement);
        dateMatcher = datePattern.matcher(string);
    }
    return string;
}
 
源代码14 项目: sakai   文件: XLSTChangesHandler.java
public void recentChangesToXML(RWikiEntity rwe, ContentHandler ch)
		throws Exception
{
	if (!isAvailable()) return;

	GregorianCalendar g = new GregorianCalendar();
	g.setTime(new Date());
	g.add(GregorianCalendar.YEAR, -1);

	Decoded d = decode(rwe.getReference() + getMinorType());
	String basepath = d.getContext() + d.getContainer();
	List changes = rwikiObjectService.findAllChangedSince(g.getTime(),
			basepath);
	int nchanges = 0;
	
	
	for (Iterator i = changes.iterator(); i.hasNext() && nchanges < 20;)
	{
		nchanges++;
		RWikiCurrentObject rwco = (RWikiCurrentObject) i.next();
		AttributesImpl propA = new AttributesImpl();
		propA.addAttribute("", SchemaNames.ATTR_ID, SchemaNames.ATTR_ID, //$NON-NLS-1$
				"string", rwco.getId()); //$NON-NLS-1$
		propA.addAttribute("", SchemaNames.ATTR_NAME, //$NON-NLS-1$
				SchemaNames.ATTR_NAME, "string", rwco.getName()); //$NON-NLS-1$
		propA.addAttribute("", SchemaNames.ATTR_LOCAL_NAME, //$NON-NLS-1$
				SchemaNames.ATTR_LOCAL_NAME, "string", NameHelper //$NON-NLS-1$
						.localizeName(rwco.getName(), rwco.getRealm()));
		propA.addAttribute("", SchemaNames.ATTR_OWNER, //$NON-NLS-1$
				SchemaNames.ATTR_OWNER, "string", rwco.getOwner()); //$NON-NLS-1$
		propA.addAttribute("", SchemaNames.ATTR_REALM, //$NON-NLS-1$
				SchemaNames.ATTR_REALM, "string", rwco.getRealm()); //$NON-NLS-1$
		propA
				.addAttribute("", SchemaNames.ATTR_REFERENCED, //$NON-NLS-1$
						SchemaNames.ATTR_REFERENCED, "string", rwco //$NON-NLS-1$
								.getReferenced());
		propA.addAttribute("", SchemaNames.ATTR_SHA1, //$NON-NLS-1$
				SchemaNames.ATTR_SHA1, "string", rwco.getSha1()); //$NON-NLS-1$
		propA.addAttribute("", SchemaNames.ATTR_USER, //$NON-NLS-1$
				SchemaNames.ATTR_USER, "string", rwco.getUser()); //$NON-NLS-1$
		propA.addAttribute("", SchemaNames.ATTR_DISPLAY_USER, //$NON-NLS-1$
				SchemaNames.ATTR_DISPLAY_USER, "string", UserDisplayHelper //$NON-NLS-1$
						.formatDisplayName(rwco.getUser(), rwco.getRealm()));
		propA.addAttribute("", SchemaNames.ATTR_REVISION, //$NON-NLS-1$
				SchemaNames.ATTR_REVISION, "string", String.valueOf(rwco //$NON-NLS-1$
						.getRevision()));
		SimpleDateFormat sd = new SimpleDateFormat(RFC822DATE);
		propA.addAttribute("", SchemaNames.ATTR_LAST_CHANGE, //$NON-NLS-1$
				SchemaNames.ATTR_LAST_CHANGE, "string", sd.format(rwco //$NON-NLS-1$
						.getVersion()));
		ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_CHANGE,
				SchemaNames.EL_NSCHANGE, propA);
		renderToXML(rwco, ch, true, true);
		ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_CHANGE,
				SchemaNames.EL_NSCHANGE);
	}

}
 
源代码15 项目: datawave   文件: JobSetupUtil.java
/**
 * Computes a set of ranges to scan over entries whose row is a shaded day (yyyyMMdd_shardNum), one range per day. We calculate a range per day so that we
 * can assume that all entries for a particular day go to the same mapper in a MapReduce job.
 *
 * This uses the supplied start and end date parameters that can be supplied at job start time, and if none are supplied, it uses the current day. The end
 * of the range is always set exclusively to the start of the day following the end of the supplied day (or the beginning of tomorrow if no end was
 * supplied).
 */
public static Collection<Range> computeShardedDayRange(Configuration conf, Logger log) {
    String start = conf.get(MetricsConfig.START);
    String end = conf.get(MetricsConfig.END);
    
    GregorianCalendar from = new GregorianCalendar();
    if (start != null)
        from.setTime(DateConverter.convert(start));
    from.set(Calendar.HOUR_OF_DAY, 0);
    from.set(Calendar.MINUTE, 0);
    from.set(Calendar.SECOND, 0);
    from.set(Calendar.MILLISECOND, 0);
    if (log.isDebugEnabled() && start == null)
        log.debug("Defaulting start to the beginning of today: " + from);
    
    GregorianCalendar until = new GregorianCalendar();
    if (end != null)
        until.setTimeInMillis(DateConverter.convert(end).getTime() + TimeUnit.DAYS.toMillis(1));
    until.set(Calendar.HOUR_OF_DAY, 0);
    until.set(Calendar.MINUTE, 0);
    until.set(Calendar.SECOND, 0);
    until.set(Calendar.MILLISECOND, 0);
    until.add(Calendar.DAY_OF_YEAR, 1);
    if (log.isDebugEnabled() && end == null)
        log.debug("Defaulting end to the beginning of tomorrow: " + until);
    
    if (until.compareTo(from) <= 0) {
        log.error("Warning: end date (" + until + ") is after begin date (" + from + "), swapping!");
        GregorianCalendar tmp = until;
        until = from;
        from = tmp;
    }
    
    ArrayList<Range> ranges = new ArrayList<>();
    while (from.compareTo(until) < 0) {
        String rangeStart = DateHelper.format(from.getTime());
        from.add(GregorianCalendar.DAY_OF_YEAR, 1);
        String rangeEnd = DateHelper.format(from.getTime());
        ranges.add(new Range(rangeStart, true, rangeEnd, false));
    }
    
    return ranges;
}
 
源代码16 项目: datawave   文件: ShardedTableTabletBalancerTest.java
@Test
public void testLargeRebalance() {
    // Start out with 255 tablet servers. Later, we'll add more.
    final int NUM_TSERVERS = 255;
    for (int i = 0; i < NUM_TSERVERS; ++i) {
        testTServers.addTServer("127.0.0.1");
    }
    
    // Come up with extents for 2 months at 241 shards per day.
    Map<KeyExtent,TServerInstance> unassigned = new HashMap<>();
    SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
    GregorianCalendar cal = new GregorianCalendar();
    String[] shardPartitions = new String[241];
    for (int i = 0; i < shardPartitions.length; ++i)
        shardPartitions[i] = "_" + i;
    Arrays.sort(shardPartitions);
    
    cal.set(2010, Calendar.JULY, 1, 0, 0, 0);
    String prevRow = null;
    for (int i = 0; i < 60; i++) {
        String date = fmt.format(cal.getTime());
        for (String shardPartition : shardPartitions) {
            String endRow = date + shardPartition;
            unassigned.put(makeExtent(TNAME, endRow, prevRow), null);
            prevRow = endRow;
        }
        cal.add(Calendar.DAY_OF_YEAR, 1);
    }
    
    // Assign the initial extents and make sure they're balanced.
    int totalExtents = unassigned.size();
    Map<KeyExtent,TServerInstance> assignments = new HashMap<>();
    testBalancer.getAssignments(testTServers.getCurrent(), unassigned, assignments);
    testTServers.applyAssignments(assignments);
    
    assertEquals(totalExtents, assignments.size());
    
    int evenMin = Math.max(241 / NUM_TSERVERS, 1);
    int evenMax = 241 / NUM_TSERVERS;
    if (241 % NUM_TSERVERS > 0)
        evenMax++;
    
    testTServers.checkShardsPerDay(evenMin, evenMax);
    
    // Now bring on more servers and ensure it's all balanced.
    for (int i = 255; i < 915; ++i) {
        testTServers.addTServer("127.0.0.1");
    }
    evenMin = Math.max(241 / 915, 1);
    evenMax = 241 / 915;
    if (241 % 915 > 0)
        evenMax++;
    
    // and balance
    runAndCheckBalance(10);
    testTServers.checkShardsPerDay(evenMin, evenMax);
    testTServers.checkDateDistribution();
    
}
 
源代码17 项目: openjdk-jdk8u   文件: TestIsoChronoImpl.java
@Test(dataProvider = "RangeVersusCalendar")
public void test_DayOfWeek_IsoChronology_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) {
    GregorianCalendar cal = new GregorianCalendar();
    assertEquals(cal.getCalendarType(), "gregory", "Unexpected calendar type");
    LocalDate isoDate = IsoChronology.INSTANCE.date(isoStartDate);

    for (DayOfWeek firstDayOfWeek : DayOfWeek.values()) {
        for (int minDays = 1; minDays <= 7; minDays++) {
            WeekFields weekDef = WeekFields.of(firstDayOfWeek, minDays);
            cal.setFirstDayOfWeek(Math.floorMod(firstDayOfWeek.getValue(), 7) + 1);
            cal.setMinimalDaysInFirstWeek(minDays);

            cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
            cal.set(Calendar.YEAR, isoDate.get(YEAR));
            cal.set(Calendar.MONTH, isoDate.get(MONTH_OF_YEAR) - 1);
            cal.set(Calendar.DAY_OF_MONTH, isoDate.get(DAY_OF_MONTH));

            // For every date in the range
            while (isoDate.isBefore(isoEndDate)) {
                assertEquals(isoDate.get(DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + isoDate + ";  cal: " + cal);
                assertEquals(isoDate.get(MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + isoDate);
                assertEquals(isoDate.get(YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + isoDate);

                int jdow = Math.floorMod(cal.get(Calendar.DAY_OF_WEEK) - 2, 7) + 1;
                int dow = isoDate.get(weekDef.dayOfWeek());
                assertEquals(jdow, dow, "Calendar DayOfWeek does not match ISO DayOfWeek");

                int jweekOfMonth = cal.get(Calendar.WEEK_OF_MONTH);
                int isoWeekOfMonth = isoDate.get(weekDef.weekOfMonth());
                assertEquals(jweekOfMonth, isoWeekOfMonth, "Calendar WeekOfMonth does not match ISO WeekOfMonth");

                int jweekOfYear = cal.get(Calendar.WEEK_OF_YEAR);
                int weekOfYear = isoDate.get(weekDef.weekOfWeekBasedYear());
                assertEquals(jweekOfYear, weekOfYear,  "GregorianCalendar WeekOfYear does not match WeekOfWeekBasedYear");

                int jWeekYear = cal.getWeekYear();
                int weekBasedYear = isoDate.get(weekDef.weekBasedYear());
                assertEquals(jWeekYear, weekBasedYear,  "GregorianCalendar getWeekYear does not match YearOfWeekBasedYear");

                int jweeksInWeekyear = cal.getWeeksInWeekYear();
                int weeksInWeekBasedYear = (int)isoDate.range(weekDef.weekOfWeekBasedYear()).getMaximum();
                assertEquals(jweeksInWeekyear, weeksInWeekBasedYear, "length of weekBasedYear");

                isoDate = isoDate.plus(1, ChronoUnit.DAYS);
                cal.add(Calendar.DAY_OF_MONTH, 1);
            }
        }
    }
}
 
源代码18 项目: sakai   文件: XLSTChangesHandler.java
public void recentChangesToXML(RWikiEntity rwe, ContentHandler ch)
		throws Exception
{
	if (!isAvailable()) return;

	GregorianCalendar g = new GregorianCalendar();
	g.setTime(new Date());
	g.add(GregorianCalendar.YEAR, -1);

	Decoded d = decode(rwe.getReference() + getMinorType());
	String basepath = d.getContext() + d.getContainer();
	List changes = rwikiObjectService.findAllChangedSince(g.getTime(),
			basepath);
	int nchanges = 0;
	
	
	for (Iterator i = changes.iterator(); i.hasNext() && nchanges < 20;)
	{
		nchanges++;
		RWikiCurrentObject rwco = (RWikiCurrentObject) i.next();
		AttributesImpl propA = new AttributesImpl();
		propA.addAttribute("", SchemaNames.ATTR_ID, SchemaNames.ATTR_ID, //$NON-NLS-1$
				"string", rwco.getId()); //$NON-NLS-1$
		propA.addAttribute("", SchemaNames.ATTR_NAME, //$NON-NLS-1$
				SchemaNames.ATTR_NAME, "string", rwco.getName()); //$NON-NLS-1$
		propA.addAttribute("", SchemaNames.ATTR_LOCAL_NAME, //$NON-NLS-1$
				SchemaNames.ATTR_LOCAL_NAME, "string", NameHelper //$NON-NLS-1$
						.localizeName(rwco.getName(), rwco.getRealm()));
		propA.addAttribute("", SchemaNames.ATTR_OWNER, //$NON-NLS-1$
				SchemaNames.ATTR_OWNER, "string", rwco.getOwner()); //$NON-NLS-1$
		propA.addAttribute("", SchemaNames.ATTR_REALM, //$NON-NLS-1$
				SchemaNames.ATTR_REALM, "string", rwco.getRealm()); //$NON-NLS-1$
		propA
				.addAttribute("", SchemaNames.ATTR_REFERENCED, //$NON-NLS-1$
						SchemaNames.ATTR_REFERENCED, "string", rwco //$NON-NLS-1$
								.getReferenced());
		propA.addAttribute("", SchemaNames.ATTR_SHA1, //$NON-NLS-1$
				SchemaNames.ATTR_SHA1, "string", rwco.getSha1()); //$NON-NLS-1$
		propA.addAttribute("", SchemaNames.ATTR_USER, //$NON-NLS-1$
				SchemaNames.ATTR_USER, "string", rwco.getUser()); //$NON-NLS-1$
		propA.addAttribute("", SchemaNames.ATTR_DISPLAY_USER, //$NON-NLS-1$
				SchemaNames.ATTR_DISPLAY_USER, "string", UserDisplayHelper //$NON-NLS-1$
						.formatDisplayName(rwco.getUser(), rwco.getRealm()));
		propA.addAttribute("", SchemaNames.ATTR_REVISION, //$NON-NLS-1$
				SchemaNames.ATTR_REVISION, "string", String.valueOf(rwco //$NON-NLS-1$
						.getRevision()));
		SimpleDateFormat sd = new SimpleDateFormat(RFC822DATE);
		propA.addAttribute("", SchemaNames.ATTR_LAST_CHANGE, //$NON-NLS-1$
				SchemaNames.ATTR_LAST_CHANGE, "string", sd.format(rwco //$NON-NLS-1$
						.getVersion()));
		ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_CHANGE,
				SchemaNames.EL_NSCHANGE, propA);
		renderToXML(rwco, ch, true, true);
		ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_CHANGE,
				SchemaNames.EL_NSCHANGE);
	}

}
 
源代码19 项目: repairnator   文件: TestTimedSummaryNotifier.java
/**
 * Tests that the filters are properly updated when the calendar is changed
 */
@Test
public void testUpdateFilters() {
    
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTime(new Date());
    calendar.add(GregorianCalendar.HOUR, -2);
    
    notifier.updateFilters(calendar.getTime());
    Date previousDate = calendar.getTime();
    
    BsonDocument rtscannerFilter = notifier.rtscannerFilter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
    BsonDocument repairAttemptsFilter = notifier.repairAttemptsFilter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
    BsonDocument patchesFilter = notifier.patchedBuildsFilter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
    
    BsonDocument[] toolFilters = new BsonDocument[tools.length];
    for(int i = 0; i < tools.length; i++) {
        toolFilters[i] = notifier.toolFilters.get(tools[i]).toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
    }
    
    System.out.println(rtscannerFilter);
    System.out.println(repairAttemptsFilter);
    System.out.println(patchesFilter);
    System.out.println(Filters.and(
            Filters.gte("buildReproductionDate", previousDate),
            Filters.or(
                    Filters.eq("status", "test failure"),
                    Filters.eq("status", "PATCHED")
                    )).toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry()));
    
    assertTrue(rtscannerFilter.equals(Filters.gte("dateWatched",previousDate).toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry())));
    assertTrue(repairAttemptsFilter.equals(Filters.and(
                Filters.gte("buildReproductionDate", previousDate),
                Filters.or(
                        Filters.eq("status", "test failure"),
                        Filters.eq("status", "PATCHED")
                        )).toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry())));
    assertTrue(patchesFilter.equals(Filters.and(
            Filters.gte("buildReproductionDate", previousDate),
            Filters.eq("status", "PATCHED")).toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry())));
    for(int i = 0; i < toolFilters.length; i++) {
        assertTrue(toolFilters[i].equals(
                Filters.and(Filters.gte("date",previousDate),
                        Filters.eq("toolname", tools[i])).toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry())));
    }
}
 
源代码20 项目: CargoTracker-J12015   文件: BookingServiceTest.java
@Test
@InSequence(1)
public void testRegisterNew() {
	// try {
	// GlassFish glassfish = GlassFishRuntime.bootstrap().newGlassFish();
	// glassfish.start();
	// File war = new File("c:\\temp\\cargo-tracker-test.war");
	// Deployer deployer = glassfish.getDeployer();
	// deployer.deploy(war);
	// } catch (GlassFishException ex) {
	// Logger.getLogger(BookingServiceTest.class.getName()).log(Level.SEVERE,
	// null, ex);
	// }

	UnLocode fromUnlocode = new UnLocode("USCHI");
	UnLocode toUnlocode = new UnLocode("SESTO");

	deadline = new Date();
	GregorianCalendar calendar = new GregorianCalendar();
	calendar.setTime(deadline);
	calendar.add(Calendar.MONTH, 6); // Six months ahead.
	deadline.setTime(calendar.getTime().getTime());

	trackingId = bookingService.bookNewCargo(fromUnlocode, toUnlocode,
			deadline);

	Cargo cargo = entityManager
			.createNamedQuery("Cargo.findByTrackingId", Cargo.class)
			.setParameter("trackingId", trackingId).getSingleResult();

	assertEquals(SampleLocations.CHICAGO, cargo.getOrigin());
	assertEquals(SampleLocations.STOCKHOLM, cargo.getRouteSpecification()
			.getDestination());
	assertTrue(DateUtils.isSameDay(deadline, cargo.getRouteSpecification()
			.getArrivalDeadline()));
	assertEquals(TransportStatus.NOT_RECEIVED, cargo.getDelivery()
			.getTransportStatus());
	assertEquals(Location.UNKNOWN, cargo.getDelivery()
			.getLastKnownLocation());
	assertEquals(Voyage.NONE, cargo.getDelivery().getCurrentVoyage());
	assertFalse(cargo.getDelivery().isMisdirected());
	assertEquals(Delivery.ETA_UNKOWN, cargo.getDelivery()
			.getEstimatedTimeOfArrival());
	assertEquals(Delivery.NO_ACTIVITY, cargo.getDelivery()
			.getNextExpectedActivity());
	assertFalse(cargo.getDelivery().isUnloadedAtDestination());
	assertEquals(RoutingStatus.NOT_ROUTED, cargo.getDelivery()
			.getRoutingStatus());
	assertEquals(Itinerary.EMPTY_ITINERARY, cargo.getItinerary());
}