Example usage for java.util Date equals

List of usage examples for java.util Date equals

Introduction

In this page you can find the example usage for java.util Date equals.

Prototype

public boolean equals(Object obj) 

Source Link

Document

Compares two dates for equality.

Usage

From source file:org.sigmah.server.endpoint.gwtrpc.handler.calendar.ActivityCalendarHandler.java

@Override
public Calendar getCalendar(Serializable identifier) {
    if (!(identifier instanceof ActivityCalendarIdentifier)) {
        throw new IllegalArgumentException(
                "Identifier must be an instance of ActivityCalendarIdentifier, received an instance of "
                        + identifier.getClass().getSimpleName());
    }//from   w w  w . j a v  a  2  s  .  com

    final ActivityCalendarIdentifier activityCalendarIdentifier = (ActivityCalendarIdentifier) identifier;

    em.clear();
    final Query query = em.createQuery("SELECT l FROM LogFrame l WHERE l.parentProject.id = :projectId");
    query.setParameter("projectId", activityCalendarIdentifier.getProjectId());

    // Configuring the calendar
    final Calendar calendar = new Calendar();
    calendar.setIdentifier(identifier);
    calendar.setName(activityCalendarIdentifier.getCalendarName());
    calendar.setEditable(false);

    final HashMap<Date, List<Event>> eventMap = new HashMap<Date, List<Event>>();
    calendar.setEvents(eventMap);

    try {
        final LogFrame logFrame = (LogFrame) query.getSingleResult();

        // Preparing the activity code
        final StringBuilder codeBuilder = new StringBuilder(activityCalendarIdentifier.getActivityPrefix());
        codeBuilder.append(' ');

        // Looping on the logical framework objects
        final List<SpecificObjective> specificObjectives = logFrame.getSpecificObjectives();
        for (final SpecificObjective specificObjective : specificObjectives) {
            int baseSize = codeBuilder.length();
            codeBuilder.append((char) ('A' + specificObjective.getCode() - 1));
            codeBuilder.append('.');

            final List<ExpectedResult> expectedResults = specificObjective.getExpectedResults();
            for (final ExpectedResult expectedResult : expectedResults) {
                int specificObjectiveSize = codeBuilder.length();
                codeBuilder.append(expectedResult.getCode());
                codeBuilder.append('.');

                // For each activity
                final List<LogFrameActivity> activities = expectedResult.getActivities();
                for (final LogFrameActivity activity : activities) {
                    int expectedResultSize = codeBuilder.length();
                    codeBuilder.append(activity.getCode());
                    codeBuilder.append('.');

                    final Date startDate = activity.getStartDate();

                    if (activity.getTitle() != null) {
                        codeBuilder.append(' ');
                        codeBuilder.append(activity.getTitle());
                    }

                    // For each day
                    if (startDate != null) {
                        //if activity end date is not spcified set its value to start date
                        if (activity.getEndDate() == null) {
                            activity.setEndDate(startDate);
                        }

                        for (Date date = new Date(startDate.getYear(), startDate.getMonth(),
                                startDate.getDate()); date.compareTo(activity.getEndDate()) < 1; date
                                        .setDate(date.getDate() + 1)) {
                            final Date key = new Date(date.getTime());

                            final Event event = new Event();
                            event.setSummary(codeBuilder.toString());
                            event.setDtstart(new Date(startDate.getTime()));

                            if (startDate.equals(activity.getEndDate())) {
                                event.setDtend(new Date(startDate.getYear(), startDate.getMonth(),
                                        startDate.getDate() + 1));
                            } else {
                                event.setDtend(new Date(activity.getEndDate().getTime()));
                            }

                            event.setParent(calendar);
                            event.setIdentifier(activity.getId());

                            // Adding the event to the event map
                            List<Event> list = eventMap.get(key);
                            if (list == null) {
                                list = new ArrayList<Event>();
                                eventMap.put(key, list);
                            }
                            list.add(event);
                        }
                    }

                    codeBuilder.setLength(expectedResultSize);
                }

                codeBuilder.setLength(specificObjectiveSize);
            }

            codeBuilder.setLength(baseSize);
        }
    } catch (NoResultException e) {
        // No activities in the current project
    }

    return calendar;
}

