Search in sources :

Example 41 with EntityCondition

use of org.apache.ofbiz.entity.condition.EntityCondition in project ofbiz-framework by apache.

the class EntityTestSuite method testRemoveByCondition.

/*
     * Tests the .removeByCondition method for removing entities directly
     */
public void testRemoveByCondition() throws Exception {
    flushAndRecreateTree("remove-by-condition-a");
    // 
    // remove all the level1 nodes by using a condition on the description field
    // 
    EntityCondition isLevel1 = EntityCondition.makeCondition("description", EntityOperator.LIKE, "remove-by-condition-a:1:%");
    int n = delegator.removeByCondition("TestingNode", isLevel1);
    assertTrue("testRemoveByCondition nodes > 0", n > 0);
}
Also used : EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition)

Example 42 with EntityCondition

use of org.apache.ofbiz.entity.condition.EntityCondition in project ofbiz-framework by apache.

the class EntityTestSuite method testForeignKeyRemove.

/*
     * Tests foreign key integrity by trying to remove an entity which has foreign-key dependencies.  Should cause an exception.
     */
public void testForeignKeyRemove() throws Exception {
    try {
        String helperName = delegator.getEntityHelper("TestingNode").getHelperName();
        Datasource datasourceInfo = EntityConfig.getDatasource(helperName);
        if (!datasourceInfo.getUseForeignKeys()) {
            Debug.logInfo("Datasource " + datasourceInfo.getName() + " use-foreign-keys set to false, skipping testForeignKeyRemove", module);
            return;
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    delegator.removeByCondition("TestingNode", EntityCondition.makeCondition("description", EntityOperator.LIKE, "foreign-key-remove #%"));
    delegator.create("TestingNode", "testingNodeId", "TEST-FK-REMOVE-0", "description", "foreign-key-remove #0");
    delegator.create("TestingNode", "testingNodeId", "TEST-FK-REMOVE-1", "primaryParentNodeId", "TEST-FK-REMOVE-0", "description", "foreign-key-remove #1");
    delegator.create("TestingNode", "testingNodeId", "TEST-FK-REMOVE-2", "primaryParentNodeId", "TEST-FK-REMOVE-1", "description", "foreign-key-remove #2");
    delegator.create("TestingNode", "testingNodeId", "TEST-FK-REMOVE-3", "primaryParentNodeId", "TEST-FK-REMOVE-2", "description", "foreign-key-remove #3");
    GenericEntityException caught = null;
    try {
        EntityCondition isLevel1 = EntityCondition.makeCondition("description", EntityOperator.EQUALS, "foreign-key-remove #1");
        delegator.removeByCondition("TestingNode", isLevel1);
    } catch (GenericEntityException e) {
        caught = e;
    }
    assertNotNull("Foreign key referential integrity is not observed for remove (DELETE)", caught);
    Debug.logInfo(caught.toString(), module);
}
Also used : Datasource(org.apache.ofbiz.entity.config.model.Datasource) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition)

Example 43 with EntityCondition

use of org.apache.ofbiz.entity.condition.EntityCondition in project ofbiz-framework by apache.

the class ListFinder method runFind.

@Override
public void runFind(Map<String, Object> context, Delegator delegator) throws GeneralException {
    String entityName = this.entityNameExdr.expandString(context);
    String useCacheStr = this.useCacheStrExdr.expandString(context);
    String filterByDateStr = this.filterByDateStrExdr.expandString(context);
    String distinctStr = this.distinctStrExdr.expandString(context);
    String delegatorName = this.delegatorNameExdr.expandString(context);
    ModelEntity modelEntity = delegator.getModelEntity(entityName);
    String resultSetTypeString = this.resultSetTypeExdr.expandString(context);
    if (modelEntity == null) {
        throw new IllegalArgumentException("In find entity by " + label + " could not find definition for entity with name [" + entityName + "].");
    }
    boolean useCache = "true".equals(useCacheStr);
    boolean filterByDate = "true".equals(filterByDateStr);
    boolean distinct = "true".equals(distinctStr);
    int resultSetType = ResultSet.TYPE_SCROLL_INSENSITIVE;
    if ("forward".equals(resultSetTypeString)) {
        resultSetType = ResultSet.TYPE_FORWARD_ONLY;
    }
    if (UtilValidate.isNotEmpty(delegatorName)) {
        delegator = DelegatorFactory.getDelegator(delegatorName);
    }
    EntityCondition whereEntityCondition = getWhereEntityCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity));
    EntityCondition havingEntityCondition = getHavingEntityCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity));
    if (useCache) {
        // if useCache == true && outputHandler instanceof UseIterator, throw exception; not a valid combination
        if (outputHandler instanceof UseIterator) {
            Debug.logWarning("In find entity by " + label + " cannot have use-cache set to true " + label + " select use-iterator for the output type. Using cache and ignoring use-iterator setting.", module);
            outputHandler = new GetAll();
        }
        if (distinct) {
            throw new IllegalArgumentException("In find entity by " + label + " cannot have use-cache set to true " + label + " set distinct to true.");
        }
        if (havingEntityCondition != null) {
            throw new IllegalArgumentException("In find entity by " + label + " cannot have use-cache set to true and specify a having-condition-list (can only use a where condition with condition-expr or condition-list).");
        }
    }
    // get the list of fieldsToSelect from selectFieldExpanderList
    Set<String> fieldsToSelect = EntityFinderUtil.makeFieldsToSelect(selectFieldExpanderList, context);
    // if fieldsToSelect != null and useCacheBool is true, throw an error
    if (fieldsToSelect != null && useCache) {
        throw new IllegalArgumentException("Error in entity query by " + label + " definition, cannot specify select-field elements when use-cache is set to true");
    }
    // get the list of orderByFields from orderByExpanderList
    List<String> orderByFields = EntityFinderUtil.makeOrderByFieldList(this.orderByExpanderList, context);
    try {
        // if filterByDate, do a date filter on the results based on the now-timestamp
        if (filterByDate && !useCache) {
            EntityCondition filterByDateCondition = EntityUtil.getFilterByDateExpr();
            if (whereEntityCondition != null) {
                whereEntityCondition = EntityCondition.makeCondition(UtilMisc.toList(whereEntityCondition, filterByDateCondition));
            } else {
                whereEntityCondition = filterByDateCondition;
            }
        }
        if (useCache) {
            List<GenericValue> results = delegator.findList(entityName, whereEntityCondition, fieldsToSelect, orderByFields, null, true);
            if (filterByDate) {
                results = EntityUtil.filterByDate(results);
            }
            this.outputHandler.handleOutput(results, context, listAcsr);
        } else {
            boolean useTransaction = true;
            if (this.outputHandler instanceof UseIterator && !TransactionUtil.isTransactionInPlace()) {
                Exception newE = new Exception("Stack Trace");
                Debug.logError(newE, "ERROR: Cannot do a by " + label + " find that returns an EntityListIterator with no transaction in place. Wrap this call in a transaction.", module);
                useTransaction = false;
            }
            EntityFindOptions options = new EntityFindOptions();
            options.setDistinct(distinct);
            options.setResultSetType(resultSetType);
            if (outputHandler instanceof LimitRange) {
                LimitRange limitRange = (LimitRange) outputHandler;
                int start = limitRange.getStart(context);
                int size = limitRange.getSize(context);
                options.setMaxRows(start + size);
            } else if (outputHandler instanceof LimitView) {
                LimitView limitView = (LimitView) outputHandler;
                int index = limitView.getIndex(context);
                int size = limitView.getSize(context);
                options.setMaxRows(size * (index + 1));
            }
            boolean beganTransaction = false;
            try {
                if (useTransaction) {
                    beganTransaction = TransactionUtil.begin();
                }
                EntityListIterator eli = delegator.find(entityName, whereEntityCondition, havingEntityCondition, fieldsToSelect, orderByFields, options);
                this.outputHandler.handleOutput(eli, context, listAcsr);
            // NOTE: the eli EntityListIterator is not closed here. It SHOULD be closed later after the returned list will be used (eg see EntityAnd.getChildren() in ModelTree.java)
            } catch (GenericEntityException e) {
                String errMsg = "Failure in by " + label + " find operation, rolling back transaction";
                Debug.logError(e, errMsg, module);
                try {
                    // only rollback the transaction if we started one...
                    TransactionUtil.rollback(beganTransaction, errMsg, e);
                } catch (GenericEntityException e2) {
                    Debug.logError(e2, "Could not rollback transaction: " + e2.toString(), module);
                }
                // after rolling back, rethrow the exception
                throw e;
            } finally {
                // only commit the transaction if we started one... this will throw an exception if it fails
                TransactionUtil.commit(beganTransaction);
            }
        }
    } catch (GenericEntityException e) {
        String errMsg = "Error doing find by " + label + ": " + e.toString();
        Debug.logError(e, module);
        throw new GeneralException(errMsg, e);
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) GetAll(org.apache.ofbiz.entity.finder.EntityFinderUtil.GetAll) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) LimitView(org.apache.ofbiz.entity.finder.EntityFinderUtil.LimitView) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GeneralException(org.apache.ofbiz.base.util.GeneralException) LimitRange(org.apache.ofbiz.entity.finder.EntityFinderUtil.LimitRange) UseIterator(org.apache.ofbiz.entity.finder.EntityFinderUtil.UseIterator) EntityFindOptions(org.apache.ofbiz.entity.util.EntityFindOptions) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator)

