Example usage for java.util Date compareTo

List of usage examples for java.util Date compareTo

Introduction

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

Prototype

public int compareTo(Date anotherDate) 

Source Link

Document

Compares two Dates for ordering.

Usage

From source file:org.apache.oozie.command.coord.CoordCommandUtils.java

/**
 * Get the next action time after a given time
 *
 * @param targetDate/* w  w  w .  ja v a 2  s.c o  m*/
 * @param coordJob
 * @return the next valid action time
 */
public static Date getNextValidActionTimeForCronFrequency(Date targetDate, CoordinatorJobBean coordJob)
        throws ParseException {

    String freq = coordJob.getFrequency();
    TimeZone tz = DateUtils.getOozieProcessingTimeZone();
    String[] cronArray = freq.split(" ");
    Date nextTime = null;

    // Current CronExpression doesn't support operations
    // where both date of months and day of weeks are specified.
    // As a result, we need to split this scenario into two cases
    // and return the earlier time
    if (!cronArray[2].trim().equals("?") && !cronArray[4].trim().equals("?")) {

        // When any one of day of month or day of week fields is a wildcard
        // we need to replace the wildcard with "?"
        if (cronArray[2].trim().equals("*") || cronArray[4].trim().equals("*")) {
            if (cronArray[2].trim().equals("*")) {
                cronArray[2] = "?";
            } else {
                cronArray[4] = "?";
            }
            freq = StringUtils.join(cronArray, " ");

            // The cronExpression class takes second
            // as the first field where oozie is operating on
            // minute basis
            CronExpression expr = new CronExpression("0 " + freq);
            expr.setTimeZone(tz);
            nextTime = expr.getNextValidTimeAfter(targetDate);
        }
        // If both fields are specified by non-wildcards,
        // we need to split it into two expressions
        else {
            String[] cronArray1 = freq.split(" ");
            String[] cronArray2 = freq.split(" ");

            cronArray1[2] = "?";
            cronArray2[4] = "?";

            String freq1 = StringUtils.join(cronArray1, " ");
            String freq2 = StringUtils.join(cronArray2, " ");

            // The cronExpression class takes second
            // as the first field where oozie is operating on
            // minute basis
            CronExpression expr1 = new CronExpression("0 " + freq1);
            expr1.setTimeZone(tz);
            CronExpression expr2 = new CronExpression("0 " + freq2);
            expr2.setTimeZone(tz);
            nextTime = expr1.getNextValidTimeAfter(targetDate);
            Date nextTime2 = expr2.getNextValidTimeAfter(targetDate);
            nextTime = nextTime.compareTo(nextTime2) < 0 ? nextTime : nextTime2;
        }
    } else {
        // The cronExpression class takes second
        // as the first field where oozie is operating on
        // minute basis
        CronExpression expr = new CronExpression("0 " + freq);
        expr.setTimeZone(tz);
        nextTime = expr.getNextValidTimeAfter(targetDate);
    }

    return nextTime;
}

From source file:org.apache.ode.bpel.runtime.PICK.java

/**
 * @see org.apache.ode.jacob.JacobRunnable#run()
 *///  w w w .j  a  va2s.  c o m