From source file:org.structr.web.servlet.HtmlServlet.java

private static boolean notModifiedSince(final HttpServletRequest request, HttpServletResponse response,
        final AbstractNode node, final boolean dontCache) {

    boolean notModified = false;
    final Date lastModified = node.getLastModifiedDate();

    // add some caching directives to header
    // see http://weblogs.java.net/blog/2007/08/08/expires-http-header-magic-number-yslow
    final DateFormat httpDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    httpDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

    response.setHeader("Date", httpDateFormat.format(new Date()));

    final Calendar cal = new GregorianCalendar();
    final Integer seconds = node.getProperty(Page.cacheForSeconds);

    if (!dontCache && seconds != null) {

        cal.add(Calendar.SECOND, seconds);
        response.setHeader("Cache-Control", "max-age=" + seconds + ", s-maxage=" + seconds + "");
        response.setHeader("Expires", httpDateFormat.format(cal.getTime()));

    } else {// www  . jav a  2s. c  o m

        if (!dontCache) {
            response.setHeader("Cache-Control", "no-cache, must-revalidate, proxy-revalidate");
        } else {
            response.setHeader("Cache-Control",
                    "private, no-cache, no-store, max-age=0, s-maxage=0, must-revalidate, proxy-revalidate");
        }

    }

    if (lastModified != null) {

        final Date roundedLastModified = DateUtils.round(lastModified, Calendar.SECOND);
        response.setHeader("Last-Modified", httpDateFormat.format(roundedLastModified));

        final String ifModifiedSince = request.getHeader("If-Modified-Since");

        if (StringUtils.isNotBlank(ifModifiedSince)) {

            try {

                Date ifModSince = httpDateFormat.parse(ifModifiedSince);

                // Note that ifModSince has not ms resolution, so the last digits are always 000
                // That requires the lastModified to be rounded to seconds
                if ((ifModSince != null)
                        && (roundedLastModified.equals(ifModSince) || roundedLastModified.before(ifModSince))) {

                    notModified = true;

                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    response.setHeader("Vary", "Accept-Encoding");

                }

            } catch (ParseException ex) {
                logger.log(Level.WARNING, "Could not parse If-Modified-Since header", ex);
            }

        }

    }

    return notModified;
}

From source file:de.ingrid.iplug.scheduler.FileJobStore.java

private boolean applyMisfire(SchedulingContext ctxt, Trigger trigger) throws JobPersistenceException {
    long misfireTime = System.currentTimeMillis() - getMisfireThreshold();
    Date nextFireTime = trigger.getNextFireTime();
    if (nextFireTime.getTime() > misfireTime) {
        return false; // we are in time
    }//from  ww  w  .  j  a  v a  2  s.co  m

    // notify for misfire
    this.fSignaler.notifyTriggerListenersMisfired(trigger);

    // calculate next fire time
    Calendar calender = retrieveCalendar(null, trigger.getCalendarName());
    trigger.updateAfterMisfire(calender);
    if (trigger.getNextFireTime() == null) {
        setTriggerState(ctxt, trigger, Trigger.STATE_COMPLETE);
        synchronized (this.fTriggersByName) {
            this.fOrderedTriggers.remove(trigger);
        }
    } else if (nextFireTime.equals(trigger.getNextFireTime()))
        return false;

    return true;
}

From source file:org.craftercms.cstudio.alfresco.dm.script.DmWorkflowServiceScript.java

