Search in sources :

Example 6 with Calendar

use of com.ibm.icu.util.Calendar in project ofbiz-framework by apache.

the class ServiceUtil method purgeOldJobs.

public static Map<String, Object> purgeOldJobs(DispatchContext dctx, Map<String, ? extends Object> context) {
    Locale locale = (Locale) context.get("locale");
    Debug.logWarning("purgeOldJobs service invoked. This service is obsolete - the Job Scheduler will purge old jobs automatically.", module);
    String sendPool = null;
    Calendar cal = Calendar.getInstance();
    try {
        sendPool = ServiceConfigUtil.getServiceEngine().getThreadPool().getSendToPool();
        int daysToKeep = ServiceConfigUtil.getServiceEngine().getThreadPool().getPurgeJobDays();
        cal.add(Calendar.DAY_OF_YEAR, -daysToKeep);
    } catch (GenericConfigException e) {
        Debug.logWarning(e, "Exception thrown while getting service configuration: ", module);
        return returnError(UtilProperties.getMessage(ServiceUtil.resource, "ServiceExceptionThrownWhileGettingServiceConfiguration", UtilMisc.toMap("errorString", e), locale));
    }
    Delegator delegator = dctx.getDelegator();
    Timestamp purgeTime = new Timestamp(cal.getTimeInMillis());
    // create the conditions to query
    EntityCondition pool = EntityCondition.makeCondition("poolId", sendPool);
    List<EntityExpr> finExp = UtilMisc.toList(EntityCondition.makeCondition("finishDateTime", EntityOperator.NOT_EQUAL, null));
    finExp.add(EntityCondition.makeCondition("finishDateTime", EntityOperator.LESS_THAN, purgeTime));
    List<EntityExpr> canExp = UtilMisc.toList(EntityCondition.makeCondition("cancelDateTime", EntityOperator.NOT_EQUAL, null));
    canExp.add(EntityCondition.makeCondition("cancelDateTime", EntityOperator.LESS_THAN, purgeTime));
    EntityCondition cancelled = EntityCondition.makeCondition(canExp);
    EntityCondition finished = EntityCondition.makeCondition(finExp);
    EntityCondition doneCond = EntityCondition.makeCondition(UtilMisc.toList(cancelled, finished), EntityOperator.OR);
    // always suspend the current transaction; use the one internally
    Transaction parent = null;
    try {
        if (TransactionUtil.getStatus() != TransactionUtil.STATUS_NO_TRANSACTION) {
            parent = TransactionUtil.suspend();
        }
        // lookup the jobs - looping 1000 at a time to avoid problems with cursors
        // also, using unique transaction to delete as many as possible even with errors
        boolean noMoreResults = false;
        boolean beganTx1 = false;
        while (!noMoreResults) {
            // current list of records
            List<GenericValue> curList = null;
            try {
                // begin this transaction
                beganTx1 = TransactionUtil.begin();
                EntityQuery eq = EntityQuery.use(delegator).select("jobId").from("JobSandbox").where(EntityCondition.makeCondition(UtilMisc.toList(doneCond, pool))).cursorScrollInsensitive().maxRows(1000);
                try (EntityListIterator foundJobs = eq.queryIterator()) {
                    curList = foundJobs.getPartialList(1, 1000);
                }
            } catch (GenericEntityException e) {
                Debug.logError(e, "Cannot obtain job data from datasource", module);
                try {
                    TransactionUtil.rollback(beganTx1, e.getMessage(), e);
                } catch (GenericTransactionException e1) {
                    Debug.logWarning(e1, module);
                }
                return ServiceUtil.returnError(e.getMessage());
            } finally {
                try {
                    TransactionUtil.commit(beganTx1);
                } catch (GenericTransactionException e) {
                    Debug.logWarning(e, module);
                }
            }
            // remove each from the list in its own transaction
            if (UtilValidate.isNotEmpty(curList)) {
                for (GenericValue job : curList) {
                    String jobId = job.getString("jobId");
                    boolean beganTx2 = false;
                    try {
                        beganTx2 = TransactionUtil.begin();
                        job.remove();
                    } catch (GenericEntityException e) {
                        Debug.logInfo("Cannot remove job data for ID: " + jobId, module);
                        try {
                            TransactionUtil.rollback(beganTx2, e.getMessage(), e);
                        } catch (GenericTransactionException e1) {
                            Debug.logWarning(e1, module);
                        }
                    } finally {
                        try {
                            TransactionUtil.commit(beganTx2);
                        } catch (GenericTransactionException e) {
                            Debug.logWarning(e, module);
                        }
                    }
                }
            } else {
                noMoreResults = true;
            }
        }
        // Now JobSandbox data is cleaned up. Now process Runtime data and remove the whole data in single shot that is of no need.
        boolean beganTx3 = false;
        GenericValue runtimeData = null;
        List<GenericValue> runtimeDataToDelete = new LinkedList<>();
        long jobsandBoxCount = 0;
        try {
            // begin this transaction
            beganTx3 = TransactionUtil.begin();
            EntityQuery eq = EntityQuery.use(delegator).select("runtimeDataId").from("RuntimeData");
            try (EntityListIterator runTimeDataIt = eq.queryIterator()) {
                while ((runtimeData = runTimeDataIt.next()) != null) {
                    EntityCondition whereCondition = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("runtimeDataId", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("runtimeDataId", EntityOperator.EQUALS, runtimeData.getString("runtimeDataId"))), EntityOperator.AND);
                    jobsandBoxCount = EntityQuery.use(delegator).from("JobSandbox").where(whereCondition).queryCount();
                    if (BigDecimal.ZERO.compareTo(BigDecimal.valueOf(jobsandBoxCount)) == 0) {
                        runtimeDataToDelete.add(runtimeData);
                    }
                }
            }
            // Now we are ready to delete runtimeData, we can safely delete complete list that we have recently fetched i.e runtimeDataToDelete.
            delegator.removeAll(runtimeDataToDelete);
        } catch (GenericEntityException e) {
            Debug.logError(e, "Cannot obtain runtime data from datasource", module);
            try {
                TransactionUtil.rollback(beganTx3, e.getMessage(), e);
            } catch (GenericTransactionException e1) {
                Debug.logWarning(e1, module);
            }
            return ServiceUtil.returnError(e.getMessage());
        } finally {
            try {
                TransactionUtil.commit(beganTx3);
            } catch (GenericTransactionException e) {
                Debug.logWarning(e, module);
            }
        }
    } catch (GenericTransactionException e) {
        Debug.logError(e, "Unable to suspend transaction; cannot purge jobs!", module);
        return ServiceUtil.returnError(e.getMessage());
    } finally {
        if (parent != null) {
            try {
                TransactionUtil.resume(parent);
            } catch (GenericTransactionException e) {
                Debug.logWarning(e, module);
            }
        }
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) Calendar(com.ibm.icu.util.Calendar) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) Timestamp(java.sql.Timestamp) LinkedList(java.util.LinkedList) GenericConfigException(org.apache.ofbiz.base.config.GenericConfigException) Delegator(org.apache.ofbiz.entity.Delegator) Transaction(javax.transaction.Transaction) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 7 with Calendar