public void run() {
    PickResponse pickResponseChannel = newChannel(PickResponse.class);
    Date timeout;
    Selector[] selectors;

    try {
        selectors = new Selector[_opick.onMessages.size()];
        int idx = 0;
        for (OPickReceive.OnMessage onMessage : _opick.onMessages) {
            // collect all initiated correlations
            Set<OScope.CorrelationSet> matchCorrelations = new HashSet<OScope.CorrelationSet>();
            matchCorrelations.addAll(onMessage.matchCorrelations);
            for (OScope.CorrelationSet cset : onMessage.joinCorrelations) {
                if (getBpelRuntimeContext().isCorrelationInitialized(_scopeFrame.resolve(cset))) {
                    matchCorrelations.add(cset);
                }
            }

            PartnerLinkInstance pLinkInstance = _scopeFrame.resolve(onMessage.partnerLink);
            CorrelationKeySet keySet = resolveCorrelationKey(pLinkInstance, matchCorrelations);

            selectors[idx] = new Selector(idx, pLinkInstance, onMessage.operation.getName(),
                    onMessage.operation.getOutput() == null, onMessage.messageExchangeId, keySet,
                    onMessage.route);
            idx++;
        }

        timeout = null;
        for (OPickReceive.OnAlarm onAlarm : _opick.onAlarms) {
            Date dt = onAlarm.forExpr != null
                    ? offsetFromNow(getBpelRuntimeContext().getExpLangRuntime()
                            .evaluateAsDuration(onAlarm.forExpr, getEvaluationContext()))
                    : getBpelRuntimeContext().getExpLangRuntime()
                            .evaluateAsDate(onAlarm.untilExpr, getEvaluationContext()).getTime();
            if (timeout == null || timeout.compareTo(dt) > 0) {
                timeout = dt;
                _alarm = onAlarm;
            }
        }
        getBpelRuntimeContext().select(pickResponseChannel, timeout, _opick.createInstanceFlag, selectors);
    } catch (FaultException e) {
        __log.error(e);
        FaultData fault = createFault(e.getQName(), _opick, e.getMessage());
        dpe(_opick.outgoingLinks);
        _self.parent.completed(fault, CompensationHandler.emptySet());
        return;
    } catch (EvaluationException e) {
        String msg = "Unexpected evaluation error evaluating alarm.";
        __log.error(msg, e);
        throw new InvalidProcessException(msg, e);
    }

    // Dead path all the alarms that have no chace of coming first.
    for (OPickReceive.OnAlarm oa : _opick.onAlarms) {
        if (!oa.equals(_alarm)) {
            dpe(oa.activity);
        }
    }

    instance(new WAITING(pickResponseChannel));
}

From source file:com.sfs.whichdoctor.search.sql.PersonSqlHandler.java

/**
 * Process racp fellowship./*from   ww  w  . j a v  a 2 s.  c  o  m*/
 *
 * @param criteria the criteria
 * @param constraints the constraints
 *
 * @return the object[]
 */