protected List<DmDependencyTO> getChildrenForRenamedItem(String site, DmDependencyTO renameItem) {
    ServicesConfig servicesConfig = getServicesManager().getService(ServicesConfig.class);
    PersistenceManagerService persistenceManagerService = getServicesManager()
            .getService(PersistenceManagerService.class);
    String siteRoot = servicesConfig.getRepositoryRootPath(site);
    List<DmDependencyTO> toRet = new FastList<DmDependencyTO>();
    List<DmDependencyTO> children = renameItem.getChildren();
    Date date = renameItem.getScheduledDate();
    if (children != null) {
        Iterator<DmDependencyTO> childItr = children.iterator();
        while (childItr.hasNext()) {
            DmDependencyTO child = childItr.next();
            Date pageDate = child.getScheduledDate();
            if ((date == null && pageDate != null) || (date != null && !date.equals(pageDate))) {
                if (!renameItem.isNow()) {
                    child.setNow(false);
                    if (date != null && (pageDate != null && pageDate.before(date))) {
                        child.setScheduledDate(date);
                    }//from  www .ja  v  a  2  s.c  o m
                }
                toRet.add(child);
                List<DmDependencyTO> childDeps = child.flattenChildren();
                for (DmDependencyTO childDep : childDeps) {
                    String depPath = siteRoot + childDep.getUri();
                    ObjectStateService.State depState = persistenceManagerService.getObjectState(depPath);
                    if (ObjectStateService.State.isUpdateOrNew(depState)) {
                        toRet.add(childDep);
                    }
                }
                child.setReference(false);
                childItr.remove();
            }
        }
    }
    return toRet;
}

From source file:org.flowable.engine.impl.cmd.SaveTaskCmd.java

public Void execute(CommandContext commandContext) {
    if (task == null) {
        throw new FlowableIllegalArgumentException("task is null");
    }/*from   ww  w. ja  v a 2 s  .  c  om*/

    if (task.getProcessDefinitionId() != null
            && Flowable5Util.isFlowable5ProcessDefinitionId(commandContext, task.getProcessDefinitionId())) {
        Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler();
        compatibilityHandler.saveTask(task);
        return null;
    }

    if (task.getRevision() == 0) {
        commandContext.getTaskEntityManager().insert(task, null);

        if (commandContext.getEventDispatcher().isEnabled()) {
            commandContext.getEventDispatcher().dispatchEvent(
                    FlowableEventBuilder.createEntityEvent(FlowableEngineEventType.TASK_CREATED, task));
        }

    } else {

        TaskInfo originalTaskEntity = null;
        if (commandContext.getProcessEngineConfiguration().getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) {
            originalTaskEntity = commandContext.getHistoricTaskInstanceEntityManager().findById(task.getId());
        }

        if (originalTaskEntity == null) {
            originalTaskEntity = commandContext.getTaskEntityManager().findById(task.getId());
        }

        String originalName = originalTaskEntity.getName();
        String originalAssignee = originalTaskEntity.getAssignee();
        String originalOwner = originalTaskEntity.getOwner();
        String originalDescription = originalTaskEntity.getDescription();
        Date originalDueDate = originalTaskEntity.getDueDate();
        int originalPriority = originalTaskEntity.getPriority();
        String originalCategory = originalTaskEntity.getCategory();
        String originalFormKey = originalTaskEntity.getFormKey();
        String originalParentTaskId = originalTaskEntity.getParentTaskId();
        String originalTaskDefinitionKey = originalTaskEntity.getTaskDefinitionKey();

        // Only update history if history is enabled
        if (commandContext.getProcessEngineConfiguration().getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) {

            if (!StringUtils.equals(originalName, task.getName())) {
                commandContext.getHistoryManager().recordTaskNameChange(task.getId(), task.getName());
            }
            if (!StringUtils.equals(originalDescription, task.getDescription())) {
                commandContext.getHistoryManager().recordTaskDescriptionChange(task.getId(),
                        task.getDescription());
            }
            if ((originalDueDate == null && task.getDueDate() != null)
                    || (originalDueDate != null && task.getDueDate() == null)
                    || (originalDueDate != null && !originalDueDate.equals(task.getDueDate()))) {
                commandContext.getHistoryManager().recordTaskDueDateChange(task.getId(), task.getDueDate());
            }
            if (originalPriority != task.getPriority()) {
                commandContext.getHistoryManager().recordTaskPriorityChange(task.getId(), task.getPriority());
            }
            if (!StringUtils.equals(originalCategory, task.getCategory())) {
                commandContext.getHistoryManager().recordTaskCategoryChange(task.getId(), task.getCategory());
            }
            if (!StringUtils.equals(originalFormKey, task.getFormKey())) {
                commandContext.getHistoryManager().recordTaskFormKeyChange(task.getId(), task.getFormKey());
            }
            if (!StringUtils.equals(originalParentTaskId, task.getParentTaskId())) {
                commandContext.getHistoryManager().recordTaskParentTaskIdChange(task.getId(),
                        task.getParentTaskId());
            }
            if (!StringUtils.equals(originalTaskDefinitionKey, task.getTaskDefinitionKey())) {
                commandContext.getHistoryManager().recordTaskDefinitionKeyChange(task.getId(),
                        task.getTaskDefinitionKey());
            }

        }

        if (!StringUtils.equals(originalOwner, task.getOwner())) {
            if (task.getProcessInstanceId() != null) {
                commandContext.getIdentityLinkEntityManager().involveUser(task.getProcessInstance(),
                        task.getOwner(), IdentityLinkType.PARTICIPANT);
            }
            commandContext.getHistoryManager().recordTaskOwnerChange(task.getId(), task.getOwner());
        }
        if (!StringUtils.equals(originalAssignee, task.getAssignee())) {
            if (task.getProcessInstanceId() != null) {
                commandContext.getIdentityLinkEntityManager().involveUser(task.getProcessInstance(),
                        task.getAssignee(), IdentityLinkType.PARTICIPANT);
            }
            commandContext.getHistoryManager().recordTaskAssigneeChange(task.getId(), task.getAssignee());

            commandContext.getProcessEngineConfiguration().getListenerNotificationHelper()
                    .executeTaskListeners(task, TaskListener.EVENTNAME_ASSIGNMENT);
            commandContext.getHistoryManager().recordTaskAssignment(task);

            if (commandContext.getEventDispatcher().isEnabled()) {
                commandContext.getEventDispatcher().dispatchEvent(
                        FlowableEventBuilder.createEntityEvent(FlowableEngineEventType.TASK_ASSIGNED, task));
            }

        }

        commandContext.getTaskEntityManager().update(task);

    }

    return null;
}

