Search in sources :

Example 1 with GenericPK

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

the class ProductUtilServices method duplicateRelated.

protected static void duplicateRelated(GenericValue product, String title, String relatedEntityName, String productIdField, String variantProductId, Timestamp nowTimestamp, boolean removeOld, Delegator delegator, boolean test) throws GenericEntityException {
    List<GenericValue> relatedList = EntityUtil.filterByDate(product.getRelated(title + relatedEntityName, null, null, false), nowTimestamp);
    for (GenericValue relatedValue : relatedList) {
        GenericValue newRelatedValue = (GenericValue) relatedValue.clone();
        newRelatedValue.set(productIdField, variantProductId);
        // create a new one? see if one already exists with different from/thru dates
        ModelEntity modelEntity = relatedValue.getModelEntity();
        if (modelEntity.isField("fromDate")) {
            GenericPK findValue = newRelatedValue.getPrimaryKey();
            // can't just set to null, need to remove the value so it isn't a constraint in the query
            findValue.remove("fromDate");
            List<GenericValue> existingValueList = EntityQuery.use(delegator).from(relatedEntityName).where(findValue).filterByDate(nowTimestamp).queryList();
            if (existingValueList.size() > 0) {
                if (test) {
                    Debug.logInfo("Found " + existingValueList.size() + " existing values for related entity name: " + relatedEntityName + ", not copying, findValue is: " + findValue, module);
                }
                continue;
            }
            newRelatedValue.set("fromDate", nowTimestamp);
        }
        if (EntityQuery.use(delegator).from(relatedEntityName).where(EntityCondition.makeCondition(newRelatedValue.getPrimaryKey(), EntityOperator.AND)).queryCount() == 0) {
            if (test) {
                Debug.logInfo("Test mode, would create: " + newRelatedValue, module);
            } else {
                newRelatedValue.create();
            }
        }
    }
    if (removeOld) {
        if (test) {
            Debug.logInfo("Test mode, would remove related " + title + relatedEntityName + " with dummy key: " + product.getRelatedDummyPK(title + relatedEntityName), module);
        } else {
            product.removeRelated(title + relatedEntityName);
        }
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GenericPK(org.apache.ofbiz.entity.GenericPK) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity)

Example 2 with GenericPK

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

the class PrimaryKeyFinder method runFind.

public static GenericValue runFind(ModelEntity modelEntity, Map<String, Object> context, Delegator delegator, boolean useCache, boolean autoFieldMap, Map<FlexibleMapAccessor<Object>, Object> fieldMap, List<FlexibleStringExpander> selectFieldExpanderList) throws GeneralException {
    // assemble the field map
    Map<String, Object> entityContext = new HashMap<>();
    if (autoFieldMap) {
        // try a map called "parameters", try it first so values from here are overridden by values in the main context
        Object parametersObj = context.get("parameters");
        Boolean parametersObjExists = parametersObj != null && parametersObj instanceof Map<?, ?>;
        // only need PK fields
        Iterator<ModelField> iter = modelEntity.getPksIterator();
        while (iter.hasNext()) {
            ModelField curField = iter.next();
            String fieldName = curField.getName();
            Object fieldValue = null;
            if (parametersObjExists) {
                fieldValue = ((Map<?, ?>) parametersObj).get(fieldName);
            }
            if (context.containsKey(fieldName)) {
                fieldValue = context.get(fieldName);
            }
            entityContext.put(fieldName, fieldValue);
        }
    }
    EntityFinderUtil.expandFieldMapToContext(fieldMap, context, entityContext);
    // then convert the types...
    // need the timeZone and locale for conversion, so add here and remove after
    entityContext.put("locale", context.get("locale"));
    entityContext.put("timeZone", context.get("timeZone"));
    modelEntity.convertFieldMapInPlace(entityContext, delegator);
    entityContext.remove("locale");
    entityContext.remove("timeZone");
    // 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-one definition, cannot specify select-field elements when use-cache is set to true");
    }
    try {
        GenericValue valueOut = null;
        GenericPK entityPK = delegator.makePK(modelEntity.getEntityName(), entityContext);
        // make sure we have a full primary key, if any field is null then just log a warning and return null instead of blowing up
        if (entityPK.containsPrimaryKey(true)) {
            if (useCache) {
                valueOut = EntityQuery.use(delegator).from(entityPK.getEntityName()).where(entityPK).cache(true).queryOne();
            } else {
                if (fieldsToSelect != null) {
                    valueOut = delegator.findByPrimaryKeyPartial(entityPK, fieldsToSelect);
                } else {
                    valueOut = EntityQuery.use(delegator).from(entityPK.getEntityName()).where(entityPK).cache(false).queryOne();
                }
            }
        } else {
            if (Debug.infoOn()) {
                Debug.logInfo("Returning null because found incomplete primary key in find: " + entityPK, module);
            }
        }
        return valueOut;
    } catch (GenericEntityException e) {
        String errMsg = "Error finding entity value by primary key with entity-one: " + e.toString();
        Debug.logError(e, errMsg, module);
        throw new GeneralException(errMsg, e);
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GenericPK(org.apache.ofbiz.entity.GenericPK) GeneralException(org.apache.ofbiz.base.util.GeneralException) HashMap(java.util.HashMap) ModelField(org.apache.ofbiz.entity.model.ModelField) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Example 3 with GenericPK

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

the class ContentManagementWorker method getCurrentValueWithCachedPK.

public static void getCurrentValueWithCachedPK(HttpServletRequest request, Delegator delegator, GenericPK cachedPK, String entityName) {
    Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
    // Build the primary key that may have been passed in as key values
    GenericValue v = delegator.makeValue(entityName);
    GenericPK passedPK = v.getPrimaryKey();
    Collection<String> keyColl = passedPK.getAllKeys();
    for (String attrName : keyColl) {
        String attrVal = (String) request.getAttribute(attrName);
        if (UtilValidate.isEmpty(attrVal)) {
            attrVal = (String) paramMap.get(attrName);
        }
        if (UtilValidate.isNotEmpty(attrVal)) {
            passedPK.put(attrName, attrVal);
        }
    }
    // If a full passed primary key exists, it takes precedence over a cached key
    // I cannot determine if the key testing utils of GenericEntity take into account
    // whether or not a field is populated.
    boolean useCached = false;
    boolean usePassed = true;
    if (cachedPK != null) {
        useCached = true;
        keyColl = cachedPK.getPrimaryKey().getAllKeys();
        for (String ky : keyColl) {
            String sCached = null;
            String sPassed = null;
            Object oPassed = null;
            Object oCached = null;
            oPassed = passedPK.get(ky);
            if (oPassed != null) {
                sPassed = oPassed.toString();
                if (UtilValidate.isEmpty(sPassed)) {
                    // If any part of passed key is not available, it can't be used
                    usePassed = false;
                } else {
                    oCached = cachedPK.get(ky);
                    if (oCached != null) {
                        sCached = oCached.toString();
                        if (UtilValidate.isEmpty(sCached)) {
                            useCached = false;
                        } else {
                        }
                    } else {
                        useCached = false;
                    }
                }
            } else {
                usePassed = false;
            }
        }
    }
    GenericPK currentPK = null;
    if (usePassed && useCached) {
        currentPK = passedPK;
    } else if (usePassed && !useCached) {
        currentPK = passedPK;
    } else if (!usePassed && useCached) {
        currentPK = cachedPK;
    }
    if (currentPK != null) {
        request.setAttribute("currentPK", currentPK);
        GenericValue currentValue = null;
        try {
            currentValue = EntityQuery.use(delegator).from(currentPK.getEntityName()).where(currentPK).queryOne();
        } catch (GenericEntityException e) {
            Debug.logError(e.getMessage(), module);
        }
        request.setAttribute("currentValue", currentValue);
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GenericPK(org.apache.ofbiz.entity.GenericPK) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Example 4 with GenericPK

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

the class EntityTestSuite method testRemoveByPK.

/*
     * Test the .removeByPrimaryKey by using findByCondition and then retrieving the GenericPk from a GenericValue
     */
public void testRemoveByPK() throws Exception {
    flushAndRecreateTree("remove-by-pk");
    // 
    // Find all the root nodes,
    // delete them their primary key
    // 
    EntityCondition isRoot = EntityCondition.makeCondition(EntityCondition.makeCondition("description", EntityOperator.LIKE, "remove-by-pk:%"), EntityOperator.AND, EntityCondition.makeCondition("primaryParentNodeId", EntityOperator.NOT_EQUAL, GenericEntity.NULL_FIELD));
    List<GenericValue> rootValues = EntityQuery.use(delegator).select("testingNodeId").from("TestingNode").where(isRoot).queryList();
    for (GenericValue value : rootValues) {
        GenericPK pk = value.getPrimaryKey();
        int del = delegator.removeByPrimaryKey(pk);
        assertEquals("Removing Root by primary key", 1, del);
    }
    // no more TestingNode should be in the data base anymore.
    List<GenericValue> testingNodes = EntityQuery.use(delegator).from("TestingNode").where(isRoot).queryList();
    assertEquals("No more TestingNode after removing the roots", 0, testingNodes.size());
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GenericPK(org.apache.ofbiz.entity.GenericPK) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition)

Example 5 with GenericPK

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

the class ProductionRunServices method productionRunDeclareAndProduce.

public static Map<String, Object> productionRunDeclareAndProduce(DispatchContext ctx, Map<String, ? extends Object> context) {
    Map<String, Object> result = new HashMap<String, Object>();
    Delegator delegator = ctx.getDelegator();
    LocalDispatcher dispatcher = ctx.getDispatcher();
    Locale locale = (Locale) context.get("locale");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    // Mandatory input fields
    String productionRunId = (String) context.get("workEffortId");
    // Optional input fields
    BigDecimal quantity = (BigDecimal) context.get("quantity");
    Map<GenericPK, Object> componentsLocationMap = UtilGenerics.checkMap(context.get("componentsLocationMap"));
    // The production run is loaded
    ProductionRun productionRun = new ProductionRun(productionRunId, delegator, dispatcher);
    BigDecimal quantityProduced = productionRun.getGenericValue().getBigDecimal("quantityProduced");
    BigDecimal quantityToProduce = productionRun.getGenericValue().getBigDecimal("quantityToProduce");
    if (quantityProduced == null) {
        quantityProduced = BigDecimal.ZERO;
    }
    if (quantityToProduce == null) {
        quantityToProduce = BigDecimal.ZERO;
    }
    BigDecimal minimumQuantityProducedByTask = quantityProduced.add(quantity);
    if (minimumQuantityProducedByTask.compareTo(quantityToProduce) > 0) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingQuantityProducedIsHigherThanQuantityDeclared", locale));
    }
    List<GenericValue> tasks = productionRun.getProductionRunRoutingTasks();
    for (int i = 0; i < tasks.size(); i++) {
        GenericValue oneTask = tasks.get(i);
        String taskId = oneTask.getString("workEffortId");
        if ("PRUN_RUNNING".equals(oneTask.getString("currentStatusId"))) {
            BigDecimal quantityDeclared = oneTask.getBigDecimal("quantityProduced");
            if (quantityDeclared == null) {
                quantityDeclared = BigDecimal.ZERO;
            }
            if (minimumQuantityProducedByTask.compareTo(quantityDeclared) > 0) {
                try {
                    Map<String, Object> serviceContext = UtilMisc.<String, Object>toMap("productionRunId", productionRunId, "productionRunTaskId", taskId);
                    serviceContext.put("addQuantityProduced", minimumQuantityProducedByTask.subtract(quantityDeclared));
                    serviceContext.put("issueRequiredComponents", Boolean.TRUE);
                    serviceContext.put("componentsLocationMap", componentsLocationMap);
                    serviceContext.put("userLogin", userLogin);
                    Map<String, Object> serviceResult = dispatcher.runSync("updateProductionRunTask", serviceContext);
                    if (ServiceUtil.isError(serviceResult)) {
                        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
                    }
                } catch (GenericServiceException e) {
                    Debug.logError(e, "Problem calling the changeProductionRunTaskStatus service", module);
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingProductionRunStatusNotChanged", locale));
                }
            }
        }
    }
    try {
        Map<String, Object> inputMap = new HashMap<String, Object>();
        inputMap.putAll(context);
        inputMap.remove("componentsLocationMap");
        result = dispatcher.runSync("productionRunProduce", inputMap);
        if (ServiceUtil.isError(result)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
        }
    } catch (GenericServiceException e) {
        Debug.logError(e, "Problem calling the changeProductionRunTaskStatus service", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingProductionRunStatusNotChanged", locale));
    }
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GenericPK(org.apache.ofbiz.entity.GenericPK) HashMap(java.util.HashMap) BigDecimal(java.math.BigDecimal) Delegator(org.apache.ofbiz.entity.Delegator) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Aggregations

GenericPK (org.apache.ofbiz.entity.GenericPK)24 GenericValue (org.apache.ofbiz.entity.GenericValue)17 HashMap (java.util.HashMap)11 BigDecimal (java.math.BigDecimal)9 Delegator (org.apache.ofbiz.entity.Delegator)8 Map (java.util.Map)7 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)7 Locale (java.util.Locale)5 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)4 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)4 ModelEntity (org.apache.ofbiz.entity.model.ModelEntity)3 Timestamp (java.sql.Timestamp)2 LinkedList (java.util.LinkedList)2 List (java.util.List)2 HttpSession (javax.servlet.http.HttpSession)2 GeneralException (org.apache.ofbiz.base.util.GeneralException)2 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)2 EntityConditionList (org.apache.ofbiz.entity.condition.EntityConditionList)2 DateFormat (java.text.DateFormat)1 SimpleDateFormat (java.text.SimpleDateFormat)1