private Object[] processRACPFellowship(final MembershipBean criteria, final MembershipBean constraints) {
    StringBuffer sqlWHERE = new StringBuffer();
    StringBuffer description = new StringBuffer();
    Collection<Object> parameters = new ArrayList<Object>();

    if (criteria.getIntField("FRACP") > 0) {
        final int fracpCriteria = criteria.getIntField("FRACP");
        final int fracpConstraints = constraints.getIntField("FRACP");

        if (fracpCriteria > 0) {
            boolean maximum = false;
            boolean minimum = false;
            boolean range = false;
            boolean single = true;

            if (fracpConstraints < 0) {
                minimum = true;
                single = false;
            }
            if (fracpConstraints > 0) {
                range = true;
                single = false;
            }

            if (fracpConstraints == 999999999) {
                maximum = true;
                range = false;
                single = false;
            }
            if (minimum) {
                // Get values less than supplied FRACP
                sqlWHERE.append(" AND " + criteria.getDataTableName("FRACP") + "."
                        + criteria.getDataFieldName("FRACP") + " <= ?");
                description.append(" and a FRACP less than '" + fracpCriteria + "'");
                parameters.add(fracpCriteria);
            }
            if (maximum) {
                maximum = true;
                // Get values greater than supplied FRACP
                sqlWHERE.append(" AND " + criteria.getDataTableName("FRACP") + "."
                        + criteria.getDataFieldName("FRACP") + " >= ?");
                description.append(" and a FRACP greater than '" + fracpCriteria + "'");
                parameters.add(fracpCriteria);
            }
            if (range) {
                // Search Constraints between A and B
                if (fracpCriteria > fracpConstraints) {
                    // A greater than B
                    sqlWHERE.append(" AND " + criteria.getDataTableName("FRACP") + "."
                            + criteria.getDataFieldName("FRACP") + " BETWEEN ? AND ?");
                    description.append(
                            " and a FRACP between '" + fracpConstraints + "' and '" + fracpCriteria + "'");
                    parameters.add(fracpConstraints);
                    parameters.add(fracpCriteria);
                } else if (fracpCriteria < fracpConstraints) {
                    // B greater than A
                    sqlWHERE.append(" AND " + criteria.getDataTableName("FRACP") + "."
                            + criteria.getDataFieldName("FRACP") + " BETWEEN ? AND ?");
                    description.append(
                            " and a FRACP between '" + fracpCriteria + "' and '" + fracpConstraints + "'");
                    parameters.add(fracpCriteria);
                    parameters.add(fracpConstraints);
                } else {
                    // A = B
                    sqlWHERE.append(" AND " + criteria.getDataTableName("FRACP") + "."
                            + criteria.getDataFieldName("FRACP") + " = ?");
                    description.append(" and a FRACP equal to '" + fracpCriteria + "'");
                    parameters.add(fracpCriteria);
                }
            }
            if (single) {
                sqlWHERE.append(" AND " + criteria.getDataTableName("FRACP") + "."
                        + criteria.getDataFieldName("FRACP") + " = ?");
                description.append(" and a FRACP equal to '" + fracpCriteria + "'");
                parameters.add(fracpCriteria);
            }
        }
    }

    // Search for date of Fellowship
    if (StringUtils.isNotBlank(criteria.getField("Fellowship Date"))) {
        Date fellowshipCriteria = criteria.getDateField("Fellowship Date");
        Date fellowshipConstraints = constraints.getDateField("Fellowship Date");

        if (fellowshipCriteria != null) {
            if (fellowshipConstraints != null) {
                int larger = fellowshipCriteria.compareTo(fellowshipConstraints);
                if (larger > 0) {
                    // SearchCriteria date after SearchConstraint
                    // date
                    String fieldA = this.getDf().format(fellowshipCriteria);
                    String fieldB = this.getDf().format(fellowshipConstraints);
                    sqlWHERE.append(" AND " + criteria.getDataTableName("Fellowship Date") + "."
                            + criteria.getDataFieldName("Fellowship Date") + " BETWEEN ? AND ?");
                    description.append(" and a Fellowship date between '" + fieldB + "' and '" + fieldA + "'");
                    parameters.add(fieldB);
                    parameters.add(fieldA);
                }
                if (larger < 0) {
                    // SearchCriteria date before SearchConstraint
                    // date
                    String fieldA = this.getDf().format(fellowshipCriteria);
                    String fieldB = this.getDf().format(fellowshipConstraints);
                    sqlWHERE.append(" AND " + criteria.getDataTableName("Fellowship Date") + "."
                            + criteria.getDataFieldName("Fellowship Date") + " BETWEEN ? AND ?");
                    description.append(" and a Fellowship date between '" + fieldA + "' and '" + fieldB + "'");
                    parameters.add(fieldA);
                    parameters.add(fieldB);

                }
                if (larger == 0) {
                    // SearchCritier and SearchConstraint are equal
                    String field = this.getDf().format(fellowshipCriteria);
                    sqlWHERE.append(" AND " + criteria.getDataTableName("Fellowship Date") + "."
                            + criteria.getDataFieldName("Fellowship Date") + " = ?");
                    description.append(" and a Fellowship date on '" + field + "'");
                    parameters.add(field);
                }
            } else {
                String field = this.getDf().format(fellowshipCriteria);
                sqlWHERE.append(" AND " + criteria.getDataTableName("Fellowship Date") + "."
                        + criteria.getDataFieldName("Fellowship Date") + " = ?");
                description.append(" and a Fellowship date on '" + field + "'");
                parameters.add(field);
            }
        }
    }
    String[] objectArray = { "Admitting SAC" };
    for (int i = 0; i < objectArray.length; i++) {
        String fieldName = objectArray[i];
        if (criteria.getField(fieldName).compareTo("") != 0) {
            ObjectTypeBean object = criteria.getObjectTypeField(fieldName);
            if (object.getClassName() != null) {
                if (object.getClassName().compareTo("") != 0) {
                    sqlWHERE.append(" AND " + criteria.getDataTableName(fieldName) + ".Class = ?");
                    description.append(" and a " + fieldName + " of '" + object.getClassName() + "'");
                    parameters.add(object.getClassName());
                }
            }
            if (object.getName() != null) {
                if (object.getName().compareTo("") != 0) {
                    sqlWHERE.append(" AND " + criteria.getDataTableName(fieldName) + ".Name = ?");
                    description.append(" and a sub-" + fieldName + " of '" + object.getName() + "'");
                    parameters.add(object.getName());
                }
            }
        }
    }
    if (StringUtils.isNotBlank(criteria.getField("Admitting Country"))) {
        sqlWHERE.append(" AND " + criteria.getDataTableName("Admitting Country") + "."
                + criteria.getDataFieldName("Admitting Country") + " = ?");
        description
                .append(" and was admitted to Fellowship by '" + criteria.getField("Admitting Country") + "'");
        parameters.add(criteria.getField("Admitting Country"));
    }

    return new Object[] { sqlWHERE.toString(), description.toString(), parameters };
}

From source file:org.mifos.accounts.business.AccountBO.java