From source file:org.activiti.engine.impl.cmd.SaveTaskCmd.java

public Void execute(CommandContext commandContext) {
    if (task == null) {
        throw new ActivitiIllegalArgumentException("task is null");
    }//from  ww w  . jav  a2  s  . c  om

    if (task.getProcessDefinitionId() != null
            && Activiti5Util.isActiviti5ProcessDefinitionId(commandContext, task.getProcessDefinitionId())) {
        Activiti5CompatibilityHandler activiti5CompatibilityHandler = Activiti5Util
                .getActiviti5CompatibilityHandler();
        activiti5CompatibilityHandler.saveTask(task);
        return null;
    }

    if (task.getRevision() == 0) {
        commandContext.getTaskEntityManager().insert(task, null);

        if (commandContext.getEventDispatcher().isEnabled()) {
            commandContext.getEventDispatcher().dispatchEvent(
                    ActivitiEventBuilder.createEntityEvent(ActivitiEventType.TASK_CREATED, task));
        }

    } else {

        TaskInfo originalTaskEntity = null;
        if (commandContext.getProcessEngineConfiguration().getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) {
            originalTaskEntity = commandContext.getHistoricTaskInstanceEntityManager().findById(task.getId());
        }

        if (originalTaskEntity == null) {
            originalTaskEntity = commandContext.getTaskEntityManager().findById(task.getId());
        }

        String originalName = originalTaskEntity.getName();
        String originalAssignee = originalTaskEntity.getAssignee();
        String originalOwner = originalTaskEntity.getOwner();
        String originalDescription = originalTaskEntity.getDescription();
        Date originalDueDate = originalTaskEntity.getDueDate();
        int originalPriority = originalTaskEntity.getPriority();
        String originalCategory = originalTaskEntity.getCategory();
        String originalFormKey = originalTaskEntity.getFormKey();
        String originalParentTaskId = originalTaskEntity.getParentTaskId();
        String originalTaskDefinitionKey = originalTaskEntity.getTaskDefinitionKey();

        // Only update history if history is enabled
        if (commandContext.getProcessEngineConfiguration().getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) {

            if (!StringUtils.equals(originalName, task.getName())) {
                commandContext.getHistoryManager().recordTaskNameChange(task.getId(), task.getName());
            }
            if (!StringUtils.equals(originalDescription, task.getDescription())) {
                commandContext.getHistoryManager().recordTaskDescriptionChange(task.getId(),
                        task.getDescription());
            }
            if ((originalDueDate == null && task.getDueDate() != null)
                    || (originalDueDate != null && task.getDueDate() == null)
                    || (originalDueDate != null && !originalDueDate.equals(task.getDueDate()))) {
                commandContext.getHistoryManager().recordTaskDueDateChange(task.getId(), task.getDueDate());
            }
            if (originalPriority != task.getPriority()) {
                commandContext.getHistoryManager().recordTaskPriorityChange(task.getId(), task.getPriority());
            }
            if (!StringUtils.equals(originalCategory, task.getCategory())) {
                commandContext.getHistoryManager().recordTaskCategoryChange(task.getId(), task.getCategory());
            }
            if (!StringUtils.equals(originalFormKey, task.getFormKey())) {
                commandContext.getHistoryManager().recordTaskFormKeyChange(task.getId(), task.getFormKey());
            }
            if (!StringUtils.equals(originalParentTaskId, task.getParentTaskId())) {
                commandContext.getHistoryManager().recordTaskParentTaskIdChange(task.getId(),
                        task.getParentTaskId());
            }
            if (!StringUtils.equals(originalTaskDefinitionKey, task.getTaskDefinitionKey())) {
                commandContext.getHistoryManager().recordTaskDefinitionKeyChange(task.getId(),
                        task.getTaskDefinitionKey());
            }

        }

        if (!StringUtils.equals(originalOwner, task.getOwner())) {
            if (task.getProcessInstanceId() != null) {
                commandContext.getIdentityLinkEntityManager().involveUser(task.getProcessInstance(),
                        task.getOwner(), IdentityLinkType.PARTICIPANT);
            }
            commandContext.getHistoryManager().recordTaskOwnerChange(task.getId(), task.getOwner());
        }
        if (!StringUtils.equals(originalAssignee, task.getAssignee())) {
            if (task.getProcessInstanceId() != null) {
                commandContext.getIdentityLinkEntityManager().involveUser(task.getProcessInstance(),
                        task.getAssignee(), IdentityLinkType.PARTICIPANT);
            }
            commandContext.getHistoryManager().recordTaskAssigneeChange(task.getId(), task.getAssignee());

            commandContext.getProcessEngineConfiguration().getListenerNotificationHelper()
                    .executeTaskListeners(task, TaskListener.EVENTNAME_ASSIGNMENT);
            commandContext.getHistoryManager().recordTaskAssignment(task);

            if (commandContext.getEventDispatcher().isEnabled()) {
                commandContext.getEventDispatcher().dispatchEvent(
                        ActivitiEventBuilder.createEntityEvent(ActivitiEventType.TASK_ASSIGNED, task));
            }

        }

        commandContext.getTaskEntityManager().update(task);

    }

    return null;
}

