Example usage for java.util Calendar after

List of usage examples for java.util Calendar after

Introduction

In this page you can find the example usage for java.util Calendar after.

Prototype

public boolean after(Object when) 

Source Link

Document

Returns whether this Calendar represents a time after the time represented by the specified Object.

Usage

From source file:org.kuali.ole.module.purap.document.service.impl.PurchaseOrderServiceImpl.java

/**
 * @see org.kuali.ole.module.purap.document.service.PurchaseOrderService#autoCloseRecurringOrders()
 *///  www .  j a  v a  2 s . c  om
@Override
public boolean autoCloseRecurringOrders() {
    LOG.debug("autoCloseRecurringOrders() started");
    boolean shouldSendEmail = true;
    MailMessage message = new MailMessage();
    String parameterEmail = parameterService.getParameterValueAsString(AutoCloseRecurringOrdersStep.class,
            PurapParameterConstants.AUTO_CLOSE_RECURRING_PO_TO_EMAIL_ADDRESSES);

    if (StringUtils.isEmpty(parameterEmail)) {
        // Don't stop the show if the email address is wrong, log it and continue.
        LOG.warn(
                "autoCloseRecurringOrders(): parameterEmail is missing, we'll not send out any emails for this job.");
        shouldSendEmail = false;
    }
    if (shouldSendEmail) {
        message = setMessageAddressesAndSubject(message, parameterEmail);
    }
    StringBuffer emailBody = new StringBuffer();
    // There should always be a "AUTO_CLOSE_RECURRING_ORDER_DT"
    // row in the table, this method sets it to "mm/dd/yyyy" after processing.
    String recurringOrderDateString = parameterService.getParameterValueAsString(
            AutoCloseRecurringOrdersStep.class, PurapParameterConstants.AUTO_CLOSE_RECURRING_PO_DATE);
    boolean validDate = true;
    java.util.Date recurringOrderDate = null;
    try {
        recurringOrderDate = dateTimeService.convertToDate(recurringOrderDateString);
    } catch (ParseException pe) {
        validDate = false;
    }
    if (StringUtils.isEmpty(recurringOrderDateString) || recurringOrderDateString.equalsIgnoreCase("mm/dd/yyyy")
            || (!validDate)) {
        if (recurringOrderDateString.equalsIgnoreCase("mm/dd/yyyy")) {
            LOG.debug("autoCloseRecurringOrders(): mm/dd/yyyy "
                    + "was found in the Application Settings table. No orders will be closed, method will end.");
            if (shouldSendEmail) {
                emailBody.append("The AUTO_CLOSE_RECURRING_ORDER_DT found in the Application Settings table "
                        + "was mm/dd/yyyy. No recurring PO's were closed.");
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("autoCloseRecurringOrders(): An invalid autoCloseRecurringOrdersDate "
                        + "was found in the Application Settings table: " + recurringOrderDateString
                        + ". Method will end.");
            }
            if (shouldSendEmail) {
                emailBody.append(
                        "An invalid AUTO_CLOSE_RECURRING_ORDER_DT was found in the Application Settings table: "
                                + recurringOrderDateString + ". No recurring PO's were closed.");
            }
        }
        if (shouldSendEmail) {
            sendMessage(message, emailBody.toString());
        }
        LOG.debug("autoCloseRecurringOrders() ended");

        return false;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(
                "autoCloseRecurringOrders() The autoCloseRecurringOrdersDate found in the Application Settings table was "
                        + recurringOrderDateString);
    }
    if (shouldSendEmail) {
        emailBody.append("The autoCloseRecurringOrdersDate found in the Application Settings table was "
                + recurringOrderDateString + ".");
    }
    Calendar appSettingsDate = dateTimeService.getCalendar(recurringOrderDate);
    Timestamp appSettingsDay = new Timestamp(appSettingsDate.getTime().getTime());

    Calendar todayMinusThreeMonths = getTodayMinusThreeMonths();
    Timestamp threeMonthsAgo = new Timestamp(todayMinusThreeMonths.getTime().getTime());

    if (appSettingsDate.after(todayMinusThreeMonths)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("autoCloseRecurringOrders() The appSettingsDate: " + appSettingsDay
                    + " is after todayMinusThreeMonths: " + threeMonthsAgo + ". The program will end.");
        }
        if (shouldSendEmail) {
            emailBody.append("\n\nThe autoCloseRecurringOrdersDate: " + appSettingsDay
                    + " is after todayMinusThreeMonths: " + threeMonthsAgo + ". The program will end.");
            sendMessage(message, emailBody.toString());
        }
        LOG.debug("autoCloseRecurringOrders() ended");

        return false;
    }

    List<AutoClosePurchaseOrderView> closeList = purchaseOrderDao
            .getAutoCloseRecurringPurchaseOrders(getExcludedVendorChoiceCodes());

    //we need to eliminate the AutoClosePurchaseOrderView whose workflowdocument status is not OPEN..
    //KFSMI-7533
    List<AutoClosePurchaseOrderView> purchaseOrderAutoCloseList = filterDocumentsForAppDocStatusOpen(closeList);

    LOG.info("autoCloseRecurringOrders(): " + purchaseOrderAutoCloseList.size()
            + " PO's were returned for processing.");
    int counter = 0;
    for (AutoClosePurchaseOrderView poAutoClose : purchaseOrderAutoCloseList) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("autoCloseRecurringOrders(): Testing PO ID " + poAutoClose.getPurapDocumentIdentifier()
                    + ". recurringPaymentEndDate: " + poAutoClose.getRecurringPaymentEndDate());
        }
        if (poAutoClose.getRecurringPaymentEndDate().before(threeMonthsAgo)) {
            String newStatus = PurapConstants.PurchaseOrderStatuses.APPDOC_PENDING_CLOSE;
            String annotation = "This recurring PO was automatically closed in batch.";
            String documentType = PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_CLOSE_DOCUMENT;
            PurchaseOrderDocument document = getPurchaseOrderByDocumentNumber(poAutoClose.getDocumentNumber());
            boolean rulePassed = kualiRuleService.applyRules(new AttributedRouteDocumentEvent("", document));

            boolean success = true;
            if (success) {
                ++counter;
                if (counter == 1) {
                    emailBody.append(
                            "\n\nThe following recurring Purchase Orders will be closed by auto close recurring batch job \n");
                }
                if (LOG.isDebugEnabled()) {
                    LOG.debug("autoCloseRecurringOrders() PO ID " + poAutoClose.getPurapDocumentIdentifier()
                            + " will be closed.");
                }
                createNoteForAutoCloseOrders(document, annotation);
                createAndRoutePotentialChangeDocument(poAutoClose.getDocumentNumber(), documentType, annotation,
                        null, newStatus);
                if (shouldSendEmail) {
                    emailBody.append("\n\n" + counter + " PO ID: " + poAutoClose.getPurapDocumentIdentifier()
                            + ", End Date: " + poAutoClose.getRecurringPaymentEndDate() + ", Status: "
                            + poAutoClose.getApplicationDocumentStatus() + ", VendorChoice: "
                            + poAutoClose.getVendorChoiceCode() + ", RecurringPaymentType: "
                            + poAutoClose.getRecurringPaymentTypeCode());
                }
            } else {
                // If it was unsuccessful, we have to clear the error map in the GlobalVariables so that the previous
                // error would not still be lingering around and the next PO in the list can be validated.
                GlobalVariables.getMessageMap().clearErrorMessages();
            }
        }
    }
    if (counter == 0) {
        LOG.debug("\n\nNo recurring PO's fit the conditions for closing.");
        if (shouldSendEmail) {
            emailBody.append("\n\nNo recurring PO's fit the conditions for closing.");
        }
    }
    if (shouldSendEmail) {
        sendMessage(message, emailBody.toString());
    }
    resetAutoCloseRecurringOrderDateParameter();
    LOG.debug("autoCloseRecurringOrders() ended");

    return true;
}