use of com.ibm.icu.util.Calendar in project ofbiz-framework by apache.

the class ExpressionUiHelper method getDayValueList.

/**
 * Returns a List of Maps containing day of the week values.
 * @param locale
 * @return List of Maps. Each Map has a
 * <code>description</code> entry and a <code>value</code> entry.
 */
public static List<Map<String, Object>> getDayValueList(Locale locale) {
    Calendar tempCal = Calendar.getInstance(locale);
    tempCal.set(Calendar.DAY_OF_WEEK, tempCal.getFirstDayOfWeek());
    SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE", locale);
    List<Map<String, Object>> result = new ArrayList<>(7);
    for (int i = 0; i < 7; i++) {
        result.add(UtilMisc.toMap("description", (Object) dateFormat.format(tempCal.getTime()), "value", tempCal.get(Calendar.DAY_OF_WEEK)));
        tempCal.roll(Calendar.DAY_OF_WEEK, 1);
    }
    return result;
}
Also used : Calendar(com.ibm.icu.util.Calendar) ArrayList(java.util.ArrayList) SimpleDateFormat(java.text.SimpleDateFormat) Map(java.util.Map)

Example 8 with Calendar

use of com.ibm.icu.util.Calendar in project ofbiz-framework by apache.

the class ExpressionUiHelper method getMonthValueList.

