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.craftercms.cstudio.alfresco.dm.service.impl.DmRenameServiceImpl.java

/**
 *
 * Prepares and starts workflow//from w w w  .  jav  a  2s  .c om
 *
 * Reverts any child nodes which are not in the same version as staging since only URL changes has to be pushed to staging.
 * A copy of the new version is placed in a temp location and recovered once we push things to workflow
 *
 */
protected void submitWorkflow(final String site, final String sub, final List<DmDependencyTO> submittedItems,
        Date now, Date scheduledDate, final String approver, MultiChannelPublishingContext mcpContext)
        throws ServiceException, org.craftercms.cstudio.alfresco.service.exception.ServiceException {

    final String assignee = DmUtils.getAssignee(site, sub);
    ServicesConfig servicesConfig = getService(ServicesConfig.class);
    final String pathPrefix = servicesConfig.getRepositoryRootPath(site);
    final PersistenceManagerService persistenceManagerService = getService(PersistenceManagerService.class);
    final List<String> paths = new FastList<String>();
    final List<String> dependenices = new FastList<String>();
    Date launchDate = scheduledDate.equals(now) ? null : scheduledDate;
    final boolean isScheduled = launchDate == null ? false : true;

    //label will keep track of all nodes that has been reverted to staging version and used during postStagingSubmission
    final StringBuilder label = new StringBuilder();
    label.append(
            isScheduled ? DmConstants.SCHEDULE_RENAME_WORKFLOW_PREFIX : DmConstants.RENAME_WORKFLOW_PREFIX);
    label.append(":");
    final Set<String> rescheduledUris = new HashSet<String>();
    DmTransactionService dmTransactionService = getService(DmTransactionService.class);
    RetryingTransactionHelper helper = dmTransactionService.getRetryingTransactionHelper();
    helper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Object>() {
        @Override
        public Object execute() throws Throwable {
            for (DmDependencyTO submittedItem : submittedItems) {
                String workflowLabel = getWorkflowPaths(site, sub, submittedItem, pathPrefix, paths,
                        dependenices, isScheduled, rescheduledUris);
                label.append(workflowLabel);
                label.append(",");
            }
            return null;
        }
    }, false, true);

    Set<String> uris = new HashSet<String>();
    Map<String, String> submittedBy = new FastMap<String, String>();
    DmContentService dmContentService = getService(DmContentService.class);
    DmPublishService dmPublishService = getService(DmPublishService.class);
    SearchService searchService = getService(SearchService.class);
    for (String path : paths) {
        String uri = path.substring(pathPrefix.length());
        uris.add(uri);
        DmUtils.addToSubmittedByMapping(persistenceManagerService, dmContentService, searchService, site, uri,
                submittedBy, approver);
        dmPublishService.cancelScheduledItem(site, uri);
    }
    GoLiveContext context = new GoLiveContext(approver, site);
    SubmitLifeCycleOperation operation = null;
    DmWorkflowService dmWorkflowService = getService(DmWorkflowService.class);
    if (launchDate == null) {
        operation = new PreGoLiveOperation(dmWorkflowService, uris, context, rescheduledUris);
    } else {
        //uri will not be have dependencies
        for (String dependency : dependenices) {
            String uri = dependency.substring(pathPrefix.length());
            uris.add(uri);
            DmUtils.addToSubmittedByMapping(persistenceManagerService, dmContentService, searchService, site,
                    uri, submittedBy, approver);
        }
        operation = new PreScheduleOperation(dmWorkflowService, uris, launchDate, context, rescheduledUris);
    }
    _workflowProcessor.addToWorkflow(site, paths, launchDate, _submitDirectWorkflowName, label.toString(),
            operation, approver, mcpContext);
    if (logger.isDebugEnabled()) {
        logger.debug("Go live rename: paths posted " + paths + "for workflow scheduled at : " + launchDate);
    }
}

From source file:org.jasig.schedassist.impl.caldav.CaldavCalendarDataDaoImpl.java

/**
 * Special method used when cancelUpdatesVisitorCalendar is set to true.
 * Returns the {@link CalendarWithURI} in the visitor's account for the event
 * with the specified start, end and eventuid.
 * /*w  ww  .j a  v a  2  s.c  o  m*/
 * @param owner
 * @param startTime
 * @param endTime
 * @param eventUid
 * @return the matching event, or null if not found.
 */
