Search in sources :

Example 51 with ModelEntity

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

the class CategoryServices method getCategoryFindEntityName.

private static String getCategoryFindEntityName(Delegator delegator, List<String> orderByFields, Timestamp introductionDateLimit, Timestamp releaseDateLimit) {
    // allow orderByFields to contain fields from the Product entity, if there are such fields
    String entityName = introductionDateLimit == null && releaseDateLimit == null ? "ProductCategoryMember" : "ProductAndCategoryMember";
    if (orderByFields == null) {
        return entityName;
    }
    if (orderByFields.size() == 0) {
        orderByFields.add("sequenceNum");
        orderByFields.add("productId");
    }
    ModelEntity productModel = delegator.getModelEntity("Product");
    ModelEntity productCategoryMemberModel = delegator.getModelEntity("ProductCategoryMember");
    for (String orderByField : orderByFields) {
        // Get the real field name from the order by field removing ascending/descending order
        if (UtilValidate.isNotEmpty(orderByField)) {
            int startPos = 0, endPos = orderByField.length();
            if (orderByField.endsWith(" DESC")) {
                endPos -= 5;
            } else if (orderByField.endsWith(" ASC")) {
                endPos -= 4;
            } else if (orderByField.startsWith("-")) {
                startPos++;
            } else if (orderByField.startsWith("+")) {
                startPos++;
            }
            if (startPos != 0 || endPos != orderByField.length()) {
                orderByField = orderByField.substring(startPos, endPos);
            }
        }
        if (!productCategoryMemberModel.isField(orderByField)) {
            if (productModel.isField(orderByField)) {
                entityName = "ProductAndCategoryMember";
                // that's what we wanted to find out, so we can quit now
                break;
            } else {
            // ahh!! bad field name, don't worry, it will blow up in the query
            }
        }
    }
    return entityName;
}
Also used : ModelEntity(org.apache.ofbiz.entity.model.ModelEntity)

Example 52 with ModelEntity

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

the class FindServices method prepareFind.

/**
 * prepareFind
 *
 * This is a generic method that expects entity data affixed with special suffixes
 * to indicate their purpose in formulating an SQL query statement.
 */
public static Map<String, Object> prepareFind(DispatchContext dctx, Map<String, ?> context) {
    String entityName = (String) context.get("entityName");
    Delegator delegator = dctx.getDelegator();
    String orderBy = (String) context.get("orderBy");
    // Input
    Map<String, ?> inputFields = checkMap(context.get("inputFields"), String.class, Object.class);
    String noConditionFind = (String) context.get("noConditionFind");
    if (UtilValidate.isEmpty(noConditionFind)) {
        // try finding in inputFields Map
        noConditionFind = (String) inputFields.get("noConditionFind");
    }
    if (UtilValidate.isEmpty(noConditionFind)) {
        // Use configured default
        noConditionFind = EntityUtilProperties.getPropertyValue("widget", "widget.defaultNoConditionFind", delegator);
    }
    String filterByDate = (String) context.get("filterByDate");
    if (UtilValidate.isEmpty(filterByDate)) {
        // try finding in inputFields Map
        filterByDate = (String) inputFields.get("filterByDate");
    }
    Timestamp filterByDateValue = (Timestamp) context.get("filterByDateValue");
    String fromDateName = (String) context.get("fromDateName");
    String thruDateName = (String) context.get("thruDateName");
    Map<String, Object> queryStringMap = new LinkedHashMap<>();
    ModelEntity modelEntity = delegator.getModelEntity(entityName);
    List<EntityCondition> tmpList = createConditionList(inputFields, modelEntity.getFieldsUnmodifiable(), queryStringMap, delegator, context);
    /* the filter by date condition should only be added when there are other conditions or when
         * the user has specified a noConditionFind.  Otherwise, specifying filterByDate will become
         * its own condition.
         */
    if (tmpList.size() > 0 || "Y".equals(noConditionFind)) {
        if ("Y".equals(filterByDate)) {
            queryStringMap.put("filterByDate", filterByDate);
            if (UtilValidate.isEmpty(fromDateName)) {
                fromDateName = "fromDate";
            } else {
                queryStringMap.put("fromDateName", fromDateName);
            }
            if (UtilValidate.isEmpty(thruDateName)) {
                thruDateName = "thruDate";
            } else {
                queryStringMap.put("thruDateName", thruDateName);
            }
            if (UtilValidate.isEmpty(filterByDateValue)) {
                EntityCondition filterByDateCondition = EntityUtil.getFilterByDateExpr(fromDateName, thruDateName);
                tmpList.add(filterByDateCondition);
            } else {
                queryStringMap.put("filterByDateValue", filterByDateValue);
                EntityCondition filterByDateCondition = EntityUtil.getFilterByDateExpr(filterByDateValue, fromDateName, thruDateName);
                tmpList.add(filterByDateCondition);
            }
        }
    }
    EntityConditionList<EntityCondition> exprList = null;
    if (tmpList.size() > 0) {
        exprList = EntityCondition.makeCondition(tmpList);
    }
    List<String> orderByList = null;
    if (UtilValidate.isNotEmpty(orderBy)) {
        orderByList = StringUtil.split(orderBy, "|");
    }
    Map<String, Object> results = ServiceUtil.returnSuccess();
    queryStringMap.put("noConditionFind", noConditionFind);
    String queryString = UtilHttp.urlEncodeArgs(queryStringMap);
    results.put("queryString", queryString);
    results.put("queryStringMap", queryStringMap);
    results.put("orderByList", orderByList);
    results.put("entityConditionList", exprList);
    return results;
}
Also used : Delegator(org.apache.ofbiz.entity.Delegator) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) Timestamp(java.sql.Timestamp) LinkedHashMap(java.util.LinkedHashMap)