/**
 * Returns a List of Maps containing month values.
 * @param locale
 * @return List of Maps. Each Map has a
 * <code>description</code> entry and a <code>value</code> entry.
 */
public static List<Map<String, Object>> getMonthValueList(Locale locale) {
    Calendar tempCal = Calendar.getInstance(locale);
    tempCal.set(Calendar.MONTH, Calendar.JANUARY);
    SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM", locale);
    List<Map<String, Object>> result = new ArrayList<>(13);
    for (int i = Calendar.JANUARY; i <= tempCal.getActualMaximum(Calendar.MONTH); i++) {
        result.add(UtilMisc.toMap("description", (Object) dateFormat.format(tempCal.getTime()), "value", i));
        tempCal.roll(Calendar.MONTH, 1);
    }
    return result;
}
Also used : Calendar(com.ibm.icu.util.Calendar) ArrayList(java.util.ArrayList) SimpleDateFormat(java.text.SimpleDateFormat) Map(java.util.Map)

Example 9 with Calendar

use of com.ibm.icu.util.Calendar in project ofbiz-framework by apache.

the class RecurrenceRule method getNextFreq.

// Gets the next frequency/interval recurrence from specified time
private Date getNextFreq(long startTime, long fromTime) {
    // Build a Calendar object
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date(startTime));
    long nextStartTime = startTime;
    while (nextStartTime < fromTime) {
        switch(getFrequency()) {
            case SECONDLY:
                cal.add(Calendar.SECOND, getIntervalInt());
                break;
            case MINUTELY:
                cal.add(Calendar.MINUTE, getIntervalInt());
                break;
            case HOURLY:
                cal.add(Calendar.HOUR_OF_DAY, getIntervalInt());
                break;
            case DAILY:
                cal.add(Calendar.DAY_OF_MONTH, getIntervalInt());
                break;
            case WEEKLY:
                cal.add(Calendar.WEEK_OF_YEAR, getIntervalInt());
                break;
            case MONTHLY:
                cal.add(Calendar.MONTH, getIntervalInt());
                break;
            case YEARLY:
                cal.add(Calendar.YEAR, getIntervalInt());
                break;
            default:
                // should never happen
                return null;
        }
        nextStartTime = cal.getTime().getTime();
    }
    return new Date(nextStartTime);
}
Also used : Calendar(com.ibm.icu.util.Calendar) Date(java.util.Date)

Example 10 with Calendar

use of com.ibm.icu.util.Calendar in project ofbiz-framework by apache.

the class RecurrenceRule method validCurrent.

/**
 * Gets the current recurrence (current for the checkTime) of this rule and returns it if it is valid.
 * If the current recurrence is not valid, doesn't try to find a valid one, instead returns 0.
 *@param startTime The time this recurrence first began.
 *@param checkTime The time to base the current recurrence on.
 *@param currentCount The total number of times the recurrence has run.
 *@return long The current recurrence as long if valid. If next recurrence is not valid, returns 0.
 */