Example 44 with EntityCondition

use of org.apache.ofbiz.entity.condition.EntityCondition in project ofbiz-framework by apache.

the class JobManager method reloadCrashedJobs.

public synchronized void reloadCrashedJobs() {
    assertIsRunning();
    if (crashedJobsReloaded) {
        return;
    }
    List<GenericValue> crashed = null;
    List<EntityExpr> statusExprList = UtilMisc.toList(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "SERVICE_PENDING"), EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "SERVICE_QUEUED"), EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "SERVICE_RUNNING"));
    EntityCondition statusCondition = EntityCondition.makeCondition(statusExprList, EntityOperator.OR);
    EntityCondition mainCondition = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("runByInstanceId", instanceId), statusCondition));
    try {
        crashed = EntityQuery.use(delegator).from("JobSandbox").where(mainCondition).orderBy("startDateTime").queryList();
    } catch (GenericEntityException e) {
        Debug.logWarning(e, "Unable to load crashed jobs", module);
    }
    if (UtilValidate.isNotEmpty(crashed)) {
        int rescheduled = 0;
        Timestamp now = UtilDateTime.nowTimestamp();
        for (GenericValue job : crashed) {
            try {
                if (Debug.infoOn()) {
                    Debug.logInfo("Scheduling Job : " + job, module);
                }
                String pJobId = job.getString("parentJobId");
                if (pJobId == null) {
                    pJobId = job.getString("jobId");
                }
                GenericValue newJob = GenericValue.create(job);
                newJob.set("statusId", "SERVICE_PENDING");
                newJob.set("runTime", now);
                newJob.set("previousJobId", job.getString("jobId"));
                newJob.set("parentJobId", pJobId);
                newJob.set("startDateTime", null);
                newJob.set("runByInstanceId", null);
                // don't set a recurrent schedule on the new job, run it just one time
                newJob.set("tempExprId", null);
                newJob.set("recurrenceInfoId", null);
                delegator.createSetNextSeqId(newJob);
                // set the cancel time on the old job to the same as the re-schedule time
                job.set("statusId", "SERVICE_CRASHED");
                job.set("cancelDateTime", now);
                delegator.store(job);
                rescheduled++;
            } catch (GenericEntityException e) {
                Debug.logWarning(e, module);
            }
        }
        if (Debug.infoOn()) {
            Debug.logInfo("-- " + rescheduled + " jobs re-scheduled", module);
        }
    } else {
        if (Debug.infoOn()) {
            Debug.logInfo("No crashed jobs to re-schedule", module);
        }
    }
    crashedJobsReloaded = true;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) Timestamp(java.sql.Timestamp) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 45 with EntityCondition

