use of org.apache.ofbiz.entity.model.ModelViewEntity in project ofbiz-framework by apache.
the class GenericDAO method selectCountByCondition.
public long selectCountByCondition(Delegator delegator, ModelEntity modelEntity, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, List<ModelField> selectFields, EntityFindOptions findOptions) throws GenericEntityException {
if (modelEntity == null) {
return 0;
}
// if no find options passed, use default
if (findOptions == null) {
findOptions = new EntityFindOptions();
}
boolean verboseOn = Debug.verboseOn();
if (verboseOn) {
// put this inside an if statement so that we don't have to generate the string when not used...
if (Debug.verboseOn())
Debug.logVerbose("Doing selectListIteratorByCondition with whereEntityCondition: " + whereEntityCondition, module);
}
boolean isGroupBy = false;
ModelViewEntity modelViewEntity = null;
if (modelEntity instanceof ModelViewEntity) {
modelViewEntity = (ModelViewEntity) modelEntity;
isGroupBy = modelViewEntity.getGroupBysSize() > 0;
}
// To get a count of the rows that will be returned when there is a GROUP BY, must do something like:
// SELECT COUNT(1) FROM (SELECT COUNT(1) FROM OFBIZ.POSTAL_ADDRESS PA GROUP BY PA.CITY) TEMP_NAME
// instead of a simple:
// SELECT COUNT(1) FROM OFBIZ.POSTAL_ADDRESS PA GROUP BY PA.CITY
StringBuilder sqlBuffer = new StringBuilder("SELECT ");
if (isGroupBy) {
sqlBuffer.append("COUNT(1) FROM (SELECT ");
}
if (findOptions.getDistinct()) {
/* DEJ20100304: the code below was causing problems so the line above may be used instead, but hopefully this is fixed now
* may need varying SQL for different databases, and also in view-entities in some cases it seems to
* cause the "COUNT(DISTINCT " to appear twice, causing an attempt to try to count a count (function="count-distinct", distinct=true in find options)
*/
if (selectFields != null && selectFields.size() > 0) {
ModelField firstSelectField = selectFields.get(0);
ModelViewEntity.ModelAlias firstModelAlias = modelViewEntity != null ? modelViewEntity.getAlias(firstSelectField.getName()) : null;
if (firstModelAlias != null && UtilValidate.isNotEmpty(firstModelAlias.getFunction())) {
// if the field has a function already we don't want to count just it, would be meaningless
sqlBuffer.append("COUNT(DISTINCT *) ");
} else {
sqlBuffer.append("COUNT(DISTINCT ");
// this only seems to support a single column, which is not desirable but seems a lot better than no columns or in certain cases all columns
sqlBuffer.append(firstSelectField.getColValue());
// sqlBuffer.append(modelEntity.colNameString(selectFields, ", ", "", datasource.aliasViews));
sqlBuffer.append(")");
}
} else {
sqlBuffer.append("COUNT(DISTINCT *) ");
}
} else {
// NOTE DEJ20080701 Changed from COUNT(*) to COUNT(1) to improve performance, and should get the same results at least when there is no DISTINCT
sqlBuffer.append("COUNT(1) ");
}
// populate the info from entity-condition in the view-entity, if it is one and there is one
List<EntityCondition> viewWhereConditions = null;
List<EntityCondition> viewHavingConditions = null;
List<String> viewOrderByList = null;
if (modelViewEntity != null) {
viewWhereConditions = new LinkedList<EntityCondition>();
viewHavingConditions = new LinkedList<EntityCondition>();
viewOrderByList = new LinkedList<String>();
modelViewEntity.populateViewEntityConditionInformation(modelFieldTypeReader, viewWhereConditions, viewHavingConditions, viewOrderByList, null);
}
// FROM clause and when necessary the JOIN or LEFT JOIN clause(s) as well
sqlBuffer.append(SqlJdbcUtil.makeFromClause(modelEntity, modelFieldTypeReader, datasource));
// WHERE clause
List<EntityConditionParam> whereEntityConditionParams = new LinkedList<EntityConditionParam>();
makeConditionWhereString(sqlBuffer, " WHERE ", modelEntity, whereEntityCondition, viewWhereConditions, whereEntityConditionParams);
// GROUP BY clause for view-entity
if (isGroupBy) {
modelViewEntity.colNameString(modelViewEntity.getGroupBysCopy(), sqlBuffer, " GROUP BY ", ", ", "", false);
}
// HAVING clause
List<EntityConditionParam> havingEntityConditionParams = new LinkedList<EntityConditionParam>();
makeConditionHavingString(sqlBuffer, " HAVING ", modelEntity, havingEntityCondition, viewHavingConditions, havingEntityConditionParams);
if (isGroupBy) {
sqlBuffer.append(") TEMP_NAME");
}
String sql = sqlBuffer.toString();
if (Debug.verboseOn())
Debug.logVerbose("Count select sql: " + sql, module);
try (SQLProcessor sqlP = new SQLProcessor(delegator, helperInfo)) {
sqlP.prepareStatement(sql, findOptions.getSpecifyTypeAndConcur(), findOptions.getResultSetType(), findOptions.getResultSetConcurrency(), findOptions.getFetchSize(), findOptions.getMaxRows());
if (verboseOn) {
// put this inside an if statement so that we don't have to generate the string when not used...
if (Debug.verboseOn())
Debug.logVerbose("Setting the whereEntityConditionParams: " + whereEntityConditionParams, module);
}
// set all of the values from the Where EntityCondition
for (EntityConditionParam whereEntityConditionParam : whereEntityConditionParams) {
SqlJdbcUtil.setValue(sqlP, whereEntityConditionParam.getModelField(), modelEntity.getEntityName(), whereEntityConditionParam.getFieldValue(), modelFieldTypeReader);
}
if (verboseOn) {
// put this inside an if statement so that we don't have to generate the string when not used...
if (Debug.verboseOn())
Debug.logVerbose("Setting the havingEntityConditionParams: " + havingEntityConditionParams, module);
}
// set all of the values from the Having EntityCondition
for (EntityConditionParam havingEntityConditionParam : havingEntityConditionParams) {
SqlJdbcUtil.setValue(sqlP, havingEntityConditionParam.getModelField(), modelEntity.getEntityName(), havingEntityConditionParam.getFieldValue(), modelFieldTypeReader);
}
try {
sqlP.executeQuery();
long count = 0;
ResultSet resultSet = sqlP.getResultSet();
if (resultSet.next()) {
count = resultSet.getLong(1);
}
return count;
} catch (SQLException e) {
throw new GenericDataSourceException("Error getting count value", e);
}
}
}
use of org.apache.ofbiz.entity.model.ModelViewEntity in project ofbiz-framework by apache.
the class GenericDAO method singleUpdateView.
/* ====================================================================== */
/* ====================================================================== */
/**
* Try to update the given ModelViewEntity by trying to insert/update on the entities of which the view is composed.
*
* Works fine with standard O/R mapped models, but has some restrictions meeting more complicated view entities.
* <li>A direct link is required, which means that one of the ModelViewLink field entries must have a value found
* in the given view entity, for each ModelViewLink</li>
* <li>For now, each member entity is updated iteratively, so if eg. the second member entity fails to update,
* the first is written although. See code for details. Try to use "clean" views, until code is more robust ...</li>
* <li>For now, aliased field names in views are not processed correctly, I guess. To be honest, I did not
* find out how to construct such a view - so view fieldnames must have same named fields in member entities.</li>
* <li>A new exception, e.g. GenericViewNotUpdatable, should be defined and thrown if the update fails</li>
*/
private int singleUpdateView(GenericEntity entity, ModelViewEntity modelViewEntity, List<ModelField> fieldsToSave, SQLProcessor sqlP) throws GenericEntityException {
Delegator delegator = entity.getDelegator();
int retVal = 0;
ModelEntity memberModelEntity = null;
// Construct insert/update for each model entity
for (ModelViewEntity.ModelMemberEntity modelMemberEntity : modelViewEntity.getMemberModelMemberEntities().values()) {
String meName = modelMemberEntity.getEntityName();
String meAlias = modelMemberEntity.getEntityAlias();
if (Debug.verboseOn())
Debug.logVerbose("[singleUpdateView]: Processing MemberEntity " + meName + " with Alias " + meAlias, module);
try {
memberModelEntity = delegator.getModelReader().getModelEntity(meName);
} catch (GenericEntityException e) {
throw new GenericEntityException("Failed to get model entity for " + meName, e);
}
Map<String, Object> findByMap = new HashMap<String, Object>();
// Now iterate the ModelViewLinks to construct the "WHERE" part for update/insert
Iterator<ModelViewEntity.ModelViewLink> linkIter = modelViewEntity.getViewLinksIterator();
while (linkIter != null && linkIter.hasNext()) {
ModelViewEntity.ModelViewLink modelViewLink = linkIter.next();
if (modelViewLink.getEntityAlias().equals(meAlias) || modelViewLink.getRelEntityAlias().equals(meAlias)) {
Iterator<ModelKeyMap> kmIter = modelViewLink.getKeyMapsIterator();
while (kmIter != null && kmIter.hasNext()) {
ModelKeyMap keyMap = kmIter.next();
String fieldName = "";
if (modelViewLink.getEntityAlias().equals(meAlias)) {
fieldName = keyMap.getFieldName();
} else {
fieldName = keyMap.getRelFieldName();
}
if (Debug.verboseOn())
Debug.logVerbose("[singleUpdateView]: --- Found field to set: " + meAlias + "." + fieldName, module);
Object value = null;
if (modelViewEntity.isField(keyMap.getFieldName())) {
value = entity.get(keyMap.getFieldName());
if (Debug.verboseOn())
Debug.logVerbose("[singleUpdateView]: --- Found map value: " + value.toString(), module);
} else if (modelViewEntity.isField(keyMap.getRelFieldName())) {
value = entity.get(keyMap.getRelFieldName());
if (Debug.verboseOn())
Debug.logVerbose("[singleUpdateView]: --- Found map value: " + value.toString(), module);
} else {
throw new GenericNotImplementedException("Update on view entities: no direct link found, unable to update");
}
findByMap.put(fieldName, value);
}
}
}
// Look what there already is in the database
List<GenericValue> meResult = null;
try {
meResult = EntityQuery.use(delegator).from(meName).where(findByMap).queryList();
} catch (GenericEntityException e) {
throw new GenericEntityException("Error while retrieving partial results for entity member: " + meName, e);
}
if (Debug.verboseOn())
Debug.logVerbose("[singleUpdateView]: --- Found " + meResult.size() + " results for entity member " + meName, module);
// Got results 0 -> INSERT, 1 -> UPDATE, >1 -> View is nor updatable
GenericValue meGenericValue = null;
if (meResult.size() == 0) {
// Create new value to insert
try {
// Create new value to store
meGenericValue = delegator.makeValue(meName, findByMap);
} catch (Exception e) {
throw new GenericEntityException("Could not create new value for member entity" + meName + " of view " + modelViewEntity.getEntityName(), e);
}
} else if (meResult.size() == 1) {
// Update existing value
meGenericValue = meResult.iterator().next();
} else {
throw new GenericEntityException("Found more than one result for member entity " + meName + " in view " + modelViewEntity.getEntityName() + " - this is no updatable view");
}
// Construct fieldsToSave list for this member entity
List<ModelField> meFieldsToSave = new LinkedList<ModelField>();
for (ModelField modelField : fieldsToSave) {
if (memberModelEntity.isField(modelField.getName())) {
ModelField meModelField = memberModelEntity.getField(modelField.getName());
if (meModelField != null) {
meGenericValue.set(meModelField.getName(), entity.get(modelField.getName()));
meFieldsToSave.add(meModelField);
if (Debug.verboseOn())
Debug.logVerbose("[singleUpdateView]: --- Added field to save: " + meModelField.getName() + " with value " + meGenericValue.get(meModelField.getName()), module);
} else {
throw new GenericEntityException("Could not get field " + modelField.getName() + " from model entity " + memberModelEntity.getEntityName());
}
}
}
/*
* Finally, do the insert/update
* TODO:
* Do the real inserts/updates outside the memberEntity-loop,
* only if all of the found member entities are updatable.
* This avoids partial creation of member entities, which would mean data inconsistency:
* If not all member entities can be updated, then none should be updated
*/
if (meResult.size() == 0) {
retVal += singleInsert(meGenericValue, memberModelEntity, memberModelEntity.getFieldsUnmodifiable(), sqlP);
} else {
if (meFieldsToSave.size() > 0) {
retVal += singleUpdate(meGenericValue, memberModelEntity, meFieldsToSave, sqlP);
} else {
if (Debug.verboseOn())
Debug.logVerbose("[singleUpdateView]: No update on member entity " + memberModelEntity.getEntityName() + " needed", module);
}
}
}
return retVal;
}
use of org.apache.ofbiz.entity.model.ModelViewEntity in project ofbiz-framework by apache.
the class GenericDAO method makeConditionWhereString.
protected StringBuilder makeConditionWhereString(StringBuilder whereString, String prefix, ModelEntity modelEntity, EntityCondition whereEntityCondition, List<EntityCondition> viewWhereConditions, List<EntityConditionParam> whereEntityConditionParams) throws GenericEntityException {
ModelViewEntity modelViewEntity = null;
if (modelEntity instanceof ModelViewEntity) {
modelViewEntity = (ModelViewEntity) modelEntity;
}
List<EntityCondition> conditions = new LinkedList<EntityCondition>();
if (UtilValidate.isNotEmpty(whereEntityCondition)) {
conditions.add(whereEntityCondition);
}
if (modelViewEntity != null && !viewWhereConditions.isEmpty()) {
EntityCondition viewWhereEntityCondition = EntityCondition.makeCondition(viewWhereConditions);
if (!viewWhereEntityCondition.isEmpty()) {
conditions.add(viewWhereEntityCondition);
}
}
String viewClause = SqlJdbcUtil.makeViewWhereClause(modelEntity, datasource.getJoinStyle());
if (viewClause.length() > 0) {
conditions.add(EntityCondition.makeConditionWhere(viewClause));
}
if (!conditions.isEmpty()) {
whereString.append(prefix);
whereString.append(EntityCondition.makeCondition(conditions, EntityOperator.AND).makeWhereString(modelEntity, whereEntityConditionParams, this.datasource));
}
return whereString;
}
use of org.apache.ofbiz.entity.model.ModelViewEntity in project ofbiz-framework by apache.
the class GenericEntity method get.
/**
* call by the previous method to be able to read with View entityName and entity Field and after for real entity
* @param modelEntity the modelEntity, for a view it's the ViewEntity
* @param modelEntityToUse, same as before except if it's a second call for a view, and so it's the real modelEntity
* @return null or resourceValue
*/
private Object get(ModelEntity modelEntity, ModelEntity modelEntityToUse, String name, String resource, Locale locale) {
if (UtilValidate.isEmpty(resource)) {
resource = modelEntityToUse.getDefaultResourceName();
// still empty? return null
if (UtilValidate.isEmpty(resource)) {
return null;
}
}
if (UtilProperties.isPropertiesResourceNotFound(resource, locale, false)) {
// Properties do not exist for this resource+locale combination
return null;
}
ResourceBundle bundle = null;
try {
bundle = UtilProperties.getResourceBundle(resource, locale);
} catch (IllegalArgumentException e) {
bundle = null;
}
if (bundle == null) {
return null;
}
StringBuilder keyBuffer = new StringBuilder();
// start with the Entity Name
keyBuffer.append(modelEntityToUse.getEntityName());
// next add the Field Name
keyBuffer.append('.');
keyBuffer.append(name);
// finish off by adding the values of all PK fields
if (modelEntity instanceof ModelViewEntity) {
// retrieve pkNames of realEntity
ModelViewEntity modelViewEntity = (ModelViewEntity) modelEntity;
List<String> pkNamesToUse = new LinkedList<>();
// iterate on realEntity for pkField
Iterator<ModelField> iter = modelEntityToUse.getPksIterator();
while (iter != null && iter.hasNext()) {
ModelField curField = iter.next();
String pkName = null;
Iterator<ModelAlias> iterAlias = modelViewEntity.getAliasesIterator();
// search aliasName for pkField of realEntity
while (iterAlias != null && iterAlias.hasNext()) {
ModelAlias aliasField = iterAlias.next();
if (aliasField.getField().equals(curField.getName())) {
ModelEntity memberModelEntity = modelViewEntity.getMemberModelEntity(aliasField.getEntityAlias());
if (memberModelEntity.getEntityName().equals(modelEntityToUse.getEntityName())) {
pkName = aliasField.getName();
break;
}
}
}
if (pkName == null) {
pkName = curField.getName();
}
pkNamesToUse.add(pkName);
}
// read value with modelEntity name of pkNames
for (String pkName : pkNamesToUse) {
if (this.containsKey(pkName)) {
keyBuffer.append('.');
keyBuffer.append(this.get(pkName));
}
}
} else {
Iterator<ModelField> iter = modelEntity.getPksIterator();
while (iter != null && iter.hasNext()) {
ModelField curField = iter.next();
keyBuffer.append('.');
keyBuffer.append(this.get(curField.getName()));
}
}
String bundleKey = keyBuffer.toString();
Object resourceValue = null;
try {
resourceValue = bundle.getObject(bundleKey);
} catch (MissingResourceException e) {
return null;
}
return resourceValue;
}
use of org.apache.ofbiz.entity.model.ModelViewEntity in project ofbiz-framework by apache.
the class WebToolsServices method exportEntityEoModelBundle.
public static Map<String, Object> exportEntityEoModelBundle(DispatchContext dctx, Map<String, ? extends Object> context) {
String eomodeldFullPath = (String) context.get("eomodeldFullPath");
String entityPackageNameOrig = (String) context.get("entityPackageName");
String entityGroupId = (String) context.get("entityGroupId");
String datasourceName = (String) context.get("datasourceName");
String entityNamePrefix = (String) context.get("entityNamePrefix");
Locale locale = (Locale) context.get("locale");
if (datasourceName == null)
datasourceName = "localderby";
ModelReader reader = dctx.getDelegator().getModelReader();
try {
if (!eomodeldFullPath.endsWith(".eomodeld")) {
eomodeldFullPath = eomodeldFullPath + ".eomodeld";
}
File outdir = new File(eomodeldFullPath);
if (!outdir.exists()) {
outdir.mkdir();
}
if (!outdir.isDirectory()) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "WebtoolsEomodelFullPathIsNotADirectory", UtilMisc.toMap("eomodeldFullPath", eomodeldFullPath), locale));
}
if (!outdir.canWrite()) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "WebtoolsEomodelFullPathIsNotWriteable", UtilMisc.toMap("eomodeldFullPath", eomodeldFullPath), locale));
}
Set<String> entityNames = new TreeSet<String>();
if (UtilValidate.isNotEmpty(entityPackageNameOrig)) {
Set<String> entityPackageNameSet = new HashSet<String>();
entityPackageNameSet.addAll(StringUtil.split(entityPackageNameOrig, ","));
Debug.logInfo("Exporting with entityPackageNameSet: " + entityPackageNameSet, module);
Map<String, TreeSet<String>> entitiesByPackage = reader.getEntitiesByPackage(entityPackageNameSet, null);
for (Map.Entry<String, TreeSet<String>> entitiesByPackageMapEntry : entitiesByPackage.entrySet()) {
entityNames.addAll(entitiesByPackageMapEntry.getValue());
}
} else if (UtilValidate.isNotEmpty(entityGroupId)) {
Debug.logInfo("Exporting entites from the Group: " + entityGroupId, module);
entityNames.addAll(EntityGroupUtil.getEntityNamesByGroup(entityGroupId, dctx.getDelegator(), false));
} else {
entityNames.addAll(reader.getEntityNames());
}
Debug.logInfo("Exporting the following entities: " + entityNames, module);
// remove all view-entity
Iterator<String> filterEntityNameIter = entityNames.iterator();
while (filterEntityNameIter.hasNext()) {
String entityName = filterEntityNameIter.next();
ModelEntity modelEntity = reader.getModelEntity(entityName);
if (modelEntity instanceof ModelViewEntity) {
filterEntityNameIter.remove();
}
}
// write the index.eomodeld file
Map<String, Object> topLevelMap = new HashMap<String, Object>();
topLevelMap.put("EOModelVersion", "\"2.1\"");
List<Map<String, Object>> entitiesMapList = new LinkedList<Map<String, Object>>();
topLevelMap.put("entities", entitiesMapList);
for (String entityName : entityNames) {
Map<String, Object> entitiesMap = new HashMap<String, Object>();
entitiesMapList.add(entitiesMap);
entitiesMap.put("className", "EOGenericRecord");
entitiesMap.put("name", entityName);
}
UtilPlist.writePlistFile(topLevelMap, eomodeldFullPath, "index.eomodeld", true);
// write each <EntityName>.plist file
for (String curEntityName : entityNames) {
ModelEntity modelEntity = reader.getModelEntity(curEntityName);
UtilPlist.writePlistFile(modelEntity.createEoModelMap(entityNamePrefix, datasourceName, entityNames, reader), eomodeldFullPath, curEntityName + ".plist", true);
}
Integer entityNamesSize = new Integer(entityNames.size());
return ServiceUtil.returnSuccess(UtilProperties.getMessage(resource, "WebtoolsEomodelExported", UtilMisc.toMap("entityNamesSize", entityNamesSize.toString(), "eomodeldFullPath", eomodeldFullPath), locale));
} catch (UnsupportedEncodingException e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "WebtoolsEomodelSavingFileError", UtilMisc.toMap("errorString", e.toString()), locale));
} catch (FileNotFoundException e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "WebtoolsEomodelFileOrDirectoryNotFound", UtilMisc.toMap("errorString", e.toString()), locale));
} catch (GenericEntityException e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "WebtoolsEomodelErrorGettingEntityNames", UtilMisc.toMap("errorString", e.toString()), locale));
}
}
Aggregations