Example 53 with ModelEntity

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

the class FindServices method buildReducedQueryString.

public static Map<String, Object> buildReducedQueryString(Map<String, ?> inputFields, String entityName, Delegator delegator) {
    // Strip the "_suffix" off of the parameter name and
    // build a three-level map of values keyed by fieldRoot name,
    // fld0 or fld1,  and, then, "op" or "value"
    // ie. id
    // - fld0
    // - op:like
    // - value:abc
    // - fld1 (if there is a range)
    // - op:lessThan
    // - value:55 (note: these two "flds" wouldn't really go together)
    // Also note that op/fld can be in any order. (eg. id_fld1_equals or id_equals_fld1)
    // Note that "normalizedFields" will contain values other than those
    // Contained in the associated entity.
    // Those extra fields will be ignored in the second half of this method.
    ModelEntity modelEntity = delegator.getModelEntity(entityName);
    Map<String, Object> normalizedFields = new LinkedHashMap<>();
    // StringBuffer queryStringBuf = new StringBuffer();
    for (Entry<String, ?> entry : inputFields.entrySet()) {
        // The name as it appears in the HTML form
        String fieldNameRaw = entry.getKey();
        // The entity field name. Everything to the left of the first "_" if
        String fieldNameRoot = null;
        // it exists, or the whole word, if not.
        // If it is a "value" field, it will be the value to be used in the query.
        Object fieldValue = null;
        // If it is an "op" field, it will be "equals", "greaterThan", etc.
        int iPos = -1;
        int iPos2 = -1;
        fieldValue = entry.getValue();
        if (ObjectType.isEmpty(fieldValue)) {
            continue;
        }
        // Look for suffix
        iPos = fieldNameRaw.indexOf('_');
        // These would have the form "fieldName_o_1"
        if (iPos >= 0) {
            String suffix = fieldNameRaw.substring(iPos + 1);
            iPos2 = suffix.indexOf('_');
            if (iPos2 == 1) {
                continue;
            }
        }
        // If no field op is present, it will assume "equals".
        if (iPos < 0) {
            fieldNameRoot = fieldNameRaw;
        } else {
            // Must have at least "fld0/1" or "equals, greaterThan, etc."
            // Some bogus fields will slip in, like "ENTITY_NAME", but they will be ignored
            fieldNameRoot = fieldNameRaw.substring(0, iPos);
        }
        if (modelEntity.isField(fieldNameRoot)) {
            normalizedFields.put(fieldNameRaw, fieldValue);
        }
    }
    return normalizedFields;
}
Also used : ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) LinkedHashMap(java.util.LinkedHashMap)

