Example usage for org.apache.commons.lang.time DateUtils truncate

List of usage examples for org.apache.commons.lang.time DateUtils truncate

Introduction

In this page you can find the example usage for org.apache.commons.lang.time DateUtils truncate.

Prototype

public static Date truncate(Object date, int field) 

Source Link

Document

Truncate this date, leaving the field specified as the most significant field.

For example, if you had the datetime of 28 Mar 2002 13:45:01.231, if you passed with HOUR, it would return 28 Mar 2002 13:00:00.000.

Usage

From source file:org.fao.geonet.kernel.harvest.harvester.localfilesystem.LocalFsHarvesterFileVisitor.java

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    if (cancelMonitor.get()) {
        return FileVisitResult.TERMINATE;
    }/*from  ww  w.  j  a v  a2 s.  com*/

    try {
        if (file != null && file.getFileName() != null && file.getFileName().toString() != null
                && (file.getFileName().toString().endsWith(".xml")
                        || MEFLib.isValidArchiveExtensionForMEF(file.getFileName().toString()))) {

            result.totalMetadata++;

            if (LOGGER.isDebugEnabled() && result.totalMetadata % 1000 == 0) {
                long elapsedTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime);
                LOGGER.debug(result.totalMetadata + "records inserted in " + elapsedTime + " s ("
                        + result.totalMetadata / elapsedTime + " records/s).");
            }

            Path filePath = file.toAbsolutePath().normalize();
            if (MEFLib.isValidArchiveExtensionForMEF(file.getFileName().toString())) {
                processMef(file, filePath);
                return FileVisitResult.CONTINUE;
            }

            Element xml;
            try {
                LOGGER.debug("reading file: " + filePath);
                xml = Xml.loadFile(file);
            } catch (JDOMException e) { // JDOM problem
                LOGGER.debug("Error loading XML from file " + filePath + ", ignoring");
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.error(e);
                }
                result.badFormat++;
                return FileVisitResult.CONTINUE; // skip this one
            } catch (Throwable e) { // some other error
                LOGGER.debug("Error retrieving XML from file  " + filePath + ", ignoring");
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.error(e);
                }
                result.unretrievable++;
                return FileVisitResult.CONTINUE; // skip this one
            }

            // transform using importxslt if not none
            if (transformIt) {
                try {
                    xml = Xml.transform(xml, thisXslt);
                } catch (Exception e) {
                    LOGGER.debug("Cannot transform XML from file " + filePath + ", ignoring. Error was: "
                            + e.getMessage());
                    result.badFormat++;
                    return FileVisitResult.CONTINUE; // skip this one
                }
            }

            String schema = null;
            try {
                schema = dataMan.autodetectSchema(xml, null);
            } catch (Exception e) {
                result.unknownSchema++;
            }
            if (schema == null) {
                return FileVisitResult.CONTINUE;
            }

            try {
                params.getValidate().validate(dataMan, context, xml);
            } catch (Exception e) {
                LOGGER.debug("Cannot validate XML from file " + filePath + ", ignoring. Error was: "
                        + e.getMessage());
                result.doesNotValidate++;
                return FileVisitResult.CONTINUE; // skip this one
            }

            String uuid = getUuidFromFile(xml, filePath, schema);
            if (uuid == null || uuid.equals("")) {
                result.badFormat++;
                return FileVisitResult.CONTINUE;
            }

            String id = dataMan.getMetadataId(uuid);
            String changeDate = new ISODate(System.currentTimeMillis(), false).getDateAndTime();
            if (id == null) {
                // For new record change date will be the time of metadata xml date change or the date when
                // the record was harvested (if can't be obtained the metadata xml date change)
                String createDate;
                // or the last modified date of the file
                if (params.checkFileLastModifiedForUpdate) {
                    createDate = new ISODate(Files.getLastModifiedTime(file).toMillis(), false)
                            .getDateAndTime();
                } else {
                    try {
                        createDate = dataMan.extractDateModified(schema, xml);
                    } catch (Exception ex) {
                        LOGGER.error(
                                "LocalFilesystemHarvester - addMetadata - can't get metadata modified date for metadata uuid= "
                                        + uuid + " using current date for modified date");
                        createDate = new ISODate().toString();
                    }
                }

                LOGGER.debug("adding new metadata");
                id = addMetadata(xml, schema, uuid, createDate);
            } else {
                // Check last modified date of the file with the record change date
                // to check if an update is required
                if (params.checkFileLastModifiedForUpdate) {
                    Date fileDate = new Date(Files.getLastModifiedTime(file).toMillis());

                    final AbstractMetadata metadata = repo.findOne(id);
                    ISODate modified = new ISODate();
                    if (metadata != null && metadata.getDataInfo() != null) {
                        modified = metadata.getDataInfo().getChangeDate();
                    }

                    Date recordDate = modified.toDate();

                    changeDate = new ISODate(fileDate.getTime(), false).getDateAndTime();

                    LOGGER.debug(" File date is: " + filePath + "filePath / record date is: " + modified);

                    if (DateUtils.truncate(recordDate, Calendar.SECOND)
                            .before(DateUtils.truncate(fileDate, Calendar.SECOND))) {
                        LOGGER.debug("  Db record is older than file. Updating record with id: " + id);
                        updateMedata(xml, id, changeDate);
                    } else {
                        LOGGER.debug(
                                "  Db record is not older than last modified date of file. No need for update.");
                        result.unchangedMetadata++;
                    }
                } else {
                    id = dataMan.getMetadataId(uuid);
                    if (id == null) {
                        // For new record change date will be the time of metadata xml date change or the date when
                        // the record was harvested (if can't be obtained the metadata xml date change)
                        String createDate;
                        // or the last modified date of the file
                        if (params.checkFileLastModifiedForUpdate) {
                            createDate = new ISODate(Files.getLastModifiedTime(file).toMillis(), false)
                                    .getDateAndTime();
                        } else {
                            try {
                                createDate = dataMan.extractDateModified(schema, xml);
                            } catch (Exception ex) {
                                LOGGER.error(
                                        "LocalFilesystemHarvester - addMetadata - can't get metadata modified date for metadata uuid= "
                                                +

                                                uuid + ", using current date for modified date");
                                createDate = new ISODate().toString();
                            }
                        }

                        LOGGER.debug("adding new metadata");
                        id = harvester.addMetadata(xml, uuid, schema, localGroups, localCateg, createDate,
                                aligner, false);
                        listOfRecordsToIndex.add(Integer.valueOf(id));
                        result.addedMetadata++;
                    } else {
                        // Check last modified date of the file with the record change date
                        // to check if an update is required
                        if (params.checkFileLastModifiedForUpdate) {
                            Date fileDate = new Date(Files.getLastModifiedTime(file).toMillis());

                            final AbstractMetadata metadata = repo.findOne(id);
                            final ISODate modified;
                            if (metadata != null && metadata.getDataInfo() != null) {
                                modified = metadata.getDataInfo().getChangeDate();
                            } else {
                                modified = new ISODate();
                            }

                            Date recordDate = modified.toDate();

                            changeDate = new ISODate(fileDate.getTime(), false).getDateAndTime();

                            LOGGER.debug(
                                    " File date is: " + fileDate.toString() + " / record date is: " + modified);

                            if (DateUtils.truncate(recordDate, Calendar.SECOND)
                                    .before(DateUtils.truncate(fileDate, Calendar.SECOND))) {
                                LOGGER.debug("  Db record is older than file. Updating record with id: " + id);
                                harvester.updateMetadata(xml, id, localGroups, localCateg, changeDate, aligner);
                                listOfRecordsToIndex.add(Integer.valueOf(id));
                                result.updatedMetadata++;
                            } else {
                                LOGGER.debug(
                                        "  Db record is not older than last modified date of file. No need for update.");
                                result.unchangedMetadata++;
                            }
                        } else {
                            LOGGER.debug("  updating existing metadata, id is: " + id);

                            try {
                                changeDate = dataMan.extractDateModified(schema, xml);
                            } catch (Exception ex) {
                                LOGGER.error(
                                        "LocalFilesystemHarvester - updateMetadata - can't get metadata modified date for "
                                                + "metadata id= " + id
                                                + ", using current date for modified date");
                                changeDate = new ISODate().toString();
                            }

                            harvester.updateMetadata(xml, id, localGroups, localCateg, changeDate, aligner);
                            listOfRecordsToIndex.add(Integer.valueOf(id));
                            result.updatedMetadata++;
                        }
                    }

                    updateMedata(xml, id, changeDate);
                }
            }
            listOfRecords.add(Integer.valueOf(id));
        }
    } catch (Throwable e) {
        LOGGER.error("An error occurred while harvesting a local file:{}. Error is: " + e.getMessage());
    }
    return FileVisitResult.CONTINUE;
}

