Search in sources :

Example 96 with Delegator

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

the class PreferenceServices method copyUserPreferenceGroup.

/**
 * Copies a user preference group. Call with
 * fromUserLoginId, userPrefGroupTypeId and optional userPrefLoginId. If userPrefLoginId
 * isn't specified, then the currently logged-in user's userLoginId will be
 * used.
 * @param ctx The DispatchContext that this service is operating in.
 * @param context Map containing the input arguments.
 * @return Map with the result of the service, the output parameters.
 */
public static Map<String, Object> copyUserPreferenceGroup(DispatchContext ctx, Map<String, ?> context) {
    Delegator delegator = ctx.getDelegator();
    Locale locale = (Locale) context.get("locale");
    String userLoginId = PreferenceWorker.getUserLoginId(context, false);
    String fromUserLoginId = (String) context.get("fromUserLoginId");
    String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId");
    if (UtilValidate.isEmpty(userLoginId) || UtilValidate.isEmpty(userPrefGroupTypeId) || UtilValidate.isEmpty(fromUserLoginId)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "copyPreference.invalidArgument", locale));
    }
    try {
        List<GenericValue> resultList = EntityQuery.use(delegator).from("UserPreference").where("userLoginId", fromUserLoginId, "userPrefGroupTypeId", userPrefGroupTypeId).queryList();
        if (resultList != null) {
            for (GenericValue preference : resultList) {
                preference.set("userLoginId", userLoginId);
            }
            delegator.storeAll(resultList);
        }
    } catch (GenericEntityException e) {
        Debug.logWarning(e.getMessage(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "copyPreference.writeFailure", new Object[] { e.getMessage() }, locale));
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Example 97 with Delegator

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

the class StatusWorker method getStatusValidChangeToDetails.

public static void getStatusValidChangeToDetails(PageContext pageContext, String attributeName, String statusId) {
    Delegator delegator = (Delegator) pageContext.getRequest().getAttribute("delegator");
    List<GenericValue> statusValidChangeToDetails = null;
    try {
        statusValidChangeToDetails = EntityQuery.use(delegator).from("StatusValidChangeToDetail").where("statusId", statusId).orderBy("sequenceId").cache(true).queryList();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    if (statusValidChangeToDetails != null)
        pageContext.setAttribute(attributeName, statusValidChangeToDetails);
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Example 98 with Delegator

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

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

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

the class EntitySyncServices method loadOfflineSyncData.

public static Map<String, Object> loadOfflineSyncData(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String fileName = (String) context.get("xmlFileName");
    Locale locale = (Locale) context.get("locale");
    URL xmlFile = UtilURL.fromResource(fileName);
    if (xmlFile != null) {
        Document xmlSyncDoc = null;
        try {
            xmlSyncDoc = UtilXml.readXmlDocument(xmlFile, false);
        } catch (SAXException e) {
            Debug.logError(e, module);
        } catch (ParserConfigurationException e) {
            Debug.logError(e, module);
        } catch (IOException e) {
            Debug.logError(e, module);
        }
        if (xmlSyncDoc == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtEntitySyncXMLDocumentIsNotValid", UtilMisc.toMap("fileName", fileName), locale));
        }
        List<? extends Element> syncElements = UtilXml.childElementList(xmlSyncDoc.getDocumentElement());
        if (syncElements != null) {
            for (Element entitySync : syncElements) {
                String entitySyncId = entitySync.getAttribute("entitySyncId");
                String startTime = entitySync.getAttribute("lastSuccessfulSynchTime");
                String createString = UtilXml.childElementValue(entitySync, "values-to-create");
                String storeString = UtilXml.childElementValue(entitySync, "values-to-store");
                String removeString = UtilXml.childElementValue(entitySync, "keys-to-remove");
                // de-serialize the value lists
                try {
                    List<GenericValue> valuesToCreate = checkList(XmlSerializer.deserialize(createString, delegator), GenericValue.class);
                    List<GenericValue> valuesToStore = checkList(XmlSerializer.deserialize(storeString, delegator), GenericValue.class);
                    List<GenericEntity> keysToRemove = checkList(XmlSerializer.deserialize(removeString, delegator), GenericEntity.class);
                    Map<String, Object> storeContext = UtilMisc.toMap("entitySyncId", entitySyncId, "valuesToCreate", valuesToCreate, "valuesToStore", valuesToStore, "keysToRemove", keysToRemove, "userLogin", userLogin);
                    // store the value(s)
                    Map<String, Object> storeResult = dispatcher.runSync("storeEntitySyncData", storeContext);
                    if (ServiceUtil.isError(storeResult)) {
                        throw new Exception(ServiceUtil.getErrorMessage(storeResult));
                    }
                // TODO create a response document to send back to the initial sync machine
                } catch (GenericServiceException gse) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtUnableToLoadXMLDocument", UtilMisc.toMap("entitySyncId", entitySyncId, "startTime", startTime, "errorString", gse.getMessage()), locale));
                } catch (Exception e) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtUnableToLoadXMLDocument", UtilMisc.toMap("entitySyncId", entitySyncId, "startTime", startTime, "errorString", e.getMessage()), locale));
                }
            }
        }
    } else {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtOfflineXMLFileNotFound", UtilMisc.toMap("fileName", fileName), locale));
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Element(org.w3c.dom.Element) IOException(java.io.IOException) Document(org.w3c.dom.Document) URL(java.net.URL) UtilURL(org.apache.ofbiz.base.util.UtilURL) SyncAbortException(org.apache.ofbiz.entityext.synchronization.EntitySyncContext.SyncAbortException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) SerializeException(org.apache.ofbiz.entity.serialize.SerializeException) SyncErrorException(org.apache.ofbiz.entityext.synchronization.EntitySyncContext.SyncErrorException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) SAXException(org.xml.sax.SAXException) SAXException(org.xml.sax.SAXException) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntity(org.apache.ofbiz.entity.GenericEntity) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Aggregations

Delegator (org.apache.ofbiz.entity.Delegator)869 GenericValue (org.apache.ofbiz.entity.GenericValue)721 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)611 Locale (java.util.Locale)485 HashMap (java.util.HashMap)328 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)324 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)278 BigDecimal (java.math.BigDecimal)205 LinkedList (java.util.LinkedList)166 Timestamp (java.sql.Timestamp)163 GeneralException (org.apache.ofbiz.base.util.GeneralException)130 IOException (java.io.IOException)117 Map (java.util.Map)113 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)61 Security (org.apache.ofbiz.security.Security)60 HttpSession (javax.servlet.http.HttpSession)59 Properties (java.util.Properties)37 UtilProperties (org.apache.ofbiz.base.util.UtilProperties)37 EntityUtilProperties (org.apache.ofbiz.entity.util.EntityUtilProperties)35 EntityListIterator (org.apache.ofbiz.entity.util.EntityListIterator)33