Search in sources :

Example 71 with ModelEntity

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

the class EntityDataServices method reencryptFields.

public static Map<String, Object> reencryptFields(DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    Security security = dctx.getSecurity();
    Locale locale = (Locale) context.get("locale");
    // check permission
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    if (!security.hasPermission("ENTITY_MAINT", userLogin)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtServicePermissionNotGranted", locale));
    }
    String groupName = (String) context.get("groupName");
    Map<String, ModelEntity> modelEntities;
    try {
        modelEntities = delegator.getModelEntityMapByGroup(groupName);
    } catch (GenericEntityException e) {
        Debug.logError(e, "Error getting list of entities in group: " + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtErrorGettingListOfEntityInGroup", UtilMisc.toMap("errorString", e.toString()), locale));
    }
    for (ModelEntity modelEntity : modelEntities.values()) {
        List<ModelField> fields = modelEntity.getFieldsUnmodifiable();
        for (ModelField field : fields) {
            if (field.getEncryptMethod().isEncrypted()) {
                try {
                    List<GenericValue> rows = EntityQuery.use(delegator).from(modelEntity.getEntityName()).select(field.getName()).queryList();
                    for (GenericValue row : rows) {
                        row.setString(field.getName(), row.getString(field.getName()));
                        row.store();
                    }
                } catch (GenericEntityException gee) {
                    return ServiceUtil.returnError(gee.getMessage());
                }
            }
        }
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) ModelField(org.apache.ofbiz.entity.model.ModelField) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) Security(org.apache.ofbiz.security.Security)

Example 72 with ModelEntity

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

the class EntitySyncContext method assembleValuesToStore.

public ArrayList<GenericValue> assembleValuesToStore() throws SyncDataErrorException {
    // simulate two ordered lists and merge them on-the-fly for faster combined sorting
    // make it an ArrayList to easily merge in sorted lists
    ArrayList<GenericValue> valuesToStore = new ArrayList<GenericValue>();
    if (this.nextUpdateTxTime != null && (this.nextUpdateTxTime.equals(currentRunEndTime) || this.nextUpdateTxTime.after(currentRunEndTime))) {
        // this means that for all entities in this pack we found on the last pass that there would be nothing for this one, so just return nothing...
        return valuesToStore;
    }
    // Debug.logInfo("Getting values to store; currentRunStartTime=" + currentRunStartTime + ", currentRunEndTime=" + currentRunEndTime, module);
    int entitiesSkippedForKnownNext = 0;
    // iterate through entities, get all records with tx stamp in the current time range, put all in a single list
    for (ModelEntity modelEntity : entityModelToUseList) {
        int insertBefore = 0;
        // first test to see if we know that there are no records for this entity in this time period...
        Timestamp knownNextUpdateTime = this.nextEntityUpdateTxTime.get(modelEntity.getEntityName());
        if (knownNextUpdateTime != null && (knownNextUpdateTime.equals(currentRunEndTime) || knownNextUpdateTime.after(currentRunEndTime))) {
            entitiesSkippedForKnownNext++;
            continue;
        }
        boolean beganTransaction = false;
        try {
            beganTransaction = TransactionUtil.begin(7200);
        } catch (GenericTransactionException e) {
            throw new SyncDataErrorException("Unable to begin JTA transaction", e);
        }
        try {
            // get all values that were updated, but NOT created in the current time range; if no info on created stamp, that's okay we'll include it here because it won't have been included in the valuesToCreate list
            EntityCondition createdBeforeStartCond = EntityCondition.makeCondition(EntityCondition.makeCondition(ModelEntity.CREATE_STAMP_TX_FIELD, EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition(ModelEntity.CREATE_STAMP_TX_FIELD, EntityOperator.LESS_THAN, currentRunStartTime));
            EntityCondition findValCondition = EntityCondition.makeCondition(EntityCondition.makeCondition(ModelEntity.STAMP_TX_FIELD, EntityOperator.GREATER_THAN_EQUAL_TO, currentRunStartTime), EntityCondition.makeCondition(ModelEntity.STAMP_TX_FIELD, EntityOperator.LESS_THAN, currentRunEndTime), createdBeforeStartCond);
            EntityListIterator eli = EntityQuery.use(delegator).from(modelEntity.getEntityName()).where(findValCondition).orderBy(ModelEntity.STAMP_TX_FIELD, ModelEntity.STAMP_FIELD).queryIterator();
            GenericValue nextValue = null;
            long valuesPerEntity = 0;
            while ((nextValue = eli.next()) != null) {
                // find first value in valuesToStore list, starting with the current insertBefore value, that has a STAMP_TX_FIELD after the nextValue.STAMP_TX_FIELD, then do the same with STAMP_FIELD
                while (insertBefore < valuesToStore.size() && valuesToStore.get(insertBefore).getTimestamp(ModelEntity.STAMP_TX_FIELD).before(nextValue.getTimestamp(ModelEntity.STAMP_TX_FIELD))) {
                    insertBefore++;
                }
                while (insertBefore < valuesToStore.size() && valuesToStore.get(insertBefore).getTimestamp(ModelEntity.STAMP_FIELD).before(nextValue.getTimestamp(ModelEntity.STAMP_FIELD))) {
                    insertBefore++;
                }
                valuesToStore.add(insertBefore, nextValue);
                valuesPerEntity++;
            }
            eli.close();
            // if we didn't find anything for this entity, find the next value's Timestamp and keep track of it
            if (valuesPerEntity == 0) {
                Timestamp startCheckStamp = new Timestamp(System.currentTimeMillis() - syncEndBufferMillis);
                EntityCondition findNextCondition = EntityCondition.makeCondition(EntityCondition.makeCondition(ModelEntity.STAMP_TX_FIELD, EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition(ModelEntity.STAMP_TX_FIELD, EntityOperator.GREATER_THAN_EQUAL_TO, currentRunEndTime), EntityCondition.makeCondition(ModelEntity.CREATE_STAMP_TX_FIELD, EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition(ModelEntity.CREATE_STAMP_TX_FIELD, EntityOperator.LESS_THAN, currentRunEndTime));
                EntityListIterator eliNext = EntityQuery.use(delegator).from(modelEntity.getEntityName()).where(findNextCondition).orderBy(ModelEntity.STAMP_TX_FIELD).queryIterator();
                // get the first element and it's tx time value...
                GenericValue firstVal = eliNext.next();
                eliNext.close();
                Timestamp nextTxTime;
                if (firstVal != null) {
                    nextTxTime = firstVal.getTimestamp(ModelEntity.CREATE_STAMP_TX_FIELD);
                } else {
                    // no results? well, then it's safe to say that up to the pre-querytime (minus the buffer, as usual) we are okay
                    nextTxTime = startCheckStamp;
                }
                if (this.nextUpdateTxTime == null || nextTxTime.before(this.nextUpdateTxTime)) {
                    this.nextUpdateTxTime = nextTxTime;
                    Debug.logInfo("EntitySync: Set nextUpdateTxTime to [" + nextTxTime + "]", module);
                }
                Timestamp curEntityNextTxTime = this.nextEntityUpdateTxTime.get(modelEntity.getEntityName());
                if (curEntityNextTxTime == null || nextTxTime.before(curEntityNextTxTime)) {
                    this.nextEntityUpdateTxTime.put(modelEntity.getEntityName(), nextTxTime);
                    Debug.logInfo("EntitySync: Set nextEntityUpdateTxTime to [" + nextTxTime + "] for the entity [" + modelEntity.getEntityName() + "]", module);
                }
            }
        } catch (GenericEntityException e) {
            try {
                TransactionUtil.rollback(beganTransaction, "Entity Engine error in assembleValuesToStore", e);
            } catch (GenericTransactionException e2) {
                Debug.logWarning(e2, "Unable to call rollback()", module);
            }
            throw new SyncDataErrorException("Error getting values to store from the datasource", e);
        } catch (Throwable t) {
            try {
                TransactionUtil.rollback(beganTransaction, "General error in assembleValuesToStore", t);
            } catch (GenericTransactionException e2) {
                Debug.logWarning(e2, "Unable to call rollback()", module);
            }
            throw new SyncDataErrorException("Caught runtime error while getting values to store", t);
        }
        try {
            TransactionUtil.commit(beganTransaction);
        } catch (GenericTransactionException e) {
            throw new SyncDataErrorException("Commit transaction failed", e);
        }
    }
    if (entitiesSkippedForKnownNext > 0) {
        if (Debug.infoOn())
            Debug.logInfo("In assembleValuesToStore skipped [" + entitiesSkippedForKnownNext + "/" + entityModelToUseList + "] entities for the time period ending at [" + currentRunEndTime + "] because of next known update times", module);
    }
    // TEST SECTION: leave false for normal use
    boolean logValues = false;
    if (logValues && valuesToStore.size() > 0) {
        StringBuilder toStoreInfo = new StringBuilder();
        for (GenericValue valueToStore : valuesToStore) {
            toStoreInfo.append("\n-->[");
            toStoreInfo.append(valueToStore.get(ModelEntity.STAMP_TX_FIELD));
            toStoreInfo.append(":");
            toStoreInfo.append(valueToStore.get(ModelEntity.STAMP_FIELD));
            toStoreInfo.append("] ");
            toStoreInfo.append(valueToStore.getPrimaryKey());
        }
        Debug.logInfo(toStoreInfo.toString(), module);
    }
    // this calculation is false, so it needs to be nullified
    if (valuesToStore.size() > 0) {
        this.nextUpdateTxTime = null;
    }
    return valuesToStore;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) ArrayList(java.util.ArrayList) Timestamp(java.sql.Timestamp) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator)

Example 73 with ModelEntity

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

the class EntityCount method exec.

@Override
public boolean exec(MethodContext methodContext) throws MiniLangException {
    try {
        Delegator delegator = getDelegator(methodContext);
        String entityName = this.entityNameFse.expandString(methodContext.getEnvMap());
        ModelEntity modelEntity = delegator.getModelEntity(entityName);
        EntityCondition whereEntityCondition = null;
        if (this.whereCondition != null) {
            whereEntityCondition = this.whereCondition.createCondition(methodContext.getEnvMap(), modelEntity, delegator.getModelFieldTypeReader(modelEntity));
        }
        EntityCondition havingEntityCondition = null;
        if (this.havingCondition != null) {
            havingEntityCondition = this.havingCondition.createCondition(methodContext.getEnvMap(), modelEntity, delegator.getModelFieldTypeReader(modelEntity));
        }
        long count = EntityQuery.use(delegator).from(entityName).where(whereEntityCondition).having(havingEntityCondition).queryCount();
        this.countFma.put(methodContext.getEnvMap(), count);
    } catch (GeneralException e) {
        String errMsg = "Exception thrown while performing entity count: " + e.getMessage();
        Debug.logWarning(e, errMsg, module);
        simpleMethod.addErrorMessage(methodContext, errMsg);
        return false;
    }
    return true;
}
Also used : GeneralException(org.apache.ofbiz.base.util.GeneralException) Delegator(org.apache.ofbiz.entity.Delegator) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity)

Example 74 with ModelEntity

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

the class EntityAutoEngine method invokeCreate.

private static Map<String, Object> invokeCreate(DispatchContext dctx, Map<String, Object> parameters, ModelService modelService, ModelEntity modelEntity, boolean allPksInOnly, List<String> pkFieldNameOutOnly) throws GeneralException {
    Locale locale = (Locale) parameters.get("locale");
    GenericValue newEntity = dctx.getDelegator().makeValue(modelEntity.getEntityName());
    boolean isSinglePk = modelEntity.getPksSize() == 1;
    boolean isDoublePk = modelEntity.getPksSize() == 2;
    Iterator<ModelField> pksIter = modelEntity.getPksIterator();
    ModelField singlePkModeField = isSinglePk ? pksIter.next() : null;
    ModelParam singlePkModelParam = isSinglePk ? modelService.getParam(singlePkModeField.getName()) : null;
    boolean isSinglePkIn = isSinglePk ? singlePkModelParam.isIn() : false;
    boolean isSinglePkOut = isSinglePk ? singlePkModelParam.isOut() : false;
    ModelParam doublePkPrimaryInParam = null;
    ModelParam doublePkSecondaryOutParam = null;
    ModelField doublePkSecondaryOutField = null;
    if (isDoublePk) {
        ModelField firstPkField = pksIter.next();
        ModelParam firstPkParam = modelService.getParam(firstPkField.getName());
        ModelField secondPkField = pksIter.next();
        ModelParam secondPkParam = modelService.getParam(secondPkField.getName());
        if (firstPkParam.isIn() && secondPkParam.isOut()) {
            doublePkPrimaryInParam = firstPkParam;
            doublePkSecondaryOutParam = secondPkParam;
            doublePkSecondaryOutField = secondPkField;
        } else if (firstPkParam.isOut() && secondPkParam.isIn()) {
            doublePkPrimaryInParam = secondPkParam;
            doublePkSecondaryOutParam = firstPkParam;
            doublePkSecondaryOutField = firstPkField;
        } else {
        // we don't have an IN and an OUT... so do nothing and leave them null
        }
    }
    if (isSinglePk && isSinglePkOut && !isSinglePkIn) {
        /*
             **** primary sequenced primary key ****
             *
            <auto-attributes include="pk" mode="OUT" optional="false"/>
             *
            <make-value entity-name="Example" value-name="newEntity"/>
            <sequenced-id-to-env sequence-name="Example" env-name="newEntity.exampleId"/> <!-- get the next sequenced ID -->
            <field-to-result field-name="newEntity.exampleId" result-name="exampleId"/>
            <set-nonpk-fields map-name="parameters" value-name="newEntity"/>
            <create-value value-name="newEntity"/>
             *
             */
        String sequencedId = dctx.getDelegator().getNextSeqId(modelEntity.getEntityName());
        newEntity.set(singlePkModeField.getName(), sequencedId);
    } else if (isSinglePk && isSinglePkOut && isSinglePkIn) {
        /*
             **** primary sequenced key with optional override passed in ****
             *
            <auto-attributes include="pk" mode="INOUT" optional="true"/>
             *
            <make-value value-name="newEntity" entity-name="Product"/>
            <set-nonpk-fields map-name="parameters" value-name="newEntity"/>
            <set from-field="parameters.productId" field="newEntity.productId"/>
            <if-empty field="newEntity.productId">
                <sequenced-id-to-env sequence-name="Product" env-name="newEntity.productId"/>
            <else>
                <check-id field-name="productId" map-name="newEntity"/>
                <check-errors/>
            </else>
            </if-empty>
            <field-to-result field-name="productId" map-name="newEntity" result-name="productId"/>
            <create-value value-name="newEntity"/>
             *
             */
        Object pkValue = parameters.get(singlePkModelParam.name);
        if (UtilValidate.isEmpty(pkValue)) {
            pkValue = dctx.getDelegator().getNextSeqId(modelEntity.getEntityName());
        } else {
            if (pkValue instanceof String) {
                StringBuffer errorDetails = new StringBuffer();
                if (!UtilValidate.isValidDatabaseId((String) pkValue, errorDetails)) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ServiceParameterValueNotValid", UtilMisc.toMap("parameterName", singlePkModelParam.name, "errorDetails", errorDetails), locale));
                }
            }
        }
        newEntity.set(singlePkModeField.getName(), pkValue);
        GenericValue lookedUpValue = PrimaryKeyFinder.runFind(modelEntity, parameters, dctx.getDelegator(), false, true, null, null);
        if (lookedUpValue != null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ServiceValueFound", UtilMisc.toMap("pkFields", newEntity.getPkShortValueString()), locale));
        }
    } else if (isDoublePk && doublePkPrimaryInParam != null && doublePkSecondaryOutParam != null) {
        /*
             **** secondary sequenced primary key ****
             *
            <auto-attributes include="pk" mode="IN" optional="false"/>
            <override name="exampleItemSeqId" mode="OUT"/> <!-- make this OUT rather than IN, we will automatically generate the next sub-sequence ID -->
             *
            <make-value entity-name="ExampleItem" value-name="newEntity"/>
            <set-pk-fields map-name="parameters" value-name="newEntity"/>
            <make-next-seq-id value-name="newEntity" seq-field-name="exampleItemSeqId"/> <!-- this finds the next sub-sequence ID -->
            <field-to-result field-name="newEntity.exampleItemSeqId" result-name="exampleItemSeqId"/>
            <set-nonpk-fields map-name="parameters" value-name="newEntity"/>
            <create-value value-name="newEntity"/>
             */
        newEntity.setPKFields(parameters, true);
        dctx.getDelegator().setNextSubSeqId(newEntity, doublePkSecondaryOutField.getName(), 5, 1);
    } else if (allPksInOnly) {
        /*
             **** plain specified primary key ****
             *
            <auto-attributes include="pk" mode="IN" optional="false"/>
             *
            <make-value entity-name="Example" value-name="newEntity"/>
            <set-pk-fields map-name="parameters" value-name="newEntity"/>
            <set-nonpk-fields map-name="parameters" value-name="newEntity"/>
            <create-value value-name="newEntity"/>
             *
             */
        newEntity.setPKFields(parameters, true);
        // with all pks present on parameters, check if the entity is not already exists.
        GenericValue lookedUpValue = PrimaryKeyFinder.runFind(modelEntity, parameters, dctx.getDelegator(), false, true, null, null);
        if (lookedUpValue != null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ServiceValueFound", UtilMisc.toMap("pkFields", newEntity.getPkShortValueString()), locale));
        }
    } else {
        /* We haven't all Pk and their are 3 or more, now check if isn't a associate entity with own sequence
            <set-pk-fields map="parameters" value-field="newEntity"/>
            <sequenced-id sequence-name="ExempleItemAssoc" field="newEntity.exempleItemAssocId"/>
            <create-value value-field="newEntity"/>
             */
        if (pkFieldNameOutOnly != null && pkFieldNameOutOnly.size() == 1) {
            newEntity.setPKFields(parameters, true);
            String pkFieldName = pkFieldNameOutOnly.get(0);
            // if it's a fromDate, don't update it now, it's will be done next step
            if (!"fromDate".equals(pkFieldName)) {
                String pkValue = dctx.getDelegator().getNextSeqId(modelEntity.getEntityName());
                newEntity.set(pkFieldName, pkValue);
            }
        } else {
            throw new GenericServiceException("In Service [" + modelService.name + "] which uses the entity-auto engine with the create invoke option: " + "could not find a valid combination of primary key settings to do a known create operation; options include: " + "1. a single OUT pk for primary auto-sequencing, " + "2. a single INOUT pk for primary auto-sequencing with optional override, " + "3. a 2-part pk with one part IN (existing primary pk) and one part OUT (the secondary pk to sub-sequence), " + "4. a N-part pk with N-1 part IN and one party OUT only (missing pk is a sub-sequence mainly for entity assoc), " + "5. all pk fields are IN for a manually specified primary key");
        }
    }
    // handle the case where there is a fromDate in the pk of the entity, and it is optional or undefined in the service def, populate automatically
    ModelField fromDateField = modelEntity.getField("fromDate");
    if (fromDateField != null && fromDateField.getIsPk()) {
        ModelParam fromDateParam = modelService.getParam("fromDate");
        if (fromDateParam == null || parameters.get("fromDate") == null) {
            newEntity.set("fromDate", UtilDateTime.nowTimestamp());
        }
    }
    newEntity.setNonPKFields(parameters, true);
    if (modelEntity.getField("createdDate") != null) {
        newEntity.set("createdDate", UtilDateTime.nowTimestamp());
        if (modelEntity.getField("createdByUserLogin") != null) {
            GenericValue userLogin = (GenericValue) parameters.get("userLogin");
            if (userLogin != null) {
                newEntity.set("createdByUserLogin", userLogin.get("userLoginId"));
                if (modelEntity.getField("lastModifiedByUserLogin") != null) {
                    newEntity.set("lastModifiedByUserLogin", userLogin.get("userLoginId"));
                } else if (modelEntity.getField("changedByUserLogin") != null) {
                    newEntity.set("changedByUserLogin", userLogin.get("userLoginId"));
                }
            }
        }
        if (modelEntity.getField("lastModifiedDate") != null) {
            newEntity.set("lastModifiedDate", UtilDateTime.nowTimestamp());
        } else if (modelEntity.getField("changedDate") != null) {
            newEntity.set("changedDate", UtilDateTime.nowTimestamp());
        }
    }
    if (modelEntity.getField("changeByUserLoginId") != null) {
        GenericValue userLogin = (GenericValue) parameters.get("userLogin");
        if (userLogin != null) {
            newEntity.set("changeByUserLoginId", userLogin.get("userLoginId"));
        } else {
            throw new GenericServiceException("You call a creation on entity that require the userLogin to track the activity, please controle that your service definition has auth='true'");
        }
        // Oh changeByUserLoginId detected, check if an EntityStatus concept
        if (modelEntity.getEntityName().endsWith("Status")) {
            if (modelEntity.getField("statusDate") != null && parameters.get("statusDate") == null) {
                newEntity.set("statusDate", UtilDateTime.nowTimestamp());
                // if a statusEndDate is present, resolve the last EntityStatus to store this value on the previous element
                if (modelEntity.getField("statusEndDate") != null) {
                    ModelEntity relatedEntity = dctx.getDelegator().getModelEntity(modelEntity.getEntityName().replaceFirst("Status", ""));
                    if (relatedEntity != null) {
                        Map<String, Object> conditionRelatedPkFieldMap = new HashMap<>();
                        for (String pkRelatedField : relatedEntity.getPkFieldNames()) {
                            conditionRelatedPkFieldMap.put(pkRelatedField, parameters.get(pkRelatedField));
                        }
                        GenericValue previousStatus = EntityQuery.use(newEntity.getDelegator()).from(modelEntity.getEntityName()).where(conditionRelatedPkFieldMap).orderBy("-statusDate").queryFirst();
                        if (previousStatus != null) {
                            previousStatus.put("statusEndDate", newEntity.get("statusDate"));
                            previousStatus.store();
                        }
                    }
                }
            }
        }
    }
    newEntity.create();
    Map<String, Object> result = ServiceUtil.returnSuccess(UtilProperties.getMessage("ServiceUiLabels", "EntityCreatedSuccessfully", UtilMisc.toMap("entityName", modelEntity.getEntityName()), locale));
    result.put("crudValue", newEntity);
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) HashMap(java.util.HashMap) ModelParam(org.apache.ofbiz.service.ModelParam) ModelField(org.apache.ofbiz.entity.model.ModelField) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity)

