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:org.videolan.vlc.gui.TimePickerDialogFragment.java

@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    if (!setTime) { //workaround for weird ICS&JB bug
        setTime = true;//from  w w w  .  ja v a2 s .  c  om
        return;
    }
    Calendar currentTime = Calendar.getInstance();
    Calendar sleepTime = Calendar.getInstance();
    sleepTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
    sleepTime.set(Calendar.MINUTE, minute);
    sleepTime.set(Calendar.SECOND, 0);
    switch (action) {
    case ACTION_SLEEP:
        if (sleepTime.before(currentTime))
            sleepTime.roll(Calendar.DATE, true);

        AdvOptionsDialog.setSleep(view.getContext(), sleepTime);
        break;
    case ACTION_JUMP:
        long time = (long) ((hourOfDay * 60 + minute) * 60000);
        LibVLC.getExistingInstance().setTime(time);
        break;
    }
}

From source file:org.opencastproject.remotetest.server.PreProcessingWorkflowTest.java

@Test
public void test() throws Exception {
    String workflowId = null;/*from ww w .j a  v a  2  s .c  om*/
    long waiting = 0;
    long TIMEOUT = TimeUnit.MILLISECONDS.convert(10, TimeUnit.SECONDS);
    long GRACE_PERIOD = 30000L;

    // Make sure the demo capture agent is online
    if (!CaptureUtils.isOnline(CAPTURE_AGENT_ID)) {
        logger.warn("Demo capture agent with id " + CAPTURE_AGENT_ID + " is not online, skipping this test");
        return;
    }

    // Specify start end end time for capture
    Calendar c = Calendar.getInstance();
    c.roll(Calendar.MINUTE, 2);
    Date start = c.getTime();
    c.roll(Calendar.MINUTE, 1);
    Date end = c.getTime();

    // TODO: How do we submit the workflow definition?

    // Schedule an event and make sure that, once the workflow is dispatched, it's on hold in the "schedule" operation
    workflowId = scheduleEvent(start, end);
    while (WorkflowUtils.isWorkflowInState(workflowId, "INSTANTIATED")) {
        logger.info("Waiting for scheduled recording workflow {} to be dispatched", workflowId);
        Thread.sleep(TIMEOUT);
    }
    if (!WorkflowUtils.isWorkflowInState(workflowId, "PAUSED")) {
        fail("Workflow " + workflowId + " should be on hold in 'schedule', or ");
    }

    logger.info("Scheduled recording {} is now paused, waiting for capture", workflowId);

    // Wait for the capture agent to start the recording and make sure the workflow enters the "capture" operation
    waiting = 120 * 1000L + GRACE_PERIOD; // 2 min +
    boolean agentIsCapturing = false;
    boolean inCaptureOperation = false;
    while (waiting > 0) {
        logger.info("Waiting for capture agent to start capture");
        String workflowXml = WorkflowUtils.getWorkflowById(workflowId);
        if (CaptureUtils.recordingExists(workflowId)) {
            agentIsCapturing |= CaptureUtils.isInState(workflowId, "capturing");
            inCaptureOperation |= WorkflowUtils.isWorkflowInOperation(workflowId, "capture");
            if (agentIsCapturing && inCaptureOperation)
                break;
        } else if (WorkflowUtils.getWorkflowState(workflowXml).contains("_error")) {
            fail("Recording failed");
        }

        waiting -= TIMEOUT;
        Thread.sleep(TIMEOUT);
    }

    // Are we already past the grace period?
    if (waiting <= 0) {
        if (!agentIsCapturing) {
            logger.info("Capture agent failed to start capture");
            fail("Agent '" + CAPTURE_AGENT_ID + "' did not start recording '" + workflowId + "'");
        } else if (!inCaptureOperation) {
            logger.info("Workflow is not in the capturing state");
            fail("Workflow '" + workflowId + "' never entered the 'capture' hold state");
        }
    }

    // Wait for capture agent to stop capturing
    Thread.sleep(Math.max(end.getTime() - System.currentTimeMillis(), 0));

    // Make sure workflow advanced to "ingest" operation
    waiting = 60 * 1000L + GRACE_PERIOD; // 1 min +
    boolean agentIsIngesting = false;
    boolean inIngestOperation = false;
    boolean workflowSucceeded = false;
    while (waiting > 0) {
        agentIsIngesting |= CaptureUtils.isInState(workflowId, "uploading");
        inIngestOperation |= WorkflowUtils.isWorkflowInOperation(workflowId, "capture");
        if (agentIsIngesting && inIngestOperation)
            break;
        // we may have missed the ingest step, since it happens so quickly. if the workflow has already succeeded, we're
        // done
        if (WorkflowUtils.isWorkflowInState(workflowId, "SUCCEEDED")) {
            workflowSucceeded = true;
            System.out.println(
                    "Workflow " + workflowId + " succeeded before we could catch it in the ingesting state");
            break;
        }
        waiting -= TIMEOUT;
        Thread.sleep(TIMEOUT);
    }

    // Are we already past the grace period?
    if (waiting <= 0) {
        if (!agentIsIngesting && !workflowSucceeded)
            fail("Agent '" + CAPTURE_AGENT_ID + "' did not start ingesting '" + workflowId + "'");
        else if (!inIngestOperation && !workflowSucceeded)
            fail("Workflow '" + workflowId + "' never entered the 'ingest' hold state");
    }

    // Wait for ingest and make sure workflow executes "cleanup", then finishes successfully
    if (!workflowSucceeded) {
        waiting = 60 * 1000L + GRACE_PERIOD; // 1 min +
        while (waiting > 0) {
            if (WorkflowUtils.isWorkflowInState(workflowId, "SUCCEEDED")) {
                workflowSucceeded = true;
                break;
            }
            waiting -= TIMEOUT;
            Thread.sleep(TIMEOUT);
        }
    }

    if (!workflowSucceeded) {
        fail("Workflow '" + workflowId + "' did not succeed");
    }

}

