Search in sources :

Example 11 with ModelFieldType

use of org.apache.ofbiz.entity.model.ModelFieldType 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 12 with ModelFieldType

use of org.apache.ofbiz.entity.model.ModelFieldType 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)

Example 13 with ModelFieldType

use of org.apache.ofbiz.entity.model.ModelFieldType in project ofbiz-framework by apache.

the class GenericWebEvent method updateGeneric.

/**
 * An HTTP WebEvent handler that updates a Generic entity
 *
 * @param request The HTTP request object for the current JSP or Servlet request.
 * @param response The HTTP response object for the current JSP or Servlet request.
 * @return Returns a String specifying the outcome state of the event. This is used to decide which event
 * to run next or which view to display. If null no event is run nor view displayed, allowing the event to
 * call a forward on a RequestDispatcher.
 */
public static String updateGeneric(HttpServletRequest request, HttpServletResponse response) {
    String entityName = request.getParameter("entityName");
    Locale locale = UtilHttp.getLocale(request);
    if (UtilValidate.isEmpty(entityName)) {
        String errMsg = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.entity_name_not_specified", locale) + ".";
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        Debug.logWarning("[GenericWebEvent.updateGeneric] The entityName was not specified, but is required.", module);
        return "error";
    }
    Security security = (Security) request.getAttribute("security");
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    if (security == null) {
        String errMsg = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.security_object_not_found", locale) + ".";
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        Debug.logWarning("[updateGeneric] The security object was not found in the request, please check the control servlet init.", module);
        return "error";
    }
    if (delegator == null) {
        String errMsg = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.delegator_object_not_found", locale) + ".";
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        Debug.logWarning("[updateGeneric] The delegator object was not found in the request, please check the control servlet init.", module);
        return "error";
    }
    ModelReader reader = delegator.getModelReader();
    ModelEntity entity = null;
    try {
        entity = reader.getModelEntity(entityName);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    String updateMode = request.getParameter("UPDATE_MODE");
    if (UtilValidate.isEmpty(updateMode)) {
        String errMsg = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.update_mode_not_specified", locale) + ".";
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        Debug.logWarning("[updateGeneric] Update Mode was not specified, but is required; entityName: " + entityName, module);
        return "error";
    }
    // check permissions before moving on...
    if (!security.hasEntityPermission("ENTITY_DATA", "_" + updateMode, request.getSession()) && !security.hasEntityPermission(entity.getPlainTableName(), "_" + updateMode, request.getSession())) {
        Map<String, String> messageMap = UtilMisc.toMap("updateMode", updateMode, "entityName", entity.getEntityName(), "entityPlainTableName", entity.getPlainTableName());
        String errMsg = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.not_sufficient_permissions_01", messageMap, locale);
        errMsg += UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.not_sufficient_permissions_02", messageMap, locale) + ".";
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        // not really successful, but error return through ERROR_MESSAGE, so quietly fail
        return "error";
    }
    GenericValue findByEntity = delegator.makeValue(entityName);
    // get the primary key parameters...
    String errMsgPk = "";
    Iterator<ModelField> pksIter = entity.getPksIterator();
    while (pksIter.hasNext()) {
        String errMsg = "";
        ModelField field = pksIter.next();
        ModelFieldType type = null;
        try {
            type = delegator.getEntityFieldType(entity, field.getType());
        } catch (GenericEntityException e) {
            Debug.logWarning(e, module);
            Map<String, String> messageMap = UtilMisc.toMap("fieldType", field.getType());
            errMsg += UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.fatal_error_param", messageMap, locale) + ".";
        }
        String fval = request.getParameter(field.getName());
        if (UtilValidate.isNotEmpty(fval)) {
            try {
                findByEntity.setString(field.getName(), fval);
            } catch (Exception e) {
                Map<String, String> messageMap = UtilMisc.toMap("fval", fval);
                errMsg = errMsg + "<li>" + field.getColName() + UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.conversion_failed", messageMap, locale) + type.getJavaType() + ".";
                Debug.logWarning("[updateGeneric] " + field.getColName() + " conversion failed: \"" + fval + "\" is not a valid " + type.getJavaType() + "; entityName: " + entityName, module);
            }
        }
    }
    if (errMsgPk.length() > 0) {
        request.setAttribute("_ERROR_MESSAGE_", errMsgPk);
        return "error";
    }
    // if this is a delete, do that before getting all of the non-pk parameters and validating them
    if ("DELETE".equals(updateMode)) {
        // Delete actual main entity last, just in case database is set up to do a cascading delete, caches won't get cleared
        try {
            delegator.removeByPrimaryKey(findByEntity.getPrimaryKey());
        } catch (GenericEntityException e) {
            String errMsg = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.delete_failed", locale) + ": " + e.toString();
            Debug.logWarning(e, errMsg, module);
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
        return "success";
    }
    // get the non-primary key parameters
    String errMsgNonPk = "";
    Iterator<ModelField> nopksIter = entity.getNopksIterator();
    while (nopksIter.hasNext()) {
        ModelField field = nopksIter.next();
        ModelFieldType type = null;
        try {
            type = delegator.getEntityFieldType(entity, field.getType());
        } catch (GenericEntityException e) {
            Debug.logWarning(e, module);
            Map<String, String> messageMap = UtilMisc.toMap("fieldType", field.getType());
            errMsgNonPk += UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.fatal_error_param", messageMap, locale) + ".";
        }
        String fval = request.getParameter(field.getName());
        if (UtilValidate.isNotEmpty(fval)) {
            try {
                findByEntity.setString(field.getName(), fval);
            } catch (Exception e) {
                Map<String, String> messageMap = UtilMisc.toMap("fval", fval);
                errMsgNonPk += field.getColName() + UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.conversion_failed", messageMap, locale) + type.getJavaType() + ".";
                Debug.logWarning("[updateGeneric] " + field.getColName() + " conversion failed: \"" + fval + "\" is not a valid " + type.getJavaType() + "; entityName: " + entityName, module);
            }
        } else {
            findByEntity.set(field.getName(), null);
        }
    }
    if (errMsgNonPk.length() > 0) {
        request.setAttribute("_ERROR_MESSAGE_", errMsgNonPk);
        return "error";
    }
    // if the updateMode is CREATE, check to see if an entity with the specified primary key already exists
    if ("CREATE".equals(updateMode)) {
        GenericValue tempEntity = null;
        try {
            tempEntity = EntityQuery.use(delegator).from(findByEntity.getEntityName()).where(findByEntity.getPrimaryKey()).queryOne();
        } catch (GenericEntityException e) {
            String errMsg = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.create_failed_by_check", locale) + ": " + e.toString();
            Debug.logWarning(e, errMsg, module);
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
        if (tempEntity != null) {
            Map<String, String> messageMap = UtilMisc.toMap("primaryKey", findByEntity.getPrimaryKey().toString());
            String errMsg = "[updateGeneric] " + entity.getEntityName() + UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.already_exists_pk", messageMap, locale) + ".";
            Debug.logWarning(errMsg, module);
        }
    }
    // Validate parameters...
    String errMsgParam = "";
    Iterator<ModelField> fieldIter = entity.getFieldsIterator();
    while (fieldIter.hasNext()) {
        ModelField field = fieldIter.next();
        for (String curValidate : field.getValidators()) {
            Class<?>[] paramTypes = new Class[] { String.class };
            Object[] params = new Object[] { findByEntity.get(field.getName()).toString() };
            String className = "org.apache.ofbiz.base.util.UtilValidate";
            String methodName = curValidate;
            if (curValidate.indexOf('.') > 0) {
                className = curValidate.substring(0, curValidate.lastIndexOf('.'));
                methodName = curValidate.substring(curValidate.lastIndexOf('.') + 1);
            }
            Class<?> valClass;
            try {
                ClassLoader loader = Thread.currentThread().getContextClassLoader();
                valClass = loader.loadClass(className);
            } catch (ClassNotFoundException cnfe) {
                Debug.logError("[updateGeneric] Could not find validation class: " + className + "; ignoring.", module);
                continue;
            }
            Method valMethod;
            try {
                valMethod = valClass.getMethod(methodName, paramTypes);
            } catch (NoSuchMethodException cnfe) {
                Debug.logError("[updateGeneric] Could not find validation method: " + methodName + " of class " + className + "; ignoring.", module);
                continue;
            }
            Boolean resultBool;
            try {
                resultBool = (Boolean) valMethod.invoke(null, params);
            } catch (Exception e) {
                Debug.logError("[updateGeneric] Could not access validation method: " + methodName + " of class " + className + "; returning true.", module);
                resultBool = Boolean.TRUE;
            }
            if (!resultBool.booleanValue()) {
                Field msgField;
                String message;
                try {
                    msgField = valClass.getField(curValidate + "Msg");
                    message = (String) msgField.get(null);
                } catch (Exception e) {
                    Debug.logError("[updateGeneric] Could not find validation message field: " + curValidate + "Msg of class " + className + "; returning generic validation failure message.", module);
                    message = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.validation_failed", locale) + ".";
                }
                errMsgParam += field.getColName() + " " + curValidate + " " + UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.failed", locale) + ": " + message;
                Debug.logWarning("[updateGeneric] " + field.getColName() + " " + curValidate + " failed: " + message, module);
            }
        }
    }
    if (errMsgParam.length() > 0) {
        errMsgParam = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.following_error_occurred", locale) + errMsgParam;
        request.setAttribute("_ERROR_MESSAGE_", errMsgParam);
        return "error";
    }
    if ("CREATE".equals(updateMode)) {
        try {
            delegator.create(findByEntity.getEntityName(), findByEntity.getAllFields());
        } catch (GenericEntityException e) {
            Map<String, String> messageMap = UtilMisc.toMap("entityName", entity.getEntityName());
            String errMsg = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.creation_param_failed", messageMap, locale) + ": " + findByEntity.toString() + ": " + e.toString();
            Debug.logWarning(e, errMsg, module);
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
    } else if ("UPDATE".equals(updateMode)) {
        GenericValue value = delegator.makeValue(findByEntity.getEntityName(), findByEntity.getAllFields());
        try {
            value.store();
        } catch (GenericEntityException e) {
            Map<String, String> messageMap = UtilMisc.toMap("entityName", entity.getEntityName());
            String errMsg = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.update_of_param_failed", messageMap, locale) + ": " + value.toString() + ": " + e.toString();
            Debug.logWarning(e, errMsg, module);
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
    } else {
        Map<String, String> messageMap = UtilMisc.toMap("updateMode", updateMode);
        String errMsg = UtilProperties.getMessage(GenericWebEvent.err_resource, "genericWebEvent.update_of_param_failed", messageMap, locale) + ".";
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        Debug.logWarning("updateGeneric: Update Mode specified (" + updateMode + ") was not valid for entity: " + findByEntity.toString(), module);
        return "error";
    }
    return "success";
}
Also used : Locale(java.util.Locale) Security(org.apache.ofbiz.security.Security) ModelField(org.apache.ofbiz.entity.model.ModelField) Field(java.lang.reflect.Field) ModelReader(org.apache.ofbiz.entity.model.ModelReader) ModelField(org.apache.ofbiz.entity.model.ModelField) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) GenericValue(org.apache.ofbiz.entity.GenericValue) Method(java.lang.reflect.Method) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ModelFieldType(org.apache.ofbiz.entity.model.ModelFieldType) Map(java.util.Map)

Aggregations

ModelFieldType (org.apache.ofbiz.entity.model.ModelFieldType)13 ModelField (org.apache.ofbiz.entity.model.ModelField)10 SQLException (java.sql.SQLException)8 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)8 ModelEntity (org.apache.ofbiz.entity.model.ModelEntity)7 ModelViewEntity (org.apache.ofbiz.entity.model.ModelViewEntity)6 Connection (java.sql.Connection)4 Statement (java.sql.Statement)4 Map (java.util.Map)3 GeneralException (org.apache.ofbiz.base.util.GeneralException)3 ModelRelation (org.apache.ofbiz.entity.model.ModelRelation)3 IOException (java.io.IOException)2 BigDecimal (java.math.BigDecimal)2 Blob (java.sql.Blob)2 HashMap (java.util.HashMap)2 LinkedList (java.util.LinkedList)2 Locale (java.util.Locale)2 TreeSet (java.util.TreeSet)2 SerialBlob (javax.sql.rowset.serial.SerialBlob)2 GenericModelException (org.apache.ofbiz.entity.GenericModelException)2