Search in sources :

Example 26 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class GenericEntity method set.

/**
 * Sets the named field to the passed value. If value is null, it is only
 *  set if the setIfNull parameter is true. This is useful because an update
 *  will only set values that are included in the HashMap and will store null
 *  values in the HashMap to the datastore. If a value is not in the HashMap,
 *  it will be left unmodified in the datastore.
 * @param name The field name to set
 * @param value The value to set
 * @param setIfNull Specifies whether or not to set the value if it is null
 */
public Object set(String name, Object value, boolean setIfNull) {
    assertIsMutable();
    ModelField modelField = getModelEntity().getField(name);
    if (modelField == null) {
        throw new IllegalArgumentException("[GenericEntity.set] \"" + name + "\" is not a field of " + entityName + ", must be one of: " + getModelEntity().fieldNameString());
    }
    if (value != null || setIfNull) {
        ModelFieldType type = null;
        try {
            type = getDelegator().getEntityFieldType(getModelEntity(), modelField.getType());
        } catch (IllegalStateException | GenericEntityException e) {
            Debug.logWarning(e, module);
        }
        if (type == null) {
            throw new IllegalArgumentException("Type " + modelField.getType() + " not found for entity [" + this.getEntityName() + "]; probably because there is no datasource (helper) setup for the entity group that this entity is in: [" + this.getDelegator().getEntityGroupName(this.getEntityName()) + "]");
        }
        if (value instanceof Boolean) {
            // if this is a Boolean check to see if we should convert from an indicator or just leave as is
            try {
                int fieldType = SqlJdbcUtil.getType(type.getJavaType());
                if (fieldType != 10) {
                    value = ((Boolean) value).booleanValue() ? "Y" : "N";
                }
            } catch (GenericNotImplementedException e) {
                throw new IllegalArgumentException(e.getMessage());
            }
        } else if (value != null && !(value instanceof NULL)) {
            // make sure the type matches the field Java type
            if (value instanceof TimeDuration) {
                try {
                    value = ObjectType.simpleTypeConvert(value, type.getJavaType(), null, null);
                } catch (GeneralException e) {
                    Debug.logError(e, module);
                }
            } else if ((value instanceof String) && "byte[]".equals(type.getJavaType())) {
                value = ((String) value).getBytes(UtilIO.getUtf8());
            }
            if (!ObjectType.instanceOf(value, type.getJavaType())) {
                if (!("java.sql.Blob".equals(type.getJavaType()) && (value instanceof byte[] || ObjectType.instanceOf(value, ByteBuffer.class)))) {
                    String errMsg = "In entity field [" + this.getEntityName() + "." + name + "] 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 GenericEntity.set =-=-=-=-=-=-=-=-= " + errMsg, module);
                }
            }
        }
        Object old = fields.put(name, value);
        generateHashCode = true;
        this.setChanged();
        this.notifyObservers(name);
        return old;
    }
    return fields.get(name);
}
Also used : GeneralException(org.apache.ofbiz.base.util.GeneralException) SQLException(java.sql.SQLException) MissingResourceException(java.util.MissingResourceException) GeneralException(org.apache.ofbiz.base.util.GeneralException) ModelField(org.apache.ofbiz.entity.model.ModelField) ModelFieldType(org.apache.ofbiz.entity.model.ModelFieldType) TimeDuration(org.apache.ofbiz.base.util.TimeDuration)

Example 27 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException 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);
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GenericPK(org.apache.ofbiz.entity.GenericPK) GeneralException(org.apache.ofbiz.base.util.GeneralException) HashMap(java.util.HashMap) ModelField(org.apache.ofbiz.entity.model.ModelField) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Example 28 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class EntityDataServices method readEntityFile.

