Example usage for java.util Calendar roll

List of usage examples for java.util Calendar roll

Introduction

In this page you can find the example usage for java.util Calendar roll.

Prototype

public void roll(int field, int amount) 

Source Link

Document

Adds the specified (signed) amount to the specified calendar field without changing larger fields.

Usage

From source file:hsa.awp.scire.controller.TestController.java

@Test
public void testCall() {

    Set<Class<? extends IProcedureLogic<?>>> types = new HashSet<Class<? extends IProcedureLogic<?>>>();
    types.add(LogicDummy.class);
    controller.setProcedureLogicTypeList(types);

    int interval = 500;
    controller.setTimerInterval(interval);

    Campaign camp = Campaign.getInstance(0L);

    Calendar endShow = Calendar.getInstance();
    endShow.roll(Calendar.YEAR, 1);

    camp.setStartShow(Calendar.getInstance());
    camp.setName("123");
    camp.setEndShow(endShow);/* ww w.ja v a  2s .  c om*/
    campaignFacade.saveCampaign(camp);

    FifoProcedure p = FifoProcedure.getInstance(0L);
    Calendar startDate = Calendar.getInstance();
    startDate.add(Calendar.SECOND, 2);

    Calendar endDate = Calendar.getInstance();
    while (startDate.compareTo(endDate) >= 0) {
        endDate.add(Calendar.SECOND, 5);
    }

    p.setInterval(startDate, endDate);

    campaignFacade.saveFifoProcedure(p);

    camp.addProcedure(p);

    campaignFacade.updateCampaign(camp);

    controller.startTimer();

    int i = 0;
    boolean foundStarted = false;
    boolean foundTerminated = false;
    LogicDummy dummy = null;

    while (i++ < 300) {
        if (foundStarted) {
            if (controller.findActiveLogicByProcedure(p.getId()) == null) {
                foundTerminated = true;
                logger.info("found started procedure");
                break;
            }
        } else if (controller.findActiveLogicByProcedure(p.getId()) != null) {
            foundStarted = true;
            dummy = (LogicDummy) controller.findActiveLogicByProcedure(p.getId());
            logger.info("found terminated procedure");
        }

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    assertTrue(foundStarted);
    assertTrue(foundTerminated);
    assertTrue(dummy.getAfterActiveCount() > 0);
    assertTrue(dummy.getBeforeActiveCount() > 0);
    assertTrue(dummy.getWhileActiveCount() > 0);

    controller.stopTimer();
}

From source file:org.rascalmpl.library.cobra.Arbitrary.java

public IValue arbDateTime() {
    Calendar cal = Calendar.getInstance();
    int milliOffset = random.nextInt(1000) * (random.nextBoolean() ? -1 : 1);
    cal.roll(Calendar.MILLISECOND, milliOffset);
    int second = random.nextInt(60) * (random.nextBoolean() ? -1 : 1);
    cal.roll(Calendar.SECOND, second);
    int minute = random.nextInt(60) * (random.nextBoolean() ? -1 : 1);
    cal.roll(Calendar.MINUTE, minute);
    int hour = random.nextInt(60) * (random.nextBoolean() ? -1 : 1);
    cal.roll(Calendar.HOUR_OF_DAY, hour);
    int day = random.nextInt(30) * (random.nextBoolean() ? -1 : 1);
    cal.roll(Calendar.DAY_OF_MONTH, day);
    int month = random.nextInt(12) * (random.nextBoolean() ? -1 : 1);
    cal.roll(Calendar.MONTH, month);

    // make sure we do not go over the 4 digit year limit, which breaks things
    int year = random.nextInt(5000) * (random.nextBoolean() ? -1 : 1);

    // make sure we don't go into negative territory
    if (cal.get(Calendar.YEAR) + year < 1)
        cal.add(Calendar.YEAR, 1);
    else/*from  w ww.j  a  va2  s  .co  m*/
        cal.add(Calendar.YEAR, year);

    return values.datetime(cal.getTimeInMillis());
}

From source file:br.com.transport.report.ManagerReportBean.java

/**
 * Retorna lista com os dias da semana/*w  ww.  j  a  va 2  s. c om*/
 * @return {@link List}< {@link Calendar} >
 */
private List<Calendar> createDayOfTheWeek() {

    Calendar firstDay = GregorianCalendar.getInstance();
    firstDay.setFirstDayOfWeek(Calendar.SUNDAY);
    firstDay.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    firstDay.set(Calendar.HOUR_OF_DAY, 0);
    firstDay.set(Calendar.MINUTE, 0);
    firstDay.set(Calendar.SECOND, 0);

    List<Calendar> daysOfTheWeek = new LinkedList<Calendar>();

    for (int count = 0; count < 7; count++) {

        Calendar temp = (Calendar) firstDay.clone();
        temp.roll(Calendar.DAY_OF_WEEK, count);
        temp.setTime(temp.getTime());
        daysOfTheWeek.add(temp);

    }

    return daysOfTheWeek;
}

From source file:org.wso2.carbon.appfactory.core.services.AppFactoryTenantInfraStructureInitializerService.java

private TaskInfo.TriggerInfo getTriggerWithDalay() {
    TaskInfo.TriggerInfo triggerInfo = new TaskInfo.TriggerInfo();
    //trigger immediately after 5s and one time
    Calendar triggerTime = Calendar.getInstance();
    triggerTime.roll(Calendar.SECOND, 5);
    triggerInfo.setStartTime(triggerTime.getTime());
    triggerInfo.setRepeatCount(0);//from ww  w. j a v a 2 s . c o m
    return triggerInfo;
}

From source file:no.abmu.lise.domain.fixtures.PaymentToSupplierTestFixture.java

public PaymentToSupplierTestFixture(ConsortiumTestFixture consortiumTestFixture) {

    Calendar calendar = Calendar.getInstance();
    Date today = calendar.getTime();
    calendar.roll(Calendar.DAY_OF_YEAR, 1);
    Date tomorrow = calendar.getTime();
    calendar.roll(Calendar.DAY_OF_YEAR, -2);
    Date yesterday = calendar.getTime();

    Consortium consortiumA = consortiumTestFixture.getConsortiumA();
    String subscriptionYearA = "subscriptionYearA";
    LiseComment liseCommentA = new LiseComment("commentA");
    liseCommentA.setCreated(yesterday);//from   w  ww.  j  a v a2  s. c  om
    liseCommentA.setLastUpdated(today);
    Date dueDateA = today;
    Date invoiceDateA = yesterday;
    Long randomLongA = RandomGeneratorUtil.createRandomLong();
    BigDecimal amountA = new BigDecimal(randomLongA);
    String invoiceNumberA = "invoiceNumberA";

    paymentToSupplierA = new PaymentToSupplier(amountA, subscriptionYearA, invoiceNumberA, dueDateA);
    paymentToSupplierA.setConsortium(consortiumA);
    paymentToSupplierA.setInvoiceDate(invoiceDateA);
    paymentToSupplierA.setLiseComment(liseCommentA);

    paymentToSupplierB = new PaymentToSupplier(amountA, subscriptionYearA, invoiceNumberA, dueDateA);
    paymentToSupplierB.setConsortium(consortiumA);
    paymentToSupplierB.setInvoiceDate(invoiceDateA);
    paymentToSupplierB.setLiseComment(liseCommentA);

    Consortium consortiumC = consortiumTestFixture.getConsortiumC();
    String subscriptionYearC = "subscriptionYearC";
    LiseComment liseCommentC = new LiseComment("commentC");
    liseCommentC.setCreated(today);
    liseCommentC.setLastUpdated(tomorrow);
    Date dueDateC = tomorrow;
    Date invoiceDateC = today;
    Long randomLongC = RandomGeneratorUtil.createRandomADifferentLong(randomLongA);
    BigDecimal amountC = new BigDecimal(randomLongC);
    String invoiceNumberC = "invoiceNumberC";

    paymentToSupplierC = new PaymentToSupplier(amountC, subscriptionYearC, invoiceNumberC, dueDateC);
    paymentToSupplierC.setConsortium(consortiumC);
    paymentToSupplierC.setInvoiceDate(invoiceDateC);
    paymentToSupplierA.setLiseComment(liseCommentC);

    paymentToSupplierD = new ExtendedPaymentToSupplier(paymentToSupplierA);

}

From source file:com.redhat.rhn.frontend.action.systems.monitoring.ProbeGraphAction.java

private TimeSeriesData[] padProbeData(TimeSeriesData[] tsd, Timestamp startTime, Timestamp endTime,
        String metricId) {//from ww w  . j  a  v a2 s  . co  m
    List retval = new LinkedList(Arrays.asList(tsd));

    // Here we determine if we need to add a blank bit of data
    // at the beginning and end of the data
    if (tsd.length >= 2) {
        TimeSeriesData first = tsd[0];
        TimeSeriesData last = tsd[tsd.length - 1];
        // We want to pad the start and end dates by 5 minutes so
        // we don't add space at the start and beginning
        Calendar pcal = Calendar.getInstance();
        pcal.setTime(startTime);
        pcal.roll(Calendar.MINUTE, 5);

        if (first.getTime().after(pcal.getTime())) {
            log.debug("Adding start padding  : " + startTime);
            TimeSeriesData firstPad = new TimeSeriesData(null, null, startTime, metricId);
            retval.add(0, firstPad);
        }
        pcal.setTime(endTime);
        pcal.roll(Calendar.MINUTE, -5);
        if (last.getTime().before(pcal.getTime())) {
            log.debug("Adding end padding : " + endTime);
            TimeSeriesData lastPad = new TimeSeriesData(null, null, endTime, metricId);
            retval.add(retval.size() - 1, lastPad);
        }
    }
    return (TimeSeriesData[]) retval.toArray(new TimeSeriesData[0]);
}

From source file:org.orcid.core.manager.impl.OrcidSocialManagerImpl.java

/**
 * Will be invoked by a cron job to tweet in the modified profiles
 * *///from w  ww. j ava 2 s.co  m
@Override
public void tweetLatestUpdates() {
    LOGGER.info("Start tweeting thread");
    if (isTwitterEnabled) {
        List<OrcidSocialEntity> toTweet = orcidSocialDao.getRecordsToTweet();
        Calendar cal = Calendar.getInstance();
        cal.roll(Calendar.HOUR, false);
        Date oneHourBack = cal.getTime();
        for (OrcidSocialEntity entity : toTweet) {
            Date lastTimeTweeted = entity.getLastRun();
            if (lastTimeTweeted == null || lastTimeTweeted.before(oneHourBack)) {
                LOGGER.info("Tweeting profile {}", entity.getId().getOrcid());
                if (lastTimeTweeted == null || entity.getProfile().getLastModified().after(lastTimeTweeted)) {
                    if (tweet(entity))
                        orcidSocialDao.updateLatestRunDate(entity.getId().getOrcid(), entity.getType());
                }
            }
        }
    } else {
        LOGGER.info("Twitter is disabled in this environment");
    }
    LOGGER.info("Finished tweeting thread");
}

From source file:hsa.awp.admingui.DummyValueCreator.java

/**
 * Inserts the test data.//from  ww w .  ja  va2 s.  c  om
 */
@Test
@Transactional
public void insertData() {

    logger.debug("start test insertData()");

    SecurityContextHolder.getContext()
            .setAuthentication(new UsernamePasswordAuthenticationToken("admin", "password"));

    Campaign c = Campaign.getInstance(0L);
    c.setName("CampaignName");
    campaignFacade.saveCampaign(c);
    logger.debug("saved campaign " + c);

    DrawProcedure d1 = DrawProcedure.getInstance(0L);
    d1.getDrawDate().roll(Calendar.DATE, 1);
    d1.getEndDate().roll(Calendar.DATE, 2);
    d1.setName("1. Losung");
    campaignFacade.saveDrawProcedure(d1);
    logger.debug("saved drawProcedure " + d1);

    DrawProcedure d2 = DrawProcedure.getInstance(0L);
    d2.getStartDate().roll(Calendar.DATE, 2);
    d2.getEndDate().roll(Calendar.DATE, 4);
    d2.getDrawDate().roll(Calendar.DATE, 3);
    d2.setName("2. Losung");
    campaignFacade.saveDrawProcedure(d2);
    logger.debug("saved drawProcedure " + d2);

    FifoProcedure f1 = FifoProcedure.getInstance(0L);
    Calendar f1Start = Calendar.getInstance();
    f1Start.roll(Calendar.DATE, 4);
    Calendar f1End = Calendar.getInstance();
    f1End.roll(Calendar.DATE, 5);
    f1.setInterval(f1Start, f1End);
    f1.setName("Restfifo");
    campaignFacade.saveFifoProcedure(f1);
    logger.debug("saved fifiProcedure " + f1);

    c.addProcedure(f1);
    c.addProcedure(d1);
    c.addProcedure(d2);
    campaignFacade.updateCampaign(c);

    Category c1 = Category.getInstance("Testkategorie1", 0L);
    Category c2 = Category.getInstance("Testkategorie2", 0L);
    eventFacade.saveCategory(c1);
    eventFacade.saveCategory(c2);

    Subject s1 = Subject.getInstance(0L);
    s1.setName("TestFach");
    eventFacade.saveSubject(s1);
    c1.addSubject(s1);
    eventFacade.updateSubject(s1);
    eventFacade.updateCategory(c1);

    SingleUser t1 = SingleUser.getInstance("meixner");
    t1.setName("Gerhard Meixner");
    RoleMapping roleMapping = RoleMapping.getInstance(Role.REGISTERED);
    userFacade.saveRoleMapping(roleMapping);
    t1.getRolemappings().add(roleMapping);
    userFacade.saveSingleUser(t1);

    Event e1 = Event.getInstance(1, 0L);
    e1.setMaxParticipants(20);
    e1.setSubject(s1);
    e1.getTeachers().add(t1.getId());
    e1.setSubject(s1);
    eventFacade.saveEvent(e1);

    Event e2 = Event.getInstance(2, 0L);
    e2.setMaxParticipants(20);
    e2.setSubject(s1);
    e2.getTeachers().add(t1.getId());
    e2.setSubject(s1);
    eventFacade.saveEvent(e2);

    Event e3 = Event.getInstance(3, 0L);
    e3.setMaxParticipants(30);
    e3.setSubject(s1);
    e3.getTeachers().add(t1.getId());
    e3.setSubject(s1);
    eventFacade.saveEvent(e3);

    s1.addEvent(e1);
    s1.addEvent(e2);
    s1.addEvent(e3);
    eventFacade.updateSubject(s1);

    c.getEventIds().add(e1.getId());
    campaignFacade.updateCampaign(c);

    PriorityList p1 = PriorityList.getInstance(0L);
    p1.setDate(Calendar.getInstance());
    campaignFacade.savePriorityList(p1);

    PriorityListItem pi1 = PriorityListItem.getInstance(p1, e1.getId(), 1, 0L);
    PriorityListItem pi2 = PriorityListItem.getInstance(p1, e2.getId(), 2, 0L);
    PriorityListItem pi3 = PriorityListItem.getInstance(p1, e3.getId(), 3, 0L);
    campaignFacade.savePriorityListItem(pi1);
    campaignFacade.savePriorityListItem(pi2);
    campaignFacade.savePriorityListItem(pi3);

    p1.getItems().add(pi1);
    p1.getItems().add(pi2);
    p1.getItems().add(pi3);
    campaignFacade.updatePriorityList(p1);

    d1.getPriorityLists().add(p1);
    campaignFacade.updatePriorityList(p1);
}

From source file:org.polymap.kaps.ui.filter.VertraegeNutzungsartenFilter.java

protected Query<VertragComposite> createFilterQuery(final IFilterEditorSite site,
        final KapsRepository repository) {

    BooleanExpression jExpr = null;// www . j  a v  a2 s .  c o  m
    VertragComposite template = QueryExpressions.templateFor(VertragComposite.class);
    Integer jahr = Integer.parseInt((String) site.getFieldValue("Jahr"));
    if (jahr != null) {
        Calendar lowerCal = new GregorianCalendar();
        lowerCal.set(Calendar.YEAR, jahr);
        lowerCal.set(Calendar.DAY_OF_MONTH, 1);
        lowerCal.set(Calendar.HOUR_OF_DAY, 0);
        lowerCal.set(Calendar.MINUTE, 0);
        lowerCal.set(Calendar.SECOND, 0);
        lowerCal.set(Calendar.MILLISECOND, 0);

        Calendar upperCal = new GregorianCalendar();
        upperCal.setTime(lowerCal.getTime());

        lowerCal.set(Calendar.MONTH, Calendar.JANUARY);
        upperCal.roll(Calendar.YEAR, true);
        upperCal.set(Calendar.MONTH, Calendar.JANUARY);

        jExpr = QueryExpressions.and(QueryExpressions.ge(template.vertragsDatum(), lowerCal.getTime()),
                QueryExpressions.lt(template.vertragsDatum(), upperCal.getTime()));
    }
    Set<Integer> nummern = Sets.newHashSet();

    for (VertragComposite vertrag : repository().findEntities(VertragComposite.class, jExpr, 0, -1)) {
        NutzungComposite nutzung = null;
        for (FlurstueckComposite flurstueck : FlurstueckComposite.Mixin.forEntity(vertrag)) {
            if (nutzung == null) {
                nutzung = flurstueck.nutzung().get();
            } else if (!nutzung.equals(flurstueck.nutzung().get())) {
                log.info("Found difference in " + vertrag.eingangsNr().get());
                nummern.add(vertrag.eingangsNr().get());
                continue;
            }
        }
    }

    BooleanExpression fExpr = null;
    for (Integer nummer : nummern) {
        BooleanExpression newExpr = QueryExpressions.eq(template.eingangsNr(), nummer);
        if (fExpr == null) {
            fExpr = newExpr;
        } else {
            fExpr = QueryExpressions.or(fExpr, newExpr);
        }
    }

    // wenn keine gefunden, ungltige Query erzeugen, damit auch keine
    // Vertrge gefunden werden
    if (fExpr == null) {
        fExpr = QueryExpressions.eq(template.identity(), "unknown");
    }

    return repository().findEntities(VertragComposite.class, fExpr, 0, getMaxResults());
}

From source file:org.openmrs.web.controller.patient.ShortPatientFormValidatorTest.java

/**
 * @see ShortPatientFormValidator#validate(Object,Errors)
 *//*w  w  w . j a v a 2  s  .c  o m*/
@Test
@Verifies(value = "should fail validation if birthdate makes patient 120 years old or older", method = "validate(Object,Errors)")
public void validate_shouldFailValidationIfBirthdateMakesPatient120YearsOldOrOlder() throws Exception {
    Patient p = ps.getPatient(2);
    Calendar c = Calendar.getInstance();
    c.roll(Calendar.YEAR, -121);
    p.setBirthdate(c.getTime());
    ShortPatientModel model = new ShortPatientModel(p);
    Errors errors = new BindException(model, "patientModel");
    validator.validate(model, errors);
    Assert.assertEquals(true, errors.hasFieldErrors());
}