private boolean isTrxnDateBeforePreviousMeetingDateAllowed(final Date trxnDate, Date meetingDate,
        boolean repaymentIndependentOfMeetingEnabled) {

    if (repaymentIndependentOfMeetingEnabled) {
        // payment date for loans must be >= disbursement date
        if (this instanceof LoanBO) {
            Date approvalDate = this.getAccountApprovalDate();
            return trxnDate.compareTo(DateUtils.getDateWithoutTimeStamp(approvalDate)) >= 0;
        }//  w  w w .  j  ava  2s.  co  m
        // must be >= creation date for other accounts
        return trxnDate.compareTo(DateUtils.getDateWithoutTimeStamp(this.getCreatedDate())) >= 0;
    } else if (meetingDate != null) {
        return trxnDate.compareTo(DateUtils.getDateWithoutTimeStamp(meetingDate)) >= 0;
    }
    return false;
}

From source file:com.zimbra.perf.chart.ChartUtil.java

private void readCsvFiles() throws Exception {
    Date minDate = null;/*from w w w . jav a2 s  .c  o  m*/
    Date maxDate = null;

    // GROUP PLOT SUPPORT
    // the downside of this loop is that it will re-open the file once
    // for each column name, if more than one column name is specified
    // per-file--shouldn't happen much since this is only for groupplot
    for (DataColumn c : mUniqueStringColumns) {
        String inFilename = c.getInfile();
        Reader reader = null;
        StringSeries data = mStringSeries.get(c);
        try {
            reader = new MultipleDirsFileReader(inFilename, mSrcDirs);
        } catch (FileNotFoundException e) {
            System.out.printf("CSV file %s not found; Skipping...\n", inFilename);
            continue;
        }
        CsvReader csv = null;

        try {
            csv = new CsvReader(reader);
            int line = 1;
            while (csv.hasNext()) {
                line++;
                String ctx = inFilename + ", line " + line;
                Date ts = null;
                try {
                    ts = readTS(csv, ctx);
                } catch (ParseException e) {
                    if (e.getMessage().compareTo("Unparseable date: \"timestamp\"") != 0) {
                        //bug 54626, ignored the repeat timestamp header
                        System.out.println(ctx + ": " + e);
                    }
                    continue;
                }

                if (ts.before(mStartAt) || ts.after(mEndAt))
                    continue;
                if (minDate == null) {
                    minDate = ts;
                    maxDate = ts;
                } else {
                    if (ts.compareTo(minDate) < 0)
                        minDate = ts;
                    if (ts.compareTo(maxDate) > 0)
                        maxDate = ts;
                }

                String value = csv.getValue(c.getColumn());
                data.AddEntry(ts, value);
            }
        } finally {
            if (csv != null)
                csv.close();
        }
    }
    // Read CSVs and populate data series.
    for (Iterator<Map.Entry<String, Set<Pair<String, DataSeries>>>> mapIter = mColumnsByInfile.entrySet()
            .iterator(); mapIter.hasNext();) {
        Map.Entry<String, Set<Pair<String, DataSeries>>> entry = mapIter.next();
        String inFilename = entry.getKey();
        Set<Pair<String, DataSeries>> columns = entry.getValue();

        System.out.println("Reading CSV " + inFilename);
        Reader reader = null;
        try {
            reader = new MultipleDirsFileReader(inFilename, mSrcDirs);
        } catch (FileNotFoundException e) {
            System.out.printf("CSV file %s not found; Skipping...\n", inFilename);
            continue;
        }

        CsvReader csv = null;
        try {
            csv = new CsvReader(reader);
            int line = 1;
            while (csv.hasNext()) {
                line++;
                String context = inFilename + ", line " + line;

                Date ts = null;
                try {
                    ts = readTS(csv, context);
                } catch (ParseException e) {
                    if (e.getMessage().compareTo("Unparseable date: \"timestamp\"") != 0) {
                        //bug 54626, ignored the repeat timestamp header
                        System.out.println(context + ": " + e);
                    }
                    continue;
                }

                if (ts.before(mStartAt) || ts.after(mEndAt))
                    continue;

                // Set min/max date
                if (minDate == null) {
                    minDate = ts;
                    maxDate = ts;
                } else {
                    if (ts.compareTo(minDate) < 0) {
                        minDate = ts;
                    }
                    if (ts.compareTo(maxDate) > 0) {
                        maxDate = ts;
                    }
                }

                // Parse values
                for (Iterator<Pair<String, DataSeries>> colIter = columns.iterator(); colIter.hasNext();) {
                    Pair<String, DataSeries> colSeries = colIter.next();
                    String column = colSeries.getFirst();
                    DataSeries series = colSeries.getSecond();
                    String val = csv.getValue(column);
                    if (!StringUtil.isNullOrEmpty(val)) {
                        try {
                            double d = Double.parseDouble(val);
                            try {
                                series.AddEntry(ts, d);
                            } catch (SeriesException e) {
                                System.out.printf("Can't add sample to series: timestamp=%s, value=%s\n", ts,
                                        val);
                                e.printStackTrace(System.out);
                            }
                        } catch (NumberFormatException e) {
                            System.out.println(String.format("%s: unable to parse value '%s' for %s: %s",
                                    context, val, column, e));
                        }
                    } else { // default an entry to 0 if string is empty
                        series.AddEntry(ts, 0.0);
                    }
                }
            }

            for (Iterator<Pair<String, DataSeries>> colIter = columns.iterator(); colIter.hasNext();) {
                Pair<String, DataSeries> colSeries = colIter.next();
                String column = colSeries.getFirst();
                DataSeries series = colSeries.getSecond();
                System.out.format("Adding %d %s points between %s and %s.\n\n", series.size(), column, minDate,
                        maxDate);
            }
        } finally {
            if (csv != null)
                csv.close();
        }
    }

    adustSampleRange(minDate, maxDate);
}