From source file:com.square.core.service.implementations.PersonneServiceImplementation.java

/**
 * Test si une relation est active ou pas  la date du jour.
 * @param dateDebut date de dbut de la relation
 * @param dateFin date de fin de la relation
 * @return true si la relation est active, false sinon
 *//*from  ww w  . ja  v  a2  s  .c  o m*/
private boolean isRelationActive(Calendar dateDebut, Calendar dateFin) {
    final Calendar dateDuJour = Calendar.getInstance();
    final int jour = dateDuJour.get(Calendar.DATE);
    final int mois = dateDuJour.get(Calendar.MONTH);
    final int annee = dateDuJour.get(Calendar.YEAR);
    dateDuJour.clear();
    dateDuJour.set(annee, mois, jour);
    return (dateDebut == null || dateDebut.before(dateDuJour) || dateDebut.equals(dateDuJour))
            && (dateFin == null || dateFin.after(dateDuJour));
}

From source file:es.sm2.openppm.front.servlets.ProjectControlServlet.java

/**
  * Generate Histogram Chart/*from w  w  w  .  j ava2s. c  o m*/
  * 
  * @param req
  * @param resp
  * @throws IOException
  */
private void histogramChartJX(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    int idProject = ParamUtil.getInteger(req, Project.IDPROJECT);
    Date since = ParamUtil.getDate(req, "since", getDateFormat(req));
    Date until = ParamUtil.getDate(req, "until", getDateFormat(req));

    JSONArray dataSeries = new JSONArray();
    JSONArray categories = new JSONArray();
    JSONArray legend = new JSONArray();

    PrintWriter out = resp.getWriter();

    try {

        TimesheetLogic timesheetLogic = new TimesheetLogic();
        TeamMemberLogic memberLogic = new TeamMemberLogic();
        JobcategoryLogic jobLogic = new JobcategoryLogic();

        Calendar sinceCal = DateUtil.getCalendar();
        sinceCal.setTime(DateUtil.getFirstWeekDay(since));

        Calendar untilCal = DateUtil.getCalendar();
        untilCal.setTime(DateUtil.getLastWeekDay(until));

        while (!sinceCal.after(untilCal)) {

            int sinceDay = sinceCal.get(Calendar.DAY_OF_MONTH);
            Calendar calWeek = DateUtil.getLastWeekDay(sinceCal);
            int untilDay = calWeek.get(Calendar.DAY_OF_MONTH);

            categories.add(sinceDay + "-" + untilDay + " "
                    + getResourceBundle(req).getString("month.min_" + (calWeek.get(Calendar.MONTH) + 1)) + " "
                    + dfYear.format(calWeek.getTime()));

            sinceCal.add(Calendar.WEEK_OF_MONTH, 1);
        }

        List<Teammember> members = memberLogic.consStaffinActualsFtes(new Project(idProject), since, until);

        List<Jobcategory> jobs = jobLogic.findByRelation(Jobcategory.COMPANY, getCompany(req), Jobcategory.NAME,
                Constants.ASCENDENT);

        int i = 0;
        for (Jobcategory job : jobs) {

            sinceCal.setTime(DateUtil.getFirstWeekDay(since));

            JSONArray series = new JSONArray();

            while (!sinceCal.after(untilCal)) {

                double resources = 0;

                for (Teammember member : members) {

                    if (member.getJobcategory() != null
                            && job.getIdJobCategory().equals(member.getJobcategory().getIdJobCategory())
                            && DateUtil.betweenWeek(member.getDateIn(), member.getDateOut(),
                                    sinceCal.getTime())) {

                        Double fte = timesheetLogic.getFte(new Project(idProject), member,
                                DateUtil.getFirstWeekDay(sinceCal.getTime()),
                                DateUtil.getLastWeekDay(sinceCal.getTime()));

                        resources += fte;
                    }
                }
                series.add((resources > 0 ? resources / 100 : 0));

                sinceCal.add(Calendar.WEEK_OF_MONTH, 1);
            }

            // Paint if values exist
            Boolean existValues = false;
            int index = 0;

            while (index < series.size() && !existValues) {

                if (series.getDouble(index) != 0.0) {
                    existValues = true;
                }

                index += 1;
            }

            if (existValues) {

                legend.add(ChartUtil.getLegend(job.getName(), ++i));

                dataSeries.add(series);
            }
        }

        legend.add(ChartUtil.getLegend(getResourceBundle(req).getString("not_defined"), 0));

        sinceCal.setTime(DateUtil.getFirstWeekDay(since));

        JSONArray series = new JSONArray();

        while (!sinceCal.after(untilCal)) {

            double resources = 0;

            for (Teammember member : members) {

                if (member.getJobcategory() == null
                        && DateUtil.betweenWeek(member.getDateIn(), member.getDateOut(), sinceCal.getTime())) {

                    Double fte = timesheetLogic.getFte(new Project(idProject), member,
                            DateUtil.getFirstWeekDay(sinceCal.getTime()),
                            DateUtil.getLastWeekDay(sinceCal.getTime()));

                    resources += fte;
                }

            }
            series.add((resources > 0 ? resources / 100 : 0));

            sinceCal.add(Calendar.WEEK_OF_MONTH, 1);
        }

        dataSeries.add(series);

        JSONObject chartJSON = new JSONObject();

        chartJSON.put("categories", categories);
        chartJSON.put("dataSeries", dataSeries);
        chartJSON.put("legend", legend);

        out.print(chartJSON);
    } catch (Exception e) {
        ExceptionUtil.evalueExceptionJX(out, req, getResourceBundle(req), LOGGER, e);
    } finally {
        out.close();
    }
}

From source file:org.kuali.ole.sys.batch.service.impl.SchedulerServiceImpl.java