From source file:fragment.web.BillingControllerTest.java

@Test
public void testTerminateSubscription() {
    Tenant tenant = createTestTenant(accountTypeDAO.getDefaultRegistrationAccountType());
    tenant.setState(com.vmops.model.Tenant.State.ACTIVE);
    tenant.setAccountType(accountTypeDAO.getDefaultRegistrationAccountType());
    User user = createTestUserInTenant(tenant);
    tenantService.setOwner(tenant, user);
    List<ProductBundle> bundles = productBundleService.listProductBundles(0, 0);
    ProductBundle nonVmBundle = null;//from   ww w  .j a v  a2s  .c om
    for (ProductBundle bundle : bundles) {
        if (!bundle.getResourceType().getResourceTypeName().equals("VirtualMachine")) {
            nonVmBundle = bundle;
            break;
        }
    }
    tenant.getOwner().setEnabled(true);
    Subscription subscription = subscriptionService.createSubscription(tenant.getOwner(), nonVmBundle, null,
            null, false, false, null, new HashMap<String, String>());
    Assert.assertNotNull(subscription);
    SubscriptionHandle subscriptionHandle = new SubscriptionHandle(subscription, "",
            subscription.getServiceInstance().getUuid(), "VirtualMachine", user, State.ACTIVE, null, null,
            "TestVM");
    subscription.addHandle(subscriptionHandle);
    subscriptionDAO.merge(subscription);
    prepareMockForTerminateAndCancelSubscriptionDetails(tenant.getOwner());
    Date timeBeforeTermination = new Date();
    Subscription sub = controller.terminateSubscription(subscription.getParam(), map);
    Assert.assertNotNull(sub);
    Assert.assertTrue((timeBeforeTermination.before(sub.getTerminationDateWithTime())
            || timeBeforeTermination.equals(sub.getTerminationDateWithTime())));
    Assert.assertEquals(sub.getState().name(), new String("EXPIRED"));
    Assert.assertEquals(State.TERMINATED, sub.getHandle().getState());

}