use of org.apache.ofbiz.entity.condition.EntityCondition in project ofbiz-framework by apache.

the class ProductionRunServices method getProductionRunTotResQty.

/**
 * Given a productId and an optional date, returns the total qty
 * of productId reserved by production runs.
 * @param ctx 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> getProductionRunTotResQty(DispatchContext ctx, Map<String, ? extends Object> context) {
    Map<String, Object> result = ServiceUtil.returnSuccess();
    Delegator delegator = ctx.getDelegator();
    Locale locale = (Locale) context.get("locale");
    String productId = (String) context.get("productId");
    Timestamp startDate = (Timestamp) context.get("startDate");
    if (startDate == null) {
        startDate = UtilDateTime.nowTimestamp();
    }
    BigDecimal totQty = BigDecimal.ZERO;
    try {
        List<EntityCondition> findOutgoingProductionRunsConds = new LinkedList<EntityCondition>();
        findOutgoingProductionRunsConds.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId));
        findOutgoingProductionRunsConds.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "WEGS_CREATED"));
        findOutgoingProductionRunsConds.add(EntityCondition.makeCondition("estimatedStartDate", EntityOperator.LESS_THAN_EQUAL_TO, startDate));
        List<EntityCondition> findOutgoingProductionRunsStatusConds = new LinkedList<EntityCondition>();
        findOutgoingProductionRunsStatusConds.add(EntityCondition.makeCondition("currentStatusId", EntityOperator.EQUALS, "PRUN_CREATED"));
        findOutgoingProductionRunsStatusConds.add(EntityCondition.makeCondition("currentStatusId", EntityOperator.EQUALS, "PRUN_SCHEDULED"));
        findOutgoingProductionRunsStatusConds.add(EntityCondition.makeCondition("currentStatusId", EntityOperator.EQUALS, "PRUN_DOC_PRINTED"));
        findOutgoingProductionRunsStatusConds.add(EntityCondition.makeCondition("currentStatusId", EntityOperator.EQUALS, "PRUN_RUNNING"));
        findOutgoingProductionRunsConds.add(EntityCondition.makeCondition(findOutgoingProductionRunsStatusConds, EntityOperator.OR));
        List<GenericValue> outgoingProductionRuns = EntityQuery.use(delegator).from("WorkEffortAndGoods").where(findOutgoingProductionRunsConds).orderBy("-estimatedStartDate").queryList();
        if (outgoingProductionRuns != null) {
            for (int i = 0; i < outgoingProductionRuns.size(); i++) {
                GenericValue outgoingProductionRun = outgoingProductionRuns.get(i);
                BigDecimal qty = outgoingProductionRun.getBigDecimal("estimatedQuantity");
                qty = qty != null ? qty : BigDecimal.ZERO;
                totQty = totQty.add(qty);
            }
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problem calling the getProductionRunTotResQty service", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingProductionResQtyCalc", locale));
    }
    result.put("reservedQuantity", totQty);
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) Timestamp(java.sql.Timestamp) BigDecimal(java.math.BigDecimal) LinkedList(java.util.LinkedList) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Aggregations

EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)118 GenericValue (org.apache.ofbiz.entity.GenericValue)96 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)78 Delegator (org.apache.ofbiz.entity.Delegator)60 LinkedList (java.util.LinkedList)58 Locale (java.util.Locale)43 Timestamp (java.sql.Timestamp)40 HashMap (java.util.HashMap)32 EntityListIterator (org.apache.ofbiz.entity.util.EntityListIterator)29 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)26 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)24 Map (java.util.Map)22 BigDecimal (java.math.BigDecimal)21 EntityExpr (org.apache.ofbiz.entity.condition.EntityExpr)18 EntityQuery (org.apache.ofbiz.entity.util.EntityQuery)14 GeneralException (org.apache.ofbiz.base.util.GeneralException)12 ArrayList (java.util.ArrayList)11 DynamicViewEntity (org.apache.ofbiz.entity.model.DynamicViewEntity)9 ModelKeyMap (org.apache.ofbiz.entity.model.ModelKeyMap)8 HashSet (java.util.HashSet)7