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.egov.egf.commons.EgovCommon.java

/**
 * This API returns List of Map, Map containing Amount, VoucherNumber, VoucherDate, BillNumber & BillId of passed projectcode
 * and. Vouchers selected accross funds. Vouchers selected within asOnDate Financial Year.
 *
 * @author chetan//from  www.j  a  v a 2s . c  o m
 * @param projectCodeId
 * @param asOnDate
 * @return
 * @throws ApplicationRuntimeException
 */
public List<Map<String, String>> getExpenditureDetailsforProjectforFinYear(final Long projectCodeId,
        final Date asOnDate) throws ApplicationRuntimeException {
    LOGGER.debug("Starting getExpenditureDetailsforProjectforFinYear .....");
    if (projectCodeId.equals(Long.valueOf(0)))
        throw new ApplicationRuntimeException("ProjectCode is null or empty");
    if (asOnDate == null || asOnDate.equals(null))
        throw new ApplicationRuntimeException("asOnDate is null");
    final Accountdetailkey adk = (Accountdetailkey) persistenceService.find(
            "FROM Accountdetailkey where accountdetailtype.name='PROJECTCODE' and detailkey=?",
            projectCodeId.intValue());
    if (adk == null || adk.equals(null))
        throw new ApplicationRuntimeException("There is no project code");

    final CFinancialYear finYear = financialYearDAO.getFinancialYearByDate(asOnDate);
    final Date startDate = finYear.getStartingDate();

    final List<Map<String, String>> result = new ArrayList<Map<String, String>>();

    final String queryForGLList = "SELECT gld.amount, vh.id, vh.voucherNumber, vh.voucherDate, egmis.billid, egbill.billnumber "
            + "FROM generalledger gl, generalledgerdetail gld, accountdetailkey adk, accountdetailtype adt, voucherheader vh left outer join eg_billregistermis egmis on vh.id=egmis.voucherheaderid left outer join eg_billregister egbill on egmis.billid=egbill.id "
            + "WHERE gl.id           = gld.generalledgerid AND gl.voucherheaderid= vh.id AND gld.detailtypeid  = adt.id "
            + "AND gld.detailkeyid   = adk.detailkey AND adt.name          ='PROJECTCODE' AND adk.detailtypeid  = adt.id "
            + "AND adk.detailkey     =" + projectCodeId + " AND gl.debitamount<>0 AND vh.voucherdate>='"
            + Constants.DDMMYYYYFORMAT1.format(startDate) + "' AND vh.voucherdate<='"
            + Constants.DDMMYYYYFORMAT1.format(asOnDate) + "' AND vh.status=0";

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("queryForGLList >> " + queryForGLList);
    final List<Object[]> generalLedgerList = persistenceService.getSession().createSQLQuery(queryForGLList)
            .list();
    for (final Object[] objects : generalLedgerList) {
        if (LOGGER.isInfoEnabled())
            LOGGER.info("Project code has vouchers.");
        final Map<String, String> mp = new HashMap<String, String>();
        if (objects[0].toString() != null)
            mp.put("Amount", objects[0].toString());
        if (objects[2] != null && objects[3] != null) {
            mp.put("VoucherNumber", objects[2].toString());
            mp.put("VoucherDate", Constants.DDMMYYYYFORMAT2.format(objects[3]));
        }
        if (objects[4] != null && objects[5] != null) {
            mp.put("BillNumber", objects[5].toString());
            mp.put("BillId", objects[4].toString());
        }
        result.add(mp);
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Completed getExpenditureDetailsforProjectforFinYear.");
    return result;
}

From source file:org.egov.egf.commons.EgovCommon.java

/**
 * This API returns List of Map, Map containing Amount, VoucherNumber, VoucherDate, BillNumber & BillId of passed Depositcode
 * and till passed date. Vouchers selected accross funds and financial year.
 *
 * @author chetan/*from  w  w  w.j a v  a  2s. c o  m*/
 * @param depositCodeId
 * @param asOnDate
 * @return List<Map<String, String>>
 * @throws ApplicationRuntimeException
 */
public List<Map<String, String>> getExpenditureDetailsforDepositCode(final Long depositCodeId,
        final Date asOnDate) throws ApplicationRuntimeException {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Starting getExpenditureDetailsforDepositCode .....");
    if (depositCodeId.equals(Long.valueOf(0)))
        throw new ApplicationRuntimeException("DepositCode is null or empty");
    if (asOnDate == null || asOnDate.equals(null))
        throw new ApplicationRuntimeException("asOnDate is null");
    final Accountdetailkey adk = (Accountdetailkey) persistenceService.find(
            "FROM Accountdetailkey where accountdetailtype.name='DEPOSITCODE' and detailkey=?",
            depositCodeId.intValue());
    if (adk == null || adk.equals(null))
        throw new ApplicationRuntimeException("There is no such Deposit code");

    final List<Map<String, String>> result = new ArrayList<Map<String, String>>();

    final String queryForGLList = "SELECT gld.amount, vh.id, vh.voucherNumber, vh.voucherDate, egmis.billid, egbill.billnumber "
            + "FROM generalledger gl, generalledgerdetail gld, accountdetailkey adk, accountdetailtype adt, voucherheader vh left outer join eg_billregistermis egmis on vh.id=egmis.voucherheaderid left outer join eg_billregister egbill on egmis.billid=egbill.id "
            + "WHERE gl.id           = gld.generalledgerid AND gl.voucherheaderid= vh.id AND gld.detailtypeid  = adt.id "
            + "AND gld.detailkeyid   = adk.detailkey AND adt.name          ='DEPOSITCODE' AND adk.detailtypeid  = adt.id "
            + "AND adk.detailkey     =" + depositCodeId + " AND gl.debitamount<>0 AND vh.voucherdate<='"
            + Constants.DDMMYYYYFORMAT1.format(asOnDate) + "' AND vh.status=0";

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("queryForGLList >> " + queryForGLList);
    final List<Object[]> generalLedgerList = persistenceService.getSession().createSQLQuery(queryForGLList)
            .list();
    for (final Object[] objects : generalLedgerList) {
        if (LOGGER.isInfoEnabled())
            LOGGER.info("Deposit code has vouchers.");
        final Map<String, String> mp = new HashMap<String, String>();
        if (objects[0].toString() != null)
            mp.put("Amount", objects[0].toString());
        if (objects[2] != null && objects[3] != null) {
            mp.put("VoucherNumber", objects[2].toString());
            mp.put("VoucherDate", Constants.DDMMYYYYFORMAT2.format(objects[3]));
        }
        if (objects[4] != null && objects[5] != null) {
            mp.put("BillNumber", objects[5].toString());
            mp.put("BillId", objects[4].toString());
        }
        result.add(mp);
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Completed getExpenditureDetailsforDepositCode.");
    return result;
}

From source file:org.egov.egf.commons.EgovCommon.java

/**
 * This API returns List of Map, Map containing Amount, VoucherNumber, VoucherDate, BillNumber & BillId of passed projectcode
 * and till passed date. Vouchers selected accross funds and financial year.
 *
 * @author chetan//w ww. j ava2  s  .  c  o m
 * @param projectCodeId
 * @param asOnDate
 * @return List<Map<String, String>>
 * @throws ApplicationRuntimeException
 */
public List<Map<String, String>> getExpenditureDetailsforProject(final Long projectCodeId, final Date asOnDate)
        throws ApplicationRuntimeException {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Starting getExpenditureDetailsforProject .....");
    if (projectCodeId.equals(Long.valueOf(0)))
        throw new ApplicationRuntimeException("ProjectCode is null or empty");
    if (asOnDate == null || asOnDate.equals(null))
        throw new ApplicationRuntimeException("asOnDate is null");
    final Accountdetailkey adk = (Accountdetailkey) persistenceService.find(
            "FROM Accountdetailkey where accountdetailtype.name='PROJECTCODE' and detailkey=?",
            projectCodeId.intValue());
    if (adk == null || adk.equals(null))
        throw new ApplicationRuntimeException("There is no project code");

    final List<Map<String, String>> result = new ArrayList<Map<String, String>>();

    final String queryForGLList = "SELECT gld.amount, vh.id, vh.voucherNumber, vh.voucherDate, egmis.billid, egbill.billnumber "
            + "FROM generalledger gl, generalledgerdetail gld, accountdetailkey adk, accountdetailtype adt, voucherheader vh left outer join eg_billregistermis egmis on vh.id=egmis.voucherheaderid left outer join eg_billregister egbill on egmis.billid=egbill.id "
            + "WHERE gl.id           = gld.generalledgerid AND gl.voucherheaderid= vh.id AND gld.detailtypeid  = adt.id "
            + "AND gld.detailkeyid   = adk.detailkey AND adt.name          ='PROJECTCODE' AND adk.detailtypeid  = adt.id "
            + "AND adk.detailkey     =" + projectCodeId + " AND gl.debitamount<>0 AND vh.voucherdate<='"
            + Constants.DDMMYYYYFORMAT1.format(asOnDate) + "' AND vh.status=0";

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("queryForGLList >> " + queryForGLList);
    final List<Object[]> generalLedgerList = persistenceService.getSession().createSQLQuery(queryForGLList)
            .list();
    for (final Object[] objects : generalLedgerList) {
        if (LOGGER.isInfoEnabled())
            LOGGER.info("Project code has vouchers.");
        final Map<String, String> mp = new HashMap<String, String>();
        if (objects[0].toString() != null)
            mp.put("Amount", objects[0].toString());
        if (objects[2] != null && objects[3] != null) {
            mp.put("VoucherNumber", objects[2].toString());
            mp.put("VoucherDate", Constants.DDMMYYYYFORMAT2.format(objects[3]));
        }
        if (objects[4] != null && objects[5] != null) {
            mp.put("BillNumber", objects[5].toString());
            mp.put("BillId", objects[4].toString());
        }
        result.add(mp);
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Completed getExpenditureDetailsforProject.");
    return result;
}

From source file:org.rapla.storage.impl.server.LocalAbstractCachableOperator.java

protected void updateLastChanged(UpdateEvent evt) throws RaplaException {
    Date currentTime = getCurrentTimestamp();
    String userId = evt.getUserId();
    User lastChangedBy = (userId != null) ? resolve(userId, User.class) : null;

    for (Entity e : evt.getStoreObjects()) {
        if (e instanceof ModifiableTimestamp) {
            ModifiableTimestamp modifiableTimestamp = (ModifiableTimestamp) e;
            Date lastChangeTime = modifiableTimestamp.getLastChanged();
            if (lastChangeTime != null && lastChangeTime.equals(currentTime)) {
                // wait 1 ms to increase timestamp
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e1) {
                    throw new RaplaException(e1.getMessage(), e1);
                }/*from   w w w  .j av a  2  s .  c o  m*/
                currentTime = getCurrentTimestamp();
            }
            modifiableTimestamp.setLastChanged(currentTime);
            modifiableTimestamp.setLastChangedBy(lastChangedBy);
        }
    }
    for (PreferencePatch patch : evt.getPreferencePatches()) {
        patch.setLastChanged(currentTime);
    }
}

From source file:org.slc.sli.dashboard.manager.impl.PopulationManagerImpl.java

/**
 * Extracts grades from transcriptAssociationRecord based on sections in the
 * past. For each section where a transcript with final letter grade exist,
 * the grade is added to the list of grades for the semester.
 * /* ww w . j a v a 2 s  .  com*/
 * @param student
 * @param interSections
 * @param stuTransAssocs
 * @param curSessionEndDate
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private void addSemesterFinalGrades(GenericEntity student, List<Map<String, Object>> interSections,
        List<Map<String, Object>> stuTransAssocs, Date curSessionEndDate) {

    // populate the end dates for all the relevant sections
    List<Date> sectionDates = new LinkedList<Date>();
    sectionDates.add(curSessionEndDate);
    for (Map<String, Object> section : interSections) {
        List<Date> dates = getSessionDates(section);
        Date sectionEndDate = (dates == null) ? null : dates.get(1);
        if (sectionEndDate != null) {
            sectionDates.add(sectionEndDate);
        }
    }
    Collections.sort(sectionDates);
    // find the related sections chronologically preceding the current one
    // on the list
    Date prevDate = findPrevDate(sectionDates, curSessionEndDate);
    Date prevPrevDate = findPrevDate(sectionDates, prevDate);

    // Iterate through the course Id's and grab transcripts grades, once
    // we have NUMBER_OF_SEMESTERS transcript grades, we're done
    for (Map<String, Object> section : interSections) {

        if (section != null) {

            Map<String, Object> course = ((Map<String, Object>) section.get(Constants.ATTR_COURSES));
            if (course != null) {
                String courseId = (String) course.get(Constants.ATTR_ID);

                // we need to keep track of special cases, e.g. previous
                // semester and two
                // semesters ago
                // data
                List<Date> dates = getSessionDates(section);
                Date sectionEndDate = (dates == null) ? null : dates.get(1);
                String tag;
                if (sectionEndDate != null) {
                    if (prevDate != null && prevDate.equals(sectionEndDate)) {
                        // this is the previous semester's section
                        tag = "previousSemester";
                    } else if (prevPrevDate != null && prevPrevDate.equals(sectionEndDate)) {
                        // this is two semesters ago
                        tag = "twoSemestersAgo";
                    } else {
                        // this is neither of the cases of interest
                        continue;
                    }
                } else {
                    // no section end date means we cannot determine where
                    // this data belongs
                    continue;
                }

                // Find the correct course. If that course is found in
                // the transcript, then record that letter grade to the
                // semesterScores.
                for (Map<String, Object> assoc : stuTransAssocs) {
                    if (courseId.equalsIgnoreCase((String) assoc.get(Constants.ATTR_COURSE_ID))) {
                        String finalLetterGrade = (String) assoc.get(Constants.ATTR_FINAL_LETTER_GRADE);
                        String courseTitle = (String) course.get(Constants.ATTR_COURSE_TITLE);
                        if (finalLetterGrade != null) {
                            Map<String, Object> grade = new LinkedHashMap<String, Object>();
                            grade.put(Constants.SECTION_LETTER_GRADE, finalLetterGrade);
                            grade.put(Constants.SECTION_COURSE, courseTitle);
                            List<Map<String, Object>> semesterScores = (List<Map<String, Object>>) student
                                    .get(tag);
                            if (semesterScores == null) {
                                semesterScores = new ArrayList<Map<String, Object>>();
                            }
                            semesterScores.add(grade);
                            student.put(tag, semesterScores);
                            break;
                        }
                    }
                }
            }
        }

    }
}

From source file:org.jahia.services.search.facets.SimpleJahiaJcrFacets.java

/**
 * @deprecated Use getFacetRangeCounts which is more generalized
 *///from  ww  w. ja v a  2  s  .  c  om
@Deprecated
public void getFacetDateCounts(String dateFacet, NamedList<Object> resOuter)
        throws IOException, ParseException, RepositoryException, JahiaException {

    parseParams(FacetParams.FACET_DATE, dateFacet);
    String f = facetValue;

    final NamedList<Object> resInner = new SimpleOrderedMap<Object>();
    String fieldName = StringUtils.substringBeforeLast(f, PROPNAME_INDEX_SEPARATOR);
    ExtendedPropertyDefinition epd = NodeTypeRegistry.getInstance()
            .getNodeType(params.get("f." + f + ".facet.nodetype")).getPropertyDefinition(fieldName);
    String fieldNameInIndex = getFieldNameInIndex(f, fieldName, epd, params.getFieldParam(f, "facet.locale"));
    String prefix = params.getFieldParam(f, FacetParams.FACET_PREFIX);
    DateField ft = StringUtils.isEmpty(prefix) ? JahiaQueryParser.DATE_TYPE : JahiaQueryParser.JR_DATE_TYPE;
    final SchemaField sf = new SchemaField(fieldNameInIndex, ft);

    // TODO: Should we use the key now ?
    //    resOuter.add(key, resInner);
    resOuter.add(fieldName + PROPNAME_INDEX_SEPARATOR + fieldNameInIndex, resInner);

    if (!(epd.getRequiredType() == PropertyType.DATE)) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                "Can not date facet on a field which is not a DateField: " + f);
    }
    Integer minCount = params.getFieldInt(f, FacetParams.FACET_MINCOUNT);
    if (minCount == null) {
        Boolean zeros = params.getFieldBool(f, FacetParams.FACET_ZEROS);
        // mincount = (zeros!=null && zeros) ? 0 : 1;
        minCount = (zeros != null && !zeros) ? 1 : 0;
        // current default is to include zeros.
    }

    final String startS = required.getFieldParam(f, FacetParams.FACET_DATE_START);
    final Date start;
    try {
        start = JahiaQueryParser.DATE_TYPE.parseMath(NOW, startS);
    } catch (SolrException e) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                "date facet 'start' is not a valid Date string: " + startS, e);
    }
    final String endS = required.getFieldParam(f, FacetParams.FACET_DATE_END);
    Date end; // not final, hardend may change this
    try {
        end = JahiaQueryParser.DATE_TYPE.parseMath(NOW, endS);
    } catch (SolrException e) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                "date facet 'end' is not a valid Date string: " + endS, e);
    }

    if (end.before(start)) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                "date facet 'end' comes before 'start': " + endS + " < " + startS);
    }

    final String gap = required.getFieldParam(f, FacetParams.FACET_DATE_GAP);
    final DateMathParser dmp = new DateMathParser(DateField.UTC, Locale.US);
    dmp.setNow(NOW);

    String[] iStrs = params.getFieldParams(f, FacetParams.FACET_DATE_INCLUDE);
    // Legacy support for default of [lower,upper,edge] for date faceting
    // this is not handled by FacetRangeInclude.parseParam because
    // range faceting has differnet defaults
    final EnumSet<FacetRangeInclude> include = (null == iStrs || 0 == iStrs.length)
            ? EnumSet.of(FacetRangeInclude.LOWER, FacetRangeInclude.UPPER, FacetRangeInclude.EDGE)
            : FacetRangeInclude.parseParam(iStrs);

    try {
        Date low = start;
        while (low.before(end)) {
            dmp.setNow(low);
            String label = JahiaQueryParser.DATE_TYPE.toExternal(low);

            Date high = dmp.parseMath(gap);
            if (end.before(high)) {
                if (params.getFieldBool(f, FacetParams.FACET_DATE_HARD_END, false)) {
                    high = end;
                } else {
                    end = high;
                }
            }
            if (high.before(low)) {
                throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                        "date facet infinite loop (is gap negative?)");
            }
            final boolean includeLower = (include.contains(FacetRangeInclude.LOWER)
                    || (include.contains(FacetRangeInclude.EDGE) && low.equals(start)));
            final boolean includeUpper = (include.contains(FacetRangeInclude.UPPER)
                    || (include.contains(FacetRangeInclude.EDGE) && high.equals(end)));

            Query rangeQuery = getRangeQuery(ft, null, sf, prefix, low, high, includeLower, includeUpper);

            int count = rangeCount(rangeQuery);
            if (count >= minCount) {
                // TODO: Can we use just label here ?                  
                resInner.add(label + PROPNAME_INDEX_SEPARATOR + rangeQuery.toString(), count);
            }
            low = high;
        }
    } catch (java.text.ParseException e) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                "date facet 'gap' is not a valid Date Math string: " + gap, e);
    }

    // explicitly return the gap and end so all the counts are meaningful
    resInner.add("gap", gap);
    resInner.add("start", start);
    resInner.add("end", end);

    final String[] othersP = params.getFieldParams(f, FacetParams.FACET_DATE_OTHER);
    if (null != othersP && 0 < othersP.length) {
        final Set<FacetDateOther> others = EnumSet.noneOf(FacetDateOther.class);

        for (final String o : othersP) {
            others.add(FacetDateOther.get(o));
        }

        // no matter what other values are listed, we don't do
        // anything if "none" is specified.
        if (!others.contains(FacetDateOther.NONE)) {
            boolean all = others.contains(FacetDateOther.ALL);

            if (all || others.contains(FacetDateOther.BEFORE)) {
                Query rangeQuery = getRangeQuery(ft, null, sf, prefix, null, start, false,
                        (include.contains(FacetRangeInclude.OUTER)
                                || (!(include.contains(FacetRangeInclude.LOWER)
                                        || include.contains(FacetRangeInclude.EDGE)))));
                int count = rangeCount(rangeQuery);
                if (count >= minCount) {
                    resInner.add(
                            FacetDateOther.BEFORE.toString() + PROPNAME_INDEX_SEPARATOR + rangeQuery.toString(),
                            count);
                }
            }
            if (all || others.contains(FacetDateOther.AFTER)) {
                Query rangeQuery = getRangeQuery(ft, null, sf, prefix, end, null,
                        (include.contains(FacetRangeInclude.OUTER)
                                || (!(include.contains(FacetRangeInclude.UPPER)
                                        || include.contains(FacetRangeInclude.EDGE)))),
                        false);
                int count = rangeCount(rangeQuery);
                if (count >= minCount) {
                    resInner.add(
                            FacetDateOther.AFTER.toString() + PROPNAME_INDEX_SEPARATOR + rangeQuery.toString(),
                            count);
                }
            }
            if (all || others.contains(FacetDateOther.BETWEEN)) {
                Query rangeQuery = getRangeQuery(ft, null, sf, prefix, start, end,
                        (include.contains(FacetRangeInclude.LOWER) || include.contains(FacetRangeInclude.EDGE)),
                        (include.contains(FacetRangeInclude.UPPER)
                                || include.contains(FacetRangeInclude.EDGE)));
                int count = rangeCount(rangeQuery);
                if (count >= minCount) {
                    resInner.add(FacetDateOther.BETWEEN.toString() + PROPNAME_INDEX_SEPARATOR
                            + rangeQuery.toString(), count);
                }
            }
        }
    }
}

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

