Search in sources :

Example 61 with Calendar

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

the class EntitySyncServices method cleanSyncRemoveInfo.

/**
 * Clean EntitySyncRemove Info
 *@param dctx The DispatchContext that this service is operating in
 *@param context Map containing the input parameters
 *@return Map with the result of the service, the output parameters
 */
public static Map<String, Object> cleanSyncRemoveInfo(DispatchContext dctx, Map<String, ? extends Object> context) {
    Debug.logInfo("Running cleanSyncRemoveInfo", module);
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");
    try {
        // find the largest keepRemoveInfoHours value on an EntitySyncRemove and kill everything before that, if none found default to 10 days (240 hours)
        double keepRemoveInfoHours = 24;
        List<GenericValue> entitySyncRemoveList = EntityQuery.use(delegator).from("EntitySync").queryList();
        for (GenericValue entitySyncRemove : entitySyncRemoveList) {
            Double curKrih = entitySyncRemove.getDouble("keepRemoveInfoHours");
            if (curKrih != null) {
                double curKrihVal = curKrih.doubleValue();
                if (curKrihVal > keepRemoveInfoHours) {
                    keepRemoveInfoHours = curKrihVal;
                }
            }
        }
        int keepSeconds = (int) Math.floor(keepRemoveInfoHours * 3600);
        Calendar nowCal = Calendar.getInstance();
        nowCal.setTimeInMillis(System.currentTimeMillis());
        nowCal.add(Calendar.SECOND, -keepSeconds);
        Timestamp keepAfterStamp = new Timestamp(nowCal.getTimeInMillis());
        int numRemoved = delegator.removeByCondition("EntitySyncRemove", EntityCondition.makeCondition(ModelEntity.STAMP_TX_FIELD, EntityOperator.LESS_THAN, keepAfterStamp));
        Debug.logInfo("In cleanSyncRemoveInfo removed [" + numRemoved + "] values with TX timestamp before [" + keepAfterStamp + "]", module);
        return ServiceUtil.returnSuccess();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Error cleaning out EntitySyncRemove info: " + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtErrorCleaningEntitySyncRemove", UtilMisc.toMap("errorString", e.toString()), locale));
    }
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) Calendar(com.ibm.icu.util.Calendar) Timestamp(java.sql.Timestamp)

Example 62 with Calendar

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

the class JobManager method poll.

/**
 * Scans the JobSandbox entity and returns a list of jobs that are due to run.
 * Returns an empty list if there are no jobs due to run.
 * This method is called by the {@link JobPoller} polling thread.
 */