From source file:org.flowable.engine.test.api.event.JobEventsTest.java

/**
 * Test job canceled and timer scheduled events for reschedule.
 *//*www.  j a va 2 s  . co m*/
@Deployment
public void testJobEntityEventsForRescheduleTimer() throws Exception {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("testJobEventsForReschedule");
    Job originalTimerJob = managementService.createTimerJobQuery().processInstanceId(processInstance.getId())
            .singleResult();
    assertNotNull(originalTimerJob);

    // Check if create-event has been dispatched
    assertEquals(3, listener.getEventsReceived().size());
    FlowableEngineEvent event = (FlowableEngineEvent) listener.getEventsReceived().get(0);
    assertEquals(FlowableEngineEventType.ENTITY_CREATED, event.getType());
    checkEventContext(event, originalTimerJob);

    event = (FlowableEngineEvent) listener.getEventsReceived().get(1);
    assertEquals(FlowableEngineEventType.ENTITY_INITIALIZED, event.getType());
    checkEventContext(event, originalTimerJob);

    event = (FlowableEngineEvent) listener.getEventsReceived().get(2);
    assertEquals(FlowableEngineEventType.TIMER_SCHEDULED, event.getType());
    checkEventContext(event, originalTimerJob);

    listener.clearEventsReceived();

    // Reschedule the timer
    managementService.rescheduleTimeDurationJob(originalTimerJob.getId(), "PT2H");

    Job rescheduledJob = managementService.createTimerJobQuery().processInstanceId(processInstance.getId())
            .singleResult();
    assertNotNull(rescheduledJob);
    assertNotSame(originalTimerJob.getId(), rescheduledJob.getId());

    assertEquals(5, listener.getEventsReceived().size());
    event = (FlowableEngineEvent) listener.getEventsReceived().get(0);
    assertEquals(FlowableEngineEventType.ENTITY_DELETED, event.getType());
    checkEventContext(event, originalTimerJob);

    Job deletedJob = (Job) ((FlowableEntityEvent) event).getEntity();
    checkEventContext(event, deletedJob);

    event = (FlowableEngineEvent) listener.getEventsReceived().get(1);
    Job newJob = (Job) ((FlowableEntityEvent) event).getEntity();
    assertEquals(FlowableEngineEventType.ENTITY_CREATED, event.getType());
    checkEventContext(event, newJob);
    checkEventContext(event, rescheduledJob);
    assertEquals(newJob.getId(), rescheduledJob.getId());

    event = (FlowableEngineEvent) listener.getEventsReceived().get(2);
    assertEquals(FlowableEngineEventType.ENTITY_INITIALIZED, event.getType());
    newJob = (Job) ((FlowableEntityEvent) event).getEntity();
    checkEventContext(event, newJob);

    event = (FlowableEngineEvent) listener.getEventsReceived().get(3);
    assertEquals(FlowableEngineEventType.JOB_RESCHEDULED, event.getType());
    Job newTimerJob = (Job) ((FlowableEntityEvent) event).getEntity();
    checkEventContext(event, rescheduledJob);
    assertEquals(rescheduledJob.getId(), newTimerJob.getId());
    assertEquals(DateUtils.truncate(rescheduledJob.getDuedate(), Calendar.SECOND),
            DateUtils.truncate(newTimerJob.getDuedate(), Calendar.SECOND));

    event = (FlowableEngineEvent) listener.getEventsReceived().get(4);
    assertEquals(FlowableEngineEventType.TIMER_SCHEDULED, event.getType());
    newJob = (Job) ((FlowableEntityEvent) event).getEntity();
    checkEventContext(event, newJob);

    listener.clearEventsReceived();

    // Force timer to fire
    Calendar tomorrow = Calendar.getInstance();
    tomorrow.add(Calendar.DAY_OF_YEAR, 1);
    processEngineConfiguration.getClock().setCurrentTime(tomorrow.getTime());
    managementService.moveTimerToExecutableJob(rescheduledJob.getId());
    managementService.executeJob(rescheduledJob.getId());

    // Check delete-event has been dispatched
    assertEquals(6, listener.getEventsReceived().size());

    event = (FlowableEngineEvent) listener.getEventsReceived().get(0);
    assertEquals(FlowableEngineEventType.ENTITY_CREATED, event.getType());
    checkEventContext(event, rescheduledJob);

    event = (FlowableEngineEvent) listener.getEventsReceived().get(1);
    assertEquals(FlowableEngineEventType.ENTITY_INITIALIZED, event.getType());
    checkEventContext(event, rescheduledJob);

    // First, a timer fired event has been dispatched
    event = (FlowableEngineEvent) listener.getEventsReceived().get(3);
    assertEquals(FlowableEngineEventType.TIMER_FIRED, event.getType());
    checkEventContext(event, rescheduledJob);

    // Next, a delete event has been dispatched
    event = (FlowableEngineEvent) listener.getEventsReceived().get(4);
    assertEquals(FlowableEngineEventType.ENTITY_DELETED, event.getType());
    checkEventContext(event, rescheduledJob);

    // Finally, a complete event has been dispatched
    event = (FlowableEngineEvent) listener.getEventsReceived().get(5);
    assertEquals(FlowableEngineEventType.JOB_EXECUTION_SUCCESS, event.getType());
    checkEventContext(event, rescheduledJob);

    checkEventCount(0, FlowableEngineEventType.TIMER_SCHEDULED);
}