From source file:at.peppol.smp.client.console.SMPClient.java

private void _addDocument() {
    final SMPServiceCaller client = new SMPServiceCaller(m_aSMPAddress);
    final W3CEndpointReference endpointReferenceType = W3CEndpointReferenceUtils
            .createEndpointReference(m_sAPAddress);

    final ObjectFactory aObjFactory = new ObjectFactory();
    final ServiceMetadataType aServiceMetadata = aObjFactory.createServiceMetadataType();

    {/*from   ww  w .j  a  v a  2 s  . com*/
        final ProcessListType aProcessList = aObjFactory.createProcessListType();
        {
            final ProcessType aProcess = aObjFactory.createProcessType();
            aProcess.setProcessIdentifier(m_aProcessID);
            {
                final ServiceEndpointList aServiceEndpointList = aObjFactory.createServiceEndpointList();
                {
                    final EndpointType aEndpoint = aObjFactory.createEndpointType();
                    aEndpoint.setEndpointReference(endpointReferenceType);
                    aEndpoint.setTransportProfile(CSMPIdentifier.TRANSPORT_PROFILE_START);

                    aEndpoint.setCertificate(m_sCertificateContent);
                    aEndpoint.setServiceActivationDate(new Date(System.currentTimeMillis()));
                    aEndpoint.setServiceDescription("Test service. For Interoperability test usage.");
                    final Calendar exp = Calendar.getInstance();
                    exp.roll(Calendar.YEAR, 10);
                    aEndpoint.setServiceExpirationDate(exp.getTime());
                    aEndpoint.setTechnicalContactUrl("");
                    aEndpoint.setMinimumAuthenticationLevel("1");
                    aEndpoint.setRequireBusinessLevelSignature(false);
                    aServiceEndpointList.getEndpoint().add(aEndpoint);
                }
                aProcess.setServiceEndpointList(aServiceEndpointList);
            }
            aProcessList.getProcess().add(aProcess);
        }

        final ServiceInformationType aServiceInformation = aObjFactory.createServiceInformationType();
        aServiceInformation.setDocumentIdentifier(m_aDocumentType);
        aServiceInformation.setParticipantIdentifier(m_aParticipantID);
        aServiceInformation.setProcessList(aProcessList);
        aServiceMetadata.setServiceInformation(aServiceInformation);
    }
    try {
        client.saveServiceRegistration(aServiceMetadata, m_aSMPCredentials);
    } catch (final Exception e) {
        s_aLogger.error("Failed to add document", e);
    }
}

