Search in sources :

Example 36 with ModelField

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

the class EntityUtil method filterByDate.

/**
 *returns the values that are active at the moment.
 *
 *@param datedValues GenericValue's that have "fromDate" and "thruDate" fields
 *@param moment the moment in question
 *@param allAreSame Specifies whether all values in the List are of the same entity; this can help speed things up a fair amount since we only have to see if the from and thru date fields are valid once
 *@return List of GenericValue's that are active at the moment
 */
public static <T extends GenericEntity> List<T> filterByDate(List<T> datedValues, java.sql.Timestamp moment, String fromDateName, String thruDateName, boolean allAreSame) {
    if (datedValues == null)
        return null;
    if (moment == null)
        return datedValues;
    if (fromDateName == null)
        fromDateName = "fromDate";
    if (thruDateName == null)
        thruDateName = "thruDate";
    List<T> result = new LinkedList<T>();
    Iterator<T> iter = datedValues.iterator();
    if (allAreSame) {
        ModelField fromDateField = null;
        ModelField thruDateField = null;
        if (iter.hasNext()) {
            T datedValue = iter.next();
            fromDateField = datedValue.getModelEntity().getField(fromDateName);
            if (fromDateField == null)
                throw new IllegalArgumentException("\"" + fromDateName + "\" is not a field of " + datedValue.getEntityName());
            thruDateField = datedValue.getModelEntity().getField(thruDateName);
            if (thruDateField == null)
                throw new IllegalArgumentException("\"" + thruDateName + "\" is not a field of " + datedValue.getEntityName());
            java.sql.Timestamp fromDate = (java.sql.Timestamp) datedValue.dangerousGetNoCheckButFast(fromDateField);
            java.sql.Timestamp thruDate = (java.sql.Timestamp) datedValue.dangerousGetNoCheckButFast(thruDateField);
            if ((thruDate == null || thruDate.after(moment)) && (fromDate == null || fromDate.before(moment) || fromDate.equals(moment))) {
                result.add(datedValue);
            }
        // else not active at moment
        }
        while (iter.hasNext()) {
            T datedValue = iter.next();
            java.sql.Timestamp fromDate = (java.sql.Timestamp) datedValue.dangerousGetNoCheckButFast(fromDateField);
            java.sql.Timestamp thruDate = (java.sql.Timestamp) datedValue.dangerousGetNoCheckButFast(thruDateField);
            if ((thruDate == null || thruDate.after(moment)) && (fromDate == null || fromDate.before(moment) || fromDate.equals(moment))) {
                result.add(datedValue);
            }
        // else not active at moment
        }
    } else {
        // if not all values are known to be of the same entity, must check each one...
        while (iter.hasNext()) {
            T datedValue = iter.next();
            java.sql.Timestamp fromDate = datedValue.getTimestamp(fromDateName);
            java.sql.Timestamp thruDate = datedValue.getTimestamp(thruDateName);
            if ((thruDate == null || thruDate.after(moment)) && (fromDate == null || fromDate.before(moment) || fromDate.equals(moment))) {
                result.add(datedValue);
            }
        // else not active at moment
        }
    }
    return result;
}
Also used : ModelField(org.apache.ofbiz.entity.model.ModelField) Timestamp(java.sql.Timestamp) Timestamp(java.sql.Timestamp) LinkedList(java.util.LinkedList)

Example 37 with ModelField

use of org.apache.ofbiz.entity.model.ModelField 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 38 with ModelField

use of org.apache.ofbiz.entity.model.ModelField 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 39 with ModelField

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

the class GenericDelegator method storeAll.

/* (non-Javadoc)
     * @see org.apache.ofbiz.entity.Delegator#storeAll(java.util.List, org.apache.ofbiz.entity.util.EntityStoreOptions)
     */