protected boolean isPastScheduleCutoffTime(Calendar dateTime, boolean log) {
    try {//  w  w w. j  a va  2  s . c  o m
        Date scheduleCutoffTimeTemp = scheduler.getTriggersOfJob(SCHEDULE_JOB_NAME, SCHEDULED_GROUP)[0]
                .getPreviousFireTime();
        Calendar scheduleCutoffTime;
        if (scheduleCutoffTimeTemp == null) {
            scheduleCutoffTime = dateTimeService.getCurrentCalendar();
        } else {
            scheduleCutoffTime = dateTimeService.getCalendar(scheduleCutoffTimeTemp);
        }
        String cutoffParameter = parameterService.getParameterValueAsString(ScheduleStep.class,
                OLEConstants.SystemGroupParameterNames.BATCH_SCHEDULE_CUTOFF_TIME);
        String[] scheduleStepCutoffTime = StringUtils.split(cutoffParameter, ":");
        if (scheduleStepCutoffTime.length != 3 && scheduleStepCutoffTime.length != 4) {
            throw new IllegalArgumentException(
                    "Error! The " + OLEConstants.SystemGroupParameterNames.BATCH_SCHEDULE_CUTOFF_TIME
                            + " parameter had an invalid value: " + cutoffParameter);
        }
        // if there are 4 components, then we have an AM/PM delimiter
        // otherwise, assume 24-hour time
        if (scheduleStepCutoffTime.length == 4) {
            int hour = Integer.parseInt(scheduleStepCutoffTime[0]);
            // need to adjust for meaning of hour
            if (hour == 12) {
                hour = 0;
            } else {
                hour--;
            }
            scheduleCutoffTime.set(Calendar.HOUR, hour);
            if (StringUtils.containsIgnoreCase(scheduleStepCutoffTime[3], "AM")) {
                scheduleCutoffTime.set(Calendar.AM_PM, Calendar.AM);
            } else {
                scheduleCutoffTime.set(Calendar.AM_PM, Calendar.PM);
            }
        } else {
            scheduleCutoffTime.set(Calendar.HOUR_OF_DAY, Integer.parseInt(scheduleStepCutoffTime[0]));
        }
        scheduleCutoffTime.set(Calendar.MINUTE, Integer.parseInt(scheduleStepCutoffTime[1]));
        scheduleCutoffTime.set(Calendar.SECOND, Integer.parseInt(scheduleStepCutoffTime[2]));
        if (parameterService.getParameterValueAsBoolean(ScheduleStep.class,
                OLEConstants.SystemGroupParameterNames.BATCH_SCHEDULE_CUTOFF_TIME_IS_NEXT_DAY)) {
            scheduleCutoffTime.add(Calendar.DAY_OF_YEAR, 1);
        }
        boolean isPastScheduleCutoffTime = dateTime.after(scheduleCutoffTime);
        if (log) {
            LOG.info(new StringBuilder("isPastScheduleCutoffTime=").append(isPastScheduleCutoffTime)
                    .append(" : ").append(dateTimeService.toDateTimeString(dateTime.getTime())).append(" / ")
                    .append(dateTimeService.toDateTimeString(scheduleCutoffTime.getTime())));
        }
        return isPastScheduleCutoffTime;
    } catch (NumberFormatException e) {
        throw new RuntimeException(
                "Caught exception while checking whether we've exceeded the schedule cutoff time", e);
    } catch (SchedulerException e) {
        throw new RuntimeException(
                "Caught exception while checking whether we've exceeded the schedule cutoff time", e);
    }
}

From source file:org.kuali.kfs.sys.batch.service.impl.SchedulerServiceImpl.java

protected boolean isPastScheduleCutoffTime(Calendar dateTime, boolean log) {
    try {//from   w ww .j  a  v  a 2 s  . c  om
        Date scheduleCutoffTimeTemp = scheduler.getTriggersOfJob(SCHEDULE_JOB_NAME, SCHEDULED_GROUP)[0]
                .getPreviousFireTime();
        Calendar scheduleCutoffTime;
        if (scheduleCutoffTimeTemp == null) {
            scheduleCutoffTime = dateTimeService.getCurrentCalendar();
        } else {
            scheduleCutoffTime = dateTimeService.getCalendar(scheduleCutoffTimeTemp);
        }
        String cutoffParameter = parameterService.getParameterValueAsString(ScheduleStep.class,
                KFSConstants.SystemGroupParameterNames.BATCH_SCHEDULE_CUTOFF_TIME);
        String[] scheduleStepCutoffTime = StringUtils.split(cutoffParameter, ":");
        if (scheduleStepCutoffTime.length != 3 && scheduleStepCutoffTime.length != 4) {
            throw new IllegalArgumentException(
                    "Error! The " + KFSConstants.SystemGroupParameterNames.BATCH_SCHEDULE_CUTOFF_TIME
                            + " parameter had an invalid value: " + cutoffParameter);
        }
        // if there are 4 components, then we have an AM/PM delimiter
        // otherwise, assume 24-hour time
        if (scheduleStepCutoffTime.length == 4) {
            int hour = Integer.parseInt(scheduleStepCutoffTime[0]);
            // need to adjust for meaning of hour
            if (hour == 12) {
                hour = 0;
            } else {
                hour--;
            }
            scheduleCutoffTime.set(Calendar.HOUR, hour);
            if (StringUtils.containsIgnoreCase(scheduleStepCutoffTime[3], "AM")) {
                scheduleCutoffTime.set(Calendar.AM_PM, Calendar.AM);
            } else {
                scheduleCutoffTime.set(Calendar.AM_PM, Calendar.PM);
            }
        } else {
            scheduleCutoffTime.set(Calendar.HOUR_OF_DAY, Integer.parseInt(scheduleStepCutoffTime[0]));
        }
        scheduleCutoffTime.set(Calendar.MINUTE, Integer.parseInt(scheduleStepCutoffTime[1]));
        scheduleCutoffTime.set(Calendar.SECOND, Integer.parseInt(scheduleStepCutoffTime[2]));
        if (parameterService.getParameterValueAsBoolean(ScheduleStep.class,
                KFSConstants.SystemGroupParameterNames.BATCH_SCHEDULE_CUTOFF_TIME_IS_NEXT_DAY)) {
            scheduleCutoffTime.add(Calendar.DAY_OF_YEAR, 1);
        }
        boolean isPastScheduleCutoffTime = dateTime.after(scheduleCutoffTime);
        if (log) {
            LOG.info(new StringBuilder("isPastScheduleCutoffTime=").append(isPastScheduleCutoffTime)
                    .append(" : ").append(dateTimeService.toDateTimeString(dateTime.getTime())).append(" / ")
                    .append(dateTimeService.toDateTimeString(scheduleCutoffTime.getTime())));
        }
        return isPastScheduleCutoffTime;
    } catch (NumberFormatException e) {
        throw new RuntimeException(
                "Caught exception while checking whether we've exceeded the schedule cutoff time", e);
    } catch (SchedulerException e) {
        throw new RuntimeException(
                "Caught exception while checking whether we've exceeded the schedule cutoff time", e);
    }
}

