use of org.apache.ofbiz.entity.model.ModelField in project ofbiz-framework by apache.
the class FindServices method createConditionList.
/**
* Parses input parameters and returns an <code>EntityCondition</code> list.
*
* @param parameters
* @param fieldList
* @param queryStringMap
* @param delegator
* @param context
* @return returns an EntityCondition list
*/
public static List<EntityCondition> createConditionList(Map<String, ? extends Object> parameters, List<ModelField> fieldList, Map<String, Object> queryStringMap, Delegator delegator, Map<String, ?> context) {
Set<String> processed = new LinkedHashSet<>();
Set<String> keys = new LinkedHashSet<>();
Map<String, ModelField> fieldMap = new LinkedHashMap<>();
/**
* When inputFields contains several xxxx_grp, yyyy_grp ... values,
* Corresponding conditions will grouped by an {@link EntityOperator.AND} then all added to final
* condition grouped by an {@link EntityOperator.OR}
* That will allow union of search criteria, instead of default intersection.
*/
Map<String, List<EntityCondition>> savedGroups = new LinkedHashMap();
for (ModelField modelField : fieldList) {
fieldMap.put(modelField.getName(), modelField);
}
List<EntityCondition> result = new LinkedList<>();
for (Map.Entry<String, ? extends Object> entry : parameters.entrySet()) {
String currentGroup = null;
String parameterName = entry.getKey();
if (processed.contains(parameterName)) {
continue;
}
keys.clear();
String fieldName = parameterName;
Object fieldValue = null;
String operation = null;
boolean ignoreCase = false;
if (parameterName.endsWith("_ic") || parameterName.endsWith("_op")) {
fieldName = parameterName.substring(0, parameterName.length() - 3);
} else if (parameterName.endsWith("_value")) {
fieldName = parameterName.substring(0, parameterName.length() - 6);
}
String key = fieldName.concat("_grp");
if (parameters.containsKey(key)) {
if (parameters.containsKey(key)) {
keys.add(key);
}
currentGroup = (String) parameters.get(key);
}
key = fieldName.concat("_ic");
if (parameters.containsKey(key)) {
keys.add(key);
ignoreCase = "Y".equals(parameters.get(key));
}
key = fieldName.concat("_op");
if (parameters.containsKey(key)) {
keys.add(key);
operation = (String) parameters.get(key);
}
key = fieldName.concat("_value");
if (parameters.containsKey(key)) {
keys.add(key);
fieldValue = parameters.get(key);
}
if (fieldName.endsWith("_fld0") || fieldName.endsWith("_fld1")) {
if (parameters.containsKey(fieldName)) {
keys.add(fieldName);
}
fieldName = fieldName.substring(0, fieldName.length() - 5);
}
if (parameters.containsKey(fieldName)) {
keys.add(fieldName);
}
processed.addAll(keys);
ModelField modelField = fieldMap.get(fieldName);
if (modelField == null) {
continue;
}
if (fieldValue == null) {
fieldValue = parameters.get(fieldName);
}
if (ObjectType.isEmpty(fieldValue) && !"empty".equals(operation)) {
continue;
}
if (UtilValidate.isNotEmpty(currentGroup)) {
List<EntityCondition> groupedConditions = new LinkedList<>();
if (savedGroups.get(currentGroup) != null) {
groupedConditions.addAll(savedGroups.get(currentGroup));
}
groupedConditions.add(createSingleCondition(modelField, operation, fieldValue, ignoreCase, delegator, context));
savedGroups.put(currentGroup, groupedConditions);
} else {
result.add(createSingleCondition(modelField, operation, fieldValue, ignoreCase, delegator, context));
}
for (String mapKey : keys) {
queryStringMap.put(mapKey, parameters.get(mapKey));
}
}
// Add OR-grouped conditions
List<EntityCondition> orConditions = new LinkedList<>();
for (String groupedConditions : savedGroups.keySet()) {
orConditions.add(EntityCondition.makeCondition(savedGroups.get(groupedConditions)));
}
if (orConditions.size() > 0)
result.add(EntityCondition.makeCondition(orConditions, EntityOperator.OR));
return result;
}
use of org.apache.ofbiz.entity.model.ModelField in project ofbiz-framework by apache.
the class EntityListIterator method currentGenericValue.
/**
* NOTE: Calling this method does return the current value, but so does calling next() or previous()
* So calling one of those AND this method will cause the value to be created twice.
*/
public GenericValue currentGenericValue() throws GenericEntityException {
if (closed)
throw new GenericResultSetClosedException("This EntityListIterator has been closed, this operation cannot be performed");
GenericValue value = GenericValue.create(modelEntity);
value.setDelegator(this.delegator);
for (int j = 0; j < selectFields.size(); j++) {
ModelField curField = selectFields.get(j);
SqlJdbcUtil.getValue(resultSet, j + 1, curField, value, modelFieldTypeReader);
}
value.synchronizedWithDatasource();
this.haveMadeValue = true;
return value;
}
use of org.apache.ofbiz.entity.model.ModelField in project ofbiz-framework by apache.
the class EntitySaxReader method endElement.
public void endElement(String namespaceURI, String localName, String fullNameString) throws SAXException {
if (Debug.verboseOn())
Debug.logVerbose("endElement: localName=" + localName + ", fullName=" + fullNameString + ", numberRead=" + numberRead, module);
if ("entity-engine-xml".equals(fullNameString)) {
return;
}
if ("entity-engine-transform-xml".equals(fullNameString)) {
// transform file & parse it, then return
URL templateUrl = null;
try {
templateUrl = FlexibleLocation.resolveLocation(templatePath.toString());
} catch (MalformedURLException e) {
throw new SAXException("Could not find transform template with resource path [" + templatePath + "]; error was: " + e.toString());
}
if (templateUrl == null) {
throw new SAXException("Could not find transform template with resource path: " + templatePath);
} else {
try {
BufferedReader templateReader = new BufferedReader(new InputStreamReader(templateUrl.openStream(), UtilIO.getUtf8()));
StringWriter outWriter = new StringWriter();
Configuration config = FreeMarkerWorker.newConfiguration();
config.setObjectWrapper(FreeMarkerWorker.getDefaultOfbizWrapper());
config.setSetting("datetime_format", "yyyy-MM-dd HH:mm:ss.SSS");
Template template = new Template("FMImportFilter", templateReader, config);
NodeModel nodeModel = NodeModel.wrap(this.rootNodeForTemplate);
Map<String, Object> context = new HashMap<String, Object>();
TemplateHashModel staticModels = FreeMarkerWorker.getDefaultOfbizWrapper().getStaticModels();
context.put("Static", staticModels);
context.put("doc", nodeModel);
template.process(context, outWriter);
String s = outWriter.toString();
if (Debug.verboseOn())
Debug.logVerbose("transformed xml: " + s, module);
EntitySaxReader reader = new EntitySaxReader(delegator);
reader.setUseTryInsertMethod(this.useTryInsertMethod);
try {
reader.setTransactionTimeout(this.transactionTimeout);
} catch (GenericTransactionException e1) {
Debug.logWarning("couldn't set tx timeout, hopefully shouldn't be a big deal", module);
}
numberRead += reader.parse(s);
} catch (TemplateException | IOException e) {
throw new SAXException("Error storing value", e);
}
}
return;
}
if (isParseForTemplate) {
this.currentNodeForTemplate = this.currentNodeForTemplate.getParentNode();
return;
}
// Test if end action tag, set action to default
if (actionTags.contains(fullNameString)) {
setAction(Action.CREATE_UPDATE);
return;
}
if (currentValue != null) {
if (currentFieldName != null) {
if (UtilValidate.isNotEmpty(currentFieldValue)) {
if (currentValue.getModelEntity().isField(currentFieldName.toString())) {
ModelEntity modelEntity = currentValue.getModelEntity();
ModelField modelField = modelEntity.getField(currentFieldName.toString());
String type = modelField.getType();
if (type != null && "blob".equals(type)) {
byte[] binData = Base64.base64Decode((new String(currentFieldValue)).getBytes());
currentValue.setBytes(currentFieldName.toString(), binData);
} else {
currentValue.setString(currentFieldName.toString(), new String(currentFieldValue));
}
} else {
Debug.logWarning("Ignoring invalid field name [" + currentFieldName + "] found for the entity: " + currentValue.getEntityName() + " with value=" + currentFieldValue, module);
}
currentFieldValue = null;
}
currentFieldName = null;
} else {
// before we write currentValue check to see if PK is there, if not and it is one field, generate it from a sequence using the entity name
if (!currentValue.containsPrimaryKey()) {
if (currentValue.getModelEntity().getPksSize() == 1) {
ModelField modelField = currentValue.getModelEntity().getOnlyPk();
String newSeq = delegator.getNextSeqId(currentValue.getEntityName());
currentValue.setString(modelField.getName(), newSeq);
} else {
throw new SAXException("Cannot store value with incomplete primary key with more than 1 primary key field: " + currentValue);
}
}
try {
boolean exist = true;
boolean skip = false;
// It's necessary to check also for specific action CREATE and DELETE to ensure it's OK
if (Action.CREATE == currentAction || Action.DELETE == currentAction || Debug.verboseOn()) {
GenericHelper helper = delegator.getEntityHelper(currentValue.getEntityName());
if (currentValue.containsPrimaryKey()) {
try {
helper.findByPrimaryKey(currentValue.getPrimaryKey());
} catch (GenericEntityNotFoundException e) {
exist = false;
}
}
if (Action.CREATE == currentAction && exist) {
skip = true;
} else if (Action.DELETE == currentAction && !exist) {
skip = true;
}
}
if (!skip) {
if (this.useTryInsertMethod && !this.checkDataOnly) {
if (Action.DELETE == currentAction) {
currentValue.remove();
} else {
currentValue.create();
}
} else {
if (Action.DELETE == currentAction) {
valuesToDelete.add(currentValue);
if (valuesToDelete.size() >= valuesPerWrite) {
delegator.removeAll(valuesToDelete);
valuesToDelete.clear();
}
} else {
valuesToWrite.add(currentValue);
if (valuesToWrite.size() >= valuesPerWrite) {
writeValues(valuesToWrite);
valuesToWrite.clear();
}
}
}
}
numberRead++;
if (Debug.verboseOn())
countValue(skip, exist);
if ((numberRead % valuesPerMessage) == 0) {
Debug.logImportant("Another " + valuesPerMessage + " values imported: now up to " + numberRead, module);
}
currentValue = null;
} catch (GenericEntityException e) {
String errMsg = "Error performing action " + currentAction;
Debug.logError(e, errMsg, module);
throw new SAXException(errMsg, e);
}
}
}
}
use of org.apache.ofbiz.entity.model.ModelField in project ofbiz-framework by apache.
the class EntityTestSuite method testModels.
public void testModels() throws Exception {
ModelEntity modelEntity = delegator.getModelEntity("TestingType");
assertNotNull("TestingType entity model not null", modelEntity);
ModelField modelField = modelEntity.getField("description");
assertNotNull("TestingType.description field model not null", modelField);
modelField = ModelField.create(modelEntity, null, "newDesc", modelField.getType(), "NEW_DESC", null, null, false, false, false, false, false, null);
modelEntity.addField(modelField);
modelField = modelEntity.getField("newDesc");
assertNotNull("TestingType.newDesc field model not null", modelField);
modelEntity.removeField("newDesc");
modelField = modelEntity.getField("newDesc");
assertNull("TestingType.newDesc field model is null", modelField);
}
use of org.apache.ofbiz.entity.model.ModelField in project ofbiz-framework by apache.
the class SqlJdbcUtil method makeFromClause.
/**
* Makes the FROM clause and when necessary the JOIN clause(s) as well
*/
public static String makeFromClause(ModelEntity modelEntity, ModelFieldTypeReader modelFieldTypeReader, Datasource datasourceInfo) throws GenericEntityException {
StringBuilder sql = new StringBuilder(" FROM ");
if (modelEntity instanceof ModelViewEntity) {
ModelViewEntity modelViewEntity = (ModelViewEntity) modelEntity;
if ("ansi".equals(datasourceInfo.getJoinStyle()) || "ansi-no-parenthesis".equals(datasourceInfo.getJoinStyle())) {
boolean useParenthesis = true;
if ("ansi-no-parenthesis".equals(datasourceInfo.getJoinStyle())) {
useParenthesis = false;
}
// FROM clause: in this case will be a bunch of joins that correspond with the view-links
// BIG NOTE on the JOIN clauses: the order of joins is determined by the order of the
// view-links; for more flexible order we'll have to figure something else out and
// extend the DTD for the nested view-link elements or something
// At this point it is assumed that in each view-link the left hand alias will
// either be the first alias in the series or will already be in a previous
// view-link and already be in the big join; SO keep a set of all aliases
// in the join so far and if the left entity alias isn't there yet, and this
// isn't the first one, throw an exception
Set<String> joinedAliasSet = new TreeSet<String>();
// TODO: at view-link read time make sure they are ordered properly so that each
// left hand alias after the first view-link has already been linked before
StringBuilder openParens = null;
if (useParenthesis)
openParens = new StringBuilder();
StringBuilder restOfStatement = new StringBuilder();
for (int i = 0; i < modelViewEntity.getViewLinksSize(); i++) {
// don't put starting parenthesis
if (i > 0 && useParenthesis)
openParens.append('(');
ModelViewEntity.ModelViewLink viewLink = modelViewEntity.getViewLink(i);
ModelEntity linkEntity = modelViewEntity.getMemberModelEntity(viewLink.getEntityAlias());
ModelEntity relLinkEntity = modelViewEntity.getMemberModelEntity(viewLink.getRelEntityAlias());
if (i == 0) {
// this is the first referenced member alias, so keep track of it for future use...
restOfStatement.append(makeViewTable(linkEntity, modelFieldTypeReader, datasourceInfo));
// another possible one that some dbs might need, but not sure of any yet: restOfStatement.append(" AS ");
restOfStatement.append(" ");
restOfStatement.append(viewLink.getEntityAlias());
joinedAliasSet.add(viewLink.getEntityAlias());
} else {
// make sure the left entity alias is already in the join...
if (!joinedAliasSet.contains(viewLink.getEntityAlias())) {
throw new GenericModelException("Tried to link the " + viewLink.getEntityAlias() + " alias to the " + viewLink.getRelEntityAlias() + " alias of the " + modelViewEntity.getEntityName() + " view-entity, but it is not the first view-link and has not been included in a previous view-link. In other words, the left/main alias isn't connected to the rest of the member-entities yet.");
}
}
// now put the rel (right) entity alias into the set that is in the join
joinedAliasSet.add(viewLink.getRelEntityAlias());
if (viewLink.isRelOptional()) {
restOfStatement.append(" LEFT OUTER JOIN ");
} else {
restOfStatement.append(" INNER JOIN ");
}
restOfStatement.append(makeViewTable(relLinkEntity, modelFieldTypeReader, datasourceInfo));
// another possible one that some dbs might need, but not sure of any yet: restOfStatement.append(" AS ");
restOfStatement.append(" ");
restOfStatement.append(viewLink.getRelEntityAlias());
restOfStatement.append(" ON ");
StringBuilder condBuffer = new StringBuilder();
for (int j = 0; j < viewLink.getKeyMapsSize(); j++) {
ModelKeyMap keyMap = viewLink.getKeyMap(j);
ModelField linkField = linkEntity.getField(keyMap.getFieldName());
if (linkField == null) {
throw new GenericModelException("Invalid field name in view-link key-map for the " + viewLink.getEntityAlias() + " and the " + viewLink.getRelEntityAlias() + " member-entities of the " + modelViewEntity.getEntityName() + " view-entity; the field [" + keyMap.getFieldName() + "] does not exist on the [" + linkEntity.getEntityName() + "] entity.");
}
ModelField relLinkField = relLinkEntity.getField(keyMap.getRelFieldName());
if (relLinkField == null) {
throw new GenericModelException("Invalid related field name in view-link key-map for the " + viewLink.getEntityAlias() + " and the " + viewLink.getRelEntityAlias() + " member-entities of the " + modelViewEntity.getEntityName() + " view-entity; the field [" + keyMap.getRelFieldName() + "] does not exist on the [" + relLinkEntity.getEntityName() + "] entity.");
}
if (condBuffer.length() > 0) {
condBuffer.append(" AND ");
}
condBuffer.append(viewLink.getEntityAlias());
condBuffer.append(".");
condBuffer.append(linkField.getColName());
condBuffer.append(" = ");
condBuffer.append(viewLink.getRelEntityAlias());
condBuffer.append(".");
condBuffer.append(relLinkField.getColName());
}
if (condBuffer.length() == 0) {
throw new GenericModelException("No view-link/join key-maps found for the " + viewLink.getEntityAlias() + " and the " + viewLink.getRelEntityAlias() + " member-entities of the " + modelViewEntity.getEntityName() + " view-entity.");
}
ModelViewEntity.ViewEntityCondition viewEntityCondition = viewLink.getViewEntityCondition();
if (viewEntityCondition != null) {
EntityCondition whereCondition = viewEntityCondition.getWhereCondition(modelFieldTypeReader, null);
condBuffer.append(" AND ");
condBuffer.append(whereCondition.makeWhereString(modelEntity, null, datasourceInfo));
}
restOfStatement.append(condBuffer.toString());
// don't put ending parenthesis
if (i < (modelViewEntity.getViewLinksSize() - 1) && useParenthesis)
restOfStatement.append(')');
}
if (useParenthesis)
sql.append(openParens.toString());
sql.append(restOfStatement.toString());
// handle tables not included in view-link
boolean fromEmpty = restOfStatement.length() == 0;
for (String aliasName : modelViewEntity.getMemberModelMemberEntities().keySet()) {
ModelEntity fromEntity = modelViewEntity.getMemberModelEntity(aliasName);
if (!joinedAliasSet.contains(aliasName)) {
if (!fromEmpty)
sql.append(", ");
fromEmpty = false;
sql.append(makeViewTable(fromEntity, modelFieldTypeReader, datasourceInfo));
sql.append(" ");
sql.append(aliasName);
}
}
} else if ("theta-oracle".equals(datasourceInfo.getJoinStyle()) || "theta-mssql".equals(datasourceInfo.getJoinStyle())) {
// FROM clause
Iterator<String> meIter = modelViewEntity.getMemberModelMemberEntities().keySet().iterator();
while (meIter.hasNext()) {
String aliasName = meIter.next();
ModelEntity fromEntity = modelViewEntity.getMemberModelEntity(aliasName);
sql.append(makeViewTable(fromEntity, modelFieldTypeReader, datasourceInfo));
sql.append(" ");
sql.append(aliasName);
if (meIter.hasNext())
sql.append(", ");
}
// JOIN clause(s): none needed, all the work done in the where clause for theta-oracle
} else {
throw new GenericModelException("The join-style " + datasourceInfo.getJoinStyle() + " is not yet supported");
}
} else {
sql.append(modelEntity.getTableName(datasourceInfo));
}
return sql.toString();
}
Aggregations