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);
}
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);
}
}
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;
}
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);
}
}
}
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);
}
}
Aggregations