From source file:org.squale.squaleweb.applicationlayer.action.results.project.ProjectResultsAction.java

/***
 * This method set the specific form implementations in case of manual practice
 * //  w  ww. ja v  a 2  s .c om
 * @param practiceId ID of the practice rule
 * @param result The current form
 * @param ac The application component
 * @param auditsDTO The selected audit
 * @param project The selected project
 * @throws JrafEnterpriseException Exception happened during the process
 */
private void manualMarkSpecificFormImplementation(Long practiceId, WActionForm result, IApplicationComponent ac,
        List auditsDTO, ComponentDTO project) throws JrafEnterpriseException {
    ResultForm curForm = (ResultForm) result;
    AuditDTO curAudit = (AuditDTO) auditsDTO.get(0);
    // The mark from the audit
    QualityResultDTO lastMarkFromAudit = (QualityResultDTO) ac.execute("lastManualMarkByAudit",
            new Object[] { project.getID(), practiceId, curAudit.getID() });
    // Last mark outside audit
    QualityResultDTO lastMark = (QualityResultDTO) ac.execute("lastManualMark",
            new Object[] { project.getID(), practiceId });
    // Mark date from the audit
    Date creationDate = lastMarkFromAudit.getCreationDate();
    // Last mark date outside audit
    Date lastMarkDate = lastMark.getCreationDate();
    // To avoid incorrect message when the date has not been recovered
    if (creationDate == null) {
        curForm.setLast(true);
    } else {
        // We check that the audit mark is later than or equal to the last mark
        if (creationDate.compareTo(lastMarkDate) >= 0) {
            curForm.setLast(true);
        }
        PracticeRuleDTO rule = (PracticeRuleDTO) lastMarkFromAudit.getRule();
        boolean markValid = TimeLimitationParser.isMarkValid(rule.getTimeLimitation(), creationDate);
        if (!markValid) {
            curForm.setOutOfDate(true);
        }
    }
    // If the comments exist
    if (lastMarkFromAudit.getManualMarkComment() != null) {
        curForm.setLastComments(lastMarkFromAudit.getManualMarkComment().getComments());
    }
}

From source file:org.openvpms.archetype.rules.finance.account.CustomerBalanceSummaryQuery.java

/**
 * Returns the next set in the iteration.
 *
 * @return the next set or {@code null} if overdue balances are being queried and the current balance is not overdue
 *///from w  w  w . ja v  a2  s . c om