From source file:org.openhab.binding.synopanalyzer.handler.SynopAnalyzerHandler.java

private Synop getLastAvailableSynop() {
    logger.debug("Retrieving last Synop message");
    Calendar observationTime = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    String message = "";

    for (int backInTime = 0; backInTime < 24 && !message.startsWith(configuration.stationId); backInTime++) {
        observationTime.roll(Calendar.HOUR, false);
        // Calendar observationTime = currentTime;
        // observationTime.ro.add(Calendar.HOUR, backInTime * -1);
        String url = forgeURL(observationTime);
        try {// ww  w . j  a v  a2s . c om
            message = IOUtils.toString(new URL(url));
        } catch (IOException e) {
            logger.warn("Erroneous URL while preparing Synop request");
            updateStatus(ThingStatus.OFFLINE);
            return null;
        }
    }

    if (message.startsWith(configuration.stationId)) {
        logger.debug("Received a valid synop message");
        updateStatus(ThingStatus.ONLINE);

        String[] messageParts = message.split(",");
        String synopMessage = messageParts[messageParts.length - 1];

        Synop synopObject = createSynopObject(synopMessage);
        return synopObject;
    } else {
        logger.warn("No valid Synop for last 24h");
        updateStatus(ThingStatus.OFFLINE);
        return null;
    }
}

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