From source file:org.hibernate.search.test.dsl.embedded.DslEmbeddedSearchTest.java

private static Calendar initCalendar(int year, int month, int day) {
    Calendar instance = createCalendar();
    instance = DateUtils.truncate(instance, Calendar.DATE);
    instance.set(year, month, day);/*ww  w  .  j  a va 2 s  . c o m*/
    return instance;
}

From source file:org.hibersap.util.DateUtil.java

public static Date stripTime(final Date date) {
    return DateUtils.truncate(date, Calendar.DAY_OF_MONTH);
}

From source file:org.hyperic.hq.measurement.server.session.DataManagerImpl.java

private Map<Date, List<TopNData>> mapDayToData(List<TopNData> topNData) {
    Map<Date, List<TopNData>> dayToDataMap = new HashMap<Date, List<TopNData>>();
    for (TopNData data : topNData) {
        Date day = DateUtils.truncate(data.getTime(), Calendar.DAY_OF_MONTH);
        List<TopNData> datas = dayToDataMap.get(day);
        if (datas == null) {
            dayToDataMap.put(day, new LinkedList<TopNData>());
        }/*from  www  .ja v  a2s  .  co m*/
        dayToDataMap.get(day).add(data);
    }
    return dayToDataMap;
}

From source file:org.hyperic.hq.measurement.server.session.ReportProcessorImpl.java

