Search in sources :

Example 46 with ModelField

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, "&apos;");
                            break;
                        case '"':
                            value.replace(i, i + 1, "&quot;");
                            break;
                        case '&':
                            value.replace(i, i + 1, "&amp;");
                            break;
                        case '<':
                            value.replace(i, i + 1, "&lt;");
                            break;
                        case '>':
                            value.replace(i, i + 1, "&gt;");
                            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, "&apos;");
                            break;
                        case // left quote
                        0x13:
                            value.replace(i, i + 1, "&quot;");
                            break;
                        case // right quote
                        0x14:
                            value.replace(i, i + 1, "&quot;");
                            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(">");
    }
}
Also used : HashMap(java.util.HashMap) ModelField(org.apache.ofbiz.entity.model.ModelField) HashMap(java.util.HashMap) LocalizedMap(org.apache.ofbiz.base.util.collections.LocalizedMap) Map(java.util.Map) ModelKeyMap(org.apache.ofbiz.entity.model.ModelKeyMap) EntityFieldMap(org.apache.ofbiz.entity.condition.EntityFieldMap)

Example 47 with ModelField

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());
    }
}
Also used : ModelField(org.apache.ofbiz.entity.model.ModelField) ModelFieldType(org.apache.ofbiz.entity.model.ModelFieldType) BigDecimal(java.math.BigDecimal)

Example 48 with ModelField

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);
}
Also used : ModelField(org.apache.ofbiz.entity.model.ModelField)

Example 49 with ModelField

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);
    }
}
Also used : ModelField(org.apache.ofbiz.entity.model.ModelField) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ModelViewEntity(org.apache.ofbiz.entity.model.ModelViewEntity)

Example 50 with ModelField

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);
        }
    }
}
Also used : GenericModelException(org.apache.ofbiz.entity.GenericModelException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ModelField(org.apache.ofbiz.entity.model.ModelField) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ModelFieldType(org.apache.ofbiz.entity.model.ModelFieldType) Collection(java.util.Collection) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity)

Aggregations

ModelField (org.apache.ofbiz.entity.model.ModelField)55 ModelEntity (org.apache.ofbiz.entity.model.ModelEntity)28 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)16 LinkedList (java.util.LinkedList)14 ModelViewEntity (org.apache.ofbiz.entity.model.ModelViewEntity)13 HashMap (java.util.HashMap)10 GenericValue (org.apache.ofbiz.entity.GenericValue)10 ModelFieldType (org.apache.ofbiz.entity.model.ModelFieldType)10 ModelKeyMap (org.apache.ofbiz.entity.model.ModelKeyMap)10 Map (java.util.Map)8 SQLException (java.sql.SQLException)7 Locale (java.util.Locale)7 GenericModelException (org.apache.ofbiz.entity.GenericModelException)7 TreeSet (java.util.TreeSet)6 Delegator (org.apache.ofbiz.entity.Delegator)6 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)6 GeneralException (org.apache.ofbiz.base.util.GeneralException)5 ModelParam (org.apache.ofbiz.service.ModelParam)5 SQLProcessor (org.apache.ofbiz.entity.jdbc.SQLProcessor)4 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)4