@Override
public IValue visitDateTime(Type type) {
    Calendar cal = Calendar.getInstance();
    int milliOffset = stRandom.nextInt(1000) * (stRandom.nextBoolean() ? -1 : 1);
    cal.roll(Calendar.MILLISECOND, milliOffset);
    int second = stRandom.nextInt(60) * (stRandom.nextBoolean() ? -1 : 1);
    cal.roll(Calendar.SECOND, second);
    int minute = stRandom.nextInt(60) * (stRandom.nextBoolean() ? -1 : 1);
    cal.roll(Calendar.MINUTE, minute);
    int hour = stRandom.nextInt(60) * (stRandom.nextBoolean() ? -1 : 1);
    cal.roll(Calendar.HOUR_OF_DAY, hour);
    int day = stRandom.nextInt(30) * (stRandom.nextBoolean() ? -1 : 1);
    cal.roll(Calendar.DAY_OF_MONTH, day);
    int month = stRandom.nextInt(12) * (stRandom.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 = stRandom.nextInt(5000) * (stRandom.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.  ja v  a 2s . c  o m
        cal.add(Calendar.YEAR, year);

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

From source file:org.jasig.portlet.calendar.adapter.BlackboardVistaICalAdapter.java

/**
 * Retrieve calendar data from Blackboard and use it to
 * build an iCal4j Calendar object.//from w w  w .  j  ava  2s.c  o  m
 * 
 * @param url URL of the calendar to be retrieved
 * @param session A valid Blackboard session for the user
 * @param period period time period to retrieve events for
 * @return ical4j Calendar object
 */
protected net.fortuna.ical4j.model.Calendar getCalendar(String soapSvrUrl, SessionVO session, Period period)
        throws CalendarException {
    Calendar beginPeriod = Calendar.getInstance();
    beginPeriod.setTime(period.getStart());
    beginPeriod.set(Calendar.HOUR_OF_DAY, 0);
    beginPeriod.set(Calendar.MINUTE, 0);
    beginPeriod.set(Calendar.SECOND, 0);
    beginPeriod.set(Calendar.MILLISECOND, 0);

    Calendar endPeriod = Calendar.getInstance();
    endPeriod.setTime(period.getEnd());
    endPeriod.set(Calendar.HOUR_OF_DAY, 0);
    endPeriod.set(Calendar.MINUTE, 0);
    endPeriod.set(Calendar.SECOND, 0);
    endPeriod.set(Calendar.MILLISECOND, 0);

    try {
        net.fortuna.ical4j.model.Calendar iCal4j = new net.fortuna.ical4j.model.Calendar();
        iCal4j.getProperties().add(new ProdId("-//Ben Fortuna//iCal4j 1.0//EN"));
        iCal4j.getProperties().add(Version.VERSION_2_0);
        iCal4j.getProperties().add(CalScale.GREGORIAN);

        // Display the PersonId from Context SDK.
        long personID = session.getSubject().getPersonID();

        // Get the  Calendar SDK Service based on the passed in URL
        CalendarSDK calSvc = new CalendarSDK(new URL(soapSvrUrl + "Calendar"));

        // Get the Calendar entries for the person.
        log.info("Get Calendar entries for personID = " + personID);
        CalendarEntryVO[] calEntries = calSvc.getEntriesForUser(session, personID);
        if (calEntries != null && calEntries.length != 0) {
            for (int i = 0; i < calEntries.length; i++) {
                log.debug("id = " + calEntries[i].getEntryDetailId());
                log.debug("Summary: " + calEntries[i].getSummary());
                log.debug("Start: " + calEntries[i].getStartDateTime().getTime());
                log.debug("End: " + calEntries[i].getEndDateTime().getTime());
                log.debug("Details: " + calEntries[i].getDetail());

                if (calEntries[i].isAllDayEventFlag()) {
                    log.debug("isAllDay");

                    Calendar endEvent = (Calendar) calEntries[i].getStartDateTime().clone();
                    endEvent.roll(Calendar.DATE, true);

                    VEvent iCal4jEvent = new VEvent(new Date(calEntries[i].getStartDateTime().getTime()),
                            new Date(endEvent.getTime()), calEntries[i].getSummary());

                    iCal4j.getComponents().add(iCal4jEvent);
                } else {
                    DateTime start = new DateTime(calEntries[i].getStartDateTime().getTime());
                    DateTime end = new DateTime(calEntries[i].getStartDateTime().getTime());
                    VEvent iCal4jEvent = new VEvent(start, end, calEntries[i].getSummary());
                    iCal4j.getComponents().add(iCal4jEvent);
                }
            }
        } else {
            log.info("No calendar entries found for this user");
        }
        log.debug(iCal4j.toString());
        return iCal4j;
    } catch (MalformedURLException mue) {
        throw new CalendarException("Problem with Calendar URL");
    } catch (ContextException cx) {
        throw new CalendarException("Problem connecting to calendar");
    } catch (RemoteException re) {
        throw new CalendarException("Problem getting data from calendar");
    } catch (com.webct.platform.sdk.calendar.exceptions.CalendarException ce) {
        throw new CalendarException("Problem with data from calendar");
    }
}

From source file:de.iteratec.iteraplan.businesslogic.service.FastExportServiceImplTest.java

/**
 * Test method for {@link de.iteratec.iteraplan.businesslogic.service.FastExportServiceImpl#getEncompassingRuntimePeriod(java.util.List)}.
 *///from   w  ww  . j  a  va  2s. c om
@Test
public void testGetEncompassingRuntimePeriodNoStartNoEnd() {
    InformationSystemRelease isr1 = mtdf.getInformationSystemReleaseTestData();
    InformationSystemRelease isr2 = mtdf.getInformationSystemReleaseTestData();

    RuntimePeriod period1 = new RuntimePeriod();
    isr1.setRuntimePeriod(period1);
    RuntimePeriod period2 = new RuntimePeriod();
    isr2.setRuntimePeriod(period2);

    // pretty much copy-paste from original method
    Calendar calendar = Calendar.getInstance();
    calendar.roll(Calendar.YEAR, false);
    calendar.roll(Calendar.MONTH, HALF_YEAR_IN_MONTHS);
    Date start = calendar.getTime();
    calendar.roll(Calendar.YEAR, 1);
    Date end = calendar.getTime();

    List<BuildingBlock> bbList = new ArrayList<BuildingBlock>();
    bbList.add(isr2);
    bbList.add(isr1);

    RuntimePeriod res = fastExportServiceImpl.getEncompassingRuntimePeriod(bbList);
    RuntimePeriod exp = new RuntimePeriod(start, end);
    assertEquals(exp, res);
}

From source file:com.janrain.backplane.server.config.BackplaneConfig.java

private String getExpiredMetricClause() {
    int interval = 0;
    try {//from www.  j  a  v a2  s.  c  o  m
        interval = Integer.valueOf(cachedGet(BpServerProperty.CLEANUP_INTERVAL_MINUTES));
    } catch (SimpleDBException e) {
        throw new RuntimeException("Error getting server property " + BpServerProperty.CLEANUP_INTERVAL_MINUTES,
                e);
    }
    Calendar now = Calendar.getInstance();
    // Cleanup metrics that may be lingering due to a shutdown server instance
    now.roll(Calendar.MINUTE, -(interval + 2));
    return "time < '" + ISO8601.format(now.getTime()) + "'";
}

From source file:org.apache.falcon.converter.OozieFeedMapperTest.java

@Test
public void testRetentionCoords() throws FalconException, JAXBException, IOException {
    org.apache.falcon.entity.v0.feed.Cluster cluster = FeedHelper.getCluster(feed, srcCluster.getName());
    final Calendar instance = Calendar.getInstance();
    instance.roll(Calendar.YEAR, 1);
    cluster.getValidity().setEnd(instance.getTime());

    OozieFeedMapper feedMapper = new OozieFeedMapper(feed);
    List<COORDINATORAPP> coords = feedMapper.getCoordinators(srcCluster, new Path("/projects/falcon/"));
    COORDINATORAPP coord = coords.get(0);

    Assert.assertEquals(coord.getAction().getWorkflow().getAppPath(), "${nameNode}/projects/falcon/RETENTION");
    Assert.assertEquals(coord.getName(), "FALCON_FEED_RETENTION_" + feed.getName());
    Assert.assertEquals(coord.getFrequency(), "${coord:hours(6)}");

    HashMap<String, String> props = new HashMap<String, String>();
    for (Property prop : coord.getAction().getWorkflow().getConfiguration().getProperty()) {
        props.put(prop.getName(), prop.getValue());
    }/* www . j av  a  2 s.co  m*/

    String feedDataPath = props.get("feedDataPath");
    String storageType = props.get("falconFeedStorageType");

    // verify the param that feed evictor depends on
    Assert.assertEquals(storageType, Storage.TYPE.FILESYSTEM.name());

    final Storage storage = FeedHelper.createStorage(cluster, feed);
    if (feedDataPath != null) {
        Assert.assertEquals(feedDataPath, storage.getUriTemplate().replaceAll(Storage.DOLLAR_EXPR_START_REGEX,
                Storage.QUESTION_EXPR_START_REGEX));
    }

    if (storageType != null) {
        Assert.assertEquals(storageType, storage.getType().name());
    }

    // verify the post processing params
    Assert.assertEquals(props.get("feedNames"), feed.getName());
    Assert.assertEquals(props.get("feedInstancePaths"), "IGNORE");

    assertWorkflowRetries(coord);
}

From source file:ilarkesto.integration.max.internet.MaxSession.java

public void executeSetRoomTemporaryMode(MaxRoom room, float temperature, Date until) {
    if (room == null)
        throw new IllegalArgumentException("room == null");
    if (until == null)
        throw new IllegalArgumentException("until == null");

    Calendar cal = Calendar.getInstance();
    cal.setTime(until);/*from   w w  w  .ja v a 2 s .c  om*/
    cal.set(Calendar.MILLISECOND, 0);
    cal.set(Calendar.SECOND, 0);
    int minute = cal.get(Calendar.MINUTE);
    if (minute == 30 || minute == 0) {
        // no change
    } else if (minute > 27) {
        cal.roll(Calendar.HOUR_OF_DAY, 1);
        cal.set(Calendar.MINUTE, 0);
    } else {
        cal.set(Calendar.MINUTE, 30);
    }
    until = cal.getTime();

    Map<String, String> extra = new LinkedHashMap<String, String>();
    extra.put("c0-e2", "string:" + room.getId());
    extra.put("c0-e3", "Date:" + until.getTime());
    extra.put("c0-e4", "number:" + temperature);
    extra.put("c0-e1",
            "Object_MaxSetRoomTemporaryMode:{roomId:reference:c0-e2, date:reference:c0-e3, temperature:reference:c0-e4}");
    executeApiMethod(true, "setClientCommands", extra, "Array:[reference:c0-e1]");
    log.info("Command transmitted:", "SetRoomTemporaryMode", temperature, until, room.getName());
}