protected CalendarWithURI getExistingAppointmentInternalForVisitor(IScheduleVisitor visitor, Date startTime,
        Date endTime, Uid eventUid) {
    final DateTime targetStartTime = new DateTime(startTime);
    final DateTime targetEndTime = new DateTime(endTime);
    if (eventUid == null) {
        log.debug("cannot call getExistingAppointmentInternal with null eventUid, visitor: " + visitor);
        return null;
    }
    List<CalendarWithURI> calendars = getCalendarsInternal(visitor.getCalendarAccount(), startTime, endTime);
    for (CalendarWithURI calendarWithUri : calendars) {
        ComponentList componentList = calendarWithUri.getCalendar().getComponents(VEvent.VEVENT);
        if (componentList.size() != 1) {
            // scheduling assistant creates calendars with only a single event, short-circuit on calendars with > 1 events
            continue;
        }
        for (Object o : componentList) {
            VEvent event = (VEvent) o;
            Date eventStart = event.getStartDate().getDate();
            Date eventEnd = event.getEndDate(true).getDate();

            Uid uid = event.getUid();
            if (uid != null && eventUid.equals(uid) && Status.VEVENT_CANCELLED.equals(event.getStatus())
                    && eventStart.equals(targetStartTime) && eventEnd.equals(targetEndTime)) {
                return calendarWithUri;
            }
        }
    }
    // not found
    return null;
}

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

@Override
public void goLive(final String site, String sub, List<DmDependencyTO> submittedItems, final String approver,
        final MultiChannelPublishingContext mcpContext) throws ServiceException {
    long start = System.currentTimeMillis();
    // get web project information
    final String assignee = getAssignee(site, sub);
    ServicesConfig servicesConfig = getService(ServicesConfig.class);
    final String pathPrefix = servicesConfig.getRepositoryRootPath(site);
    final Date now = new Date();
    if (submittedItems != null) {
        // group submitted items into packages by their scheduled date
        Map<Date, List<DmDependencyTO>> groupedPackages = groupByDate(submittedItems, now);

        PersistenceManagerService persistenceManagerService = getService(PersistenceManagerService.class);
        persistenceManagerService.disableBehaviour(ContentModel.ASPECT_LOCKABLE);
        for (Date scheduledDate : groupedPackages.keySet()) {
            List<DmDependencyTO> goLivePackage = groupedPackages.get(scheduledDate);
            if (goLivePackage != null) {
                Date launchDate = scheduledDate.equals(now) ? null : scheduledDate;

                final boolean isNotScheduled = (launchDate == null);
                // for submit direct, package them together and submit them
                // together as direct submit
                final SubmitPackage submitpackage = new SubmitPackage(pathPrefix);
                /*//w w  w.java2  s. c  om
                dependencyPackage holds references of page.
                 */
                final Set<String> rescheduledUris = new HashSet<String>();
                final SubmitPackage dependencyPackage = new SubmitPackage("");
                DmTransactionService dmTransactionService = getService(DmTransactionService.class);
                for (final DmDependencyTO dmDependencyTO : goLivePackage) {
                    RetryingTransactionHelper helper = dmTransactionService.getRetryingTransactionHelper();
                    helper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback() {
                        @Override
                        public Object execute() throws Throwable {
                            goLivepackage(site, submitpackage, dmDependencyTO, isNotScheduled,
                                    dependencyPackage, approver, rescheduledUris);
                            return null;
                        }
                    }, false, true);
                }

                List<String> stringList = submitpackage.getPaths();
                String label = submitpackage.getLabel();
                SubmitLifeCycleOperation operation = null;
                GoLiveContext context = new GoLiveContext(approver, site);
                if (!isNotScheduled) {
                    Set<String> uris = new HashSet<String>();
                    uris.addAll(dependencyPackage.getUris());
                    uris.addAll(submitpackage.getUris());
                    label = getScheduleLabel(submitpackage, dependencyPackage);
                    operation = new PreScheduleOperation(this, uris, launchDate, context, rescheduledUris);
                } else {
                    operation = new PreGoLiveOperation(this, submitpackage.getUris(), context, rescheduledUris);
                }
                if (!stringList.isEmpty()) {
                    // get the workflow initiator mapping
                    Map<String, String> submittedBy = new FastMap<String, String>();

                    DmContentService dmContentService = getService(DmContentService.class);
                    DmPublishService dmPublishService = getService(DmPublishService.class);
                    for (String longPath : stringList) {
                        String uri = longPath.substring(pathPrefix.length());
                        DmUtils.addToSubmittedByMapping(getService(PersistenceManagerService.class),
                                dmContentService, site, uri, submittedBy, approver);
                        dmPublishService.cancelScheduledItem(site, uri);
                    }
                    _workflowProcessor.addToWorkflow(site, stringList, launchDate, _submitDirectWorkflowName,
                            label, operation, approver, mcpContext);
                }
                Set<DmDependencyTO> dependencyTOSet = submitpackage.getItems();
                for (DmDependencyTO dmDependencyTO : dependencyTOSet) {
                    _listener.postGolive(site, dmDependencyTO);
                }
                dependencyTOSet = dependencyPackage.getItems();
                for (DmDependencyTO dmDependencyTO : dependencyTOSet) {
                    _listener.postGolive(site, dmDependencyTO);
                }
            }
        }
        persistenceManagerService.enableBehaviour(ContentModel.ASPECT_LOCKABLE);
    }
    if (logger.isDebugEnabled()) {
        long end = System.currentTimeMillis();
        logger.debug("Total go live time = " + (end - start));
    }
}