/**
 * Internal version of {@link #getExistingAppointment(ScheduleOwner, AvailableBlock)} that takes
 * (and uses) an existing {@link Session}.
 * /*  w w w  . j  a v a 2  s  .  c o  m*/
 * @param owner
 * @param block
 * @param session
 * @return
 * @throws StatusException
 * @throws ParserException
 */
protected VEvent getAvailableAppointmentInternal(IScheduleOwner owner, Date startTime, Date endTime,
        Session session) throws StatusException, ParserException {
    final DateTime ical4jstart = new DateTime(startTime);
    final DateTime ical4jend = new DateTime(endTime);
    String agenda = getCalendarInternal(owner.getCalendarAccount(), startTime, endTime, session);
    Calendar calendar = parseAgenda(agenda);
    ComponentList componentList = calendar.getComponents(VEvent.VEVENT);
    for (Object o : componentList) {
        VEvent event = (VEvent) o;
        Date eventStart = event.getStartDate().getDate();
        Date eventEnd = event.getEndDate(true).getDate();
        Property availableApptProperty = event
                .getProperty(SchedulingAssistantAppointment.AVAILABLE_APPOINTMENT);
        if (!SchedulingAssistantAppointment.TRUE.equals(availableApptProperty)) {
            // immediately skip over non-available appointments
            continue;
        }

        // check for version first
        Property versionProperty = event.getProperty(AvailableVersion.AVAILABLE_VERSION);
        if (null == versionProperty) {
            // this is a version 1.0 appointment
            // in version 1.0, the only check was to verify that visitor was an attendee
            return event;
        } else if (AvailableVersion.AVAILABLE_VERSION_1_1.equals(versionProperty)) {
            Property ownerAttendee = this.oracleEventUtils.getAttendeeForUserFromEvent(event,
                    owner.getCalendarAccount());
            if (ownerAttendee == null) {
                continue;
            }
            Parameter ownerAttendeeRole = ownerAttendee.getParameter(AppointmentRole.APPOINTMENT_ROLE);

            // event has to be (1) an available appointment
            // with (2) owner as AppointmentRole#OWNER (or AppointmentRole#BOTH)
            // (3) start and (4) end date have to match
            if ((AppointmentRole.BOTH.equals(ownerAttendeeRole)
                    || AppointmentRole.OWNER.equals(ownerAttendeeRole)) && eventStart.equals(startTime)
                    && eventEnd.equals(endTime)) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("getAvailableAppointment found " + event);
                }
                return event;
            }
        } else if (AvailableVersion.AVAILABLE_VERSION_1_2.equals(versionProperty)) {
            Parameter ownerAttendeeRole = null;
            Property ownerAttendee = this.oracleEventUtils.getAttendeeForUserFromEvent(event,
                    owner.getCalendarAccount());
            if (ownerAttendee == null) {
                // check for resource account
                Property resourceAttendee = event.getProperty(OracleResourceAttendee.ORACLE_RESOURCE_ATTENDEE);
                if (this.oracleEventUtils.attendeeMatchesPerson(resourceAttendee, owner.getCalendarAccount())) {
                    // resource accounts can only be OWNER role
                    ownerAttendeeRole = AppointmentRole.OWNER;
                }
            } else {
                ownerAttendeeRole = ownerAttendee.getParameter(AppointmentRole.APPOINTMENT_ROLE);
            }

            if (null == ownerAttendeeRole) {
                // owner role not on organizer or on attendee
                continue;
            }
            // event has to be (1) an available appointment
            // with (2) owner as AppointmentRole#OWNER (or AppointmentRole#BOTH)
            // (3) start and (4) end date have to match
            if ((AppointmentRole.BOTH.equals(ownerAttendeeRole)
                    || AppointmentRole.OWNER.equals(ownerAttendeeRole)) && eventStart.equals(ical4jstart)
                    && eventEnd.equals(ical4jend)) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("getAvailableAppointment found " + event);
                }

                return event;
            }
        }
    }
    if (LOG.isTraceEnabled()) {
        LOG.trace("getAvailableAppointment found no match for times: " + startTime + ", " + endTime
                + ", owner: " + owner);
    }
    return null;
}