public void handleTopNReport(List<TopReport> reports, String agentToken) throws DataInserterException {
    final boolean debug = log.isDebugEnabled();
    final StopWatch watch = new StopWatch();
    DataInserter<TopNData> d = measurementInserterManager.getTopNInserter();
    List<TopNData> topNs = new LinkedList<TopNData>();
    Agent agent = null;/*  w  ww  .ja  v a  2s  . c  o  m*/
    try {
        agent = agentManager.getAgent(agentToken);
    } catch (AgentNotFoundException e) {
        log.warn("Recieved a Top Process report from an unknown agent with token '" + agentToken
                + "' , ignoring the report");
        return;
    }
    if (agent == null) {
        log.error("agent associated with token=" + agentToken + " is null, ignoring report");
        return;
    }
    final Platform platform = platformManager.getPlatformByAgentId(agent.getId());
    final Resource platformRes = (platform == null) ? null : platform.getResource();
    if (platformRes == null) {
        return;
    }
    int resourceId = platformRes.getId();
    for (TopReport report : reports) {
        Date minute = DateUtils.truncate(new Date(report.getCreateTime()), Calendar.MINUTE);
        try {
            TopNData topNData = new TopNData(resourceId, minute, report.toSerializedForm());
            topNs.add(topNData);
        } catch (IOException e) {
            log.error("Error serializing TopN data: " + e, e);
        }
    }

    if (debug) {
        watch.markTimeBegin("insertTopNToDB");
    }
    try {
        d.insertData(topNs);
    } catch (InterruptedException e) {
        throw new SystemException("Interrupted while attempting to insert topN data", e);
    }
    if (debug) {
        watch.markTimeEnd("insertTopNToDB");
    }
}

From source file:org.jasig.schedassist.impl.caldav.integration.CaldavIntegrationTest.java

/**
 * Basic workflow integration test://from   w  ww .j a v  a 2s .  c  om
 * <ol>
 * <li>Create an individual appointment using mock owner and visitor ("owner1" and "visitor1")</li>
 * <li>Verify event retrieved via {@link ICalendarDataDao#getExistingAppointment(org.jasig.schedassist.model.IScheduleOwner, AvailableBlock)}</li>
 * <li>Verify event contains expected properties and parameters</li>
 * <li>Cancel appointment, verify removed</li>
 * </ol>
 */