private ObjectSet doNext() {
    IMObjectReference current = null;
    Map<IMObjectReference, ObjectSet> sets = new LinkedHashMap<IMObjectReference, ObjectSet>();
    // the sets for the current customer, keyed on act. This is necessary
    // to filter duplicate rows, should a customer erroneously have > 1
    // account type configured

    if (last != null) {
        sets.put(getAct(last), last);
        current = getEntity(last);
        last = null;
    }
    while (iterator.hasNext()) {
        ObjectSet set = iterator.next();
        IMObjectReference party = getEntity(set);
        if (party != null) {
            if (current == null || current.equals(party)) {
                current = party;
                sets.put(getAct(set), set);
            } else {
                last = set;
                break;
            }
        }
    }
    if (sets.isEmpty()) {
        throw new NoSuchElementException();
    }

    String name = null;
    BigDecimal balance = BigDecimal.ZERO;
    BigDecimal overdueBalance = BigDecimal.ZERO;
    BigDecimal creditBalance = BigDecimal.ZERO;
    BigDecimal unbilled = BigDecimal.ZERO;
    Date overdueDate = null;
    Date overdueFrom = null;
    Date overdueTo = null;
    String code;
    Lookup lookup = null;
    for (ObjectSet set : sets.values()) {
        name = (String) set.get("e.name");
        Date startTime = (Date) set.get("a.startTime");
        if (startTime instanceof Timestamp) {
            startTime = new Date(startTime.getTime());
        }
        String status = (String) set.get("a.status");
        BigDecimal amount = (BigDecimal) set.get("a.amount");
        BigDecimal allocated = (BigDecimal) set.get("a.allocatedAmount");
        boolean credit = (Boolean) set.get("a.credit");
        if (POSTED.equals(status)) {
            BigDecimal unallocated = balanceCalc.getAllocatable(amount, allocated);
            balance = calculator.addAmount(balance, unallocated, credit);
            code = (String) set.get("c.code");
            if (code != null && lookup == null) {
                lookup = getLookup(code);
            }
            if (overdueDate == null) {
                if (lookup == null) {
                    overdueDate = date;
                } else {
                    overdueDate = rules.getOverdueDate(lookup, date);
                }
                overdueFrom = overdueDate;
                if (from > 0) {
                    overdueFrom = DateRules.getDate(overdueFrom, -from, DateUnits.DAYS);
                }
                if (to > 0) {
                    overdueTo = DateRules.getDate(overdueDate, -to, DateUnits.DAYS);
                }
            }
            if (!credit && startTime.compareTo(overdueFrom) < 0
                    && (overdueTo == null || (overdueTo != null && startTime.compareTo(overdueTo) > 0))) {
                overdueBalance = calculator.addAmount(overdueBalance, unallocated, credit);
            }
            if (credit) {
                creditBalance = calculator.addAmount(creditBalance, unallocated, credit);
            }
        } else {
            IMObjectReference act = getAct(set);
            if (TypeHelper.isA(act, INVOICE, COUNTER, CREDIT)) {
                unbilled = calculator.addAmount(unbilled, amount, credit);
            }
        }
    }
    if (overdueBalance.signum() < 0) {
        overdueBalance = BigDecimal.ZERO;
    }
    ObjectSet result = null;
    boolean exclude = true;
    if (overdue && overdueBalance.compareTo(BigDecimal.ZERO) != 0) {
        exclude = false;
    }
    if (nonOverdue && overdueBalance.compareTo(BigDecimal.ZERO) == 0) {
        exclude = false;
    }
    if (excludeCredit && creditBalance.compareTo(BigDecimal.ZERO) != 0) {
        exclude = true;
    }

    if (!exclude) {
        result = new BalanceObjectSet(current);
        result.set(CUSTOMER_REFERENCE, current);
        result.set(CUSTOMER_NAME, name);
        result.set(BALANCE, balance);
        result.set(OVERDUE_BALANCE, overdueBalance);
        result.set(CREDIT_BALANCE, creditBalance);
        result.set(UNBILLED_AMOUNT, unbilled);
    }
    return result;
}

From source file:org.openmrs.module.dataintegrityworkflow.impl.DataIntegrityWorkflowServiceImpl.java

