use of org.apache.ofbiz.entity.model.ModelField 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.ModelField in project ofbiz-framework by apache.
the class GenericEntity method isPrimaryKey.
public boolean isPrimaryKey(boolean requireValue) {
TreeSet<String> fieldKeys = new TreeSet<>(this.fields.keySet());
for (ModelField curPk : this.getModelEntity().getPkFieldsUnmodifiable()) {
String fieldName = curPk.getName();
if (requireValue) {
if (this.fields.get(fieldName) == null) {
return false;
}
} else {
if (!this.fields.containsKey(fieldName)) {
return false;
}
}
fieldKeys.remove(fieldName);
}
if (!fieldKeys.isEmpty()) {
return false;
}
return true;
}
use of org.apache.ofbiz.entity.model.ModelField in project ofbiz-framework by apache.
the class PrimaryKeyFinder method runFind.
public static GenericValue runFind(ModelEntity modelEntity, Map<String, Object> context, Delegator delegator, boolean useCache, boolean autoFieldMap, Map<FlexibleMapAccessor<Object>, Object> fieldMap, List<FlexibleStringExpander> selectFieldExpanderList) throws GeneralException {
// assemble the field map
Map<String, Object> entityContext = new HashMap<>();
if (autoFieldMap) {
// try a map called "parameters", try it first so values from here are overridden by values in the main context
Object parametersObj = context.get("parameters");
Boolean parametersObjExists = parametersObj != null && parametersObj instanceof Map<?, ?>;
// only need PK fields
Iterator<ModelField> iter = modelEntity.getPksIterator();
while (iter.hasNext()) {
ModelField curField = iter.next();
String fieldName = curField.getName();
Object fieldValue = null;
if (parametersObjExists) {
fieldValue = ((Map<?, ?>) parametersObj).get(fieldName);
}
if (context.containsKey(fieldName)) {
fieldValue = context.get(fieldName);
}
entityContext.put(fieldName, fieldValue);
}
}
EntityFinderUtil.expandFieldMapToContext(fieldMap, context, entityContext);
// then convert the types...
// need the timeZone and locale for conversion, so add here and remove after
entityContext.put("locale", context.get("locale"));
entityContext.put("timeZone", context.get("timeZone"));
modelEntity.convertFieldMapInPlace(entityContext, delegator);
entityContext.remove("locale");
entityContext.remove("timeZone");
// get the list of fieldsToSelect from selectFieldExpanderList
Set<String> fieldsToSelect = EntityFinderUtil.makeFieldsToSelect(selectFieldExpanderList, context);
// if fieldsToSelect != null and useCacheBool is true, throw an error
if (fieldsToSelect != null && useCache) {
throw new IllegalArgumentException("Error in entity-one definition, cannot specify select-field elements when use-cache is set to true");
}
try {
GenericValue valueOut = null;
GenericPK entityPK = delegator.makePK(modelEntity.getEntityName(), entityContext);
// make sure we have a full primary key, if any field is null then just log a warning and return null instead of blowing up
if (entityPK.containsPrimaryKey(true)) {
if (useCache) {
valueOut = EntityQuery.use(delegator).from(entityPK.getEntityName()).where(entityPK).cache(true).queryOne();
} else {
if (fieldsToSelect != null) {
valueOut = delegator.findByPrimaryKeyPartial(entityPK, fieldsToSelect);
} else {
valueOut = EntityQuery.use(delegator).from(entityPK.getEntityName()).where(entityPK).cache(false).queryOne();
}
}
} else {
if (Debug.infoOn()) {
Debug.logInfo("Returning null because found incomplete primary key in find: " + entityPK, module);
}
}
return valueOut;
} catch (GenericEntityException e) {
String errMsg = "Error finding entity value by primary key with entity-one: " + e.toString();
Debug.logError(e, errMsg, module);
throw new GeneralException(errMsg, e);
}
}
use of org.apache.ofbiz.entity.model.ModelField in project ofbiz-framework by apache.
the class ModelServiceReader method createAutoAttrDef.
private void createAutoAttrDef(Element autoElement, ModelService service) {
// get the entity name; first from the auto-attributes then from the service def
String entityName = UtilXml.checkEmpty(autoElement.getAttribute("entity-name"));
if (UtilValidate.isEmpty(entityName)) {
entityName = service.defaultEntityName;
if (UtilValidate.isEmpty(entityName)) {
Debug.logWarning("Auto-Attribute does not specify an entity-name; not default-entity on service definition", module);
}
}
// get the include type 'pk|nonpk|all'
String includeType = UtilXml.checkEmpty(autoElement.getAttribute("include"));
boolean includePk = "pk".equals(includeType) || "all".equals(includeType);
boolean includeNonPk = "nonpk".equals(includeType) || "all".equals(includeType);
if (delegator == null) {
Debug.logWarning("Cannot use auto-attribute fields with a null delegator", module);
}
if (delegator != null && entityName != null) {
Map<String, ModelParam> modelParamMap = new LinkedHashMap<>();
try {
ModelEntity entity = delegator.getModelEntity(entityName);
if (entity == null) {
throw new GeneralException("Could not find entity with name [" + entityName + "]");
}
Iterator<ModelField> fieldsIter = entity.getFieldsIterator();
while (fieldsIter.hasNext()) {
ModelField field = fieldsIter.next();
if ((!field.getIsAutoCreatedInternal()) && ((field.getIsPk() && includePk) || (!field.getIsPk() && includeNonPk))) {
ModelFieldType fieldType = delegator.getEntityFieldType(entity, field.getType());
if (fieldType == null) {
throw new GeneralException("Null field type from delegator for entity [" + entityName + "]");
}
ModelParam param = new ModelParam();
param.entityName = entityName;
param.fieldName = field.getName();
param.name = field.getName();
param.type = fieldType.getJavaType();
// this is a special case where we use something different in the service layer than we do in the entity/data layer
if ("java.sql.Blob".equals(param.type)) {
param.type = "java.nio.ByteBuffer";
}
param.mode = UtilXml.checkEmpty(autoElement.getAttribute("mode")).intern();
// default to true
param.optional = "true".equalsIgnoreCase(autoElement.getAttribute("optional"));
// default to false
param.formDisplay = !"false".equalsIgnoreCase(autoElement.getAttribute("form-display"));
// default to none
param.allowHtml = UtilXml.checkEmpty(autoElement.getAttribute("allow-html"), "none").intern();
modelParamMap.put(field.getName(), param);
}
}
// get the excludes list; and remove those from the map
List<? extends Element> excludes = UtilXml.childElementList(autoElement, "exclude");
if (excludes != null) {
for (Element exclude : excludes) {
modelParamMap.remove(UtilXml.checkEmpty(exclude.getAttribute("field-name")));
}
}
// now add in all the remaining params
for (ModelParam thisParam : modelParamMap.values()) {
service.addParam(thisParam);
}
} catch (GenericEntityException e) {
Debug.logError(e, "Problem loading auto-attributes [" + entityName + "] for " + service.name, module);
} catch (GeneralException e) {
Debug.logError(e, "Cannot load auto-attributes : " + e.getMessage() + " for " + service.name, module);
}
}
}
use of org.apache.ofbiz.entity.model.ModelField in project ofbiz-framework by apache.
the class WebToolsServices method getEntityRefData.
/**
* Get entity reference data. Returns the number of entities in
* <code>numberOfEntities</code> and a List of Maps -
* <code>packagesList</code>.
* Each Map contains:<br>
* <ul><li><code>packageName</code> - the entity package name</li>
* <li><code>entitiesList</code> - a list of Maps:
* <ul>
* <li><code>entityName</code></li>
* <li><code>helperName</code></li>
* <li><code>groupName</code></li>
* <li><code>plainTableName</code></li>
* <li><code>title</code></li>
* <li><code>description</code></li>
* <!-- <li><code>location</code></li> -->
* <li><code>javaNameList</code> - list of Maps:
* <ul>
* <li><code>isPk</code></li>
* <li><code>name</code></li>
* <li><code>colName</code></li>
* <li><code>description</code></li>
* <li><code>type</code></li>
* <li><code>javaType</code></li>
* <li><code>sqlType</code></li>
* </ul>
* </li>
* <li><code>relationsList</code> - list of Maps:
* <ul>
* <li><code>title</code></li>
* <!-- <li><code>description</code></li> -->
* <li><code>relEntity</code></li>
* <li><code>fkName</code></li>
* <li><code>type</code></li>
* <li><code>length</code></li>
* <li><code>keysList</code> - list of Maps:
* <ul>
* <li><code>row</code></li>
* <li><code>fieldName</code></li>
* <li><code>relFieldName</code></li>
* </ul>
* </li>
* </ul>
* </li>
* <li><code>indexList</code> - list of Maps:
* <ul>
* <li><code>name</code></li>
* <!-- <li><code>description</code></li> -->
* <li><code>fieldNameList</code> - list of Strings</li>
* </ul>
* </li>
* </ul>
* </li></ul>
*/
public static Map<String, Object> getEntityRefData(DispatchContext dctx, Map<String, ? extends Object> context) {
Delegator delegator = dctx.getDelegator();
Locale locale = (Locale) context.get("locale");
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Map<String, Object> resultMap = ServiceUtil.returnSuccess();
ModelReader reader = delegator.getModelReader();
Map<String, TreeSet<String>> entitiesByPackage = new HashMap<String, TreeSet<String>>();
Set<String> packageNames = new TreeSet<String>();
Set<String> tableNames = new TreeSet<String>();
// put the entityNames TreeSets in a HashMap by packageName
try {
Collection<String> ec = reader.getEntityNames();
resultMap.put("numberOfEntities", ec.size());
for (String eName : ec) {
ModelEntity ent = reader.getModelEntity(eName);
// make sure the table name is in the list of all table names, if not null
if (UtilValidate.isNotEmpty(ent.getPlainTableName())) {
tableNames.add(ent.getPlainTableName());
}
TreeSet<String> entities = entitiesByPackage.get(ent.getPackageName());
if (entities == null) {
entities = new TreeSet<String>();
entitiesByPackage.put(ent.getPackageName(), entities);
packageNames.add(ent.getPackageName());
}
entities.add(eName);
}
} catch (GenericEntityException e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityImportErrorRetrievingEntityNames", locale) + e.getMessage());
}
String search = (String) context.get("search");
List<Map<String, Object>> packagesList = new LinkedList<Map<String, Object>>();
try {
for (String pName : packageNames) {
Map<String, Object> packageMap = new HashMap<String, Object>();
TreeSet<String> entities = entitiesByPackage.get(pName);
List<Map<String, Object>> entitiesList = new LinkedList<Map<String, Object>>();
for (String entityName : entities) {
Map<String, Object> entityMap = new HashMap<String, Object>();
String helperName = delegator.getEntityHelperName(entityName);
String groupName = delegator.getEntityGroupName(entityName);
if (search == null || entityName.toLowerCase().indexOf(search.toLowerCase()) != -1) {
ModelEntity entity = reader.getModelEntity(entityName);
ResourceBundle bundle = null;
if (UtilValidate.isNotEmpty(entity.getDefaultResourceName())) {
try {
bundle = UtilResourceBundle.getBundle(entity.getDefaultResourceName(), locale, loader);
} catch (Exception exception) {
Debug.logInfo(exception.getMessage(), module);
}
}
String entityDescription = null;
if (bundle != null) {
try {
entityDescription = bundle.getString("EntityDescription." + entity.getEntityName());
} catch (Exception exception) {
}
}
if (UtilValidate.isEmpty(entityDescription)) {
entityDescription = entity.getDescription();
}
// fields list
List<Map<String, Object>> javaNameList = new LinkedList<Map<String, Object>>();
for (Iterator<ModelField> f = entity.getFieldsIterator(); f.hasNext(); ) {
Map<String, Object> javaNameMap = new HashMap<String, Object>();
ModelField field = f.next();
ModelFieldType type = delegator.getEntityFieldType(entity, field.getType());
javaNameMap.put("isPk", field.getIsPk());
javaNameMap.put("name", field.getName());
javaNameMap.put("colName", field.getColName());
String fieldDescription = null;
if (bundle != null) {
try {
fieldDescription = bundle.getString("FieldDescription." + entity.getEntityName() + "." + field.getName());
} catch (Exception exception) {
}
}
if (UtilValidate.isEmpty(fieldDescription)) {
fieldDescription = field.getDescription();
}
if (UtilValidate.isEmpty(fieldDescription) && bundle != null) {
try {
fieldDescription = bundle.getString("FieldDescription." + field.getName());
} catch (Exception exception) {
}
}
if (UtilValidate.isEmpty(fieldDescription)) {
fieldDescription = ModelUtil.javaNameToDbName(field.getName()).toLowerCase();
fieldDescription = ModelUtil.upperFirstChar(fieldDescription.replace('_', ' '));
}
javaNameMap.put("description", fieldDescription);
javaNameMap.put("type", (field.getType()) != null ? field.getType() : null);
javaNameMap.put("javaType", (field.getType() != null && type != null) ? type.getJavaType() : "Undefined");
javaNameMap.put("sqlType", (type != null && type.getSqlType() != null) ? type.getSqlType() : "Undefined");
javaNameMap.put("encrypted", field.getEncryptMethod().isEncrypted());
javaNameMap.put("encryptMethod", field.getEncryptMethod());
javaNameList.add(javaNameMap);
}
// relations list
List<Map<String, Object>> relationsList = new LinkedList<Map<String, Object>>();
for (int r = 0; r < entity.getRelationsSize(); r++) {
Map<String, Object> relationMap = new HashMap<String, Object>();
ModelRelation relation = entity.getRelation(r);
List<Map<String, Object>> keysList = new LinkedList<Map<String, Object>>();
int row = 1;
for (ModelKeyMap keyMap : relation.getKeyMaps()) {
Map<String, Object> keysMap = new HashMap<String, Object>();
String fieldName = null;
String relFieldName = null;
if (keyMap.getFieldName().equals(keyMap.getRelFieldName())) {
fieldName = keyMap.getFieldName();
relFieldName = "aa";
} else {
fieldName = keyMap.getFieldName();
relFieldName = keyMap.getRelFieldName();
}
keysMap.put("row", row++);
keysMap.put("fieldName", fieldName);
keysMap.put("relFieldName", relFieldName);
keysList.add(keysMap);
}
relationMap.put("title", relation.getTitle());
relationMap.put("description", relation.getDescription());
relationMap.put("relEntity", relation.getRelEntityName());
relationMap.put("fkName", relation.getFkName());
relationMap.put("type", relation.getType());
relationMap.put("length", relation.getType().length());
relationMap.put("keysList", keysList);
relationsList.add(relationMap);
}
// index list
List<Map<String, Object>> indexList = new LinkedList<Map<String, Object>>();
for (int r = 0; r < entity.getIndexesSize(); r++) {
List<String> fieldNameList = new LinkedList<String>();
ModelIndex index = entity.getIndex(r);
for (Iterator<ModelIndex.Field> fieldIterator = index.getFields().iterator(); fieldIterator.hasNext(); ) {
fieldNameList.add(fieldIterator.next().getFieldName());
}
Map<String, Object> indexMap = new HashMap<String, Object>();
indexMap.put("name", index.getName());
indexMap.put("description", index.getDescription());
indexMap.put("fieldNameList", fieldNameList);
indexList.add(indexMap);
}
entityMap.put("entityName", entityName);
entityMap.put("helperName", helperName);
entityMap.put("groupName", groupName);
entityMap.put("plainTableName", entity.getPlainTableName());
entityMap.put("title", entity.getTitle());
entityMap.put("description", entityDescription);
String entityLocation = entity.getLocation();
entityLocation = entityLocation.replaceFirst(System.getProperty("ofbiz.home") + "/", "");
entityMap.put("location", entityLocation);
entityMap.put("javaNameList", javaNameList);
entityMap.put("relationsList", relationsList);
entityMap.put("indexList", indexList);
entitiesList.add(entityMap);
}
}
packageMap.put("packageName", pName);
packageMap.put("entitiesList", entitiesList);
packagesList.add(packageMap);
}
} catch (GenericEntityException e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityImportErrorRetrievingEntityNames", locale) + e.getMessage());
}
resultMap.put("packagesList", packagesList);
return resultMap;
}
Aggregations