Example 54 with ModelEntity

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

the class EntityDataLoader method generateData.

public static int generateData(Delegator delegator, List<Object> errorMessages) throws GenericEntityException {
    int rowsChanged = 0;
    ModelReader reader = delegator.getModelReader();
    for (String entityName : reader.getEntityNames()) {
        ModelEntity entity = reader.getModelEntity(entityName);
        String baseName = entity.getPlainTableName();
        if (entity instanceof ModelViewEntity) {
            baseName = ModelUtil.javaNameToDbName(entity.getEntityName());
        }
        if (baseName != null) {
            try {
                List<GenericValue> toBeStored = new LinkedList<GenericValue>();
                toBeStored.add(delegator.makeValue("SecurityPermission", "permissionId", baseName + "_ADMIN", "description", "Permission to Administer a " + entity.getEntityName() + " entity."));
                toBeStored.add(delegator.makeValue("SecurityGroupPermission", "groupId", "FULLADMIN", "permissionId", baseName + "_ADMIN", "fromDate", UtilDateTime.nowTimestamp()));
                rowsChanged += delegator.storeAll(toBeStored);
            } catch (GenericEntityException e) {
                errorMessages.add("[generateData] ERROR: Failed Security Generation for entity \"" + baseName + "\"");
            }
        /*
                toStore.add(delegator.makeValue("SecurityPermission", "permissionId", baseName + "_VIEW", "description", "Permission to View a " + entity.getEntityName() + " entity."));
                toStore.add(delegator.makeValue("SecurityPermission", "permissionId", baseName + "_CREATE", "description", "Permission to Create a " + entity.getEntityName() + " entity."));
                toStore.add(delegator.makeValue("SecurityPermission", "permissionId", baseName + "_UPDATE", "description", "Permission to Update a " + entity.getEntityName() + " entity."));
                toStore.add(delegator.makeValue("SecurityPermission", "permissionId", baseName + "_DELETE", "description", "Permission to Delete a " + entity.getEntityName() + " entity."));

                toStore.add(delegator.makeValue("SecurityGroupPermission", "groupId", "FLEXADMIN", "permissionId", baseName + "_VIEW"));
                toStore.add(delegator.makeValue("SecurityGroupPermission", "groupId", "FLEXADMIN", "permissionId", baseName + "_CREATE"));
                toStore.add(delegator.makeValue("SecurityGroupPermission", "groupId", "FLEXADMIN", "permissionId", baseName + "_UPDATE"));
                toStore.add(delegator.makeValue("SecurityGroupPermission", "groupId", "FLEXADMIN", "permissionId", baseName + "_DELETE"));
                */
        }
    }
    return rowsChanged;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) ModelReader(org.apache.ofbiz.entity.model.ModelReader) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ModelViewEntity(org.apache.ofbiz.entity.model.ModelViewEntity) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) LinkedList(java.util.LinkedList)

Example 55 with ModelEntity

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

the class EntitySaxReader method startElement.