From source file:es.sm2.openppm.front.servlets.ProjectPlanServlet.java

/**
  * Update Team Calendar/*from   w w  w.  j  a v a2s.c  o m*/
  * @param req
  * @param resp
  * @throws IOException 
 * @throws ServletException
  */
private void updateTeamCalendarJX(HttpServletRequest req, HttpServletResponse resp)
        throws IOException, ServletException {

    int idProject = ParamUtil.getInteger(req, Project.IDPROJECT);
    Date since = ParamUtil.getDate(req, "since", getDateFormat(req));
    Date until = ParamUtil.getDate(req, "until", getDateFormat(req));

    try {
        ProjectcalendarLogic projectcalendarLogic = new ProjectcalendarLogic();
        TeamMemberLogic teamMemberLogic = new TeamMemberLogic();

        Projectcalendar calendar = projectcalendarLogic.consCalendarByProject(new Project(idProject));

        List<Teammember> members = teamMemberLogic.consStaffinFtes(new Project(idProject), since, until, true);

        List<TeamCalendar> teamCalendars = new ArrayList<TeamCalendar>();

        Contact contact = null;
        TeamCalendar teamCalendar = null;

        for (Teammember member : members) {

            if (contact == null || contact.getIdContact() != member.getEmployee().getContact().getIdContact()) {

                if (teamCalendar != null) {
                    teamCalendars.add(teamCalendar);
                }

                teamCalendar = new TeamCalendar(member.getEmployee());
                contact = member.getEmployee().getContact();
            }

            Calendar sinceCal = DateUtil.getCalendar();
            sinceCal.setTime(member.getDateIn());

            Calendar untilCal = DateUtil.getCalendar();
            untilCal.setTime(member.getDateOut());

            while (!sinceCal.after(untilCal)) {

                teamCalendar.addWork(sinceCal.getTime());
                sinceCal.add(Calendar.DAY_OF_MONTH, 1);
            }
        }
        if (teamCalendar != null) {
            teamCalendars.add(teamCalendar);
        }

        List<String> dates = new ArrayList<String>();

        boolean isCreateDates = false;

        for (TeamCalendar teamCal : teamCalendars) {

            JSONObject teamJSON = new JSONObject();
            teamJSON.put("name", teamCal.getName());

            Calendar sinceCal = DateUtil.getCalendar();
            sinceCal.setTime(since);

            Calendar untilCal = DateUtil.getCalendar();
            untilCal.setTime(until);

            while (!sinceCal.after(untilCal)) {

                if (!isCreateDates) {
                    dates.add(sinceCal.get(Calendar.DAY_OF_MONTH) + "-" + (sinceCal.get(Calendar.MONTH) + 1));
                }

                boolean isException = false;
                if (calendar != null) {
                    for (Projectcalendarexceptions exception : calendar.getProjectcalendarexceptionses()) {

                        if (DateUtil.between(exception.getStartDate(), exception.getFinishDate(),
                                sinceCal.getTime())) {

                            teamCal.addValue("exceptionDay");
                            isException = true;
                            break;
                        }
                    }
                    if (!isException) {
                        if (calendar.getCalendarbase() != null) {
                            for (Calendarbaseexceptions exception : calendar.getCalendarbase()
                                    .getCalendarbaseexceptionses()) {

                                if (DateUtil.between(exception.getStartDate(), exception.getFinishDate(),
                                        sinceCal.getTime())) {

                                    teamCal.addValue("exceptionDay");
                                    isException = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (!isException) {

                        CalendarbaseexceptionsLogic exceptionsLogic = new CalendarbaseexceptionsLogic();
                        List<Calendarbaseexceptions> exceptions = exceptionsLogic
                                .findByEmployee(teamCal.getIdEmployee());

                        for (Calendarbaseexceptions exception : exceptions) {

                            if (DateUtil.between(exception.getStartDate(), exception.getFinishDate(),
                                    sinceCal.getTime())) {

                                teamCal.addValue("exceptionDay");
                                isException = true;
                                break;
                            }
                        }
                    }
                }

                if (!isException) {

                    if (DateUtil.isWeekend(sinceCal)) {
                        teamCal.addValue("nonWorkingDay");
                    } else if (teamCal.getWork().contains(sinceCal.getTime())) {
                        teamCal.addValue("workDay");
                    } else {
                        teamCal.addValue("notWorkDay");
                    }
                }

                sinceCal.add(Calendar.DAY_OF_MONTH, 1);
            }

            isCreateDates = true;
        }

        req.setAttribute("dates", dates);
        req.setAttribute("teamCalendars", teamCalendars);
    } catch (Exception e) {
        ExceptionUtil.evalueException(req, getResourceBundle(req), LOGGER, e);
    }

    req.setAttribute("documentationList", DocumentUtils.getDocumentationList(req));
    forward("/project/plan/plan_team_calendar.ajax.jsp", req, resp);
}

From source file:es.sm2.openppm.front.servlets.ProjectPlanServlet.java

/**
* Generate Team Members Ftes by Project/*ww  w .  j  a v  a2s.c om*/
* @param teammembers
* @param sinceDate
* @param untilDate
* @return
* @throws LogicException
*/
private List<TeamMembersFTEs> generateFTEsMembersByProject(List<Teammember> teammembers, Date sinceDate,
        Date untilDate) throws Exception {

    List<TeamMembersFTEs> listMembers = new ArrayList<TeamMembersFTEs>();
    Calendar sinceCal = DateUtil.getCalendar();
    Calendar untilCal = DateUtil.getCalendar();
    int idEmploye = -1;
    TeamMembersFTEs memberFtes = null;
    int[] listFTES = null;

    if (sinceDate != null || untilDate != null) {
        sinceCal.setTime(sinceDate);
        untilCal.setTime(untilDate);

        int weeks = 0;
        while (!sinceCal.after(untilCal)) {
            weeks++;
            sinceCal.add(Calendar.DAY_OF_MONTH, +7);
        }

        for (Teammember member : teammembers) {

            if (memberFtes == null || !(idEmploye == member.getEmployee().getIdEmployee())) {

                if (memberFtes != null) {
                    memberFtes.setFtes(listFTES);
                    listMembers.add(memberFtes);
                }

                listFTES = new int[weeks];
                memberFtes = new TeamMembersFTEs(member);
                idEmploye = member.getEmployee().getIdEmployee();
            }

            int i = 0;
            sinceCal.setTime(sinceDate);

            Calendar dayCal = null;
            Calendar weekCal = null;

            while (!sinceCal.after(untilCal)) {

                dayCal = DateUtil.getCalendar();
                dayCal.setTime(sinceCal.getTime());
                weekCal = DateUtil.getLastWeekDay(dayCal);

                int fte = 0;
                int workDays = 5;

                while (!dayCal.after(weekCal)) {

                    if (DateUtil.between(member.getDateIn(), member.getDateOut(), dayCal.getTime())
                            && !DateUtil.isWeekend(dayCal)) {
                        fte += (member.getFte() == null ? 0 : member.getFte());
                    }

                    dayCal.add(Calendar.DAY_OF_MONTH, 1);
                }

                listFTES[i] += (workDays > 0 ? fte / workDays : 0);

                i++;
                sinceCal.add(Calendar.DAY_OF_MONTH, +7);
            }
        }
        if (memberFtes != null) {
            memberFtes.setFtes(listFTES);
            listMembers.add(memberFtes);
        }
    }
    return listMembers;
}

From source file:es.sm2.openppm.front.servlets.ProjectPlanServlet.java

/**
  * Update Staffing Table//  w  w w  .java  2s  .c  o m
  * @param req
  * @param resp
  * @throws IOException 
  * @throws ServletException 
  */
private void updateStaffingTableJX(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    int idProject = ParamUtil.getInteger(req, Project.IDPROJECT);
    Date since = ParamUtil.getDate(req, "since", getDateFormat(req));
    Date until = ParamUtil.getDate(req, "until", getDateFormat(req));
    boolean showDisabled = ParamUtil.getBoolean(req, Configurations.FILTER_DISABLED, false);

    List<TeamMembersFTEs> ftEs = null;
    List<String> listDates = new ArrayList<String>();

    try {
        TeamMemberLogic teamMemberLogic = new TeamMemberLogic();

        SimpleDateFormat dfYear = new SimpleDateFormat("yy");

        Calendar sinceCal = DateUtil.getCalendar();
        Calendar untilCal = DateUtil.getCalendar();

        sinceCal.setTime(DateUtil.getFirstWeekDay(since));
        untilCal.setTime(DateUtil.getLastWeekDay(until));

        List<Teammember> teammembers = teamMemberLogic.consStaffinFtes(new Project(idProject), since, until,
                showDisabled);

        ftEs = generateFTEsMembersByProject(teammembers, sinceCal.getTime(), untilCal.getTime());

        while (!sinceCal.after(untilCal)) {

            int sinceDay = sinceCal.get(Calendar.DAY_OF_MONTH);
            Calendar calWeek = DateUtil.getLastWeekDay(sinceCal);
            int untilDay = calWeek.get(Calendar.DAY_OF_MONTH);

            listDates.add(sinceDay + "-" + untilDay + " "
                    + getResourceBundle(req).getString("month.min_" + (calWeek.get(Calendar.MONTH) + 1)) + " "
                    + dfYear.format(calWeek.getTime()));

            sinceCal.add(Calendar.WEEK_OF_MONTH, 1);
        }

        // Find configurations
        HashMap<String, String> configurations = RequestUtil.getConfigurationValues(req,
                Configurations.FILTER_DISABLED);

        // Save configuration
        ConfigurationLogic configurationLogic = new ConfigurationLogic();
        configurationLogic.saveConfigurations(getUser(req), configurations,
                Configurations.TYPE_CAPACITY_PLANNING);

    } catch (Exception e) {
        ExceptionUtil.evalueException(req, getResourceBundle(req), LOGGER, e);
    }

    req.setAttribute("listDates", listDates);
    req.setAttribute("ftEs", ftEs);

    forward("/project/common/staffing_table.ajax.jsp", req, resp);
}

From source file:org.atricore.idbus.capabilities.sso.main.sp.producers.AssertionConsumerProducer.java

private void validateAssertionConditions(ResponseType response, ConditionsType conditions)
        throws SSOException, SSOResponseException {

    if (conditions == null)
        return;/*from  ww w.  j  a  v  a 2 s .  c  o m*/

    long tolerance = ((AbstractSSOMediator) channel.getIdentityMediator()).getTimestampValidationTolerance();
    Calendar utcCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

    if (conditions.getConditionOrAudienceRestrictionOrOneTimeUse() == null && conditions.getNotBefore() == null
            && conditions.getNotOnOrAfter() == null) {
        return;
    }

    logger.debug("Current time (UTC): " + utcCalendar.toString());

    XMLGregorianCalendar notBeforeUTC = null;
    XMLGregorianCalendar notOnOrAfterUTC = null;

    if (conditions.getNotBefore() != null) {
        //normalize to UTC         
        logger.debug("Conditions.NotBefore: " + conditions.getNotBefore());

        notBeforeUTC = conditions.getNotBefore().normalize();
        logger.debug("Conditions.NotBefore normalized: " + notBeforeUTC.toString());

        if (!notBeforeUTC.isValid()) {
            throw new SSOResponseException(response, StatusCode.TOP_REQUESTER,
                    StatusCode.INVALID_ATTR_NAME_OR_VALUE, StatusDetails.INVALID_UTC_VALUE,
                    notBeforeUTC.toString());
        } else {

            Calendar notBefore = notBeforeUTC.toGregorianCalendar();
            notBefore.add(Calendar.MILLISECOND, (int) tolerance * -1);

            if (utcCalendar.before(notBefore))

                throw new SSOResponseException(response, StatusCode.TOP_REQUESTER,
                        StatusCode.INVALID_ATTR_NAME_OR_VALUE, StatusDetails.NOT_BEFORE_VIOLATED,
                        notBeforeUTC.toString());
        }
    }

    // Make sure that the NOT ON OR AFTER is not violated, give a five minutes tolerance (should be configurable)
    if (conditions.getNotOnOrAfter() != null) {
        //normalize to UTC
        logger.debug("Conditions.NotOnOrAfter: " + conditions.getNotOnOrAfter().toString());
        notOnOrAfterUTC = conditions.getNotOnOrAfter().normalize();
        logger.debug("Conditions.NotOnOrAfter normalized: " + notOnOrAfterUTC.toString());
        if (!notOnOrAfterUTC.isValid()) {
            throw new SSOResponseException(response, StatusCode.TOP_REQUESTER,
                    StatusCode.INVALID_ATTR_NAME_OR_VALUE, StatusDetails.INVALID_UTC_VALUE,
                    notOnOrAfterUTC.toString());

        } else {

            // diff in millis
            Calendar notOnOrAfter = notOnOrAfterUTC.toGregorianCalendar();
            notOnOrAfter.add(Calendar.MILLISECOND, (int) tolerance);

            if (utcCalendar.after(notOnOrAfter))
                throw new SSOResponseException(response, StatusCode.TOP_REQUESTER,
                        StatusCode.INVALID_ATTR_NAME_OR_VALUE, StatusDetails.NOT_ONORAFTER_VIOLATED,
                        notOnOrAfterUTC.toString());
        }
    }

    if (notBeforeUTC != null && notOnOrAfterUTC != null && notOnOrAfterUTC.compare(notBeforeUTC) <= 0) {

        throw new SSOResponseException(response, StatusCode.TOP_REQUESTER,
                StatusCode.INVALID_ATTR_NAME_OR_VALUE, StatusDetails.INVALID_CONDITION,
                "'Not On or After' earlier that 'Not Before'");
    }

    // Our SAMLR2 Enityt ID should be part of the audience
    CircleOfTrustMemberDescriptor sp = this.getCotMemberDescriptor();
    MetadataEntry spMd = sp.getMetadata();

    if (spMd == null || spMd.getEntry() == null)
        throw new SSOException("No metadata descriptor found for SP " + sp);

    EntityDescriptorType md = null;
    if (spMd.getEntry() instanceof EntityDescriptorType) {
        md = (EntityDescriptorType) spMd.getEntry();
    } else
        throw new SSOException("Unsupported Metadata type " + md + ", SAML 2 Metadata expected");

    if (conditions.getConditionOrAudienceRestrictionOrOneTimeUse() != null) {
        boolean audienceRestrictionValid = false;
        boolean spInAllAudiences = false;
        boolean initState = true;
        for (ConditionAbstractType conditionAbs : conditions.getConditionOrAudienceRestrictionOrOneTimeUse()) {
            if (conditionAbs instanceof AudienceRestrictionType) {
                AudienceRestrictionType audienceRestriction = (AudienceRestrictionType) conditionAbs;
                if (audienceRestriction.getAudience() != null) {
                    boolean spInAudience = false;
                    for (String audience : audienceRestriction.getAudience()) {
                        if (audience.equals(md.getEntityID())) {
                            spInAudience = true;
                            break;
                        }
                    }
                    spInAllAudiences = (initState ? spInAudience : spInAllAudiences && spInAudience);
                    initState = false;
                }
            }
            audienceRestrictionValid = audienceRestrictionValid || spInAllAudiences;
        }
        if (!audienceRestrictionValid) {
            logger.error("SP is not in Audience list.");
            throw new SSOResponseException(response, StatusCode.TOP_REQUESTER,
                    StatusCode.INVALID_ATTR_NAME_OR_VALUE, StatusDetails.NOT_IN_AUDIENCE);
        }
    }

}

From source file:com.microsoft.tfs.core.clients.versioncontrol.internal.localworkspace.LocalDataAccessLayer.java

private static boolean reconcileLocalWorkspaceHelper(final Workspace workspace,
        final WebServiceLayer webServiceLayer, final boolean unscannedReconcile,
        final boolean reconcileMissingFromDisk, final AtomicReference<Failure[]> failures,
        final AtomicBoolean pendingChangesUpdatedByServer) {
    Check.notNull(workspace, "workspace"); //$NON-NLS-1$
    pendingChangesUpdatedByServer.set(false);
    final List<PendingChange> convertedAdds = new ArrayList<PendingChange>();

    final boolean throwOnProjectRenamed;
    if (EnvironmentVariables.isDefined(EnvironmentVariables.DD_SUITES_PROJECT_RENAME_UNPATCHED_CLIENT)) {
        throwOnProjectRenamed = false;/*from   w  w w . ja  v  a  2 s . c  om*/
    } else {
        throwOnProjectRenamed = true;
    }

    final AtomicReference<GUID> serverPendingChangeSignature = new AtomicReference<GUID>(GUID.EMPTY);

    // No optimization away of reconciles when sending up MissingFromDisk
    // rows, since the bit in the header (lvHeader.PendingReconcile) may be
    // false when we actually have work to do (there are rows in the table
    // marked MissingFromDisk).
    if ((unscannedReconcile || !workspace.getWorkspaceWatcher().isScanNecessary())
            && !reconcileMissingFromDisk) {
        // Pre-reconcile
        final AtomicBoolean hasPendingLocalVersionRows = new AtomicBoolean(true);
        LocalWorkspaceTransaction transaction = new LocalWorkspaceTransaction(workspace);

        try {
            transaction.execute(new LocalVersionHeaderTransaction() {
                @Override
                public void invoke(final WorkspaceVersionTableHeader lvh) {
                    hasPendingLocalVersionRows.set(lvh.getPendingReconcile());
                }
            });
        } finally {
            try {
                transaction.close();
            } catch (final IOException e) {
                throw new VersionControlException(e);
            }
        }

        final AtomicReference<GUID> clientPendingChangeSignature = new AtomicReference<GUID>(GUID.EMPTY);

        if (!hasPendingLocalVersionRows.get()) {
            transaction = new LocalWorkspaceTransaction(workspace);
            try {
                transaction.execute(new PendingChangesHeaderTransaction() {
                    @Override
                    public void invoke(final LocalPendingChangesTableHeader pch) {
                        clientPendingChangeSignature.set(pch.getClientSignature());

                    }
                });
            } finally {
                try {
                    transaction.close();
                } catch (final IOException e) {
                    throw new VersionControlException(e);
                }
            }

            final GUID lastServerPendingChangeGuid = workspace.getOfflineCacheData()
                    .getLastServerPendingChangeSignature();
            final Calendar lastReconcileTime = workspace.getOfflineCacheData().getLastReconcileTime();
            lastReconcileTime.add(Calendar.SECOND, 8);

            if (lastServerPendingChangeGuid != GUID.EMPTY
                    && clientPendingChangeSignature.get().equals(lastServerPendingChangeGuid)
                    && lastReconcileTime.after(Calendar.getInstance())) {
                // This reconcile was optimized away with no server call.

                failures.set(new Failure[0]);
                return false;
            }

            serverPendingChangeSignature.set(
                    webServiceLayer.queryPendingChangeSignature(workspace.getName(), workspace.getOwnerName()));

            if (serverPendingChangeSignature.get() != GUID.EMPTY
                    && clientPendingChangeSignature.get().equals(serverPendingChangeSignature)) {
                // This reconcile was optimized away.

                workspace.getOfflineCacheData()
                        .setLastServerPendingChangeSignature(serverPendingChangeSignature.get());
                workspace.getOfflineCacheData().setLastReconcileTime(Calendar.getInstance());

                failures.set(new Failure[0]);
                return false;
            }
        }
    }

    final AtomicBoolean toReturn = new AtomicBoolean(true);

    final LocalWorkspaceTransaction transaction = new LocalWorkspaceTransaction(workspace);
    try {
        final AtomicReference<Failure[]> delegateFailures = new AtomicReference<Failure[]>(new Failure[0]);
        final AtomicBoolean delegatePCUpdated = new AtomicBoolean(false);

        transaction.execute(new AllTablesTransaction() {
            @Override
            public void invoke(final LocalWorkspaceProperties wp, final WorkspaceVersionTable lv,
                    final LocalPendingChangesTable pc) {
                if (!unscannedReconcile) {
                    // The line below has been commented out because we
                    // decided not to force a full scan here, because it
                    // causes significant degradation in UI performance.
                    //
                    // workspace.getWorkspaceWatcher().markPathChanged(null);
                    //
                    // It was an attempt to fix the bug:
                    // Bug 6191: When using local workspaces, get latest
                    // does not get a file that has been deleted from disk.
                    //
                    // The customer has to explicitly invoke
                    // Pending Changes>Actions>Detect local changes
                    // in Team Explorer.
                    //
                    // Note that none of customers reported that as an
                    // issue.
                    // It was detected on our tests only.
                    workspace.getWorkspaceWatcher().scan(wp, lv, pc);
                }

                // Pre-reconcile
                if (!lv.getPendingReconcile() && !reconcileMissingFromDisk
                        && GUID.EMPTY == serverPendingChangeSignature.get()) {
                    serverPendingChangeSignature.set(webServiceLayer
                            .queryPendingChangeSignature(workspace.getName(), workspace.getOwnerName()));

                    if (serverPendingChangeSignature.get() != GUID.EMPTY
                            && pc.getClientSignature().equals(serverPendingChangeSignature.get())) {
                        // This reconcile was optimized away.
                        delegateFailures.set(new Failure[0]);

                        workspace.getOfflineCacheData()
                                .setLastServerPendingChangeSignature(serverPendingChangeSignature.get());
                        workspace.getOfflineCacheData().setLastReconcileTime(Calendar.getInstance());

                        toReturn.set(true);

                        return;
                    }
                }

                // Acknowledgment of team project renames, if any have been
                // completed
                if (wp.getNewProjectRevisionId() > 0) {
                    webServiceLayer.promotePendingWorkspaceMappings(workspace.getName(),
                            workspace.getOwnerName(), wp.getNewProjectRevisionId());

                    wp.setNewProjectRevisionId(0);
                }

                final LocalPendingChange[] pendingChanges = pc.queryByTargetServerItem(ServerPath.ROOT,
                        RecursionType.FULL, null);

                /*
                 * TEE-specific Code
                 *
                 * In order to support offline property changes, which
                 * cannot be reconciled with
                 * WebServiceLayer.reconcileLocalWorkspace (the property
                 * values can't be sent), we have to pull out the pended
                 * property changes and send them to the server before
                 * reconciling.
                 */
                final List<ChangeRequest> propertyRequests = new ArrayList<ChangeRequest>();

                for (final LocalPendingChange lpc : pendingChanges) {
                    if (lpc.getChangeType().contains(ChangeType.PROPERTY)) {
                        final PropertyValue[] pv = lpc.getPropertyValues();
                        final String serverItem = lpc.getTargetServerItem();

                        if (pv != null && pv.length > 0 && serverItem != null) {
                            final ChangeRequest request = new ChangeRequest(
                                    new ItemSpec(serverItem, RecursionType.NONE),
                                    new WorkspaceVersionSpec(workspace), RequestType.PROPERTY, ItemType.ANY,
                                    VersionControlConstants.ENCODING_UNCHANGED, LockLevel.UNCHANGED, 0, null,
                                    false);

                            request.setProperties(pv);

                            propertyRequests.add(request);
                        }
                    }
                }

                if (propertyRequests.size() > 0) {
                    ((WebServiceLayerLocalWorkspaces) webServiceLayer).pendChangesInLocalWorkspace(
                            workspace.getName(), workspace.getOwnerName(),
                            propertyRequests.toArray(new ChangeRequest[propertyRequests.size()]),
                            PendChangesOptions.NONE, SupportedFeatures.ALL, new AtomicReference<Failure[]>(),
                            null, null, new AtomicBoolean(), new AtomicReference<ChangePendedFlags>());

                    // TODO handle failures?
                }

                // Back to normal, non-TEE behavior

                final AtomicBoolean outClearLocalVersionTable = new AtomicBoolean();
                final ServerItemLocalVersionUpdate[] lvUpdates = lv.getUpdatesForReconcile(pendingChanges,
                        reconcileMissingFromDisk, outClearLocalVersionTable);

                ReconcileResult result = webServiceLayer.reconcileLocalWorkspace(workspace.getName(),
                        workspace.getOwnerName(), pc.getClientSignature(), pendingChanges, lvUpdates,
                        outClearLocalVersionTable.get(), throwOnProjectRenamed);

                // report any failures
                Failure[] reconcileFailures = result.getFailures();
                workspace.getClient().reportFailures(workspace, reconcileFailures);

                if (reconcileFailures.length > 0) {
                    throw new ReconcileFailedException(reconcileFailures);
                }

                GUID newSignature = new GUID(result.getNewSignature());
                PendingChange[] newPendingChanges = result.getNewPendingChanges();

                // If the local version rows for this local workspace have
                // been purged from the server, then the server will set
                // this flag on the result of the next reconcile.
                if (result.isReplayLocalVersionsRequired()) {
                    // Reconcile a second time. This time, set the
                    // clearLocalVersionTable flag. This way, we know
                    // we have cleared out any lingering local version rows
                    // for this workspace.
                    if (!outClearLocalVersionTable.get()) {
                        result = webServiceLayer.reconcileLocalWorkspace(workspace.getName(),
                                workspace.getOwnerName(), pc.getClientSignature(), pendingChanges, lvUpdates,
                                true /* clearLocalVersionTable */, throwOnProjectRenamed);

                        // Report any failures
                        reconcileFailures = result.getFailures();
                        workspace.getClient().reportFailures(workspace, reconcileFailures);

                        if (reconcileFailures.length > 0) {
                            throw new ReconcileFailedException(reconcileFailures);
                        }

                        // Grab the new signature and new pending changes
                        newSignature = new GUID(result.getNewSignature());
                        newPendingChanges = result.getNewPendingChanges();
                    }

                    // Now, go through the local version table and replay
                    // every row that we have.
                    final List<ServerItemLocalVersionUpdate> replayUpdates = new ArrayList<ServerItemLocalVersionUpdate>(
                            Math.min(lv.getLocalItemsCount(), 1000));

                    for (final WorkspaceLocalItem lvEntry : lv.queryByServerItem(ServerPath.ROOT,
                            RecursionType.FULL, null, true /* includeDeleted */)) {
                        final ServerItemLocalVersionUpdate replayUpdate = lvEntry
                                .getLocalVersionUpdate(reconcileMissingFromDisk, true /* force */);

                        if (replayUpdate != null) {
                            replayUpdates.add(replayUpdate);

                            // Batch these updates in groups of 1000 items.
                            if (replayUpdates.size() >= 1000) {
                                webServiceLayer.updateLocalVersion(workspace.getName(),
                                        workspace.getOwnerName(), replayUpdates.toArray(
                                                new ServerItemLocalVersionUpdate[replayUpdates.size()]));

                                replayUpdates.clear();
                            }
                        }
                    }

                    if (replayUpdates.size() > 0) {
                        webServiceLayer.updateLocalVersion(workspace.getName(), workspace.getOwnerName(),
                                replayUpdates.toArray(new ServerItemLocalVersionUpdate[replayUpdates.size()]));
                    }
                }

                if (result.isPendingChangesUpdated()) {
                    delegatePCUpdated.set(true);

                    final Map<String, ItemType> newPendingDeletes = new TreeMap<String, ItemType>(
                            String.CASE_INSENSITIVE_ORDER);

                    for (final PendingChange pendingChange : newPendingChanges) {
                        if (pendingChange.isAdd()) {
                            final LocalPendingChange oldPendingChange = pc
                                    .getByTargetServerItem(pendingChange.getServerItem());

                            if (null == oldPendingChange || !oldPendingChange.isAdd()) {
                                // Before calling ReconcileLocalWorkspace,
                                // we did not have a pending add at this
                                // target server item.
                                convertedAdds.add(pendingChange);
                            }
                        } else if (pendingChange.isDelete()) {
                            // If the server removed any of our presented
                            // pending deletes, we want to know about it so
                            // we can get rid of the local version rows that
                            // we have in the deleted state. The server will
                            // remove our pending deletes when the item has
                            // been destroyed on the server.
                            newPendingDeletes.put(
                                    pendingChange.getSourceServerItem() == null ? pendingChange.getServerItem()
                                            : pendingChange.getSourceServerItem(),
                                    pendingChange.getItemType());
                        }
                    }

                    for (final LocalPendingChange oldPendingChange : pc
                            .queryByCommittedServerItem(ServerPath.ROOT, RecursionType.FULL, null)) {
                        if (oldPendingChange.isDelete()
                                && !newPendingDeletes.containsKey(oldPendingChange.getCommittedServerItem())) {
                            // We presented this delete to the server for
                            // Reconcile, but the server removed it from the
                            // pending changes manifest. We need to get rid
                            // of the LV rows for
                            // oldPendingChange.CommittedServerItem since
                            // this item is now destroyed.
                            final List<ServerItemIsCommittedTuple> lvRowsToRemove = new ArrayList<ServerItemIsCommittedTuple>();

                            final RecursionType recursion = oldPendingChange.isRecursiveChange()
                                    ? RecursionType.FULL
                                    : RecursionType.NONE;

                            // Aggregate up the deleted local version
                            // entries at this committed server item
                            // (or below if it's a folder), and we'll remove
                            // them.
                            for (final WorkspaceLocalItem lvEntry : lv.queryByServerItem(
                                    oldPendingChange.getCommittedServerItem(), recursion, null,
                                    true /* includeDeleted */)) {
                                if (lvEntry.isDeleted()) {
                                    lvRowsToRemove.add(new ServerItemIsCommittedTuple(lvEntry.getServerItem(),
                                            lvEntry.isCommitted()));
                                }
                            }

                            for (final ServerItemIsCommittedTuple tuple : lvRowsToRemove) {
                                // We don't need to reconcile the removal of
                                // LV entries marked IsDeleted since they
                                // don't exist on the server anyway.
                                lv.removeByServerItem(tuple.getCommittedServerItem(), tuple.isCommitted(),
                                        false);
                            }
                        }
                    }

                    pc.replacePendingChanges(newPendingChanges);
                }

                // If all we're doing to LV is marking it reconciled, then
                // don't use TxF to commit
                // both tables atomically as this is slower
                if (!lv.isDirty()) {
                    transaction.setAllowTxF(false);
                }

                if (lvUpdates.length > 0) {
                    lv.markAsReconciled(wp, reconcileMissingFromDisk);

                    // If we removed all missing-from-disk items from the
                    // local version table, then we need to remove
                    // the corresponding candidate delete rows for those
                    // items as well.
                    if (reconcileMissingFromDisk) {
                        List<String> candidatesToRemove = null;

                        for (final LocalPendingChange candidateChange : pc
                                .queryCandidatesByTargetServerItem(ServerPath.ROOT, RecursionType.FULL, null)) {
                            if (candidateChange.isDelete()) {
                                if (null == candidatesToRemove) {
                                    candidatesToRemove = new ArrayList<String>();
                                }
                                candidatesToRemove.add(candidateChange.getTargetServerItem());
                            }
                        }

                        if (null != candidatesToRemove) {
                            for (final String candidateDeleteTargetServerItem : candidatesToRemove) {
                                pc.removeCandidateByTargetServerItem(candidateDeleteTargetServerItem);
                            }
                            // Set the candidates changed to true so that it
                            // refreshes the UI
                            LocalWorkspaceTransaction.getCurrent().setRaisePendingChangeCandidatesChanged(true);
                        }
                    }
                }

                newSignature = webServiceLayer.queryPendingChangeSignature(workspace.getName(),
                        workspace.getOwnerName());

                if (!newSignature.equals(pc.getClientSignature())) {
                    pc.setClientSignature(newSignature);
                    workspace.getOfflineCacheData().setLastServerPendingChangeSignature(newSignature);
                }

                if (!newSignature.equals(pc.getClientSignature())) {
                    pc.setClientSignature(newSignature);
                    workspace.getOfflineCacheData().setLastServerPendingChangeSignature(newSignature);
                }

                workspace.getOfflineCacheData().setLastReconcileTime(Calendar.getInstance());
            }
        });

        failures.set(delegateFailures.get());
        pendingChangesUpdatedByServer.set(delegatePCUpdated.get());
    } finally {
        try {
            transaction.close();
        } catch (final IOException e) {
            throw new VersionControlException(e);
        }
    }

    if (convertedAdds.size() > 0) {
        final UpdateLocalVersionQueueOptions options = UpdateLocalVersionQueueOptions.UPDATE_BOTH;
        final UpdateLocalVersionQueue ulvq = new UpdateLocalVersionQueue(workspace, options);

        try {
            for (final PendingChange pc : convertedAdds) {
                // Every item in this list has a ChangeType of Add. As a
                // result they are uncommitted items with no committed hash
                // value, no committed length, and no baseline file GUID.
                ulvq.queueUpdate(new ClientLocalVersionUpdate(pc.getServerItem(), pc.getItemID(),
                        pc.getLocalItem(), 0 /* localVersion */, DotNETDate.MIN_CALENDAR, pc.getEncoding(),
                        null /* committedHashValue */, 0 /* committedLength */, null /* baselineFileGuid */,
                        null /* pendingChangeTargetServerItem */, null /* properties */));
            }
        } finally {
            ulvq.close();
        }
    }

    return toReturn.get();
}