From 6786aa4dbcfedc0bb5b53445ea3a7a63e458f56c Mon Sep 17 00:00:00 2001 From: Adrian Crum Date: Sun, 9 Aug 2009 18:04:26 +0000 Subject: [PATCH] Refactored GenericDelegator: 1. Converted GenericDelegator to an interface. We already have DelegatorInterface, but it isn't being used anywhere. Removed DelegatorInterface.java. 2. Extracted the static, cached data from the GenericDelegator implementation and put it in its own class - DelegatorData. The GenericDelegator implementation holds a reference to the DelegatorData instance. This makes it possible to have per-thread instances of GenericDelegator. 3. Replaced the ThreadLocal variables with regular variables. ThreadLocal variables are no longer needed. Client code doesn't need to be concerned with pushing and popping the GenericDelegator state. This commit paves the way for the forthcoming ExecutionContext. User modifications will have to replace GenericDelegator.getGenericDelegator(...) with DelegatorFactory.getGenericDelegator(...). Also, replace the push code with the new setXxx methods, and remove the pop code. If modifications used DelegatorInterface, replace that with GenericDelegator. Aside from those changes, this commit is backwards compatible. git-svn-id: https://svn.apache.org/repos/asf/ofbiz/trunk@802567 13f79535-47bb-0310-9956-ffa450edef68 --- .../order/shoppingcart/CartEventListener.java | 3 +- .../order/shoppingcart/ShoppingCart.java | 3 +- .../order/shoppingcart/ShoppingCartItem.java | 3 +- .../shipment/packing/PackingSession.java | 3 +- .../shipment/verify/VerifyPickSession.java | 3 +- .../weightPackage/WeightPackageSession.java | 3 +- .../catalina/container/CatalinaContainer.java | 3 +- .../src/org/ofbiz/entity/DelegatorData.java | 110 + .../org/ofbiz/entity/DelegatorFactory.java | 44 + .../src/org/ofbiz/entity/DelegatorImpl.java | 2726 +++++++++++ .../org/ofbiz/entity/DelegatorInterface.java | 236 - .../org/ofbiz/entity/GenericDelegator.java | 3977 ++++------------- .../src/org/ofbiz/entity/GenericEntity.java | 10 +- .../org/ofbiz/entity/cache/AbstractCache.java | 3 +- .../ofbiz/entity/condition/EntityExpr.java | 3 +- .../org/ofbiz/entity/finder/ListFinder.java | 3 +- .../data/EntityDataLoadContainer.java | 3 +- .../synchronization/EntitySyncContext.java | 3 +- .../synchronization/EntitySyncServices.java | 3 +- .../org/ofbiz/guiapp/xui/XuiContainer.java | 3 +- .../method/entityops/EntityCount.java | 3 +- .../minilang/method/entityops/EntityData.java | 3 +- .../minilang/method/entityops/FindByAnd.java | 3 +- .../method/entityops/FindByPrimaryKey.java | 3 +- .../org/ofbiz/service/ServiceDispatcher.java | 15 +- .../ofbiz/service/mail/JavaMailContainer.java | 3 +- .../service/rmi/RmiServiceContainer.java | 3 +- .../org/ofbiz/testtools/ModelTestSuite.java | 3 +- .../ofbiz/webapp/control/ContextFilter.java | 3 +- .../ofbiz/webapp/control/ControlServlet.java | 25 +- .../ofbiz/webapp/control/RequestHandler.java | 4 +- .../org/ofbiz/webapp/event/CoreEvents.java | 3 +- .../webapp/event/ServiceStreamHandler.java | 3 +- .../webapp/event/XmlRpcEventHandler.java | 3 +- .../org/ofbiz/webapp/stats/ServerHitBin.java | 3 +- .../org/ofbiz/webapp/stats/VisitHandler.java | 5 +- .../ofbiz/webapp/webdav/WebDavServlet.java | 3 +- .../webslinger/WebslingerContextMapper.java | 5 +- .../org/ofbiz/webtools/WebToolsServices.java | 3 +- .../ofbiz/shark/audit/AuditEntityObject.java | 3 +- .../ofbiz/shark/container/SharkContainer.java | 3 +- .../shark/instance/InstanceEntityObject.java | 3 +- .../shark/requester/AbstractRequester.java | 3 +- .../ofbiz/webpos/session/WebPosSession.java | 3 +- .../ofbiz/workflow/definition/XpdlReader.java | 3 +- 45 files changed, 3786 insertions(+), 3473 deletions(-) create mode 100644 framework/entity/src/org/ofbiz/entity/DelegatorData.java create mode 100644 framework/entity/src/org/ofbiz/entity/DelegatorFactory.java create mode 100644 framework/entity/src/org/ofbiz/entity/DelegatorImpl.java delete mode 100644 framework/entity/src/org/ofbiz/entity/DelegatorInterface.java diff --git a/applications/order/src/org/ofbiz/order/shoppingcart/CartEventListener.java b/applications/order/src/org/ofbiz/order/shoppingcart/CartEventListener.java index 61370d94f5..8f34b0e1f7 100644 --- a/applications/order/src/org/ofbiz/order/shoppingcart/CartEventListener.java +++ b/applications/order/src/org/ofbiz/order/shoppingcart/CartEventListener.java @@ -28,6 +28,7 @@ import javax.servlet.http.HttpSessionListener; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.webapp.stats.VisitHandler; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; @@ -58,7 +59,7 @@ public class CartEventListener implements HttpSessionListener { String delegatorName = (String) session.getAttribute("delegatorName"); GenericDelegator delegator = null; if (UtilValidate.isNotEmpty(delegatorName)) { - delegator = GenericDelegator.getGenericDelegator(delegatorName); + delegator = DelegatorFactory.getGenericDelegator(delegatorName); } if (delegator == null) { Debug.logError("Could not find delegator with delegatorName in session, not saving abandoned cart info.", module); diff --git a/applications/order/src/org/ofbiz/order/shoppingcart/ShoppingCart.java b/applications/order/src/org/ofbiz/order/shoppingcart/ShoppingCart.java index 0a0ecfc6f9..2e66441491 100644 --- a/applications/order/src/org/ofbiz/order/shoppingcart/ShoppingCart.java +++ b/applications/order/src/org/ofbiz/order/shoppingcart/ShoppingCart.java @@ -21,6 +21,7 @@ package org.ofbiz.order.shoppingcart; import javolution.util.FastList; import javolution.util.FastMap; import org.ofbiz.base.util.*; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericPK; @@ -275,7 +276,7 @@ public class ShoppingCart implements Serializable { public GenericDelegator getDelegator() { if (delegator == null) { - delegator = GenericDelegator.getGenericDelegator(delegatorName); + delegator = DelegatorFactory.getGenericDelegator(delegatorName); } return delegator; } diff --git a/applications/order/src/org/ofbiz/order/shoppingcart/ShoppingCartItem.java b/applications/order/src/org/ofbiz/order/shoppingcart/ShoppingCartItem.java index da79c410b4..b46c70b8e8 100644 --- a/applications/order/src/org/ofbiz/order/shoppingcart/ShoppingCartItem.java +++ b/applications/order/src/org/ofbiz/order/shoppingcart/ShoppingCartItem.java @@ -41,6 +41,7 @@ import org.ofbiz.base.util.UtilFormatOut; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilProperties; import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericPK; @@ -2406,7 +2407,7 @@ public class ShoppingCartItem implements java.io.Serializable { if (UtilValidate.isEmpty(delegatorName)) { throw new IllegalStateException("Bad delegator name"); } - delegator = GenericDelegator.getGenericDelegator(delegatorName); + delegator = DelegatorFactory.getGenericDelegator(delegatorName); } return delegator; } diff --git a/applications/product/src/org/ofbiz/shipment/packing/PackingSession.java b/applications/product/src/org/ofbiz/shipment/packing/PackingSession.java index 6a717d0c1f..124ee5b18e 100644 --- a/applications/product/src/org/ofbiz/shipment/packing/PackingSession.java +++ b/applications/product/src/org/ofbiz/shipment/packing/PackingSession.java @@ -35,6 +35,7 @@ import org.ofbiz.base.util.GeneralException; import org.ofbiz.base.util.UtilFormatOut; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; @@ -500,7 +501,7 @@ public class PackingSession implements java.io.Serializable { public GenericDelegator getDelegator() { if (_delegator == null) { - _delegator = GenericDelegator.getGenericDelegator(delegatorName); + _delegator = DelegatorFactory.getGenericDelegator(delegatorName); } return _delegator; } diff --git a/applications/product/src/org/ofbiz/shipment/verify/VerifyPickSession.java b/applications/product/src/org/ofbiz/shipment/verify/VerifyPickSession.java index 173a4b497a..06227d26ef 100644 --- a/applications/product/src/org/ofbiz/shipment/verify/VerifyPickSession.java +++ b/applications/product/src/org/ofbiz/shipment/verify/VerifyPickSession.java @@ -32,6 +32,7 @@ import org.ofbiz.base.util.GeneralException; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilProperties; import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; @@ -76,7 +77,7 @@ public class VerifyPickSession implements Serializable { public GenericDelegator getDelegator() { if (_delegator == null) { - _delegator = GenericDelegator.getGenericDelegator(delegatorName); + _delegator = DelegatorFactory.getGenericDelegator(delegatorName); } return _delegator; } diff --git a/applications/product/src/org/ofbiz/shipment/weightPackage/WeightPackageSession.java b/applications/product/src/org/ofbiz/shipment/weightPackage/WeightPackageSession.java index 62311f81e9..805cadc9c6 100644 --- a/applications/product/src/org/ofbiz/shipment/weightPackage/WeightPackageSession.java +++ b/applications/product/src/org/ofbiz/shipment/weightPackage/WeightPackageSession.java @@ -34,6 +34,7 @@ import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilNumber; import org.ofbiz.base.util.UtilProperties; import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; @@ -102,7 +103,7 @@ public class WeightPackageSession implements Serializable { public GenericDelegator getDelegator() { if (_delegator == null) { - _delegator = GenericDelegator.getGenericDelegator(delegatorName); + _delegator = DelegatorFactory.getGenericDelegator(delegatorName); } return _delegator; } diff --git a/framework/catalina/src/org/ofbiz/catalina/container/CatalinaContainer.java b/framework/catalina/src/org/ofbiz/catalina/container/CatalinaContainer.java index 03fd87ac1a..6a3ef20ea5 100644 --- a/framework/catalina/src/org/ofbiz/catalina/container/CatalinaContainer.java +++ b/framework/catalina/src/org/ofbiz/catalina/container/CatalinaContainer.java @@ -36,6 +36,7 @@ import org.ofbiz.base.container.ContainerConfig; import org.ofbiz.base.container.ContainerException; import org.ofbiz.base.container.ContainerConfig.Container.Property; import org.ofbiz.base.util.*; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.apache.catalina.Cluster; @@ -168,7 +169,7 @@ public class CatalinaContainer implements Container { //int debug = ContainerConfig.getPropertyValue(cc, "debug", 0); // grab some global context settings - this.delegator = GenericDelegator.getGenericDelegator(ContainerConfig.getPropertyValue(cc, "delegator-name", "default")); + this.delegator = DelegatorFactory.getGenericDelegator(ContainerConfig.getPropertyValue(cc, "delegator-name", "default")); this.contextReloadable = ContainerConfig.getPropertyValue(cc, "apps-context-reloadable", false); this.crossContext = ContainerConfig.getPropertyValue(cc, "apps-cross-context", true); this.distribute = ContainerConfig.getPropertyValue(cc, "apps-distributable", true); diff --git a/framework/entity/src/org/ofbiz/entity/DelegatorData.java b/framework/entity/src/org/ofbiz/entity/DelegatorData.java new file mode 100644 index 0000000000..0a62bdf216 --- /dev/null +++ b/framework/entity/src/org/ofbiz/entity/DelegatorData.java @@ -0,0 +1,110 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.entity; + +import java.util.Map; + +import javolution.util.FastMap; + +import org.ofbiz.base.util.Debug; +import org.ofbiz.entity.cache.Cache; +import org.ofbiz.entity.config.DelegatorInfo; +import org.ofbiz.entity.config.EntityConfigUtil; +import org.ofbiz.entity.eca.EntityEcaHandler; +import org.ofbiz.entity.model.ModelGroupReader; +import org.ofbiz.entity.model.ModelReader; +import org.ofbiz.entity.util.DistributedCacheClear; +import org.ofbiz.entity.util.EntityCrypto; +import org.ofbiz.entity.util.SequenceUtil; + +/** Data source for the DelegatorImpl Class. */ +public class DelegatorData implements Cloneable { + + public static final String module = DelegatorData.class.getName(); + /** + * the delegatorDataCache will now be a HashMap, allowing reload of + * definitions, but the delegator will always be the same object for the + * given name + */ + protected static final Map delegatorDataCache = FastMap.newInstance(); + + /** + * keeps a list of field key sets used in the by and cache, a Set (of Sets + * of fieldNames) for each entityName + */ + protected Map andCacheFieldSets = FastMap.newInstance(); + protected Cache cache = null; + protected EntityCrypto crypto = null; + protected DelegatorInfo delegatorInfo = null; + protected String delegatorName = null; + protected DistributedCacheClear distributedCacheClear = null; + protected EntityEcaHandler entityEcaHandler = null; + protected ModelGroupReader modelGroupReader = null; + protected ModelReader modelReader = null; + protected String originalDelegatorName = null; + protected SequenceUtil sequencer = null; + protected boolean initialized = false; + + public static synchronized DelegatorData getInstance(String delegatorName) throws GenericEntityException { + if (delegatorName == null) { + delegatorName = "default"; + Debug.logWarning(new Exception("Location where getting delegator with null name"), "Got a getGenericDelegator call with a null delegatorName, assuming \"default\" for the name.", module); + } + DelegatorData delegatorData = delegatorDataCache.get(delegatorName); + if (delegatorData == null) { + if (Debug.infoOn()) { + Debug.logInfo("Creating new delegator data instance [" + delegatorName + "] (" + Thread.currentThread().getName() + ")", module); + } + delegatorData = new DelegatorData(delegatorName); + delegatorDataCache.put(delegatorName, delegatorData); + } + return delegatorData; + } + + /** Only allow creation through the factory method */ + protected DelegatorData() { + } + + /** Only allow creation through the factory method */ + protected DelegatorData(String delegatorName) throws GenericEntityException { + this.delegatorName = delegatorName; + this.originalDelegatorName = delegatorName; + this.modelReader = ModelReader.getModelReader(delegatorName); + this.modelGroupReader = ModelGroupReader.getModelGroupReader(delegatorName); + this.cache = new Cache(delegatorName); + this.delegatorInfo = EntityConfigUtil.getDelegatorInfo(this.delegatorName); + } + + @Override + protected Object clone() { + DelegatorData delegatorData = new DelegatorData(); + delegatorData.modelReader = this.modelReader; + delegatorData.modelGroupReader = this.modelGroupReader; + delegatorData.delegatorName = this.delegatorName; + delegatorData.delegatorInfo = this.delegatorInfo; + delegatorData.cache = this.cache; + delegatorData.andCacheFieldSets = this.andCacheFieldSets; + delegatorData.distributedCacheClear = this.distributedCacheClear; + delegatorData.originalDelegatorName = this.originalDelegatorName; + delegatorData.entityEcaHandler = this.entityEcaHandler; + delegatorData.sequencer = this.sequencer; + delegatorData.crypto = this.crypto; + return delegatorData; + } +} diff --git a/framework/entity/src/org/ofbiz/entity/DelegatorFactory.java b/framework/entity/src/org/ofbiz/entity/DelegatorFactory.java new file mode 100644 index 0000000000..a376ad86cc --- /dev/null +++ b/framework/entity/src/org/ofbiz/entity/DelegatorFactory.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.entity; + +import org.ofbiz.base.util.Debug; + +/** GenericDelegator Factory Class. */ +public class DelegatorFactory { + + public static final String module = DelegatorFactory.class.getName(); + + public static GenericDelegator getGenericDelegator(String delegatorName) { + if (delegatorName == null) { + delegatorName = "default"; + Debug.logWarning(new Exception("Location where getting delegator with null name"), "Got a getGenericDelegator call with a null delegatorName, assuming default for the name.", module); + } + DelegatorData delegatorData = null; + try { + delegatorData = DelegatorData.getInstance(delegatorName); + } catch (GenericEntityException e) { + Debug.logError(e, "Could not create delegator with name \"" + delegatorName + "\": ", module); + } + if (delegatorData != null) { + return new DelegatorImpl(delegatorData); + } + return null; + } +} diff --git a/framework/entity/src/org/ofbiz/entity/DelegatorImpl.java b/framework/entity/src/org/ofbiz/entity/DelegatorImpl.java new file mode 100644 index 0000000000..7ca7ef14cf --- /dev/null +++ b/framework/entity/src/org/ofbiz/entity/DelegatorImpl.java @@ -0,0 +1,2726 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.entity; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.net.URL; +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +import javax.xml.parsers.ParserConfigurationException; + +import javolution.util.FastList; +import javolution.util.FastMap; + +import org.ofbiz.base.util.Debug; +import org.ofbiz.base.util.GeneralRuntimeException; +import org.ofbiz.base.util.UtilDateTime; +import org.ofbiz.base.util.UtilFormatOut; +import org.ofbiz.base.util.UtilMisc; +import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.base.util.UtilXml; +import org.ofbiz.base.util.cache.CacheLine; +import org.ofbiz.base.util.cache.UtilCache; +import org.ofbiz.entity.cache.Cache; +import org.ofbiz.entity.condition.EntityCondition; +import org.ofbiz.entity.condition.EntityConditionList; +import org.ofbiz.entity.condition.EntityExpr; +import org.ofbiz.entity.condition.EntityOperator; +import org.ofbiz.entity.config.DatasourceInfo; +import org.ofbiz.entity.config.DelegatorInfo; +import org.ofbiz.entity.config.EntityConfigUtil; +import org.ofbiz.entity.datasource.GenericHelper; +import org.ofbiz.entity.datasource.GenericHelperFactory; +import org.ofbiz.entity.eca.EntityEcaHandler; +import org.ofbiz.entity.model.DynamicViewEntity; +import org.ofbiz.entity.model.ModelEntity; +import org.ofbiz.entity.model.ModelEntityChecker; +import org.ofbiz.entity.model.ModelField; +import org.ofbiz.entity.model.ModelFieldType; +import org.ofbiz.entity.model.ModelFieldTypeReader; +import org.ofbiz.entity.model.ModelGroupReader; +import org.ofbiz.entity.model.ModelKeyMap; +import org.ofbiz.entity.model.ModelReader; +import org.ofbiz.entity.model.ModelRelation; +import org.ofbiz.entity.model.ModelViewEntity; +import org.ofbiz.entity.serialize.SerializeException; +import org.ofbiz.entity.serialize.XmlSerializer; +import org.ofbiz.entity.transaction.GenericTransactionException; +import org.ofbiz.entity.transaction.TransactionUtil; +import org.ofbiz.entity.util.DistributedCacheClear; +import org.ofbiz.entity.util.EntityCrypto; +import org.ofbiz.entity.util.EntityFindOptions; +import org.ofbiz.entity.util.EntityListIterator; +import org.ofbiz.entity.util.SequenceUtil; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.xml.sax.SAXException; + +/** + * Implementation of the GenericDelegator interface. The class + * contains a reference to a shared instance of DelegatorData - + * making it possible to have per-thread instances of this class while + * sharing common delegator data. + */ +public class DelegatorImpl implements Cloneable, GenericDelegator { + + protected static class EntityEcaRuleRunner { + protected EntityEcaHandler entityEcaHandler; + protected Map> eventMap; + + protected EntityEcaRuleRunner(EntityEcaHandler entityEcaHandler, Map> eventMap) { + this.entityEcaHandler = entityEcaHandler; + this.eventMap = eventMap; + } + + protected void evalRules(String event, String currentOperation, GenericEntity value, boolean isError) throws GenericEntityException { + if (entityEcaHandler == null) { + return; + } + entityEcaHandler.evalRules(currentOperation, eventMap, event, value, isError); + } + } + + private enum OperationType { + DELETE, INSERT, UPDATE + } + + public class TestOperation { + private final OperationType operation; + private final GenericValue value; + + public TestOperation(OperationType operation, GenericValue value) { + this.operation = operation; + this.value = value; + } + + public OperationType getOperation() { + return operation; + } + + public GenericValue getValue() { + return value; + } + } + + /** + * This flag is only here for lower level technical testing, it shouldn't be + * user configurable (or at least I don't think so yet); when true all + * operations without a transaction will be wrapped in one; seems to be + * necessary for some (all?) XA aware connection pools, and should improve + * overall stability and consistency + */ + public static final boolean alwaysUseTransaction = true; + + public static final String module = DelegatorImpl.class.getName(); + + protected static EntityEcaRuleRunner createEntityEcaRuleRunner(EntityEcaHandler entityEcaHandler, String entityName) { + return new EntityEcaRuleRunner(entityEcaHandler, entityEcaHandler != null ? entityEcaHandler.getEntityEventMap(entityName) : null); + } + + protected final DelegatorData delegatorData; + + protected Locale locale = Locale.getDefault(); + + private boolean testMode = false; + + private List testOperations = null; + + private boolean testRollbackInProgress = false; + + protected String sessionIdentifier = ""; + + protected String userIdentifier = ""; + + protected DelegatorImpl(DelegatorData delegatorData) { + this.delegatorData = delegatorData; + if (!delegatorData.initialized) { + synchronized (delegatorData) { + if (delegatorData.initialized) { + return; + } + // do the entity model check + List warningList = FastList.newInstance(); + Debug.logImportant("Doing entity definition check...", module); + try { + ModelEntityChecker.checkEntities(this, warningList); + } catch (GenericEntityException e) { + Debug.logError(e, "Error while checking entities: ", module); + } + if (warningList.size() > 0) { + Debug.logWarning("=-=-=-=-= Found " + warningList.size() + " warnings when checking the entity definitions:", module); + for (String warning : warningList) { + Debug.logWarning(warning, module); + } + } + + // initialize helpers by group + Set groupNames = getModelGroupReader().getGroupNames(this.delegatorData.delegatorName); + Iterator groups = UtilMisc.toIterator(groupNames); + while (groups != null && groups.hasNext()) { + String groupName = groups.next(); + String helperName = this.getGroupHelperName(groupName); + + if (Debug.infoOn()) + Debug.logInfo("Delegator \"" + this.delegatorData.delegatorName + "\" initializing helper \"" + helperName + "\" for entity group \"" + groupName + "\".", module); + TreeSet helpersDone = new TreeSet(); + if (helperName != null && helperName.length() > 0) { + // make sure each helper is only loaded once + if (helpersDone.contains(helperName)) { + if (Debug.infoOn()) + Debug.logInfo("Helper \"" + helperName + "\" already initialized, not re-initializing.", module); + continue; + } + helpersDone.add(helperName); + // pre-load field type defs, the return value is ignored + ModelFieldTypeReader.getModelFieldTypeReader(helperName); + // get the helper and if configured, do the datasource check + GenericHelper helper = GenericHelperFactory.getHelper(helperName); + + DatasourceInfo datasourceInfo = EntityConfigUtil.getDatasourceInfo(helperName); + if (datasourceInfo.checkOnStart) { + if (Debug.infoOn()) + Debug.logInfo("Doing database check as requested in entityengine.xml with addMissing=" + datasourceInfo.addMissingOnStart, module); + try { + helper.checkDataSource(this.getModelEntityMapByGroup(groupName), null, datasourceInfo.addMissingOnStart); + } catch (GenericEntityException e) { + Debug.logWarning(e, e.getMessage(), module); + } + } + } + } + // Let other instances know the shared data is ready to use + this.delegatorData.initialized = true; + // setup the crypto class + this.delegatorData.crypto = new EntityCrypto(this); + + // time to do some tricks with manual class loading that resolves + // circular dependencies, like calling services... + ClassLoader loader = Thread.currentThread().getContextClassLoader(); + + // if useDistributedCacheClear is false do nothing since the + // distributedCacheClear member field with a null value will cause the + // dcc code to do nothing + if (this.delegatorData.delegatorInfo.useDistributedCacheClear) { + // initialize the distributedCacheClear mechanism + String distributedCacheClearClassName = this.delegatorData.delegatorInfo.distributedCacheClearClassName; + + try { + Class dccClass = loader.loadClass(distributedCacheClearClassName); + this.delegatorData.distributedCacheClear = (DistributedCacheClear) dccClass.newInstance(); + this.delegatorData.distributedCacheClear.setDelegator(this, this.delegatorData.delegatorInfo.distributedCacheClearUserLoginId); + } catch (ClassNotFoundException e) { + Debug.logWarning(e, "DistributedCacheClear class with name " + distributedCacheClearClassName + " was not found, distributed cache clearing will be disabled", module); + } catch (InstantiationException e) { + Debug.logWarning(e, "DistributedCacheClear class with name " + distributedCacheClearClassName + " could not be instantiated, distributed cache clearing will be disabled", module); + } catch (IllegalAccessException e) { + Debug.logWarning(e, "DistributedCacheClear class with name " + distributedCacheClearClassName + " could not be accessed (illegal), distributed cache clearing will be disabled", module); + } catch (ClassCastException e) { + Debug.logWarning(e, "DistributedCacheClear class with name " + distributedCacheClearClassName + " does not implement the DistributedCacheClear interface, distributed cache clearing will be disabled", module); + } + } else { + Debug.logInfo("Distributed Cache Clear System disabled for delegator [" + this.delegatorData.delegatorName + "]", module); + } + + // setup the Entity ECA Handler + initEntityEcaHandler(); + } + } + } + + protected void absorbList(List lst) { + if (lst == null) + return; + for (GenericValue value : lst) { + value.setDelegator(this); + } + } + + public void clearAllCacheLinesByDummyPK(Collection dummyPKs) { + if (dummyPKs == null) + return; + for (GenericEntity entity : dummyPKs) { + this.clearCacheLineFlexible(entity); + } + } + + public void clearAllCacheLinesByValue(Collection values) { + if (values == null) + return; + for (GenericValue value : values) { + this.clearCacheLine(value); + } + } + + public void clearAllCaches() { + this.clearAllCaches(true); + } + + public void clearAllCaches(boolean distribute) { + this.delegatorData.cache.clear(); + if (distribute && this.delegatorData.distributedCacheClear != null) { + this.delegatorData.distributedCacheClear.clearAllCaches(); + } + } + + public void clearCacheLine(GenericPK primaryKey) { + this.clearCacheLine(primaryKey, true); + } + + public void clearCacheLine(GenericPK primaryKey, boolean distribute) { + if (primaryKey == null) + return; + + // if never cached, then don't bother clearing + if (primaryKey.getModelEntity().getNeverCache()) + return; + + this.delegatorData.cache.remove(primaryKey); + + if (distribute && this.delegatorData.distributedCacheClear != null) { + this.delegatorData.distributedCacheClear.distributedClearCacheLine(primaryKey); + } + } + + public void clearCacheLine(GenericValue value) { + this.clearCacheLine(value, true); + } + + public void clearCacheLine(GenericValue value, boolean distribute) { + // TODO: make this a bit more intelligent by passing in the operation + // being done (create, update, remove) so we can not do unnecessary + // cache clears... + // for instance: + // on create don't clear by primary cache (and won't clear original + // values because there won't be any) + // on remove don't clear by and for new values, but do for original + // values + + // Debug.logInfo("running clearCacheLine for value: " + value + ", + // distribute: " + distribute, module); + if (value == null) + return; + + // if never cached, then don't bother clearing + if (value.getModelEntity().getNeverCache()) + return; + + this.delegatorData.cache.remove(value); + + if (distribute && this.delegatorData.distributedCacheClear != null) { + this.delegatorData.distributedCacheClear.distributedClearCacheLine(value); + } + } + + public void clearCacheLine(String entityName) { + this.delegatorData.cache.remove(entityName); + } + + public void clearCacheLine(String entityName, Map fields) { + // if no fields passed, do the all cache quickly and return + if (fields == null) { + this.delegatorData.cache.remove(entityName); + return; + } + + ModelEntity entity = this.getModelEntity(entityName); + if (entity == null) { + throw new IllegalArgumentException("[GenericDelegator.clearCacheLine] could not find entity for entityName: " + entityName); + } + // if never cached, then don't bother clearing + if (entity.getNeverCache()) + return; + + GenericValue dummyValue = GenericValue.create(entity, fields); + dummyValue.setDelegator(this); + this.clearCacheLineFlexible(dummyValue); + } + + public void clearCacheLine(String entityName, Object... fields) { + clearCacheLine(entityName, UtilMisc. toMap(fields)); + } + + public void clearCacheLineByCondition(String entityName, EntityCondition condition) { + clearCacheLineByCondition(entityName, condition, true); + } + + public void clearCacheLineByCondition(String entityName, EntityCondition condition, boolean distribute) { + if (entityName != null) { + // if never cached, then don't bother clearing + if (getModelEntity(entityName).getNeverCache()) + return; + + this.delegatorData.cache.remove(entityName, condition); + + if (distribute && this.delegatorData.distributedCacheClear != null) { + this.delegatorData.distributedCacheClear.distributedClearCacheLineByCondition(entityName, condition); + } + } + } + + public void clearCacheLineFlexible(GenericEntity dummyPK) { + this.clearCacheLineFlexible(dummyPK, true); + } + + public void clearCacheLineFlexible(GenericEntity dummyPK, boolean distribute) { + if (dummyPK != null) { + // if never cached, then don't bother clearing + if (dummyPK.getModelEntity().getNeverCache()) + return; + + this.delegatorData.cache.remove(dummyPK); + + if (distribute && this.delegatorData.distributedCacheClear != null) { + this.delegatorData.distributedCacheClear.distributedClearCacheLineFlexible(dummyPK); + } + } + } + + @SuppressWarnings("unchecked") + protected void clearCacheValues(UtilCache cache, String entityName, EntityCondition condition) { + Iterator iterator = cache.cacheLineTable.values().iterator(); + while (iterator.hasNext()) { + CacheLine line = (CacheLine) iterator.next(); + GenericValue value = (GenericValue) line.getValue(); + if (value != null && value.getEntityName().equals(entityName) && condition.entityMatches(value)) { + iterator.remove(); + } + } + } + + @Override + protected Object clone() { + return this.cloneDelegator(this.delegatorData.delegatorName); + } + + public GenericDelegator cloneDelegator() { + return this.cloneDelegator(this.delegatorData.delegatorName); + } + + public GenericDelegator cloneDelegator(String delegatorName) { + // creates an exact clone of the delegator; except for the sequencer + // note that this will not be cached and should be used only when + // needed to change something for single instance (use). + DelegatorImpl newDelegator = new DelegatorImpl((DelegatorData) this.delegatorData.clone()); + newDelegator.delegatorData.delegatorName = delegatorName; + // In case this delegator is in testMode give it a reference to + // the rollback list + newDelegator.testOperations = this.testOperations; + // not setting the sequencer so that we have unique sequences. + newDelegator.delegatorData.sequencer = null; + return newDelegator; + } + + public GenericValue create(GenericPK primaryKey) throws GenericEntityException { + return this.create(primaryKey, true); + } + + public GenericValue create(GenericPK primaryKey, boolean doCacheClear) throws GenericEntityException { + if (primaryKey == null) { + throw new GenericEntityException("Cannot create from a null primaryKey"); + } + + return this.create(GenericValue.create(primaryKey), doCacheClear); + } + + public GenericValue create(GenericValue value) throws GenericEntityException { + return this.create(value, true); + } + + public GenericValue create(GenericValue value, boolean doCacheClear) throws GenericEntityException { + boolean beganTransaction = false; + try { + if (alwaysUseTransaction) { + beganTransaction = TransactionUtil.begin(); + } + + EntityEcaRuleRunner ecaRunner = this.getEcaRuleRunner(value.getEntityName()); + ecaRunner.evalRules(EntityEcaHandler.EV_VALIDATE, EntityEcaHandler.OP_CREATE, value, false); + + if (value == null) { + throw new GenericEntityException("Cannot create a null value"); + } + GenericHelper helper = getEntityHelper(value.getEntityName()); + + ecaRunner.evalRules(EntityEcaHandler.EV_RUN, EntityEcaHandler.OP_CREATE, value, false); + + value.setDelegator(this); + this.encryptFields(value); + + // if audit log on for any fields, save new value with no old value + // because it's a create + if (value != null && value.getModelEntity().getHasFieldWithAuditLog()) { + createEntityAuditLogAll(value, false, false); + } + + value = helper.create(value); + + if (testMode) { + storeForTestRollback(new TestOperation(OperationType.INSERT, value)); + } + if (value != null) { + value.setDelegator(this); + if (value.lockEnabled()) { + refresh(value, doCacheClear); + } else { + if (doCacheClear) { + ecaRunner.evalRules(EntityEcaHandler.EV_CACHE_CLEAR, EntityEcaHandler.OP_CREATE, value, false); + this.clearCacheLine(value); + } + } + } + + ecaRunner.evalRules(EntityEcaHandler.EV_RETURN, EntityEcaHandler.OP_CREATE, value, false); + + return value; + } catch (GenericEntityException e) { + String errMsg = "Failure in create operation for entity [" + value.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; + Debug.logError(e, errMsg, module); + try { + // only rollback the transaction if we started one... + TransactionUtil.rollback(beganTransaction, errMsg, e); + } catch (GenericEntityException e2) { + Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); + } + // after rolling back, rethrow the exception + throw e; + } finally { + // only commit the transaction if we started one... this will throw + // an exception if it fails + TransactionUtil.commit(beganTransaction); + } + } + + public GenericValue create(String entityName, Map fields) throws GenericEntityException { + if (entityName == null || fields == null) { + return null; + } + ModelEntity entity = this.getModelReader().getModelEntity(entityName); + GenericValue genericValue = GenericValue.create(entity, fields); + + return this.create(genericValue, true); + } + + public GenericValue create(String entityName, Object... fields) throws GenericEntityException { + return create(entityName, UtilMisc. toMap(fields)); + } + + protected void createEntityAuditLogAll(GenericValue value, boolean isUpdate, boolean isRemove) throws GenericEntityException { + for (ModelField mf : value.getModelEntity().getFieldsUnmodifiable()) { + if (mf.getEnableAuditLog()) { + createEntityAuditLogSingle(value, mf, isUpdate, isRemove); + } + } + } + + protected void createEntityAuditLogSingle(GenericValue value, ModelField mf, boolean isUpdate, boolean isRemove) throws GenericEntityException { + if (value == null || mf == null || !mf.getEnableAuditLog() || this.testRollbackInProgress) { + return; + } + + GenericValue entityAuditLog = this.makeValue("EntityAuditLog"); + entityAuditLog.set("auditHistorySeqId", this.getNextSeqId("EntityAuditLog")); + entityAuditLog.set("changedEntityName", value.getEntityName()); + entityAuditLog.set("changedFieldName", mf.getName()); + + String pkCombinedValueText = value.getPkShortValueString(); + if (pkCombinedValueText.length() > 250) { + // uh-oh, the string is too long! + pkCombinedValueText = pkCombinedValueText.substring(0, 250); + } + entityAuditLog.set("pkCombinedValueText", pkCombinedValueText); + + GenericValue oldGv = null; + if (isUpdate) { + // it's an update, get it from the database + oldGv = this.findOne(value.getEntityName(), value.getPrimaryKey(), false); + } else if (isRemove) { + oldGv = value; + } + if (oldGv == null) { + if (isUpdate || isRemove) { + entityAuditLog.set("oldValueText", "[ERROR] Old value not found even though it was an update or remove"); + } + } else { + // lookup old value + String oldValueText = null; + Object oldValue = oldGv.get(mf.getName()); + if (oldValue != null) { + oldValueText = oldValue.toString(); + if (oldValueText.length() > 250) { + oldValueText = oldValueText.substring(0, 250); + } + } + entityAuditLog.set("oldValueText", oldValueText); + } + + if (!isRemove) { + String newValueText = null; + Object newValue = value.get(mf.getName()); + if (newValue != null) { + newValueText = newValue.toString(); + if (newValueText.length() > 250) { + newValueText = newValueText.substring(0, 250); + } + } + entityAuditLog.set("newValueText", newValueText); + } + + entityAuditLog.set("changedDate", UtilDateTime.nowTimestamp()); + entityAuditLog.set("changedByInfo", this.userIdentifier); + entityAuditLog.set("changedSessionInfo", this.sessionIdentifier); + + this.create(entityAuditLog); + } + + public GenericValue createOrStore(GenericValue value) throws GenericEntityException { + return createOrStore(value, true); + } + + public GenericValue createOrStore(GenericValue value, boolean doCacheClear) throws GenericEntityException { + boolean beganTransaction = false; + try { + if (alwaysUseTransaction) { + beganTransaction = TransactionUtil.begin(); + } + + GenericValue checkValue = this.findOne(value.getEntityName(), value.getPrimaryKey(), false); + if (checkValue != null) { + this.store(value, doCacheClear); + } else { + this.create(value, doCacheClear); + } + if (value.lockEnabled()) { + this.refresh(value); + } + + return value; + } catch (GenericEntityException e) { + String errMsg = "Failure in createOrStore operation for entity [" + value.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; + Debug.logError(e, errMsg, module); + try { + // only rollback the transaction if we started one... + TransactionUtil.rollback(beganTransaction, errMsg, e); + } catch (GenericEntityException e2) { + Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); + } + // after rolling back, rethrow the exception + throw e; + } finally { + // only commit the transaction if we started one... this will throw + // an exception if it fails + TransactionUtil.commit(beganTransaction); + } + } + + public GenericValue createSetNextSeqId(GenericValue value) throws GenericEntityException { + boolean doCacheClear = true; + + GenericHelper helper = getEntityHelper(value.getEntityName()); + // just make sure it is this delegator... + value.setDelegator(this); + // this will throw an IllegalArgumentException if the entity for the + // value does not have one pk field, or if it already has a value set + // for the one pk field + value.setNextSeqId(); + + boolean beganTransaction = false; + try { + if (alwaysUseTransaction) { + beganTransaction = TransactionUtil.begin(); + } + + EntityEcaRuleRunner ecaRunner = this.getEcaRuleRunner(value.getEntityName()); + ecaRunner.evalRules(EntityEcaHandler.EV_VALIDATE, EntityEcaHandler.OP_CREATE, value, false); + + if (value == null) { + throw new GenericEntityException("Cannot create a null value"); + } + + ecaRunner.evalRules(EntityEcaHandler.EV_RUN, EntityEcaHandler.OP_CREATE, value, false); + + value.setDelegator(this); + this.encryptFields(value); + + // if audit log on for any fields, save new value with no old value + // because it's a create + if (value != null && value.getModelEntity().getHasFieldWithAuditLog()) { + createEntityAuditLogAll(value, false, false); + } + + try { + value = helper.create(value); + + if (testMode) { + storeForTestRollback(new TestOperation(OperationType.INSERT, value)); + } + } catch (GenericEntityException e) { + // see if this was caused by an existing record before resetting + // the sequencer and trying again + // NOTE: use the helper directly so ECA rules, etc won't be run + GenericValue existingValue = helper.findByPrimaryKey(value.getPrimaryKey()); + if (existingValue == null) { + throw e; + } else { + Debug.logInfo("Error creating entity record with a sequenced value [" + value.getPrimaryKey() + "], trying again about to refresh bank for entity [" + value.getEntityName() + "]", module); + + // found an existing value... was probably a duplicate key, + // so clean things up and try again + this.delegatorData.sequencer.forceBankRefresh(value.getEntityName(), 1); + + value.setNextSeqId(); + value = helper.create(value); + Debug.logInfo("Successfully created new entity record on retry with a sequenced value [" + value.getPrimaryKey() + "], after getting refreshed bank for entity [" + value.getEntityName() + "]", module); + + if (testMode) { + storeForTestRollback(new TestOperation(OperationType.INSERT, value)); + } + } + } + + if (value != null) { + value.setDelegator(this); + if (value.lockEnabled()) { + refresh(value, doCacheClear); + } else { + if (doCacheClear) { + ecaRunner.evalRules(EntityEcaHandler.EV_CACHE_CLEAR, EntityEcaHandler.OP_CREATE, value, false); + this.clearCacheLine(value); + } + } + } + + ecaRunner.evalRules(EntityEcaHandler.EV_RETURN, EntityEcaHandler.OP_CREATE, value, false); + + return value; + } catch (GenericEntityException e) { + String errMsg = "Failure in create operation for entity [" + value.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; + Debug.logError(e, errMsg, module); + try { + // only rollback the transaction if we started one... + TransactionUtil.rollback(beganTransaction, errMsg, e); + } catch (GenericEntityException e2) { + Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); + } + // after rolling back, rethrow the exception + throw e; + } finally { + // only commit the transaction if we started one... this will throw + // an exception if it fails + TransactionUtil.commit(beganTransaction); + } + } + + public GenericValue createSingle(String entityName, Object singlePkValue) throws GenericEntityException { + if (entityName == null || singlePkValue == null) { + return null; + } + ModelEntity entity = this.getModelReader().getModelEntity(entityName); + GenericValue genericValue = GenericValue.create(entity, singlePkValue); + + return this.create(genericValue, true); + } + + public void decryptFields(GenericEntity entity) throws GenericEntityException { + ModelEntity model = entity.getModelEntity(); + String entityName = model.getEntityName(); + + Iterator i = model.getFieldsIterator(); + while (i.hasNext()) { + ModelField field = i.next(); + if (field.getEncrypt()) { + String keyName = entityName; + if (model instanceof ModelViewEntity) { + ModelViewEntity modelView = (ModelViewEntity) model; + keyName = modelView.getAliasedEntity(modelView.getAlias(field.getName()).getEntityAlias(), this.delegatorData.modelReader).getEntityName(); + } + + String encHex = (String) entity.get(field.getName()); + if (UtilValidate.isNotEmpty(encHex)) { + try { + entity.dangerousSetNoCheckButFast(field, this.delegatorData.crypto.decrypt(keyName, encHex)); + } catch (EntityCryptoException e) { + // not fatal -- allow returning of the encrypted value + Debug.logWarning(e, "Problem decrypting field [" + entityName + " / " + field.getName() + "]", module); + } + } + } + } + } + + public void decryptFields(List entities) throws GenericEntityException { + if (entities != null) { + for (GenericEntity entity : entities) { + this.decryptFields(entity); + } + } + } + + public void encryptFields(GenericEntity entity) throws GenericEntityException { + ModelEntity model = entity.getModelEntity(); + String entityName = model.getEntityName(); + + Iterator i = model.getFieldsIterator(); + while (i.hasNext()) { + ModelField field = i.next(); + if (field.getEncrypt()) { + Object obj = entity.get(field.getName()); + if (obj != null) { + if (obj instanceof String && UtilValidate.isEmpty((String) obj)) { + continue; + } + entity.dangerousSetNoCheckButFast(field, this.encryptFieldValue(entityName, obj)); + } + } + } + } + + public void encryptFields(List entities) throws GenericEntityException { + if (entities != null) { + for (GenericEntity entity : entities) { + this.encryptFields(entity); + } + } + } + + public Object encryptFieldValue(String entityName, Object fieldValue) throws EntityCryptoException { + if (fieldValue != null) { + if (fieldValue instanceof String && UtilValidate.isEmpty((String) fieldValue)) { + return fieldValue; + } + return this.delegatorData.crypto.encrypt(entityName, fieldValue); + } + return fieldValue; + } + + public EntityListIterator find(String entityName, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, Set fieldsToSelect, List orderBy, EntityFindOptions findOptions) throws GenericEntityException { + + // if there is no transaction throw an exception, we don't want to + // create a transaction here since closing it would mess up the ELI + if (!TransactionUtil.isTransactionInPlace()) { + // throw new GenericEntityException("ERROR: Cannot do a find that + // returns an EntityListIterator with no transaction in place. Wrap + // this call in a transaction."); + + // throwing an exception is a little harsh for now, just display a + // really big error message since we want to get all of these + // fixed... + Exception newE = new Exception("Stack Trace"); + Debug.logError(newE, "ERROR: Cannot do a find that returns an EntityListIterator with no transaction in place. Wrap this call in a transaction.", module); + } + + ModelEntity modelEntity = getModelReader().getModelEntity(entityName); + GenericValue dummyValue = GenericValue.create(modelEntity); + EntityEcaRuleRunner ecaRunner = this.getEcaRuleRunner(modelEntity.getEntityName()); + ecaRunner.evalRules(EntityEcaHandler.EV_VALIDATE, EntityEcaHandler.OP_FIND, dummyValue, false); + + if (whereEntityCondition != null) { + whereEntityCondition.checkCondition(modelEntity); + whereEntityCondition.encryptConditionFields(modelEntity, this); + } + if (havingEntityCondition != null) { + havingEntityCondition.checkCondition(modelEntity); + havingEntityCondition.encryptConditionFields(modelEntity, this); + } + + ecaRunner.evalRules(EntityEcaHandler.EV_RUN, EntityEcaHandler.OP_FIND, dummyValue, false); + GenericHelper helper = getEntityHelper(modelEntity.getEntityName()); + EntityListIterator eli = helper.findListIteratorByCondition(modelEntity, whereEntityCondition, havingEntityCondition, fieldsToSelect, orderBy, findOptions); + eli.setDelegator(this); + + ecaRunner.evalRules(EntityEcaHandler.EV_RETURN, EntityEcaHandler.OP_FIND, dummyValue, false); + return eli; + } + + public List findAll(String entityName) throws GenericEntityException { + return this.findList(entityName, null, null, null, null, false); + } + + public List findAll(String entityName, List orderBy) throws GenericEntityException { + return this.findList(entityName, null, null, orderBy, null, false); + } + + public List findAll(String entityName, String... orderBy) throws GenericEntityException { + return findList(entityName, null, null, Arrays.asList(orderBy), null, false); + } + + public List findAllByPrimaryKeys(Collection primaryKeys) throws GenericEntityException { + boolean beganTransaction = false; + try { + if (alwaysUseTransaction) { + beganTransaction = TransactionUtil.begin(); + } + + // TODO: add eca eval calls + // TODO: maybe this should use the internal findBy methods + if (primaryKeys == null) + return null; + List results = FastList.newInstance(); + + // from the delegator level this is complicated because different + // GenericPK + // objects in the list may correspond to different helpers + Map> pksPerHelper = FastMap.newInstance(); + for (GenericPK curPK : primaryKeys) { + String helperName = this.getEntityHelperName(curPK.getEntityName()); + List pks = pksPerHelper.get(helperName); + + if (pks == null) { + pks = FastList.newInstance(); + pksPerHelper.put(helperName, pks); + } + pks.add(curPK); + } + + for (Map.Entry> curEntry : pksPerHelper.entrySet()) { + String helperName = curEntry.getKey(); + GenericHelper helper = GenericHelperFactory.getHelper(helperName); + List values = helper.findAllByPrimaryKeys(curEntry.getValue()); + + results.addAll(values); + } + + this.decryptFields(results); + return results; + } catch (GenericEntityException e) { + String errMsg = "Failure in findAllByPrimaryKeys operation, rolling back transaction"; + Debug.logError(e, errMsg, module); + try { + // only rollback the transaction if we started one... + TransactionUtil.rollback(beganTransaction, errMsg, e); + } catch (GenericEntityException e2) { + Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); + } + // after rolling back, rethrow the exception + throw e; + } finally { + // only commit the transaction if we started one... this will throw + // an exception if it fails + TransactionUtil.commit(beganTransaction); + } + } + + public List findAllByPrimaryKeysCache(Collection primaryKeys) throws GenericEntityException { + boolean beganTransaction = false; + try { + if (alwaysUseTransaction) { + beganTransaction = TransactionUtil.begin(); + } + + // TODO: add eca eval calls + // TODO: maybe this should use the internal findBy methods + if (primaryKeys == null) + return null; + List results = FastList.newInstance(); + + // from the delegator level this is complicated because different + // GenericPK + // objects in the list may correspond to different helpers + Map> pksPerHelper = FastMap.newInstance(); + for (GenericPK curPK : primaryKeys) { + GenericValue value = this.getFromPrimaryKeyCache(curPK); + + if (value != null) { + // it is in the cache, so just put the cached value in the + // results + results.add(value); + } else { + // is not in the cache, so put in a list for a call to the + // helper + String helperName = this.getEntityHelperName(curPK.getEntityName()); + List pks = pksPerHelper.get(helperName); + + if (pks == null) { + pks = FastList.newInstance(); + pksPerHelper.put(helperName, pks); + } + pks.add(curPK); + } + } + + for (Map.Entry> curEntry : pksPerHelper.entrySet()) { + String helperName = curEntry.getKey(); + GenericHelper helper = GenericHelperFactory.getHelper(helperName); + List values = helper.findAllByPrimaryKeys(curEntry.getValue()); + + this.putAllInPrimaryKeyCache(values); + results.addAll(values); + } + + this.decryptFields(results); + return results; + } catch (GenericEntityException e) { + String errMsg = "Failure in findAllByPrimaryKeysCache operation, rolling back transaction"; + Debug.logError(e, errMsg, module); + try { + // only rollback the transaction if we started one... + TransactionUtil.rollback(beganTransaction, errMsg, e); + } catch (GenericEntityException e2) { + Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); + } + // after rolling back, rethrow the exception + throw e; + } finally { + // only commit the transaction if we started one... this will throw + // an exception if it fails + TransactionUtil.commit(beganTransaction); + } + } + + public List findAllCache(String entityName) throws GenericEntityException { + return this.findList(entityName, null, null, null, null, true); + } + + public List findAllCache(String entityName, List orderBy) throws GenericEntityException { + return this.findList(entityName, null, null, orderBy, null, true); + } + + public List findAllCache(String entityName, String... orderBy) throws GenericEntityException { + return findList(entityName, null, null, Arrays.asList(orderBy), null, true); + } + + public List findByAnd(String entityName, List expressions) throws GenericEntityException { + EntityConditionList ecl = EntityCondition.makeCondition(expressions, EntityOperator.AND); + return this.findList(entityName, ecl, null, null, null, false); + } + + public List findByAnd(String entityName, List expressions, List orderBy) throws GenericEntityException { + EntityConditionList ecl = EntityCondition.makeCondition(expressions, EntityOperator.AND); + return this.findList(entityName, ecl, null, orderBy, null, false); + } + + public List findByAnd(String entityName, Map fields) throws GenericEntityException { + EntityCondition ecl = EntityCondition.makeCondition(fields); + return this.findList(entityName, ecl, null, null, null, false); + } + + public List findByAnd(String entityName, Map fields, List orderBy) throws GenericEntityException { + EntityCondition ecl = EntityCondition.makeCondition(fields); + return this.findList(entityName, ecl, null, orderBy, null, false); + } + + public List findByAnd(String entityName, Object... fields) throws GenericEntityException { + return findByAnd(entityName, UtilMisc. toMap(fields)); + } + + public List findByAnd(String entityName, T... expressions) throws GenericEntityException { + EntityConditionList ecl = EntityCondition.makeCondition(EntityOperator.AND, expressions); + return this.findList(entityName, ecl, null, null, null, false); + } + + public List findByAndCache(String entityName, Map fields) throws GenericEntityException { + return this.findList(entityName, EntityCondition.makeCondition(fields), null, null, null, true); + } + + public List findByAndCache(String entityName, Map fields, List orderBy) throws GenericEntityException { + return this.findList(entityName, EntityCondition.makeCondition(fields), null, orderBy, null, true); + } + + public List findByAndCache(String entityName, Object... fields) throws GenericEntityException { + return this.findByAndCache(entityName, UtilMisc. toMap(fields)); + } + + public List findByCondition(String entityName, EntityCondition entityCondition, Collection fieldsToSelect, List orderBy) throws GenericEntityException { + return this.findList(entityName, entityCondition, UtilMisc.toSet(fieldsToSelect), orderBy, null, false); + } + + public List findByCondition(String entityName, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, Collection fieldsToSelect, List orderBy, EntityFindOptions findOptions) throws GenericEntityException { + boolean beganTransaction = false; + try { + if (alwaysUseTransaction) { + beganTransaction = TransactionUtil.begin(); + } + + EntityListIterator eli = this.find(entityName, whereEntityCondition, havingEntityCondition, UtilMisc.toSet(fieldsToSelect), orderBy, findOptions); + eli.setDelegator(this); + List list = eli.getCompleteList(); + eli.close(); + + return list; + } catch (GenericEntityException e) { + String errMsg = "Failure in findByCondition operation for entity [" + entityName + "]: " + e.toString() + ". Rolling back transaction."; + Debug.logError(e, errMsg, module); + try { + // only rollback the transaction if we started one... + TransactionUtil.rollback(beganTransaction, errMsg, e); + } catch (GenericEntityException e2) { + Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); + } + // after rolling back, rethrow the exception + throw e; + } finally { + // only commit the transaction if we started one... this will throw + // an exception if it fails + TransactionUtil.commit(beganTransaction); + } + } + + public List findByConditionCache(String entityName, EntityCondition entityCondition, Collection fieldsToSelect, List orderBy) throws GenericEntityException { + return this.findList(entityName, entityCondition, UtilMisc.collectionToSet(fieldsToSelect), orderBy, null, true); + } + + public List findByLike(String entityName, Map fields) throws GenericEntityException { + List likeExpressions = FastList.newInstance(); + if (fields != null) { + for (Map.Entry fieldEntry : fields.entrySet()) { + likeExpressions.add(EntityCondition.makeCondition(fieldEntry.getKey(), EntityOperator.LIKE, fieldEntry.getValue())); + } + } + EntityConditionList ecl = EntityCondition.makeCondition(likeExpressions, EntityOperator.AND); + return this.findList(entityName, ecl, null, null, null, false); + } + + public List findByLike(String entityName, Map fields, List orderBy) throws GenericEntityException { + List likeExpressions = FastList.newInstance(); + if (fields != null) { + for (Map.Entry fieldEntry : fields.entrySet()) { + likeExpressions.add(EntityCondition.makeCondition(fieldEntry.getKey(), EntityOperator.LIKE, fieldEntry.getValue())); + } + } + EntityConditionList ecl = EntityCondition.makeCondition(likeExpressions, EntityOperator.AND); + return this.findList(entityName, ecl, null, orderBy, null, false); + } + + public List findByLike(String entityName, Object... fields) throws GenericEntityException { + Map fieldMap = UtilMisc. toMap(fields); + List likeExpressions = FastList.newInstance(); + if (fieldMap != null) { + for (Map.Entry fieldEntry : fieldMap.entrySet()) { + likeExpressions.add(EntityCondition.makeCondition(fieldEntry.getKey(), EntityOperator.LIKE, fieldEntry.getValue())); + } + } + EntityConditionList ecl = EntityCondition.makeCondition(likeExpressions, EntityOperator.AND); + return this.findList(entityName, ecl, null, null, null, false); + } + + public List findByOr(String entityName, List expressions) throws GenericEntityException { + EntityConditionList ecl = EntityCondition.makeCondition(expressions, EntityOperator.OR); + return this.findList(entityName, ecl, null, null, null, false); + } + + public List findByOr(String entityName, List expressions, List orderBy) throws GenericEntityException { + EntityConditionList ecl = EntityCondition.makeCondition(expressions, EntityOperator.OR); + return this.findList(entityName, ecl, null, orderBy, null, false); + } + + public List findByOr(String entityName, Map fields) throws GenericEntityException { + EntityCondition ecl = EntityCondition.makeCondition(fields, EntityOperator.OR); + return this.findList(entityName, ecl, null, null, null, false); + } + + public List findByOr(String entityName, Map fields, List orderBy) throws GenericEntityException { + EntityCondition ecl = EntityCondition.makeCondition(fields, EntityOperator.OR); + return this.findList(entityName, ecl, null, orderBy, null, false); + } + + public List findByOr(String entityName, Object... fields) throws GenericEntityException { + EntityCondition ecl = EntityCondition.makeCondition(EntityOperator.OR, fields); + return this.findList(entityName, ecl, null, null, null, false); + } + + public List findByOr(String entityName, T... expressions) throws GenericEntityException { + return this.findList(entityName, EntityCondition.makeCondition(EntityOperator.AND, expressions), null, null, null, false); + } + + public GenericValue findByPrimaryKey(GenericPK primaryKey) throws GenericEntityException { + return findOne(primaryKey.getEntityName(), primaryKey, false); + } + + public GenericValue findByPrimaryKey(String entityName, Map fields) throws GenericEntityException { + return findOne(entityName, fields, false); + } + + public GenericValue findByPrimaryKey(String entityName, Object... fields) throws GenericEntityException { + return findByPrimaryKey(entityName, UtilMisc. toMap(fields)); + } + + public GenericValue findByPrimaryKeyCache(GenericPK primaryKey) throws GenericEntityException { + return findOne(primaryKey.getEntityName(), primaryKey, true); + } + + public GenericValue findByPrimaryKeyCache(String entityName, Map fields) throws GenericEntityException { + return findOne(entityName, fields, true); + } + + public GenericValue findByPrimaryKeyCache(String entityName, Object... fields) throws GenericEntityException { + return findByPrimaryKeyCache(entityName, UtilMisc. toMap(fields)); + } + + public GenericValue findByPrimaryKeyCacheSingle(String entityName, Object singlePkValue) throws GenericEntityException { + return findOne(entityName, makePKSingle(entityName, singlePkValue), true); + } + + public GenericValue findByPrimaryKeyPartial(GenericPK primaryKey, Set keys) throws GenericEntityException { + boolean beganTransaction = false; + try { + if (alwaysUseTransaction) { + beganTransaction = TransactionUtil.begin(); + } + + EntityEcaRuleRunner ecaRunner = this.getEcaRuleRunner(primaryKey.getEntityName()); + ecaRunner.evalRules(EntityEcaHandler.EV_VALIDATE, EntityEcaHandler.OP_FIND, primaryKey, false); + + GenericHelper helper = getEntityHelper(primaryKey.getEntityName()); + GenericValue value = null; + + if (!primaryKey.isPrimaryKey()) { + throw new GenericModelException("[GenericDelegator.findByPrimaryKey] Passed primary key is not a valid primary key: " + primaryKey); + } + + ecaRunner.evalRules(EntityEcaHandler.EV_RUN, EntityEcaHandler.OP_FIND, primaryKey, false); + try { + value = helper.findByPrimaryKeyPartial(primaryKey, keys); + } catch (GenericEntityNotFoundException e) { + value = null; + } + if (value != null) + value.setDelegator(this); + + ecaRunner.evalRules(EntityEcaHandler.EV_RETURN, EntityEcaHandler.OP_FIND, primaryKey, false); + return value; + } catch (GenericEntityException e) { + String errMsg = "Failure in findByPrimaryKeyPartial operation for entity [" + primaryKey.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; + Debug.logError(e, errMsg, module); + try { + // only rollback the transaction if we started one... + TransactionUtil.rollback(beganTransaction, errMsg, e); + } catch (GenericEntityException e2) { + Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); + } + // after rolling back, rethrow the exception + throw e; + } finally { + // only commit the transaction if we started one... this will throw + // an exception if it fails + TransactionUtil.commit(beganTransaction); + } + } + + public GenericValue findByPrimaryKeyPartial(GenericPK primaryKey, String... keys) throws GenericEntityException { + return findByPrimaryKeyPartial(primaryKey, UtilMisc.makeSetWritable(Arrays.asList(keys))); + } + + public GenericValue findByPrimaryKeySingle(String entityName, Object singlePkValue) throws GenericEntityException { + return findOne(entityName, makePKSingle(entityName, singlePkValue), false); + } + + public long findCountByAnd(String entityName) throws GenericEntityException { + return findCountByCondition(entityName, null, null, null); + } + + public long findCountByAnd(String entityName, Map fields) throws GenericEntityException { + return findCountByCondition(entityName, EntityCondition.makeCondition(fields, EntityOperator.AND), null, null); + } + + public long findCountByAnd(String entityName, Object... fields) throws GenericEntityException { + return findCountByCondition(entityName, EntityCondition.makeCondition(UtilMisc. toMap(fields), EntityOperator.AND), null, null); + } + + public long findCountByCondition(String entityName, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition) throws GenericEntityException { + return findCountByCondition(entityName, whereEntityCondition, havingEntityCondition, null); + } + + public long findCountByCondition(String entityName, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, EntityFindOptions findOptions) throws GenericEntityException { + + boolean beganTransaction = false; + try { + if (alwaysUseTransaction) { + beganTransaction = TransactionUtil.begin(); + } + + ModelEntity modelEntity = getModelReader().getModelEntity(entityName); + GenericValue dummyValue = GenericValue.create(modelEntity); + EntityEcaRuleRunner ecaRunner = this.getEcaRuleRunner(modelEntity.getEntityName()); + ecaRunner.evalRules(EntityEcaHandler.EV_VALIDATE, EntityEcaHandler.OP_FIND, dummyValue, false); + + if (whereEntityCondition != null) { + whereEntityCondition.checkCondition(modelEntity); + whereEntityCondition.encryptConditionFields(modelEntity, this); + } + if (havingEntityCondition != null) { + havingEntityCondition.checkCondition(modelEntity); + havingEntityCondition.encryptConditionFields(modelEntity, this); + } + + ecaRunner.evalRules(EntityEcaHandler.EV_RUN, EntityEcaHandler.OP_FIND, dummyValue, false); + GenericHelper helper = getEntityHelper(modelEntity.getEntityName()); + long count = helper.findCountByCondition(modelEntity, whereEntityCondition, havingEntityCondition, findOptions); + + ecaRunner.evalRules(EntityEcaHandler.EV_RETURN, EntityEcaHandler.OP_FIND, dummyValue, false); + return count; + } catch (GenericEntityException e) { + String errMsg = "Failure in findListIteratorByCondition operation for entity [DynamicView]: " + e.toString() + ". Rolling back transaction."; + Debug.logError(e, errMsg, module); + try { + // only rollback the transaction if we started one... + TransactionUtil.rollback(beganTransaction, errMsg, e); + } catch (GenericEntityException e2) { + Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); + } + // after rolling back, rethrow the exception + throw e; + } finally { + // only commit the transaction if we started one... this will throw + // an exception if it fails + TransactionUtil.commit(beganTransaction); + } + } + + public List findList(String entityName, EntityCondition entityCondition, Set fieldsToSelect, List orderBy, EntityFindOptions findOptions, boolean useCache) throws GenericEntityException { + + EntityEcaRuleRunner ecaRunner = null; + GenericValue dummyValue = null; + if (useCache) { + ecaRunner = this.getEcaRuleRunner(entityName); + ModelEntity modelEntity = getModelReader().getModelEntity(entityName); + dummyValue = GenericValue.create(modelEntity); + ecaRunner.evalRules(EntityEcaHandler.EV_CACHE_CHECK, EntityEcaHandler.OP_FIND, dummyValue, false); + + List cacheList = this.delegatorData.cache.get(entityName, entityCondition, orderBy); + if (cacheList != null) { + return cacheList; + } + } + + boolean beganTransaction = false; + try { + if (alwaysUseTransaction) { + beganTransaction = TransactionUtil.begin(); + } + + EntityListIterator eli = this.find(entityName, entityCondition, null, fieldsToSelect, orderBy, findOptions); + eli.setDelegator(this); + List list = eli.getCompleteList(); + eli.close(); + + if (useCache) { + ecaRunner.evalRules(EntityEcaHandler.EV_CACHE_PUT, EntityEcaHandler.OP_FIND, dummyValue, false); + this.delegatorData.cache.put(entityName, entityCondition, orderBy, list); + } + return list; + } catch (GenericEntityException e) { + String errMsg = "Failure in findByCondition operation for entity [" + entityName + "]: " + e.toString() + ". Rolling back transaction."; + Debug.logError(e, errMsg, module); + try { + // only rollback the transaction if we started one... + TransactionUtil.rollback(beganTransaction, errMsg, e); + } catch (GenericEntityException e2) { + Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); + } + // after rolling back, rethrow the exception + throw e; + } finally { + // only commit the transaction if we started one... this will throw + // an exception if it fails + TransactionUtil.commit(beganTransaction); + } + } + + public EntityListIterator findListIteratorByCondition(DynamicViewEntity dynamicViewEntity, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, Collection fieldsToSelect, List orderBy, EntityFindOptions findOptions) throws GenericEntityException { + + // if there is no transaction throw an exception, we don't want to + // create a transaction here since closing it would mess up the ELI + if (!TransactionUtil.isTransactionInPlace()) { + // throw new GenericEntityException("ERROR: Cannot do a find that + // returns an EntityListIterator with no transaction in place. Wrap + // this call in a transaction."); + + // throwing an exception is a little harsh for now, just display a + // really big error message since we want to get all of these + // fixed... + Exception newE = new Exception("Stack Trace"); + Debug.logError(newE, "ERROR: Cannot do a find that returns an EntityListIterator with no transaction in place. Wrap this call in a transaction.", module); + } + + ModelViewEntity modelViewEntity = dynamicViewEntity.makeModelViewEntity(this); + if (whereEntityCondition != null) + whereEntityCondition.checkCondition(modelViewEntity); + if (havingEntityCondition != null) + havingEntityCondition.checkCondition(modelViewEntity); + + GenericHelper helper = getEntityHelper(dynamicViewEntity.getOneRealEntityName()); + EntityListIterator eli = helper.findListIteratorByCondition(modelViewEntity, whereEntityCondition, havingEntityCondition, fieldsToSelect, orderBy, findOptions); + eli.setDelegator(this); + // TODO: add decrypt fields + return eli; + } + + public EntityListIterator findListIteratorByCondition(String entityName, EntityCondition entityCondition, Collection fieldsToSelect, List orderBy) throws GenericEntityException { + return this.find(entityName, entityCondition, null, UtilMisc.collectionToSet(fieldsToSelect), orderBy, null); + } + + public EntityListIterator findListIteratorByCondition(String entityName, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, Collection fieldsToSelect, List orderBy, EntityFindOptions findOptions) throws GenericEntityException { + + return this.find(entityName, whereEntityCondition, havingEntityCondition, UtilMisc.collectionToSet(fieldsToSelect), orderBy, findOptions); + } + + public GenericValue findOne(String entityName, boolean useCache, Object... fields) throws GenericEntityException { + return findOne(entityName, UtilMisc.toMap(fields), useCache); + } + + public GenericValue findOne(String entityName, Map fields, boolean useCache) throws GenericEntityException { + GenericPK primaryKey = this.makePK(entityName, fields); + EntityEcaRuleRunner ecaRunner = this.getEcaRuleRunner(entityName); + if (useCache) { + ecaRunner.evalRules(EntityEcaHandler.EV_CACHE_CHECK, EntityEcaHandler.OP_FIND, primaryKey, false); + + GenericValue value = this.getFromPrimaryKeyCache(primaryKey); + if (value != null) { + return value; + } + } + + boolean beganTransaction = false; + try { + if (alwaysUseTransaction) { + beganTransaction = TransactionUtil.begin(); + } + + ecaRunner.evalRules(EntityEcaHandler.EV_VALIDATE, EntityEcaHandler.OP_FIND, primaryKey, false); + + GenericHelper helper = getEntityHelper(entityName); + GenericValue value = null; + + if (!primaryKey.isPrimaryKey()) { + throw new GenericModelException("[GenericDelegator.findOne] Passed primary key is not a valid primary key: " + primaryKey); + } + ecaRunner.evalRules(EntityEcaHandler.EV_RUN, EntityEcaHandler.OP_FIND, primaryKey, false); + try { + value = helper.findByPrimaryKey(primaryKey); + } catch (GenericEntityNotFoundException e) { + value = null; + } + if (value != null) { + value.setDelegator(this); + this.decryptFields(value); + } + + if (useCache) { + if (value != null) { + ecaRunner.evalRules(EntityEcaHandler.EV_CACHE_PUT, EntityEcaHandler.OP_FIND, value, false); + this.putInPrimaryKeyCache(primaryKey, value); + } else { + this.putInPrimaryKeyCache(primaryKey, GenericValue.NULL_VALUE); + } + } + + ecaRunner.evalRules(EntityEcaHandler.EV_RETURN, EntityEcaHandler.OP_FIND, (value == null ? primaryKey : value), false); + return value; + } catch (GenericEntityException e) { + String errMsg = "Failure in findOne operation for entity [" + entityName + "]: " + e.toString() + ". Rolling back transaction."; + Debug.logError(e, errMsg, module); + try { + // only rollback the transaction if we started one... + TransactionUtil.rollback(beganTransaction, errMsg, e); + } catch (GenericEntityException e2) { + Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); + } + // after rolling back, rethrow the exception + throw e; + } finally { + // only commit the transaction if we started one... this will throw + // an exception if it fails + TransactionUtil.commit(beganTransaction); + } + } + + public Cache getCache() { + return this.delegatorData.cache; + } + + public GenericDelegator getDelegator(String delegatorName) { + return DelegatorFactory.getGenericDelegator(delegatorName); + } + + protected DelegatorInfo getDelegatorInfo() { + return this.delegatorData.delegatorInfo; + } + + public String getDelegatorName() { + return this.delegatorData.delegatorName; + } + + protected EntityEcaRuleRunner getEcaRuleRunner(String entityName) { + if (this.testRollbackInProgress) + return createEntityEcaRuleRunner(null, null); + return createEntityEcaRuleRunner(this.delegatorData.entityEcaHandler, entityName); + } + + @SuppressWarnings("unchecked") + public EntityEcaHandler getEntityEcaHandler() { + return this.delegatorData.entityEcaHandler; + } + + public ModelFieldType getEntityFieldType(ModelEntity entity, String type) throws GenericEntityException { + return this.getModelFieldTypeReader(entity).getModelFieldType(type); + } + + public Collection getEntityFieldTypeNames(ModelEntity entity) throws GenericEntityException { + String helperName = getEntityHelperName(entity); + + if (helperName == null || helperName.length() <= 0) + return null; + ModelFieldTypeReader modelFieldTypeReader = ModelFieldTypeReader.getModelFieldTypeReader(helperName); + + if (modelFieldTypeReader == null) { + throw new GenericEntityException("ModelFieldTypeReader not found for entity " + entity.getEntityName() + " with helper name " + helperName); + } + return modelFieldTypeReader.getFieldTypeNames(); + } + + public String getEntityGroupName(String entityName) { + return getModelGroupReader().getEntityGroupName(entityName, getOriginalDelegatorName()); + } + + public GenericHelper getEntityHelper(ModelEntity entity) throws GenericEntityException { + return getEntityHelper(entity.getEntityName()); + } + + public GenericHelper getEntityHelper(String entityName) throws GenericEntityException { + String helperName = getEntityHelperName(entityName); + + if (helperName != null && helperName.length() > 0) { + return GenericHelperFactory.getHelper(helperName); + } else { + throw new GenericEntityException("There is no datasource (Helper) configured for the entity-group [" + this.getEntityGroupName(entityName) + "]; was trying to find datesource (helper) for entity [" + entityName + "]"); + } + } + + public String getEntityHelperName(ModelEntity entity) { + if (entity == null) + return null; + return getEntityHelperName(entity.getEntityName()); + } + + public String getEntityHelperName(String entityName) { + return this.getGroupHelperName(this.getEntityGroupName(entityName)); + } + + public GenericValue getFromPrimaryKeyCache(GenericPK primaryKey) { + if (primaryKey == null) + return null; + GenericValue value = (GenericValue) this.delegatorData.cache.get(primaryKey); + if (value == GenericValue.NULL_VALUE) { + return null; + } + return value; + } + + public String getGroupHelperName(String groupName) { + return this.getDelegatorInfo().groupMap.get(groupName); + } + + public Locale getLocale() { + return this.locale; + } + + public ModelEntity getModelEntity(String entityName) { + try { + return getModelReader().getModelEntity(entityName); + } catch (GenericEntityException e) { + Debug.logError(e, "Error getting entity definition from model", module); + return null; + } + } + + public Map getModelEntityMapByGroup(String groupName) throws GenericEntityException { + Set entityNameSet = getModelGroupReader().getEntityNamesByGroup(groupName); + + if (this.getDelegatorInfo().defaultGroupName.equals(groupName)) { + // add all entities with no group name to the Set + Set allEntityNames = this.getModelReader().getEntityNames(); + for (String entityName : allEntityNames) { + if (this.getDelegatorInfo().defaultGroupName.equals(getModelGroupReader().getEntityGroupName(entityName, getDelegatorName()))) { + entityNameSet.add(entityName); + } + } + } + + Map entities = FastMap.newInstance(); + if (entityNameSet == null || entityNameSet.size() == 0) { + return entities; + } + + int errorCount = 0; + for (String entityName : entityNameSet) { + try { + ModelEntity entity = getModelReader().getModelEntity(entityName); + if (entity != null) { + entities.put(entity.getEntityName(), entity); + } else { + throw new IllegalStateException("Could not find entity with name " + entityName); + } + } catch (GenericEntityException ex) { + errorCount++; + Debug.logError("Entity [" + entityName + "] named in Entity Group with name " + groupName + " are not defined in any Entity Definition file", module); + } + } + + if (errorCount > 0) { + Debug.logError(errorCount + " entities were named in ModelGroup but not defined in any EntityModel", module); + } + + return entities; + } + + public ModelFieldTypeReader getModelFieldTypeReader(ModelEntity entity) { + String helperName = getEntityHelperName(entity); + if (helperName == null || helperName.length() <= 0) { + return null; + } + ModelFieldTypeReader modelFieldTypeReader = ModelFieldTypeReader.getModelFieldTypeReader(helperName); + if (modelFieldTypeReader == null) { + throw new IllegalArgumentException("ModelFieldTypeReader not found for entity " + entity.getEntityName() + " with helper name " + helperName); + } + return modelFieldTypeReader; + } + + public ModelGroupReader getModelGroupReader() { + return this.delegatorData.modelGroupReader; + } + + public ModelReader getModelReader() { + return this.delegatorData.modelReader; + } + + public List getMultiRelation(GenericValue value, String relationNameOne, String relationNameTwo) throws GenericEntityException { + return getMultiRelation(value, relationNameOne, relationNameTwo, null); + } + + public List getMultiRelation(GenericValue value, String relationNameOne, String relationNameTwo, List orderBy) throws GenericEntityException { + boolean beganTransaction = false; + try { + if (alwaysUseTransaction) { + beganTransaction = TransactionUtil.begin(); + } + // TODO: add eca eval calls + // traverse the relationships + ModelEntity modelEntity = value.getModelEntity(); + ModelRelation modelRelationOne = modelEntity.getRelation(relationNameOne); + ModelEntity modelEntityOne = getModelEntity(modelRelationOne.getRelEntityName()); + ModelRelation modelRelationTwo = modelEntityOne.getRelation(relationNameTwo); + ModelEntity modelEntityTwo = getModelEntity(modelRelationTwo.getRelEntityName()); + + GenericHelper helper = getEntityHelper(modelEntity); + + return helper.findByMultiRelation(value, modelRelationOne, modelEntityOne, modelRelationTwo, modelEntityTwo, orderBy); + } catch (GenericEntityException e) { + String errMsg = "Failure in getMultiRelation operation for entity [" + value.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; + Debug.logError(e, errMsg, module); + try { + // only rollback the transaction if we started one... + TransactionUtil.rollback(beganTransaction, errMsg, e); + } catch (GenericEntityException e2) { + Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); + } + // after rolling back, rethrow the exception + throw e; + } finally { + // only commit the transaction if we started one... + // this will throw an exception if it fails + TransactionUtil.commit(beganTransaction); + } + } + + public String getNextSeqId(String seqName) { + return this.getNextSeqId(seqName, 1); + } + + public String getNextSeqId(String seqName, long staggerMax) { + Long nextSeqLong = this.getNextSeqIdLong(seqName, staggerMax); + + if (nextSeqLong == null) { + // NOTE: the getNextSeqIdLong method SHOULD throw a runtime + // exception when no sequence value is found, which means we + // should never see it get here + throw new IllegalArgumentException("Could not get next sequenced ID for sequence name: " + seqName); + } + + if (UtilValidate.isNotEmpty(this.getDelegatorInfo().sequencedIdPrefix)) { + return this.getDelegatorInfo().sequencedIdPrefix + nextSeqLong.toString(); + } else { + return nextSeqLong.toString(); + } + } + + public Long getNextSeqIdLong(String seqName) { + return this.getNextSeqIdLong(seqName, 1); + } + + public Long getNextSeqIdLong(String seqName, long staggerMax) { + boolean beganTransaction = false; + try { + if (alwaysUseTransaction) { + beganTransaction = TransactionUtil.begin(); + } + + if (this.delegatorData.sequencer == null) { + synchronized (this.delegatorData) { + if (this.delegatorData.sequencer == null) { + String helperName = this.getEntityHelperName("SequenceValueItem"); + ModelEntity seqEntity = this.getModelEntity("SequenceValueItem"); + this.delegatorData.sequencer = new SequenceUtil(helperName, seqEntity, "seqName", "seqId"); + } + } + } + + // might be null, but will usually match the entity name + ModelEntity seqModelEntity = this.getModelEntity(seqName); + + Long newSeqId = this.delegatorData.sequencer == null ? null : this.delegatorData.sequencer.getNextSeqId(seqName, staggerMax, seqModelEntity); + + return newSeqId; + } catch (GenericEntityException e) { + String errMsg = "Failure in getNextSeqIdLong operation for seqName [" + seqName + "]: " + e.toString() + ". Rolling back transaction."; + try { + // only rollback the transaction if we started one... + TransactionUtil.rollback(beganTransaction, errMsg, e); + } catch (GenericEntityException e2) { + Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); + } + // rather than logging the problem and returning null, thus hiding the + // problem, throw an exception + throw new GeneralRuntimeException(errMsg, e); + } finally { + try { + // only commit the transaction if we started one... + TransactionUtil.commit(beganTransaction); + } catch (GenericTransactionException e1) { + Debug.logError(e1, "[GenericDelegator] Could not commit transaction: " + e1.toString(), module); + } + } + } + + public String getOriginalDelegatorName() { + return this.delegatorData.originalDelegatorName == null ? this.delegatorData.delegatorName : this.delegatorData.originalDelegatorName; + } + + @Deprecated + public List getRelated(String relationName, GenericValue value) throws GenericEntityException { + return getRelated(relationName, null, null, value); + } + + public List getRelated(String relationName, Map byAndFields, List orderBy, GenericValue value) throws GenericEntityException { + ModelEntity modelEntity = value.getModelEntity(); + ModelRelation relation = modelEntity.getRelation(relationName); + + if (relation == null) { + throw new GenericModelException("Could not find relation for relationName: " + relationName + " for value " + value); + } + + // put the byAndFields (if not null) into the hash map first, + // they will be overridden by value's fields if over-specified + // this is important for security and cleanliness + Map fields = FastMap.newInstance(); + if (byAndFields != null) + fields.putAll(byAndFields); + for (int i = 0; i < relation.getKeyMapsSize(); i++) { + ModelKeyMap keyMap = relation.getKeyMap(i); + fields.put(keyMap.getRelFieldName(), value.get(keyMap.getFieldName())); + } + + return this.findByAnd(relation.getRelEntityName(), fields, orderBy); + } + + public List getRelatedByAnd(String relationName, Map byAndFields, GenericValue value) throws GenericEntityException { + return this.getRelated(relationName, byAndFields, null, value); + } + + public List getRelatedCache(String relationName, GenericValue value) throws GenericEntityException { + ModelEntity modelEntity = value.getModelEntity(); + ModelRelation relation = modelEntity.getRelation(relationName); + + if (relation == null) { + throw new GenericModelException("Could not find relation for relationName: " + relationName + " for value " + value); + } + + Map fields = FastMap.newInstance(); + for (int i = 0; i < relation.getKeyMapsSize(); i++) { + ModelKeyMap keyMap = relation.getKeyMap(i); + fields.put(keyMap.getRelFieldName(), value.get(keyMap.getFieldName())); + } + + return this.findByAndCache(relation.getRelEntityName(), fields, null); + } + + public GenericPK getRelatedDummyPK(String relationName, Map byAndFields, GenericValue value) throws GenericEntityException { + ModelEntity modelEntity = value.getModelEntity(); + ModelRelation relation = modelEntity.getRelation(relationName); + + if (relation == null) { + throw new GenericModelException("Could not find relation for relationName: " + relationName + " for value " + value); + } + ModelEntity relatedEntity = getModelReader().getModelEntity(relation.getRelEntityName()); + + // put the byAndFields (if not null) into the hash map first, + // they will be overridden by value's fields if + // over-specified this is important for security and + // cleanliness + Map fields = FastMap.newInstance(); + if (byAndFields != null) + fields.putAll(byAndFields); + for (int i = 0; i < relation.getKeyMapsSize(); i++) { + ModelKeyMap keyMap = relation.getKeyMap(i); + fields.put(keyMap.getRelFieldName(), value.get(keyMap.getFieldName())); + } + + GenericPK dummyPK = GenericPK.create(relatedEntity, fields); + dummyPK.setDelegator(this); + return dummyPK; + } + + public GenericValue getRelatedOne(String relationName, GenericValue value) throws GenericEntityException { + ModelRelation relation = value.getModelEntity().getRelation(relationName); + + if (relation == null) { + throw new GenericModelException("Could not find relation for relationName: " + relationName + " for value " + value); + } + if (!"one".equals(relation.getType()) && !"one-nofk".equals(relation.getType())) { + throw new GenericModelException("Relation is not a 'one' or a 'one-nofk' relation: " + relationName + " of entity " + value.getEntityName()); + } + + Map fields = FastMap.newInstance(); + for (int i = 0; i < relation.getKeyMapsSize(); i++) { + ModelKeyMap keyMap = relation.getKeyMap(i); + fields.put(keyMap.getRelFieldName(), value.get(keyMap.getFieldName())); + } + + return this.findByPrimaryKey(relation.getRelEntityName(), fields); + } + + public GenericValue getRelatedOneCache(String relationName, GenericValue value) throws GenericEntityException { + ModelEntity modelEntity = value.getModelEntity(); + ModelRelation relation = modelEntity.getRelation(relationName); + + if (relation == null) { + throw new GenericModelException("Could not find relation for relationName: " + relationName + " for value " + value); + } + if (!"one".equals(relation.getType()) && !"one-nofk".equals(relation.getType())) { + throw new GenericModelException("Relation is not a 'one' or a 'one-nofk' relation: " + relationName + " of entity " + value.getEntityName()); + } + + Map fields = FastMap.newInstance(); + for (int i = 0; i < relation.getKeyMapsSize(); i++) { + ModelKeyMap keyMap = relation.getKeyMap(i); + fields.put(keyMap.getRelFieldName(), value.get(keyMap.getFieldName())); + } + + return this.findByPrimaryKeyCache(relation.getRelEntityName(), fields); + } + + public List getRelatedOrderBy(String relationName, List orderBy, GenericValue value) throws GenericEntityException { + return this.getRelated(relationName, null, orderBy, value); + } + + protected void initEntityEcaHandler() { + if (this.delegatorData.delegatorInfo.useEntityEca) { + ClassLoader loader = Thread.currentThread().getContextClassLoader(); + // initialize the entity eca handler + String entityEcaHandlerClassName = this.delegatorData.delegatorInfo.entityEcaHandlerClassName; + try { + Class eecahClass = loader.loadClass(entityEcaHandlerClassName); + this.delegatorData.entityEcaHandler = (EntityEcaHandler) eecahClass.newInstance(); + this.delegatorData.entityEcaHandler.setDelegator(this); + } catch (ClassNotFoundException e) { + Debug.logWarning(e, "EntityEcaHandler class with name " + entityEcaHandlerClassName + " was not found, Entity ECA Rules will be disabled", module); + } catch (InstantiationException e) { + Debug.logWarning(e, "EntityEcaHandler class with name " + entityEcaHandlerClassName + " could not be instantiated, Entity ECA Rules will be disabled", module); + } catch (IllegalAccessException e) { + Debug.logWarning(e, "EntityEcaHandler class with name " + entityEcaHandlerClassName + " could not be accessed (illegal), Entity ECA Rules will be disabled", module); + } catch (ClassCastException e) { + Debug.logWarning(e, "EntityEcaHandler class with name " + entityEcaHandlerClassName + " does not implement the EntityEcaHandler interface, Entity ECA Rules will be disabled", module); + } + } else { + Debug.logInfo("Entity ECA Handler disabled for delegator [" + this.delegatorData.delegatorName + "]", module); + } + } + + public GenericPK makePK(Element element) { + GenericValue value = makeValue(element); + + return value.getPrimaryKey(); + } + + public GenericPK makePK(String entityName) { + return this.makePK(entityName, (Map) null); + } + + public GenericPK makePK(String entityName, Map fields) { + ModelEntity entity = this.getModelEntity(entityName); + if (entity == null) { + throw new IllegalArgumentException("[GenericDelegator.makePK] could not find entity for entityName: " + entityName); + } + GenericPK pk = GenericPK.create(entity, fields); + + pk.setDelegator(this); + return pk; + } + + public GenericPK makePK(String entityName, Object... fields) { + return makePK(entityName, UtilMisc. toMap(fields)); + } + + public GenericPK makePKSingle(String entityName, Object singlePkValue) { + ModelEntity entity = this.getModelEntity(entityName); + if (entity == null) { + throw new IllegalArgumentException("[GenericDelegator.makePKSingle] could not find entity for entityName: " + entityName); + } + GenericPK pk = GenericPK.create(entity, singlePkValue); + + pk.setDelegator(this); + return pk; + } + + public GenericDelegator makeTestDelegator(String delegatorName) { + DelegatorImpl testDelegator = (DelegatorImpl) this.cloneDelegator(delegatorName); + testDelegator.setTestMode(true); + return testDelegator; + } + + public GenericValue makeValidValue(String entityName, Map fields) { + ModelEntity entity = this.getModelEntity(entityName); + if (entity == null) { + throw new IllegalArgumentException("[GenericDelegator.makeValidValue] could not find entity for entityName: " + entityName); + } + GenericValue value = GenericValue.create(entity); + value.setPKFields(fields, true); + value.setNonPKFields(fields, true); + value.setDelegator(this); + return value; + } + + public GenericValue makeValidValue(String entityName, Object... fields) { + return makeValidValue(entityName, UtilMisc. toMap(fields)); + } + + 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 modelFields = modelEntity.getFieldsIterator(); + + while (modelFields.hasNext()) { + ModelField modelField = modelFields.next(); + String name = modelField.getName(); + String attr = element.getAttribute(name); + + if (attr != null && attr.length() > 0) { + 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; + } + + public GenericValue makeValue(String entityName) { + ModelEntity entity = this.getModelEntity(entityName); + if (entity == null) { + throw new IllegalArgumentException("[GenericDelegator.makeValue] could not find entity for entityName: " + entityName); + } + GenericValue value = GenericValue.create(entity); + value.setDelegator(this); + return value; + } + + public GenericValue makeValue(String entityName, Map fields) { + ModelEntity entity = this.getModelEntity(entityName); + if (entity == null) { + throw new IllegalArgumentException("[GenericDelegator.makeValue] could not find entity for entityName: " + entityName); + } + GenericValue value = GenericValue.create(entity, fields); + value.setDelegator(this); + return value; + } + + public GenericValue makeValue(String entityName, Object... fields) { + return makeValue(entityName, UtilMisc. toMap(fields)); + } + + public List makeValues(Document document) { + if (document == null) + return null; + List values = FastList.newInstance(); + + Element docElement = document.getDocumentElement(); + + if (docElement == null) + return null; + if (!"entity-engine-xml".equals(docElement.getTagName())) { + Debug.logError("[GenericDelegator.makeValues] Root node was not ", module); + throw new java.lang.IllegalArgumentException("Root node was not "); + } + docElement.normalize(); + Node curChild = docElement.getFirstChild(); + + if (curChild != null) { + do { + if (curChild.getNodeType() == Node.ELEMENT_NODE) { + Element element = (Element) curChild; + GenericValue value = this.makeValue(element); + + if (value != null) + values.add(value); + } + } while ((curChild = curChild.getNextSibling()) != null); + } else { + Debug.logWarning("[GenericDelegator.makeValues] No child nodes found in document.", module); + } + + return values; + } + + public GenericValue makeValueSingle(String entityName, Object singlePkValue) { + ModelEntity entity = this.getModelEntity(entityName); + if (entity == null) { + throw new IllegalArgumentException("[GenericDelegator.makeValue] could not find entity for entityName: " + entityName); + } + GenericValue value = GenericValue.create(entity, singlePkValue); + value.setDelegator(this); + return value; + } + + public void putAllInPrimaryKeyCache(List values) { + if (values == null) + return; + for (GenericValue value : values) { + this.putInPrimaryKeyCache(value.getPrimaryKey(), value); + } + } + + public void putInPrimaryKeyCache(GenericPK primaryKey, GenericValue value) { + if (primaryKey == null) + return; + + if (primaryKey.getModelEntity().getNeverCache()) { + Debug.logWarning("Tried to put a value of the " + value.getEntityName() + " entity in the BY PRIMARY KEY cache but this entity has never-cache set to true, not caching.", module); + return; + } + + // before going into the cache, make this value immutable + value.setImmutable(); + this.delegatorData.cache.put(primaryKey, value); + } + + // ======= XML Related Methods ======== + public List readXmlDocument(URL url) throws SAXException, ParserConfigurationException, java.io.IOException { + if (url == null) + return null; + return this.makeValues(UtilXml.readXmlDocument(url, false)); + } + + public void refresh(GenericValue value) throws GenericEntityException { + this.refresh(value, true); + } + + public void refresh(GenericValue value, boolean doCacheClear) throws GenericEntityException { + if (doCacheClear) { + // always clear cache before the operation + clearCacheLine(value); + } + GenericPK pk = value.getPrimaryKey(); + GenericValue newValue = this.findOne(pk.getEntityName(), pk, false); + value.refreshFromValue(newValue); + } + + public void refreshFromCache(GenericValue value) throws GenericEntityException { + GenericPK pk = value.getPrimaryKey(); + GenericValue newValue = findOne(pk.getEntityName(), pk, true); + value.refreshFromValue(newValue); + } + + public void refreshSequencer() { + this.delegatorData.sequencer = null; + } + + public int removeAll(List dummyPKs) throws GenericEntityException { + return this.removeAll(dummyPKs, true); + } + + public int removeAll(List dummyPKs, boolean doCacheClear) throws GenericEntityException { + if (dummyPKs == null) { + return 0; + } + + boolean beganTransaction = false; + int numRemoved = 0; + + try { + for (GenericEntity value : dummyPKs) { + if (value.containsPrimaryKey()) { + numRemoved += this.removeByPrimaryKey(value.getPrimaryKey(), doCacheClear); + } else { + numRemoved += this.removeByAnd(value.getEntityName(), value.getAllFields(), doCacheClear); + } + } + + return numRemoved; + } catch (GenericEntityException e) { + String errMsg = "Failure in removeAll operation: " + e.toString() + ". Rolling back transaction."; + Debug.logError(e, errMsg, module); + try { + // only rollback the transaction if we started one... + TransactionUtil.rollback(beganTransaction, errMsg, e); + } catch (GenericEntityException e2) { + Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); + } + // after rolling back, rethrow the exception + throw e; + } finally { + // only commit the + // transaction if we started + // one... this will throw an + // exception if it fails + TransactionUtil.commit(beganTransaction); + } + } + + public int removeAll(String entityName) throws GenericEntityException { + return removeByAnd(entityName, (Map) null); + } + + public int removeByAnd(String entityName, boolean doCacheClear, Object... fields) throws GenericEntityException { + return removeByAnd(entityName, UtilMisc. toMap(fields), doCacheClear); + } + + public int removeByAnd(String entityName, Map fields) throws GenericEntityException { + return this.removeByAnd(entityName, fields, true); + } + + public int removeByAnd(String entityName, Map fields, boolean doCacheClear) throws GenericEntityException { + EntityCondition ecl = EntityCondition.makeCondition(fields); + return removeByCondition(entityName, ecl, doCacheClear); + } + + public int removeByAnd(String entityName, Object... fields) throws GenericEntityException { + return removeByAnd(entityName, UtilMisc. toMap(fields)); + } + + public int removeByCondition(String entityName, EntityCondition condition) throws GenericEntityException { + return this.removeByCondition(entityName, condition, true); + } + + public int removeByCondition(String entityName, EntityCondition condition, boolean doCacheClear) throws GenericEntityException { + boolean beganTransaction = false; + try { + if (alwaysUseTransaction) { + beganTransaction = TransactionUtil.begin(); + } + + if (doCacheClear) { + // always clear cache before the operation + this.clearCacheLineByCondition(entityName, condition); + } + ModelEntity modelEntity = getModelReader().getModelEntity(entityName); + GenericHelper helper = getEntityHelper(entityName); + + List removedEntities = null; + if (testMode) { + removedEntities = this.findList(entityName, condition, null, null, null, false); + } + + int rowsAffected = helper.removeByCondition(modelEntity, condition); + + if (testMode) { + for (GenericValue entity : removedEntities) { + storeForTestRollback(new TestOperation(OperationType.DELETE, entity)); + } + } + + return rowsAffected; + } catch (GenericEntityException e) { + String errMsg = "Failure in removeByCondition operation for entity [" + entityName + "]: " + e.toString() + ". Rolling back transaction."; + Debug.logError(e, errMsg, module); + try { + // only rollback the transaction if we started one... + TransactionUtil.rollback(beganTransaction, errMsg, e); + } catch (GenericEntityException e2) { + Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); + } + // after rolling back, rethrow the exception + throw e; + } finally { + // only commit + // the + // transaction + // if we started + // one... this + // will throw an + // exception if + // it fails + TransactionUtil.commit(beganTransaction); + } + } + + public int removeByPrimaryKey(GenericPK primaryKey) throws GenericEntityException { + int retVal = this.removeByPrimaryKey(primaryKey, true); + return retVal; + } + + public int removeByPrimaryKey(GenericPK primaryKey, boolean doCacheClear) throws GenericEntityException { + boolean beganTransaction = false; + try { + if (alwaysUseTransaction) { + beganTransaction = TransactionUtil.begin(); + } + + EntityEcaRuleRunner ecaRunner = this.getEcaRuleRunner(primaryKey.getEntityName()); + ecaRunner.evalRules(EntityEcaHandler.EV_VALIDATE, EntityEcaHandler.OP_REMOVE, primaryKey, false); + + GenericHelper helper = getEntityHelper(primaryKey.getEntityName()); + + if (doCacheClear) { + // always + // clear + // cache + // before + // the + // operation + ecaRunner.evalRules(EntityEcaHandler.EV_CACHE_CLEAR, EntityEcaHandler.OP_REMOVE, primaryKey, false); + this.clearCacheLine(primaryKey); + } + + ecaRunner.evalRules(EntityEcaHandler.EV_RUN, EntityEcaHandler.OP_REMOVE, primaryKey, false); + + // if audit log on for any fields, save old value before + // removing so it's still there + if (primaryKey != null && primaryKey.getModelEntity().getHasFieldWithAuditLog()) { + createEntityAuditLogAll(this.findOne(primaryKey.getEntityName(), primaryKey, false), true, true); + } + + GenericValue removedEntity = null; + if (testMode) { + removedEntity = this.findOne(primaryKey.entityName, primaryKey, false); + } + int num = helper.removeByPrimaryKey(primaryKey); + this.saveEntitySyncRemoveInfo(primaryKey); + + if (testMode) { + storeForTestRollback(new TestOperation(OperationType.DELETE, removedEntity)); + } + + ecaRunner.evalRules(EntityEcaHandler.EV_RETURN, EntityEcaHandler.OP_REMOVE, primaryKey, false); + + return num; + } catch (GenericEntityException e) { + String errMsg = "Failure in removeByPrimaryKey operation for entity [" + primaryKey.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; + Debug.logError(e, errMsg, module); + try { + // only rollback the transaction if we started one... + TransactionUtil.rollback(beganTransaction, errMsg, e); + } catch (GenericEntityException e2) { + Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); + } + // after rolling back, rethrow the exception + throw e; + } finally { + // only commit the transaction if we started one... this will throw an + // exception if it fails + TransactionUtil.commit(beganTransaction); + } + } + + public int removeRelated(String relationName, GenericValue value) throws GenericEntityException { + return this.removeRelated(relationName, value, true); + } + + public int removeRelated(String relationName, GenericValue value, boolean doCacheClear) throws GenericEntityException { + ModelEntity modelEntity = value.getModelEntity(); + ModelRelation relation = modelEntity.getRelation(relationName); + + if (relation == null) { + throw new GenericModelException("Could not find relation for relationName: " + relationName + " for value " + value); + } + + Map fields = FastMap.newInstance(); + for (int i = 0; i < relation.getKeyMapsSize(); i++) { + ModelKeyMap keyMap = relation.getKeyMap(i); + fields.put(keyMap.getRelFieldName(), value.get(keyMap.getFieldName())); + } + + return this.removeByAnd(relation.getRelEntityName(), fields, doCacheClear); + } + + public int removeValue(GenericValue value) throws GenericEntityException { + return this.removeValue(value, true); + } + + public int removeValue(GenericValue value, boolean doCacheClear) throws GenericEntityException { + // NOTE: this does not call the GenericDelegator.removeByPrimaryKey + // method because it has more information to pass to the ECA rule hander + boolean beganTransaction = false; + try { + if (alwaysUseTransaction) { + beganTransaction = TransactionUtil.begin(); + } + + EntityEcaRuleRunner ecaRunner = this.getEcaRuleRunner(value.getEntityName()); + ecaRunner.evalRules(EntityEcaHandler.EV_VALIDATE, EntityEcaHandler.OP_REMOVE, value, false); + + GenericHelper helper = getEntityHelper(value.getEntityName()); + + if (doCacheClear) { + ecaRunner.evalRules(EntityEcaHandler.EV_CACHE_CLEAR, EntityEcaHandler.OP_REMOVE, value, false); + this.clearCacheLine(value); + } + + ecaRunner.evalRules(EntityEcaHandler.EV_RUN, EntityEcaHandler.OP_REMOVE, value, false); + + // if audit log on for any fields, save old value before actual + // remove + if (value != null && value.getModelEntity().getHasFieldWithAuditLog()) { + createEntityAuditLogAll(value, true, true); + } + + GenericValue removedValue = null; + if (testMode) { + removedValue = this.findOne(value.getEntityName(), value.getPrimaryKey(), false); + } + + int num = helper.removeByPrimaryKey(value.getPrimaryKey()); + + if (testMode) { + storeForTestRollback(new TestOperation(OperationType.DELETE, removedValue)); + } + + this.saveEntitySyncRemoveInfo(value.getPrimaryKey()); + + ecaRunner.evalRules(EntityEcaHandler.EV_RETURN, EntityEcaHandler.OP_REMOVE, value, false); + + return num; + } catch (GenericEntityException e) { + String errMsg = "Failure in removeValue operation for entity [" + value.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; + Debug.logError(e, errMsg, module); + try { + // only rollback the transaction if we started one... + TransactionUtil.rollback(beganTransaction, errMsg, e); + } catch (GenericEntityException e2) { + Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); + } + // after rolling back, rethrow the exception + throw e; + } finally { + // only commit the transaction if we started one... this will throw + // an exception if it fails + TransactionUtil.commit(beganTransaction); + } + } + + public void rollback() { + if (!this.testMode) { + Debug.logError("Rollback requested outside of testmode", module); + } + this.testMode = false; + this.testRollbackInProgress = true; + synchronized (testOperations) { + Debug.logInfo("Rolling back " + testOperations.size() + " entity operations", module); + ListIterator iterator = this.testOperations.listIterator(this.testOperations.size()); + while (iterator.hasPrevious()) { + TestOperation testOperation = iterator.previous(); + try { + if (testOperation.getOperation().equals(OperationType.INSERT)) { + this.removeValue(testOperation.getValue()); + } else if (testOperation.getOperation().equals(OperationType.UPDATE)) { + this.store(testOperation.getValue()); + } else if (testOperation.getOperation().equals(OperationType.DELETE)) { + this.create(testOperation.getValue()); + } + } catch (GenericEntityException e) { + Debug.logWarning(e.toString(), module); + } + } + this.testOperations.clear(); + } + this.testRollbackInProgress = false; + this.testMode = true; + } + + protected void saveEntitySyncRemoveInfo(GenericEntity dummyPK) throws GenericEntityException { + // don't store remove info on entities where it is disabled + if (dummyPK.getModelEntity().getNoAutoStamp() || this.testRollbackInProgress) { + return; + } + + // don't store remove info on things removed on an entity sync + if (dummyPK.getIsFromEntitySync()) { + return; + } + + String serializedPK = null; + try { + serializedPK = XmlSerializer.serialize(dummyPK); + } catch (SerializeException e) { + Debug.logError(e, "Could not serialize primary key to save EntitySyncRemove", module); + } catch (FileNotFoundException e) { + Debug.logError(e, "Could not serialize primary key to save EntitySyncRemove", module); + } catch (IOException e) { + Debug.logError(e, "Could not serialize primary key to save EntitySyncRemove", module); + } + + if (serializedPK != null) { + GenericValue entitySyncRemove = this.makeValue("EntitySyncRemove"); + entitySyncRemove.set("primaryKeyRemoved", serializedPK); + this.createSetNextSeqId(entitySyncRemove); + } + } + + public void setDistributedCacheClear(DistributedCacheClear distributedCacheClear) { + this.delegatorData.distributedCacheClear = distributedCacheClear; + } + + public void setEntityCrypto(EntityCrypto crypto) { + this.delegatorData.crypto = crypto; + } + + @SuppressWarnings("unchecked") + public void setEntityEcaHandler(EntityEcaHandler entityEcaHandler) { + this.delegatorData.entityEcaHandler = entityEcaHandler; + } + + public void setNextSubSeqId(GenericValue value, String seqFieldName, int numericPadding, int incrementBy) { + if (value != null && UtilValidate.isEmpty(value.getString(seqFieldName))) { + String sequencedIdPrefix = this.getDelegatorInfo().sequencedIdPrefix; + + value.remove(seqFieldName); + GenericValue lookupValue = this.makeValue(value.getEntityName()); + lookupValue.setPKFields(value); + + boolean beganTransaction = false; + try { + if (alwaysUseTransaction) { + beganTransaction = TransactionUtil.begin(); + } + + // get values in whatever order, we will go through all of them + // to find the highest value + List allValues = this.findByAnd(value.getEntityName(), lookupValue, null); + // Debug.logInfo("Get existing values from entity " + + // value.getEntityName() + " with lookupValue: " + lookupValue + + // ", and the seqFieldName: " + seqFieldName + ", and the + // results are: " + allValues, module); + Integer highestSeqVal = null; + for (GenericValue curValue : allValues) { + String currentSeqId = curValue.getString(seqFieldName); + if (currentSeqId != null) { + if (UtilValidate.isNotEmpty(sequencedIdPrefix)) { + if (currentSeqId.startsWith(sequencedIdPrefix)) { + currentSeqId = currentSeqId.substring(sequencedIdPrefix.length()); + } else { + continue; + } + } + try { + int seqVal = Integer.parseInt(currentSeqId); + if (highestSeqVal == null || seqVal > highestSeqVal.intValue()) { + highestSeqVal = Integer.valueOf(seqVal); + } + } catch (Exception e) { + Debug.logWarning("Error in make-next-seq-id converting SeqId [" + currentSeqId + "] in field: " + seqFieldName + " from entity: " + value.getEntityName() + " to a number: " + e.toString(), module); + } + } + } + + int seqValToUse = (highestSeqVal == null ? 1 : highestSeqVal.intValue() + incrementBy); + String newSeqId = sequencedIdPrefix + UtilFormatOut.formatPaddedNumber(seqValToUse, numericPadding); + value.set(seqFieldName, newSeqId); + + // only commit the transaction if we started one... + TransactionUtil.commit(beganTransaction); + } catch (Exception e) { + String errMsg = "Failure in setNextSubSeqId operation for entity [" + value.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; + Debug.logError(e, errMsg, module); + try { + // only rollback the transaction if we started one... + TransactionUtil.rollback(beganTransaction, errMsg, e); + } catch (GenericEntityException e2) { + Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); + } + Debug.logError(e, "Error making next seqId", module); + } + } + } + + public void setLocale(Locale locale) { + this.locale = locale; + } + + public void setSessionIdentifier(String identifier) { + this.sessionIdentifier = identifier; + } + + public void setUserIdentifier(String identifier) { + this.userIdentifier = identifier; + } + + public void setSequencer(SequenceUtil sequencer) { + this.delegatorData.sequencer = sequencer; + } + + private void setTestMode(boolean testMode) { + this.testMode = testMode; + if (testMode) { + this.testOperations = FastList.newInstance(); + } else { + this.testOperations.clear(); + } + } + + public int store(GenericValue value) throws GenericEntityException { + return this.store(value, true); + } + + public int store(GenericValue value, boolean doCacheClear) throws GenericEntityException { + boolean beganTransaction = false; + try { + if (alwaysUseTransaction) { + beganTransaction = TransactionUtil.begin(); + } + + EntityEcaRuleRunner ecaRunner = this.getEcaRuleRunner(value.getEntityName()); + ecaRunner.evalRules(EntityEcaHandler.EV_VALIDATE, EntityEcaHandler.OP_STORE, value, false); + GenericHelper helper = getEntityHelper(value.getEntityName()); + + if (doCacheClear) { + // always clear cache before the operation + ecaRunner.evalRules(EntityEcaHandler.EV_CACHE_CLEAR, EntityEcaHandler.OP_STORE, value, false); + this.clearCacheLine(value); + } + + ecaRunner.evalRules(EntityEcaHandler.EV_RUN, EntityEcaHandler.OP_STORE, value, false); + this.encryptFields(value); + + // if audit log on for any fields, save old value before the update + // so we still have both + if (value != null && value.getModelEntity().getHasFieldWithAuditLog()) { + createEntityAuditLogAll(value, true, false); + } + + GenericValue updatedEntity = null; + + if (testMode) { + updatedEntity = this.findOne(value.entityName, value.getPrimaryKey(), false); + } + + int retVal = helper.store(value); + + if (testMode) { + storeForTestRollback(new TestOperation(OperationType.UPDATE, updatedEntity)); + } + // refresh the valueObject to get the new version + if (value.lockEnabled()) { + refresh(value, doCacheClear); + } + + ecaRunner.evalRules(EntityEcaHandler.EV_RETURN, EntityEcaHandler.OP_STORE, value, false); + + return retVal; + } catch (GenericEntityException e) { + String errMsg = "Failure in store operation for entity [" + value.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; + Debug.logError(e, errMsg, module); + try { + // only rollback the transaction if we started one... + TransactionUtil.rollback(beganTransaction, errMsg, e); + } catch (GenericEntityException e2) { + Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); + } + // after rolling back, rethrow the exception + throw e; + } finally { + // only commit the transaction if we started one... this will throw + // an exception if it fails + TransactionUtil.commit(beganTransaction); + } + } + + public int storeAll(List values) throws GenericEntityException { + return this.storeAll(values, true); + } + + public int storeAll(List values, boolean doCacheClear) throws GenericEntityException { + return this.storeAll(values, doCacheClear, false); + } + + public int storeAll(List values, boolean doCacheClear, boolean createDummyFks) throws GenericEntityException { + if (values == null) { + return 0; + } + + 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); + + // exists? + // 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); + this.decryptFields(existing); + } catch (GenericEntityNotFoundException e) { + existing = null; + } + + if (existing == null) { + if (createDummyFks) { + value.checkFks(true); + } + this.create(value, doCacheClear); + 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(modelEntity, (Map) value.getPrimaryKey()); + toStore.setDelegator(this); + boolean atLeastOneField = false; + Iterator 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 ((fieldValue == null && oldValue != null) || (fieldValue != null && !fieldValue.equals(oldValue))) { + toStore.put(fieldName, fieldValue); + atLeastOneField = true; + } + } + } + + if (atLeastOneField) { + if (createDummyFks) { + value.checkFks(true); + } + numberChanged += this.store(toStore, doCacheClear); + } + } + } + + return numberChanged; + } catch (GenericEntityException e) { + String errMsg = "Failure in storeAll operation: " + e.toString() + ". Rolling back transaction."; + Debug.logError(e, errMsg, module); + try { + // only rollback the transaction if we started one... + TransactionUtil.rollback(beganTransaction, errMsg, e); + } catch (GenericEntityException e2) { + Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); + } + // after rolling back, rethrow the exception + throw e; + } finally { + // only commit the transaction if we started one... this will throw + // an exception if it fails + TransactionUtil.commit(beganTransaction); + } + } + + public int storeByCondition(String entityName, Map fieldsToSet, EntityCondition condition) throws GenericEntityException { + return storeByCondition(entityName, fieldsToSet, condition, true); + } + + public int storeByCondition(String entityName, Map fieldsToSet, EntityCondition condition, boolean doCacheClear) throws GenericEntityException { + boolean beganTransaction = false; + try { + if (alwaysUseTransaction) { + beganTransaction = TransactionUtil.begin(); + } + + if (doCacheClear) { + // always clear cache before the operation + this.clearCacheLineByCondition(entityName, condition); + } + ModelEntity modelEntity = getModelReader().getModelEntity(entityName); + GenericHelper helper = getEntityHelper(entityName); + + List updatedEntities = null; + if (testMode) { + updatedEntities = this.findList(entityName, condition, null, null, null, false); + } + + int rowsAffected = helper.storeByCondition(modelEntity, fieldsToSet, condition); + + if (testMode) { + for (GenericValue entity : updatedEntities) { + storeForTestRollback(new TestOperation(OperationType.UPDATE, entity)); + } + } + + return rowsAffected; + } catch (GenericEntityException e) { + String errMsg = "Failure in storeByCondition operation for entity [" + entityName + "]: " + e.toString() + ". Rolling back transaction."; + Debug.logError(e, errMsg, module); + try { + // only rollback the transaction if we started one... + TransactionUtil.rollback(beganTransaction, errMsg, e); + } catch (GenericEntityException e2) { + Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); + } + // after rolling back, rethrow the exception + throw e; + } finally { + // only commit the transaction if we started one... this will throw + // an exception if it fails + TransactionUtil.commit(beganTransaction); + } + } + + private void storeForTestRollback(TestOperation testOperation) { + if (!this.testMode || this.testRollbackInProgress) { + throw new IllegalStateException("An attempt was made to store a TestOperation during rollback or outside of test mode"); + } + this.testOperations.add(testOperation); + } + +} diff --git a/framework/entity/src/org/ofbiz/entity/DelegatorInterface.java b/framework/entity/src/org/ofbiz/entity/DelegatorInterface.java deleted file mode 100644 index 3d397b0ac7..0000000000 --- a/framework/entity/src/org/ofbiz/entity/DelegatorInterface.java +++ /dev/null @@ -1,236 +0,0 @@ -/******************************************************************************* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - *******************************************************************************/ -package org.ofbiz.entity; - -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.ofbiz.entity.cache.Cache; -import org.ofbiz.entity.condition.EntityCondition; -import org.ofbiz.entity.datasource.GenericHelper; -import org.ofbiz.entity.model.ModelEntity; -import org.ofbiz.entity.model.ModelFieldType; -import org.ofbiz.entity.model.ModelGroupReader; -import org.ofbiz.entity.model.ModelReader; -import org.ofbiz.entity.util.EntityFindOptions; -import org.ofbiz.entity.util.EntityListIterator; -import org.ofbiz.entity.util.SequenceUtil; - -/** - * Delegator Interface - */ -public interface DelegatorInterface { - - String getDelegatorName(); - - ModelReader getModelReader(); - - ModelGroupReader getModelGroupReader(); - - ModelEntity getModelEntity(String entityName); - - String getEntityGroupName(String entityName); - - Map getModelEntityMapByGroup(String groupName) throws GenericEntityException; - - String getGroupHelperName(String groupName); - - String getEntityHelperName(String entityName); - - String getEntityHelperName(ModelEntity entity); - - GenericHelper getEntityHelper(String entityName) throws GenericEntityException; - - GenericHelper getEntityHelper(ModelEntity entity) throws GenericEntityException; - - ModelFieldType getEntityFieldType(ModelEntity entity, String type) throws GenericEntityException; - - Collection getEntityFieldTypeNames(ModelEntity entity) throws GenericEntityException; - - GenericValue makeValue(String entityName); - - GenericValue makeValue(String entityName, Object... fields); - - GenericValue makeValue(String entityName, Map fields); - - GenericValue makeValueSingle(String entityName, Object singlePkValue); - - GenericValue makeValidValue(String entityName, Object... fields); - - GenericValue makeValidValue(String entityName, Map fields); - - GenericPK makePK(String entityName); - - GenericPK makePK(String entityName, Object... fields); - - GenericPK makePK(String entityName, Map fields); - - GenericPK makePKSingle(String entityName, Object singlePkValue); - - GenericValue create(String entityName, Object... fields) throws GenericEntityException; - - GenericValue create(String entityName, Map fields) throws GenericEntityException; - - GenericValue createSingle(String entityName, Object singlePkValue) throws GenericEntityException; - - GenericValue create(GenericValue value) throws GenericEntityException; - - GenericValue create(GenericValue value, boolean doCacheClear) throws GenericEntityException; - - GenericValue create(GenericPK primaryKey) throws GenericEntityException; - - GenericValue create(GenericPK primaryKey, boolean doCacheClear) throws GenericEntityException; - - GenericValue createOrStore(GenericValue value, boolean doCacheClear) throws GenericEntityException; - - GenericValue createOrStore(GenericValue value) throws GenericEntityException; - - GenericValue findOne(String entityName, Map fields, boolean useCache) throws GenericEntityException; - - GenericValue findByPrimaryKey(String entityName, Map fields) throws GenericEntityException; - - GenericValue findByPrimaryKeyCache(String entityName, Object... fields) throws GenericEntityException; - - GenericValue findByPrimaryKeyCache(String entityName, Map fields) throws GenericEntityException; - - GenericValue findByPrimaryKeyPartial(GenericPK primaryKey, Set keys) throws GenericEntityException; - - int removeByPrimaryKey(GenericPK primaryKey) throws GenericEntityException; - - int removeByPrimaryKey(GenericPK primaryKey, boolean doCacheClear) throws GenericEntityException; - - int removeValue(GenericValue value) throws GenericEntityException; - - int removeValue(GenericValue value, boolean doCacheClear) throws GenericEntityException; - - List findByAnd(String entityName, Object... fields) throws GenericEntityException; - - List findByAnd(String entityName, Map fields) throws GenericEntityException; - - List findByAnd(String entityName, Map fields, List orderBy) throws GenericEntityException; - - //List findByAnd(ModelEntity modelEntity, Map fields, List orderBy) throws GenericEntityException; - - List findByOr(String entityName, Map fields, List orderBy) throws GenericEntityException; - - List findByAndCache(String entityName, Map fields) throws GenericEntityException; - - List findByAndCache(String entityName, Map fields, List orderBy) throws GenericEntityException; - - EntityListIterator find(String entityName, EntityCondition whereEntityCondition, - EntityCondition havingEntityCondition, Set fieldsToSelect, List orderBy, EntityFindOptions findOptions) - throws GenericEntityException; - - List findList(String entityName, EntityCondition entityCondition, - Set fieldsToSelect, List orderBy, EntityFindOptions findOptions, boolean useCache) - throws GenericEntityException; - - int removeByAnd(String entityName, Object... fields) throws GenericEntityException; - - int removeByAnd(String entityName, Map fields) throws GenericEntityException; - - int removeByAnd(String entityName, boolean doCacheClear, Object... fields) throws GenericEntityException; - - int removeByAnd(String entityName, Map fields, boolean doCacheClear) throws GenericEntityException; - - int removeByCondition(String entityName, EntityCondition condition) throws GenericEntityException; - - int removeByCondition(String entityName, EntityCondition condition, boolean doCacheClear) throws GenericEntityException; - - List getMultiRelation(GenericValue value, String relationNameOne, String relationNameTwo, List orderBy) throws GenericEntityException; - - List getRelated(String relationName, Map byAndFields, List orderBy, GenericValue value) throws GenericEntityException; - - GenericPK getRelatedDummyPK(String relationName, Map byAndFields, GenericValue value) throws GenericEntityException; - - List getRelatedCache(String relationName, GenericValue value) throws GenericEntityException; - - GenericValue getRelatedOne(String relationName, GenericValue value) throws GenericEntityException; - - GenericValue getRelatedOneCache(String relationName, GenericValue value) throws GenericEntityException; - - int removeRelated(String relationName, GenericValue value) throws GenericEntityException; - - int removeRelated(String relationName, GenericValue value, boolean doCacheClear) throws GenericEntityException; - - void refresh(GenericValue value) throws GenericEntityException; - - void refresh(GenericValue value, boolean doCacheClear) throws GenericEntityException; - - int store(GenericValue value) throws GenericEntityException; - - int store(GenericValue value, boolean doCacheClear) throws GenericEntityException; - - int storeAll(List values) throws GenericEntityException; - - int storeAll(List values, boolean doCacheClear) throws GenericEntityException; - - int storeByCondition(String entityName, Map fieldsToSet, EntityCondition condition) throws GenericEntityException; - - int storeByCondition(String entityName, Map fieldsToSet, EntityCondition condition, boolean doCacheClear) throws GenericEntityException; - - int removeAll(String entityName) throws GenericEntityException; - - int removeAll(List dummyPKs) throws GenericEntityException; - - int removeAll(List dummyPKs, boolean doCacheClear) throws GenericEntityException; - - void clearAllCaches(); - - void clearAllCaches(boolean distribute); - - void clearCacheLine(String entityName); - - void clearCacheLine(String entityName, Object... fields); - - void clearCacheLine(String entityName, Map fields); - - void clearCacheLineFlexible(GenericEntity dummyPK); - - void clearCacheLineFlexible(GenericEntity dummyPK, boolean distribute); - - void clearCacheLine(GenericPK primaryKey); - - void clearCacheLine(GenericPK primaryKey, boolean distribute); - - void clearCacheLine(GenericValue value); - - void clearCacheLine(GenericValue value, boolean distribute); - - void clearCacheLineByCondition(String entityName, EntityCondition condition); - - void clearAllCacheLinesByDummyPK(Collection dummyPKs); - - void clearAllCacheLinesByValue(Collection values); - - GenericValue getFromPrimaryKeyCache(GenericPK primaryKey); - - String getNextSeqId(String seqName); - String getNextSeqId(String seqName, long staggerMax); - Long getNextSeqIdLong(String seqName); - Long getNextSeqIdLong(String seqName, long staggerMax); - - void setSequencer(SequenceUtil sequencer); - - void refreshSequencer(); - - Cache getCache(); -} diff --git a/framework/entity/src/org/ofbiz/entity/GenericDelegator.java b/framework/entity/src/org/ofbiz/entity/GenericDelegator.java index 1a6ec808f7..a3c23ad298 100644 --- a/framework/entity/src/org/ofbiz/entity/GenericDelegator.java +++ b/framework/entity/src/org/ofbiz/entity/GenericDelegator.java @@ -18,58 +18,25 @@ */ package org.ofbiz.entity; -import java.io.FileNotFoundException; -import java.io.IOException; import java.net.URL; -import java.util.Arrays; import java.util.Collection; -import java.util.Iterator; import java.util.List; -import java.util.ListIterator; +import java.util.Locale; import java.util.Map; import java.util.Set; -import java.util.TreeSet; import javax.xml.parsers.ParserConfigurationException; -import javolution.util.FastList; -import javolution.util.FastMap; - -import org.ofbiz.base.util.Debug; -import org.ofbiz.base.util.GeneralRuntimeException; -import org.ofbiz.base.util.UtilDateTime; -import org.ofbiz.base.util.UtilFormatOut; -import org.ofbiz.base.util.UtilMisc; -import org.ofbiz.base.util.UtilValidate; -import org.ofbiz.base.util.UtilXml; -import org.ofbiz.base.util.cache.CacheLine; -import org.ofbiz.base.util.cache.UtilCache; import org.ofbiz.entity.cache.Cache; import org.ofbiz.entity.condition.EntityCondition; -import org.ofbiz.entity.condition.EntityConditionList; -import org.ofbiz.entity.condition.EntityExpr; -import org.ofbiz.entity.condition.EntityOperator; -import org.ofbiz.entity.config.DatasourceInfo; -import org.ofbiz.entity.config.DelegatorInfo; -import org.ofbiz.entity.config.EntityConfigUtil; import org.ofbiz.entity.datasource.GenericHelper; -import org.ofbiz.entity.datasource.GenericHelperFactory; import org.ofbiz.entity.eca.EntityEcaHandler; import org.ofbiz.entity.model.DynamicViewEntity; import org.ofbiz.entity.model.ModelEntity; -import org.ofbiz.entity.model.ModelEntityChecker; -import org.ofbiz.entity.model.ModelField; import org.ofbiz.entity.model.ModelFieldType; import org.ofbiz.entity.model.ModelFieldTypeReader; import org.ofbiz.entity.model.ModelGroupReader; -import org.ofbiz.entity.model.ModelKeyMap; import org.ofbiz.entity.model.ModelReader; -import org.ofbiz.entity.model.ModelRelation; -import org.ofbiz.entity.model.ModelViewEntity; -import org.ofbiz.entity.serialize.SerializeException; -import org.ofbiz.entity.serialize.XmlSerializer; -import org.ofbiz.entity.transaction.GenericTransactionException; -import org.ofbiz.entity.transaction.TransactionUtil; import org.ofbiz.entity.util.DistributedCacheClear; import org.ofbiz.entity.util.EntityCrypto; import org.ofbiz.entity.util.EntityFindOptions; @@ -77,618 +44,127 @@ import org.ofbiz.entity.util.EntityListIterator; import org.ofbiz.entity.util.SequenceUtil; import org.w3c.dom.Document; import org.w3c.dom.Element; -import org.w3c.dom.Node; import org.xml.sax.SAXException; /** - * Generic Data Source Delegator Class - * + * Delegator Interface */ -public class GenericDelegator implements DelegatorInterface { +public interface GenericDelegator { - public static final String module = GenericDelegator.class.getName(); + public void clearAllCacheLinesByDummyPK(Collection dummyPKs); - protected ModelReader modelReader = null; - protected ModelGroupReader modelGroupReader = null; + public void clearAllCacheLinesByValue(Collection values); - /** This flag is only here for lower level technical testing, it shouldn't be user configurable (or at least I don't think so yet); when true all operations without a transaction will be wrapped in one; seems to be necessary for some (all?) XA aware connection pools, and should improve overall stability and consistency */ - public static final boolean alwaysUseTransaction = true; - - /** the delegatorCache will now be a HashMap, allowing reload of definitions, - * but the delegator will always be the same object for the given name */ - protected static Map delegatorCache = FastMap.newInstance(); - protected String delegatorName = null; - protected DelegatorInfo delegatorInfo = null; - - protected Cache cache = null; - - /** keeps a list of field key sets used in the by and cache, a Set (of Sets of fieldNames) for each entityName */ - protected Map andCacheFieldSets = FastMap.newInstance(); - - protected DistributedCacheClear distributedCacheClear = null; - protected EntityEcaHandler entityEcaHandler = null; - protected SequenceUtil sequencer = null; - protected EntityCrypto crypto = null; - - /** A ThreadLocal variable to allow other methods to specify a user identifier (usually the userLoginId, though technically the Entity Engine doesn't know anything about the UserLogin entity) */ - protected static ThreadLocal> userIdentifierStack = new ThreadLocal>(); - /** A ThreadLocal variable to allow other methods to specify a session identifier (usually the visitId, though technically the Entity Engine doesn't know anything about the Visit entity) */ - protected static ThreadLocal> sessionIdentifierStack = new ThreadLocal>(); - - private boolean testMode = false; - private boolean testRollbackInProgress = false; - private List testOperations = null; - private enum OperationType {INSERT, UPDATE, DELETE}; - - private String originalDelegatorName = null; - - - public static GenericDelegator getGenericDelegator(String delegatorName) { - if (delegatorName == null) { - delegatorName = "default"; - Debug.logWarning(new Exception("Location where getting delegator with null name"), "Got a getGenericDelegator call with a null delegatorName, assuming default for the name.", module); - } - GenericDelegator delegator = delegatorCache.get(delegatorName); - - if (delegator == null) { - synchronized (GenericDelegator.class) { - // must check if null again as one of the blocked threads can still enter - delegator = delegatorCache.get(delegatorName); - if (delegator == null) { - if (Debug.infoOn()) Debug.logInfo("Creating new delegator [" + delegatorName + "] (" + Thread.currentThread().getName() + ")", module); - //Debug.logInfo(new Exception(), "Showing stack where new delegator is being created...", module); - try { - delegator = new GenericDelegator(delegatorName); - } catch (GenericEntityException e) { - Debug.logError(e, "Error creating delegator", module); - } - if (delegator != null) { - delegatorCache.put(delegatorName, delegator); - } else { - Debug.logError("Could not create delegator with name " + delegatorName + ", constructor failed (got null value) not sure why/how.", module); - } - } - } - } - return delegator; - } - - protected static List getUserIdentifierStack() { - List curValList = userIdentifierStack.get(); - if (curValList == null) { - curValList = FastList.newInstance(); - userIdentifierStack.set(curValList); - } - return curValList; - } - - public static String getCurrentUserIdentifier() { - List curValList = getUserIdentifierStack(); - Object curVal = curValList.size() > 0 ? curValList.get(0) : null; - if (curVal == null) { - return null; - } else { - return curVal.toString(); - } - } - - public static void pushUserIdentifier(String userIdentifier) { - if (userIdentifier == null) { - return; - } - List curValList = getUserIdentifierStack(); - curValList.add(0, userIdentifier); - } - - public static String popUserIdentifier() { - List curValList = getUserIdentifierStack(); - if (curValList.size() == 0) { - return null; - } else { - return (String) curValList.remove(0); - } - } - - public static void clearUserIdentifierStack() { - List curValList = getUserIdentifierStack(); - curValList.clear(); - } - - protected static List getSessionIdentifierStack() { - List curValList = sessionIdentifierStack.get(); - if (curValList == null) { - curValList = FastList.newInstance(); - sessionIdentifierStack.set(curValList); - } - return curValList; - } - - public static String getCurrentSessionIdentifier() { - List curValList = getSessionIdentifierStack(); - Object curVal = curValList.size() > 0 ? curValList.get(0) : null; - if (curVal == null) { - return null; - } else { - return curVal.toString(); - } - } - - public static void pushSessionIdentifier(String sessionIdentifier) { - if (sessionIdentifier == null) { - return; - } - List curValList = getSessionIdentifierStack(); - curValList.add(0, sessionIdentifier); - } - - public static String popSessionIdentifier() { - List curValList = getSessionIdentifierStack(); - if (curValList.size() == 0) { - return null; - } else { - return (String) curValList.remove(0); - } - } - - public static void clearSessionIdentifierStack() { - List curValList = getSessionIdentifierStack(); - curValList.clear(); - } - - /** Only allow creation through the factory method */ - protected GenericDelegator() {} - - /** Only allow creation through the factory method */ - protected GenericDelegator(String delegatorName) throws GenericEntityException { - //if (Debug.infoOn()) Debug.logInfo("Creating new Delegator with name \"" + delegatorName + "\".", module); - - this.delegatorName = delegatorName; - this.modelReader = ModelReader.getModelReader(delegatorName); - this.modelGroupReader = ModelGroupReader.getModelGroupReader(delegatorName); - - cache = new Cache(delegatorName); - - // do the entity model check - List warningList = FastList.newInstance(); - Debug.logImportant("Doing entity definition check...", module); - ModelEntityChecker.checkEntities(this, warningList); - if (warningList.size() > 0) { - Debug.logWarning("=-=-=-=-= Found " + warningList.size() + " warnings when checking the entity definitions:", module); - for (String warning: warningList) { - Debug.logWarning(warning, module); - } - } - - // initialize helpers by group - Set groupNames = getModelGroupReader().getGroupNames(delegatorName); - Iterator groups = UtilMisc.toIterator(groupNames); - while (groups != null && groups.hasNext()) { - String groupName = groups.next(); - String helperName = this.getGroupHelperName(groupName); - - if (Debug.infoOn()) Debug.logInfo("Delegator \"" + delegatorName + "\" initializing helper \"" + - helperName + "\" for entity group \"" + groupName + "\".", module); - TreeSet helpersDone = new TreeSet(); - if (helperName != null && helperName.length() > 0) { - // make sure each helper is only loaded once - if (helpersDone.contains(helperName)) { - if (Debug.infoOn()) Debug.logInfo("Helper \"" + helperName + "\" already initialized, not re-initializing.", module); - continue; - } - helpersDone.add(helperName); - // pre-load field type defs, the return value is ignored - ModelFieldTypeReader.getModelFieldTypeReader(helperName); - // get the helper and if configured, do the datasource check - GenericHelper helper = GenericHelperFactory.getHelper(helperName); - - DatasourceInfo datasourceInfo = EntityConfigUtil.getDatasourceInfo(helperName); - if (datasourceInfo.checkOnStart) { - if (Debug.infoOn()) Debug.logInfo("Doing database check as requested in entityengine.xml with addMissing=" + datasourceInfo.addMissingOnStart, module); - try { - helper.checkDataSource(this.getModelEntityMapByGroup(groupName), null, datasourceInfo.addMissingOnStart); - } catch (GenericEntityException e) { - Debug.logWarning(e, e.getMessage(), module); - } - } - } - } - - // NOTE: doing some things before the ECAs and such to make sure it is in place just in case it is used in a service engine startup thing or something - // put the delegator in the master Map by its name - GenericDelegator.delegatorCache.put(delegatorName, this); - - // setup the crypto class - this.crypto = new EntityCrypto(this); - - //time to do some tricks with manual class loading that resolves circular dependencies, like calling services... - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - - // if useDistributedCacheClear is false do nothing since the - // distributedCacheClear member field with a null value will cause the - // dcc code to do nothing - if (getDelegatorInfo().useDistributedCacheClear) { - // initialize the distributedCacheClear mechanism - String distributedCacheClearClassName = getDelegatorInfo().distributedCacheClearClassName; - - try { - Class dccClass = loader.loadClass(distributedCacheClearClassName); - this.distributedCacheClear = (DistributedCacheClear) dccClass.newInstance(); - this.distributedCacheClear.setDelegator(this, getDelegatorInfo().distributedCacheClearUserLoginId); - } catch (ClassNotFoundException e) { - Debug.logWarning(e, "DistributedCacheClear class with name " + distributedCacheClearClassName + " was not found, distributed cache clearing will be disabled", module); - } catch (InstantiationException e) { - Debug.logWarning(e, "DistributedCacheClear class with name " + distributedCacheClearClassName + " could not be instantiated, distributed cache clearing will be disabled", module); - } catch (IllegalAccessException e) { - Debug.logWarning(e, "DistributedCacheClear class with name " + distributedCacheClearClassName + " could not be accessed (illegal), distributed cache clearing will be disabled", module); - } catch (ClassCastException e) { - Debug.logWarning(e, "DistributedCacheClear class with name " + distributedCacheClearClassName + " does not implement the DistributedCacheClear interface, distributed cache clearing will be disabled", module); - } - } else { - Debug.logInfo("Distributed Cache Clear System disabled for delegator [" + delegatorName + "]", module); - } - - // setup the Entity ECA Handler - initEntityEcaHandler(); - } - - public void initEntityEcaHandler() { - if (getDelegatorInfo().useEntityEca) { - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - // initialize the entity eca handler - String entityEcaHandlerClassName = getDelegatorInfo().entityEcaHandlerClassName; - - try { - Class eecahClass = loader.loadClass(entityEcaHandlerClassName); - this.entityEcaHandler = (EntityEcaHandler) eecahClass.newInstance(); - this.entityEcaHandler.setDelegator(this); - } catch (ClassNotFoundException e) { - Debug.logWarning(e, "EntityEcaHandler class with name " + entityEcaHandlerClassName + " was not found, Entity ECA Rules will be disabled", module); - } catch (InstantiationException e) { - Debug.logWarning(e, "EntityEcaHandler class with name " + entityEcaHandlerClassName + " could not be instantiated, Entity ECA Rules will be disabled", module); - } catch (IllegalAccessException e) { - Debug.logWarning(e, "EntityEcaHandler class with name " + entityEcaHandlerClassName + " could not be accessed (illegal), Entity ECA Rules will be disabled", module); - } catch (ClassCastException e) { - Debug.logWarning(e, "EntityEcaHandler class with name " + entityEcaHandlerClassName + " does not implement the EntityEcaHandler interface, Entity ECA Rules will be disabled", module); - } - } else { - Debug.logInfo("Entity ECA Handler disabled for delegator [" + delegatorName + "]", module); - } - } - - public String getDelegatorName() { - return this.delegatorName; - } - - /** Gets the name of the server configuration that corresponds to this delegator - * @return server configuration name + /** This method is a shortcut to completely clear all entity engine caches. + * For performance reasons this should not be called very often. */ - public String getOriginalDelegatorName() { - return this.originalDelegatorName == null ? this.delegatorName : this.originalDelegatorName; - } + public void clearAllCaches(); - protected DelegatorInfo getDelegatorInfo() { - if (this.delegatorInfo == null) { - this.delegatorInfo = EntityConfigUtil.getDelegatorInfo(this.delegatorName); - } - return this.delegatorInfo; - } + public void clearAllCaches(boolean distribute); - /** Gets the instance of ModelReader that corresponds to this delegator - *@return ModelReader that corresponds to this delegator + /** Remove a CACHED Generic Entity from the cache by its primary key, does NOT + * check to see if the passed GenericPK is a complete primary key. + * Also tries to clear the corresponding all cache entry. + *@param primaryKey The primary key to clear by. */ - public ModelReader getModelReader() { - return this.modelReader; - } + public void clearCacheLine(GenericPK primaryKey); - /** Gets the instance of ModelGroupReader that corresponds to this delegator - *@return ModelGroupReader that corresponds to this delegator + public void clearCacheLine(GenericPK primaryKey, boolean distribute); + + /** Remove a CACHED GenericValue from as many caches as it can. Automatically + * tries to remove entries from the all cache, the by primary key cache, and + * the by and cache. This is the ONLY method that tries to clear automatically + * from the by and cache. + *@param value The GenericValue to clear by. */ - public ModelGroupReader getModelGroupReader() { - return this.modelGroupReader; - } + public void clearCacheLine(GenericValue value); - /** Gets the instance of ModelEntity that corresponds to this delegator and the specified entityName - *@param entityName The name of the entity to get - *@return ModelEntity that corresponds to this delegator and the specified entityName + public void clearCacheLine(GenericValue value, boolean distribute); + + /** Remove all CACHED Generic Entity (List) from the cache + *@param entityName The Name of the Entity as defined in the entity XML file */ - public ModelEntity getModelEntity(String entityName) { - try { - return getModelReader().getModelEntity(entityName); - } catch (GenericEntityException e) { - Debug.logError(e, "Error getting entity definition from model", module); - return null; - } - } + public void clearCacheLine(String entityName); - /** Gets the helper name that corresponds to this delegator and the specified entityName - *@param entityName The name of the entity to get the helper for - *@return String with the helper name that corresponds to this delegator and the specified entityName + /** Remove a CACHED Generic Entity (List) from the cache, either a PK, ByAnd, or All + *@param entityName The Name of the Entity as defined in the entity XML file + *@param fields The fields of the named entity to query by with their corresponding values */ - public String getEntityGroupName(String entityName) { - return getModelGroupReader().getEntityGroupName(entityName, getOriginalDelegatorName()); - } + public void clearCacheLine(String entityName, Map fields); - /** Gets a Map of entity name & entity model pairs that are in the named group - *@param groupName The name of the group - *@return Map of entityName String keys and ModelEntity instance values + /** Remove a CACHED Generic Entity (List) from the cache, either a PK, ByAnd, or All + *@param entityName The Name of the Entity as defined in the entity XML file + *@param fields The fields of the named entity to query by with their corresponding values */ - public Map getModelEntityMapByGroup(String groupName) throws GenericEntityException { - Set entityNameSet = getModelGroupReader().getEntityNamesByGroup(groupName); + public void clearCacheLine(String entityName, Object... fields); - if (this.getDelegatorInfo().defaultGroupName.equals(groupName)) { - // add all entities with no group name to the Set - Set allEntityNames = this.getModelReader().getEntityNames(); - for (String entityName: allEntityNames) { - if (this.getDelegatorInfo().defaultGroupName.equals(getModelGroupReader().getEntityGroupName(entityName, getDelegatorName()))) { - entityNameSet.add(entityName); - } - } - } + public void clearCacheLineByCondition(String entityName, EntityCondition condition); - Map entities = FastMap.newInstance(); - if (entityNameSet == null || entityNameSet.size() == 0) { - return entities; - } + public void clearCacheLineByCondition(String entityName, EntityCondition condition, boolean distribute); - int errorCount = 0; - for (String entityName: entityNameSet) { - try { - ModelEntity entity = getModelReader().getModelEntity(entityName); - if (entity != null) { - entities.put(entity.getEntityName(), entity); - } else { - throw new IllegalStateException("Could not find entity with name " + entityName); - } - } catch (GenericEntityException ex) { - errorCount++; - Debug.logError("Entity [" + entityName + "] named in Entity Group with name " + groupName + " are not defined in any Entity Definition file", module); - } - } - - if (errorCount > 0) { - Debug.logError(errorCount + " entities were named in ModelGroup but not defined in any EntityModel", module); - } - - return entities; - } - - /** Gets the helper name that corresponds to this delegator and the specified entityName - *@param groupName The name of the group to get the helper name for - *@return String with the helper name that corresponds to this delegator and the specified entityName + /** Remove a CACHED Generic Entity from the cache by its primary key. + * Checks to see if the passed GenericPK is a complete primary key, if + * it is then the cache line will be removed from the primaryKeyCache; if it + * is NOT a complete primary key it will remove the cache line from the andCache. + * If the fields map is empty, then the allCache for the entity will be cleared. + *@param dummyPK The dummy primary key to clear by. */ - public String getGroupHelperName(String groupName) { - return this.getDelegatorInfo().groupMap.get(groupName); - } + public void clearCacheLineFlexible(GenericEntity dummyPK); - /** Gets the helper name that corresponds to this delegator and the specified entityName - *@param entityName The name of the entity to get the helper name for - *@return String with the helper name that corresponds to this delegator and the specified entityName - */ - public String getEntityHelperName(String entityName) { - return this.getGroupHelperName(this.getEntityGroupName(entityName)); - } + public void clearCacheLineFlexible(GenericEntity dummyPK, boolean distribute); - /** Gets the helper name that corresponds to this delegator and the specified entity - *@param entity The entity to get the helper for - *@return String with the helper name that corresponds to this delegator and the specified entity - */ - public String getEntityHelperName(ModelEntity entity) { - if (entity == null) - return null; - return getEntityHelperName(entity.getEntityName()); - } + public GenericDelegator cloneDelegator(); - /** Gets the an instance of helper that corresponds to this delegator and the specified entityName - *@param entityName The name of the entity to get the helper for - *@return GenericHelper that corresponds to this delegator and the specified entityName - */ - public GenericHelper getEntityHelper(String entityName) throws GenericEntityException { - String helperName = getEntityHelperName(entityName); - - if (helperName != null && helperName.length() > 0) { - return GenericHelperFactory.getHelper(helperName); - } else { - throw new GenericEntityException("There is no datasource (Helper) configured for the entity-group [" + this.getEntityGroupName(entityName) + "]; was trying to find datesource (helper) for entity [" + entityName + "]"); - } - } - - /** Gets the an instance of helper that corresponds to this delegator and the specified entity - *@param entity The entity to get the helper for - *@return GenericHelper that corresponds to this delegator and the specified entity - */ - public GenericHelper getEntityHelper(ModelEntity entity) throws GenericEntityException { - return getEntityHelper(entity.getEntityName()); - } - - /** Gets a field type instance by name from the helper that corresponds to the specified entity - *@param entity The entity - *@param type The name of the type - *@return ModelFieldType instance for the named type from the helper that corresponds to the specified entity - */ - public ModelFieldType getEntityFieldType(ModelEntity entity, String type) throws GenericEntityException { - return this.getModelFieldTypeReader(entity).getModelFieldType(type); - } - - public ModelFieldTypeReader getModelFieldTypeReader(ModelEntity entity) { - String helperName = getEntityHelperName(entity); - if (helperName == null || helperName.length() <= 0) { - return null; - } - ModelFieldTypeReader modelFieldTypeReader = ModelFieldTypeReader.getModelFieldTypeReader(helperName); - if (modelFieldTypeReader == null) { - throw new IllegalArgumentException("ModelFieldTypeReader not found for entity " + entity.getEntityName() + " with helper name " + helperName); - } - return modelFieldTypeReader; - } - - /** Gets field type names from the helper that corresponds to the specified entity - *@param entity The entity - *@return Collection of field type names from the helper that corresponds to the specified entity - */ - public Collection getEntityFieldTypeNames(ModelEntity entity) throws GenericEntityException { - String helperName = getEntityHelperName(entity); - - if (helperName == null || helperName.length() <= 0) - return null; - ModelFieldTypeReader modelFieldTypeReader = ModelFieldTypeReader.getModelFieldTypeReader(helperName); - - if (modelFieldTypeReader == null) { - throw new GenericEntityException("ModelFieldTypeReader not found for entity " + entity.getEntityName() + " with helper name " + helperName); - } - return modelFieldTypeReader.getFieldTypeNames(); - } - - /** Creates a Entity in the form of a GenericValue without persisting it */ - public GenericValue makeValue(String entityName) { - ModelEntity entity = this.getModelEntity(entityName); - if (entity == null) { - throw new IllegalArgumentException("[GenericDelegator.makeValue] could not find entity for entityName: " + entityName); - } - GenericValue value = GenericValue.create(entity); - value.setDelegator(this); - return value; - } - - /** Creates a Entity in the form of a GenericValue without persisting it */ - public GenericValue makeValue(String entityName, Object... fields) { - return makeValue(entityName, UtilMisc.toMap(fields)); - } - - /** Creates a Entity in the form of a GenericValue without persisting it */ - public GenericValue makeValue(String entityName, Map fields) { - ModelEntity entity = this.getModelEntity(entityName); - if (entity == null) { - throw new IllegalArgumentException("[GenericDelegator.makeValue] could not find entity for entityName: " + entityName); - } - GenericValue value = GenericValue.create(entity, fields); - value.setDelegator(this); - return value; - } - - /** Creates a Entity in the form of a GenericValue without persisting it */ - public GenericValue makeValueSingle(String entityName, Object singlePkValue) { - ModelEntity entity = this.getModelEntity(entityName); - if (entity == null) { - throw new IllegalArgumentException("[GenericDelegator.makeValue] could not find entity for entityName: " + entityName); - } - GenericValue value = GenericValue.create(entity, singlePkValue); - value.setDelegator(this); - return value; - } - - /** Creates a Entity in the form of a GenericValue without persisting it; only valid fields will be pulled from the fields Map */ - public GenericValue makeValidValue(String entityName, Object... fields) { - return makeValidValue(entityName, UtilMisc.toMap(fields)); - } - - /** Creates a Entity in the form of a GenericValue without persisting it; only valid fields will be pulled from the fields Map */ - public GenericValue makeValidValue(String entityName, Map fields) { - ModelEntity entity = this.getModelEntity(entityName); - if (entity == null) { - throw new IllegalArgumentException("[GenericDelegator.makeValidValue] could not find entity for entityName: " + entityName); - } - GenericValue value = GenericValue.create(entity); - value.setPKFields(fields, true); - value.setNonPKFields(fields, true); - value.setDelegator(this); - return value; - } - - /** Creates a Primary Key in the form of a GenericPK without persisting it */ - public GenericPK makePK(String entityName) { - return this.makePK(entityName, (Map) null); - } - - /** Creates a Primary Key in the form of a GenericPK without persisting it */ - public GenericPK makePK(String entityName, Object... fields) { - return makePK(entityName, UtilMisc.toMap(fields)); - } - - /** Creates a Primary Key in the form of a GenericPK without persisting it */ - public GenericPK makePK(String entityName, Map fields) { - ModelEntity entity = this.getModelEntity(entityName); - if (entity == null) { - throw new IllegalArgumentException("[GenericDelegator.makePK] could not find entity for entityName: " + entityName); - } - GenericPK pk = GenericPK.create(entity, fields); - - pk.setDelegator(this); - return pk; - } - - /** Creates a Primary Key in the form of a GenericPK without persisting it */ - public GenericPK makePKSingle(String entityName, Object singlePkValue) { - ModelEntity entity = this.getModelEntity(entityName); - if (entity == null) { - throw new IllegalArgumentException("[GenericDelegator.makePKSingle] could not find entity for entityName: " + entityName); - } - GenericPK pk = GenericPK.create(entity, singlePkValue); - - pk.setDelegator(this); - return pk; - } + public GenericDelegator cloneDelegator(String delegatorName); /** Creates a Entity in the form of a GenericValue and write it to the datasource *@param primaryKey The GenericPK to create a value in the datasource from *@return GenericValue instance containing the new instance */ - public GenericValue create(GenericPK primaryKey) throws GenericEntityException { - return this.create(primaryKey, true); - } + public GenericValue create(GenericPK primaryKey) throws GenericEntityException; /** Creates a Entity in the form of a GenericValue and write it to the datasource *@param primaryKey The GenericPK to create a value in the datasource from *@param doCacheClear boolean that specifies whether to clear related cache entries for this primaryKey to be created *@return GenericValue instance containing the new instance */ - public GenericValue create(GenericPK primaryKey, boolean doCacheClear) throws GenericEntityException { - if (primaryKey == null) { - throw new GenericEntityException("Cannot create from a null primaryKey"); - } - - return this.create(GenericValue.create(primaryKey), doCacheClear); - } - - /** Creates a Entity in the form of a GenericValue and write it to the database - *@return GenericValue instance containing the new instance - */ - public GenericValue create(String entityName, Object... fields) throws GenericEntityException { - return create(entityName, UtilMisc.toMap(fields)); - } - - /** Creates a Entity in the form of a GenericValue and write it to the database - *@return GenericValue instance containing the new instance - */ - public GenericValue create(String entityName, Map fields) throws GenericEntityException { - if (entityName == null || fields == null) { - return null; - } - ModelEntity entity = this.getModelReader().getModelEntity(entityName); - GenericValue genericValue = GenericValue.create(entity, fields); - - return this.create(genericValue, true); - } - - /** Creates a Entity in the form of a GenericValue and write it to the database - *@return GenericValue instance containing the new instance - */ - public GenericValue createSingle(String entityName, Object singlePkValue) throws GenericEntityException { - if (entityName == null || singlePkValue == null) { - return null; - } - ModelEntity entity = this.getModelReader().getModelEntity(entityName); - GenericValue genericValue = GenericValue.create(entity, singlePkValue); - - return this.create(genericValue, true); - } + public GenericValue create(GenericPK primaryKey, boolean doCacheClear) throws GenericEntityException; /** Creates a Entity in the form of a GenericValue and write it to the datasource *@param value The GenericValue to create a value in the datasource from *@return GenericValue instance containing the new instance */ - public GenericValue create(GenericValue value) throws GenericEntityException { - return this.create(value, true); - } + public GenericValue create(GenericValue value) throws GenericEntityException; + + /** Creates a Entity in the form of a GenericValue and write it to the datasource + *@param value The GenericValue to create a value in the datasource from + *@param doCacheClear boolean that specifies whether or not to automatically clear cache entries related to this operation + *@return GenericValue instance containing the new instance + */ + public GenericValue create(GenericValue value, boolean doCacheClear) throws GenericEntityException; + + /** Creates a Entity in the form of a GenericValue and write it to the database + *@return GenericValue instance containing the new instance + */ + public GenericValue create(String entityName, Map fields) throws GenericEntityException; + + /** Creates a Entity in the form of a GenericValue and write it to the database + *@return GenericValue instance containing the new instance + */ + public GenericValue create(String entityName, Object... fields) throws GenericEntityException; + + /** Creates or stores an Entity + *@param value The GenericValue instance containing the new or existing instance + *@return GenericValue instance containing the new or updated instance + */ + public GenericValue createOrStore(GenericValue value) throws GenericEntityException; + + /** Creates or stores an Entity + *@param value The GenericValue instance containing the new or existing instance + *@param doCacheClear boolean that specifies whether or not to automatically clear cache entries related to this operation + *@return GenericValue instance containing the new or updated instance + */ + public GenericValue createOrStore(GenericValue value, boolean doCacheClear) throws GenericEntityException; /** Sets the sequenced ID (for entity with one primary key field ONLY), and then does a create in the database * as normal. The reason to do it this way is that it will retry and fix the sequence if somehow the sequencer @@ -696,1108 +172,64 @@ public class GenericDelegator implements DelegatorInterface { *@param value The GenericValue to create a value in the datasource from *@return GenericValue instance containing the new instance */ - public GenericValue createSetNextSeqId(GenericValue value) throws GenericEntityException { - boolean doCacheClear = true; + public GenericValue createSetNextSeqId(GenericValue value) throws GenericEntityException; - GenericHelper helper = getEntityHelper(value.getEntityName()); - // just make sure it is this delegator... - value.setDelegator(this); - // this will throw an IllegalArgumentException if the entity for the value does not have one pk field, or if it already has a value set for the one pk field - value.setNextSeqId(); - - boolean beganTransaction = false; - try { - if (alwaysUseTransaction) { - beganTransaction = TransactionUtil.begin(); - } - - EntityEcaRuleRunner ecaRunner = this.getEcaRuleRunner(value.getEntityName()); - ecaRunner.evalRules(EntityEcaHandler.EV_VALIDATE, EntityEcaHandler.OP_CREATE, value, false); - - if (value == null) { - throw new GenericEntityException("Cannot create a null value"); - } - - ecaRunner.evalRules(EntityEcaHandler.EV_RUN, EntityEcaHandler.OP_CREATE, value, false); - - value.setDelegator(this); - this.encryptFields(value); - - // if audit log on for any fields, save new value with no old value because it's a create - if (value != null && value.getModelEntity().getHasFieldWithAuditLog()) { - createEntityAuditLogAll(value, false, false); - } - - try { - value = helper.create(value); - - if (testMode) { - storeForTestRollback(new TestOperation(OperationType.INSERT, value)); - } - } catch (GenericEntityException e) { - // see if this was caused by an existing record before resetting the sequencer and trying again - // NOTE: use the helper directly so ECA rules, etc won't be run - GenericValue existingValue = helper.findByPrimaryKey(value.getPrimaryKey()); - if (existingValue == null) { - throw e; - } else { - Debug.logInfo("Error creating entity record with a sequenced value [" + value.getPrimaryKey() + "], trying again about to refresh bank for entity [" + value.getEntityName() + "]", module); - - // found an existing value... was probably a duplicate key, so clean things up and try again - this.sequencer.forceBankRefresh(value.getEntityName(), 1); - - value.setNextSeqId(); - value = helper.create(value); - Debug.logInfo("Successfully created new entity record on retry with a sequenced value [" + value.getPrimaryKey() + "], after getting refreshed bank for entity [" + value.getEntityName() + "]", module); - - if (testMode) { - storeForTestRollback(new TestOperation(OperationType.INSERT, value)); - } - } - } - - if (value != null) { - value.setDelegator(this); - if (value.lockEnabled()) { - refresh(value, doCacheClear); - } else { - if (doCacheClear) { - ecaRunner.evalRules(EntityEcaHandler.EV_CACHE_CLEAR, EntityEcaHandler.OP_CREATE, value, false); - this.clearCacheLine(value); - } - } - } - - ecaRunner.evalRules(EntityEcaHandler.EV_RETURN, EntityEcaHandler.OP_CREATE, value, false); - - return value; - } catch (GenericEntityException e) { - String errMsg = "Failure in create operation for entity [" + value.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; - Debug.logError(e, errMsg, module); - try { - // only rollback the transaction if we started one... - TransactionUtil.rollback(beganTransaction, errMsg, e); - } catch (GenericEntityException e2) { - Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); - } - // after rolling back, rethrow the exception - throw e; - } finally { - // only commit the transaction if we started one... this will throw an exception if it fails - TransactionUtil.commit(beganTransaction); - } - } - - /** Creates a Entity in the form of a GenericValue and write it to the datasource - *@param value The GenericValue to create a value in the datasource from - *@param doCacheClear boolean that specifies whether or not to automatically clear cache entries related to this operation + /** Creates a Entity in the form of a GenericValue and write it to the database *@return GenericValue instance containing the new instance */ - public GenericValue create(GenericValue value, boolean doCacheClear) throws GenericEntityException { - boolean beganTransaction = false; - try { - if (alwaysUseTransaction) { - beganTransaction = TransactionUtil.begin(); - } + public GenericValue createSingle(String entityName, Object singlePkValue) throws GenericEntityException; - EntityEcaRuleRunner ecaRunner = this.getEcaRuleRunner(value.getEntityName()); - ecaRunner.evalRules(EntityEcaHandler.EV_VALIDATE, EntityEcaHandler.OP_CREATE, value, false); + public void decryptFields(GenericEntity entity) throws GenericEntityException; - if (value == null) { - throw new GenericEntityException("Cannot create a null value"); - } - GenericHelper helper = getEntityHelper(value.getEntityName()); + public void decryptFields(List entities) throws GenericEntityException; - ecaRunner.evalRules(EntityEcaHandler.EV_RUN, EntityEcaHandler.OP_CREATE, value, false); + public void encryptFields(GenericEntity entity) throws GenericEntityException; - value.setDelegator(this); - this.encryptFields(value); + public void encryptFields(List entities) throws GenericEntityException; - // if audit log on for any fields, save new value with no old value because it's a create - if (value != null && value.getModelEntity().getHasFieldWithAuditLog()) { - createEntityAuditLogAll(value, false, false); - } + public Object encryptFieldValue(String entityName, Object fieldValue) throws EntityCryptoException; - value = helper.create(value); - - if (testMode) { - storeForTestRollback(new TestOperation(OperationType.INSERT, value)); - } - if (value != null) { - value.setDelegator(this); - if (value.lockEnabled()) { - refresh(value, doCacheClear); - } else { - if (doCacheClear) { - ecaRunner.evalRules(EntityEcaHandler.EV_CACHE_CLEAR, EntityEcaHandler.OP_CREATE, value, false); - this.clearCacheLine(value); - } - } - } - - ecaRunner.evalRules(EntityEcaHandler.EV_RETURN, EntityEcaHandler.OP_CREATE, value, false); - - return value; - } catch (GenericEntityException e) { - String errMsg = "Failure in create operation for entity [" + value.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; - Debug.logError(e, errMsg, module); - try { - // only rollback the transaction if we started one... - TransactionUtil.rollback(beganTransaction, errMsg, e); - } catch (GenericEntityException e2) { - Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); - } - // after rolling back, rethrow the exception - throw e; - } finally { - // only commit the transaction if we started one... this will throw an exception if it fails - TransactionUtil.commit(beganTransaction); - } - } - - /** Creates or stores an Entity - *@param value The GenericValue instance containing the new or existing instance - *@param doCacheClear boolean that specifies whether or not to automatically clear cache entries related to this operation - *@return GenericValue instance containing the new or updated instance - */ - public GenericValue createOrStore(GenericValue value, boolean doCacheClear) throws GenericEntityException { - boolean beganTransaction = false; - try { - if (alwaysUseTransaction) { - beganTransaction = TransactionUtil.begin(); - } - - GenericValue checkValue = this.findOne(value.getEntityName(), value.getPrimaryKey(), false); - if (checkValue != null) { - this.store(value, doCacheClear); - } else { - this.create(value, doCacheClear); - } - if (value.lockEnabled()) { - this.refresh(value); - } - - return value; - } catch (GenericEntityException e) { - String errMsg = "Failure in createOrStore operation for entity [" + value.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; - Debug.logError(e, errMsg, module); - try { - // only rollback the transaction if we started one... - TransactionUtil.rollback(beganTransaction, errMsg, e); - } catch (GenericEntityException e2) { - Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); - } - // after rolling back, rethrow the exception - throw e; - } finally { - // only commit the transaction if we started one... this will throw an exception if it fails - TransactionUtil.commit(beganTransaction); - } - } - - /** Creates or stores an Entity - *@param value The GenericValue instance containing the new or existing instance - *@return GenericValue instance containing the new or updated instance - */ - public GenericValue createOrStore(GenericValue value) throws GenericEntityException { - return createOrStore(value, true); - } - - protected void saveEntitySyncRemoveInfo(GenericEntity dummyPK) throws GenericEntityException { - // don't store remove info on entities where it is disabled - if (dummyPK.getModelEntity().getNoAutoStamp() || this.testRollbackInProgress) { - return; - } - - // don't store remove info on things removed on an entity sync - if (dummyPK.getIsFromEntitySync()) { - return; - } - - String serializedPK = null; - try { - serializedPK = XmlSerializer.serialize(dummyPK); - } catch (SerializeException e) { - Debug.logError(e, "Could not serialize primary key to save EntitySyncRemove", module); - } catch (FileNotFoundException e) { - Debug.logError(e, "Could not serialize primary key to save EntitySyncRemove", module); - } catch (IOException e) { - Debug.logError(e, "Could not serialize primary key to save EntitySyncRemove", module); - } - - if (serializedPK != null) { - GenericValue entitySyncRemove = this.makeValue("EntitySyncRemove"); - entitySyncRemove.set("primaryKeyRemoved", serializedPK); - this.createSetNextSeqId(entitySyncRemove); - } - } - - /** Remove a Generic Entity corresponding to the primaryKey - *@param primaryKey The primary key of the entity to remove. - *@return int representing number of rows effected by this operation - */ - public int removeByPrimaryKey(GenericPK primaryKey) throws GenericEntityException { - int retVal = this.removeByPrimaryKey(primaryKey, true); - return retVal; - } - - /** Remove a Generic Entity corresponding to the primaryKey - *@param primaryKey The primary key of the entity to remove. - *@param doCacheClear boolean that specifies whether to clear cache entries for this primaryKey to be removed - *@return int representing number of rows effected by this operation - */ - public int removeByPrimaryKey(GenericPK primaryKey, boolean doCacheClear) throws GenericEntityException { - boolean beganTransaction = false; - try { - if (alwaysUseTransaction) { - beganTransaction = TransactionUtil.begin(); - } - - EntityEcaRuleRunner ecaRunner = this.getEcaRuleRunner(primaryKey.getEntityName()); - ecaRunner.evalRules(EntityEcaHandler.EV_VALIDATE, EntityEcaHandler.OP_REMOVE, primaryKey, false); - - GenericHelper helper = getEntityHelper(primaryKey.getEntityName()); - - if (doCacheClear) { - // always clear cache before the operation - ecaRunner.evalRules(EntityEcaHandler.EV_CACHE_CLEAR, EntityEcaHandler.OP_REMOVE, primaryKey, false); - this.clearCacheLine(primaryKey); - } - - ecaRunner.evalRules(EntityEcaHandler.EV_RUN, EntityEcaHandler.OP_REMOVE, primaryKey, false); - - // if audit log on for any fields, save old value before removing so it's still there - if (primaryKey != null && primaryKey.getModelEntity().getHasFieldWithAuditLog()) { - createEntityAuditLogAll(this.findOne(primaryKey.getEntityName(), primaryKey, false), true, true); - } - - GenericValue removedEntity = null; - if (testMode) { - removedEntity = this.findOne(primaryKey.entityName, primaryKey, false); - } - int num = helper.removeByPrimaryKey(primaryKey); - this.saveEntitySyncRemoveInfo(primaryKey); - - if (testMode) { - storeForTestRollback(new TestOperation(OperationType.DELETE, removedEntity)); - } - - ecaRunner.evalRules(EntityEcaHandler.EV_RETURN, EntityEcaHandler.OP_REMOVE, primaryKey, false); - - return num; - } catch (GenericEntityException e) { - String errMsg = "Failure in removeByPrimaryKey operation for entity [" + primaryKey.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; - Debug.logError(e, errMsg, module); - try { - // only rollback the transaction if we started one... - TransactionUtil.rollback(beganTransaction, errMsg, e); - } catch (GenericEntityException e2) { - Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); - } - // after rolling back, rethrow the exception - throw e; - } finally { - // only commit the transaction if we started one... this will throw an exception if it fails - TransactionUtil.commit(beganTransaction); - } - } - - /** Remove a Generic Value from the database - *@param value The GenericValue object of the entity to remove. - *@return int representing number of rows effected by this operation - */ - public int removeValue(GenericValue value) throws GenericEntityException { - return this.removeValue(value, true); - } - - /** Remove a Generic Value from the database - *@param value The GenericValue object of the entity to remove. - *@param doCacheClear boolean that specifies whether to clear cache entries for this value to be removed - *@return int representing number of rows effected by this operation - */ - public int removeValue(GenericValue value, boolean doCacheClear) throws GenericEntityException { - // NOTE: this does not call the GenericDelegator.removeByPrimaryKey method because it has more information to pass to the ECA rule hander - boolean beganTransaction = false; - try { - if (alwaysUseTransaction) { - beganTransaction = TransactionUtil.begin(); - } - - EntityEcaRuleRunner ecaRunner = this.getEcaRuleRunner(value.getEntityName()); - ecaRunner.evalRules(EntityEcaHandler.EV_VALIDATE, EntityEcaHandler.OP_REMOVE, value, false); - - GenericHelper helper = getEntityHelper(value.getEntityName()); - - if (doCacheClear) { - ecaRunner.evalRules(EntityEcaHandler.EV_CACHE_CLEAR, EntityEcaHandler.OP_REMOVE, value, false); - this.clearCacheLine(value); - } - - ecaRunner.evalRules(EntityEcaHandler.EV_RUN, EntityEcaHandler.OP_REMOVE, value, false); - - // if audit log on for any fields, save old value before actual remove - if (value != null && value.getModelEntity().getHasFieldWithAuditLog()) { - createEntityAuditLogAll(value, true, true); - } - - GenericValue removedValue = null; - if (testMode) { - removedValue = this.findOne(value.getEntityName(), value.getPrimaryKey(), false); - } - - int num = helper.removeByPrimaryKey(value.getPrimaryKey()); - - if (testMode) { - storeForTestRollback(new TestOperation(OperationType.DELETE, removedValue)); - } - - this.saveEntitySyncRemoveInfo(value.getPrimaryKey()); - - ecaRunner.evalRules(EntityEcaHandler.EV_RETURN, EntityEcaHandler.OP_REMOVE, value, false); - - return num; - } catch (GenericEntityException e) { - String errMsg = "Failure in removeValue operation for entity [" + value.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; - Debug.logError(e, errMsg, module); - try { - // only rollback the transaction if we started one... - TransactionUtil.rollback(beganTransaction, errMsg, e); - } catch (GenericEntityException e2) { - Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); - } - // after rolling back, rethrow the exception - throw e; - } finally { - // only commit the transaction if we started one... this will throw an exception if it fails - TransactionUtil.commit(beganTransaction); - } - } - - /** Removes/deletes Generic Entity records found by all of the specified fields (ie: combined using AND) - *@param entityName The Name of the Entity as defined in the entity XML file - *@param fields The fields of the named entity to query by with their corresponding values - *@return int representing number of rows effected by this operation - */ - public int removeByAnd(String entityName, Object... fields) throws GenericEntityException { - return removeByAnd(entityName, UtilMisc.toMap(fields)); - } - - /** Removes/deletes Generic Entity records found by all of the specified fields (ie: combined using AND) - *@param entityName The Name of the Entity as defined in the entity XML file - *@param fields The fields of the named entity to query by with their corresponding values - *@return int representing number of rows effected by this operation - */ - public int removeByAnd(String entityName, Map fields) throws GenericEntityException { - return this.removeByAnd(entityName, fields, true); - } - - /** Removes/deletes Generic Entity records found by all of the specified fields (ie: combined using AND) - *@param entityName The Name of the Entity as defined in the entity XML file - *@param doCacheClear boolean that specifies whether to clear cache entries for this value to be removed - *@param fields The fields of the named entity to query by with their corresponding values - *@return int representing number of rows effected by this operation - */ - public int removeByAnd(String entityName, boolean doCacheClear, Object... fields) throws GenericEntityException { - return removeByAnd(entityName, UtilMisc.toMap(fields), doCacheClear); - } - - /** Removes/deletes Generic Entity records found by all of the specified fields (ie: combined using AND) - *@param entityName The Name of the Entity as defined in the entity XML file - *@param fields The fields of the named entity to query by with their corresponding values - *@param doCacheClear boolean that specifies whether to clear cache entries for this value to be removed - *@return int representing number of rows effected by this operation - */ - public int removeByAnd(String entityName, Map fields, boolean doCacheClear) throws GenericEntityException { - EntityCondition ecl = EntityCondition.makeCondition(fields); - return removeByCondition(entityName, ecl, doCacheClear); - } - - /** Removes/deletes Generic Entity records found by the condition - *@param entityName The Name of the Entity as defined in the entity XML file - *@param condition The condition used to restrict the removing - *@return int representing number of rows effected by this operation - */ - public int removeByCondition(String entityName, EntityCondition condition) throws GenericEntityException { - return this.removeByCondition(entityName, condition, true); - } - - /** Removes/deletes Generic Entity records found by the condition - *@param entityName The Name of the Entity as defined in the entity XML file - *@param condition The condition used to restrict the removing - *@param doCacheClear boolean that specifies whether to clear cache entries for this value to be removed - *@return int representing number of rows effected by this operation - */ - public int removeByCondition(String entityName, EntityCondition condition, boolean doCacheClear) throws GenericEntityException { - boolean beganTransaction = false; - try { - if (alwaysUseTransaction) { - beganTransaction = TransactionUtil.begin(); - } - - if (doCacheClear) { - // always clear cache before the operation - this.clearCacheLineByCondition(entityName, condition); - } - ModelEntity modelEntity = getModelReader().getModelEntity(entityName); - GenericHelper helper = getEntityHelper(entityName); - - List removedEntities = null; - if (testMode) { - removedEntities = this.findList(entityName, condition, null, null, null, false); - } - - int rowsAffected = helper.removeByCondition(modelEntity, condition); - - if (testMode) { - for (GenericValue entity : removedEntities) { - storeForTestRollback(new TestOperation(OperationType.DELETE, entity)); - } - } - - return rowsAffected; - } catch (GenericEntityException e) { - String errMsg = "Failure in removeByCondition operation for entity [" + entityName + "]: " + e.toString() + ". Rolling back transaction."; - Debug.logError(e, errMsg, module); - try { - // only rollback the transaction if we started one... - TransactionUtil.rollback(beganTransaction, errMsg, e); - } catch (GenericEntityException e2) { - Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); - } - // after rolling back, rethrow the exception - throw e; - } finally { - // only commit the transaction if we started one... this will throw an exception if it fails - TransactionUtil.commit(beganTransaction); - } - } - - /** Remove the named Related Entity for the GenericValue from the persistent store - *@param relationName String containing the relation name which is the - * combination of relation.title and relation.rel-entity-name as - * specified in the entity XML definition file - *@param value GenericValue instance containing the entity - *@return int representing number of rows effected by this operation - */ - public int removeRelated(String relationName, GenericValue value) throws GenericEntityException { - return this.removeRelated(relationName, value, true); - } - - /** Remove the named Related Entity for the GenericValue from the persistent store - *@param relationName String containing the relation name which is the - * combination of relation.title and relation.rel-entity-name as - * specified in the entity XML definition file - *@param value GenericValue instance containing the entity - *@param doCacheClear boolean that specifies whether to clear cache entries for this value to be removed - *@return int representing number of rows effected by this operation - */ - public int removeRelated(String relationName, GenericValue value, boolean doCacheClear) throws GenericEntityException { - ModelEntity modelEntity = value.getModelEntity(); - ModelRelation relation = modelEntity.getRelation(relationName); - - if (relation == null) { - throw new GenericModelException("Could not find relation for relationName: " + relationName + " for value " + value); - } - - Map fields = FastMap.newInstance(); - for (int i = 0; i < relation.getKeyMapsSize(); i++) { - ModelKeyMap keyMap = relation.getKeyMap(i); - fields.put(keyMap.getRelFieldName(), value.get(keyMap.getFieldName())); - } - - return this.removeByAnd(relation.getRelEntityName(), fields, doCacheClear); - } - - /** Refresh the Entity for the GenericValue from the persistent store - *@param value GenericValue instance containing the entity to refresh - */ - public void refresh(GenericValue value) throws GenericEntityException { - this.refresh(value, true); - } - - /** Refresh the Entity for the GenericValue from the persistent store - *@param value GenericValue instance containing the entity to refresh - *@param doCacheClear boolean that specifies whether or not to automatically clear cache entries related to this operation - */ - public void refresh(GenericValue value, boolean doCacheClear) throws GenericEntityException { - if (doCacheClear) { - // always clear cache before the operation - clearCacheLine(value); - } - GenericPK pk = value.getPrimaryKey(); - GenericValue newValue = this.findOne(pk.getEntityName(), pk, false); - value.refreshFromValue(newValue); - } - - /** Refresh the Entity for the GenericValue from the cache - *@param value GenericValue instance containing the entity to refresh - */ - public void refreshFromCache(GenericValue value) throws GenericEntityException { - GenericPK pk = value.getPrimaryKey(); - GenericValue newValue = findOne(pk.getEntityName(), pk, true); - value.refreshFromValue(newValue); - } - - /** Store a group of values - *@param entityName The name of the Entity as defined in the entity XML file - *@param fieldsToSet The fields of the named entity to set in the database - *@param condition The condition that restricts the list of stored values - *@return int representing number of rows effected by this operation - *@throws GenericEntityException - */ - public int storeByCondition(String entityName, Map fieldsToSet, EntityCondition condition) throws GenericEntityException { - return storeByCondition(entityName, fieldsToSet, condition, true); - } - - /** Store a group of values - *@param entityName The name of the Entity as defined in the entity XML file - *@param fieldsToSet The fields of the named entity to set in the database - *@param condition The condition that restricts the list of stored values - *@param doCacheClear boolean that specifies whether to clear cache entries for these values - *@return int representing number of rows effected by this operation - *@throws GenericEntityException - */ - public int storeByCondition(String entityName, Map fieldsToSet, EntityCondition condition, boolean doCacheClear) throws GenericEntityException { - boolean beganTransaction = false; - try { - if (alwaysUseTransaction) { - beganTransaction = TransactionUtil.begin(); - } - - if (doCacheClear) { - // always clear cache before the operation - this.clearCacheLineByCondition(entityName, condition); - } - ModelEntity modelEntity = getModelReader().getModelEntity(entityName); - GenericHelper helper = getEntityHelper(entityName); - - List updatedEntities = null; - if (testMode) { - updatedEntities = this.findList(entityName, condition, null, null, null, false); - } - - int rowsAffected = helper.storeByCondition(modelEntity, fieldsToSet, condition); - - if (testMode) { - for (GenericValue entity : updatedEntities) { - storeForTestRollback(new TestOperation(OperationType.UPDATE, entity)); - } - } - - return rowsAffected; - } catch (GenericEntityException e) { - String errMsg = "Failure in storeByCondition operation for entity [" + entityName + "]: " + e.toString() + ". Rolling back transaction."; - Debug.logError(e, errMsg, module); - try { - // only rollback the transaction if we started one... - TransactionUtil.rollback(beganTransaction, errMsg, e); - } catch (GenericEntityException e2) { - Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); - } - // after rolling back, rethrow the exception - throw e; - } finally { - // only commit the transaction if we started one... this will throw an exception if it fails - TransactionUtil.commit(beganTransaction); - } - } - - /** Store the Entity from the GenericValue to the persistent store - *@param value GenericValue instance containing the entity - *@return int representing number of rows effected by this operation - */ - public int store(GenericValue value) throws GenericEntityException { - return this.store(value, true); - } - - /** Store the Entity from the GenericValue to the persistent store - *@param value GenericValue instance containing the entity - *@param doCacheClear boolean that specifies whether or not to automatically clear cache entries related to this operation - *@return int representing number of rows effected by this operation - */ - public int store(GenericValue value, boolean doCacheClear) throws GenericEntityException { - boolean beganTransaction = false; - try { - if (alwaysUseTransaction) { - beganTransaction = TransactionUtil.begin(); - } - - EntityEcaRuleRunner ecaRunner = this.getEcaRuleRunner(value.getEntityName()); - ecaRunner.evalRules(EntityEcaHandler.EV_VALIDATE, EntityEcaHandler.OP_STORE, value, false); - GenericHelper helper = getEntityHelper(value.getEntityName()); - - if (doCacheClear) { - // always clear cache before the operation - ecaRunner.evalRules(EntityEcaHandler.EV_CACHE_CLEAR, EntityEcaHandler.OP_STORE, value, false); - this.clearCacheLine(value); - } - - ecaRunner.evalRules(EntityEcaHandler.EV_RUN, EntityEcaHandler.OP_STORE, value, false); - this.encryptFields(value); - - // if audit log on for any fields, save old value before the update so we still have both - if (value != null && value.getModelEntity().getHasFieldWithAuditLog()) { - createEntityAuditLogAll(value, true, false); - } - - GenericValue updatedEntity = null; - - if (testMode) { - updatedEntity = this.findOne(value.entityName, value.getPrimaryKey(), false); - } - - int retVal = helper.store(value); - - if (testMode) { - storeForTestRollback(new TestOperation(OperationType.UPDATE, updatedEntity)); - } - // refresh the valueObject to get the new version - if (value.lockEnabled()) { - refresh(value, doCacheClear); - } - - ecaRunner.evalRules(EntityEcaHandler.EV_RETURN, EntityEcaHandler.OP_STORE, value, false); - - return retVal; - } catch (GenericEntityException e) { - String errMsg = "Failure in store operation for entity [" + value.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; - Debug.logError(e, errMsg, module); - try { - // only rollback the transaction if we started one... - TransactionUtil.rollback(beganTransaction, errMsg, e); - } catch (GenericEntityException e2) { - Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); - } - // after rolling back, rethrow the exception - throw e; - } finally { - // only commit the transaction if we started one... this will throw an exception if it fails - TransactionUtil.commit(beganTransaction); - } - } - - /** Store the Entities from the List GenericValue instances to the persistent store. - *
This is different than the normal store method in that the store method only does - * an update, while the storeAll method checks to see if each entity exists, then - * either does an insert or an update as appropriate. - *
These updates all happen in one transaction, so they will either all succeed or all fail, - * if the data source supports transactions. This is just like to othersToStore feature - * of the GenericEntity on a create or store. - *@param values List of GenericValue instances containing the entities to store - *@return int representing number of rows effected by this operation - */ - public int storeAll(List values) throws GenericEntityException { - return this.storeAll(values, true); - } - - /** Store the Entities from the List GenericValue instances to the persistent store. - *
This is different than the normal store method in that the store method only does - * an update, while the storeAll method checks to see if each entity exists, then - * either does an insert or an update as appropriate. - *
These updates all happen in one transaction, so they will either all succeed or all fail, - * if the data source supports transactions. This is just like to othersToStore feature - * of the GenericEntity on a create or store. - *@param values List of GenericValue instances containing the entities to store - *@param doCacheClear boolean that specifies whether or not to automatically clear cache entries related to this operation - *@return int representing number of rows effected by this operation - */ - public int storeAll(List values, boolean doCacheClear) throws GenericEntityException { - return this.storeAll(values, doCacheClear, false); - } - - /** Store the Entities from the List GenericValue instances to the persistent store. - *
This is different than the normal store method in that the store method only does - * an update, while the storeAll method checks to see if each entity exists, then - * either does an insert or an update as appropriate. - *
These updates all happen in one transaction, so they will either all succeed or all fail, - * if the data source supports transactions. This is just like to othersToStore feature - * of the GenericEntity on a create or store. - *@param values List of GenericValue instances containing the entities to store - *@param doCacheClear boolean that specifies whether or not to automatically clear cache entries related to this operation - *@param createDummyFks boolean that specifies whether or not to automatically create "dummy" place holder FKs - *@return int representing number of rows effected by this operation - */ - public int storeAll(List values, boolean doCacheClear, boolean createDummyFks) throws GenericEntityException { - if (values == null) { - return 0; - } - - 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); - - // exists? - // 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); - this.decryptFields(existing); - } catch (GenericEntityNotFoundException e) { - existing = null; - } - - if (existing == null) { - if (createDummyFks) { - value.checkFks(true); - } - this.create(value, doCacheClear); - 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(modelEntity, (Map) value.getPrimaryKey()); - toStore.setDelegator(this); - boolean atLeastOneField = false; - Iterator 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 ((fieldValue == null && oldValue != null) || (fieldValue != null && !fieldValue.equals(oldValue))) { - toStore.put(fieldName, fieldValue); - atLeastOneField = true; - } - } - } - - if (atLeastOneField) { - if (createDummyFks) { - value.checkFks(true); - } - numberChanged += this.store(toStore, doCacheClear); - } - } - } - - return numberChanged; - } catch (GenericEntityException e) { - String errMsg = "Failure in storeAll operation: " + e.toString() + ". Rolling back transaction."; - Debug.logError(e, errMsg, module); - try { - // only rollback the transaction if we started one... - TransactionUtil.rollback(beganTransaction, errMsg, e); - } catch (GenericEntityException e2) { - Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); - } - // after rolling back, rethrow the exception - throw e; - } finally { - // only commit the transaction if we started one... this will throw an exception if it fails - TransactionUtil.commit(beganTransaction); - } - } - - public int removeAll(String entityName) throws GenericEntityException { - return removeByAnd(entityName, (Map) null); - } - - /** Remove the Entities from the List from the persistent store. - *
The List contains GenericEntity objects, can be either GenericPK or GenericValue. - *
If a certain entity contains a complete primary key, the entity in the datasource corresponding - * to that primary key will be removed, this is like a removeByPrimary Key. - *
On the other hand, if a certain entity is an incomplete or non primary key, - * if will behave like the removeByAnd method. - *
These updates all happen in one transaction, so they will either all succeed or all fail, - * if the data source supports transactions. - *@param dummyPKs Collection of GenericEntity instances containing the entities or by and fields to remove - *@return int representing number of rows effected by this operation - */ - public int removeAll(List dummyPKs) throws GenericEntityException { - return this.removeAll(dummyPKs, true); - } - - /** Remove the Entities from the List from the persistent store. - *
The List contains GenericEntity objects, can be either GenericPK or GenericValue. - *
If a certain entity contains a complete primary key, the entity in the datasource corresponding - * to that primary key will be removed, this is like a removeByPrimary Key. - *
On the other hand, if a certain entity is an incomplete or non primary key, - * if will behave like the removeByAnd method. - *
These updates all happen in one transaction, so they will either all succeed or all fail, - * if the data source supports transactions. - *@param dummyPKs Collection of GenericEntity instances containing the entities or by and fields to remove - *@param doCacheClear boolean that specifies whether or not to automatically clear cache entries related to this operation - *@return int representing number of rows effected by this operation - */ - public int removeAll(List dummyPKs, boolean doCacheClear) throws GenericEntityException { - if (dummyPKs == null) { - return 0; - } - - boolean beganTransaction = false; - int numRemoved = 0; - - try { - for (GenericEntity value: dummyPKs) { - if (value.containsPrimaryKey()) { - numRemoved += this.removeByPrimaryKey(value.getPrimaryKey(), doCacheClear); - } else { - numRemoved += this.removeByAnd(value.getEntityName(), value.getAllFields(), doCacheClear); - } - } - - return numRemoved; - } catch (GenericEntityException e) { - String errMsg = "Failure in removeAll operation: " + e.toString() + ". Rolling back transaction."; - Debug.logError(e, errMsg, module); - try { - // only rollback the transaction if we started one... - TransactionUtil.rollback(beganTransaction, errMsg, e); - } catch (GenericEntityException e2) { - Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); - } - // after rolling back, rethrow the exception - throw e; - } finally { - // only commit the transaction if we started one... this will throw an exception if it fails - TransactionUtil.commit(beganTransaction); - } - } - - // ====================================== - // ======= Find Methods ================= - // ====================================== - - /** Find a Generic Entity by its Primary Key - * NOTE 20080502: 6 references - *@param entityName The Name of the Entity as defined in the entity XML file - *@param fields The fields of the named entity to query by with their corresponding values - *@return The GenericValue corresponding to the primaryKey - */ - public GenericValue findOne(String entityName, boolean useCache, Object... fields) throws GenericEntityException { - return findOne(entityName, UtilMisc.toMap(fields), useCache); - } - /** Find a Generic Entity by its Primary Key - * NOTE 20080502: 6 references - *@param entityName The Name of the Entity as defined in the entity XML file - *@param fields The fields of the named entity to query by with their corresponding values - *@return The GenericValue corresponding to the primaryKey - */ - public GenericValue findOne(String entityName, Map fields, boolean useCache) throws GenericEntityException { - GenericPK primaryKey = this.makePK(entityName, fields); - EntityEcaRuleRunner ecaRunner = this.getEcaRuleRunner(entityName); - if (useCache) { - ecaRunner.evalRules(EntityEcaHandler.EV_CACHE_CHECK, EntityEcaHandler.OP_FIND, primaryKey, false); - - GenericValue value = this.getFromPrimaryKeyCache(primaryKey); - if (value != null) { - return value; - } - } - - boolean beganTransaction = false; - try { - if (alwaysUseTransaction) { - beganTransaction = TransactionUtil.begin(); - } - - ecaRunner.evalRules(EntityEcaHandler.EV_VALIDATE, EntityEcaHandler.OP_FIND, primaryKey, false); - - GenericHelper helper = getEntityHelper(entityName); - GenericValue value = null; - - if (!primaryKey.isPrimaryKey()) { - throw new GenericModelException("[GenericDelegator.findOne] Passed primary key is not a valid primary key: " + primaryKey); - } - ecaRunner.evalRules(EntityEcaHandler.EV_RUN, EntityEcaHandler.OP_FIND, primaryKey, false); - try { - value = helper.findByPrimaryKey(primaryKey); - } catch (GenericEntityNotFoundException e) { - value = null; - } - if (value != null) { - value.setDelegator(this); - this.decryptFields(value); - } - - if (useCache) { - if (value != null) { - ecaRunner.evalRules(EntityEcaHandler.EV_CACHE_PUT, EntityEcaHandler.OP_FIND, value, false); - this.putInPrimaryKeyCache(primaryKey, value); - } else { - this.putInPrimaryKeyCache(primaryKey, GenericValue.NULL_VALUE); - } - } - - ecaRunner.evalRules(EntityEcaHandler.EV_RETURN, EntityEcaHandler.OP_FIND, (value == null ? primaryKey : value), false); - return value; - } catch (GenericEntityException e) { - String errMsg = "Failure in findOne operation for entity [" + entityName + "]: " + e.toString() + ". Rolling back transaction."; - Debug.logError(e, errMsg, module); - try { - // only rollback the transaction if we started one... - TransactionUtil.rollback(beganTransaction, errMsg, e); - } catch (GenericEntityException e2) { - Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); - } - // after rolling back, rethrow the exception - throw e; - } finally { - // only commit the transaction if we started one... this will throw an exception if it fails - TransactionUtil.commit(beganTransaction); - } - } - - /** Find a Generic Entity by its Primary Key - * NOTE 20080502: 15 references; all changed to findOne - *@param primaryKey The primary key to find by. - *@return The GenericValue corresponding to the primaryKey - *@deprecated Use findOne() instead - */ - @Deprecated - public GenericValue findByPrimaryKey(GenericPK primaryKey) throws GenericEntityException { - return findOne(primaryKey.getEntityName(), primaryKey, false); - } - - /** Find a CACHED Generic Entity by its Primary Key - * NOTE 20080502: 2 references; all changed to findOne - *@param primaryKey The primary key to find by. - *@return The GenericValue corresponding to the primaryKey - *@deprecated Use findOne() instead - */ - @Deprecated - public GenericValue findByPrimaryKeyCache(GenericPK primaryKey) throws GenericEntityException { - return findOne(primaryKey.getEntityName(), primaryKey, true); - } - - /** Find a Generic Entity by its Primary Key - * NOTE 20080502: 21 references; all changed to findOne - *@param entityName The Name of the Entity as defined in the entity XML file - *@param fields The fields of the named entity to query by with their corresponding values - *@return The GenericValue corresponding to the primaryKey - *@deprecated Use findOne() instead - */ - @Deprecated - public GenericValue findByPrimaryKey(String entityName, Object... fields) throws GenericEntityException { - return findByPrimaryKey(entityName, UtilMisc.toMap(fields)); - } - - /** Find a Generic Entity by its Primary Key - * NOTE 20080502: 550 references (20080503 521 left); needs to be deprecated, should use findOne instead, but lots of stuff to replace! - *@param entityName The Name of the Entity as defined in the entity XML file - *@param fields The fields of the named entity to query by with their corresponding values - *@return The GenericValue corresponding to the primaryKey - */ - public GenericValue findByPrimaryKey(String entityName, Map fields) throws GenericEntityException { - return findOne(entityName, fields, false); - } - - /** Find a Generic Entity by its Primary Key - * NOTE 20080502: 0 references - *@param entityName The Name of the Entity as defined in the entity XML file - *@param singlePkValue - *@return The GenericValue corresponding to the primaryKey - *@deprecated Use findOne() instead - */ - @Deprecated - public GenericValue findByPrimaryKeySingle(String entityName, Object singlePkValue) throws GenericEntityException { - return findOne(entityName, makePKSingle(entityName, singlePkValue), false); - } - - /** Find a CACHED Generic Entity by its Primary Key - * NOTE 20080502: 2 references - *@param entityName The Name of the Entity as defined in the entity XML file - *@param fields The fields of the named entity to query by with their corresponding values - *@return The GenericValue corresponding to the primaryKey - */ - public GenericValue findByPrimaryKeyCache(String entityName, Object... fields) throws GenericEntityException { - return findByPrimaryKeyCache(entityName, UtilMisc.toMap(fields)); - } - - /** Find a CACHED Generic Entity by its Primary Key - * NOTE 20080502: 218 references - *@param entityName The Name of the Entity as defined in the entity XML file - *@param fields The fields of the named entity to query by with their corresponding values - *@return The GenericValue corresponding to the primaryKey - */ - public GenericValue findByPrimaryKeyCache(String entityName, Map fields) throws GenericEntityException { - return findOne(entityName, fields, true); - } - - /** Find a CACHED Generic Entity by its Primary Key - * NOTE 20080502: 0 references - *@param entityName The Name of the Entity as defined in the entity XML file - *@param singlePkValue - *@return The GenericValue corresponding to the primaryKey - *@deprecated Use findOne() instead - */ - @Deprecated - public GenericValue findByPrimaryKeyCacheSingle(String entityName, Object singlePkValue) throws GenericEntityException { - return findOne(entityName, makePKSingle(entityName, singlePkValue), true); - } - - /** Find a Generic Entity by its Primary Key and only returns the values requested by the passed keys (names) - * NOTE 20080502: 0 references - *@param primaryKey The primary key to find by. - *@param keys The keys, or names, of the values to retrieve; only these values will be retrieved - *@return The GenericValue corresponding to the primaryKey - *@deprecated Use findByPrimaryKeyPartial(GenericPK, Set) instead - */ - @Deprecated - public GenericValue findByPrimaryKeyPartial(GenericPK primaryKey, String... keys) throws GenericEntityException { - return findByPrimaryKeyPartial(primaryKey, UtilMisc.makeSetWritable(Arrays.asList(keys))); - } - - /** Find a Generic Entity by its Primary Key and only returns the values requested by the passed keys (names) + /** Finds GenericValues by the conditions specified in the EntityCondition object, the the EntityCondition javadoc for more details. * NOTE 20080502: 3 references - *@param primaryKey The primary key to find by. - *@param keys The keys, or names, of the values to retrieve; only these values will be retrieved - *@return The GenericValue corresponding to the primaryKey + *@param entityName The name of the Entity as defined in the entity XML file + *@param whereEntityCondition The EntityCondition object that specifies how to constrain this query before any groupings are done (if this is a view entity with group-by aliases) + *@param havingEntityCondition The EntityCondition object that specifies how to constrain this query after any groupings are done (if this is a view entity with group-by aliases) + *@param fieldsToSelect The fields of the named entity to get from the database; if empty or null all fields will be retreived + *@param orderBy The fields of the named entity to order the query by; optionally add a " ASC" for ascending or " DESC" for descending + *@param findOptions An instance of EntityFindOptions that specifies advanced query options. See the EntityFindOptions JavaDoc for more details. + *@return EntityListIterator representing the result of the query: NOTE THAT THIS MUST BE CLOSED (preferably in a finally block) WHEN YOU ARE + * DONE WITH IT, AND DON'T LEAVE IT OPEN TOO LONG BEACUSE IT WILL MAINTAIN A DATABASE CONNECTION. */ - public GenericValue findByPrimaryKeyPartial(GenericPK primaryKey, Set keys) throws GenericEntityException { - boolean beganTransaction = false; - try { - if (alwaysUseTransaction) { - beganTransaction = TransactionUtil.begin(); - } + public EntityListIterator find(String entityName, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, Set fieldsToSelect, List orderBy, EntityFindOptions findOptions) throws GenericEntityException; - EntityEcaRuleRunner ecaRunner = this.getEcaRuleRunner(primaryKey.getEntityName()); - ecaRunner.evalRules(EntityEcaHandler.EV_VALIDATE, EntityEcaHandler.OP_FIND, primaryKey, false); + /** Finds all Generic entities + * NOTE 20080502: 14 references; all changed to findList + *@param entityName The Name of the Entity as defined in the entity XML file + *@return List containing all Generic entities + *@deprecated Use findList() instead + */ + @Deprecated + public List findAll(String entityName) throws GenericEntityException; - GenericHelper helper = getEntityHelper(primaryKey.getEntityName()); - GenericValue value = null; + /** Finds all Generic entities + * NOTE 20080502: 10 references; all changed to findList + *@param entityName The Name of the Entity as defined in the entity XML file + *@param orderBy The fields of the named entity to order the query by; optionally add a " ASC" for ascending or " DESC" for descending + *@return List containing all Generic entities + *@deprecated Use findList() instead + */ + @Deprecated + public List findAll(String entityName, List orderBy) throws GenericEntityException; - if (!primaryKey.isPrimaryKey()) { - throw new GenericModelException("[GenericDelegator.findByPrimaryKey] Passed primary key is not a valid primary key: " + primaryKey); - } - - ecaRunner.evalRules(EntityEcaHandler.EV_RUN, EntityEcaHandler.OP_FIND, primaryKey, false); - try { - value = helper.findByPrimaryKeyPartial(primaryKey, keys); - } catch (GenericEntityNotFoundException e) { - value = null; - } - if (value != null) value.setDelegator(this); - - ecaRunner.evalRules(EntityEcaHandler.EV_RETURN, EntityEcaHandler.OP_FIND, primaryKey, false); - return value; - } catch (GenericEntityException e) { - String errMsg = "Failure in findByPrimaryKeyPartial operation for entity [" + primaryKey.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; - Debug.logError(e, errMsg, module); - try { - // only rollback the transaction if we started one... - TransactionUtil.rollback(beganTransaction, errMsg, e); - } catch (GenericEntityException e2) { - Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); - } - // after rolling back, rethrow the exception - throw e; - } finally { - // only commit the transaction if we started one... this will throw an exception if it fails - TransactionUtil.commit(beganTransaction); - } - } + /** Finds all Generic entities + * NOTE 20080502: 0 references + *@param entityName The Name of the Entity as defined in the entity XML file + *@param orderBy The fields of the named entity to order the query by; optionally add a " ASC" for ascending or " DESC" for descending + *@return List containing all Generic entities + *@deprecated Use findList() instead + */ + @Deprecated + public List findAll(String entityName, String... orderBy) throws GenericEntityException; /** Find a number of Generic Value objects by their Primary Keys, all at once * NOTE 20080502: 0 references @@ -1806,58 +238,7 @@ public class GenericDelegator implements DelegatorInterface { *@deprecated */ @Deprecated - public List findAllByPrimaryKeys(Collection primaryKeys) throws GenericEntityException { - boolean beganTransaction = false; - try { - if (alwaysUseTransaction) { - beganTransaction = TransactionUtil.begin(); - } - - //TODO: add eca eval calls - //TODO: maybe this should use the internal findBy methods - if (primaryKeys == null) return null; - List results = FastList.newInstance(); - - // from the delegator level this is complicated because different GenericPK - // objects in the list may correspond to different helpers - Map> pksPerHelper = FastMap.newInstance(); - for (GenericPK curPK: primaryKeys) { - String helperName = this.getEntityHelperName(curPK.getEntityName()); - List pks = pksPerHelper.get(helperName); - - if (pks == null) { - pks = FastList.newInstance(); - pksPerHelper.put(helperName, pks); - } - pks.add(curPK); - } - - for (Map.Entry> curEntry: pksPerHelper.entrySet()) { - String helperName = curEntry.getKey(); - GenericHelper helper = GenericHelperFactory.getHelper(helperName); - List values = helper.findAllByPrimaryKeys(curEntry.getValue()); - - results.addAll(values); - } - - this.decryptFields(results); - return results; - } catch (GenericEntityException e) { - String errMsg = "Failure in findAllByPrimaryKeys operation, rolling back transaction"; - Debug.logError(e, errMsg, module); - try { - // only rollback the transaction if we started one... - TransactionUtil.rollback(beganTransaction, errMsg, e); - } catch (GenericEntityException e2) { - Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); - } - // after rolling back, rethrow the exception - throw e; - } finally { - // only commit the transaction if we started one... this will throw an exception if it fails - TransactionUtil.commit(beganTransaction); - } - } + public List findAllByPrimaryKeys(Collection primaryKeys) throws GenericEntityException; /** Find a number of Generic Value objects by their Primary Keys, all at once; * this first looks in the local cache for each PK and if there then it puts it @@ -1869,103 +250,7 @@ public class GenericDelegator implements DelegatorInterface { *@deprecated */ @Deprecated - public List findAllByPrimaryKeysCache(Collection primaryKeys) throws GenericEntityException { - boolean beganTransaction = false; - try { - if (alwaysUseTransaction) { - beganTransaction = TransactionUtil.begin(); - } - - //TODO: add eca eval calls - //TODO: maybe this should use the internal findBy methods - if (primaryKeys == null) - return null; - List results = FastList.newInstance(); - - // from the delegator level this is complicated because different GenericPK - // objects in the list may correspond to different helpers - Map> pksPerHelper = FastMap.newInstance(); - for (GenericPK curPK: primaryKeys) { - GenericValue value = this.getFromPrimaryKeyCache(curPK); - - if (value != null) { - // it is in the cache, so just put the cached value in the results - results.add(value); - } else { - // is not in the cache, so put in a list for a call to the helper - String helperName = this.getEntityHelperName(curPK.getEntityName()); - List pks = pksPerHelper.get(helperName); - - if (pks == null) { - pks = FastList.newInstance(); - pksPerHelper.put(helperName, pks); - } - pks.add(curPK); - } - } - - for (Map.Entry> curEntry: pksPerHelper.entrySet()) { - String helperName = curEntry.getKey(); - GenericHelper helper = GenericHelperFactory.getHelper(helperName); - List values = helper.findAllByPrimaryKeys(curEntry.getValue()); - - this.putAllInPrimaryKeyCache(values); - results.addAll(values); - } - - this.decryptFields(results); - return results; - } catch (GenericEntityException e) { - String errMsg = "Failure in findAllByPrimaryKeysCache operation, rolling back transaction"; - Debug.logError(e, errMsg, module); - try { - // only rollback the transaction if we started one... - TransactionUtil.rollback(beganTransaction, errMsg, e); - } catch (GenericEntityException e2) { - Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); - } - // after rolling back, rethrow the exception - throw e; - } finally { - // only commit the transaction if we started one... this will throw an exception if it fails - TransactionUtil.commit(beganTransaction); - } - } - - /** Finds all Generic entities - * NOTE 20080502: 14 references; all changed to findList - *@param entityName The Name of the Entity as defined in the entity XML file - *@return List containing all Generic entities - *@deprecated Use findList() instead - */ - @Deprecated - public List findAll(String entityName) throws GenericEntityException { - return this.findList(entityName, null, null, null, null, false); - } - - /** Finds all Generic entities - * NOTE 20080502: 0 references - *@param entityName The Name of the Entity as defined in the entity XML file - *@param orderBy The fields of the named entity to order the query by; optionally add a " ASC" for ascending or " DESC" for descending - *@return List containing all Generic entities - *@deprecated Use findList() instead - */ - @Deprecated - public List findAll(String entityName, String... orderBy) throws GenericEntityException { - return findList(entityName, null, null, Arrays.asList(orderBy), null, false); - } - - /** Finds all Generic entities - * NOTE 20080502: 10 references; all changed to findList - *@param entityName The Name of the Entity as defined in the entity XML file - *@param orderBy The fields of the named entity to order the query by; optionally add a " ASC" for ascending or " DESC" for descending - *@return List containing all Generic entities - *@deprecated Use findList() instead - */ - @Deprecated - public List findAll(String entityName, List orderBy) throws GenericEntityException { - return this.findList(entityName, null, null, orderBy, null, false); - } + public List findAllByPrimaryKeysCache(Collection primaryKeys) throws GenericEntityException; /** Finds all Generic entities, looking first in the cache * NOTE 20080502: 4 references; all changed to findList @@ -1974,21 +259,7 @@ public class GenericDelegator implements DelegatorInterface { *@deprecated Use findList() instead */ @Deprecated - public List findAllCache(String entityName) throws GenericEntityException { - return this.findList(entityName, null, null, null, null, true); - } - - /** Finds all Generic entities, looking first in the cache; uses orderBy for lookup, but only keys results on the entityName and fields - * NOTE 20080502: 0 references - *@param entityName The Name of the Entity as defined in the entity XML file - *@param orderBy The fields of the named entity to order the query by; optionally add a " ASC" for ascending or " DESC" for descending - *@return List containing all Generic entities - *@deprecated Use findList() instead - */ - @Deprecated - public List findAllCache(String entityName, String... orderBy) throws GenericEntityException { - return findList(entityName, null, null, Arrays.asList(orderBy), null, true); - } + public List findAllCache(String entityName) throws GenericEntityException; /** Finds all Generic entities, looking first in the cache; uses orderBy for lookup, but only keys results on the entityName and fields * NOTE 20080502: 2 references; all changed to findList @@ -1998,130 +269,17 @@ public class GenericDelegator implements DelegatorInterface { *@deprecated Use findList() instead */ @Deprecated - public List findAllCache(String entityName, List orderBy) throws GenericEntityException { - return this.findList(entityName, null, null, orderBy, null, true); - } + public List findAllCache(String entityName, List orderBy) throws GenericEntityException; - /** Finds Generic Entity records by all of the specified fields (ie: combined using AND) - * NOTE 20080502: 1 references - * @param entityName The Name of the Entity as defined in the entity XML file - * @param fields The fields of the named entity to query by with their corresponding values - * @return List of GenericValue instances that match the query - */ - public List findByAnd(String entityName, Object... fields) throws GenericEntityException { - return findByAnd(entityName, UtilMisc.toMap(fields)); - } - - /** Finds Generic Entity records by all of the specified fields (ie: combined using AND) - * NOTE 20080502: 264 references - * @param entityName The Name of the Entity as defined in the entity XML file - * @param fields The fields of the named entity to query by with their corresponding values - * @return List of GenericValue instances that match the query - */ - public List findByAnd(String entityName, Map fields) throws GenericEntityException { - EntityCondition ecl = EntityCondition.makeCondition(fields); - return this.findList(entityName, ecl, null, null, null, false); - } - - /** Finds Generic Entity records by all of the specified fields (ie: combined using OR) - * NOTE 20080502: 0 references - * @param entityName The Name of the Entity as defined in the entity XML file - * @param fields The fields of the named entity to query by with their corresponding values - * @return List of GenericValue instances that match the query - *@deprecated Use findList() instead - */ - @Deprecated - public List findByOr(String entityName, Object... fields) throws GenericEntityException { - EntityCondition ecl = EntityCondition.makeCondition(EntityOperator.OR, fields); - return this.findList(entityName, ecl, null, null, null, false); - } - - /** Finds Generic Entity records by all of the specified fields (ie: combined using OR) - * NOTE 20080502: 1 references; all changed to findList - * @param entityName The Name of the Entity as defined in the entity XML file - * @param fields The fields of the named entity to query by with their corresponding values - * @return List of GenericValue instances that match the query - *@deprecated Use findList() instead - */ - @Deprecated - public List findByOr(String entityName, Map fields) throws GenericEntityException { - EntityCondition ecl = EntityCondition.makeCondition(fields, EntityOperator.OR); - return this.findList(entityName, ecl, null, null, null, false); - } - - /** Finds Generic Entity records by all of the specified fields (ie: combined using AND) - * NOTE 20080502: 72 references - * @param entityName The Name of the Entity as defined in the entity XML file - * @param fields The fields of the named entity to query by with their corresponding values - * @param orderBy The fields of the named entity to order the query by; - * optionally add a " ASC" for ascending or " DESC" for descending - * @return List of GenericValue instances that match the query - */ - public List findByAnd(String entityName, Map fields, List orderBy) throws GenericEntityException { - EntityCondition ecl = EntityCondition.makeCondition(fields); - return this.findList(entityName, ecl, null, orderBy, null, false); - } - - /** Finds Generic Entity records by all of the specified fields (ie: combined using OR) - * NOTE 20080502: 1 references; all changed to findList - * @param entityName The Name of the Entity as defined in the entity XML file - * @param fields The fields of the named entity to query by with their corresponding values - * @param orderBy The fields of the named entity to order the query by; - * optionally add a " ASC" for ascending or " DESC" for descending - * @return List of GenericValue instances that match the query - *@deprecated Use findList() instead - */ - @Deprecated - public List findByOr(String entityName, Map fields, List orderBy) throws GenericEntityException { - EntityCondition ecl = EntityCondition.makeCondition(fields, EntityOperator.OR); - return this.findList(entityName, ecl, null, orderBy, null, false); - } - - /** Finds Generic Entity records by all of the specified fields (ie: combined using AND), looking first in the cache; uses orderBy for lookup, but only keys results on the entityName and fields + /** Finds all Generic entities, looking first in the cache; uses orderBy for lookup, but only keys results on the entityName and fields * NOTE 20080502: 0 references *@param entityName The Name of the Entity as defined in the entity XML file - *@param fields The fields of the named entity to query by with their corresponding values - *@return List of GenericValue instances that match the query - *@deprecated Use findList() instead - */ - @Deprecated - public List findByAndCache(String entityName, Object... fields) throws GenericEntityException { - return this.findByAndCache(entityName, UtilMisc.toMap(fields)); - } - - /** Finds Generic Entity records by all of the specified fields (ie: combined using AND), looking first in the cache; uses orderBy for lookup, but only keys results on the entityName and fields - * NOTE 20080502: 91 references - *@param entityName The Name of the Entity as defined in the entity XML file - *@param fields The fields of the named entity to query by with their corresponding values - *@return List of GenericValue instances that match the query - */ - public List findByAndCache(String entityName, Map fields) throws GenericEntityException { - return this.findList(entityName, EntityCondition.makeCondition(fields), null, null, null, true); - } - - /** Finds Generic Entity records by all of the specified fields (ie: combined using AND), looking first in the cache; uses orderBy for lookup, but only keys results on the entityName and fields - * NOTE 20080502: 56 references - *@param entityName The Name of the Entity as defined in the entity XML file - *@param fields The fields of the named entity to query by with their corresponding values *@param orderBy The fields of the named entity to order the query by; optionally add a " ASC" for ascending or " DESC" for descending - *@return List of GenericValue instances that match the query - */ - public List findByAndCache(String entityName, Map fields, List orderBy) throws GenericEntityException { - return this.findList(entityName, EntityCondition.makeCondition(fields), null, orderBy, null, true); - } - - /** Finds Generic Entity records by all of the specified expressions (ie: combined using AND) - * NOTE 20080502: 0 references - *@param entityName The Name of the Entity as defined in the entity XML file - *@param expressions The expressions to use for the lookup, each consisting of at least a field name, an EntityOperator, and a value to compare to - *@return List of GenericValue instances that match the query + *@return List containing all Generic entities *@deprecated Use findList() instead */ @Deprecated - public List findByAnd(String entityName, T... expressions) throws GenericEntityException { - EntityConditionList ecl = EntityCondition.makeCondition(EntityOperator.AND, expressions); - return this.findList(entityName, ecl, null, null, null, false); - } + public List findAllCache(String entityName, String... orderBy) throws GenericEntityException; /** Finds Generic Entity records by all of the specified expressions (ie: combined using AND) * NOTE 20080502: 11 references; all changed to findList @@ -2131,10 +289,7 @@ public class GenericDelegator implements DelegatorInterface { *@deprecated Use findList() instead */ @Deprecated - public List findByAnd(String entityName, List expressions) throws GenericEntityException { - EntityConditionList ecl = EntityCondition.makeCondition(expressions, EntityOperator.AND); - return this.findList(entityName, ecl, null, null, null, false); - } + public List findByAnd(String entityName, List expressions) throws GenericEntityException; /** Finds Generic Entity records by all of the specified expressions (ie: combined using AND) * NOTE 20080502: 24 references; all changed to findList @@ -2145,12 +300,35 @@ public class GenericDelegator implements DelegatorInterface { *@deprecated Use findList() instead */ @Deprecated - public List findByAnd(String entityName, List expressions, List orderBy) throws GenericEntityException { - EntityConditionList ecl = EntityCondition.makeCondition(expressions, EntityOperator.AND); - return this.findList(entityName, ecl, null, orderBy, null, false); - } + public List findByAnd(String entityName, List expressions, List orderBy) throws GenericEntityException; - /** Finds Generic Entity records by all of the specified expressions (ie: combined using OR) + /** Finds Generic Entity records by all of the specified fields (ie: combined using AND) + * NOTE 20080502: 264 references + * @param entityName The Name of the Entity as defined in the entity XML file + * @param fields The fields of the named entity to query by with their corresponding values + * @return List of GenericValue instances that match the query + */ + public List findByAnd(String entityName, Map fields) throws GenericEntityException; + + /** Finds Generic Entity records by all of the specified fields (ie: combined using AND) + * NOTE 20080502: 72 references + * @param entityName The Name of the Entity as defined in the entity XML file + * @param fields The fields of the named entity to query by with their corresponding values + * @param orderBy The fields of the named entity to order the query by; + * optionally add a " ASC" for ascending or " DESC" for descending + * @return List of GenericValue instances that match the query + */ + public List findByAnd(String entityName, Map fields, List orderBy) throws GenericEntityException; + + /** Finds Generic Entity records by all of the specified fields (ie: combined using AND) + * NOTE 20080502: 1 references + * @param entityName The Name of the Entity as defined in the entity XML file + * @param fields The fields of the named entity to query by with their corresponding values + * @return List of GenericValue instances that match the query + */ + public List findByAnd(String entityName, Object... fields) throws GenericEntityException; + + /** Finds Generic Entity records by all of the specified expressions (ie: combined using AND) * NOTE 20080502: 0 references *@param entityName The Name of the Entity as defined in the entity XML file *@param expressions The expressions to use for the lookup, each consisting of at least a field name, an EntityOperator, and a value to compare to @@ -2158,85 +336,34 @@ public class GenericDelegator implements DelegatorInterface { *@deprecated Use findList() instead */ @Deprecated - public List findByOr(String entityName, T... expressions) throws GenericEntityException { - return this.findList(entityName, EntityCondition.makeCondition(EntityOperator.AND, expressions), null, null, null, false); - } + public List findByAnd(String entityName, T... expressions) throws GenericEntityException; - /** Finds Generic Entity records by all of the specified expressions (ie: combined using OR) - * NOTE 20080502: 2 references; all changed to findList + /** Finds Generic Entity records by all of the specified fields (ie: combined using AND), looking first in the cache; uses orderBy for lookup, but only keys results on the entityName and fields + * NOTE 20080502: 91 references *@param entityName The Name of the Entity as defined in the entity XML file - *@param expressions The expressions to use for the lookup, each consisting of at least a field name, an EntityOperator, and a value to compare to + *@param fields The fields of the named entity to query by with their corresponding values *@return List of GenericValue instances that match the query - *@deprecated Use findList() instead */ - @Deprecated - public List findByOr(String entityName, List expressions) throws GenericEntityException { - EntityConditionList ecl = EntityCondition.makeCondition(expressions, EntityOperator.OR); - return this.findList(entityName, ecl, null, null, null, false); - } + public List findByAndCache(String entityName, Map fields) throws GenericEntityException; - /** Finds Generic Entity records by all of the specified expressions (ie: combined using OR) - * NOTE 20080502: 0 references + /** Finds Generic Entity records by all of the specified fields (ie: combined using AND), looking first in the cache; uses orderBy for lookup, but only keys results on the entityName and fields + * NOTE 20080502: 56 references *@param entityName The Name of the Entity as defined in the entity XML file - *@param expressions The expressions to use for the lookup, each consisting of at least a field name, an EntityOperator, and a value to compare to + *@param fields The fields of the named entity to query by with their corresponding values *@param orderBy The fields of the named entity to order the query by; optionally add a " ASC" for ascending or " DESC" for descending *@return List of GenericValue instances that match the query - *@deprecated Use findList() instead */ - @Deprecated - public List findByOr(String entityName, List expressions, List orderBy) throws GenericEntityException { - EntityConditionList ecl = EntityCondition.makeCondition(expressions, EntityOperator.OR); - return this.findList(entityName, ecl, null, orderBy, null, false); - } + public List findByAndCache(String entityName, Map fields, List orderBy) throws GenericEntityException; - /** + /** Finds Generic Entity records by all of the specified fields (ie: combined using AND), looking first in the cache; uses orderBy for lookup, but only keys results on the entityName and fields * NOTE 20080502: 0 references + *@param entityName The Name of the Entity as defined in the entity XML file + *@param fields The fields of the named entity to query by with their corresponding values + *@return List of GenericValue instances that match the query *@deprecated Use findList() instead */ @Deprecated - public List findByLike(String entityName, Object... fields) throws GenericEntityException { - Map fieldMap = UtilMisc.toMap(fields); - List likeExpressions = FastList.newInstance(); - if (fieldMap != null) { - for (Map.Entry fieldEntry: fieldMap.entrySet()) { - likeExpressions.add(EntityCondition.makeCondition(fieldEntry.getKey(), EntityOperator.LIKE, fieldEntry.getValue())); - } - } - EntityConditionList ecl = EntityCondition.makeCondition(likeExpressions, EntityOperator.AND); - return this.findList(entityName, ecl, null, null, null, false); - } - - /** - * NOTE 20080502: 1 references; all changed to findList - *@deprecated Use findList() instead - */ - @Deprecated - public List findByLike(String entityName, Map fields) throws GenericEntityException { - List likeExpressions = FastList.newInstance(); - if (fields != null) { - for (Map.Entry fieldEntry: fields.entrySet()) { - likeExpressions.add(EntityCondition.makeCondition(fieldEntry.getKey(), EntityOperator.LIKE, fieldEntry.getValue())); - } - } - EntityConditionList ecl = EntityCondition.makeCondition(likeExpressions, EntityOperator.AND); - return this.findList(entityName, ecl, null, null, null, false); - } - - /** - * NOTE 20080502: 1 references; all changed to findList - *@deprecated Use findList() instead - */ - @Deprecated - public List findByLike(String entityName, Map fields, List orderBy) throws GenericEntityException { - List likeExpressions = FastList.newInstance(); - if (fields != null) { - for (Map.Entry fieldEntry: fields.entrySet()) { - likeExpressions.add(EntityCondition.makeCondition(fieldEntry.getKey(), EntityOperator.LIKE, fieldEntry.getValue())); - } - } - EntityConditionList ecl = EntityCondition.makeCondition(likeExpressions, EntityOperator.AND); - return this.findList(entityName, ecl, null, orderBy, null, false); - } + public List findByAndCache(String entityName, Object... fields) throws GenericEntityException; /** Finds GenericValues by the conditions specified in the EntityCondition object, the the EntityCondition javadoc for more details. * NOTE 20080502: 64 references; all changed to findList @@ -2248,9 +375,7 @@ public class GenericDelegator implements DelegatorInterface { *@deprecated Use findList() instead */ @Deprecated - public List findByCondition(String entityName, EntityCondition entityCondition, Collection fieldsToSelect, List orderBy) throws GenericEntityException { - return this.findList(entityName, entityCondition, UtilMisc.toSet(fieldsToSelect), orderBy, null, false); - } + public List findByCondition(String entityName, EntityCondition entityCondition, Collection fieldsToSelect, List orderBy) throws GenericEntityException; /** Finds GenericValues by the conditions specified in the EntityCondition object, the the EntityCondition javadoc for more details. * NOTE 20080502: 6 references; all changed to findList @@ -2264,37 +389,7 @@ public class GenericDelegator implements DelegatorInterface { *@deprecated Use findList() instead */ @Deprecated - public List findByCondition(String entityName, EntityCondition whereEntityCondition, - EntityCondition havingEntityCondition, Collection fieldsToSelect, List orderBy, EntityFindOptions findOptions) - throws GenericEntityException { - boolean beganTransaction = false; - try { - if (alwaysUseTransaction) { - beganTransaction = TransactionUtil.begin(); - } - - EntityListIterator eli = this.find(entityName, whereEntityCondition, havingEntityCondition, UtilMisc.toSet(fieldsToSelect), orderBy, findOptions); - eli.setDelegator(this); - List list = eli.getCompleteList(); - eli.close(); - - return list; - } catch (GenericEntityException e) { - String errMsg = "Failure in findByCondition operation for entity [" + entityName + "]: " + e.toString() + ". Rolling back transaction."; - Debug.logError(e, errMsg, module); - try { - // only rollback the transaction if we started one... - TransactionUtil.rollback(beganTransaction, errMsg, e); - } catch (GenericEntityException e2) { - Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); - } - // after rolling back, rethrow the exception - throw e; - } finally { - // only commit the transaction if we started one... this will throw an exception if it fails - TransactionUtil.commit(beganTransaction); - } - } + public List findByCondition(String entityName, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, Collection fieldsToSelect, List orderBy, EntityFindOptions findOptions) throws GenericEntityException; /** Finds GenericValues by the conditions specified in the EntityCondition object, looking first in the cache, see the EntityCondition javadoc for more details. * NOTE 20080502: 17 references; all changed to findList @@ -2306,9 +401,238 @@ public class GenericDelegator implements DelegatorInterface { *@deprecated Use findList() instead */ @Deprecated - public List findByConditionCache(String entityName, EntityCondition entityCondition, Collection fieldsToSelect, List orderBy) throws GenericEntityException { - return this.findList(entityName, entityCondition, UtilMisc.collectionToSet(fieldsToSelect), orderBy, null, true); - } + public List findByConditionCache(String entityName, EntityCondition entityCondition, Collection fieldsToSelect, List orderBy) throws GenericEntityException; + + /** + * NOTE 20080502: 1 references; all changed to findList + *@deprecated Use findList() instead + */ + @Deprecated + public List findByLike(String entityName, Map fields) throws GenericEntityException; + + /** + * NOTE 20080502: 1 references; all changed to findList + *@deprecated Use findList() instead + */ + @Deprecated + public List findByLike(String entityName, Map fields, List orderBy) throws GenericEntityException; + + /** + * NOTE 20080502: 0 references + *@deprecated Use findList() instead + */ + @Deprecated + public List findByLike(String entityName, Object... fields) throws GenericEntityException; + + /** Finds Generic Entity records by all of the specified expressions (ie: combined using OR) + * NOTE 20080502: 2 references; all changed to findList + *@param entityName The Name of the Entity as defined in the entity XML file + *@param expressions The expressions to use for the lookup, each consisting of at least a field name, an EntityOperator, and a value to compare to + *@return List of GenericValue instances that match the query + *@deprecated Use findList() instead + */ + @Deprecated + public List findByOr(String entityName, List expressions) throws GenericEntityException; + + /** Finds Generic Entity records by all of the specified expressions (ie: combined using OR) + * NOTE 20080502: 0 references + *@param entityName The Name of the Entity as defined in the entity XML file + *@param expressions The expressions to use for the lookup, each consisting of at least a field name, an EntityOperator, and a value to compare to + *@param orderBy The fields of the named entity to order the query by; optionally add a " ASC" for ascending or " DESC" for descending + *@return List of GenericValue instances that match the query + *@deprecated Use findList() instead + */ + @Deprecated + public List findByOr(String entityName, List expressions, List orderBy) throws GenericEntityException; + + /** Finds Generic Entity records by all of the specified fields (ie: combined using OR) + * NOTE 20080502: 1 references; all changed to findList + * @param entityName The Name of the Entity as defined in the entity XML file + * @param fields The fields of the named entity to query by with their corresponding values + * @return List of GenericValue instances that match the query + *@deprecated Use findList() instead + */ + @Deprecated + public List findByOr(String entityName, Map fields) throws GenericEntityException; + + /** Finds Generic Entity records by all of the specified fields (ie: combined using OR) + * NOTE 20080502: 1 references; all changed to findList + * @param entityName The Name of the Entity as defined in the entity XML file + * @param fields The fields of the named entity to query by with their corresponding values + * @param orderBy The fields of the named entity to order the query by; + * optionally add a " ASC" for ascending or " DESC" for descending + * @return List of GenericValue instances that match the query + *@deprecated Use findList() instead + */ + @Deprecated + public List findByOr(String entityName, Map fields, List orderBy) throws GenericEntityException; + + /** Finds Generic Entity records by all of the specified fields (ie: combined using OR) + * NOTE 20080502: 0 references + * @param entityName The Name of the Entity as defined in the entity XML file + * @param fields The fields of the named entity to query by with their corresponding values + * @return List of GenericValue instances that match the query + *@deprecated Use findList() instead + */ + @Deprecated + public List findByOr(String entityName, Object... fields) throws GenericEntityException; + + /** Finds Generic Entity records by all of the specified expressions (ie: combined using OR) + * NOTE 20080502: 0 references + *@param entityName The Name of the Entity as defined in the entity XML file + *@param expressions The expressions to use for the lookup, each consisting of at least a field name, an EntityOperator, and a value to compare to + *@return List of GenericValue instances that match the query + *@deprecated Use findList() instead + */ + @Deprecated + public List findByOr(String entityName, T... expressions) throws GenericEntityException; + + /** Find a Generic Entity by its Primary Key + * NOTE 20080502: 15 references; all changed to findOne + *@param primaryKey The primary key to find by. + *@return The GenericValue corresponding to the primaryKey + *@deprecated Use findOne() instead + */ + @Deprecated + public GenericValue findByPrimaryKey(GenericPK primaryKey) throws GenericEntityException; + + /** Find a Generic Entity by its Primary Key + * NOTE 20080502: 550 references (20080503 521 left); needs to be deprecated, should use findOne instead, but lots of stuff to replace! + *@param entityName The Name of the Entity as defined in the entity XML file + *@param fields The fields of the named entity to query by with their corresponding values + *@return The GenericValue corresponding to the primaryKey + */ + public GenericValue findByPrimaryKey(String entityName, Map fields) throws GenericEntityException; + + /** Find a Generic Entity by its Primary Key + * NOTE 20080502: 21 references; all changed to findOne + *@param entityName The Name of the Entity as defined in the entity XML file + *@param fields The fields of the named entity to query by with their corresponding values + *@return The GenericValue corresponding to the primaryKey + *@deprecated Use findOne() instead + */ + @Deprecated + public GenericValue findByPrimaryKey(String entityName, Object... fields) throws GenericEntityException; + + /** Find a CACHED Generic Entity by its Primary Key + * NOTE 20080502: 2 references; all changed to findOne + *@param primaryKey The primary key to find by. + *@return The GenericValue corresponding to the primaryKey + *@deprecated Use findOne() instead + */ + @Deprecated + public GenericValue findByPrimaryKeyCache(GenericPK primaryKey) throws GenericEntityException; + + /** Find a CACHED Generic Entity by its Primary Key + * NOTE 20080502: 218 references + *@param entityName The Name of the Entity as defined in the entity XML file + *@param fields The fields of the named entity to query by with their corresponding values + *@return The GenericValue corresponding to the primaryKey + */ + public GenericValue findByPrimaryKeyCache(String entityName, Map fields) throws GenericEntityException; + + /** Find a CACHED Generic Entity by its Primary Key + * NOTE 20080502: 2 references + *@param entityName The Name of the Entity as defined in the entity XML file + *@param fields The fields of the named entity to query by with their corresponding values + *@return The GenericValue corresponding to the primaryKey + */ + public GenericValue findByPrimaryKeyCache(String entityName, Object... fields) throws GenericEntityException; + + /** Find a CACHED Generic Entity by its Primary Key + * NOTE 20080502: 0 references + *@param entityName The Name of the Entity as defined in the entity XML file + *@param singlePkValue + *@return The GenericValue corresponding to the primaryKey + *@deprecated Use findOne() instead + */ + @Deprecated + public GenericValue findByPrimaryKeyCacheSingle(String entityName, Object singlePkValue) throws GenericEntityException; + + /** Find a Generic Entity by its Primary Key and only returns the values requested by the passed keys (names) + * NOTE 20080502: 3 references + *@param primaryKey The primary key to find by. + *@param keys The keys, or names, of the values to retrieve; only these values will be retrieved + *@return The GenericValue corresponding to the primaryKey + */ + public GenericValue findByPrimaryKeyPartial(GenericPK primaryKey, Set keys) throws GenericEntityException; + + /** Find a Generic Entity by its Primary Key and only returns the values requested by the passed keys (names) + * NOTE 20080502: 0 references + *@param primaryKey The primary key to find by. + *@param keys The keys, or names, of the values to retrieve; only these values will be retrieved + *@return The GenericValue corresponding to the primaryKey + *@deprecated Use findByPrimaryKeyPartial(GenericPK, Set) instead + */ + @Deprecated + public GenericValue findByPrimaryKeyPartial(GenericPK primaryKey, String... keys) throws GenericEntityException; + + /** Find a Generic Entity by its Primary Key + * NOTE 20080502: 0 references + *@param entityName The Name of the Entity as defined in the entity XML file + *@param singlePkValue + *@return The GenericValue corresponding to the primaryKey + *@deprecated Use findOne() instead + */ + @Deprecated + public GenericValue findByPrimaryKeySingle(String entityName, Object singlePkValue) throws GenericEntityException; + + /** + * NOTE 20080502: 3 references; all changed to findCoundByCondition + *@deprecated Use findCountByCondition() instead + */ + @Deprecated + public long findCountByAnd(String entityName) throws GenericEntityException; + + /** + * NOTE 20080502: 8 references; all changed to use findCountByCondition + *@deprecated Use findCountByCondition() instead + */ + @Deprecated + public long findCountByAnd(String entityName, Map fields) throws GenericEntityException; + + /** + * NOTE 20080502: 1 references; all changed to use findCountByCondition + *@deprecated Use findCountByCondition() instead + */ + @Deprecated + public long findCountByAnd(String entityName, Object... fields) throws GenericEntityException; + + /** + * NOTE 20080502: 17 references; all changed to use remaining findCountByCondition + *@deprecated Use findCountByCondition() instead + */ + @Deprecated + public long findCountByCondition(String entityName, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition) throws GenericEntityException; + + /** + * NOTE 20080502: 2 references + */ + public long findCountByCondition(String entityName, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, EntityFindOptions findOptions) throws GenericEntityException; + + /** Finds GenericValues by the conditions specified in the EntityCondition object, the the EntityCondition javadoc for more details. + * NOTE 20080502: 12 references + *@param entityName The name of the Entity as defined in the entity XML file + *@param entityCondition The EntityCondition object that specifies how to constrain this query before any groupings are done (if this is a view entity with group-by aliases) + *@param fieldsToSelect The fields of the named entity to get from the database; if empty or null all fields will be retreived + *@param orderBy The fields of the named entity to order the query by; optionally add a " ASC" for ascending or " DESC" for descending + *@param findOptions An instance of EntityFindOptions that specifies advanced query options. See the EntityFindOptions JavaDoc for more details. + *@return List of GenericValue objects representing the result + */ + public List findList(String entityName, EntityCondition entityCondition, Set fieldsToSelect, List orderBy, EntityFindOptions findOptions, boolean useCache) throws GenericEntityException; + + /** Finds GenericValues by the conditions specified in the EntityCondition object, the the EntityCondition javadoc for more details. + * NOTE 20080502: 9 references + *@param dynamicViewEntity The DynamicViewEntity to use for the entity model for this query; generally created on the fly for limited use + *@param whereEntityCondition The EntityCondition object that specifies how to constrain this query before any groupings are done (if this is a view entity with group-by aliases) + *@param havingEntityCondition The EntityCondition object that specifies how to constrain this query after any groupings are done (if this is a view entity with group-by aliases) + *@param fieldsToSelect The fields of the named entity to get from the database; if empty or null all fields will be retreived + *@param orderBy The fields of the named entity to order the query by; optionally add a " ASC" for ascending or " DESC" for descending + *@param findOptions An instance of EntityFindOptions that specifies advanced query options. See the EntityFindOptions JavaDoc for more details. + *@return EntityListIterator representing the result of the query: NOTE THAT THIS MUST BE CLOSED WHEN YOU ARE + * DONE WITH IT, AND DON'T LEAVE IT OPEN TOO LONG BEACUSE IT WILL MAINTAIN A DATABASE CONNECTION. + */ + public EntityListIterator findListIteratorByCondition(DynamicViewEntity dynamicViewEntity, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, Collection fieldsToSelect, List orderBy, EntityFindOptions findOptions) throws GenericEntityException; /** Finds GenericValues by the conditions specified in the EntityCondition object, the the EntityCondition javadoc for more details. * NOTE 20080502: 26 references; all changed to find @@ -2321,10 +645,7 @@ public class GenericDelegator implements DelegatorInterface { *@deprecated Use find() instead */ @Deprecated - public EntityListIterator findListIteratorByCondition(String entityName, EntityCondition entityCondition, - Collection fieldsToSelect, List orderBy) throws GenericEntityException { - return this.find(entityName, entityCondition, null, UtilMisc.collectionToSet(fieldsToSelect), orderBy, null); - } + public EntityListIterator findListIteratorByCondition(String entityName, EntityCondition entityCondition, Collection fieldsToSelect, List orderBy) throws GenericEntityException; /** Finds GenericValues by the conditions specified in the EntityCondition object, the the EntityCondition javadoc for more details. * NOTE 20080502: 12 references; all changed to find @@ -2339,290 +660,108 @@ public class GenericDelegator implements DelegatorInterface { *@deprecated Use find() instead */ @Deprecated - public EntityListIterator findListIteratorByCondition(String entityName, EntityCondition whereEntityCondition, - EntityCondition havingEntityCondition, Collection fieldsToSelect, List orderBy, EntityFindOptions findOptions) - throws GenericEntityException { + public EntityListIterator findListIteratorByCondition(String entityName, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, Collection fieldsToSelect, List orderBy, EntityFindOptions findOptions) throws GenericEntityException; - return this.find(entityName, whereEntityCondition, havingEntityCondition, UtilMisc.collectionToSet(fieldsToSelect), orderBy, findOptions); - } - - /** Finds GenericValues by the conditions specified in the EntityCondition object, the the EntityCondition javadoc for more details. - * NOTE 20080502: 3 references - *@param entityName The name of the Entity as defined in the entity XML file - *@param whereEntityCondition The EntityCondition object that specifies how to constrain this query before any groupings are done (if this is a view entity with group-by aliases) - *@param havingEntityCondition The EntityCondition object that specifies how to constrain this query after any groupings are done (if this is a view entity with group-by aliases) - *@param fieldsToSelect The fields of the named entity to get from the database; if empty or null all fields will be retreived - *@param orderBy The fields of the named entity to order the query by; optionally add a " ASC" for ascending or " DESC" for descending - *@param findOptions An instance of EntityFindOptions that specifies advanced query options. See the EntityFindOptions JavaDoc for more details. - *@return EntityListIterator representing the result of the query: NOTE THAT THIS MUST BE CLOSED (preferably in a finally block) WHEN YOU ARE - * DONE WITH IT, AND DON'T LEAVE IT OPEN TOO LONG BEACUSE IT WILL MAINTAIN A DATABASE CONNECTION. + /** Find a Generic Entity by its Primary Key + * NOTE 20080502: 6 references + *@param entityName The Name of the Entity as defined in the entity XML file + *@param fields The fields of the named entity to query by with their corresponding values + *@return The GenericValue corresponding to the primaryKey */ - public EntityListIterator find(String entityName, EntityCondition whereEntityCondition, - EntityCondition havingEntityCondition, Set fieldsToSelect, List orderBy, EntityFindOptions findOptions) - throws GenericEntityException { + public GenericValue findOne(String entityName, boolean useCache, Object... fields) throws GenericEntityException; - // if there is no transaction throw an exception, we don't want to create a transaction here since closing it would mess up the ELI - if (!TransactionUtil.isTransactionInPlace()) { - //throw new GenericEntityException("ERROR: Cannot do a find that returns an EntityListIterator with no transaction in place. Wrap this call in a transaction."); - - //throwing an exception is a little harsh for now, just display a really big error message since we want to get all of these fixed... - Exception newE = new Exception("Stack Trace"); - Debug.logError(newE, "ERROR: Cannot do a find that returns an EntityListIterator with no transaction in place. Wrap this call in a transaction.", module); - } - - ModelEntity modelEntity = getModelReader().getModelEntity(entityName); - GenericValue dummyValue = GenericValue.create(modelEntity); - EntityEcaRuleRunner ecaRunner = this.getEcaRuleRunner(modelEntity.getEntityName()); - ecaRunner.evalRules(EntityEcaHandler.EV_VALIDATE, EntityEcaHandler.OP_FIND, dummyValue, false); - - if (whereEntityCondition != null) { - whereEntityCondition.checkCondition(modelEntity); - whereEntityCondition.encryptConditionFields(modelEntity, this); - } - if (havingEntityCondition != null) { - havingEntityCondition.checkCondition(modelEntity); - havingEntityCondition.encryptConditionFields(modelEntity, this); - } - - ecaRunner.evalRules(EntityEcaHandler.EV_RUN, EntityEcaHandler.OP_FIND, dummyValue, false); - GenericHelper helper = getEntityHelper(modelEntity.getEntityName()); - EntityListIterator eli = helper.findListIteratorByCondition(modelEntity, whereEntityCondition, - havingEntityCondition, fieldsToSelect, orderBy, findOptions); - eli.setDelegator(this); - - ecaRunner.evalRules(EntityEcaHandler.EV_RETURN, EntityEcaHandler.OP_FIND, dummyValue, false); - return eli; - } - - /** Finds GenericValues by the conditions specified in the EntityCondition object, the the EntityCondition javadoc for more details. - * NOTE 20080502: 12 references - *@param entityName The name of the Entity as defined in the entity XML file - *@param entityCondition The EntityCondition object that specifies how to constrain this query before any groupings are done (if this is a view entity with group-by aliases) - *@param fieldsToSelect The fields of the named entity to get from the database; if empty or null all fields will be retreived - *@param orderBy The fields of the named entity to order the query by; optionally add a " ASC" for ascending or " DESC" for descending - *@param findOptions An instance of EntityFindOptions that specifies advanced query options. See the EntityFindOptions JavaDoc for more details. - *@return List of GenericValue objects representing the result + /** Find a Generic Entity by its Primary Key + * NOTE 20080502: 6 references + *@param entityName The Name of the Entity as defined in the entity XML file + *@param fields The fields of the named entity to query by with their corresponding values + *@return The GenericValue corresponding to the primaryKey */ - public List findList(String entityName, EntityCondition entityCondition, - Set fieldsToSelect, List orderBy, EntityFindOptions findOptions, boolean useCache) - throws GenericEntityException { + public GenericValue findOne(String entityName, Map fields, boolean useCache) throws GenericEntityException; - EntityEcaRuleRunner ecaRunner = null; - GenericValue dummyValue = null; - if (useCache) { - ecaRunner = this.getEcaRuleRunner(entityName); - ModelEntity modelEntity = getModelReader().getModelEntity(entityName); - dummyValue = GenericValue.create(modelEntity); - ecaRunner.evalRules(EntityEcaHandler.EV_CACHE_CHECK, EntityEcaHandler.OP_FIND, dummyValue, false); + public Cache getCache(); - List cacheList = this.cache.get(entityName, entityCondition, orderBy); - if (cacheList != null) { - return cacheList; - } - } + public GenericDelegator getDelegator(String delegatorName); - boolean beganTransaction = false; - try { - if (alwaysUseTransaction) { - beganTransaction = TransactionUtil.begin(); - } + public String getDelegatorName(); - EntityListIterator eli = this.find(entityName, entityCondition, null, fieldsToSelect, orderBy, findOptions); - eli.setDelegator(this); - List list = eli.getCompleteList(); - eli.close(); + public EntityEcaHandler getEntityEcaHandler(); - if (useCache) { - ecaRunner.evalRules(EntityEcaHandler.EV_CACHE_PUT, EntityEcaHandler.OP_FIND, dummyValue, false); - this.cache.put(entityName, entityCondition, orderBy, list); - } - return list; - } catch (GenericEntityException e) { - String errMsg = "Failure in findByCondition operation for entity [" + entityName + "]: " + e.toString() + ". Rolling back transaction."; - Debug.logError(e, errMsg, module); - try { - // only rollback the transaction if we started one... - TransactionUtil.rollback(beganTransaction, errMsg, e); - } catch (GenericEntityException e2) { - Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); - } - // after rolling back, rethrow the exception - throw e; - } finally { - // only commit the transaction if we started one... this will throw an exception if it fails - TransactionUtil.commit(beganTransaction); - } - } - - /** Finds GenericValues by the conditions specified in the EntityCondition object, the the EntityCondition javadoc for more details. - * NOTE 20080502: 9 references - *@param dynamicViewEntity The DynamicViewEntity to use for the entity model for this query; generally created on the fly for limited use - *@param whereEntityCondition The EntityCondition object that specifies how to constrain this query before any groupings are done (if this is a view entity with group-by aliases) - *@param havingEntityCondition The EntityCondition object that specifies how to constrain this query after any groupings are done (if this is a view entity with group-by aliases) - *@param fieldsToSelect The fields of the named entity to get from the database; if empty or null all fields will be retreived - *@param orderBy The fields of the named entity to order the query by; optionally add a " ASC" for ascending or " DESC" for descending - *@param findOptions An instance of EntityFindOptions that specifies advanced query options. See the EntityFindOptions JavaDoc for more details. - *@return EntityListIterator representing the result of the query: NOTE THAT THIS MUST BE CLOSED WHEN YOU ARE - * DONE WITH IT, AND DON'T LEAVE IT OPEN TOO LONG BEACUSE IT WILL MAINTAIN A DATABASE CONNECTION. + /** Gets a field type instance by name from the helper that corresponds to the specified entity + *@param entity The entity + *@param type The name of the type + *@return ModelFieldType instance for the named type from the helper that corresponds to the specified entity */ - public EntityListIterator findListIteratorByCondition(DynamicViewEntity dynamicViewEntity, EntityCondition whereEntityCondition, - EntityCondition havingEntityCondition, Collection fieldsToSelect, List orderBy, EntityFindOptions findOptions) - throws GenericEntityException { + public ModelFieldType getEntityFieldType(ModelEntity entity, String type) throws GenericEntityException; - // if there is no transaction throw an exception, we don't want to create a transaction here since closing it would mess up the ELI - if (!TransactionUtil.isTransactionInPlace()) { - //throw new GenericEntityException("ERROR: Cannot do a find that returns an EntityListIterator with no transaction in place. Wrap this call in a transaction."); - - //throwing an exception is a little harsh for now, just display a really big error message since we want to get all of these fixed... - Exception newE = new Exception("Stack Trace"); - Debug.logError(newE, "ERROR: Cannot do a find that returns an EntityListIterator with no transaction in place. Wrap this call in a transaction.", module); - } - - ModelViewEntity modelViewEntity = dynamicViewEntity.makeModelViewEntity(this); - if (whereEntityCondition != null) whereEntityCondition.checkCondition(modelViewEntity); - if (havingEntityCondition != null) havingEntityCondition.checkCondition(modelViewEntity); - - GenericHelper helper = getEntityHelper(dynamicViewEntity.getOneRealEntityName()); - EntityListIterator eli = helper.findListIteratorByCondition(modelViewEntity, whereEntityCondition, - havingEntityCondition, fieldsToSelect, orderBy, findOptions); - eli.setDelegator(this); - //TODO: add decrypt fields - return eli; - } - - /** - * NOTE 20080502: 3 references; all changed to findCoundByCondition - *@deprecated Use findCountByCondition() instead + /** Gets field type names from the helper that corresponds to the specified entity + *@param entity The entity + *@return Collection of field type names from the helper that corresponds to the specified entity */ - @Deprecated - public long findCountByAnd(String entityName) throws GenericEntityException { - return findCountByCondition(entityName, null, null, null); - } + public Collection getEntityFieldTypeNames(ModelEntity entity) throws GenericEntityException; - /** - * NOTE 20080502: 1 references; all changed to use findCountByCondition - *@deprecated Use findCountByCondition() instead + /** Gets the helper name that corresponds to this delegator and the specified entityName + *@param entityName The name of the entity to get the helper for + *@return String with the helper name that corresponds to this delegator and the specified entityName */ - @Deprecated - public long findCountByAnd(String entityName, Object... fields) throws GenericEntityException { - return findCountByCondition(entityName, EntityCondition.makeCondition(UtilMisc.toMap(fields), EntityOperator.AND), null, null); - } + public String getEntityGroupName(String entityName); - /** - * NOTE 20080502: 8 references; all changed to use findCountByCondition - *@deprecated Use findCountByCondition() instead + /** Gets the an instance of helper that corresponds to this delegator and the specified entity + *@param entity The entity to get the helper for + *@return GenericHelper that corresponds to this delegator and the specified entity */ - @Deprecated - public long findCountByAnd(String entityName, Map fields) throws GenericEntityException { - return findCountByCondition(entityName, EntityCondition.makeCondition(fields, EntityOperator.AND), null, null); - } + public GenericHelper getEntityHelper(ModelEntity entity) throws GenericEntityException; - /** - * NOTE 20080502: 17 references; all changed to use remaining findCountByCondition - *@deprecated Use findCountByCondition() instead + /** Gets the an instance of helper that corresponds to this delegator and the specified entityName + *@param entityName The name of the entity to get the helper for + *@return GenericHelper that corresponds to this delegator and the specified entityName */ - @Deprecated - public long findCountByCondition(String entityName, EntityCondition whereEntityCondition, - EntityCondition havingEntityCondition) throws GenericEntityException { - return findCountByCondition(entityName, whereEntityCondition, havingEntityCondition, null); - } + public GenericHelper getEntityHelper(String entityName) throws GenericEntityException; - /** - * NOTE 20080502: 2 references + /** Gets the helper name that corresponds to this delegator and the specified entity + *@param entity The entity to get the helper for + *@return String with the helper name that corresponds to this delegator and the specified entity */ - public long findCountByCondition(String entityName, EntityCondition whereEntityCondition, - EntityCondition havingEntityCondition, EntityFindOptions findOptions) throws GenericEntityException { + public String getEntityHelperName(ModelEntity entity); - boolean beganTransaction = false; - try { - if (alwaysUseTransaction) { - beganTransaction = TransactionUtil.begin(); - } - - ModelEntity modelEntity = getModelReader().getModelEntity(entityName); - GenericValue dummyValue = GenericValue.create(modelEntity); - EntityEcaRuleRunner ecaRunner = this.getEcaRuleRunner(modelEntity.getEntityName()); - ecaRunner.evalRules(EntityEcaHandler.EV_VALIDATE, EntityEcaHandler.OP_FIND, dummyValue, false); - - if (whereEntityCondition != null) { - whereEntityCondition.checkCondition(modelEntity); - whereEntityCondition.encryptConditionFields(modelEntity, this); - } - if (havingEntityCondition != null) { - havingEntityCondition.checkCondition(modelEntity); - havingEntityCondition.encryptConditionFields(modelEntity, this); - } - - ecaRunner.evalRules(EntityEcaHandler.EV_RUN, EntityEcaHandler.OP_FIND, dummyValue, false); - GenericHelper helper = getEntityHelper(modelEntity.getEntityName()); - long count = helper.findCountByCondition(modelEntity, whereEntityCondition, havingEntityCondition, findOptions); - - ecaRunner.evalRules(EntityEcaHandler.EV_RETURN, EntityEcaHandler.OP_FIND, dummyValue, false); - return count; - } catch (GenericEntityException e) { - String errMsg = "Failure in findListIteratorByCondition operation for entity [DynamicView]: " + e.toString() + ". Rolling back transaction."; - Debug.logError(e, errMsg, module); - try { - // only rollback the transaction if we started one... - TransactionUtil.rollback(beganTransaction, errMsg, e); - } catch (GenericEntityException e2) { - Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); - } - // after rolling back, rethrow the exception - throw e; - } finally { - // only commit the transaction if we started one... this will throw an exception if it fails - TransactionUtil.commit(beganTransaction); - } - } - - /** - * Get the named Related Entity for the GenericValue from the persistent store across another Relation. - * Helps to get related Values in a multi-to-multi relationship. - * NOTE 20080502: 3 references - * @param relationNameOne String containing the relation name which is the - * combination of relation.title and relation.rel-entity-name as - * specified in the entity XML definition file, for first relation - * @param relationNameTwo String containing the relation name for second relation - * @param value GenericValue instance containing the entity - * @param orderBy The fields of the named entity to order the query by; may be null; - * optionally add a " ASC" for ascending or " DESC" for descending - * @return List of GenericValue instances as specified in the relation definition + /** Gets the helper name that corresponds to this delegator and the specified entityName + *@param entityName The name of the entity to get the helper name for + *@return String with the helper name that corresponds to this delegator and the specified entityName */ - public List getMultiRelation(GenericValue value, String relationNameOne, String relationNameTwo, List orderBy) throws GenericEntityException { - boolean beganTransaction = false; - try { - if (alwaysUseTransaction) { - beganTransaction = TransactionUtil.begin(); - } + public String getEntityHelperName(String entityName); - //TODO: add eca eval calls - // traverse the relationships - ModelEntity modelEntity = value.getModelEntity(); - ModelRelation modelRelationOne = modelEntity.getRelation(relationNameOne); - ModelEntity modelEntityOne = getModelEntity(modelRelationOne.getRelEntityName()); - ModelRelation modelRelationTwo = modelEntityOne.getRelation(relationNameTwo); - ModelEntity modelEntityTwo = getModelEntity(modelRelationTwo.getRelEntityName()); + public GenericValue getFromPrimaryKeyCache(GenericPK primaryKey); - GenericHelper helper = getEntityHelper(modelEntity); + /** Gets the helper name that corresponds to this delegator and the specified entityName + *@param groupName The name of the group to get the helper name for + *@return String with the helper name that corresponds to this delegator and the specified entityName + */ + public String getGroupHelperName(String groupName); - return helper.findByMultiRelation(value, modelRelationOne, modelEntityOne, modelRelationTwo, modelEntityTwo, orderBy); - } catch (GenericEntityException e) { - String errMsg = "Failure in getMultiRelation operation for entity [" + value.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; - Debug.logError(e, errMsg, module); - try { - // only rollback the transaction if we started one... - TransactionUtil.rollback(beganTransaction, errMsg, e); - } catch (GenericEntityException e2) { - Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); - } - // after rolling back, rethrow the exception - throw e; - } finally { - // only commit the transaction if we started one... this will throw an exception if it fails - TransactionUtil.commit(beganTransaction); - } - } + public Locale getLocale(); + + /** Gets the instance of ModelEntity that corresponds to this delegator and the specified entityName + *@param entityName The name of the entity to get + *@return ModelEntity that corresponds to this delegator and the specified entityName + */ + public ModelEntity getModelEntity(String entityName); + + /** Gets a Map of entity name & entity model pairs that are in the named group + *@param groupName The name of the group + *@return Map of entityName String keys and ModelEntity instance values + */ + public Map getModelEntityMapByGroup(String groupName) throws GenericEntityException; + + public ModelFieldTypeReader getModelFieldTypeReader(ModelEntity entity); + + /** Gets the instance of ModelGroupReader that corresponds to this delegator + *@return ModelGroupReader that corresponds to this delegator + */ + public ModelGroupReader getModelGroupReader(); + + /** Gets the instance of ModelReader that corresponds to this delegator + *@return ModelReader that corresponds to this delegator + */ + public ModelReader getModelReader(); /** * Get the named Related Entity for the GenericValue from the persistent store across another Relation. @@ -2637,9 +776,57 @@ public class GenericDelegator implements DelegatorInterface { *@deprecated Use getMultiRelation() instead */ @Deprecated - public List getMultiRelation(GenericValue value, String relationNameOne, String relationNameTwo) throws GenericEntityException { - return getMultiRelation(value, relationNameOne, relationNameTwo, null); - } + public List getMultiRelation(GenericValue value, String relationNameOne, String relationNameTwo) throws GenericEntityException; + + /** + * Get the named Related Entity for the GenericValue from the persistent store across another Relation. + * Helps to get related Values in a multi-to-multi relationship. + * NOTE 20080502: 3 references + * @param relationNameOne String containing the relation name which is the + * combination of relation.title and relation.rel-entity-name as + * specified in the entity XML definition file, for first relation + * @param relationNameTwo String containing the relation name for second relation + * @param value GenericValue instance containing the entity + * @param orderBy The fields of the named entity to order the query by; may be null; + * optionally add a " ASC" for ascending or " DESC" for descending + * @return List of GenericValue instances as specified in the relation definition + */ + public List getMultiRelation(GenericValue value, String relationNameOne, String relationNameTwo, List orderBy) throws GenericEntityException; + + /** Get the next guaranteed unique seq id from the sequence with the given sequence name; + * if the named sequence doesn't exist, it will be created + *@param seqName The name of the sequence to get the next seq id from + *@return String with the next sequenced id for the given sequence name + */ + public String getNextSeqId(String seqName); + + /** Get the next guaranteed unique seq id from the sequence with the given sequence name; + * if the named sequence doesn't exist, it will be created + *@param seqName The name of the sequence to get the next seq id from + *@param staggerMax The maximum amount to stagger the sequenced ID, if 1 the sequence will be incremented by 1, otherwise the current sequence ID will be incremented by a value between 1 and staggerMax + *@return Long with the next seq id for the given sequence name + */ + public String getNextSeqId(String seqName, long staggerMax); + + /** Get the next guaranteed unique seq id from the sequence with the given sequence name; + * if the named sequence doesn't exist, it will be created + *@param seqName The name of the sequence to get the next seq id from + *@return Long with the next sequenced id for the given sequence name + */ + public Long getNextSeqIdLong(String seqName); + + /** Get the next guaranteed unique seq id from the sequence with the given sequence name; + * if the named sequence doesn't exist, it will be created + *@param seqName The name of the sequence to get the next seq id from + *@param staggerMax The maximum amount to stagger the sequenced ID, if 1 the sequence will be incremented by 1, otherwise the current sequence ID will be incremented by a value between 1 and staggerMax + *@return Long with the next seq id for the given sequence name + */ + public Long getNextSeqIdLong(String seqName, long staggerMax); + + /** Gets the name of the server configuration that corresponds to this delegator + * @return server configuration name + */ + public String getOriginalDelegatorName(); /** Get the named Related Entity for the GenericValue from the persistent store * NOTE 20080502: 1 references; all changed to use remaining getRelated @@ -2651,40 +838,7 @@ public class GenericDelegator implements DelegatorInterface { *@deprecated Use getRelated() instead */ @Deprecated - public List getRelated(String relationName, GenericValue value) throws GenericEntityException { - return getRelated(relationName, null, null, value); - } - - /** Get the named Related Entity for the GenericValue from the persistent store - * NOTE 20080502: 1 references; all changed to use getRelated - * @param relationName String containing the relation name which is the - * combination of relation.title and relation.rel-entity-name as - * specified in the entity XML definition file - * @param byAndFields the fields that must equal in order to keep; may be null - * @param value GenericValue instance containing the entity - * @return List of GenericValue instances as specified in the relation definition - *@deprecated Use getRelated() instead - */ - @Deprecated - public List getRelatedByAnd(String relationName, Map byAndFields, GenericValue value) throws GenericEntityException { - return this.getRelated(relationName, byAndFields, null, value); - } - - /** Get the named Related Entity for the GenericValue from the persistent store - * NOTE 20080502: 1 references; all changed to use getRelated - * @param relationName String containing the relation name which is the - * combination of relation.title and relation.rel-entity-name as - * specified in the entity XML definition file - * @param orderBy The fields of the named entity to order the query by; may be null; - * optionally add a " ASC" for ascending or " DESC" for descending - * @param value GenericValue instance containing the entity - * @return List of GenericValue instances as specified in the relation definition - *@deprecated Use getRelated() instead - */ - @Deprecated - public List getRelatedOrderBy(String relationName, List orderBy, GenericValue value) throws GenericEntityException { - return this.getRelated(relationName, null, orderBy, value); - } + public List getRelated(String relationName, GenericValue value) throws GenericEntityException; /** Get the named Related Entity for the GenericValue from the persistent store * NOTE 20080502: 5 references @@ -2697,25 +851,30 @@ public class GenericDelegator implements DelegatorInterface { * @param value GenericValue instance containing the entity * @return List of GenericValue instances as specified in the relation definition */ - public List getRelated(String relationName, Map byAndFields, List orderBy, GenericValue value) throws GenericEntityException { - ModelEntity modelEntity = value.getModelEntity(); - ModelRelation relation = modelEntity.getRelation(relationName); + public List getRelated(String relationName, Map byAndFields, List orderBy, GenericValue value) throws GenericEntityException; - if (relation == null) { - throw new GenericModelException("Could not find relation for relationName: " + relationName + " for value " + value); - } + /** Get the named Related Entity for the GenericValue from the persistent store + * NOTE 20080502: 1 references; all changed to use getRelated + * @param relationName String containing the relation name which is the + * combination of relation.title and relation.rel-entity-name as + * specified in the entity XML definition file + * @param byAndFields the fields that must equal in order to keep; may be null + * @param value GenericValue instance containing the entity + * @return List of GenericValue instances as specified in the relation definition + *@deprecated Use getRelated() instead + */ + @Deprecated + public List getRelatedByAnd(String relationName, Map byAndFields, GenericValue value) throws GenericEntityException; - // put the byAndFields (if not null) into the hash map first, - // they will be overridden by value's fields if over-specified this is important for security and cleanliness - Map fields = FastMap.newInstance(); - if (byAndFields != null) fields.putAll(byAndFields); - for (int i = 0; i < relation.getKeyMapsSize(); i++) { - ModelKeyMap keyMap = relation.getKeyMap(i); - fields.put(keyMap.getRelFieldName(), value.get(keyMap.getFieldName())); - } - - return this.findByAnd(relation.getRelEntityName(), fields, orderBy); - } + /** Get the named Related Entity for the GenericValue from the persistent store, checking first in the cache to see if the desired value is there + * NOTE 20080502: 4 references + * @param relationName String containing the relation name which is the + * combination of relation.title and relation.rel-entity-name as + * specified in the entity XML definition file + * @param value GenericValue instance containing the entity + * @return List of GenericValue instances as specified in the relation definition + */ + public List getRelatedCache(String relationName, GenericValue value) throws GenericEntityException; /** Get a dummy primary key for the named Related Entity for the GenericValue * NOTE 20080502: 2 references @@ -2726,829 +885,307 @@ public class GenericDelegator implements DelegatorInterface { * @param value GenericValue instance containing the entity * @return GenericPK containing a possibly incomplete PrimaryKey object representing the related entity or entities */ - public GenericPK getRelatedDummyPK(String relationName, Map byAndFields, GenericValue value) throws GenericEntityException { - ModelEntity modelEntity = value.getModelEntity(); - ModelRelation relation = modelEntity.getRelation(relationName); - - if (relation == null) { - throw new GenericModelException("Could not find relation for relationName: " + relationName + " for value " + value); - } - ModelEntity relatedEntity = getModelReader().getModelEntity(relation.getRelEntityName()); - - // put the byAndFields (if not null) into the hash map first, - // they will be overridden by value's fields if over-specified this is important for security and cleanliness - Map fields = FastMap.newInstance(); - if (byAndFields != null) fields.putAll(byAndFields); - for (int i = 0; i < relation.getKeyMapsSize(); i++) { - ModelKeyMap keyMap = relation.getKeyMap(i); - fields.put(keyMap.getRelFieldName(), value.get(keyMap.getFieldName())); - } - - GenericPK dummyPK = GenericPK.create(relatedEntity, fields); - dummyPK.setDelegator(this); - return dummyPK; - } - - /** Get the named Related Entity for the GenericValue from the persistent store, checking first in the cache to see if the desired value is there - * NOTE 20080502: 4 references - * @param relationName String containing the relation name which is the - * combination of relation.title and relation.rel-entity-name as - * specified in the entity XML definition file - * @param value GenericValue instance containing the entity - * @return List of GenericValue instances as specified in the relation definition - */ - public List getRelatedCache(String relationName, GenericValue value) throws GenericEntityException { - ModelEntity modelEntity = value.getModelEntity(); - ModelRelation relation = modelEntity.getRelation(relationName); - - if (relation == null) { - throw new GenericModelException("Could not find relation for relationName: " + relationName + " for value " + value); - } - - Map fields = FastMap.newInstance(); - for (int i = 0; i < relation.getKeyMapsSize(); i++) { - ModelKeyMap keyMap = relation.getKeyMap(i); - fields.put(keyMap.getRelFieldName(), value.get(keyMap.getFieldName())); - } - - return this.findByAndCache(relation.getRelEntityName(), fields, null); - } + public GenericPK getRelatedDummyPK(String relationName, Map byAndFields, GenericValue value) throws GenericEntityException; /** Get related entity where relation is of type one, uses findByPrimaryKey * NOTE 20080502: 7 references * @throws IllegalArgumentException if the list found has more than one item */ - public GenericValue getRelatedOne(String relationName, GenericValue value) throws GenericEntityException { - ModelRelation relation = value.getModelEntity().getRelation(relationName); - - if (relation == null) { - throw new GenericModelException("Could not find relation for relationName: " + relationName + " for value " + value); - } - if (!"one".equals(relation.getType()) && !"one-nofk".equals(relation.getType())) { - throw new GenericModelException("Relation is not a 'one' or a 'one-nofk' relation: " + relationName + " of entity " + value.getEntityName()); - } - - Map fields = FastMap.newInstance(); - for (int i = 0; i < relation.getKeyMapsSize(); i++) { - ModelKeyMap keyMap = relation.getKeyMap(i); - fields.put(keyMap.getRelFieldName(), value.get(keyMap.getFieldName())); - } - - return this.findByPrimaryKey(relation.getRelEntityName(), fields); - } + public GenericValue getRelatedOne(String relationName, GenericValue value) throws GenericEntityException; /** Get related entity where relation is of type one, uses findByPrimaryKey, checking first in the cache to see if the desired value is there * NOTE 20080502: 1 references * @throws IllegalArgumentException if the list found has more than one item */ - public GenericValue getRelatedOneCache(String relationName, GenericValue value) throws GenericEntityException { - ModelEntity modelEntity = value.getModelEntity(); - ModelRelation relation = modelEntity.getRelation(relationName); + public GenericValue getRelatedOneCache(String relationName, GenericValue value) throws GenericEntityException; - if (relation == null) { - throw new GenericModelException("Could not find relation for relationName: " + relationName + " for value " + value); - } - if (!"one".equals(relation.getType()) && !"one-nofk".equals(relation.getType())) { - throw new GenericModelException("Relation is not a 'one' or a 'one-nofk' relation: " + relationName + " of entity " + value.getEntityName()); - } - - Map fields = FastMap.newInstance(); - for (int i = 0; i < relation.getKeyMapsSize(); i++) { - ModelKeyMap keyMap = relation.getKeyMap(i); - fields.put(keyMap.getRelFieldName(), value.get(keyMap.getFieldName())); - } - - return this.findByPrimaryKeyCache(relation.getRelEntityName(), fields); - } - - - // ====================================== - // ======= Cache Related Methods ======== - // ====================================== - - /** This method is a shortcut to completely clear all entity engine caches. - * For performance reasons this should not be called very often. + /** Get the named Related Entity for the GenericValue from the persistent store + * NOTE 20080502: 1 references; all changed to use getRelated + * @param relationName String containing the relation name which is the + * combination of relation.title and relation.rel-entity-name as + * specified in the entity XML definition file + * @param orderBy The fields of the named entity to order the query by; may be null; + * optionally add a " ASC" for ascending or " DESC" for descending + * @param value GenericValue instance containing the entity + * @return List of GenericValue instances as specified in the relation definition + *@deprecated Use getRelated() instead */ - public void clearAllCaches() { - this.clearAllCaches(true); - } + @Deprecated + public List getRelatedOrderBy(String relationName, List orderBy, GenericValue value) throws GenericEntityException; - public void clearAllCaches(boolean distribute) { - cache.clear(); + public GenericPK makePK(Element element); - if (distribute && this.distributedCacheClear != null) { - this.distributedCacheClear.clearAllCaches(); - } - } + /** Creates a Primary Key in the form of a GenericPK without persisting it */ + public GenericPK makePK(String entityName); - /** Remove all CACHED Generic Entity (List) from the cache - *@param entityName The Name of the Entity as defined in the entity XML file - */ - public void clearCacheLine(String entityName) { - cache.remove(entityName); - } + /** Creates a Primary Key in the form of a GenericPK without persisting it */ + public GenericPK makePK(String entityName, Map fields); - /** Remove a CACHED Generic Entity (List) from the cache, either a PK, ByAnd, or All - *@param entityName The Name of the Entity as defined in the entity XML file - *@param fields The fields of the named entity to query by with their corresponding values - */ - public void clearCacheLine(String entityName, Object... fields) { - clearCacheLine(entityName, UtilMisc.toMap(fields)); - } + /** Creates a Primary Key in the form of a GenericPK without persisting it */ + public GenericPK makePK(String entityName, Object... fields); - /** Remove a CACHED Generic Entity (List) from the cache, either a PK, ByAnd, or All - *@param entityName The Name of the Entity as defined in the entity XML file - *@param fields The fields of the named entity to query by with their corresponding values - */ - public void clearCacheLine(String entityName, Map fields) { - // if no fields passed, do the all cache quickly and return - if (fields == null) { - cache.remove(entityName); - return; - } + /** Creates a Primary Key in the form of a GenericPK without persisting it */ + public GenericPK makePKSingle(String entityName, Object singlePkValue); - ModelEntity entity = this.getModelEntity(entityName); - if (entity == null) { - throw new IllegalArgumentException("[GenericDelegator.clearCacheLine] could not find entity for entityName: " + entityName); - } - //if never cached, then don't bother clearing - if (entity.getNeverCache()) return; + public GenericDelegator makeTestDelegator(String delegatorName); - GenericValue dummyValue = GenericValue.create(entity, fields); - dummyValue.setDelegator(this); - this.clearCacheLineFlexible(dummyValue); - } + /** Creates a Entity in the form of a GenericValue without persisting it; only valid fields will be pulled from the fields Map */ + public GenericValue makeValidValue(String entityName, Map fields); - /** Remove a CACHED Generic Entity from the cache by its primary key. - * Checks to see if the passed GenericPK is a complete primary key, if - * it is then the cache line will be removed from the primaryKeyCache; if it - * is NOT a complete primary key it will remove the cache line from the andCache. - * If the fields map is empty, then the allCache for the entity will be cleared. - *@param dummyPK The dummy primary key to clear by. - */ - public void clearCacheLineFlexible(GenericEntity dummyPK) { - this.clearCacheLineFlexible(dummyPK, true); - } + /** Creates a Entity in the form of a GenericValue without persisting it; only valid fields will be pulled from the fields Map */ + public GenericValue makeValidValue(String entityName, Object... fields); - public void clearCacheLineFlexible(GenericEntity dummyPK, boolean distribute) { - if (dummyPK != null) { - //if never cached, then don't bother clearing - if (dummyPK.getModelEntity().getNeverCache()) return; + public GenericValue makeValue(Element element); - cache.remove(dummyPK); + /** Creates a Entity in the form of a GenericValue without persisting it */ + public GenericValue makeValue(String entityName); - if (distribute && this.distributedCacheClear != null) { - this.distributedCacheClear.distributedClearCacheLineFlexible(dummyPK); - } - } - } + /** Creates a Entity in the form of a GenericValue without persisting it */ + public GenericValue makeValue(String entityName, Map fields); - protected void clearCacheValues(UtilCache cache, String entityName, EntityCondition condition) { - Iterator iterator = cache.cacheLineTable.values().iterator(); - while (iterator.hasNext()) { - CacheLine line = (CacheLine) iterator.next(); - GenericValue value = (GenericValue) line.getValue(); - if (value != null && value.getEntityName().equals(entityName) && condition.entityMatches(value)) { - iterator.remove(); - } - } - } + /** Creates a Entity in the form of a GenericValue without persisting it */ + public GenericValue makeValue(String entityName, Object... fields); - public void clearCacheLineByCondition(String entityName, EntityCondition condition) { - clearCacheLineByCondition(entityName, condition, true); - } + public List makeValues(Document document); - public void clearCacheLineByCondition(String entityName, EntityCondition condition, boolean distribute) { - if (entityName != null) { - //if never cached, then don't bother clearing - if (getModelEntity(entityName).getNeverCache()) return; + /** Creates a Entity in the form of a GenericValue without persisting it */ + public GenericValue makeValueSingle(String entityName, Object singlePkValue); - cache.remove(entityName, condition); + public void putAllInPrimaryKeyCache(List values); - if (distribute && this.distributedCacheClear != null) { - this.distributedCacheClear.distributedClearCacheLineByCondition(entityName, condition); - } - } - } - - /** Remove a CACHED Generic Entity from the cache by its primary key, does NOT - * check to see if the passed GenericPK is a complete primary key. - * Also tries to clear the corresponding all cache entry. - *@param primaryKey The primary key to clear by. - */ - public void clearCacheLine(GenericPK primaryKey) { - this.clearCacheLine(primaryKey, true); - } - - public void clearCacheLine(GenericPK primaryKey, boolean distribute) { - if (primaryKey == null) return; - - //if never cached, then don't bother clearing - if (primaryKey.getModelEntity().getNeverCache()) return; - - cache.remove(primaryKey); - - if (distribute && this.distributedCacheClear != null) { - this.distributedCacheClear.distributedClearCacheLine(primaryKey); - } - } - - /** Remove a CACHED GenericValue from as many caches as it can. Automatically - * tries to remove entries from the all cache, the by primary key cache, and - * the by and cache. This is the ONLY method that tries to clear automatically - * from the by and cache. - *@param value The GenericValue to clear by. - */ - public void clearCacheLine(GenericValue value) { - this.clearCacheLine(value, true); - } - - public void clearCacheLine(GenericValue value, boolean distribute) { - // TODO: make this a bit more intelligent by passing in the operation being done (create, update, remove) so we can not do unnecessary cache clears... - // for instance: - // on create don't clear by primary cache (and won't clear original values because there won't be any) - // on remove don't clear by and for new values, but do for original values - - // Debug.logInfo("running clearCacheLine for value: " + value + ", distribute: " + distribute, module); - if (value == null) return; - - //if never cached, then don't bother clearing - if (value.getModelEntity().getNeverCache()) return; - - cache.remove(value); - - if (distribute && this.distributedCacheClear != null) { - this.distributedCacheClear.distributedClearCacheLine(value); - } - } - - public void clearAllCacheLinesByDummyPK(Collection dummyPKs) { - if (dummyPKs == null) return; - for (GenericEntity entity: dummyPKs) { - this.clearCacheLineFlexible(entity); - } - } - - public void clearAllCacheLinesByValue(Collection values) { - if (values == null) return; - for (GenericValue value: values) { - this.clearCacheLine(value); - } - } - - public GenericValue getFromPrimaryKeyCache(GenericPK primaryKey) { - if (primaryKey == null) return null; - GenericValue value = (GenericValue) cache.get(primaryKey); - if (value == GenericValue.NULL_VALUE) { - return null; - } - return value; - } - - public void putInPrimaryKeyCache(GenericPK primaryKey, GenericValue value) { - if (primaryKey == null) return; - - if (primaryKey.getModelEntity().getNeverCache()) { - Debug.logWarning("Tried to put a value of the " + value.getEntityName() + " entity in the BY PRIMARY KEY cache but this entity has never-cache set to true, not caching.", module); - return; - } - - // before going into the cache, make this value immutable - value.setImmutable(); - cache.put(primaryKey, value); - } - - public void putAllInPrimaryKeyCache(List values) { - if (values == null) return; - for (GenericValue value: values) { - this.putInPrimaryKeyCache(value.getPrimaryKey(), value); - } - } - - public void setDistributedCacheClear(DistributedCacheClear distributedCacheClear) { - this.distributedCacheClear = distributedCacheClear; - } + public void putInPrimaryKeyCache(GenericPK primaryKey, GenericValue value); // ======= XML Related Methods ======== - public List readXmlDocument(URL url) throws SAXException, ParserConfigurationException, java.io.IOException { - if (url == null) return null; - return this.makeValues(UtilXml.readXmlDocument(url, false)); - } + public List readXmlDocument(URL url) throws SAXException, ParserConfigurationException, java.io.IOException; - public List makeValues(Document document) { - if (document == null) return null; - List values = FastList.newInstance(); - - Element docElement = document.getDocumentElement(); - - if (docElement == null) - return null; - if (!"entity-engine-xml".equals(docElement.getTagName())) { - Debug.logError("[GenericDelegator.makeValues] Root node was not ", module); - throw new java.lang.IllegalArgumentException("Root node was not "); - } - docElement.normalize(); - Node curChild = docElement.getFirstChild(); - - if (curChild != null) { - do { - if (curChild.getNodeType() == Node.ELEMENT_NODE) { - Element element = (Element) curChild; - GenericValue value = this.makeValue(element); - - if (value != null) - values.add(value); - } - } while ((curChild = curChild.getNextSibling()) != null); - } else { - Debug.logWarning("[GenericDelegator.makeValues] No child nodes found in document.", module); - } - - return values; - } - - public GenericPK makePK(Element element) { - GenericValue value = makeValue(element); - - return value.getPrimaryKey(); - } - - 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 modelFields = modelEntity.getFieldsIterator(); - - while (modelFields.hasNext()) { - ModelField modelField = modelFields.next(); - String name = modelField.getName(); - String attr = element.getAttribute(name); - - if (attr != null && attr.length() > 0) { - 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; - } - - // ======= Misc Methods ======== - - protected static class EntityEcaRuleRunner { - protected EntityEcaHandler entityEcaHandler; - protected Map> eventMap; - - protected EntityEcaRuleRunner(EntityEcaHandler entityEcaHandler, Map> eventMap) { - this.entityEcaHandler = entityEcaHandler; - this.eventMap = eventMap; - } - - protected void evalRules(String event, String currentOperation, GenericEntity value, boolean isError) throws GenericEntityException { - if (entityEcaHandler == null) return; - //if (!"find".equals(currentOperation)) Debug.logWarning("evalRules for entity " + value.getEntityName() + ", currentOperation " + currentOperation + ", event " + event, module); - entityEcaHandler.evalRules(currentOperation, eventMap, event, value, isError); - } - } - - protected EntityEcaRuleRunner getEcaRuleRunner(String entityName) { - if (this.testRollbackInProgress) return createEntityEcaRuleRunner(null, null); - return createEntityEcaRuleRunner(this.entityEcaHandler, entityName); - } - - protected static EntityEcaRuleRunner createEntityEcaRuleRunner(EntityEcaHandler entityEcaHandler, String entityName) { - return new EntityEcaRuleRunner(entityEcaHandler, entityEcaHandler != null ? entityEcaHandler.getEntityEventMap(entityName) : null); - } - - public void setEntityEcaHandler(EntityEcaHandler entityEcaHandler) { - this.entityEcaHandler = entityEcaHandler; - } - - public EntityEcaHandler getEntityEcaHandler() { - return this.entityEcaHandler; - } - - /** Get the next guaranteed unique seq id from the sequence with the given sequence name; - * if the named sequence doesn't exist, it will be created - *@param seqName The name of the sequence to get the next seq id from - *@return String with the next sequenced id for the given sequence name + /** Refresh the Entity for the GenericValue from the persistent store + *@param value GenericValue instance containing the entity to refresh */ - public String getNextSeqId(String seqName) { - return this.getNextSeqId(seqName, 1); - } + public void refresh(GenericValue value) throws GenericEntityException; - /** Get the next guaranteed unique seq id from the sequence with the given sequence name; - * if the named sequence doesn't exist, it will be created - *@param seqName The name of the sequence to get the next seq id from - *@param staggerMax The maximum amount to stagger the sequenced ID, if 1 the sequence will be incremented by 1, otherwise the current sequence ID will be incremented by a value between 1 and staggerMax - *@return Long with the next seq id for the given sequence name + /** Refresh the Entity for the GenericValue from the persistent store + *@param value GenericValue instance containing the entity to refresh + *@param doCacheClear boolean that specifies whether or not to automatically clear cache entries related to this operation */ - public String getNextSeqId(String seqName, long staggerMax) { - Long nextSeqLong = this.getNextSeqIdLong(seqName, staggerMax); + public void refresh(GenericValue value, boolean doCacheClear) throws GenericEntityException; - if (nextSeqLong == null) { - // NOTE: the getNextSeqIdLong method SHOULD throw a runtime exception when no sequence value is found, which means we should never see it get here - throw new IllegalArgumentException("Could not get next sequenced ID for sequence name: " + seqName); - } - - if (UtilValidate.isNotEmpty(this.getDelegatorInfo().sequencedIdPrefix)) { - return this.getDelegatorInfo().sequencedIdPrefix + nextSeqLong.toString(); - } else { - return nextSeqLong.toString(); - } - } - - /** Get the next guaranteed unique seq id from the sequence with the given sequence name; - * if the named sequence doesn't exist, it will be created - *@param seqName The name of the sequence to get the next seq id from - *@return Long with the next sequenced id for the given sequence name + /** Refresh the Entity for the GenericValue from the cache + *@param value GenericValue instance containing the entity to refresh */ - public Long getNextSeqIdLong(String seqName) { - return this.getNextSeqIdLong(seqName, 1); - } + public void refreshFromCache(GenericValue value) throws GenericEntityException; - /** Get the next guaranteed unique seq id from the sequence with the given sequence name; - * if the named sequence doesn't exist, it will be created - *@param seqName The name of the sequence to get the next seq id from - *@param staggerMax The maximum amount to stagger the sequenced ID, if 1 the sequence will be incremented by 1, otherwise the current sequence ID will be incremented by a value between 1 and staggerMax - *@return Long with the next seq id for the given sequence name + /** Refreshes the ID sequencer clearing all cached bank values. */ + public void refreshSequencer(); + + /** Remove the Entities from the List from the persistent store. + *
The List contains GenericEntity objects, can be either GenericPK or GenericValue. + *
If a certain entity contains a complete primary key, the entity in the datasource corresponding + * to that primary key will be removed, this is like a removeByPrimary Key. + *
On the other hand, if a certain entity is an incomplete or non primary key, + * if will behave like the removeByAnd method. + *
These updates all happen in one transaction, so they will either all succeed or all fail, + * if the data source supports transactions. + *@param dummyPKs Collection of GenericEntity instances containing the entities or by and fields to remove + *@return int representing number of rows effected by this operation */ - public Long getNextSeqIdLong(String seqName, long staggerMax) { - boolean beganTransaction = false; - try { - if (alwaysUseTransaction) { - beganTransaction = TransactionUtil.begin(); - } + public int removeAll(List dummyPKs) throws GenericEntityException; - if (sequencer == null) { - synchronized (this) { - if (sequencer == null) { - String helperName = this.getEntityHelperName("SequenceValueItem"); - ModelEntity seqEntity = this.getModelEntity("SequenceValueItem"); - sequencer = new SequenceUtil(helperName, seqEntity, "seqName", "seqId"); - } - } - } + /** Remove the Entities from the List from the persistent store. + *
The List contains GenericEntity objects, can be either GenericPK or GenericValue. + *
If a certain entity contains a complete primary key, the entity in the datasource corresponding + * to that primary key will be removed, this is like a removeByPrimary Key. + *
On the other hand, if a certain entity is an incomplete or non primary key, + * if will behave like the removeByAnd method. + *
These updates all happen in one transaction, so they will either all succeed or all fail, + * if the data source supports transactions. + *@param dummyPKs Collection of GenericEntity instances containing the entities or by and fields to remove + *@param doCacheClear boolean that specifies whether or not to automatically clear cache entries related to this operation + *@return int representing number of rows effected by this operation + */ + public int removeAll(List dummyPKs, boolean doCacheClear) throws GenericEntityException; - // might be null, but will usually match the entity name - ModelEntity seqModelEntity = this.getModelEntity(seqName); + public int removeAll(String entityName) throws GenericEntityException; - Long newSeqId = sequencer == null ? null : sequencer.getNextSeqId(seqName, staggerMax, seqModelEntity); + /** Removes/deletes Generic Entity records found by all of the specified fields (ie: combined using AND) + *@param entityName The Name of the Entity as defined in the entity XML file + *@param doCacheClear boolean that specifies whether to clear cache entries for this value to be removed + *@param fields The fields of the named entity to query by with their corresponding values + *@return int representing number of rows effected by this operation + */ + public int removeByAnd(String entityName, boolean doCacheClear, Object... fields) throws GenericEntityException; - return newSeqId; - } catch (GenericEntityException e) { - String errMsg = "Failure in getNextSeqIdLong operation for seqName [" + seqName + "]: " + e.toString() + ". Rolling back transaction."; - try { - // only rollback the transaction if we started one... - TransactionUtil.rollback(beganTransaction, errMsg, e); - } catch (GenericEntityException e2) { - Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); - } - // rather than logging the problem and returning null, thus hiding the problem, throw an exception - throw new GeneralRuntimeException(errMsg, e); - } finally { - try { - // only commit the transaction if we started one... - TransactionUtil.commit(beganTransaction); - } catch (GenericTransactionException e1) { - Debug.logError(e1, "[GenericDelegator] Could not commit transaction: " + e1.toString(), module); - } - } - } + /** Removes/deletes Generic Entity records found by all of the specified fields (ie: combined using AND) + *@param entityName The Name of the Entity as defined in the entity XML file + *@param fields The fields of the named entity to query by with their corresponding values + *@return int representing number of rows effected by this operation + */ + public int removeByAnd(String entityName, Map fields) throws GenericEntityException; + + /** Removes/deletes Generic Entity records found by all of the specified fields (ie: combined using AND) + *@param entityName The Name of the Entity as defined in the entity XML file + *@param fields The fields of the named entity to query by with their corresponding values + *@param doCacheClear boolean that specifies whether to clear cache entries for this value to be removed + *@return int representing number of rows effected by this operation + */ + public int removeByAnd(String entityName, Map fields, boolean doCacheClear) throws GenericEntityException; + + /** Removes/deletes Generic Entity records found by all of the specified fields (ie: combined using AND) + *@param entityName The Name of the Entity as defined in the entity XML file + *@param fields The fields of the named entity to query by with their corresponding values + *@return int representing number of rows effected by this operation + */ + public int removeByAnd(String entityName, Object... fields) throws GenericEntityException; + + /** Removes/deletes Generic Entity records found by the condition + *@param entityName The Name of the Entity as defined in the entity XML file + *@param condition The condition used to restrict the removing + *@return int representing number of rows effected by this operation + */ + public int removeByCondition(String entityName, EntityCondition condition) throws GenericEntityException; + + /** Removes/deletes Generic Entity records found by the condition + *@param entityName The Name of the Entity as defined in the entity XML file + *@param condition The condition used to restrict the removing + *@param doCacheClear boolean that specifies whether to clear cache entries for this value to be removed + *@return int representing number of rows effected by this operation + */ + public int removeByCondition(String entityName, EntityCondition condition, boolean doCacheClear) throws GenericEntityException; + + /** Remove a Generic Entity corresponding to the primaryKey + *@param primaryKey The primary key of the entity to remove. + *@return int representing number of rows effected by this operation + */ + public int removeByPrimaryKey(GenericPK primaryKey) throws GenericEntityException; + + /** Remove a Generic Entity corresponding to the primaryKey + *@param primaryKey The primary key of the entity to remove. + *@param doCacheClear boolean that specifies whether to clear cache entries for this primaryKey to be removed + *@return int representing number of rows effected by this operation + */ + public int removeByPrimaryKey(GenericPK primaryKey, boolean doCacheClear) throws GenericEntityException; + + /** Remove the named Related Entity for the GenericValue from the persistent store + *@param relationName String containing the relation name which is the + * combination of relation.title and relation.rel-entity-name as + * specified in the entity XML definition file + *@param value GenericValue instance containing the entity + *@return int representing number of rows effected by this operation + */ + public int removeRelated(String relationName, GenericValue value) throws GenericEntityException; + + /** Remove the named Related Entity for the GenericValue from the persistent store + *@param relationName String containing the relation name which is the + * combination of relation.title and relation.rel-entity-name as + * specified in the entity XML definition file + *@param value GenericValue instance containing the entity + *@param doCacheClear boolean that specifies whether to clear cache entries for this value to be removed + *@return int representing number of rows effected by this operation + */ + public int removeRelated(String relationName, GenericValue value, boolean doCacheClear) throws GenericEntityException; + + /** Remove a Generic Value from the database + *@param value The GenericValue object of the entity to remove. + *@return int representing number of rows effected by this operation + */ + public int removeValue(GenericValue value) throws GenericEntityException; + + /** Remove a Generic Value from the database + *@param value The GenericValue object of the entity to remove. + *@param doCacheClear boolean that specifies whether to clear cache entries for this value to be removed + *@return int representing number of rows effected by this operation + */ + public int removeValue(GenericValue value, boolean doCacheClear) throws GenericEntityException; + + public void rollback(); + + public void setDistributedCacheClear(DistributedCacheClear distributedCacheClear); + + public void setEntityCrypto(EntityCrypto crypto); + + public void setEntityEcaHandler(EntityEcaHandler entityEcaHandler); + + /** Look at existing values for a sub-entity with a sequenced secondary ID, and get the highest plus 1 */ + public void setNextSubSeqId(GenericValue value, String seqFieldName, int numericPadding, int incrementBy); /** Allows you to pass a SequenceUtil class (possibly one that overrides the getNextSeqId method); * if null is passed will effectively refresh the sequencer. */ - public void setSequencer(SequenceUtil sequencer) { - this.sequencer = sequencer; - } + public void setSequencer(SequenceUtil sequencer); - /** Refreshes the ID sequencer clearing all cached bank values. */ - public void refreshSequencer() { - this.sequencer = null; - } + public void setLocale(Locale locale); + public void setSessionIdentifier(String identifier); - /** Look at existing values for a sub-entity with a sequenced secondary ID, and get the highest plus 1 */ - public void setNextSubSeqId(GenericValue value, String seqFieldName, int numericPadding, int incrementBy) { - if (value != null && UtilValidate.isEmpty(value.getString(seqFieldName))) { - String sequencedIdPrefix = this.getDelegatorInfo().sequencedIdPrefix; + public void setUserIdentifier(String identifier); - value.remove(seqFieldName); - GenericValue lookupValue = this.makeValue(value.getEntityName()); - lookupValue.setPKFields(value); + /** Store the Entity from the GenericValue to the persistent store + *@param value GenericValue instance containing the entity + *@return int representing number of rows effected by this operation + */ + public int store(GenericValue value) throws GenericEntityException; - boolean beganTransaction = false; - try { - if (alwaysUseTransaction) { - beganTransaction = TransactionUtil.begin(); - } + /** Store the Entity from the GenericValue to the persistent store + *@param value GenericValue instance containing the entity + *@param doCacheClear boolean that specifies whether or not to automatically clear cache entries related to this operation + *@return int representing number of rows effected by this operation + */ + public int store(GenericValue value, boolean doCacheClear) throws GenericEntityException; - // get values in whatever order, we will go through all of them to find the highest value - List allValues = this.findByAnd(value.getEntityName(), lookupValue, null); - //Debug.logInfo("Get existing values from entity " + value.getEntityName() + " with lookupValue: " + lookupValue + ", and the seqFieldName: " + seqFieldName + ", and the results are: " + allValues, module); - Integer highestSeqVal = null; - for (GenericValue curValue: allValues) { - String currentSeqId = curValue.getString(seqFieldName); - if (currentSeqId != null) { - if (UtilValidate.isNotEmpty(sequencedIdPrefix)) { - if (currentSeqId.startsWith(sequencedIdPrefix)) { - currentSeqId = currentSeqId.substring(sequencedIdPrefix.length()); - } else { - continue; - } - } - try { - int seqVal = Integer.parseInt(currentSeqId); - if (highestSeqVal == null || seqVal > highestSeqVal.intValue()) { - highestSeqVal = Integer.valueOf(seqVal); - } - } catch (Exception e) { - Debug.logWarning("Error in make-next-seq-id converting SeqId [" + currentSeqId + "] in field: " + seqFieldName + " from entity: " + value.getEntityName() + " to a number: " + e.toString(), module); - } - } - } + /** Store the Entities from the List GenericValue instances to the persistent store. + *
This is different than the normal store method in that the store method only does + * an update, while the storeAll method checks to see if each entity exists, then + * either does an insert or an update as appropriate. + *
These updates all happen in one transaction, so they will either all succeed or all fail, + * if the data source supports transactions. This is just like to othersToStore feature + * of the GenericEntity on a create or store. + *@param values List of GenericValue instances containing the entities to store + *@return int representing number of rows effected by this operation + */ + public int storeAll(List values) throws GenericEntityException; - int seqValToUse = (highestSeqVal == null ? 1 : highestSeqVal.intValue() + incrementBy); - String newSeqId = sequencedIdPrefix + UtilFormatOut.formatPaddedNumber(seqValToUse, numericPadding); - value.set(seqFieldName, newSeqId); + /** Store the Entities from the List GenericValue instances to the persistent store. + *
This is different than the normal store method in that the store method only does + * an update, while the storeAll method checks to see if each entity exists, then + * either does an insert or an update as appropriate. + *
These updates all happen in one transaction, so they will either all succeed or all fail, + * if the data source supports transactions. This is just like to othersToStore feature + * of the GenericEntity on a create or store. + *@param values List of GenericValue instances containing the entities to store + *@param doCacheClear boolean that specifies whether or not to automatically clear cache entries related to this operation + *@return int representing number of rows effected by this operation + */ + public int storeAll(List values, boolean doCacheClear) throws GenericEntityException; - // only commit the transaction if we started one... - TransactionUtil.commit(beganTransaction); - } catch (Exception e) { - String errMsg = "Failure in setNextSubSeqId operation for entity [" + value.getEntityName() + "]: " + e.toString() + ". Rolling back transaction."; - Debug.logError(e, errMsg, module); - try { - // only rollback the transaction if we started one... - TransactionUtil.rollback(beganTransaction, errMsg, e); - } catch (GenericEntityException e2) { - Debug.logError(e2, "[GenericDelegator] Could not rollback transaction: " + e2.toString(), module); - } - Debug.logError(e, "Error making next seqId", module); - } - } - } + /** Store the Entities from the List GenericValue instances to the persistent store. + *
This is different than the normal store method in that the store method only does + * an update, while the storeAll method checks to see if each entity exists, then + * either does an insert or an update as appropriate. + *
These updates all happen in one transaction, so they will either all succeed or all fail, + * if the data source supports transactions. This is just like to othersToStore feature + * of the GenericEntity on a create or store. + *@param values List of GenericValue instances containing the entities to store + *@param doCacheClear boolean that specifies whether or not to automatically clear cache entries related to this operation + *@param createDummyFks boolean that specifies whether or not to automatically create "dummy" place holder FKs + *@return int representing number of rows effected by this operation + */ + public int storeAll(List values, boolean doCacheClear, boolean createDummyFks) throws GenericEntityException; - public void encryptFields(List entities) throws GenericEntityException { - if (entities != null) { - for (GenericEntity entity: entities) { - this.encryptFields(entity); - } - } - } + /** Store a group of values + *@param entityName The name of the Entity as defined in the entity XML file + *@param fieldsToSet The fields of the named entity to set in the database + *@param condition The condition that restricts the list of stored values + *@return int representing number of rows effected by this operation + *@throws GenericEntityException + */ + public int storeByCondition(String entityName, Map fieldsToSet, EntityCondition condition) throws GenericEntityException; - public void encryptFields(GenericEntity entity) throws GenericEntityException { - ModelEntity model = entity.getModelEntity(); - String entityName = model.getEntityName(); + /** Store a group of values + *@param entityName The name of the Entity as defined in the entity XML file + *@param fieldsToSet The fields of the named entity to set in the database + *@param condition The condition that restricts the list of stored values + *@param doCacheClear boolean that specifies whether to clear cache entries for these values + *@return int representing number of rows effected by this operation + *@throws GenericEntityException + */ + public int storeByCondition(String entityName, Map fieldsToSet, EntityCondition condition, boolean doCacheClear) throws GenericEntityException; - Iterator i = model.getFieldsIterator(); - while (i.hasNext()) { - ModelField field = i.next(); - if (field.getEncrypt()) { - Object obj = entity.get(field.getName()); - if (obj != null) { - if (obj instanceof String && UtilValidate.isEmpty((String) obj)) { - continue; - } - entity.dangerousSetNoCheckButFast(field, this.encryptFieldValue(entityName, obj)); - } - } - } - } - - public Object encryptFieldValue(String entityName, Object fieldValue) throws EntityCryptoException { - if (fieldValue != null) { - if (fieldValue instanceof String && UtilValidate.isEmpty((String) fieldValue)) { - return fieldValue; - } - return this.crypto.encrypt(entityName, fieldValue); - } - return fieldValue; - } - - public void decryptFields(List entities) throws GenericEntityException { - if (entities != null) { - for (GenericEntity entity: entities) { - this.decryptFields(entity); - } - } - } - - public void decryptFields(GenericEntity entity) throws GenericEntityException { - ModelEntity model = entity.getModelEntity(); - String entityName = model.getEntityName(); - - Iterator i = model.getFieldsIterator(); - while (i.hasNext()) { - ModelField field = i.next(); - if (field.getEncrypt()) { - String keyName = entityName; - if (model instanceof ModelViewEntity) { - ModelViewEntity modelView = (ModelViewEntity) model; - keyName = modelView.getAliasedEntity(modelView.getAlias(field.getName()).getEntityAlias(), modelReader).getEntityName(); - } - - String encHex = (String) entity.get(field.getName()); - if (UtilValidate.isNotEmpty(encHex)) { - try { - entity.dangerousSetNoCheckButFast(field, crypto.decrypt(keyName, encHex)); - } catch (EntityCryptoException e) { - // not fatal -- allow returning of the encrypted value - Debug.logWarning(e, "Problem decrypting field [" + entityName + " / " + field.getName() + "]", module); - } - } - } - } - } - - public void setEntityCrypto(EntityCrypto crypto) { - this.crypto = crypto; - } - - protected void absorbList(List lst) { - if (lst == null) return; - for (GenericValue value: lst) { - value.setDelegator(this); - } - } - - public Cache getCache() { - return cache; - } - - protected void createEntityAuditLogAll(GenericValue value, boolean isUpdate, boolean isRemove) throws GenericEntityException { - for (ModelField mf: value.getModelEntity().getFieldsUnmodifiable()) { - if (mf.getEnableAuditLog()) { - createEntityAuditLogSingle(value, mf, isUpdate, isRemove); - } - } - } - - protected void createEntityAuditLogSingle(GenericValue value, ModelField mf, boolean isUpdate, boolean isRemove) throws GenericEntityException { - if (value == null || mf == null || !mf.getEnableAuditLog() || this.testRollbackInProgress) { - return; - } - - GenericValue entityAuditLog = this.makeValue("EntityAuditLog"); - entityAuditLog.set("auditHistorySeqId", this.getNextSeqId("EntityAuditLog")); - entityAuditLog.set("changedEntityName", value.getEntityName()); - entityAuditLog.set("changedFieldName", mf.getName()); - - String pkCombinedValueText = value.getPkShortValueString(); - if (pkCombinedValueText.length() > 250) { - // uh-oh, the string is too long! - pkCombinedValueText = pkCombinedValueText.substring(0, 250); - } - entityAuditLog.set("pkCombinedValueText", pkCombinedValueText); - - GenericValue oldGv = null; - if (isUpdate) { - // it's an update, get it from the database - oldGv = this.findOne(value.getEntityName(), value.getPrimaryKey(), false); - } else if (isRemove) { - oldGv = value; - } - if (oldGv == null) { - if (isUpdate || isRemove) { - entityAuditLog.set("oldValueText", "[ERROR] Old value not found even though it was an update or remove"); - } - } else { - // lookup old value - String oldValueText = null; - Object oldValue = oldGv.get(mf.getName()); - if (oldValue != null) { - oldValueText = oldValue.toString(); - if (oldValueText.length() > 250) { - oldValueText = oldValueText.substring(0, 250); - } - } - entityAuditLog.set("oldValueText", oldValueText); - } - - if (!isRemove) { - String newValueText = null; - Object newValue = value.get(mf.getName()); - if (newValue != null) { - newValueText = newValue.toString(); - if (newValueText.length() > 250) { - newValueText = newValueText.substring(0, 250); - } - } - entityAuditLog.set("newValueText", newValueText); - } - - entityAuditLog.set("changedDate", UtilDateTime.nowTimestamp()); - entityAuditLog.set("changedByInfo", getCurrentUserIdentifier()); - entityAuditLog.set("changedSessionInfo", getCurrentSessionIdentifier()); - - this.create(entityAuditLog); - } - - public GenericDelegator cloneDelegator(String delegatorName) { - // creates an exact clone of the delegator; except for the sequencer - // note that this will not be cached and should be used only when - // needed to change something for single instance (use). - GenericDelegator newDelegator = new GenericDelegator(); - newDelegator.modelReader = this.modelReader; - newDelegator.modelGroupReader = this.modelGroupReader; - newDelegator.delegatorName = delegatorName; - newDelegator.delegatorInfo = this.delegatorInfo; - newDelegator.cache = this.cache; - newDelegator.andCacheFieldSets = this.andCacheFieldSets; - newDelegator.distributedCacheClear = this.distributedCacheClear; - newDelegator.originalDelegatorName = getOriginalDelegatorName(); - newDelegator.entityEcaHandler = this.entityEcaHandler; - newDelegator.crypto = this.crypto; - // In case this delegator is in testMode give it a reference to - // the rollback list - newDelegator.testOperations = this.testOperations; - // not setting the sequencer so that we have unique sequences. - - return newDelegator; - } - - public GenericDelegator cloneDelegator() { - return this.cloneDelegator(this.delegatorName); - } - - public GenericDelegator makeTestDelegator(String delegatorName) { - GenericDelegator testDelegator = this.cloneDelegator(delegatorName); - testDelegator.initEntityEcaHandler(); - testDelegator.setTestMode(true); - return testDelegator; - } - - private void setTestMode(boolean testMode) { - this.testMode = testMode; - if (testMode) { - this.testOperations = FastList.newInstance(); - } else { - this.testOperations.clear(); - } - } - - private void storeForTestRollback(TestOperation testOperation) { - if (!this.testMode || this.testRollbackInProgress) { - throw new IllegalStateException("An attempt was made to store a TestOperation during rollback or outside of test mode"); - } - this.testOperations.add(testOperation); - } - - public void rollback() { - if (!this.testMode) { - Debug.logError("Rollback requested outside of testmode", module); - } - this.testMode = false; - this.testRollbackInProgress = true; - synchronized (testOperations) { - Debug.logInfo("Rolling back " + testOperations.size() + " entity operations", module); - ListIterator iterator = this.testOperations.listIterator(this.testOperations.size()); - while (iterator.hasPrevious()) { - TestOperation testOperation = iterator.previous(); - try { - if (testOperation.getOperation().equals(OperationType.INSERT)) { - this.removeValue(testOperation.getValue()); - } else if (testOperation.getOperation().equals(OperationType.UPDATE)) { - this.store(testOperation.getValue()); - } else if (testOperation.getOperation().equals(OperationType.DELETE)) { - this.create(testOperation.getValue()); - } - } catch (GenericEntityException e) { - Debug.logWarning(e.toString(), module); - } - } - this.testOperations.clear(); - } - this.testRollbackInProgress = false; - this.testMode = true; - } - - public class TestOperation { - private final OperationType operation; - public OperationType getOperation() { - return operation; - } - public GenericValue getValue() { - return value; - } - private final GenericValue value; - public TestOperation(OperationType operation, GenericValue value) { - this.operation = operation; - this.value = value; - } - } } diff --git a/framework/entity/src/org/ofbiz/entity/GenericEntity.java b/framework/entity/src/org/ofbiz/entity/GenericEntity.java index 7da769124b..15c9ffa23a 100644 --- a/framework/entity/src/org/ofbiz/entity/GenericEntity.java +++ b/framework/entity/src/org/ofbiz/entity/GenericEntity.java @@ -285,7 +285,7 @@ public class GenericEntity extends Observable implements Map, Lo public GenericDelegator getDelegator() { if (internalDelegator == null) { if (delegatorName == null) delegatorName = "default"; - if (delegatorName != null) internalDelegator = GenericDelegator.getGenericDelegator(delegatorName); + if (delegatorName != null) internalDelegator = DelegatorFactory.getGenericDelegator(delegatorName); if (internalDelegator == null) { throw new IllegalStateException("[GenericEntity.getDelegator] could not find delegator with name " + delegatorName); } @@ -300,7 +300,7 @@ public class GenericEntity extends Observable implements Map, Lo this.internalDelegator = internalDelegator; } - public Object get(String name) { + protected Object getFieldValue(String name) { if (getModelEntity().getField(name) == null) { throw new IllegalArgumentException("[GenericEntity.get] \"" + name + "\" is not a field of " + entityName); } @@ -696,7 +696,7 @@ public class GenericEntity extends Observable implements Map, Lo public Object get(String name, String resource, Locale locale) { Object fieldValue = null; try { - fieldValue = get(name); + fieldValue = getFieldValue(name); } catch (IllegalArgumentException e) { if (Debug.verboseOn()) { Debug.logVerbose(e, "The field name (or key) [" + name + "] is not valid for entity [" + this.getEntityName() + "], printing IllegalArgumentException instead of throwing it because Map interface specification does not allow throwing that exception.", module); @@ -754,7 +754,7 @@ public class GenericEntity extends Observable implements Map, Lo while (iter != null && iter.hasNext()) { ModelField curField = iter.next(); keyBuffer.append('.'); - keyBuffer.append(this.get(curField.getName())); + keyBuffer.append(this.getFieldValue(curField.getName())); } String bundleKey = keyBuffer.toString(); @@ -1337,7 +1337,7 @@ public class GenericEntity extends Observable implements Map, Lo public Object get(Object key) { try { - return this.get((String) key); + return this.get((String)key, this.getDelegator().getLocale()); } catch (IllegalArgumentException e) { if (Debug.verboseOn()) { Debug.logVerbose(e, "The field name (or key) [" + key + "] is not valid for entity [" + this.getEntityName() + "], printing IllegalArgumentException instead of throwing it because Map interface specification does not allow throwing that exception.", module); diff --git a/framework/entity/src/org/ofbiz/entity/cache/AbstractCache.java b/framework/entity/src/org/ofbiz/entity/cache/AbstractCache.java index 32f9943e0c..fd2cbd5ca7 100644 --- a/framework/entity/src/org/ofbiz/entity/cache/AbstractCache.java +++ b/framework/entity/src/org/ofbiz/entity/cache/AbstractCache.java @@ -19,6 +19,7 @@ package org.ofbiz.entity.cache; import org.ofbiz.base.util.cache.UtilCache; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; public abstract class AbstractCache { @@ -31,7 +32,7 @@ public abstract class AbstractCache { } public GenericDelegator getDelegator() { - return GenericDelegator.getGenericDelegator(delegatorName); + return DelegatorFactory.getGenericDelegator(delegatorName); } public void remove(String entityName) { diff --git a/framework/entity/src/org/ofbiz/entity/condition/EntityExpr.java b/framework/entity/src/org/ofbiz/entity/condition/EntityExpr.java index cf85d44e2f..196d986372 100644 --- a/framework/entity/src/org/ofbiz/entity/condition/EntityExpr.java +++ b/framework/entity/src/org/ofbiz/entity/condition/EntityExpr.java @@ -27,6 +27,7 @@ import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.ObjectType; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.entity.EntityCryptoException; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntity; import org.ofbiz.entity.GenericEntityException; @@ -251,7 +252,7 @@ public class EntityExpr extends EntityCondition { if (delegator == null) { // this will be the common case for now as the delegator isn't available where we want to do this // we'll cheat a little here and assume the default delegator - delegator = GenericDelegator.getGenericDelegator("default"); + delegator = DelegatorFactory.getGenericDelegator("default"); } String fieldName = null; diff --git a/framework/entity/src/org/ofbiz/entity/finder/ListFinder.java b/framework/entity/src/org/ofbiz/entity/finder/ListFinder.java index 36eac73b3d..afec138003 100644 --- a/framework/entity/src/org/ofbiz/entity/finder/ListFinder.java +++ b/framework/entity/src/org/ofbiz/entity/finder/ListFinder.java @@ -32,6 +32,7 @@ import org.ofbiz.base.util.UtilValidate; import org.ofbiz.base.util.UtilXml; import org.ofbiz.base.util.collections.FlexibleMapAccessor; import org.ofbiz.base.util.string.FlexibleStringExpander; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; @@ -136,7 +137,7 @@ public abstract class ListFinder extends Finder { resultSetType = ResultSet.TYPE_FORWARD_ONLY; if (delegatorName != null && delegatorName.length() > 0) { - delegator = GenericDelegator.getGenericDelegator(delegatorName); + delegator = DelegatorFactory.getGenericDelegator(delegatorName); } EntityCondition whereEntityCondition = getWhereEntityCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity)); diff --git a/framework/entityext/src/org/ofbiz/entityext/data/EntityDataLoadContainer.java b/framework/entityext/src/org/ofbiz/entityext/data/EntityDataLoadContainer.java index e0367a2c10..9d15dcc0f6 100644 --- a/framework/entityext/src/org/ofbiz/entityext/data/EntityDataLoadContainer.java +++ b/framework/entityext/src/org/ofbiz/entityext/data/EntityDataLoadContainer.java @@ -35,6 +35,7 @@ import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.StringUtil; import org.ofbiz.base.util.UtilURL; import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.jdbc.DatabaseUtil; @@ -224,7 +225,7 @@ public class EntityDataLoadContainer implements Container { String delegatorNameToUse = overrideDelegator != null ? overrideDelegator : delegatorName; String groupNameToUse = overrideGroup != null ? overrideGroup : entityGroupName; - GenericDelegator delegator = GenericDelegator.getGenericDelegator(delegatorNameToUse); + GenericDelegator delegator = DelegatorFactory.getGenericDelegator(delegatorNameToUse); if (delegator == null) { throw new ContainerException("Invalid delegator name!"); } diff --git a/framework/entityext/src/org/ofbiz/entityext/synchronization/EntitySyncContext.java b/framework/entityext/src/org/ofbiz/entityext/synchronization/EntitySyncContext.java index 544e4c03d0..a566fe7d28 100644 --- a/framework/entityext/src/org/ofbiz/entityext/synchronization/EntitySyncContext.java +++ b/framework/entityext/src/org/ofbiz/entityext/synchronization/EntitySyncContext.java @@ -35,6 +35,7 @@ import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilDateTime; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntity; import org.ofbiz.entity.GenericEntityException; @@ -148,7 +149,7 @@ public class EntitySyncContext { // what to do with the delegatorName? this is the delegatorName to use in this service... String delegatorName = (String) context.get("delegatorName"); if (UtilValidate.isNotEmpty(delegatorName)) { - this.delegator = GenericDelegator.getGenericDelegator(delegatorName); + this.delegator = DelegatorFactory.getGenericDelegator(delegatorName); } diff --git a/framework/entityext/src/org/ofbiz/entityext/synchronization/EntitySyncServices.java b/framework/entityext/src/org/ofbiz/entityext/synchronization/EntitySyncServices.java index a1ccf0a78d..02033d3f37 100644 --- a/framework/entityext/src/org/ofbiz/entityext/synchronization/EntitySyncServices.java +++ b/framework/entityext/src/org/ofbiz/entityext/synchronization/EntitySyncServices.java @@ -41,6 +41,7 @@ import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.base.util.UtilXml; import org.ofbiz.base.util.UtilURL; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntity; import org.ofbiz.entity.GenericEntityException; @@ -133,7 +134,7 @@ public class EntitySyncServices { GenericDelegator delegator = dctx.getDelegator(); String overrideDelegatorName = (String) context.get("delegatorName"); if (UtilValidate.isNotEmpty(overrideDelegatorName)) { - delegator = GenericDelegator.getGenericDelegator(overrideDelegatorName); + delegator = DelegatorFactory.getGenericDelegator(overrideDelegatorName); if (delegator == null) { return ServiceUtil.returnError("Could not find delegator with specified name " + overrideDelegatorName); } diff --git a/framework/guiapp/src/org/ofbiz/guiapp/xui/XuiContainer.java b/framework/guiapp/src/org/ofbiz/guiapp/xui/XuiContainer.java index 406b952a0a..288b2bcd34 100644 --- a/framework/guiapp/src/org/ofbiz/guiapp/xui/XuiContainer.java +++ b/framework/guiapp/src/org/ofbiz/guiapp/xui/XuiContainer.java @@ -29,6 +29,7 @@ import org.ofbiz.base.container.Container; import org.ofbiz.base.container.ContainerConfig; import org.ofbiz.base.container.ContainerException; import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.service.GenericDispatcher; import org.ofbiz.service.LocalDispatcher; @@ -60,7 +61,7 @@ public abstract class XuiContainer implements Container { // get the delegator String delegatorName = ContainerConfig.getPropertyValue(cc, "delegator-name", "default"); - GenericDelegator delegator = GenericDelegator.getGenericDelegator(delegatorName); + GenericDelegator delegator = DelegatorFactory.getGenericDelegator(delegatorName); // get the dispatcher String dispatcherName = ContainerConfig.getPropertyValue(cc, "dispatcher-name", "xui-dispatcher"); diff --git a/framework/minilang/src/org/ofbiz/minilang/method/entityops/EntityCount.java b/framework/minilang/src/org/ofbiz/minilang/method/entityops/EntityCount.java index 5cf3029160..491b698464 100644 --- a/framework/minilang/src/org/ofbiz/minilang/method/entityops/EntityCount.java +++ b/framework/minilang/src/org/ofbiz/minilang/method/entityops/EntityCount.java @@ -26,6 +26,7 @@ import org.ofbiz.base.util.UtilValidate; import org.ofbiz.base.util.UtilXml; import org.ofbiz.base.util.collections.FlexibleMapAccessor; import org.ofbiz.base.util.string.FlexibleStringExpander; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.condition.EntityCondition; import org.ofbiz.entity.finder.EntityFinderUtil.Condition; @@ -101,7 +102,7 @@ public class EntityCount extends MethodOperation { String delegatorName = this.delegatorNameExdr.expandString(context); if (delegatorName != null && delegatorName.length() > 0) { - delegator = GenericDelegator.getGenericDelegator(delegatorName); + delegator = DelegatorFactory.getGenericDelegator(delegatorName); } ModelEntity modelEntity = delegator.getModelEntity(entityName); diff --git a/framework/minilang/src/org/ofbiz/minilang/method/entityops/EntityData.java b/framework/minilang/src/org/ofbiz/minilang/method/entityops/EntityData.java index 12560fdee7..51ea0384b9 100644 --- a/framework/minilang/src/org/ofbiz/minilang/method/entityops/EntityData.java +++ b/framework/minilang/src/org/ofbiz/minilang/method/entityops/EntityData.java @@ -28,6 +28,7 @@ import org.ofbiz.base.location.FlexibleLocation; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.base.util.string.FlexibleStringExpander; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.util.EntityDataAssert; import org.ofbiz.entity.util.EntitySaxReader; @@ -86,7 +87,7 @@ public class EntityData extends MethodOperation { GenericDelegator delegator = methodContext.getDelegator(); if (delegatorName != null && delegatorName.length() > 0) { - delegator = GenericDelegator.getGenericDelegator(delegatorName); + delegator = DelegatorFactory.getGenericDelegator(delegatorName); } URL dataUrl = null; diff --git a/framework/minilang/src/org/ofbiz/minilang/method/entityops/FindByAnd.java b/framework/minilang/src/org/ofbiz/minilang/method/entityops/FindByAnd.java index 36f2083f09..1cb8df4b28 100644 --- a/framework/minilang/src/org/ofbiz/minilang/method/entityops/FindByAnd.java +++ b/framework/minilang/src/org/ofbiz/minilang/method/entityops/FindByAnd.java @@ -22,6 +22,7 @@ import java.util.List; import java.util.Map; import org.ofbiz.base.util.Debug; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; @@ -87,7 +88,7 @@ public class FindByAnd extends MethodOperation { GenericDelegator delegator = methodContext.getDelegator(); if (delegatorName != null && delegatorName.length() > 0) { - delegator = GenericDelegator.getGenericDelegator(delegatorName); + delegator = DelegatorFactory.getGenericDelegator(delegatorName); } try { diff --git a/framework/minilang/src/org/ofbiz/minilang/method/entityops/FindByPrimaryKey.java b/framework/minilang/src/org/ofbiz/minilang/method/entityops/FindByPrimaryKey.java index 12fc9f63b5..059f5c002a 100644 --- a/framework/minilang/src/org/ofbiz/minilang/method/entityops/FindByPrimaryKey.java +++ b/framework/minilang/src/org/ofbiz/minilang/method/entityops/FindByPrimaryKey.java @@ -25,6 +25,7 @@ import java.util.Map; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntity; import org.ofbiz.entity.GenericValue; @@ -78,7 +79,7 @@ public class FindByPrimaryKey extends MethodOperation { GenericDelegator delegator = methodContext.getDelegator(); if (delegatorName != null && delegatorName.length() > 0) { - delegator = GenericDelegator.getGenericDelegator(delegatorName); + delegator = DelegatorFactory.getGenericDelegator(delegatorName); } Map inMap = mapAcsr.get(methodContext); diff --git a/framework/service/src/org/ofbiz/service/ServiceDispatcher.java b/framework/service/src/org/ofbiz/service/ServiceDispatcher.java index 181162f0a3..d99c1859df 100644 --- a/framework/service/src/org/ofbiz/service/ServiceDispatcher.java +++ b/framework/service/src/org/ofbiz/service/ServiceDispatcher.java @@ -34,6 +34,7 @@ import org.ofbiz.base.util.UtilTimer; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.base.util.UtilXml; import org.ofbiz.base.util.collections.LRUMap; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; @@ -104,7 +105,7 @@ public class ServiceDispatcher { try { GenericDelegator origDelegator = this.delegator; if (!this.delegator.getOriginalDelegatorName().equals(this.delegator.getDelegatorName())) { - origDelegator = GenericDelegator.getGenericDelegator(this.delegator.getOriginalDelegatorName()); + origDelegator = DelegatorFactory.getGenericDelegator(this.delegator.getOriginalDelegatorName()); } this.jm = JobManager.getInstance(origDelegator, enableJM); } catch (GeneralRuntimeException e) { @@ -276,11 +277,12 @@ public class ServiceDispatcher { // get eventMap once for all calls for speed, don't do event calls if it is null Map> eventMap = ServiceEcaUtil.getServiceEventMap(modelService.name); - // check the locale - Locale locale = this.checkLocale(context); - // setup the engine and context DispatchContext ctx = localContext.get(localName); + GenericDelegator delegator = ctx.getDelegator(); + Locale locale = this.checkLocale(context); + delegator.setLocale(locale); + GenericEngine engine = this.getGenericEngine(modelService.engineName); // set IN attributes with default-value as applicable @@ -356,7 +358,7 @@ public class ServiceDispatcher { // now that we have authed, if there is a userLogin, set the EE userIdentifier if (userLogin != null && userLogin.getString("userLoginId") != null) { - GenericDelegator.pushUserIdentifier(userLogin.getString("userLoginId")); + delegator.setUserIdentifier(userLogin.getString("userLoginId")); } // pre-validate ECA @@ -551,9 +553,6 @@ public class ServiceDispatcher { // call notifications -- event is determined from the result (success, error, fail) modelService.evalNotifications(this.getLocalContext(localName), context, result); - - // clear out the EE userIdentifier - GenericDelegator.popUserIdentifier(); } } catch (GenericTransactionException te) { Debug.logError(te, "Problems with the transaction", module); diff --git a/framework/service/src/org/ofbiz/service/mail/JavaMailContainer.java b/framework/service/src/org/ofbiz/service/mail/JavaMailContainer.java index 4a0d4aec6d..3e4390565d 100644 --- a/framework/service/src/org/ofbiz/service/mail/JavaMailContainer.java +++ b/framework/service/src/org/ofbiz/service/mail/JavaMailContainer.java @@ -35,6 +35,7 @@ import org.ofbiz.base.container.ContainerException; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.base.util.UtilMisc; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.GenericEntityException; @@ -85,7 +86,7 @@ public class JavaMailContainer implements Container { String delegatorName = ContainerConfig.getPropertyValue(cfg, "delegator-name", "default"); this.deleteMail = "true".equals(ContainerConfig.getPropertyValue(cfg, "delete-mail", "false")); - this.delegator = GenericDelegator.getGenericDelegator(delegatorName); + this.delegator = DelegatorFactory.getGenericDelegator(delegatorName); this.dispatcher = GenericDispatcher.getLocalDispatcher(dispatcherName, delegator); this.timerDelay = (long) ContainerConfig.getPropertyValue(cfg, "poll-delay", 300000); this.maxSize = (long) ContainerConfig.getPropertyValue(cfg, "maxSize", 1000000); // maximum size in bytes diff --git a/framework/service/src/org/ofbiz/service/rmi/RmiServiceContainer.java b/framework/service/src/org/ofbiz/service/rmi/RmiServiceContainer.java index 2b0f4c1e99..737e8b2362 100644 --- a/framework/service/src/org/ofbiz/service/rmi/RmiServiceContainer.java +++ b/framework/service/src/org/ofbiz/service/rmi/RmiServiceContainer.java @@ -29,6 +29,7 @@ import javax.naming.NamingException; import org.ofbiz.base.container.Container; import org.ofbiz.base.container.ContainerConfig; import org.ofbiz.base.container.ContainerException; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.service.GenericDispatcher; import org.ofbiz.service.LocalDispatcher; @@ -120,7 +121,7 @@ public class RmiServiceContainer implements Container { } // get the delegator for this container - GenericDelegator delegator = GenericDelegator.getGenericDelegator(delegatorProp.value); + GenericDelegator delegator = DelegatorFactory.getGenericDelegator(delegatorProp.value); // create the LocalDispatcher LocalDispatcher dispatcher = GenericDispatcher.getLocalDispatcher(name, delegator); diff --git a/framework/testtools/src/org/ofbiz/testtools/ModelTestSuite.java b/framework/testtools/src/org/ofbiz/testtools/ModelTestSuite.java index 2961a8d224..88c91d366f 100644 --- a/framework/testtools/src/org/ofbiz/testtools/ModelTestSuite.java +++ b/framework/testtools/src/org/ofbiz/testtools/ModelTestSuite.java @@ -33,6 +33,7 @@ import org.ofbiz.base.util.UtilGenerics; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.base.util.UtilXml; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.testtools.EntityTestCase; import org.ofbiz.service.GenericDispatcher; @@ -68,7 +69,7 @@ public class ModelTestSuite { String uniqueSuffix = "-" + RandomStringUtils.randomAlphanumeric(10); - this.delegator = GenericDelegator.getGenericDelegator(this.originalDelegatorName).makeTestDelegator(this.originalDelegatorName + uniqueSuffix); + this.delegator = DelegatorFactory.getGenericDelegator(this.originalDelegatorName).makeTestDelegator(this.originalDelegatorName + uniqueSuffix); this.dispatcher = GenericDispatcher.getLocalDispatcher(originalDispatcherName + uniqueSuffix, delegator); for (Element testCaseElement : UtilXml.childElementList(mainElement, UtilMisc.toSet("test-case", "test-group"))) { diff --git a/framework/webapp/src/org/ofbiz/webapp/control/ContextFilter.java b/framework/webapp/src/org/ofbiz/webapp/control/ContextFilter.java index a29f22472d..0f9ad2a68d 100644 --- a/framework/webapp/src/org/ofbiz/webapp/control/ContextFilter.java +++ b/framework/webapp/src/org/ofbiz/webapp/control/ContextFilter.java @@ -50,6 +50,7 @@ import static org.ofbiz.base.util.UtilGenerics.checkMap; import org.ofbiz.base.util.UtilHttp; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.base.util.UtilObject; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.security.Security; import org.ofbiz.security.SecurityConfigurationException; @@ -329,7 +330,7 @@ public class ContextFilter implements Filter { delegatorName = "default"; } if (Debug.verboseOn()) Debug.logVerbose("Setup Entity Engine Delegator with name " + delegatorName, module); - delegator = GenericDelegator.getGenericDelegator(delegatorName); + delegator = DelegatorFactory.getGenericDelegator(delegatorName); config.getServletContext().setAttribute("delegator", delegator); if (delegator == null) { Debug.logError("[ContextFilter.init] ERROR: delegator factory returned null for delegatorName \"" + delegatorName + "\"", module); diff --git a/framework/webapp/src/org/ofbiz/webapp/control/ControlServlet.java b/framework/webapp/src/org/ofbiz/webapp/control/ControlServlet.java index 6677e73417..3b75688c9d 100644 --- a/framework/webapp/src/org/ofbiz/webapp/control/ControlServlet.java +++ b/framework/webapp/src/org/ofbiz/webapp/control/ControlServlet.java @@ -36,6 +36,7 @@ import org.ofbiz.base.util.UtilHttp; import org.ofbiz.base.util.UtilJ2eeCompat; import org.ofbiz.base.util.UtilTimer; import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.transaction.GenericTransactionException; @@ -111,11 +112,6 @@ public class ControlServlet extends HttpServlet { GenericValue userLogin = (GenericValue) session.getAttribute("userLogin"); //Debug.log("Cert Chain: " + request.getAttribute("javax.servlet.request.X509Certificate"), module); - // set the Entity Engine user info if we have a userLogin - if (userLogin != null) { - GenericDelegator.pushUserIdentifier(userLogin.getString("userLoginId")); - } - // workaraound if we are in the root webapp String webappName = UtilHttp.getApplicationName(request); @@ -148,7 +144,7 @@ public class ControlServlet extends HttpServlet { GenericDelegator delegator = null; String delegatorName = (String) session.getAttribute("delegatorName"); if (UtilValidate.isNotEmpty(delegatorName)) { - delegator = GenericDelegator.getGenericDelegator(delegatorName); + delegator = DelegatorFactory.getGenericDelegator(delegatorName); } if (delegator == null) { delegator = (GenericDelegator) getServletContext().getAttribute("delegator"); @@ -194,10 +190,15 @@ public class ControlServlet extends HttpServlet { UtilHttp.setInitialRequestInfo(request); VisitHandler.getVisitor(request, response); - // set the Entity Engine user info if we have a userLogin - String visitId = VisitHandler.getVisitId(session); - if (UtilValidate.isNotEmpty(visitId)) { - GenericDelegator.pushSessionIdentifier(visitId); + if (delegator != null) { + // set the GenericDelegator properties + String visitId = VisitHandler.getVisitId(session); + if (UtilValidate.isNotEmpty(visitId)) { + delegator.setSessionIdentifier(visitId); + } + if (userLogin != null) { + delegator.setUserIdentifier(userLogin.getString("userLoginId")); + } } // display details on the servlet objects @@ -310,10 +311,6 @@ public class ControlServlet extends HttpServlet { } } if (Debug.timingOn()) timer.timerString("[" + rname + "] Request Done", module); - - // sanity check 2: make sure there are no user or session infos in the delegator, ie clear the thread - GenericDelegator.clearUserIdentifierStack(); - GenericDelegator.clearSessionIdentifierStack(); } /** diff --git a/framework/webapp/src/org/ofbiz/webapp/control/RequestHandler.java b/framework/webapp/src/org/ofbiz/webapp/control/RequestHandler.java index d7b4c75817..ab065acf16 100644 --- a/framework/webapp/src/org/ofbiz/webapp/control/RequestHandler.java +++ b/framework/webapp/src/org/ofbiz/webapp/control/RequestHandler.java @@ -107,6 +107,8 @@ public class RequestHandler { GenericValue userLogin, GenericDelegator delegator) throws RequestHandlerException { HttpSession session = request.getSession(); + Locale locale = UtilHttp.getLocale(request); + delegator.setLocale(locale); // get the controllerConfig once for this method so we don't have to get it over and over inside the method ConfigXMLReader.ControllerConfig controllerConfig = this.getControllerConfig(); @@ -180,7 +182,6 @@ public class RequestHandler { // If the request method was POST then return an error to avoid problems with XSRF where the request may have come from another machine/program and had the same session ID but was not encrypted as it should have been (we used to let it pass to not lose data since it was too late to protect that data anyway) if (request.getMethod().equalsIgnoreCase("POST")) { // we can't redirect with the body parameters, and for better security from XSRF, just return an error message - Locale locale = UtilHttp.getLocale(request); String errMsg = UtilProperties.getMessage("WebappUiLabels", "requestHandler.InsecureFormPostToSecureRequest", locale); Debug.logError("Got a insecure (non-https) form POST to a secure (http) request [" + requestMap.uri + "], returning error", module); @@ -387,7 +388,6 @@ public class RequestHandler { // check to see if there is an "error" response, if so go there and make an request error message if (requestMap.requestResponseMap.containsKey("error")) { eventReturn = "error"; - Locale locale = UtilHttp.getLocale(request); String errMsg = UtilProperties.getMessage("WebappUiLabels", "requestHandler.error_call_event", locale); request.setAttribute("_ERROR_MESSAGE_", errMsg + ": " + e.toString()); } else { diff --git a/framework/webapp/src/org/ofbiz/webapp/event/CoreEvents.java b/framework/webapp/src/org/ofbiz/webapp/event/CoreEvents.java index 65f728623b..560302cf6e 100644 --- a/framework/webapp/src/org/ofbiz/webapp/event/CoreEvents.java +++ b/framework/webapp/src/org/ofbiz/webapp/event/CoreEvents.java @@ -43,6 +43,7 @@ import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilHttp; import org.ofbiz.base.util.UtilProperties; import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntity; import org.ofbiz.entity.GenericValue; @@ -117,7 +118,7 @@ public class CoreEvents { return "error"; } - GenericDelegator delegator = GenericDelegator.getGenericDelegator(delegatorName); + GenericDelegator delegator = DelegatorFactory.getGenericDelegator(delegatorName); if (delegator == null) { String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.no_delegator_name_defined", locale); diff --git a/framework/webapp/src/org/ofbiz/webapp/event/ServiceStreamHandler.java b/framework/webapp/src/org/ofbiz/webapp/event/ServiceStreamHandler.java index 1dd814cf50..8793fc9d7a 100644 --- a/framework/webapp/src/org/ofbiz/webapp/event/ServiceStreamHandler.java +++ b/framework/webapp/src/org/ofbiz/webapp/event/ServiceStreamHandler.java @@ -32,6 +32,7 @@ import javax.servlet.http.HttpServletResponse; import javolution.util.FastMap; import org.ofbiz.base.util.Debug; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.service.GenericDispatcher; import org.ofbiz.service.GenericServiceException; @@ -52,7 +53,7 @@ public class ServiceStreamHandler implements EventHandler { public void init(ServletContext context) throws EventHandlerException { String delegatorName = context.getInitParameter("entityDelegatorName"); - this.delegator = GenericDelegator.getGenericDelegator(delegatorName); + this.delegator = DelegatorFactory.getGenericDelegator(delegatorName); this.dispatcher = GenericDispatcher.getLocalDispatcher(dispatcherName, delegator); } diff --git a/framework/webapp/src/org/ofbiz/webapp/event/XmlRpcEventHandler.java b/framework/webapp/src/org/ofbiz/webapp/event/XmlRpcEventHandler.java index 158164bc45..c57757643b 100644 --- a/framework/webapp/src/org/ofbiz/webapp/event/XmlRpcEventHandler.java +++ b/framework/webapp/src/org/ofbiz/webapp/event/XmlRpcEventHandler.java @@ -49,6 +49,7 @@ import org.apache.xmlrpc.server.XmlRpcNoSuchHandlerException; import org.apache.xmlrpc.util.HttpUtil; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.service.DispatchContext; import org.ofbiz.service.GenericDispatcher; @@ -74,7 +75,7 @@ public class XmlRpcEventHandler extends XmlRpcHttpServer implements EventHandler public void init(ServletContext context) throws EventHandlerException { String delegatorName = context.getInitParameter("entityDelegatorName"); - this.delegator = GenericDelegator.getGenericDelegator(delegatorName); + this.delegator = DelegatorFactory.getGenericDelegator(delegatorName); this.dispatcher = GenericDispatcher.getLocalDispatcher(dispatcherName, delegator); this.setHandlerMapping(new ServiceRpcHandler()); diff --git a/framework/webapp/src/org/ofbiz/webapp/stats/ServerHitBin.java b/framework/webapp/src/org/ofbiz/webapp/stats/ServerHitBin.java index d94821e24d..83bc98f2c7 100644 --- a/framework/webapp/src/org/ofbiz/webapp/stats/ServerHitBin.java +++ b/framework/webapp/src/org/ofbiz/webapp/stats/ServerHitBin.java @@ -33,6 +33,7 @@ import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilHttp; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilProperties; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; @@ -353,7 +354,7 @@ public class ServerHitBin { public GenericDelegator getDelegator() { if (this.delegator == null) { - this.delegator = GenericDelegator.getGenericDelegator(this.delegatorName); + this.delegator = DelegatorFactory.getGenericDelegator(this.delegatorName); } // if still null, then we have a problem if (this.delegator == null) { diff --git a/framework/webapp/src/org/ofbiz/webapp/stats/VisitHandler.java b/framework/webapp/src/org/ofbiz/webapp/stats/VisitHandler.java index f04bb7d662..1053e832d7 100644 --- a/framework/webapp/src/org/ofbiz/webapp/stats/VisitHandler.java +++ b/framework/webapp/src/org/ofbiz/webapp/stats/VisitHandler.java @@ -32,6 +32,7 @@ import org.ofbiz.base.util.UtilHttp; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilProperties; import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; @@ -107,7 +108,7 @@ public class VisitHandler { // first try the session attribute delegatorName String delegatorName = (String) session.getAttribute("delegatorName"); if (UtilValidate.isNotEmpty(delegatorName)) { - delegator = GenericDelegator.getGenericDelegator(delegatorName); + delegator = DelegatorFactory.getGenericDelegator(delegatorName); } // then try the ServletContext attribute delegator, should always be there... @@ -199,7 +200,7 @@ public class VisitHandler { String delegatorName = (String) session.getAttribute("delegatorName"); if (delegator == null && UtilValidate.isNotEmpty(delegatorName)) { - delegator = GenericDelegator.getGenericDelegator(delegatorName); + delegator = DelegatorFactory.getGenericDelegator(delegatorName); } if (delegator == null) { diff --git a/framework/webapp/src/org/ofbiz/webapp/webdav/WebDavServlet.java b/framework/webapp/src/org/ofbiz/webapp/webdav/WebDavServlet.java index 48bae7206f..a55f15360d 100644 --- a/framework/webapp/src/org/ofbiz/webapp/webdav/WebDavServlet.java +++ b/framework/webapp/src/org/ofbiz/webapp/webdav/WebDavServlet.java @@ -32,6 +32,7 @@ import javax.servlet.http.HttpSession; import org.ofbiz.base.util.CachedClassLoader; import org.ofbiz.base.util.Debug; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.security.Security; import org.ofbiz.security.SecurityFactory; @@ -67,7 +68,7 @@ public class WebDavServlet extends GenericServlet { Thread.currentThread().setContextClassLoader(loader); ServletContext context = this.getServletContext(); String delegatorName = context.getInitParameter("entityDelegatorName"); - this.delegator = GenericDelegator.getGenericDelegator(delegatorName); + this.delegator = DelegatorFactory.getGenericDelegator(delegatorName); String dispatcherName = context.getInitParameter("localDispatcherName"); this.dispatcher = GenericDispatcher.getLocalDispatcher(dispatcherName, this.delegator); this.security = SecurityFactory.getInstance(this.delegator); diff --git a/framework/webslinger/src/org/ofbiz/webslinger/WebslingerContextMapper.java b/framework/webslinger/src/org/ofbiz/webslinger/WebslingerContextMapper.java index 315c9114f8..947b0ccbb3 100644 --- a/framework/webslinger/src/org/ofbiz/webslinger/WebslingerContextMapper.java +++ b/framework/webslinger/src/org/ofbiz/webslinger/WebslingerContextMapper.java @@ -33,6 +33,7 @@ import javax.servlet.http.HttpServletRequest; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilProperties; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; @@ -59,7 +60,7 @@ public class WebslingerContextMapper extends AbstractMappingWebslingerServletCon System.err.println(org.webslinger.commons.vfs.flat.FlatFileProvider.class); servletContext = config.getServletContext(); String delegatorName = servletContext.getInitParameter("entityDelegatorName"); - delegator = GenericDelegator.getGenericDelegator(delegatorName); + delegator = DelegatorFactory.getGenericDelegator(delegatorName); String readerFiles = servletContext.getInitParameter("serviceReaderUrls"); if (readerFiles != null) { for (String reader: CollectionUtil.split(readerFiles, ";")) { @@ -103,7 +104,7 @@ public class WebslingerContextMapper extends AbstractMappingWebslingerServletCon @Override protected void initializeContext(WebslingerServletContext context, Layout layout) throws Exception { OfbizLayout ofbizLayout = (OfbizLayout) layout; - GenericDelegator delegator = GenericDelegator.getGenericDelegator(ofbizLayout.delegatorName); + GenericDelegator delegator = DelegatorFactory.getGenericDelegator(ofbizLayout.delegatorName); context.setAttribute("delegator", delegator); context.setAttribute("dispatcher", new WebslingerGenericDispatcher(context, layout.getTarget(), delegator, globalReaderURLs)); context.setAttribute("authz", AuthorizationFactory.getInstance(delegator)); diff --git a/framework/webtools/src/org/ofbiz/webtools/WebToolsServices.java b/framework/webtools/src/org/ofbiz/webtools/WebToolsServices.java index d6b9479441..69aa7c3e74 100644 --- a/framework/webtools/src/org/ofbiz/webtools/WebToolsServices.java +++ b/framework/webtools/src/org/ofbiz/webtools/WebToolsServices.java @@ -62,6 +62,7 @@ import org.ofbiz.base.util.UtilProperties; import org.ofbiz.base.util.UtilURL; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.base.util.UtilProperties.UtilResourceBundle; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; @@ -349,7 +350,7 @@ public class WebToolsServices { } String groupNameToUse = overrideGroup != null ? overrideGroup : "org.ofbiz"; - GenericDelegator delegator = UtilValidate.isNotEmpty(overrideDelegator) ? GenericDelegator.getGenericDelegator(overrideDelegator) : dctx.getDelegator(); + GenericDelegator delegator = UtilValidate.isNotEmpty(overrideDelegator) ? DelegatorFactory.getGenericDelegator(overrideDelegator) : dctx.getDelegator(); String helperName = delegator.getGroupHelperName(groupNameToUse); if (helperName == null) { diff --git a/specialpurpose/shark/src/org/ofbiz/shark/audit/AuditEntityObject.java b/specialpurpose/shark/src/org/ofbiz/shark/audit/AuditEntityObject.java index 34e8e89b84..a4d87e56ea 100644 --- a/specialpurpose/shark/src/org/ofbiz/shark/audit/AuditEntityObject.java +++ b/specialpurpose/shark/src/org/ofbiz/shark/audit/AuditEntityObject.java @@ -18,6 +18,7 @@ *******************************************************************************/ package org.ofbiz.shark.audit; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; @@ -40,7 +41,7 @@ public abstract class AuditEntityObject { public GenericDelegator getGenericDelegator() { if (this.delegator == null && delegatorName != null) { - this.delegator = GenericDelegator.getGenericDelegator(delegatorName); + this.delegator = DelegatorFactory.getGenericDelegator(delegatorName); } return this.delegator; } diff --git a/specialpurpose/shark/src/org/ofbiz/shark/container/SharkContainer.java b/specialpurpose/shark/src/org/ofbiz/shark/container/SharkContainer.java index 02b665cdfb..ac7d7eb6a0 100644 --- a/specialpurpose/shark/src/org/ofbiz/shark/container/SharkContainer.java +++ b/specialpurpose/shark/src/org/ofbiz/shark/container/SharkContainer.java @@ -40,6 +40,7 @@ import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.GeneralRuntimeException; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilProperties; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; @@ -107,7 +108,7 @@ public class SharkContainer implements Container, Runnable } // get the delegator and dispatcher objects - SharkContainer.delegator = GenericDelegator.getGenericDelegator(delegatorProp.value); + SharkContainer.delegator = DelegatorFactory.getGenericDelegator(delegatorProp.value); try { SharkContainer.dispatcher = GenericDispatcher.getLocalDispatcher(dispatcherProp.value, SharkContainer.delegator); } catch (GenericServiceException e) { diff --git a/specialpurpose/shark/src/org/ofbiz/shark/instance/InstanceEntityObject.java b/specialpurpose/shark/src/org/ofbiz/shark/instance/InstanceEntityObject.java index f2efbf69de..2fcee4ca1b 100644 --- a/specialpurpose/shark/src/org/ofbiz/shark/instance/InstanceEntityObject.java +++ b/specialpurpose/shark/src/org/ofbiz/shark/instance/InstanceEntityObject.java @@ -18,6 +18,7 @@ *******************************************************************************/ package org.ofbiz.shark.instance; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericDelegator; @@ -39,7 +40,7 @@ public abstract class InstanceEntityObject { public GenericDelegator getGenericDelegator() { if (this.delegator == null && delegatorName != null) { - this.delegator = GenericDelegator.getGenericDelegator(delegatorName); + this.delegator = DelegatorFactory.getGenericDelegator(delegatorName); } return this.delegator; } diff --git a/specialpurpose/shark/src/org/ofbiz/shark/requester/AbstractRequester.java b/specialpurpose/shark/src/org/ofbiz/shark/requester/AbstractRequester.java index 43e2345d8f..750a9543ea 100644 --- a/specialpurpose/shark/src/org/ofbiz/shark/requester/AbstractRequester.java +++ b/specialpurpose/shark/src/org/ofbiz/shark/requester/AbstractRequester.java @@ -25,6 +25,7 @@ import java.util.Map; import java.util.HashMap; import java.io.Serializable; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; @@ -146,7 +147,7 @@ public abstract class AbstractRequester implements WfRequester, Serializable { protected synchronized GenericDelegator getDelegator() { if (this.delegator == null && this.delegatorName != null) { - this.delegator = GenericDelegator.getGenericDelegator(this.delegatorName); + this.delegator = DelegatorFactory.getGenericDelegator(this.delegatorName); } return this.delegator; } diff --git a/specialpurpose/webpos/src/org/ofbiz/webpos/session/WebPosSession.java b/specialpurpose/webpos/src/org/ofbiz/webpos/session/WebPosSession.java index 0e1f544691..a0fd443b9a 100755 --- a/specialpurpose/webpos/src/org/ofbiz/webpos/session/WebPosSession.java +++ b/specialpurpose/webpos/src/org/ofbiz/webpos/session/WebPosSession.java @@ -28,6 +28,7 @@ import org.ofbiz.base.util.GeneralException; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilProperties; import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; @@ -145,7 +146,7 @@ public class WebPosSession { public GenericDelegator getDelegator() { if (UtilValidate.isEmpty(delegator)) { - delegator = GenericDelegator.getGenericDelegator(delegatorName); + delegator = DelegatorFactory.getGenericDelegator(delegatorName); } return delegator; } diff --git a/specialpurpose/workflow/src/org/ofbiz/workflow/definition/XpdlReader.java b/specialpurpose/workflow/src/org/ofbiz/workflow/definition/XpdlReader.java index f48d417c4d..1811fddcad 100644 --- a/specialpurpose/workflow/src/org/ofbiz/workflow/definition/XpdlReader.java +++ b/specialpurpose/workflow/src/org/ofbiz/workflow/definition/XpdlReader.java @@ -35,6 +35,7 @@ import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilURL; import org.ofbiz.base.util.UtilXml; import org.ofbiz.base.util.UtilValidate; +import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; @@ -1312,7 +1313,7 @@ public class XpdlReader { if (args.length > 0) sampleFileName = args[0]; - List values = readXpdl(UtilURL.fromFilename(sampleFileName), GenericDelegator.getGenericDelegator("default")); + List values = readXpdl(UtilURL.fromFilename(sampleFileName), DelegatorFactory.getGenericDelegator("default")); Iterator viter = values.iterator(); while (viter.hasNext())