private static int readEntityFile(File file, String delimiter, Delegator delegator) throws IOException, GeneralException {
    String entityName = file.getName().substring(0, file.getName().lastIndexOf('.'));
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), UtilIO.getUtf8()));
    String[] header = readEntityHeader(file, delimiter, reader);
    // Debug.logInfo("Opened data file [" + file.getName() + "] now running...", module);
    GeneralException exception = null;
    String line = null;
    int lineNumber = 1;
    while ((line = reader.readLine()) != null) {
        // process the record
        String[] fields = line.split(delimiter);
        // Debug.logInfo("Split record", module);
        if (fields.length < 1) {
            exception = new GeneralException("Illegal number of fields [" + file.getName() + " / " + lineNumber);
            break;
        }
        GenericValue newValue = makeGenericValue(delegator, entityName, header, fields);
        // Debug.logInfo("Made value object", module);
        newValue = delegator.createOrStore(newValue);
        if (lineNumber % 500 == 0 || lineNumber == 1) {
            Debug.logInfo("Records Stored [" + file.getName() + "]: " + lineNumber, module);
        // Debug.logInfo("Last record : " + newValue, module);
        }
        lineNumber++;
    }
    reader.close();
    // now that we closed the reader; throw the exception
    if (exception != null) {
        throw exception;
    }
    return lineNumber;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) FileInputStream(java.io.FileInputStream)

Example 29 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException 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);
        }
    }
}
Also used : GeneralException(org.apache.ofbiz.base.util.GeneralException) Element(org.w3c.dom.Element) LinkedHashMap(java.util.LinkedHashMap) ModelField(org.apache.ofbiz.entity.model.ModelField) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ModelFieldType(org.apache.ofbiz.entity.model.ModelFieldType) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity)

Example 30 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class ValidateMethod method exec.

@Override
public void exec(Map<String, Object> inMap, Map<String, Object> results, List<Object> messages, Locale locale, ClassLoader loader) {
    Object obj = inMap.get(fieldName);
    String fieldValue = null;
    try {
        fieldValue = (String) ObjectType.simpleTypeConvert(obj, "String", null, locale);
    } catch (GeneralException e) {
        messages.add("Could not convert field value for comparison: " + e.getMessage());
        return;
    }
    if (loader == null) {
        loader = Thread.currentThread().getContextClassLoader();
    }
    Class<?>[] paramTypes = new Class<?>[] { String.class };
    Object[] params = new Object[] { fieldValue };
    Class<?> valClass;
    try {
        valClass = loader.loadClass(className);
    } catch (ClassNotFoundException cnfe) {
        String msg = "Could not find validation class: " + className;
        messages.add(msg);
        Debug.logError("[ValidateMethod.exec] " + msg, module);
        return;
    }
    Method valMethod;
    try {
        valMethod = valClass.getMethod(methodName, paramTypes);
    } catch (NoSuchMethodException cnfe) {
        String msg = "Could not find validation method: " + methodName + " of class " + className;
        messages.add(msg);
        Debug.logError("[ValidateMethod.exec] " + msg, module);
        return;
    }
    Boolean resultBool = Boolean.FALSE;
    try {
        resultBool = (Boolean) valMethod.invoke(null, params);
    } catch (Exception e) {
        String msg = "Error in validation method " + methodName + " of class " + className + ": " + e.getMessage();
        messages.add(msg);
        Debug.logError("[ValidateMethod.exec] " + msg, module);
        return;
    }
    if (!resultBool.booleanValue()) {
        addMessage(messages, loader, locale);
    }
}
Also used : GeneralException(org.apache.ofbiz.base.util.GeneralException) Method(java.lang.reflect.Method) GeneralException(org.apache.ofbiz.base.util.GeneralException)

Aggregations

GeneralException (org.apache.ofbiz.base.util.GeneralException)216 GenericValue (org.apache.ofbiz.entity.GenericValue)133 Delegator (org.apache.ofbiz.entity.Delegator)101 Locale (java.util.Locale)81 HashMap (java.util.HashMap)71 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)68 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)68 IOException (java.io.IOException)65 BigDecimal (java.math.BigDecimal)55 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)54 Writer (java.io.Writer)29 LinkedList (java.util.LinkedList)29 Map (java.util.Map)29 Timestamp (java.sql.Timestamp)26 StringWriter (java.io.StringWriter)19 Environment (freemarker.core.Environment)15 HttpServletRequest (javax.servlet.http.HttpServletRequest)14 ShoppingCart (org.apache.ofbiz.order.shoppingcart.ShoppingCart)14 HttpSession (javax.servlet.http.HttpSession)13 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)13