Search in sources :

Example 91 with GenericEntityException

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

the class GenericDAO method singleUpdateView.

/* ====================================================================== */
/* ====================================================================== */
/**
 * Try to update the given ModelViewEntity by trying to insert/update on the entities of which the view is composed.
 *
 * Works fine with standard O/R mapped models, but has some restrictions meeting more complicated view entities.
 * <li>A direct link is required, which means that one of the ModelViewLink field entries must have a value found
 * in the given view entity, for each ModelViewLink</li>
 * <li>For now, each member entity is updated iteratively, so if eg. the second member entity fails to update,
 * the first is written although. See code for details. Try to use "clean" views, until code is more robust ...</li>
 * <li>For now, aliased field names in views are not processed correctly, I guess. To be honest, I did not
 * find out how to construct such a view - so view fieldnames must have same named fields in member entities.</li>
 * <li>A new exception, e.g. GenericViewNotUpdatable, should be defined and thrown if the update fails</li>
 */
private int singleUpdateView(GenericEntity entity, ModelViewEntity modelViewEntity, List<ModelField> fieldsToSave, SQLProcessor sqlP) throws GenericEntityException {
    Delegator delegator = entity.getDelegator();
    int retVal = 0;
    ModelEntity memberModelEntity = null;
    // Construct insert/update for each model entity
    for (ModelViewEntity.ModelMemberEntity modelMemberEntity : modelViewEntity.getMemberModelMemberEntities().values()) {
        String meName = modelMemberEntity.getEntityName();
        String meAlias = modelMemberEntity.getEntityAlias();
        if (Debug.verboseOn())
            Debug.logVerbose("[singleUpdateView]: Processing MemberEntity " + meName + " with Alias " + meAlias, module);
        try {
            memberModelEntity = delegator.getModelReader().getModelEntity(meName);
        } catch (GenericEntityException e) {
            throw new GenericEntityException("Failed to get model entity for " + meName, e);
        }
        Map<String, Object> findByMap = new HashMap<String, Object>();
        // Now iterate the ModelViewLinks to construct the "WHERE" part for update/insert
        Iterator<ModelViewEntity.ModelViewLink> linkIter = modelViewEntity.getViewLinksIterator();
        while (linkIter != null && linkIter.hasNext()) {
            ModelViewEntity.ModelViewLink modelViewLink = linkIter.next();
            if (modelViewLink.getEntityAlias().equals(meAlias) || modelViewLink.getRelEntityAlias().equals(meAlias)) {
                Iterator<ModelKeyMap> kmIter = modelViewLink.getKeyMapsIterator();
                while (kmIter != null && kmIter.hasNext()) {
                    ModelKeyMap keyMap = kmIter.next();
                    String fieldName = "";
                    if (modelViewLink.getEntityAlias().equals(meAlias)) {
                        fieldName = keyMap.getFieldName();
                    } else {
                        fieldName = keyMap.getRelFieldName();
                    }
                    if (Debug.verboseOn())
                        Debug.logVerbose("[singleUpdateView]: --- Found field to set: " + meAlias + "." + fieldName, module);
                    Object value = null;
                    if (modelViewEntity.isField(keyMap.getFieldName())) {
                        value = entity.get(keyMap.getFieldName());
                        if (Debug.verboseOn())
                            Debug.logVerbose("[singleUpdateView]: --- Found map value: " + value.toString(), module);
                    } else if (modelViewEntity.isField(keyMap.getRelFieldName())) {
                        value = entity.get(keyMap.getRelFieldName());
                        if (Debug.verboseOn())
                            Debug.logVerbose("[singleUpdateView]: --- Found map value: " + value.toString(), module);
                    } else {
                        throw new GenericNotImplementedException("Update on view entities: no direct link found, unable to update");
                    }
                    findByMap.put(fieldName, value);
                }
            }
        }
        // Look what there already is in the database
        List<GenericValue> meResult = null;
        try {
            meResult = EntityQuery.use(delegator).from(meName).where(findByMap).queryList();
        } catch (GenericEntityException e) {
            throw new GenericEntityException("Error while retrieving partial results for entity member: " + meName, e);
        }
        if (Debug.verboseOn())
            Debug.logVerbose("[singleUpdateView]: --- Found " + meResult.size() + " results for entity member " + meName, module);
        // Got results 0 -> INSERT, 1 -> UPDATE, >1 -> View is nor updatable
        GenericValue meGenericValue = null;
        if (meResult.size() == 0) {
            // Create new value to insert
            try {
                // Create new value to store
                meGenericValue = delegator.makeValue(meName, findByMap);
            } catch (Exception e) {
                throw new GenericEntityException("Could not create new value for member entity" + meName + " of view " + modelViewEntity.getEntityName(), e);
            }
        } else if (meResult.size() == 1) {
            // Update existing value
            meGenericValue = meResult.iterator().next();
        } else {
            throw new GenericEntityException("Found more than one result for member entity " + meName + " in view " + modelViewEntity.getEntityName() + " - this is no updatable view");
        }
        // Construct fieldsToSave list for this member entity
        List<ModelField> meFieldsToSave = new LinkedList<ModelField>();
        for (ModelField modelField : fieldsToSave) {
            if (memberModelEntity.isField(modelField.getName())) {
                ModelField meModelField = memberModelEntity.getField(modelField.getName());
                if (meModelField != null) {
                    meGenericValue.set(meModelField.getName(), entity.get(modelField.getName()));
                    meFieldsToSave.add(meModelField);
                    if (Debug.verboseOn())
                        Debug.logVerbose("[singleUpdateView]: --- Added field to save: " + meModelField.getName() + " with value " + meGenericValue.get(meModelField.getName()), module);
                } else {
                    throw new GenericEntityException("Could not get field " + modelField.getName() + " from model entity " + memberModelEntity.getEntityName());
                }
            }
        }
        /*
             * Finally, do the insert/update
             * TODO:
             * Do the real inserts/updates outside the memberEntity-loop,
             * only if all of the found member entities are updatable.
             * This avoids partial creation of member entities, which would mean data inconsistency:
             * If not all member entities can be updated, then none should be updated
             */
        if (meResult.size() == 0) {
            retVal += singleInsert(meGenericValue, memberModelEntity, memberModelEntity.getFieldsUnmodifiable(), sqlP);
        } else {
            if (meFieldsToSave.size() > 0) {
                retVal += singleUpdate(meGenericValue, memberModelEntity, meFieldsToSave, sqlP);
            } else {
                if (Debug.verboseOn())
                    Debug.logVerbose("[singleUpdateView]: No update on member entity " + memberModelEntity.getEntityName() + " needed", module);
            }
        }
    }
    return retVal;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) GenericNotImplementedException(org.apache.ofbiz.entity.GenericNotImplementedException) SQLException(java.sql.SQLException) GenericDataSourceException(org.apache.ofbiz.entity.GenericDataSourceException) GenericNotImplementedException(org.apache.ofbiz.entity.GenericNotImplementedException) EntityLockedException(org.apache.ofbiz.entity.EntityLockedException) GenericModelException(org.apache.ofbiz.entity.GenericModelException) GenericEntityNotFoundException(org.apache.ofbiz.entity.GenericEntityNotFoundException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) LinkedList(java.util.LinkedList) ModelKeyMap(org.apache.ofbiz.entity.model.ModelKeyMap) Delegator(org.apache.ofbiz.entity.Delegator) ModelField(org.apache.ofbiz.entity.model.ModelField) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ModelViewEntity(org.apache.ofbiz.entity.model.ModelViewEntity) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity)

