use of org.apache.ofbiz.entity.GenericEntityConfException in project ofbiz-framework by apache.
the class ModelGroupReader method getGroupCache.
public Map<String, String> getGroupCache(String delegatorName) {
if (this.groupCache == null) {
// don't want to block here
synchronized (ModelGroupReader.class) {
// must check if null again as one of the blocked threads can still enter
if (this.groupCache == null) {
// now it's safe
this.groupCache = new HashMap<>();
this.groupNames = new TreeSet<>();
UtilTimer utilTimer = new UtilTimer();
// utilTimer.timerString("[ModelGroupReader.getGroupCache] Before getDocument");
int i = 0;
for (ResourceHandler entityGroupResourceHandler : this.entityGroupResourceHandlers) {
Document document = null;
try {
document = entityGroupResourceHandler.getDocument();
} catch (GenericConfigException e) {
Debug.logError(e, "Error loading entity group model", module);
}
if (document == null) {
this.groupCache = null;
return null;
}
// utilTimer.timerString("[ModelGroupReader.getGroupCache] Before getDocumentElement");
Element docElement = document.getDocumentElement();
if (docElement == null) {
continue;
}
docElement.normalize();
Node curChild = docElement.getFirstChild();
if (curChild != null) {
utilTimer.timerString("[ModelGroupReader.getGroupCache] Before start of entity loop");
do {
if (curChild.getNodeType() == Node.ELEMENT_NODE && "entity-group".equals(curChild.getNodeName())) {
Element curEntity = (Element) curChild;
String entityName = UtilXml.checkEmpty(curEntity.getAttribute("entity")).intern();
String groupName = UtilXml.checkEmpty(curEntity.getAttribute("group")).intern();
try {
if (null == EntityConfig.getInstance().getDelegator(delegatorName).getGroupDataSource(groupName)) {
Debug.logError("The declared group name " + groupName + " has no corresponding group-map in entityengine.xml: ", module);
}
} catch (GenericEntityConfException e) {
Debug.logWarning(e, "Exception thrown while getting group name: ", module);
}
this.groupNames.add(groupName);
this.groupCache.put(entityName, groupName);
// utilTimer.timerString(" After entityEntityName -- " + i + " --");
i++;
}
} while ((curChild = curChild.getNextSibling()) != null);
} else {
Debug.logWarning("[ModelGroupReader.getGroupCache] No child nodes found.", module);
}
}
utilTimer.timerString("[ModelGroupReader.getGroupCache] FINISHED - Total Entity-Groups: " + i + " FINISHED");
}
}
}
return this.groupCache;
}
use of org.apache.ofbiz.entity.GenericEntityConfException in project ofbiz-framework by apache.
the class ModelReader method getEntityCache.
public Map<String, ModelEntity> getEntityCache() throws GenericEntityException {
if (entityCache == null) {
// don't want to block here
synchronized (ModelReader.class) {
// must check if null again as one of the blocked threads can still enter
if (entityCache == null) {
// now it's safe
numEntities = 0;
numViewEntities = 0;
numFields = 0;
numRelations = 0;
numAutoRelations = 0;
entityCache = new HashMap<>();
List<ModelViewEntity> tempViewEntityList = new LinkedList<>();
List<Element> tempExtendEntityElementList = new LinkedList<>();
UtilTimer utilTimer = new UtilTimer();
for (ResourceHandler entityResourceHandler : entityResourceHandlers) {
// utilTimer.timerString("Before getDocument in file " + entityFileName);
Document document = null;
try {
document = entityResourceHandler.getDocument();
} catch (GenericConfigException e) {
throw new GenericEntityConfException("Error getting document from resource handler", e);
}
if (document == null) {
throw new GenericEntityConfException("Could not get document for " + entityResourceHandler.toString());
}
// utilTimer.timerString("Before getDocumentElement in " +
// entityResourceHandler.toString());
Element docElement = document.getDocumentElement();
if (docElement == null) {
return null;
}
docElement.normalize();
Node curChild = docElement.getFirstChild();
ModelInfo def = ModelInfo.createFromElements(ModelInfo.DEFAULT, docElement);
int i = 0;
if (curChild != null) {
utilTimer.timerString("Before start of entity loop in " + entityResourceHandler.toString());
do {
boolean isEntity = "entity".equals(curChild.getNodeName());
boolean isViewEntity = "view-entity".equals(curChild.getNodeName());
boolean isExtendEntity = "extend-entity".equals(curChild.getNodeName());
if ((isEntity || isViewEntity) && curChild.getNodeType() == Node.ELEMENT_NODE) {
i++;
ModelEntity modelEntity = buildEntity(entityResourceHandler, (Element) curChild, i, def);
// put the view entity in a list to get ready for the second pass to populate fields...
if (isViewEntity) {
tempViewEntityList.add((ModelViewEntity) modelEntity);
} else {
entityCache.put(modelEntity.getEntityName(), modelEntity);
}
} else if (isExtendEntity && curChild.getNodeType() == Node.ELEMENT_NODE) {
tempExtendEntityElementList.add((Element) curChild);
}
} while ((curChild = curChild.getNextSibling()) != null);
} else {
Debug.logWarning("No child nodes found.", module);
}
utilTimer.timerString("Finished " + entityResourceHandler.toString() + " - Total Entities: " + i + " FINISHED");
}
// all entity elements in, now go through extend-entity elements and add their stuff
for (Element extendEntityElement : tempExtendEntityElementList) {
String entityName = UtilXml.checkEmpty(extendEntityElement.getAttribute("entity-name"));
ModelEntity modelEntity = entityCache.get(entityName);
if (modelEntity == null)
throw new GenericEntityConfException("Entity to extend does not exist: " + entityName);
modelEntity.addExtendEntity(this, extendEntityElement);
}
// do a pass on all of the view entities now that all of the entities have loaded and populate the fields
while (!tempViewEntityList.isEmpty()) {
int startSize = tempViewEntityList.size();
Iterator<ModelViewEntity> mveIt = tempViewEntityList.iterator();
TEMP_VIEW_LOOP: while (mveIt.hasNext()) {
ModelViewEntity curViewEntity = mveIt.next();
for (ModelViewEntity.ModelMemberEntity mve : curViewEntity.getAllModelMemberEntities()) {
if (!entityCache.containsKey(mve.getEntityName())) {
continue TEMP_VIEW_LOOP;
}
}
mveIt.remove();
curViewEntity.populateFields(this);
for (ModelViewEntity.ModelMemberEntity mve : curViewEntity.getAllModelMemberEntities()) {
ModelEntity me = entityCache.get(mve.getEntityName());
me.addViewEntity(curViewEntity);
}
entityCache.put(curViewEntity.getEntityName(), curViewEntity);
}
if (tempViewEntityList.size() == startSize) {
// that have some reference problem.
break;
}
}
if (!tempViewEntityList.isEmpty()) {
StringBuilder sb = new StringBuilder("View entities reference non-existant members:\n");
Set<String> allViews = new HashSet<>();
for (ModelViewEntity curViewEntity : tempViewEntityList) {
allViews.add(curViewEntity.getEntityName());
}
for (ModelViewEntity curViewEntity : tempViewEntityList) {
Set<String> perViewMissingEntities = new HashSet<>();
Iterator<ModelViewEntity.ModelMemberEntity> mmeIt = curViewEntity.getAllModelMemberEntities().iterator();
while (mmeIt.hasNext()) {
ModelViewEntity.ModelMemberEntity mme = mmeIt.next();
String memberEntityName = mme.getEntityName();
if (!entityCache.containsKey(memberEntityName)) {
// check to see if it is a view
if (!allViews.contains(memberEntityName)) {
// not a view, it's a real missing entity
perViewMissingEntities.add(memberEntityName);
}
}
}
for (String perViewMissingEntity : perViewMissingEntities) {
sb.append("\t[").append(curViewEntity.getEntityName()).append("] missing member entity [").append(perViewMissingEntity).append("]\n");
}
}
throw new GenericEntityConfException(sb.toString());
}
// auto-create relationships
Set<String> orderedMessages = new TreeSet<>();
for (String curEntityName : new TreeSet<>(this.getEntityNames())) {
ModelEntity curModelEntity = this.getModelEntity(curEntityName);
if (curModelEntity instanceof ModelViewEntity) {
// for view-entities auto-create relationships for all member-entity
// relationships that have all corresponding fields in the view-entity
} else {
// for entities auto-create many relationships for all type one relationships
// just in case we add a new relation to the same entity, keep in a separate
// list and add them at the end
List<ModelRelation> newSameEntityRelations = new LinkedList<>();
Iterator<ModelRelation> relationsIter = curModelEntity.getRelationsIterator();
while (relationsIter.hasNext()) {
ModelRelation modelRelation = relationsIter.next();
if (("one".equals(modelRelation.getType()) || "one-nofk".equals(modelRelation.getType())) && !modelRelation.isAutoRelation()) {
ModelEntity relatedEnt = null;
try {
relatedEnt = this.getModelEntity(modelRelation.getRelEntityName());
} catch (GenericModelException e) {
throw new GenericModelException("Error getting related entity [" + modelRelation.getRelEntityName() + "] definition from entity [" + curEntityName + "]", e);
}
// create the new relationship even if one exists so we can show what we are
// looking for in the info message
// don't do relationship to the same entity, unless title is "Parent", then do a
// "Child" automatically
String title = modelRelation.getTitle();
if (curModelEntity.getEntityName().equals(relatedEnt.getEntityName()) && "Parent".equals(title)) {
title = "Child";
}
String description = "";
String type = "";
String relEntityName = curModelEntity.getEntityName();
String fkName = "";
ArrayList<ModelKeyMap> keyMaps = new ArrayList<>();
boolean isAutoRelation = true;
Set<String> curEntityKeyFields = new HashSet<>();
for (ModelKeyMap curkm : modelRelation.getKeyMaps()) {
keyMaps.add(new ModelKeyMap(curkm.getRelFieldName(), curkm.getFieldName()));
curEntityKeyFields.add(curkm.getFieldName());
}
keyMaps.trimToSize();
// the complete pk of the relEntity
if (curModelEntity.containsAllPkFieldNames(curEntityKeyFields)) {
// always use one-nofk, we don't want auto-fks getting in for these automatic ones
type = "one-nofk";
// to keep it clean, remove any additional keys that aren't part of the PK
List<String> curPkFieldNames = curModelEntity.getPkFieldNames();
Iterator<ModelKeyMap> nrkmIter = keyMaps.iterator();
while (nrkmIter.hasNext()) {
ModelKeyMap nrkm = nrkmIter.next();
String checkField = nrkm.getRelFieldName();
if (!curPkFieldNames.contains(checkField)) {
nrkmIter.remove();
}
}
} else {
type = "many";
}
ModelRelation newRel = ModelRelation.create(relatedEnt, description, type, title, relEntityName, fkName, keyMaps, isAutoRelation);
ModelRelation existingRelation = relatedEnt.getRelation(title + curModelEntity.getEntityName());
if (existingRelation == null) {
numAutoRelations++;
if (curModelEntity.getEntityName().equals(relatedEnt.getEntityName())) {
newSameEntityRelations.add(newRel);
} else {
relatedEnt.addRelation(newRel);
}
} else {
if (newRel.equals(existingRelation)) {
// don't warn if the target title+entity = current title+entity
if (Debug.infoOn() && !(title + curModelEntity.getEntityName()).equals(modelRelation.getTitle() + modelRelation.getRelEntityName())) {
// String errorMsg = "Relation already exists to entity [] with title ["
// + targetTitle + "],from entity []";
String message = "Entity [" + relatedEnt.getPackageName() + ":" + relatedEnt.getEntityName() + "] already has identical relationship to entity [" + curModelEntity.getEntityName() + "] title [" + title + "]; would auto-create: type [" + newRel.getType() + "] and fields [" + newRel.keyMapString(",", "") + "]";
orderedMessages.add(message);
}
} else {
String message = "Existing relationship with the same name, but different specs found from what would be auto-created for Entity [" + relatedEnt.getEntityName() + "] and relationship to entity [" + curModelEntity.getEntityName() + "] title [" + title + "]; would auto-create: type [" + newRel.getType() + "] and fields [" + newRel.keyMapString(",", "") + "]";
if (Debug.verboseOn())
Debug.logVerbose(message, module);
}
}
}
}
if (newSameEntityRelations.size() > 0) {
for (ModelRelation newRel : newSameEntityRelations) {
curModelEntity.addRelation(newRel);
}
}
}
}
if (Debug.infoOn()) {
for (String message : orderedMessages) {
Debug.logInfo(message, module);
}
Debug.logInfo("Finished loading entities; #Entities=" + numEntities + " #ViewEntities=" + numViewEntities + " #Fields=" + numFields + " #Relationships=" + numRelations + " #AutoRelationships=" + numAutoRelations, module);
}
}
}
}
return entityCache;
}
use of org.apache.ofbiz.entity.GenericEntityConfException in project ofbiz-framework by apache.
the class EntityEcaUtil method readConfig.
private static void readConfig(String entityEcaReaderName, Map<String, Map<String, List<EntityEcaRule>>> ecaCache) {
EntityEcaReader entityEcaReaderInfo = null;
try {
entityEcaReaderInfo = EntityConfig.getInstance().getEntityEcaReader(entityEcaReaderName);
} catch (GenericEntityConfException e) {
Debug.logError(e, "Exception thrown while getting entity-eca-reader config with name: " + entityEcaReaderName, module);
}
if (entityEcaReaderInfo == null) {
Debug.logError("BAD ERROR: Could not find entity-eca-reader config with name: " + entityEcaReaderName, module);
return;
}
List<Future<List<EntityEcaRule>>> futures = new LinkedList<Future<List<EntityEcaRule>>>();
for (Resource eecaResourceElement : entityEcaReaderInfo.getResourceList()) {
ResourceHandler handler = new MainResourceHandler(EntityConfig.ENTITY_ENGINE_XML_FILENAME, eecaResourceElement.getLoader(), eecaResourceElement.getLocation());
futures.add(ExecutionPool.GLOBAL_FORK_JOIN.submit(createEcaLoaderCallable(handler)));
}
// get all of the component resource eca stuff, ie specified in each ofbiz-component.xml file
for (ComponentConfig.EntityResourceInfo componentResourceInfo : ComponentConfig.getAllEntityResourceInfos("eca")) {
if (entityEcaReaderName.equals(componentResourceInfo.readerName)) {
futures.add(ExecutionPool.GLOBAL_FORK_JOIN.submit(createEcaLoaderCallable(componentResourceInfo.createResourceHandler())));
}
}
for (List<EntityEcaRule> oneFileRules : ExecutionPool.getAllFutures(futures)) {
for (EntityEcaRule rule : oneFileRules) {
String entityName = rule.getEntityName();
String eventName = rule.getEventName();
Map<String, List<EntityEcaRule>> eventMap = ecaCache.get(entityName);
List<EntityEcaRule> rules = null;
if (eventMap == null) {
eventMap = new HashMap<String, List<EntityEcaRule>>();
rules = new LinkedList<EntityEcaRule>();
ecaCache.put(entityName, eventMap);
eventMap.put(eventName, rules);
} else {
rules = eventMap.get(eventName);
if (rules == null) {
rules = new LinkedList<EntityEcaRule>();
eventMap.put(eventName, rules);
}
}
// This will prevent duplicate rule execution along with enabled/disabled eca workflow
if (rules.remove(rule)) {
Debug.logWarning("Duplicate Entity ECA [" + entityName + "]" + "for operation [ " + rule.getOperationName() + "] " + "on [" + eventName + "] ", module);
}
rules.add(rule);
}
}
}
use of org.apache.ofbiz.entity.GenericEntityConfException in project ofbiz-framework by apache.
the class DBCPConnectionFactory method getConnection.
public Connection getConnection(GenericHelperInfo helperInfo, JdbcElement abstractJdbc) throws SQLException, GenericEntityException {
String cacheKey = helperInfo.getHelperFullName();
DebugManagedDataSource mds = dsCache.get(cacheKey);
if (mds != null) {
return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
}
if (!(abstractJdbc instanceof InlineJdbc)) {
throw new GenericEntityConfException("DBCP requires an <inline-jdbc> child element in the <datasource> element");
}
InlineJdbc jdbcElement = (InlineJdbc) abstractJdbc;
// connection properties
TransactionManager txMgr = TransactionFactoryLoader.getInstance().getTransactionManager();
String driverName = jdbcElement.getJdbcDriver();
String jdbcUri = helperInfo.getOverrideJdbcUri(jdbcElement.getJdbcUri());
String jdbcUsername = helperInfo.getOverrideUsername(jdbcElement.getJdbcUsername());
String jdbcPassword = helperInfo.getOverridePassword(EntityConfig.getJdbcPassword(jdbcElement));
// pool settings
int maxSize = jdbcElement.getPoolMaxsize();
int minSize = jdbcElement.getPoolMinsize();
int maxIdle = jdbcElement.getIdleMaxsize();
// maxIdle must be greater than pool-minsize
maxIdle = maxIdle > minSize ? maxIdle : minSize;
// load the driver
Driver jdbcDriver;
synchronized (DBCPConnectionFactory.class) {
// Sync needed for MS SQL JDBC driver. See OFBIZ-5216.
try {
jdbcDriver = (Driver) Class.forName(driverName, true, Thread.currentThread().getContextClassLoader()).newInstance();
} catch (Exception e) {
Debug.logError(e, module);
throw new GenericEntityException(e.getMessage(), e);
}
}
// connection factory properties
Properties cfProps = new Properties();
cfProps.put("user", jdbcUsername);
cfProps.put("password", jdbcPassword);
// create the connection factory
org.apache.commons.dbcp2.ConnectionFactory cf = new DriverConnectionFactory(jdbcDriver, jdbcUri, cfProps);
// wrap it with a LocalXAConnectionFactory
XAConnectionFactory xacf = new LocalXAConnectionFactory(txMgr, cf);
// create the pool object factory
PoolableConnectionFactory factory = new PoolableManagedConnectionFactory(xacf, null);
factory.setValidationQuery(jdbcElement.getPoolJdbcTestStmt());
factory.setDefaultReadOnly(false);
factory.setRollbackOnReturn(false);
factory.setEnableAutoCommitOnReturn(false);
String transIso = jdbcElement.getIsolationLevel();
if (!transIso.isEmpty()) {
if ("Serializable".equals(transIso)) {
factory.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
} else if ("RepeatableRead".equals(transIso)) {
factory.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
} else if ("ReadUncommitted".equals(transIso)) {
factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
} else if ("ReadCommitted".equals(transIso)) {
factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
} else if ("None".equals(transIso)) {
factory.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
}
}
// configure the pool settings
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setMaxTotal(maxSize);
// settings for idle connections
poolConfig.setMaxIdle(maxIdle);
poolConfig.setMinIdle(minSize);
poolConfig.setTimeBetweenEvictionRunsMillis(jdbcElement.getTimeBetweenEvictionRunsMillis());
// disabled in favour of setSoftMinEvictableIdleTimeMillis(...)
poolConfig.setMinEvictableIdleTimeMillis(-1);
poolConfig.setSoftMinEvictableIdleTimeMillis(jdbcElement.getSoftMinEvictableIdleTimeMillis());
// test all the idle connections
poolConfig.setNumTestsPerEvictionRun(maxSize);
// settings for when the pool is exhausted
// the thread requesting the connection waits if no connection is available
poolConfig.setBlockWhenExhausted(true);
// throw an exception if, after getPoolSleeptime() ms, no connection is available for the requesting thread
poolConfig.setMaxWaitMillis(jdbcElement.getPoolSleeptime());
// settings for the execution of the validation query
poolConfig.setTestOnCreate(jdbcElement.getTestOnCreate());
poolConfig.setTestOnBorrow(jdbcElement.getTestOnBorrow());
poolConfig.setTestOnReturn(jdbcElement.getTestOnReturn());
poolConfig.setTestWhileIdle(jdbcElement.getTestWhileIdle());
GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(factory, poolConfig);
factory.setPool(pool);
mds = new DebugManagedDataSource(pool, xacf.getTransactionRegistry());
mds.setAccessToUnderlyingConnectionAllowed(true);
// cache the pool
dsCache.putIfAbsent(cacheKey, mds);
mds = dsCache.get(cacheKey);
return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
}
Aggregations