@Override
public int storeAll(List<GenericValue> values, EntityStoreOptions storeOptions) throws GenericEntityException {
    if (values == null) {
        return 0;
    }
    // if no store options passed, use default
    if (storeOptions == null) {
        storeOptions = new EntityStoreOptions();
    }
    int numberChanged = 0;
    boolean beganTransaction = false;
    try {
        beganTransaction = TransactionUtil.begin();
        for (GenericValue value : values) {
            String entityName = value.getEntityName();
            GenericPK primaryKey = value.getPrimaryKey();
            GenericHelper helper = getEntityHelper(entityName);
            // NOTE: don't use findByPrimaryKey because we don't want to the ECA events to fire and such
            if (!primaryKey.isPrimaryKey()) {
                throw new GenericModelException("[GenericDelegator.storeAll] One of the passed primary keys is not a valid primary key: " + primaryKey);
            }
            GenericValue existing = null;
            try {
                existing = helper.findByPrimaryKey(primaryKey);
            } catch (GenericEntityNotFoundException e) {
                existing = null;
            }
            if (existing == null) {
                if (storeOptions.isCreateDummyFks()) {
                    value.checkFks(true);
                }
                this.create(value);
                numberChanged++;
            } else {
                // don't send fields that are the same, and if no fields have changed, update nothing
                ModelEntity modelEntity = value.getModelEntity();
                GenericValue toStore = GenericValue.create(this, modelEntity, value.getPrimaryKey());
                boolean atLeastOneField = false;
                Iterator<ModelField> nonPksIter = modelEntity.getNopksIterator();
                while (nonPksIter.hasNext()) {
                    ModelField modelField = nonPksIter.next();
                    String fieldName = modelField.getName();
                    if (value.containsKey(fieldName)) {
                        Object fieldValue = value.get(fieldName);
                        Object oldValue = existing.get(fieldName);
                        if (!UtilObject.equalsHelper(oldValue, fieldValue)) {
                            toStore.put(fieldName, fieldValue);
                            atLeastOneField = true;
                        }
                    }
                }
                if (atLeastOneField) {
                    if (storeOptions.isCreateDummyFks()) {
                        value.checkFks(true);
                    }
                    numberChanged += this.store(toStore);
                }
            }
        }
        TransactionUtil.commit(beganTransaction);
        return numberChanged;
    } catch (GenericEntityException e) {
        String errMsg = "Failure in storeAll operation: " + e.toString() + ". Rolling back transaction.";
        Debug.logError(e, errMsg, module);
        TransactionUtil.rollback(beganTransaction, errMsg, e);
        throw new GenericEntityException(e);
    }
}
Also used : GenericHelper(org.apache.ofbiz.entity.datasource.GenericHelper) EntityStoreOptions(org.apache.ofbiz.entity.util.EntityStoreOptions) ModelField(org.apache.ofbiz.entity.model.ModelField) UtilObject(org.apache.ofbiz.base.util.UtilObject) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity)

Example 40 with ModelField

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

the class GenericDelegator method makeValue.

/* (non-Javadoc)
     * @see org.apache.ofbiz.entity.Delegator#makeValue(org.w3c.dom.Element)
     */
@Override
public GenericValue makeValue(Element element) {
    if (element == null) {
        return null;
    }
    String entityName = element.getTagName();
    // if a dash or colon is in the tag name, grab what is after it
    if (entityName.indexOf('-') > 0) {
        entityName = entityName.substring(entityName.indexOf('-') + 1);
    }
    if (entityName.indexOf(':') > 0) {
        entityName = entityName.substring(entityName.indexOf(':') + 1);
    }
    GenericValue value = this.makeValue(entityName);
    ModelEntity modelEntity = value.getModelEntity();
    Iterator<ModelField> modelFields = modelEntity.getFieldsIterator();
    while (modelFields.hasNext()) {
        ModelField modelField = modelFields.next();
        String name = modelField.getName();
        String attr = element.getAttribute(name);
        if (UtilValidate.isNotEmpty(attr)) {
            // that and treat it as null
            if (GenericEntity.NULL_FIELD.toString().equals(attr)) {
                value.set(name, null);
            } else {
                value.setString(name, attr);
            }
        } else {
            // if no attribute try a subelement
            Element subElement = UtilXml.firstChildElement(element, name);
            if (subElement != null) {
                value.setString(name, UtilXml.elementValue(subElement));
            }
        }
    }
    return value;
}
Also used : ModelField(org.apache.ofbiz.entity.model.ModelField) DelegatorElement(org.apache.ofbiz.entity.config.model.DelegatorElement) Element(org.w3c.dom.Element) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity)

Aggregations

ModelField (org.apache.ofbiz.entity.model.ModelField)55 ModelEntity (org.apache.ofbiz.entity.model.ModelEntity)28 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)16 LinkedList (java.util.LinkedList)14 ModelViewEntity (org.apache.ofbiz.entity.model.ModelViewEntity)13 HashMap (java.util.HashMap)10 GenericValue (org.apache.ofbiz.entity.GenericValue)10 ModelFieldType (org.apache.ofbiz.entity.model.ModelFieldType)10 ModelKeyMap (org.apache.ofbiz.entity.model.ModelKeyMap)10 Map (java.util.Map)8 SQLException (java.sql.SQLException)7 Locale (java.util.Locale)7 GenericModelException (org.apache.ofbiz.entity.GenericModelException)7 TreeSet (java.util.TreeSet)6 Delegator (org.apache.ofbiz.entity.Delegator)6 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)6 GeneralException (org.apache.ofbiz.base.util.GeneralException)5 ModelParam (org.apache.ofbiz.service.ModelParam)5 SQLProcessor (org.apache.ofbiz.entity.jdbc.SQLProcessor)4 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)4