use of org.apache.ofbiz.entity.model.ModelField in project ofbiz-framework by apache.
the class GenericEntity method writeXmlText.
/**
* Writes XML text with an attribute or CDATA element for each field of the entity
*@param writer A PrintWriter to write to
*@param prefix A prefix to put in front of the entity name in the tag name
*/
public void writeXmlText(PrintWriter writer, String prefix) {
int indent = 4;
StringBuilder indentStrBuf = new StringBuilder();
for (int i = 0; i < indent; i++) {
indentStrBuf.append(' ');
}
String indentString = indentStrBuf.toString();
if (prefix == null) {
prefix = "";
}
writer.print(indentString);
writer.print('<');
writer.print(prefix);
writer.print(this.getEntityName());
// write attributes immediately and if a CDATA element is needed, put those in a Map for now
Map<String, String> cdataMap = new HashMap<>();
Iterator<ModelField> modelFields = this.getModelEntity().getFieldsIterator();
while (modelFields.hasNext()) {
ModelField modelField = modelFields.next();
String name = modelField.getName();
String type = modelField.getType();
if (type != null && "blob".equals(type)) {
Object obj = get(name);
boolean b1 = obj instanceof byte[];
if (b1) {
byte[] binData = (byte[]) obj;
String strData = new String(Base64.base64Encode(binData), UtilIO.getUtf8());
cdataMap.put(name, strData);
} else {
Debug.logWarning("Field:" + name + " is not of type 'byte[]'. obj: " + obj, module);
}
} else {
String valueStr = this.getString(name);
if (valueStr != null) {
StringBuilder value = new StringBuilder(valueStr);
boolean needsCdata = false;
// check each character, if line-feed or carriage-return is found set needsCdata to true; also look for invalid characters
for (int i = 0; i < value.length(); i++) {
char curChar = value.charAt(i);
switch(curChar) {
case '\'':
value.replace(i, i + 1, "'");
break;
case '"':
value.replace(i, i + 1, """);
break;
case '&':
value.replace(i, i + 1, "&");
break;
case '<':
value.replace(i, i + 1, "<");
break;
case '>':
value.replace(i, i + 1, ">");
break;
case // newline, \n
0xA:
needsCdata = true;
break;
case // carriage return, \r
0xD:
needsCdata = true;
break;
case // tab
0x9:
// do nothing, just catch here so it doesn't get into the default
break;
case // elipses (...)
0x5:
value.replace(i, i + 1, "...");
break;
case // apostrophe
0x12:
value.replace(i, i + 1, "'");
break;
case // left quote
0x13:
value.replace(i, i + 1, """);
break;
case // right quote
0x14:
value.replace(i, i + 1, """);
break;
case // big(?) dash -
0x16:
value.replace(i, i + 1, "-");
break;
case // dash -
0x17:
value.replace(i, i + 1, "-");
break;
case // tm
0x19:
value.replace(i, i + 1, "tm");
break;
default:
if (curChar < 0x20) {
// if it is less that 0x20 at this point it is invalid because the only valid values < 0x20 are 0x9, 0xA, 0xD as caught above
Debug.logInfo("Removing invalid character [" + curChar + "] numeric value [" + (int) curChar + "] for field " + name + " of entity with PK: " + this.getPrimaryKey().toString(), module);
value.deleteCharAt(i);
} else if (curChar > 0x7F) {
// Replace each char which is out of the ASCII range with a XML entity
String replacement = "&#" + (int) curChar + ";";
if (Debug.verboseOn()) {
Debug.logVerbose("Entity: " + this.getEntityName() + ", PK: " + this.getPrimaryKey().toString() + " -> char [" + curChar + "] replaced with [" + replacement + "]", module);
}
value.replace(i, i + 1, replacement);
}
}
}
if (needsCdata) {
// use valueStr instead of the escaped value, not needed or wanted in a CDATA block
cdataMap.put(name, valueStr);
} else {
writer.print(' ');
writer.print(name);
writer.print("=\"");
// encode the value...
writer.print(value.toString());
writer.print("\"");
}
}
}
}
if (cdataMap.size() == 0) {
writer.println("/>");
} else {
writer.println('>');
for (Map.Entry<String, String> entry : cdataMap.entrySet()) {
writer.print(indentString);
writer.print(indentString);
writer.print('<');
writer.print(entry.getKey());
writer.print("><![CDATA[");
writer.print(entry.getValue());
writer.print("]]></");
writer.print(entry.getKey());
writer.println('>');
}
// don't forget to close the entity.
writer.print(indentString);
writer.print("</");
writer.print(this.getEntityName());
writer.println(">");
}
}
use of org.apache.ofbiz.entity.model.ModelField in project ofbiz-framework by apache.
the class GenericEntity method setString.
/**
* Sets the named field to the passed value, converting the value from a String to the corrent type using <code>Type.valueOf()</code>
* @param name The field name to set
* @param value The String value to convert and set
*/
public void setString(String name, String value) {
if (value == null) {
set(name, null);
return;
}
boolean isNullString = false;
if ("null".equals(value) || "[null-field]".equals(value)) {
// keep [null-field] but it'not used now
// count this as a null too, but only for numbers and stuff, not for Strings
isNullString = true;
}
ModelField field = getModelEntity().getField(name);
if (field == null) {
// this will get an error in the set() method...
set(name, value);
}
ModelFieldType type = null;
try {
if (field != null) {
type = getDelegator().getEntityFieldType(getModelEntity(), field.getType());
}
} catch (IllegalStateException | GenericEntityException e) {
Debug.logWarning(e, module);
}
if (type == null) {
throw new IllegalArgumentException("Type " + field.getType() + " not found");
}
String fieldType = type.getJavaType();
try {
switch(SqlJdbcUtil.getType(fieldType)) {
case 1:
set(name, value);
break;
case 2:
set(name, isNullString ? null : java.sql.Timestamp.valueOf(value));
break;
case 3:
set(name, isNullString ? null : java.sql.Time.valueOf(value));
break;
case 4:
set(name, isNullString ? null : java.sql.Date.valueOf(value));
break;
case 5:
set(name, isNullString ? null : Integer.valueOf(value));
break;
case 6:
set(name, isNullString ? null : Long.valueOf(value));
break;
case 7:
set(name, isNullString ? null : Float.valueOf(value));
break;
case 8:
set(name, isNullString ? null : Double.valueOf(value));
break;
case // BigDecimal
9:
set(name, isNullString ? null : new BigDecimal(value));
break;
case 10:
set(name, isNullString ? null : Boolean.valueOf(value));
break;
case // Object
11:
set(name, value);
break;
case // java.sql.Blob
12:
// TODO: any better way to handle Blob from String?
set(name, value);
break;
case // java.sql.Clob
13:
// TODO: any better way to handle Clob from String?
set(name, value);
break;
case // java.util.Date
14:
set(name, UtilDateTime.toDate(value));
break;
case // java.util.Collection
15:
// TODO: how to convert from String to Collection? ie what should the default behavior be?
set(name, value);
break;
}
} catch (GenericNotImplementedException ex) {
throw new IllegalArgumentException(ex.getMessage());
}
}
use of org.apache.ofbiz.entity.model.ModelField in project ofbiz-framework by apache.
the class EntityComparisonOperator method addSqlValue.
@Override
public void addSqlValue(StringBuilder sql, ModelEntity entity, List<EntityConditionParam> entityConditionParams, boolean compat, L lhs, R rhs, Datasource datasourceInfo) {
// if this is an IN operator and the rhs Object isEmpty, add "1=0" instead of the normal SQL. Note that "FALSE" does not work with all databases.
if (this.idInt == EntityOperator.ID_IN && UtilValidate.isEmpty(rhs)) {
sql.append("1=0");
return;
}
ModelField field;
if (lhs instanceof EntityConditionValue) {
EntityConditionValue ecv = (EntityConditionValue) lhs;
ecv.addSqlValue(sql, entity, entityConditionParams, false, datasourceInfo);
field = ecv.getModelField(entity);
} else if (compat && lhs instanceof String) {
field = getField(entity, (String) lhs);
if (field == null) {
sql.append(lhs);
} else {
sql.append(field.getColName());
}
} else {
addValue(sql, null, lhs, entityConditionParams);
field = null;
}
makeRHSWhereString(entity, entityConditionParams, sql, field, rhs, datasourceInfo);
}
use of org.apache.ofbiz.entity.model.ModelField in project ofbiz-framework by apache.
the class EntityConditionSubSelect method addSqlValue.
@Override
public void addSqlValue(StringBuilder sql, Map<String, String> tableAliases, ModelEntity parentModelEntity, List<EntityConditionParam> entityConditionParams, boolean includeTableNamePrefix, Datasource datasourceInfo) {
if (localModelEntity instanceof ModelViewEntity && datasourceInfo == null) {
throw new IllegalArgumentException("Call to EntityConditionSubSelect.addSqlValue with datasourceInfo=null which is not allowed because the local entity [" + this.localModelEntity.getEntityName() + "] is a view entity");
}
try {
// add select and where and such, based on local entity not on the main entity
ModelField localModelField = localModelEntity.getField(this.keyFieldName);
if (this.requireAll) {
sql.append(" ALL(");
} else {
sql.append(" ANY(");
}
sql.append("SELECT ");
sql.append(localModelField.getColName());
// FROM clause and when necessary the JOIN or LEFT JOIN clause(s) as well
sql.append(SqlJdbcUtil.makeFromClause(localModelEntity, null, datasourceInfo));
// WHERE clause
StringBuilder whereString = new StringBuilder();
String entityCondWhereString = "";
if (this.whereCond != null) {
entityCondWhereString = this.whereCond.makeWhereString(localModelEntity, entityConditionParams, datasourceInfo);
}
String viewClause = SqlJdbcUtil.makeViewWhereClause(localModelEntity, (datasourceInfo != null ? datasourceInfo.getJoinStyle() : null));
if (viewClause.length() > 0) {
if (entityCondWhereString.length() > 0) {
whereString.append("(");
whereString.append(entityCondWhereString);
whereString.append(") AND ");
}
whereString.append(viewClause);
} else {
whereString.append(entityCondWhereString);
}
if (whereString.length() > 0) {
sql.append(" WHERE ");
sql.append(whereString.toString());
}
sql.append(")");
} catch (GenericEntityException e) {
String errMsg = "Could not generate sub-select SQL: " + e.toString();
Debug.logError(e, errMsg, module);
}
}
use of org.apache.ofbiz.entity.model.ModelField in project ofbiz-framework by apache.
the class EntityExpr method checkRhsType.
public void checkRhsType(ModelEntity modelEntity, Delegator delegator) {
if (this.rhs == null || this.rhs == GenericEntity.NULL_FIELD || modelEntity == null) {
return;
}
Object value = this.rhs;
if (this.rhs instanceof EntityFunction<?>) {
value = UtilGenerics.<EntityFunction<?>>cast(this.rhs).getOriginalValue();
}
if (value instanceof Collection<?>) {
Collection<?> valueCol = UtilGenerics.cast(value);
if (valueCol.size() > 0) {
value = valueCol.iterator().next();
} else {
value = null;
}
}
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 = DelegatorFactory.getDelegator("default");
}
String fieldName = null;
ModelField curField;
if (this.lhs instanceof EntityFieldValue) {
EntityFieldValue efv = (EntityFieldValue) this.lhs;
fieldName = efv.getFieldName();
curField = efv.getModelField(modelEntity);
} else {
// nothing to check
return;
}
if (curField == null) {
throw new IllegalArgumentException("FieldName " + fieldName + " not found for entity: " + modelEntity.getEntityName());
}
ModelFieldType type = null;
try {
type = delegator.getEntityFieldType(modelEntity, curField.getType());
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
if (type == null) {
throw new IllegalArgumentException("Type " + curField.getType() + " not found for entity [" + modelEntity.getEntityName() + "]; probably because there is no datasource (helper) setup for the entity group that this entity is in: [" + delegator.getEntityGroupName(modelEntity.getEntityName()) + "]");
}
if (value instanceof EntityConditionSubSelect) {
ModelFieldType valueType = null;
try {
ModelEntity valueModelEntity = ((EntityConditionSubSelect) value).getModelEntity();
valueType = delegator.getEntityFieldType(valueModelEntity, valueModelEntity.getField(((EntityConditionSubSelect) value).getKeyFieldName()).getType());
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
if (valueType == null) {
throw new IllegalArgumentException("Type " + curField.getType() + " not found for entity [" + modelEntity.getEntityName() + "]; probably because there is no datasource (helper) setup for the entity group that this entity is in: [" + delegator.getEntityGroupName(modelEntity.getEntityName()) + "]");
}
// make sure the type of keyFieldName of EntityConditionSubSelect matches the field Java type
try {
if (!ObjectType.instanceOf(ObjectType.loadClass(valueType.getJavaType()), type.getJavaType())) {
String errMsg = "Warning using [" + value.getClass().getName() + "] and entity field [" + modelEntity.getEntityName() + "." + curField.getName() + "]. The Java type of keyFieldName : [" + valueType.getJavaType() + "] is not compatible with the Java type of the field [" + type.getJavaType() + "]";
// eventually we should do this, but for now we'll do a "soft" failure: throw new IllegalArgumentException(errMsg);
Debug.logWarning(new Exception("Location of database type warning"), "=-=-=-=-=-=-=-=-= Database type warning in EntityExpr =-=-=-=-=-=-=-=-= " + errMsg, module);
}
} catch (ClassNotFoundException e) {
String errMsg = "Warning using [" + value.getClass().getName() + "] and entity field [" + modelEntity.getEntityName() + "." + curField.getName() + "]. The Java type of keyFieldName : [" + valueType.getJavaType() + "] could not be found]";
// eventually we should do this, but for now we'll do a "soft" failure: throw new IllegalArgumentException(errMsg);
Debug.logWarning(e, "=-=-=-=-=-=-=-=-= Database type warning in EntityExpr =-=-=-=-=-=-=-=-= " + errMsg, module);
}
} else if (value instanceof EntityFieldValue) {
EntityFieldValue efv = (EntityFieldValue) this.lhs;
String rhsFieldName = efv.getFieldName();
ModelField rhsField = efv.getModelField(modelEntity);
if (rhsField == null) {
throw new IllegalArgumentException("FieldName " + rhsFieldName + " not found for entity: " + modelEntity.getEntityName());
}
ModelFieldType rhsType = null;
try {
rhsType = delegator.getEntityFieldType(modelEntity, rhsField.getType());
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
try {
if (!ObjectType.instanceOf(ObjectType.loadClass(rhsType.getJavaType()), type.getJavaType())) {
String errMsg = "Warning using [" + value.getClass().getName() + "] and entity field [" + modelEntity.getEntityName() + "." + curField.getName() + "]. The Java type [" + rhsType.getJavaType() + "] of rhsFieldName : [" + rhsFieldName + "] is not compatible with the Java type of the field [" + type.getJavaType() + "]";
// eventually we should do this, but for now we'll do a "soft" failure: throw new IllegalArgumentException(errMsg);
Debug.logWarning(new Exception("Location of database type warning"), "=-=-=-=-=-=-=-=-= Database type warning in EntityExpr =-=-=-=-=-=-=-=- " + errMsg, module);
}
} catch (ClassNotFoundException e) {
String errMsg = "Warning using [" + value.getClass().getName() + "] and entity field [" + modelEntity.getEntityName() + "." + curField.getName() + "]. The Java type [" + rhsType.getJavaType() + "] of rhsFieldName : [" + rhsFieldName + "] could not be found]";
// eventually we should do this, but for now we'll do a "soft" failure: throw new IllegalArgumentException(errMsg);
Debug.logWarning(e, "=-=-=-=-=-=-=-=-= Database type warning in EntityExpr =-=-=-=-=-=-=-=-= " + errMsg, module);
}
} else {
// make sure the type matches the field Java type
if (!ObjectType.instanceOf(value, type.getJavaType())) {
String errMsg = "In entity field [" + modelEntity.getEntityName() + "." + curField.getName() + "] set the value passed in [" + value.getClass().getName() + "] is not compatible with the Java type of the field [" + type.getJavaType() + "]";
// eventually we should do this, but for now we'll do a "soft" failure: throw new IllegalArgumentException(errMsg);
Debug.logWarning(new Exception("Location of database type warning"), "=-=-=-=-=-=-=-=-= Database type warning in EntityExpr =-=-=-=-=-=-=-=-= " + errMsg, module);
}
}
}
Aggregations