public List<IntegrityWorkflowRecord> getResultsForCustomQuery(String status, String stage, Date fromDate,
        Date toDate, User assignee, String checkId) {
    DataIntegrityWorkflowService integrityWorkflowService = Context
            .getService(DataIntegrityWorkflowService.class);
    List<IntegrityWorkflowRecord> assigneRecords = integrityWorkflowService
            .getAssignedIntegrityWorkflowRecordsOfSpecifiedCheckAndCurrentUser(assignee,
                    Integer.parseInt(checkId));
    List<IntegrityWorkflowRecord> filteredList = new ArrayList<IntegrityWorkflowRecord>();
    WorkflowStage workflowStage = integrityWorkflowService
            .getWorkflowStage(Integer.parseInt(stage.split("-")[1]));
    int statusId = Integer.parseInt(status.split("-")[1]);
    for (IntegrityWorkflowRecord integrityWorkflowRecord : assigneRecords) {
        if (integrityWorkflowRecord.getIntegrityCheckResult().getStatus() == statusId) {
            if (integrityWorkflowRecord.getCurrentAssignee().getCurrentIntegrityRecordAssignment()
                    .getCurrentStage().equals(workflowStage)) {
                IntegrityRecordStageChange lastChange = null;
                for (IntegrityRecordStageChange integrityRecordStageChange : integrityWorkflowRecord
                        .getCurrentAssignee().getCurrentIntegrityRecordAssignment()
                        .getIntegrityRecordStageChanges()) {
                    lastChange = integrityRecordStageChange;
                }/*  www.j  a  v  a  2  s . c o  m*/
                if (lastChange != null) {
                    if (fromDate.compareTo(lastChange.getChangeDate()) <= 0
                            && toDate.compareTo(lastChange.getChangeDate()) >= 0) {
                        filteredList.add(integrityWorkflowRecord);
                    }
                }
            }
        }
    }
    return filteredList;
}

From source file:com.autentia.tnt.bean.activity.ActivityBean.java

/**
 * Go to create page//from   w w  w . ja  v  a2  s .  c  om
 * 
 * @return forward to CREATE page
 */