public long validCurrent(long startTime, long checkTime, long currentCount) {
    if (startTime == 0) {
        startTime = RecurrenceUtil.now();
    }
    if (checkTime == 0) {
        checkTime = startTime;
    }
    // Test the end time of the recurrence.
    if (getEndTime() != 0 && getEndTime() <= RecurrenceUtil.now()) {
        return 0;
    }
    // Test the recurrence limit.
    if (getCount() != -1 && currentCount >= getCount()) {
        return 0;
    }
    // Get the next frequency from checkTime
    Date nextRun = getNextFreq(startTime, checkTime);
    Calendar cal = Calendar.getInstance();
    Calendar checkTimeCal = Calendar.getInstance();
    cal.setTime(nextRun);
    checkTimeCal.setTime(new Date(checkTime));
    // Get previous frequency and update its values from checkTime
    switch(getFrequency()) {
        case YEARLY:
            cal.add(Calendar.YEAR, -getIntervalInt());
            if (cal.get(Calendar.YEAR) != checkTimeCal.get(Calendar.YEAR)) {
                return 0;
            }
        case MONTHLY:
            if (MONTHLY == getFrequency()) {
                cal.add(Calendar.MONTH, -getIntervalInt());
                if (cal.get(Calendar.MONTH) != checkTimeCal.get(Calendar.MONTH)) {
                    return 0;
                }
            } else {
                cal.set(Calendar.MONTH, checkTimeCal.get(Calendar.MONTH));
            }
        case WEEKLY:
            if (WEEKLY == getFrequency()) {
                cal.add(Calendar.WEEK_OF_YEAR, -getIntervalInt());
                if (cal.get(Calendar.WEEK_OF_YEAR) != checkTimeCal.get(Calendar.WEEK_OF_YEAR)) {
                    return 0;
                }
            } else {
                cal.set(Calendar.WEEK_OF_YEAR, checkTimeCal.get(Calendar.WEEK_OF_YEAR));
            }
        case DAILY:
            if (DAILY == getFrequency()) {
                cal.add(Calendar.DAY_OF_MONTH, -getIntervalInt());
                if (cal.get(Calendar.DAY_OF_MONTH) != checkTimeCal.get(Calendar.DAY_OF_MONTH)) {
                    return 0;
                }
            } else {
                cal.set(Calendar.DAY_OF_MONTH, checkTimeCal.get(Calendar.DAY_OF_MONTH));
            }
        case HOURLY:
            if (HOURLY == getFrequency()) {
                cal.add(Calendar.HOUR_OF_DAY, -getIntervalInt());
                if (cal.get(Calendar.HOUR_OF_DAY) != checkTimeCal.get(Calendar.HOUR_OF_DAY)) {
                    return 0;
                }
            } else {
                cal.set(Calendar.HOUR_OF_DAY, checkTimeCal.get(Calendar.HOUR_OF_DAY));
            }
        case MINUTELY:
            if (MINUTELY == getFrequency()) {
                cal.add(Calendar.MINUTE, -getIntervalInt());
                if (cal.get(Calendar.MINUTE) != checkTimeCal.get(Calendar.MINUTE)) {
                    return 0;
                }
            } else {
                cal.set(Calendar.MINUTE, checkTimeCal.get(Calendar.MINUTE));
            }
        case SECONDLY:
            if (SECONDLY == getFrequency()) {
                cal.add(Calendar.SECOND, -getIntervalInt());
                if (cal.get(Calendar.SECOND) != checkTimeCal.get(Calendar.SECOND)) {
                    return 0;
                }
            } else {
                cal.set(Calendar.SECOND, checkTimeCal.get(Calendar.SECOND));
            }
    }
    // Check for validity of the current frequency.
    if (validByRule(cal.getTime())) {
        return cal.getTime().getTime();
    }
    return 0;
}
Also used : Calendar(com.ibm.icu.util.Calendar) Date(java.util.Date)

Aggregations

Calendar (com.ibm.icu.util.Calendar)75 Timestamp (java.sql.Timestamp)37 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)24 GenericValue (org.apache.ofbiz.entity.GenericValue)24 Delegator (org.apache.ofbiz.entity.Delegator)17 Date (java.util.Date)14 HashMap (java.util.HashMap)12 Locale (java.util.Locale)12 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)11 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)11 GregorianCalendar (com.ibm.icu.util.GregorianCalendar)10 ArrayList (java.util.ArrayList)8 SimpleDateFormat (java.text.SimpleDateFormat)6 LinkedList (java.util.LinkedList)6 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)6 Map (java.util.Map)5 TimeDuration (org.apache.ofbiz.base.util.TimeDuration)5 BigDecimal (java.math.BigDecimal)4 Time (java.sql.Time)4 UtilDateTime (org.apache.ofbiz.base.util.UtilDateTime)4