Example 92 with GenericEntityException

use of org.apache.ofbiz.entity.GenericEntityException 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 93 with GenericEntityException

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

the class EntityPermissionChecker method runPermissionCheck.

public boolean runPermissionCheck(Map<String, ?> context) {
    boolean passed = false;
    String idString = entityIdExdr.expandString(context);
    List<String> entityIdList = null;
    if (UtilValidate.isNotEmpty(idString)) {
        entityIdList = StringUtil.split(idString, "|");
    } else {
        entityIdList = new LinkedList<String>();
    }
    String entityName = entityNameExdr.expandString(context);
    HttpServletRequest request = (HttpServletRequest) context.get("request");
    GenericValue userLogin = null;
    String partyId = null;
    Delegator delegator = null;
    if (request != null) {
        HttpSession session = request.getSession();
        userLogin = (GenericValue) session.getAttribute("userLogin");
        if (userLogin != null) {
            partyId = userLogin.getString("partyId");
        }
        delegator = (Delegator) request.getAttribute("delegator");
    }
    if (auxiliaryValueGetter != null)
        auxiliaryValueGetter.clearList();
    if (relatedRoleGetter != null)
        relatedRoleGetter.clearList();
    try {
        permissionConditionGetter.init(delegator);
        passed = checkPermissionMethod(delegator, partyId, entityName, entityIdList, auxiliaryValueGetter, relatedRoleGetter, permissionConditionGetter);
        if (!passed && displayFailCond) {
            String errMsg = "Permission is denied. \nThese are the conditions of which one must be met:\n" + permissionConditionGetter.dumpAsText();
            List<Object> errorMessageList = checkList(context.get("errorMessageList"));
            errorMessageList.add(errMsg);
        }
    } catch (GenericEntityException e) {
        throw new RuntimeException(e.getMessage());
    }
    return passed;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) HttpSession(javax.servlet.http.HttpSession) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Example 94 with GenericEntityException

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