public void startElement(String namepsaceURI, String localName, String fullNameString, Attributes attributes) throws SAXException {
    if (Debug.verboseOn())
        Debug.logVerbose("startElement: localName=" + localName + ", fullName=" + fullNameString + ", attributes=" + attributes, module);
    if ("entity-engine-xml".equals(fullNameString)) {
        // check the maintain-timestamp flag
        CharSequence maintainTx = attributes.getValue("maintain-timestamps");
        if (maintainTx != null) {
            this.setMaintainTxStamps("true".equalsIgnoreCase(maintainTx.toString()));
        }
        // check the disable-eeca flag
        CharSequence ecaDisable = attributes.getValue("disable-eeca");
        if (ecaDisable != null) {
            this.setDisableEeca("true".equalsIgnoreCase(ecaDisable.toString()));
        }
        // check the use-dummy-fk flag
        CharSequence dummyFk = attributes.getValue("create-dummy-fk");
        if (dummyFk != null) {
            this.setCreateDummyFks("true".equalsIgnoreCase(dummyFk.toString()));
        }
        return;
    }
    if ("entity-engine-transform-xml".equals(fullNameString)) {
        templatePath = attributes.getValue("template");
        isParseForTemplate = true;
        documentForTemplate = UtilXml.makeEmptyXmlDocument();
        return;
    }
    if (isParseForTemplate) {
        Element newElement = this.documentForTemplate.createElement(fullNameString);
        int length = attributes.getLength();
        for (int i = 0; i < length; i++) {
            CharSequence name = attributes.getLocalName(i);
            CharSequence value = attributes.getValue(i);
            if (UtilValidate.isEmpty(name)) {
                name = attributes.getQName(i);
            }
            newElement.setAttribute(name.toString(), value.toString());
        }
        if (this.currentNodeForTemplate == null) {
            this.currentNodeForTemplate = newElement;
            this.rootNodeForTemplate = newElement;
        } else {
            this.currentNodeForTemplate.appendChild(newElement);
            this.currentNodeForTemplate = newElement;
        }
        return;
    }
    // Test if action change
    if (actionTags.contains(fullNameString)) {
        if ("create".equals(fullNameString))
            setAction(Action.CREATE);
        if ("create-update".equals(fullNameString))
            setAction(Action.CREATE_UPDATE);
        if ("create-replace".equals(fullNameString))
            setAction(Action.CREATE_REPLACE);
        if ("delete".equals(fullNameString))
            setAction(Action.DELETE);
        return;
    }
    if (currentValue != null) {
        // we have a nested value/CDATA element
        currentFieldName = fullNameString;
    } else {
        String entityName = fullNameString;
        // 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);
        }
        try {
            currentValue = delegator.makeValue(entityName);
            if (this.maintainTxStamps) {
                currentValue.setIsFromEntitySync(true);
            }
        } catch (Exception e) {
            if (continueOnFail) {
                Debug.logError(e, module);
            } else {
                throw new SAXException(e);
            }
        }
        if (currentValue != null) {
            int length = attributes.getLength();
            List<String> absentFields = null;
            if (Action.CREATE_REPLACE == currentAction) {
                // get all non pk fields
                ModelEntity currentEntity = currentValue.getModelEntity();
                absentFields = currentEntity.getNoPkFieldNames();
                absentFields.removeAll(currentEntity.getAutomaticFieldNames());
            }
            for (int i = 0; i < length; i++) {
                CharSequence name = attributes.getLocalName(i);
                CharSequence value = attributes.getValue(i);
                if (UtilValidate.isNotEmpty(value)) {
                    String tmp = FlexibleStringExpander.expandString(value.toString(), placeholderValues);
                    value = tmp.subSequence(0, tmp.length());
                }
                if (UtilValidate.isEmpty(name)) {
                    name = attributes.getQName(i);
                }
                try {
                    // treat empty strings as nulls, but do NOT ignore them, instead set as null and update
                    if (value != null) {
                        if (currentValue.getModelEntity().isField(name.toString())) {
                            String valueString = (value.length() > 0 ? value.toString() : null);
                            currentValue.setString(name.toString(), valueString);
                            if (Action.CREATE_REPLACE == currentAction && absentFields != null)
                                absentFields.remove(name);
                        } else {
                            Debug.logWarning("Ignoring invalid field name [" + name + "] found for the entity: " + currentValue.getEntityName() + " with value=" + value, module);
                        }
                    }
                } catch (Exception e) {
                    Debug.logWarning(e, "Could not set field " + entityName + "." + name + " to the value " + value, module);
                }
            }
            if (Action.CREATE_REPLACE == currentAction && absentFields != null) {
                for (String fieldName : absentFields) {
                    currentValue.set(fieldName, null);
                }
            }
        }
    }
}
Also used : Element(org.w3c.dom.Element) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) TemplateException(freemarker.template.TemplateException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) GenericEntityNotFoundException(org.apache.ofbiz.entity.GenericEntityNotFoundException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) SAXException(org.xml.sax.SAXException) SAXException(org.xml.sax.SAXException)

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