Example 75 with ModelEntity

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

the class ProductContentWrapper method getProductContentAsText.

public static void getProductContentAsText(String productId, GenericValue product, String productContentTypeId, Locale locale, String mimeTypeId, String partyId, String roleTypeId, Delegator delegator, LocalDispatcher dispatcher, Writer outWriter, boolean cache) throws GeneralException, IOException {
    if (productId == null && product != null) {
        productId = product.getString("productId");
    }
    if (delegator == null && product != null) {
        delegator = product.getDelegator();
    }
    if (UtilValidate.isEmpty(mimeTypeId)) {
        mimeTypeId = EntityUtilProperties.getPropertyValue("content", "defaultMimeType", "text/html; charset=utf-8", delegator);
    }
    if (delegator == null) {
        throw new GeneralRuntimeException("Unable to find a delegator to use!");
    }
    List<GenericValue> productContentList = EntityQuery.use(delegator).from("ProductContent").where("productId", productId, "productContentTypeId", productContentTypeId).orderBy("-fromDate").cache(cache).filterByDate().queryList();
    if (UtilValidate.isEmpty(productContentList) && ("Y".equals(product.getString("isVariant")))) {
        GenericValue parent = ProductWorker.getParentProduct(productId, delegator);
        if (parent != null) {
            productContentList = EntityQuery.use(delegator).from("ProductContent").where("productId", parent.get("productId"), "productContentTypeId", productContentTypeId).orderBy("-fromDate").cache(cache).filterByDate().queryList();
        }
    }
    GenericValue productContent = EntityUtil.getFirst(productContentList);
    if (productContent != null) {
        // when rendering the product content, always include the Product and ProductContent records that this comes from
        Map<String, Object> inContext = new HashMap<>();
        inContext.put("product", product);
        inContext.put("productContent", productContent);
        ContentWorker.renderContentAsText(dispatcher, productContent.getString("contentId"), outWriter, inContext, locale, mimeTypeId, partyId, roleTypeId, cache);
        return;
    }
    String candidateFieldName = ModelUtil.dbNameToVarName(productContentTypeId);
    ModelEntity productModel = delegator.getModelEntity("Product");
    if (product == null) {
        product = EntityQuery.use(delegator).from("Product").where("productId", productId).cache().queryOne();
    }
    if (UtilValidate.isEmpty(product)) {
        Debug.logWarning("No Product entity found for productId: " + productId, module);
        return;
    }
    if (productModel.isField(candidateFieldName)) {
        String candidateValue = product.getString(candidateFieldName);
        if (UtilValidate.isNotEmpty(candidateValue)) {
            outWriter.write(candidateValue);
            return;
        } else if ("Y".equals(product.getString("isVariant"))) {
            // look up the virtual product
            GenericValue parent = ProductWorker.getParentProduct(productId, delegator);
            if (parent != null) {
                candidateValue = parent.getString(candidateFieldName);
                if (UtilValidate.isNotEmpty(candidateValue)) {
                    outWriter.write(candidateValue);
                    return;
                }
            }
        }
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralRuntimeException(org.apache.ofbiz.base.util.GeneralRuntimeException) HashMap(java.util.HashMap) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity)

Aggregations

ModelEntity (org.apache.ofbiz.entity.model.ModelEntity)102 GenericValue (org.apache.ofbiz.entity.GenericValue)37 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)29 ModelField (org.apache.ofbiz.entity.model.ModelField)28 HashMap (java.util.HashMap)22 Delegator (org.apache.ofbiz.entity.Delegator)17 ModelViewEntity (org.apache.ofbiz.entity.model.ModelViewEntity)16 LinkedList (java.util.LinkedList)14 Locale (java.util.Locale)12 ModelKeyMap (org.apache.ofbiz.entity.model.ModelKeyMap)11 ArrayList (java.util.ArrayList)10 ModelRelation (org.apache.ofbiz.entity.model.ModelRelation)10 IOException (java.io.IOException)8 TreeSet (java.util.TreeSet)8 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)8 Map (java.util.Map)7 GeneralRuntimeException (org.apache.ofbiz.base.util.GeneralRuntimeException)7 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)7 ModelFieldType (org.apache.ofbiz.entity.model.ModelFieldType)7 GenericTransactionException (org.apache.ofbiz.entity.transaction.GenericTransactionException)7