public String create() {
    activity = new Activity();
    externalActivity = new ExternalActivity();
    selectedOrganization = null;
    selectedProject = null;
    organizations.clear();
    projects.clear();

    cal.setTime(scheduleModel.getSelectedDate());

    if (scheduleModel.getMode() == ScheduleModel.MONTH || scheduleModel.getMode() == ScheduleModel.WEEK) {
        cal.set(Calendar.HOUR_OF_DAY,
                ((SettingBean) FacesUtils.getBean("settingBean")).getMySettings().getWorkingDayHourStarts());
    }

    activity.setStartDate(cal.getTime());
    activity.setDescription(FacesUtils.getMessage("activity.description"));
    activity.setUser(authManager.getCurrentPrincipal().getUser());

    externalActivity.setStartDate(cal.getTime());
    externalActivity.setEndDate(cal.getTime()); //it is going to end in the same day
    externalActivity.setComments(FacesUtils.getMessage("offer.observations"));
    externalActivity.setOwnerId(authManager.getCurrentPrincipal().getUser().getId());
    externalActivity.setDepartmentId(authManager.getCurrentPrincipal().getUser().getDepartmentId());

    DocumentCategory padre = dcManager.getDocumentCategoryParent();
    // User category
    DocumentCategory extActDocCategory = new DocumentCategory();
    extActDocCategory.setName(externalActivity.getName());
    extActDocCategory.setDescription(externalActivity.getName());
    extActDocCategory.setPadre(padre);
    externalActivity.setDocumentCategory(extActDocCategory);

    // Preselect last selected options
    Setting val = settings.get(SettingPath.BITACORE_LAST_ROLEID, false);
    int projectRoleId = SettingManager.getInt(val, -1);

    Project pr = null;

    if (projectRoleId != -1) {
        ProjectRole projectRole;
        try {
            projectRole = projectRoleMgr.getEntityById(projectRoleId);
            if (!projectRole.getProject().isFinished()) {
                setRole(projectRole);
                setSelectedProject(projectRole.getProject());
                setSelectedOrganization(getSelectedProject().getClient());
                pr = projectRole.getProject();
            }
        } catch (ObjectNotFoundException onfex) {
            // Caso especial. Si no se  localiza el anterior rol, continuamos con la ejecucion.
        }
    }

    if (pr != null) {
        setBillable(pr.getBillable());
        setDefaultBillable(pr.getBillable());
    } else {
        val = settings.get(SettingPath.BITACORE_LAST_BILLABLE, false);
        setBillable(SettingManager.getBoolean(val, false));
    }

    if (scheduleModel.getMode() == ScheduleModel.MONTH || scheduleModel.getMode() == ScheduleModel.WEEK) {

        ActivitySearch searchToday = new ActivitySearch();
        ExternalActivitySearch extActivitySearchToday = new ExternalActivitySearch();

        Calendar initToday = Calendar.getInstance();
        initToday.setTime(scheduleModel.getSelectedDate());
        Calendar lastToday = Calendar.getInstance();
        lastToday.setTime(scheduleModel.getSelectedDate());

        initToday.set(Calendar.HOUR_OF_DAY, cal.getMinimum(Calendar.HOUR_OF_DAY));
        initToday.set(Calendar.MINUTE, cal.getMinimum(Calendar.MINUTE));
        initToday.set(Calendar.SECOND, cal.getMinimum(Calendar.SECOND));
        initToday.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND));

        lastToday.set(Calendar.HOUR_OF_DAY, cal.getMaximum(Calendar.HOUR_OF_DAY));
        lastToday.set(Calendar.MINUTE, cal.getMaximum(Calendar.MINUTE));
        lastToday.set(Calendar.SECOND, cal.getMaximum(Calendar.SECOND));
        lastToday.set(Calendar.MILLISECOND, cal.getMaximum(Calendar.MILLISECOND));

        searchToday.setStartStartDate(initToday.getTime());
        searchToday.setEndStartDate(lastToday.getTime());

        extActivitySearchToday.setStartStartDate(initToday.getTime());
        extActivitySearchToday.setEndStartDate(lastToday.getTime());

        // Try to obtain the last hour in day.

        searchToday.setUser(authManager.getCurrentPrincipal().getUser());
        extActivitySearchToday.setOwner(authManager.getCurrentPrincipal().getUser());

        List<Activity> activities = manager.getAllEntities(searchToday,
                new SortCriteria(sortColumn, sortAscending));

        List<ExternalActivity> extActivities = externalActivityManager.getAllEntities(extActivitySearchToday,
                new SortCriteria(sortColumn, sortAscending));

        if (activities.size() > 0 && extActivities.size() <= 0) {
            //No externalActivities
            //sort is descendent
            Collections.sort(activities, new compareActivitiesByStartAndDuration());
            activity.setStartDate(activities.get(0).getEndDate());
            externalActivity.setStartDate(activities.get(0).getEndDate());
            externalActivity.setEndDate(activities.get(0).getEndDate());
        } else if (activities.size() <= 0 && extActivities.size() > 0) {
            //No activities
            Collections.sort(extActivities, new compareExternalActivitiesActivitiesByStartAndDuration());
            activity.setStartDate(extActivities.get(0).getEndDate());
            externalActivity.setStartDate(extActivities.get(0).getEndDate());
            externalActivity.setEndDate(extActivities.get(0).getEndDate());
        } else if (activities.size() > 0 && extActivities.size() > 0) {

            Collections.sort(activities, new compareActivitiesByStartAndDuration());
            Collections.sort(extActivities, new compareExternalActivitiesActivitiesByStartAndDuration());

            Date lastActivityEndDate = activities.get(0).getEndDate();
            Date lastExtActivityEndDate = extActivities.get(0).getEndDate();

            Date startDate = (lastActivityEndDate.compareTo(lastExtActivityEndDate) > 0) ? lastActivityEndDate
                    : lastExtActivityEndDate;
            activity.setStartDate(startDate);
            externalActivity.setStartDate(startDate);
            externalActivity.setEndDate(startDate);
        }

    }

    tabsRendered = NO_EDIT_SELECTED;

    return NavigationResults.CREATE;
}

From source file:org.apache.falcon.workflow.engine.OozieWorkflowEngine.java

private List<CoordinatorJob> getApplicableCoords(OozieClient client, Date start, Date end,
        List<BundleJob> bundles, List<LifeCycle> lifeCycles) throws FalconException {
    List<CoordinatorJob> applicableCoords = new ArrayList<CoordinatorJob>();
    try {//  w w  w .j  a v  a  2s .  co  m
        for (BundleJob bundle : bundles) {
            List<CoordinatorJob> coords = client.getBundleJobInfo(bundle.getId()).getCoordinators();
            for (CoordinatorJob coord : coords) {
                // ignore coords in PREP state, not yet running and retention coord

                if (coord.getStatus() == Status.PREP || !isCoordApplicable(coord.getAppName(), lifeCycles)) {
                    continue;
                }

                // if end time is before coord-start time or start time is
                // after coord-end time ignore.
                if (!(end.compareTo(coord.getStartTime()) <= 0 || start.compareTo(coord.getEndTime()) >= 0)) {
                    applicableCoords.add(coord);
                }
            }
        }

        sortDescByStartTime(applicableCoords);
        return applicableCoords;
    } catch (OozieClientException e) {
        throw new FalconException(e);
    }
}