@Test
public void testCreateAndCancelIndividualAppointment() {
    // starts now
    Date start = DateUtils.truncate(new Date(), java.util.Calendar.MINUTE);
    Date end = DateUtils.addHours(start, 1);
    final DateTime ical4jstart = new DateTime(start);
    final DateTime ical4jend = new DateTime(end);

    AvailableBlock block = AvailableBlockBuilder.createBlock(start, end, 1);
    MockScheduleOwner owner1 = new MockScheduleOwner(ownerCalendarAccount1, 1);
    owner1.setPreference(Preferences.MEETING_PREFIX, "test appointment");
    owner1.setPreference(Preferences.LOCATION, "meeting room 1a");

    MockScheduleVisitor visitor1 = new MockScheduleVisitor(visitorCalendarAccount1);
    VEvent event = this.calendarDataDao.createAppointment(visitor1, owner1, block,
            "testCreateAndCancelIndividualAppointment");
    Assert.assertNotNull(event);

    VEvent lookupResult = this.calendarDataDao.getExistingAppointment(owner1, block);
    Assert.assertNotNull(lookupResult);
    Assert.assertEquals(ical4jstart, lookupResult.getStartDate().getDate());
    Assert.assertEquals(ical4jend, lookupResult.getEndDate().getDate());
    Assert.assertEquals(SchedulingAssistantAppointment.TRUE,
            lookupResult.getProperty(SchedulingAssistantAppointment.AVAILABLE_APPOINTMENT));
    Assert.assertEquals(1, Integer.parseInt(lookupResult.getProperty(VisitorLimit.VISITOR_LIMIT).getValue()));

    Assert.assertEquals(2, lookupResult.getProperties(Attendee.ATTENDEE).size());

    Property visitorAttendee = this.eventUtils.getAttendeeForUserFromEvent(event, visitorCalendarAccount1);
    Assert.assertNotNull(visitorAttendee);
    Assert.assertEquals(AppointmentRole.VISITOR,
            visitorAttendee.getParameter(AppointmentRole.APPOINTMENT_ROLE));

    Property ownerAttendee = this.eventUtils.getAttendeeForUserFromEvent(event, ownerCalendarAccount1);
    Assert.assertNotNull(ownerAttendee);
    Assert.assertEquals(AppointmentRole.OWNER, ownerAttendee.getParameter(AppointmentRole.APPOINTMENT_ROLE));

    this.calendarDataDao.cancelAppointment(visitor1, owner1, event);
    VEvent lookupResultAfterCancel = this.calendarDataDao.getExistingAppointment(owner1, block);
    Assert.assertNull(lookupResultAfterCancel);
}

From source file:org.jasig.schedassist.impl.caldav.integration.CaldavIntegrationTest.java

/**
 * Basic workflow integration test:// ww  w  . j ava 2  s .  c om
 * <ol>
 * <li>Create an individual appointment using mock resource and visitor ("resource1" and "visitor1")</li>
 * <li>Verify event retrieved via {@link ICalendarDataDao#getExistingAppointment(org.jasig.schedassist.model.IScheduleOwner, AvailableBlock)}</li>
 * <li>Verify event contains expected properties and parameters</li>
 * <li>Cancel appointment, verify removed</li>
 * </ol>
 */