From source file:org.dataconservancy.dcs.access.server.MediciServiceImpl.java

private Stats checkStatus(String statusUrl, String submitterId, String datasetTitle, String wfInstanceId,
        Date latestDate, String sipBasePath, int totalNumOfEntities, int totalNumOfFiles) {

    Map<Date, List<Event>> events = (new DepositServiceImpl()).statusUpdate(statusUrl, latestDate, 0);

    List<Date> sortedDates = new ArrayList<Date>();
    Map<Date, List<Event>> tempEvents = new HashMap<Date, List<Event>>(events);
    Iterator iterator = tempEvents.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<Date, List<Event>> pair = (Map.Entry<Date, List<Event>>) iterator.next();
        sortedDates.add(pair.getKey());//from www . j av  a  2s  .co  m
        iterator.remove();
    }
    Stats stats = new Stats();

    Collections.sort(sortedDates);
    String previousEvent = null;
    int sortedDatesCount = 0;
    for (Date date : sortedDates) {
        sortedDatesCount++;
        if (date.after(latestDate) || date.equals(latestDate)) {
            //get events from that date and fire events accordingly
            int tmpEventsCount = 0;
            List<Event> currentEvents = events.get(date);
            Collections.sort(currentEvents);
            for (final Event event : currentEvents) {
                tmpEventsCount++;
                if (event.getEventType().equalsIgnoreCase(Events.FIXITY_DIGEST))//why are we skipping fixity digest?
                    continue;
                //if complete, do something

                if (event.getEventType().contains("match")) {
                    stats.latestDate = latestDate;

                    ProvenanceRecord provRecord = new ProvenanceRecord();
                    String[] arr = sipBasePath.split("_sip")[0].split("/");
                    String datasetId = arr[arr.length - 1];
                    provRecord.setDatasetId(datasetId);
                    provRecord.setWfInstanceId(wfInstanceId);
                    provRecord.setDatasetTitle(datasetTitle);
                    provRecord.setSipId(statusUrl);
                    provRecord.setDate(
                            //                              latestDate
                            event.getEventDate());
                    provRecord.setSubmitterId(submitterId);
                    provRecord.setStatus(
                            org.dataconservancy.dcs.access.shared.Status.fromString(stats.status.getText()));
                    Event provEvent = new Event();
                    provEvent.setEventPercent(100);
                    provEvent.setEventType(event.getEventType());
                    provEvent.setEventDate(
                            //                              latestDate
                            event.getEventDate());
                    provEvent.setEventDetail(event.getEventDetail());
                    provRecord.addEvent(provEvent);

                    provDao.insertProvenanceRecord(provRecord);

                    continue;
                    //possibly re-submit?

                }
                if (event.getEventType().equalsIgnoreCase("ingest.complete")) {
                    stats.latestDate = latestDate;
                    stats.status = Status.Completed;

                    ProvenanceRecord provRecord = new ProvenanceRecord();
                    String[] arr = sipBasePath.split("_sip")[0].split("/");
                    String datasetId = arr[arr.length - 1];
                    provRecord.setDatasetId(datasetId);
                    provRecord.setWfInstanceId(wfInstanceId);
                    provRecord.setDatasetTitle(datasetTitle);
                    provRecord.setSipId(statusUrl);
                    provRecord.setDate(
                            //                                 latestDate
                            event.getEventDate());
                    provRecord.setSubmitterId(submitterId);
                    provRecord.setStatus(
                            org.dataconservancy.dcs.access.shared.Status.fromString(stats.status.getText()));
                    Event provEvent = new Event();
                    provEvent.setEventPercent(100);
                    provEvent.setEventType(event.getEventType());
                    provEvent.setEventDate(
                            //                                 latestDate
                            event.getEventDate());
                    provEvent.setEventDetail(event.getEventDetail());
                    provRecord.addEvent(provEvent);

                    provDao.insertProvenanceRecord(provRecord);

                    return stats;
                    //possibly re-submit?

                } //if failed, do something
                if (event.getEventType().contains("fail")) {

                    stats.latestDate = latestDate;
                    stats.status = Status.Failed;
                    ProvenanceRecord provRecord = new ProvenanceRecord();
                    String[] arr = sipBasePath.split("_sip")[0].split("/");
                    String datasetId = arr[arr.length - 1];
                    provRecord.setDatasetId(datasetId);
                    provRecord.setDatasetTitle(datasetTitle);
                    provRecord.setSipId(statusUrl);
                    provRecord.setWfInstanceId(wfInstanceId);
                    provRecord.setDate(
                            //                              latestDate
                            event.getEventDate());
                    provRecord.setSubmitterId(submitterId);
                    provRecord.setStatus(
                            org.dataconservancy.dcs.access.shared.Status.fromString(stats.status.getText()));
                    Event provEvent = new Event();
                    provEvent.setEventPercent(100);
                    provEvent.setEventType(event.getEventType());
                    provEvent.setEventDate(
                            //                              latestDate
                            event.getEventDate());
                    provEvent.setEventDetail(event.getEventDetail());
                    provRecord.addEvent(provEvent);

                    provDao.insertProvenanceRecord(provRecord);
                    return stats;
                }

                else {//else just insert new event values in the database possibly

                    stats.status = Status.Pending;

                    if (previousEvent != null && previousEvent.equals(event.getEventType())
                            && Constants.multiEventMessages.contains(previousEvent)) {//Case #1 - continuation of an event
                        finishedFiles++;
                        int number = 0;
                        if (Constants.multiEventCheck.get(event.getEventType()) == 1)
                            number = totalNumOfFiles;
                        else
                            number = totalNumOfEntities;

                        //In the case below, we handle completion of a multi-event (finishedFiles==number) or completion of the list of events in which case the last event could have completed upto, say 60% - both inner and outer loop (sortedDatesCount==sortedDates.size()&&tmpEventsCount==tmpEvents.size())
                        if ((sortedDatesCount == sortedDates.size() && tmpEventsCount == currentEvents.size())
                                || finishedFiles == number)//case #4 - 100% completion of a continued task
                        {
                            event.setEventPercent(finishedFiles / number * 100);

                            ProvenanceRecord provRecord = new ProvenanceRecord();
                            String[] arr = sipBasePath.split("_sip")[0].split("/");
                            String datasetId = arr[arr.length - 1];
                            provRecord.setDatasetId(datasetId);
                            provRecord.setDatasetTitle(datasetTitle);
                            provRecord.setSipId(statusUrl);
                            provRecord.setWfInstanceId(wfInstanceId);
                            provRecord.setDate(latestDate);
                            provRecord.setSubmitterId(submitterId);
                            provRecord.setStatus(org.dataconservancy.dcs.access.shared.Status
                                    .fromString(stats.status.getText()));//This is the status of the whole SIP and not for the particular task. For the particular task, status is indicated by percent
                            Event provEvent = new Event();
                            provEvent.setEventPercent(finishedFiles / number * 100);
                            provEvent.setEventType(event.getEventType());
                            provEvent.setEventDate(latestDate);
                            provEvent.setEventDetail(event.getEventDetail());
                            provRecord.addEvent(provEvent);
                            provDao.insertProvenanceRecord(provRecord);
                            if (finishedFiles == number)
                                finishedFiles = 0;
                        }
                        previousEvent = event.getEventType();
                    } else {
                        if (previousEvent == null) {//case #2-First event
                            finishedFiles++;

                            if (!Constants.multiEventMessages.contains(event.getEventType())) //case #2.a - Done only once
                            {
                                System.out.println(event.getEventType());
                                event.setEventPercent(
                                        //finishedFiles*100/1
                                        -10);
                                ProvenanceRecord provRecord = new ProvenanceRecord();
                                String[] arr = sipBasePath.split("_sip")[0].split("/");
                                String datasetId = arr[arr.length - 1];
                                provRecord.setDatasetId(datasetId);
                                provRecord.setDatasetTitle(datasetTitle);
                                provRecord.setSipId(statusUrl);
                                provRecord.setWfInstanceId(wfInstanceId);
                                provRecord.setDate(
                                        //                                       latestDate
                                        event.getEventDate());
                                provRecord.setSubmitterId(submitterId);
                                provRecord.setStatus(org.dataconservancy.dcs.access.shared.Status
                                        .fromString(stats.status.getText()));
                                Event provEvent = new Event();
                                provEvent.setEventType(event.getEventType());
                                provEvent.setEventPercent(100);
                                provEvent.setEventDate(
                                        //                                       latestDate
                                        event.getEventDate());
                                provEvent.setEventDetail(event.getEventDetail());
                                provRecord.addEvent(provEvent);
                                provDao.insertProvenanceRecord(provRecord);
                                finishedFiles = 0;
                            } else {
                                //Multi-event message first event
                                //Do nothing
                                //till the event changes or till end of this event in the list - it might be done only 60% during this status check
                            }

                            previousEvent = event.getEventType();//else case #1
                        } else if (!previousEvent.equals(event.getEventType())) {//Case #3 - New event
                            finishedFiles++;
                            if (!Constants.multiEventMessages.contains(event.getEventType())) //case #3.a - Done only once
                            {
                                event.setEventPercent(
                                        //finishedFiles*100/1
                                        -10);
                                ProvenanceRecord provRecord = new ProvenanceRecord();
                                String[] arr = sipBasePath.split("_sip")[0].split("/");
                                String datasetId = arr[arr.length - 1];
                                provRecord.setDatasetId(datasetId);
                                provRecord.setDatasetTitle(datasetTitle);
                                provRecord.setSipId(statusUrl);
                                provRecord.setWfInstanceId(wfInstanceId);
                                provRecord.setDate(
                                        //                                       latestDate
                                        event.getEventDate());
                                provRecord.setSubmitterId(submitterId);
                                provRecord.setStatus(org.dataconservancy.dcs.access.shared.Status
                                        .fromString(stats.status.getText()));
                                Event provEvent = new Event();
                                provEvent.setEventPercent(100);
                                provEvent.setEventType(event.getEventType());
                                provEvent.setEventDate(
                                        //                                       latestDate
                                        event.getEventDate());
                                provEvent.setEventDetail(event.getEventDetail());
                                provRecord.addEvent(provEvent);
                                provDao.insertProvenanceRecord(provRecord);
                                finishedFiles = 0;
                            } else {
                                //Multi-event message first event
                                //Do nothing
                                //till the event changes or till end of this event in the list - it might be done only 60% during this status check
                            }
                            previousEvent = event.getEventType();

                        }
                    }

                }
                //with 2 second gaps at the minimum
                latestDate = date;
            }

        }

        //Issues:
        //Some ACR instance with ip 71.x.x.x (check) keeps querying without escaping - send email about it
    }
    stats.latestDate = latestDate;
    return stats;
}

From source file:org.craftercms.cstudio.alfresco.dm.service.impl.DmSimpleWorkflowServiceImpl.java

protected boolean areEqual(Date oldDate, Date newDate) {
    if (oldDate == null && newDate == null) {
        return true;
    }/*from w ww.  j  a v a 2 s  .co  m*/
    if (oldDate != null && newDate != null) {
        return oldDate.equals(newDate);
    }
    return false;
}