From source file:org.apache.any23.extractor.microdata.MicrodataParserTest.java

@Test
public void testGetDateConcurrent() throws Exception {
    final Date expectedDate = new GregorianCalendar(2009, Calendar.MAY, 10).getTime(); // 2009-05-10
    final byte[] content = IOUtils
            .toByteArray(getClass().getResourceAsStream("/microdata/microdata-basic.html"));
    final int threadCount = 10;
    final int attemptCount = 100;
    final List<Thread> threads = new ArrayList<Thread>();
    final CountDownLatch beforeLatch = new CountDownLatch(1);
    final CountDownLatch afterLatch = new CountDownLatch(threadCount);
    final AtomicBoolean foundFailure = new AtomicBoolean(false);
    for (int i = 0; i < threadCount; i++) {
        threads.add(new Thread("Test-thread-" + i) {
            @Override//  www.  j  a va 2s .c o m
            public void run() {
                try {
                    beforeLatch.await();
                    int counter = 0;
                    while (counter++ < attemptCount && !foundFailure.get()) {
                        final Document document = getDom(content);
                        final MicrodataParserReport report = MicrodataParser.getMicrodata(document);
                        final ItemScope target = report.getDetectedItemScopes()[4];
                        Date actualDate = target.getProperties().get("birthday").get(0).getValue().getAsDate();
                        if (!expectedDate.equals(actualDate)) {
                            foundFailure.set(true);
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    foundFailure.set(true);
                } finally {
                    afterLatch.countDown();
                }
            }
        });
    }
    for (Thread thread : threads) {
        thread.start();
    }
    // Let threads start computation
    beforeLatch.countDown();
    // Wait for all threads to complete
    afterLatch.await();
    assertFalse(foundFailure.get());
}

From source file:no.abmu.lise.service.hibernate3.LiseImportServiceH3Impl.java

private Consortium findConsortiumInDb(LiseImportExcelParser excelParser) {
    String consortiumName = excelParser.getConsortiumName();
    Date agrementStartDate = excelParser.getConsortiumAgreementStartDate();
    Date agrementEndDate = excelParser.getConsortiumAgreementEndDate();

    if (agrementStartDate == null) {
        String warningMessage = "Row " + excelParser.getCurrentRowNumber() + " in " + excelParser.getSheetName()
                + " has no agreementStartDate";
        logger.warn(warningMessage);/* w w  w. ja  v a  2  s .com*/
        return null;
    }
    ConsortiumFinderSpecification finderSpecification = new ConsortiumFinderSpecification(consortiumName);

    Collection<Consortium> consortiumCollection = baseService.find(finderSpecification);
    if (consortiumCollection.size() == 0) {
        String warningMessage = "Row " + excelParser.getCurrentRowNumber() + " in " + excelParser.getSheetName()
                + " no consortium in DB with name: " + consortiumName;
        logger.warn(warningMessage);
        return null;
    }

    for (Consortium consortium : consortiumCollection) {
        if (agrementStartDate.equals(consortium.getConsortiumAgreementStartDate())) {
            if (agrementEndDate == null) {
                if (consortium.getConsortiumAgreementEndDate() == null) {
                    return consortium;
                }
            } else if (agrementEndDate.equals(consortium.getConsortiumAgreementEndDate())) {
                return consortium;
            }
        }
    }

    String warningMessage = "Row " + excelParser.getCurrentRowNumber() + " in " + excelParser.getSheetName()
            + " no consortium with name: '" + consortiumName + "', startDate: '" + agrementStartDate
            + "' and endDate: '" + agrementEndDate + "'.";
    logger.warn(warningMessage);
    return null;
}

From source file:org.pentaho.di.trans.steps.script.ScriptAddedFunctions.java

public static Object date2str(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {
    Object oRC = new Object();
    switch (ArgList.length) {
    case 0:/* www . jav a 2 s  .c om*/
        throw new RuntimeException("Please provide a valid date to the function call date2str.");
    case 1:
        try {
            if (isNull(ArgList)) {
                return null;
            } else if (isUndefined(ArgList)) {
                return undefinedValue;
            }
            java.util.Date dArg1 = (java.util.Date) ArgList[0];
            if (dArg1.equals(null)) {
                return null;
            }
            Format dfFormatter = new SimpleDateFormat();
            oRC = dfFormatter.format(dArg1);
        } catch (Exception e) {
            throw new RuntimeException("Could not convert to local format.");
        }
        break;
    case 2:
        try {
            if (isNull(ArgList, new int[] { 0, 1 })) {
                return null;
            } else if (isUndefined(ArgList, new int[] { 0, 1 })) {
                return undefinedValue;
            }
            java.util.Date dArg1 = (java.util.Date) ArgList[0];
            String sArg2 = (String) ArgList[1];
            Format dfFormatter = new SimpleDateFormat(sArg2);
            oRC = dfFormatter.format(dArg1);
        } catch (Exception e) {
            throw new RuntimeException("Could not convert to the given format.");
        }
        break;
    case 3:
        try {
            if (isNull(ArgList, new int[] { 0, 1, 2 })) {
                return null;
            } else if (isUndefined(ArgList, new int[] { 0, 1, 2 })) {
                return undefinedValue;
            }
            java.util.Date dArg1 = (java.util.Date) ArgList[0];
            DateFormat dfFormatter;
            String sArg2 = (String) ArgList[1];
            String sArg3 = (String) ArgList[2];
            if (sArg3.length() == 2) {
                Locale dfLocale = EnvUtil.createLocale(sArg3.toLowerCase());
                dfFormatter = new SimpleDateFormat(sArg2, dfLocale);
                oRC = dfFormatter.format(dArg1);
            } else {
                throw new RuntimeException("Locale is not 2 characters long.");
            }
        } catch (Exception e) {
            throw new RuntimeException("Could not convert to the given local format.");
        }
        break;
    case 4:
        try {
            if (isNull(ArgList, new int[] { 0, 1, 2, 3 })) {
                return null;
            } else if (isUndefined(ArgList, new int[] { 0, 1, 2, 3 })) {
                return undefinedValue;
            }
            java.util.Date dArg1 = (java.util.Date) ArgList[0];
            DateFormat dfFormatter;
            String sArg2 = (String) ArgList[1];
            String sArg3 = (String) ArgList[2];
            String sArg4 = (String) ArgList[3];

            // If the timezone is not recognized, java will automatically
            // take GMT.
            TimeZone tz = TimeZone.getTimeZone(sArg4);

            if (sArg3.length() == 2) {
                Locale dfLocale = EnvUtil.createLocale(sArg3.toLowerCase());
                dfFormatter = new SimpleDateFormat(sArg2, dfLocale);
                dfFormatter.setTimeZone(tz);
                oRC = dfFormatter.format(dArg1);
            } else {
                throw new RuntimeException("Locale is not 2 characters long.");
            }
        } catch (Exception e) {
            throw new RuntimeException("Could not convert to the given local format.");
        }
        break;
    default:
        throw new RuntimeException("The function call date2str requires 1, 2, 3, or 4 arguments.");
    }
    return oRC;
}

From source file:gov.nih.nci.cabig.caaers.web.ae.CreateReportingPeriodController.java

protected void validateRepPeriodDates(AdverseEventReportingPeriod rPeriod,
        List<AdverseEventReportingPeriod> rPeriodList, Date firstCourseDate, Errors errors) {

    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.rejectValue("reportingPeriod.startDate", "CRP_008",
                "Start date of this course/cycle cannot be earlier than the Start date of first course/cycle");
    }/*from  w w  w.  j  ava  2 s  . co m*/

    if (startDate != null && endDate != null && (endDate.getTime() - startDate.getTime() < 0)) {
        errors.rejectValue("reportingPeriod.endDate", "CRP_003", "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 (rPeriod.getEpoch() != null && !rPeriod.getEpoch().getName().equals("Baseline")) {
        if (endDate != null && startDate.equals(endDate)) {
            errors.rejectValue("reportingPeriod.startDate", "CRP_004",
                    "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.rejectValue("reportingPeriod.endDate", "CRP_005",
                            "Course/cycle cannot overlap with an existing course/cycle.");
                    break;
                }
            } else if (startDate != null && DateUtils.compareDate(sDate, startDate) == 0) {
                errors.rejectValue("reportingPeriod.startDate", "CRP_005",
                        "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.rejectValue("reportingPeriod.endDate", "CRP_005",
                            "Course/cycle cannot overlap with an existing course/cycle.");
                    break;
                }
            } else if (sDate != null && DateUtils.compareDate(sDate, startDate) == 0) {
                errors.rejectValue("reportingPeriod.startDate", "CRP_005",
                        "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 (rPeriod.getEpoch() != null && rPeriod.getEpoch().getName().equals("Baseline")) {
            if (aerp.getEpoch() != null && !aerp.getEpoch().getName().equals("Baseline")) {
                if (DateUtils.compareDate(sDate, startDate) < 0) {
                    errors.rejectValue("reportingPeriod.startDate", "CRP_006",
                            "Baseline treatment type cannot start after an existing Non-Baseline treatment type.");
                    return;
                }
            }
        } else {
            if (aerp.getEpoch() != null && aerp.getEpoch().getName().equals("Baseline")) {
                if (DateUtils.compareDate(startDate, sDate) < 0) {
                    errors.rejectValue("reportingPeriod.startDate", "CRP_007",
                            "Non-Baseline treatment type cannot start before an existing Baseline treatment type.");
                    return;
                }
            }
        }

    }

}

From source file:org.ejbca.ui.web.admin.certprof.CertProfileBean.java

private final void applyExpirationRestrictionForValidityWithFixedDate(final CertificateProfile profile) {
    final String encodedValidty = profile.getEncodedValidity();
    if (profile.getUseExpirationRestrictionForWeekdays()) {
        Date endDate = null;// w w w. j  av  a2 s.  com
        try {
            endDate = ValidityDate.parseAsIso8601(encodedValidty);
        } catch (ParseException e) {
            // NOOP
        }
        if (null != endDate) { // for fixed end dates.
            log.info("Applying expiration restrictions for weekdays with fixed end date: " + encodedValidty
                    + " days " + Arrays.toString(profile.getExpirationRestrictionWeekdays()));
            try {
                final Date appliedDate = ValidityDate.applyExpirationRestrictionForWeekdays(endDate,
                        profile.getExpirationRestrictionWeekdays(),
                        profile.getExpirationRestrictionForWeekdaysExpireBefore());
                if (!appliedDate.equals(endDate)) {
                    final String newEncodedValidity = ValidityDate
                            .formatAsISO8601ServerTZ(appliedDate.getTime(), ValidityDate.TIMEZONE_SERVER);
                    profile.setEncodedValidity(newEncodedValidity);
                    addInfoMessage("CERT_EXPRIATION_RESTRICTION_FIXED_DATE_CHANGED", encodedValidty,
                            newEncodedValidity);
                }
            } catch (Exception e) {
                log.warn("Expiration restriction of certificate profile could not be applied!");
            }
        }
    }
}

From source file:org.jpos.gl.GLSession.java

private Iterator findSummarizedGLEntries(Journal journal, Date start, Date end, boolean credit, short layer)
        throws HibernateException, GLException {
    StringBuffer qs = new StringBuffer(
            "select entry.account, sum(entry.amount)" + " from org.jpos.gl.GLEntry entry,"
                    + " org.jpos.gl.GLTransaction txn" + " where txn.id = entry.transaction"
                    + " and credit = :credit" + " and txn.journal = :journal" + " and entry.layer = :layer");
    boolean equalDate = start.equals(end);
    if (equalDate) {
        qs.append(" and txn.postDate = :date");
    } else {/*from   w  w w. j av  a 2 s. com*/
        qs.append(" and txn.postDate >= :start");
        qs.append(" and txn.postDate <= :end");
    }
    qs.append(" group by entry.account");
    Query q = session.createQuery(qs.toString());
    q.setLong("journal", journal.getId());
    q.setParameter("credit", credit ? "Y" : "N");
    q.setShort("layer", layer);
    if (equalDate)
        q.setParameter("date", start);
    else {
        q.setParameter("start", start);
        q.setParameter("end", end);
    }
    return q.iterate();
}

From source file:org.egov.stms.service.es.SewerageIndexService.java

public SewerageIndex createSewarageIndex(final SewerageApplicationDetails sewerageApplicationDetails,
        final AssessmentDetails assessmentDetails) {
    final City cityWebsite = cityService.getCityByURL(ApplicationThreadLocals.getDomainName());

    final SewerageIndex sewarageIndex = new SewerageIndex();
    sewarageIndex.setUlbName(cityWebsite.getName());
    sewarageIndex.setDistrictName(cityWebsite.getDistrictName());
    sewarageIndex.setRegionName(cityWebsite.getRegionName());
    sewarageIndex.setUlbGrade(cityWebsite.getGrade());
    sewarageIndex.setUlbCode(cityWebsite.getCode());
    sewarageIndex.setApplicationCreatedBy(sewerageApplicationDetails.getCreatedBy().getName());
    sewarageIndex/*from ww  w .j a  va 2  s .  c  om*/
            .setId(cityWebsite.getCode().concat("-").concat(sewerageApplicationDetails.getApplicationNumber()));
    sewarageIndex.setApplicationDate(sewerageApplicationDetails.getApplicationDate());
    sewarageIndex.setApplicationNumber(sewerageApplicationDetails.getApplicationNumber());
    sewarageIndex.setApplicationStatus(sewerageApplicationDetails.getStatus() != null
            ? sewerageApplicationDetails.getStatus().getDescription()
            : EMPTY);
    sewarageIndex.setConsumerNumber(sewerageApplicationDetails.getApplicationNumber());
    sewarageIndex.setApplicationType(sewerageApplicationDetails.getApplicationType() != null
            ? sewerageApplicationDetails.getApplicationType().getName()
            : EMPTY);
    sewarageIndex.setConnectionStatus(sewerageApplicationDetails.getConnection().getStatus() != null
            ? sewerageApplicationDetails.getConnection().getStatus().name()
            : EMPTY);
    sewarageIndex.setCreatedDate(sewerageApplicationDetails.getCreatedDate());
    sewarageIndex.setShscNumber(sewerageApplicationDetails.getConnection().getShscNumber() != null
            ? sewerageApplicationDetails.getConnection().getShscNumber()
            : EMPTY);
    sewarageIndex.setDisposalDate(sewerageApplicationDetails.getDisposalDate());

    sewarageIndex.setExecutionDate(sewerageApplicationDetails.getConnection().getExecutionDate());
    sewarageIndex.setIslegacy(sewerageApplicationDetails.getConnection().getLegacy());
    sewarageIndex.setNoOfClosets_nonResidential(
            sewerageApplicationDetails.getConnectionDetail().getNoOfClosetsNonResidential());
    sewarageIndex.setNoOfClosets_residential(
            sewerageApplicationDetails.getConnectionDetail().getNoOfClosetsResidential());
    sewarageIndex.setPropertyIdentifier(
            sewerageApplicationDetails.getConnectionDetail().getPropertyIdentifier() != null
                    ? sewerageApplicationDetails.getConnectionDetail().getPropertyIdentifier()
                    : EMPTY);
    sewarageIndex.setPropertyType(sewerageApplicationDetails.getConnectionDetail().getPropertyType() != null
            ? sewerageApplicationDetails.getConnectionDetail().getPropertyType().name()
            : EMPTY);
    if (sewerageApplicationDetails.getEstimationDate() != null)
        sewarageIndex.setEstimationDate(sewerageApplicationDetails.getEstimationDate());
    sewarageIndex.setEstimationNumber(sewerageApplicationDetails.getEstimationNumber() != null
            ? sewerageApplicationDetails.getEstimationNumber()
            : EMPTY);
    if (sewerageApplicationDetails.getWorkOrderDate() != null)
        sewarageIndex.setWorkOrderDate(sewerageApplicationDetails.getWorkOrderDate());
    sewarageIndex.setWorkOrderNumber(sewerageApplicationDetails.getWorkOrderNumber() != null
            ? sewerageApplicationDetails.getWorkOrderNumber()
            : EMPTY);
    if (sewerageApplicationDetails.getClosureNoticeDate() != null)
        sewarageIndex.setClosureNoticeDate(sewerageApplicationDetails.getClosureNoticeDate());
    sewarageIndex.setClosureNoticeNumber(sewerageApplicationDetails.getClosureNoticeNumber() != null
            ? sewerageApplicationDetails.getClosureNoticeNumber()
            : EMPTY);
    if (sewerageApplicationDetails.getRejectionDate() != null)
        sewarageIndex.setRejectionNoticeDate(sewerageApplicationDetails.getRejectionDate());
    sewarageIndex.setRejectionNoticeNumber(sewerageApplicationDetails.getRejectionNumber() != null
            ? sewerageApplicationDetails.getRejectionNumber()
            : EMPTY);
    Iterator<OwnerName> ownerNameItr = null;
    if (null != assessmentDetails.getOwnerNames())
        ownerNameItr = assessmentDetails.getOwnerNames().iterator();
    final StringBuilder consumerName = new StringBuilder();
    final StringBuilder mobileNumber = new StringBuilder();
    if (null != ownerNameItr && ownerNameItr.hasNext()) {
        final OwnerName primaryOwner = ownerNameItr.next();
        consumerName.append(primaryOwner.getOwnerName() != null ? primaryOwner.getOwnerName() : EMPTY);
        mobileNumber.append(primaryOwner.getMobileNumber() != null ? primaryOwner.getMobileNumber() : EMPTY);
        while (ownerNameItr.hasNext()) {
            final OwnerName secondaryOwner = ownerNameItr.next();
            consumerName.append(",")
                    .append(secondaryOwner.getOwnerName() != null ? secondaryOwner.getOwnerName() : EMPTY);
            mobileNumber.append(",").append(
                    secondaryOwner.getMobileNumber() != null ? secondaryOwner.getMobileNumber() : EMPTY);
        }
    }
    sewarageIndex.setMobileNumber(mobileNumber.toString());
    sewarageIndex.setConsumerName(consumerName.toString());
    sewarageIndex.setDoorNo(assessmentDetails.getHouseNo() != null ? assessmentDetails.getHouseNo() : EMPTY);
    sewarageIndex.setWard(assessmentDetails.getBoundaryDetails() != null
            ? assessmentDetails.getBoundaryDetails().getWardName()
            : EMPTY);
    sewarageIndex.setRevenueBlock(assessmentDetails.getBoundaryDetails() != null
            ? assessmentDetails.getBoundaryDetails().getBlockName()
            : EMPTY);
    sewarageIndex.setLocationName(assessmentDetails.getBoundaryDetails() != null
            ? assessmentDetails.getBoundaryDetails().getLocalityName()
            : EMPTY);
    sewarageIndex.setAddress(
            assessmentDetails.getPropertyAddress() != null ? assessmentDetails.getPropertyAddress() : EMPTY);
    sewarageIndex
            .setSource(sewerageApplicationDetails.getSource() != null ? sewerageApplicationDetails.getSource()
                    : Source.SYSTEM.toString());
    // Setting application status is active or in-active
    sewarageIndex.setActive(sewerageApplicationDetails.isActive());

    // setting connection fees details
    for (final SewerageConnectionFee scf : sewerageApplicationDetails.getConnectionFees()) {

        if (scf.getFeesDetail().getCode().equals(FEES_SEWERAGETAX_CODE))
            sewarageIndex.setSewerageTax(BigDecimal.valueOf(scf.getAmount()));
        if (scf.getFeesDetail().getCode().equals(FEES_DONATIONCHARGE_CODE))
            sewarageIndex.setDonationAmount(BigDecimal.valueOf(scf.getAmount()));
        if (scf.getFeesDetail().getCode().equals(FEE_INSPECTIONCHARGE))
            sewarageIndex.setInspectionCharge(BigDecimal.valueOf(scf.getAmount()));
        if (scf.getFeesDetail().getCode().equals(FEES_ESTIMATIONCHARGES_CODE))
            sewarageIndex.setEstimationCharge(BigDecimal.valueOf(scf.getAmount()));
    }

    // setting demand details
    final List<SewerageRateDCBResult> rateResultList = sewerageDCBReporService
            .getSewerageRateDCBReport(sewerageApplicationDetails);
    final Date currentInstallmentYear = sewerageDemandService.getCurrentInstallment().getInstallmentYear();
    BigDecimal totalDemandAmount = BigDecimal.ZERO;
    BigDecimal totalCollectedDemandamount = BigDecimal.ZERO;
    BigDecimal totalArrearamount = BigDecimal.ZERO;
    BigDecimal totalCollectedArearamount = BigDecimal.ZERO;
    final Calendar calendar = new GregorianCalendar();

    for (final SewerageRateDCBResult demand : rateResultList) {// FIXME: SORT BASED ON INSTALLMENT DESCRIPTION
        final Date installmentYear = installmentDao
                .getInsatllmentByModuleAndDescription(moduleDao.getModuleByName(MODULE_NAME),
                        demand.getInstallmentYearDescription())
                .getInstallmentYear();

        String period = null;
        if (sewerageApplicationDetails.getConnection().getExecutionDate() != null)
            calendar.setTime(sewerageApplicationDetails.getConnection().getExecutionDate());
        final int year = calendar.get(Calendar.YEAR);
        period = year + "-" + demand.getInstallmentYearDescription().substring(5, 9);
        sewarageIndex.setPeriod(period != null ? period : EMPTY);

        if (installmentYear.equals(currentInstallmentYear) || installmentYear.after(currentInstallmentYear)) {
            totalDemandAmount = totalDemandAmount.add(demand.getDemandAmount());
            totalCollectedDemandamount = totalCollectedDemandamount.add(demand.getCollectedDemandAmount());

        }
        if (installmentYear.before(currentInstallmentYear)) {
            totalArrearamount = totalArrearamount.add(demand.getDemandAmount());
            totalCollectedArearamount = totalCollectedArearamount.add(demand.getCollectedDemandAmount());

        }
        if (demand.getCollectedAdvanceAmount() != null)
            sewarageIndex.setExtraAdvanceAmount(demand.getCollectedAdvanceAmount());
    }
    sewarageIndex.setDemandAmount(totalDemandAmount != null ? totalDemandAmount : BigDecimal.ZERO);
    sewarageIndex.setCollectedDemandAmount(
            totalCollectedDemandamount != null ? totalCollectedDemandamount : BigDecimal.ZERO);
    sewarageIndex.setArrearAmount(totalArrearamount != null ? totalArrearamount : BigDecimal.ZERO);
    sewarageIndex.setCollectedArrearAmount(
            totalCollectedArearamount != null ? totalCollectedArearamount : BigDecimal.ZERO);
    sewarageIndex.setTotalAmount(totalDemandAmount.add(totalArrearamount));
    sewerageIndexRepository.save(sewarageIndex);
    return sewarageIndex;
}