@Test
public void testCreateAndCancelIndividualAppointmentDelegateOwner() {
    // starts now
    Date start = DateUtils.truncate(new Date(), java.util.Calendar.MINUTE);
    Date end = DateUtils.addHours(start, 1);
    final DateTime ical4jstart = new DateTime(start);
    final DateTime ical4jend = new DateTime(end);

    AvailableBlock block = AvailableBlockBuilder.createBlock(start, end, 1);
    MockScheduleOwner owner1 = new MockScheduleOwner(resourceCalendarAccount1, 1);
    owner1.setPreference(Preferences.MEETING_PREFIX, "test resource appointment");
    owner1.setPreference(Preferences.LOCATION, "meeting room 1a");

    MockScheduleVisitor visitor1 = new MockScheduleVisitor(visitorCalendarAccount1);
    VEvent event = this.calendarDataDao.createAppointment(visitor1, owner1, block,
            "testCreateAndCancelIndividualAppointmentDelegateOwner");
    Assert.assertNotNull(event);

    VEvent lookupResult = this.calendarDataDao.getExistingAppointment(owner1, block);
    Assert.assertNotNull(lookupResult);
    Assert.assertEquals(ical4jstart, lookupResult.getStartDate().getDate());
    Assert.assertEquals(ical4jend, lookupResult.getEndDate().getDate());
    Assert.assertEquals(SchedulingAssistantAppointment.TRUE,
            lookupResult.getProperty(SchedulingAssistantAppointment.AVAILABLE_APPOINTMENT));
    Assert.assertEquals(1, Integer.parseInt(lookupResult.getProperty(VisitorLimit.VISITOR_LIMIT).getValue()));

    Assert.assertEquals(2, lookupResult.getProperties(Attendee.ATTENDEE).size());

    Property visitorAttendee = this.eventUtils.getAttendeeForUserFromEvent(event, visitorCalendarAccount1);
    Assert.assertNotNull(visitorAttendee);
    Assert.assertEquals(AppointmentRole.VISITOR,
            visitorAttendee.getParameter(AppointmentRole.APPOINTMENT_ROLE));

    Property ownerAttendee = this.eventUtils.getAttendeeForUserFromEvent(event, resourceCalendarAccount1);
    Assert.assertNotNull(ownerAttendee);
    Assert.assertEquals(AppointmentRole.OWNER, ownerAttendee.getParameter(AppointmentRole.APPOINTMENT_ROLE));

    this.calendarDataDao.cancelAppointment(visitor1, owner1, event);
    VEvent lookupResultAfterCancel = this.calendarDataDao.getExistingAppointment(owner1, block);
    Assert.assertNull(lookupResultAfterCancel);
}

From source file:org.jasig.schedassist.impl.caldav.integration.CaldavIntegrationTest.java

/**
 * Integration test to create and manipulate a group appointment.
 * <ol>// w  w w. j  a  v  a 2  s.c  o  m
 * <li>Visitor1 creates group appointment with Owner1</li>
 * <li>Visitor2 joins same appointment</li>
 * <li>Visitor1 leaves same appointment</li>
 * <li>Visitor2 cancels appointment</li>
 * </ol>
 * 
 * @throws SchedulingException 
 */