From source file:org.rapla.storage.impl.server.LocalAbstractCachableOperator.java

private void checkAbandonedAppointments() {
    Collection<? extends Allocatable> allocatables = cache.getAllocatables();
    Logger logger = getLogger().getChildLogger("appointmentcheck");
    try {//from ww w  .j a  v  a  2  s.c o  m
        for (Allocatable allocatable : allocatables) {
            SortedSet<Appointment> appointmentSet = this.appointmentMap.get(allocatable.getId());
            if (appointmentSet == null) {
                continue;
            }
            for (Appointment app : appointmentSet) {
                {
                    SimpleEntity original = (SimpleEntity) app;
                    String id = original.getId();
                    if (id == null) {
                        logger.error("Empty id  for " + original);
                        continue;
                    }
                    Appointment persistant = cache.tryResolve(id, Appointment.class);
                    if (persistant == null) {
                        logger.error("appointment not stored in cache " + original);
                        continue;
                    }
                }
                Reservation reservation = app.getReservation();
                if (reservation == null) {
                    logger.error("Appointment without a reservation stored in cache " + app);
                    appointmentSet.remove(app);
                    continue;
                } else if (!reservation.hasAllocated(allocatable, app)) {
                    logger.error("Allocation is not stored correctly for " + reservation + " " + app + " "
                            + allocatable + " removing binding for " + app);
                    appointmentSet.remove(app);
                    continue;
                } else {
                    {
                        Reservation original = reservation;
                        String id = original.getId();
                        if (id == null) {
                            logger.error("Empty id  for " + original);
                            continue;
                        }
                        Reservation persistant = cache.tryResolve(id, Reservation.class);
                        if (persistant != null) {
                            Date lastChanged = original.getLastChanged();
                            Date persistantLastChanged = persistant.getLastChanged();
                            if (persistantLastChanged != null && !persistantLastChanged.equals(lastChanged)) {
                                logger.error(
                                        "Reservation stored in cache is not the same as in allocation store "
                                                + original);
                                continue;
                            }
                        } else {
                            logger.error("Reservation not stored in cache " + original
                                    + " removing binding for " + app);
                            appointmentSet.remove(app);
                            continue;
                        }
                    }

                }
            }
        }
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
}

From source file:gov.nih.nci.cabig.caaers.api.impl.AdverseEventManagementServiceImpl.java

private ValidationErrors validateRepPeriodDates(AdverseEventReportingPeriod rPeriod,
        List<AdverseEventReportingPeriod> rPeriodList, Date firstCourseDate, Epoch epoch) {

    ValidationErrors errors = new ValidationErrors();
    Date startDate = rPeriod.getStartDate();
    Date endDate = rPeriod.getEndDate();

    // Check if the start date is equal to or before the end date.
    if (firstCourseDate != null && startDate != null && (firstCourseDate.getTime() - startDate.getTime() > 0)) {
        errors.addValidationError("WS_AEMS_014",
                "Start date of this course/cycle cannot be earlier than the Start date of first course/cycle");
    }//  w w  w .  j  a v a2  s  . c  o  m

    if (startDate != null && endDate != null && (endDate.getTime() - startDate.getTime() < 0)) {
        errors.addValidationError("WS_AEMS_015", "Course End date cannot be earlier than Start date.");
    }

    // Check if the start date is equal to end date.
    // This is allowed only for Baseline reportingPeriods and not for other
    // reporting periods.

    if (epoch != null && !epoch.getName().equals("Baseline")) {
        if (endDate != null && startDate.equals(endDate)) {
            errors.addValidationError("WS_AEMS_016",
                    "For Non-Baseline treatment type Start date cannot be equal to End date.");
        }

    }

    // Check if the start date - end date for the reporting Period overlaps
    // with the date range of an existing Reporting Period.
    for (AdverseEventReportingPeriod aerp : rPeriodList) {
        Date sDate = aerp.getStartDate();
        Date eDate = aerp.getEndDate();

        if (!aerp.getId().equals(rPeriod.getId())) {

            // we should make sure that no existing Reporting Period, start
            // date falls, in-between these dates.
            if (startDate != null && endDate != null) {
                if (DateUtils.compareDate(sDate, startDate) >= 0 && DateUtils.compareDate(sDate, endDate) < 0) {
                    errors.addValidationError("WS_AEMS_017",
                            "Course/cycle cannot overlap with an existing course/cycle.");
                    break;
                }
            } else if (startDate != null && DateUtils.compareDate(sDate, startDate) == 0) {
                errors.addValidationError("WS_AEMS_017",
                        "Course/cycle cannot overlap with an existing course/cycle.");
                break;
            }

            // newly created reporting period start date, should not fall
            // within any other existing reporting periods
            if (sDate != null && eDate != null) {
                if (DateUtils.compareDate(sDate, startDate) <= 0
                        && DateUtils.compareDate(startDate, eDate) < 0) {
                    errors.addValidationError("WS_AEMS_017",
                            "Course/cycle cannot overlap with an existing course/cycle.");
                    break;
                }
            } else if (sDate != null && DateUtils.compareDate(sDate, startDate) == 0) {
                errors.addValidationError("WS_AEMS_017",
                        "Course/cycle cannot overlap with an existing course/cycle.");
                break;
            }
        }

        // If the epoch of reportingPeriod is not - Baseline , then it
        // cannot be earlier than a Baseline
        if (epoch != null && epoch.getName().equals("Baseline")) {
            if (aerp.getEpoch() != null && (!aerp.getEpoch().getName().equals("Baseline"))) {
                if (DateUtils.compareDate(sDate, startDate) < 0) {
                    errors.addValidationError("WS_AEMS_018",
                            "Baseline treatment type cannot start after an existing Non-Baseline treatment type.");
                    return errors;
                }
            }
        } else {
            if (aerp.getEpoch() != null && aerp.getEpoch().getName().equals("Baseline")) {
                if (DateUtils.compareDate(startDate, sDate) < 0) {
                    errors.addValidationError("WS_AEMS_019",
                            "Non-Baseline treatment type cannot start before an existing Baseline treatment type.");
                    return errors;
                }
            }
        }

        // Duplicate Baseline check
        if (epoch != null && epoch.getName().equals("Baseline")) {
            // Iterating through the already anything exists with the treatment type Baseline.
            for (AdverseEventReportingPeriod rp : rPeriodList) {

                if (rp.getEpoch() != null && rp.getEpoch().getName() != null
                        && rp.getEpoch().getName().equals("Baseline")) {
                    errors.addValidationError("WS_AEMS_085", "A Baseline treatment type already exists");
                    break;
                }
            }

        }

    }
    return errors;

}

From source file:org.openmrs.module.kenyaemr.fragment.controller.patient.ImportPatientsListFragmentController.java

protected void handleOncePerPatientObs(Patient patient, Concept question, Concept newValue, String textValue,
        Date textDate, Encounter en, Visit v) {

    if (newValue != null) {
        Obs o = new Obs();
        o.setPerson(patient);/*from w  w w  .  j a va  2s. c o  m*/
        o.setConcept(question);
        if (en != null) {
            o.setObsDatetime(en.getEncounterDatetime());
        } else {
            o.setObsDatetime(v.getStartDatetime());
        }
        o.setLocation(Context.getService(KenyaEmrService.class).getDefaultLocation());
        if (newValue != null && !newValue.equals("")) {
            o.setValueCoded(newValue);
        }
        if (textValue != null && !textValue.equals("")) {
            o.setValueText(textValue);
        }
        if (textDate != null && !textDate.equals("")) {
            o.setValueDate(textDate);
        }
        if (en != null) {
            o.setEncounter(en);
        }

        Context.getObsService().saveObs(o, "Patient Registration Details");
    }

}