the class EntityPermissionChecker method getRelatedPurposes.

/**
 * getRelatedPurposes
 */
public static List<String> getRelatedPurposes(GenericValue entity, List<String> passedPurposes) {
    if (entity == null)
        return passedPurposes;
    List<String> purposeIds = null;
    if (passedPurposes == null) {
        purposeIds = new LinkedList<String>();
    } else {
        purposeIds = new LinkedList<String>();
        purposeIds.addAll(passedPurposes);
    }
    String entityName = entity.getEntityName();
    String lcEntityName = entityName.toLowerCase();
    List<GenericValue> purposes = null;
    try {
        purposes = entity.getRelated(entityName + "Purpose", null, null, true);
    } catch (GenericEntityException e) {
        Debug.logError(e, "No associated purposes found. ", module);
        return purposeIds;
    }
    for (GenericValue val : purposes) {
        purposeIds.add((String) val.get(lcEntityName + "PurposeTypeId"));
    }
    return purposeIds;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Example 95 with GenericEntityException

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

the class EntityDataServices method reencryptPrivateKeys.

public static Map<String, Object> reencryptPrivateKeys(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 oldKey = (String) context.get("oldKey");
    String newKey = (String) context.get("newKey");
    AesCipherService cipherService = new AesCipherService();
    try {
        List<GenericValue> rows = EntityQuery.use(delegator).from("EntityKeyStore").queryList();
        for (GenericValue row : rows) {
            byte[] keyBytes = Base64.decodeBase64(row.getString("keyText"));
            Debug.logInfo("Processing entry " + row.getString("keyName") + " with key: " + row.getString("keyText"), module);
            if (oldKey != null) {
                Debug.logInfo("Decrypting with old key: " + oldKey, module);
                try {
                    keyBytes = cipherService.decrypt(keyBytes, Base64.decodeBase64(oldKey)).getBytes();
                } catch (Exception e) {
                    Debug.logInfo("Failed to decrypt with Shiro cipher; trying with old cipher", module);
                    try {
                        keyBytes = DesCrypt.decrypt(DesCrypt.getDesKey(Base64.decodeBase64(oldKey)), keyBytes);
                    } catch (Exception e1) {
                        Debug.logError(e1, module);
                        return ServiceUtil.returnError(e1.getMessage());
                    }
                }
            }
            String newKeyText;
            if (newKey != null) {
                Debug.logInfo("Encrypting with new key: " + oldKey, module);
                newKeyText = cipherService.encrypt(keyBytes, Base64.decodeBase64(newKey)).toBase64();
            } else {
                newKeyText = Base64.encodeBase64String(keyBytes);
            }
            Debug.logInfo("Storing new encrypted value: " + newKeyText, module);
            row.setString("keyText", newKeyText);
            row.store();
        }
    } catch (GenericEntityException gee) {
        Debug.logError(gee, module);
        return ServiceUtil.returnError(gee.getMessage());
    }
    delegator.clearAllCaches();
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) AesCipherService(org.apache.shiro.crypto.AesCipherService) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) Security(org.apache.ofbiz.security.Security) URISyntaxException(java.net.URISyntaxException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GeneralException(org.apache.ofbiz.base.util.GeneralException)

Aggregations

GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)913 GenericValue (org.apache.ofbiz.entity.GenericValue)847 Delegator (org.apache.ofbiz.entity.Delegator)599 Locale (java.util.Locale)384 HashMap (java.util.HashMap)336 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)270 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)259 LinkedList (java.util.LinkedList)231 BigDecimal (java.math.BigDecimal)213 Timestamp (java.sql.Timestamp)171 Map (java.util.Map)109 GeneralException (org.apache.ofbiz.base.util.GeneralException)95 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)78 IOException (java.io.IOException)75 EntityListIterator (org.apache.ofbiz.entity.util.EntityListIterator)57 Security (org.apache.ofbiz.security.Security)54 ArrayList (java.util.ArrayList)48 EntityExpr (org.apache.ofbiz.entity.condition.EntityExpr)47 GenericTransactionException (org.apache.ofbiz.entity.transaction.GenericTransactionException)39 LinkedHashMap (java.util.LinkedHashMap)37