@Test
public void testGroupAppointmentWorkflow() {
    // start an hour from now to avoid conflicts with individual apppointment
    Date startDate = DateUtils.truncate(DateUtils.addHours(new Date(), 1), java.util.Calendar.MINUTE);
    Date endDate = DateUtils.addHours(startDate, 1);
    final DateTime ical4jstart = new DateTime(startDate);
    final DateTime ical4jend = new DateTime(endDate);
    AvailableBlock block = AvailableBlockBuilder.createBlock(startDate, endDate, 2);

    MockScheduleOwner owner1 = new MockScheduleOwner(ownerCalendarAccount1, 1);
    owner1.setPreference(Preferences.MEETING_PREFIX, "group appointment");
    owner1.setPreference(Preferences.LOCATION, "meeting room 1b");
    MockScheduleVisitor visitor1 = new MockScheduleVisitor(visitorCalendarAccount1);

    VEvent original = this.calendarDataDao.createAppointment(visitor1, owner1, block,
            "testGroupAppointmentWorkflow");
    Assert.assertNotNull(original);
    VEvent lookup1 = this.calendarDataDao.getExistingAppointment(owner1, block);
    Assert.assertNotNull(lookup1);
    Assert.assertEquals(SchedulingAssistantAppointment.TRUE,
            lookup1.getProperty(SchedulingAssistantAppointment.AVAILABLE_APPOINTMENT));
    Assert.assertEquals(2, Integer.parseInt(lookup1.getProperty(VisitorLimit.VISITOR_LIMIT).getValue()));
    Assert.assertEquals(2, lookup1.getProperties(Attendee.ATTENDEE).size());
    Property visitorAttendee = this.eventUtils.getAttendeeForUserFromEvent(lookup1,
            visitor1.getCalendarAccount());
    Assert.assertNotNull(visitorAttendee);
    Assert.assertEquals(AppointmentRole.VISITOR,
            visitorAttendee.getParameter(AppointmentRole.APPOINTMENT_ROLE));
    Property ownerAttendee = this.eventUtils.getAttendeeForUserFromEvent(lookup1, owner1.getCalendarAccount());
    Assert.assertNotNull(ownerAttendee);
    Assert.assertEquals(AppointmentRole.OWNER, ownerAttendee.getParameter(AppointmentRole.APPOINTMENT_ROLE));

    Assert.assertEquals(ical4jstart, lookup1.getStartDate().getDate());
    Assert.assertEquals(ical4jend, lookup1.getEndDate().getDate());
    Assert.assertEquals(SchedulingAssistantAppointment.TRUE,
            lookup1.getProperty(SchedulingAssistantAppointment.AVAILABLE_APPOINTMENT));
    Assert.assertEquals(2, Integer.parseInt(lookup1.getProperty(VisitorLimit.VISITOR_LIMIT).getValue()));
    Assert.assertEquals(2, lookup1.getProperties(Attendee.ATTENDEE).size());

    MockScheduleVisitor visitor2 = new MockScheduleVisitor(visitorCalendarAccount2);

    // make 2nd visitor join
    try {
        this.calendarDataDao.joinAppointment(visitor2, owner1, lookup1);
    } catch (SchedulingException e) {
        Assert.fail("caught SchedulingException when visitor2 attempts join: " + e);
    }
    VEvent lookup2 = this.calendarDataDao.getExistingAppointment(owner1, block);
    Assert.assertNotNull(lookup2);
    Assert.assertEquals(ical4jstart, lookup2.getStartDate().getDate());
    Assert.assertEquals(ical4jend, lookup2.getEndDate().getDate());
    Assert.assertEquals(SchedulingAssistantAppointment.TRUE,
            lookup2.getProperty(SchedulingAssistantAppointment.AVAILABLE_APPOINTMENT));
    Assert.assertEquals(2, Integer.parseInt(lookup2.getProperty(VisitorLimit.VISITOR_LIMIT).getValue()));
    Assert.assertEquals(3, lookup2.getProperties(Attendee.ATTENDEE).size());
    PropertyList attendeeList = lookup2.getProperties(Attendee.ATTENDEE);
    for (Object o : attendeeList) {
        Attendee attendee = (Attendee) o;
        Parameter participationStatus = attendee.getParameter(PartStat.PARTSTAT);
        Assert.assertEquals(PartStat.ACCEPTED, participationStatus);
        if (AppointmentRole.OWNER.equals(attendee.getParameter(AppointmentRole.APPOINTMENT_ROLE))) {
            Assert.assertEquals("mailto:" + owner1.getCalendarAccount().getEmailAddress(), attendee.getValue());
        } else if (AppointmentRole.VISITOR.equals(attendee.getParameter(AppointmentRole.APPOINTMENT_ROLE))) {
            String value = attendee.getValue();
            if (value.equals("mailto:" + visitor1.getCalendarAccount().getEmailAddress())
                    || value.equals("mailto:" + visitor2.getCalendarAccount().getEmailAddress())) {
                // success
            } else {
                Assert.fail("unexpected visitor attendee value: " + value);
            }
        }
    }

    // now make visitor1 leave the appointment
    try {
        this.calendarDataDao.leaveAppointment(visitor1, owner1, lookup2);
    } catch (SchedulingException e) {
        Assert.fail("caught SchedulingException when visitor1 attempts leave: " + e);
    }
    VEvent lookup3 = this.calendarDataDao.getExistingAppointment(owner1, block);
    Assert.assertNotNull(lookup3);
    Assert.assertEquals(ical4jstart, lookup3.getStartDate().getDate());
    Assert.assertEquals(ical4jend, lookup3.getEndDate().getDate());
    Assert.assertEquals(SchedulingAssistantAppointment.TRUE,
            lookup3.getProperty(SchedulingAssistantAppointment.AVAILABLE_APPOINTMENT));
    Assert.assertEquals(2, Integer.parseInt(lookup3.getProperty(VisitorLimit.VISITOR_LIMIT).getValue()));
    Assert.assertEquals(2, lookup3.getProperties(Attendee.ATTENDEE).size());
    attendeeList = lookup3.getProperties(Attendee.ATTENDEE);
    for (Object o : attendeeList) {
        Attendee attendee = (Attendee) o;
        Parameter participationStatus = attendee.getParameter(PartStat.PARTSTAT);
        Assert.assertEquals(PartStat.ACCEPTED, participationStatus);
        if (AppointmentRole.OWNER.equals(attendee.getParameter(AppointmentRole.APPOINTMENT_ROLE))) {
            Assert.assertEquals("mailto:" + owner1.getCalendarAccount().getEmailAddress(), attendee.getValue());
        } else if (AppointmentRole.VISITOR.equals(attendee.getParameter(AppointmentRole.APPOINTMENT_ROLE))) {
            String value = attendee.getValue();
            if (value.equals("mailto:" + visitor2.getCalendarAccount().getEmailAddress())) {
                // success
            } else {
                Assert.fail("unexpected visitor attendee value: " + value);
            }
        }
    }

    this.calendarDataDao.cancelAppointment(visitor2, owner1, lookup3);
    VEvent lookupResultAfterCancel = this.calendarDataDao.getExistingAppointment(owner1, block);
    Assert.assertNull(lookupResultAfterCancel);
}