protected List<Job> poll(int limit) {
    assertIsRunning();
    // The rest of this method logs exceptions and does not throw them.
    // The idea is to keep the JobPoller working even when a database
    // connection is not available (possible on a saturated server).
    DispatchContext dctx = getDispatcher().getDispatchContext();
    if (dctx == null) {
        Debug.logWarning("Unable to locate DispatchContext object; not running job!", module);
        return Collections.emptyList();
    }
    // basic query
    List<EntityExpr> expressions = UtilMisc.toList(EntityCondition.makeCondition("runTime", EntityOperator.LESS_THAN_EQUAL_TO, UtilDateTime.nowTimestamp()), EntityCondition.makeCondition("startDateTime", EntityOperator.EQUALS, null), EntityCondition.makeCondition("cancelDateTime", EntityOperator.EQUALS, null), EntityCondition.makeCondition("runByInstanceId", EntityOperator.EQUALS, null));
    // limit to just defined pools
    List<String> pools = null;
    try {
        pools = getRunPools();
    } catch (GenericConfigException e) {
        Debug.logWarning(e, "Unable to get run pools - not running job: ", module);
        return Collections.emptyList();
    }
    List<EntityExpr> poolsExpr = UtilMisc.toList(EntityCondition.makeCondition("poolId", EntityOperator.EQUALS, null));
    if (!pools.isEmpty()) {
        for (String poolName : pools) {
            poolsExpr.add(EntityCondition.makeCondition("poolId", EntityOperator.EQUALS, poolName));
        }
    }
    List<Job> poll = new ArrayList<>(limit);
    // make the conditions
    EntityCondition baseCondition = EntityCondition.makeCondition(expressions);
    EntityCondition poolCondition = EntityCondition.makeCondition(poolsExpr, EntityOperator.OR);
    EntityCondition mainCondition = EntityCondition.makeCondition(UtilMisc.toList(baseCondition, poolCondition));
    boolean beganTransaction = false;
    try {
        beganTransaction = TransactionUtil.begin();
        if (!beganTransaction) {
            Debug.logWarning("Unable to poll JobSandbox for jobs; unable to begin transaction.", module);
            return poll;
        }
        try (EntityListIterator jobsIterator = EntityQuery.use(delegator).from("JobSandbox").where(mainCondition).orderBy("runTime").queryIterator()) {
            GenericValue jobValue = jobsIterator.next();
            while (jobValue != null) {
                // Claim ownership of this value. Using storeByCondition to avoid a race condition.
                List<EntityExpr> updateExpression = UtilMisc.toList(EntityCondition.makeCondition("jobId", EntityOperator.EQUALS, jobValue.get("jobId")), EntityCondition.makeCondition("runByInstanceId", EntityOperator.EQUALS, null));
                int rowsUpdated = delegator.storeByCondition("JobSandbox", UtilMisc.toMap("runByInstanceId", instanceId), EntityCondition.makeCondition(updateExpression));
                if (rowsUpdated == 1) {
                    poll.add(new PersistedServiceJob(dctx, jobValue, null));
                    if (poll.size() == limit) {
                        break;
                    }
                }
                jobValue = jobsIterator.next();
            }
        } catch (GenericEntityException e) {
            Debug.logWarning(e, module);
        }
        TransactionUtil.commit(beganTransaction);
    } catch (Throwable t) {
        String errMsg = "Exception thrown while polling JobSandbox: ";
        try {
            TransactionUtil.rollback(beganTransaction, errMsg, t);
        } catch (GenericEntityException e) {
            Debug.logWarning(e, "Exception thrown while rolling back transaction: ", module);
        }
        Debug.logWarning(t, errMsg, module);
        return Collections.emptyList();
    }
    if (poll.isEmpty()) {
        // No jobs to run, see if there are any jobs to purge
        Calendar cal = Calendar.getInstance();
        try {
            int daysToKeep = ServiceConfigUtil.getServiceEngine().getThreadPool().getPurgeJobDays();
            cal.add(Calendar.DAY_OF_YEAR, -daysToKeep);
        } catch (GenericConfigException e) {
            Debug.logWarning(e, "Unable to get purge job days: ", module);
            return Collections.emptyList();
        }
        Timestamp purgeTime = new Timestamp(cal.getTimeInMillis());
        List<EntityExpr> finExp = UtilMisc.toList(EntityCondition.makeCondition("finishDateTime", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("finishDateTime", EntityOperator.LESS_THAN, purgeTime));
        List<EntityExpr> canExp = UtilMisc.toList(EntityCondition.makeCondition("cancelDateTime", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("cancelDateTime", EntityOperator.LESS_THAN, purgeTime));
        EntityCondition doneCond = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition(canExp), EntityCondition.makeCondition(finExp)), EntityOperator.OR);
        mainCondition = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("runByInstanceId", instanceId), doneCond));
        beganTransaction = false;
        try {
            beganTransaction = TransactionUtil.begin();
            if (!beganTransaction) {
                Debug.logWarning("Unable to poll JobSandbox for jobs; unable to begin transaction.", module);
                return Collections.emptyList();
            }
            try (EntityListIterator jobsIterator = EntityQuery.use(delegator).from("JobSandbox").where(mainCondition).orderBy("jobId").queryIterator()) {
                GenericValue jobValue = jobsIterator.next();
                while (jobValue != null) {
                    poll.add(new PurgeJob(jobValue));
                    if (poll.size() == limit) {
                        break;
                    }
                    jobValue = jobsIterator.next();
                }
            } catch (GenericEntityException e) {
                Debug.logWarning(e, module);
            }
            TransactionUtil.commit(beganTransaction);
        } catch (Throwable t) {
            String errMsg = "Exception thrown while polling JobSandbox: ";
            try {
                TransactionUtil.rollback(beganTransaction, errMsg, t);
            } catch (GenericEntityException e) {
                Debug.logWarning(e, "Exception thrown while rolling back transaction: ", module);
            }
            Debug.logWarning(t, errMsg, module);
            return Collections.emptyList();
        }
    }
    return poll;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) Calendar(com.ibm.icu.util.Calendar) ArrayList(java.util.ArrayList) Timestamp(java.sql.Timestamp) DispatchContext(org.apache.ofbiz.service.DispatchContext) GenericConfigException(org.apache.ofbiz.base.config.GenericConfigException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 63 with Calendar

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

the class PersistedServiceJob method failed.

@Override
protected void failed(Throwable t) throws InvalidJobException {
    super.failed(t);
    // if the job has not been re-scheduled; we need to re-schedule and run again
    if (nextRecurrence == -1) {
        if (this.canRetry()) {
            // create a recurrence
            Calendar cal = Calendar.getInstance();
            try {
                cal.add(Calendar.MINUTE, ServiceConfigUtil.getServiceEngine().getThreadPool().getFailedRetryMin());
            } catch (GenericConfigException e) {
                Debug.logWarning(e, "Unable to get retry minutes for job [" + getJobId() + "], defaulting to now: ", module);
            }
            long next = cal.getTimeInMillis();
            try {
                createRecurrence(next, true);
            } catch (GenericEntityException e) {
                Debug.logError(e, "Unable to re-schedule job [" + getJobId() + "]: ", module);
            }
            Debug.logInfo("Persisted Job [" + getJobId() + "] Failed. Re-Scheduling : " + next, module);
        } else {
            Debug.logWarning("Persisted Job [" + getJobId() + "] Failed. Max Retry Hit, not re-scheduling", module);
        }
    }
    // set the failed status
    jobValue.set("statusId", "SERVICE_FAILED");
    jobValue.set("finishDateTime", UtilDateTime.nowTimestamp());
    jobValue.set("jobResult", StringUtils.substring(t.getMessage(), 0, 255));
    try {
        jobValue.store();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Cannot update the JobSandbox entity", module);
    }
}
Also used : GenericConfigException(org.apache.ofbiz.base.config.GenericConfigException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) Calendar(com.ibm.icu.util.Calendar)

Example 64 with Calendar

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

the class ICalRecurConverter method visit.

@SuppressWarnings("unchecked")
@Override
public void visit(TemporalExpressions.MonthRange expr) {
    int startMonth = expr.getStartMonth();
    int endMonth = expr.getEndMonth();
    Calendar cal = Calendar.getInstance();
    int maxMonth = cal.getActualMaximum(Calendar.MONTH);
    NumberList monthList = new NumberList();
    monthList.add(startMonth + 1);
    while (startMonth != endMonth) {
        startMonth++;
        if (startMonth > maxMonth) {
            startMonth = Calendar.JANUARY;
        }
        monthList.add(startMonth + 1);
    }
    Recur recur = new Recur(Recur.MONTHLY, 0);
    recur.getMonthList().addAll(monthList);
    this.state.addRecur(recur);
}
Also used : Calendar(com.ibm.icu.util.Calendar) NumberList(net.fortuna.ical4j.model.NumberList) Recur(net.fortuna.ical4j.model.Recur)

Example 65 with Calendar

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

the class DateTimeTests method testDateTimeConverters.

public void testDateTimeConverters() throws Exception {
    Calendar cal = Calendar.getInstance();
    long currentTime = cal.getTimeInMillis();
    cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
    cal.set(Calendar.MILLISECOND, 0);
    // Start of day today
    long longTime = cal.getTimeInMillis();
    assertNotEquals("currentTime and longTime are not equal", currentTime, longTime);
    java.util.Date utilDate = new java.util.Date(longTime);
    java.sql.Date sqlDate = new java.sql.Date(longTime);
    java.sql.Timestamp timestamp = new java.sql.Timestamp(longTime);
    // Source class = java.util.Date
    assertConversion("DateToLong", new DateTimeConverters.DateToLong(), utilDate, longTime);
    assertConversion("DateToSqlDate", new DateTimeConverters.DateToSqlDate(), utilDate, new java.sql.Date(longTime));
    assertConversion("DateToString", new DateTimeConverters.DateToString(), utilDate, utilDate.toString());
    assertConversion("DateToTimestamp", new DateTimeConverters.DateToTimestamp(), utilDate, timestamp);
    // Source class = java.sql.Date
    assertConversion("SqlDateToLong", new DateTimeConverters.DateToLong(), sqlDate, longTime);
    assertConversion("SqlDateToDate", new DateTimeConverters.SqlDateToDate(), sqlDate, utilDate);
    assertConversion("SqlDateToString", new DateTimeConverters.SqlDateToString(), sqlDate, sqlDate.toString());
    assertConversion("SqlDateToTimestamp", new DateTimeConverters.SqlDateToTimestamp(), sqlDate, timestamp);
    // Source class = java.sql.Timestamp
    assertConversion("TimestampToLong", new DateTimeConverters.DateToLong(), timestamp, longTime);
    assertConversion("TimestampToDate", new DateTimeConverters.TimestampToDate(), timestamp, utilDate);
    assertConversion("TimestampToSqlDate", new DateTimeConverters.TimestampToSqlDate(), timestamp, sqlDate);
    assertConversion("TimestampToString", new DateTimeConverters.TimestampToString(), timestamp, timestamp.toString());
    // Source class = java.lang.Long
    assertConversion("LongToDate", new DateTimeConverters.NumberToDate(), longTime, utilDate);
    assertConversion("LongToSqlDate", new DateTimeConverters.NumberToSqlDate(), longTime, sqlDate);
    // Test conversion to start of day
    assertConversion("LongToSqlDate", new DateTimeConverters.NumberToSqlDate(), currentTime, sqlDate);
    assertConversion("LongToTimestamp", new DateTimeConverters.NumberToTimestamp(), longTime, timestamp);
    // Source class = java.lang.String
    assertConversion("StringToTimestamp", new DateTimeConverters.StringToTimestamp(), timestamp.toString(), timestamp);
}
Also used : Calendar(com.ibm.icu.util.Calendar) DateTimeConverters(org.apache.ofbiz.base.conversion.DateTimeConverters)

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