From source file:org.jasig.schedassist.impl.oraclecalendar.DefaultOracleCalendarDaoImplTest.java

/**
 * //from w  w w . j  ava  2  s  . c  o  m
 * @throws Exception
 */
@Test
public void testCreateAndCancel() throws Exception {
    // construct owner from traditional user account
    OracleCalendarUserAccount user = new OracleCalendarUserAccount();
    user.setUsername("npblair");
    user.setCtcalxitemid("20000:01182");
    user.setDisplayName("NICHOLAS P BLAIR");
    user.setEmailAddress("nblair@doit.wisc.edu");
    user.setGivenName("NICHOLAS");
    user.setSurname("BLAIR");

    MockScheduleOwner owner = new MockScheduleOwner(user, 1);
    owner.setPreference(Preferences.MEETING_PREFIX, "prefix");
    owner.setPreference(Preferences.LOCATION, "meeting room");

    // construct visitor from traditional user account
    OracleCalendarUserAccount visitorUser = new OracleCalendarUserAccount();
    visitorUser.setUsername("jstalnak");
    visitorUser.setCtcalxitemid("20000:01220");
    visitorUser.setDisplayName("JAMES G STALNAKER");
    visitorUser.setEmailAddress("jstalnak@doit.wisc.edu");
    visitorUser.setGivenName("JAMES");
    visitorUser.setSurname("STALNAKER");
    MockScheduleVisitor visitor = new MockScheduleVisitor(visitorUser);

    Date startDate = DateUtils.truncate(new Date(), java.util.Calendar.MINUTE);
    Date endDate = DateUtils.addHours(startDate, 1);
    final DateTime ical4jstart = new DateTime(startDate);
    final DateTime ical4jend = new DateTime(endDate);
    AvailableBlock block = AvailableBlockBuilder.createBlock(startDate, endDate, 1);
    VEvent event = oracleCalendarDao.createAppointment(visitor, owner, block, "testCreateEvent");
    Assert.assertNotNull(event);

    VEvent lookupResult = oracleCalendarDao.getExistingAppointment(owner, block);
    Assert.assertNotNull(lookupResult);
    Assert.assertEquals(ical4jstart, lookupResult.getStartDate().getDate());
    Assert.assertEquals(ical4jend, lookupResult.getEndDate().getDate());
    Assert.assertEquals(SchedulingAssistantAppointment.TRUE,
            lookupResult.getProperty(SchedulingAssistantAppointment.AVAILABLE_APPOINTMENT));
    Assert.assertEquals(1, Integer.parseInt(lookupResult.getProperty(VisitorLimit.VISITOR_LIMIT).getValue()));
    Assert.assertEquals(2, lookupResult.getProperties(Attendee.ATTENDEE).size());
    Property visitorAttendee = this.oracleEventUtils.getAttendeeForUserFromEvent(lookupResult,
            visitor.getCalendarAccount());
    Assert.assertNotNull(visitorAttendee);
    Assert.assertEquals(AppointmentRole.VISITOR,
            visitorAttendee.getParameter(AppointmentRole.APPOINTMENT_ROLE));
    Property ownerAttendee = this.oracleEventUtils.getAttendeeForUserFromEvent(lookupResult,
            owner.getCalendarAccount());
    Assert.assertNotNull(ownerAttendee);
    Assert.assertEquals(AppointmentRole.OWNER, ownerAttendee.getParameter(AppointmentRole.APPOINTMENT_ROLE));
    Assert.assertEquals("testCreateEvent", lookupResult.getDescription().getValue());

    oracleCalendarDao.cancelAppointment(visitor, owner, event);
    VEvent lookupResultAfterCancel = oracleCalendarDao.getExistingAppointment(owner, block);
    Assert.assertNull(lookupResultAfterCancel);
}