use of org.apache.ofbiz.entity.model.ModelEntity in project ofbiz-framework by apache.
the class SqlJdbcUtil method getValue.
public static void getValue(ResultSet rs, int ind, ModelField curField, GenericEntity entity, ModelFieldTypeReader modelFieldTypeReader) throws GenericEntityException {
ModelFieldType mft = modelFieldTypeReader.getModelFieldType(curField.getType());
if (mft == null) {
throw new GenericModelException("definition fieldType " + curField.getType() + " not found, cannot getValue for field " + entity.getEntityName() + "." + curField.getName() + ".");
}
ModelEntity model = entity.getModelEntity();
String encryptionKeyName = entity.getEntityName();
if (curField.getEncryptMethod().isEncrypted() && model instanceof ModelViewEntity) {
ModelViewEntity modelView = (ModelViewEntity) model;
encryptionKeyName = modelView.getAliasedEntity(modelView.getAlias(curField.getName()).getEntityAlias(), entity.getDelegator().getModelReader()).getEntityName();
}
// ----- Try out the new handler code -----
JdbcValueHandler<?> handler = mft.getJdbcValueHandler();
if (handler != null) {
try {
Object jdbcValue = handler.getValue(rs, ind);
if (jdbcValue instanceof String && curField.getEncryptMethod().isEncrypted()) {
jdbcValue = entity.getDelegator().decryptFieldValue(encryptionKeyName, curField.getEncryptMethod(), (String) jdbcValue);
}
entity.dangerousSetNoCheckButFast(curField, jdbcValue);
return;
} catch (Exception e) {
Debug.logError(e, module);
}
} else {
Debug.logWarning("JdbcValueHandler not found for java-type " + mft.getJavaType() + ", falling back on switch statement. Entity = " + curField.getModelEntity().getEntityName() + ", field = " + curField.getName() + ".", module);
}
// ------------------------------------------
String fieldType = mft.getJavaType();
try {
// checking to see if the object is null is really only necessary for the numbers
int typeValue = getType(fieldType);
ResultSetMetaData rsmd = rs.getMetaData();
int colType = rsmd.getColumnType(ind);
if (typeValue <= 4 || typeValue >= 11) {
switch(typeValue) {
case 1:
if (java.sql.Types.CLOB == colType) {
// Debug.logInfo("For field " + curField.getName() + " of entity " + entity.getEntityName() + " getString is a CLOB, trying getCharacterStream", module);
// if the String is empty, try to get a text input stream, this is required for some databases for larger fields, like CLOBs
Clob valueClob = rs.getClob(ind);
Reader valueReader = null;
if (valueClob != null) {
valueReader = valueClob.getCharacterStream();
}
// Reader valueReader = rs.getCharacterStream(ind);
if (valueReader != null) {
char[] inCharBuffer = new char[CHAR_BUFFER_SIZE];
StringBuilder strBuf = new StringBuilder();
int charsRead = 0;
try {
while ((charsRead = valueReader.read(inCharBuffer, 0, CHAR_BUFFER_SIZE)) > 0) {
strBuf.append(inCharBuffer, 0, charsRead);
}
valueReader.close();
} catch (IOException e) {
throw new GenericEntityException("Error reading long character stream for field " + curField.getName() + " of entity " + entity.getEntityName(), e);
}
entity.dangerousSetNoCheckButFast(curField, strBuf.toString());
} else {
entity.dangerousSetNoCheckButFast(curField, null);
}
} else {
String value = rs.getString(ind);
if (curField.getEncryptMethod().isEncrypted()) {
value = (String) entity.getDelegator().decryptFieldValue(encryptionKeyName, curField.getEncryptMethod(), value);
}
entity.dangerousSetNoCheckButFast(curField, value);
}
break;
case 2:
entity.dangerousSetNoCheckButFast(curField, rs.getTimestamp(ind));
break;
case 3:
entity.dangerousSetNoCheckButFast(curField, rs.getTime(ind));
break;
case 4:
entity.dangerousSetNoCheckButFast(curField, rs.getDate(ind));
break;
case 11:
Object obj = null;
byte[] originalBytes = rs.getBytes(ind);
obj = deserializeField(originalBytes, ind, curField);
if (obj != null) {
entity.dangerousSetNoCheckButFast(curField, obj);
} else {
entity.dangerousSetNoCheckButFast(curField, originalBytes);
}
break;
case 12:
Object originalObject;
byte[] fieldBytes;
try {
Blob theBlob = rs.getBlob(ind);
fieldBytes = theBlob != null ? theBlob.getBytes(1, (int) theBlob.length()) : null;
originalObject = theBlob;
} catch (SQLException e) {
// for backward compatibility if getBlob didn't work try getBytes
fieldBytes = rs.getBytes(ind);
originalObject = fieldBytes;
}
if (originalObject != null) {
// for backward compatibility, check to see if there is a serialized object and if so return that
Object blobObject = deserializeField(fieldBytes, ind, curField);
if (blobObject != null) {
entity.dangerousSetNoCheckButFast(curField, blobObject);
} else {
if (originalObject instanceof Blob) {
// NOTE using SerialBlob here instead of the Blob from the database to make sure we can pass it around, serialize it, etc
entity.dangerousSetNoCheckButFast(curField, new SerialBlob((Blob) originalObject));
} else {
entity.dangerousSetNoCheckButFast(curField, originalObject);
}
}
}
break;
case 13:
entity.dangerousSetNoCheckButFast(curField, new SerialClob(rs.getClob(ind)));
break;
case 14:
case 15:
entity.dangerousSetNoCheckButFast(curField, rs.getObject(ind));
break;
}
} else {
switch(typeValue) {
case 5:
int intValue = rs.getInt(ind);
if (rs.wasNull()) {
entity.dangerousSetNoCheckButFast(curField, null);
} else {
entity.dangerousSetNoCheckButFast(curField, Integer.valueOf(intValue));
}
break;
case 6:
long longValue = rs.getLong(ind);
if (rs.wasNull()) {
entity.dangerousSetNoCheckButFast(curField, null);
} else {
entity.dangerousSetNoCheckButFast(curField, Long.valueOf(longValue));
}
break;
case 7:
float floatValue = rs.getFloat(ind);
if (rs.wasNull()) {
entity.dangerousSetNoCheckButFast(curField, null);
} else {
entity.dangerousSetNoCheckButFast(curField, Float.valueOf(floatValue));
}
break;
case 8:
double doubleValue = rs.getDouble(ind);
if (rs.wasNull()) {
entity.dangerousSetNoCheckButFast(curField, null);
} else {
entity.dangerousSetNoCheckButFast(curField, Double.valueOf(doubleValue));
}
break;
case 9:
BigDecimal bigDecimalValue = rs.getBigDecimal(ind);
if (rs.wasNull()) {
entity.dangerousSetNoCheckButFast(curField, null);
} else {
entity.dangerousSetNoCheckButFast(curField, bigDecimalValue);
}
break;
case 10:
boolean booleanValue = rs.getBoolean(ind);
if (rs.wasNull()) {
entity.dangerousSetNoCheckButFast(curField, null);
} else {
entity.dangerousSetNoCheckButFast(curField, Boolean.valueOf(booleanValue));
}
break;
}
}
} catch (SQLException sqle) {
throw new GenericDataSourceException("SQL Exception while getting value : " + curField.getName() + " [" + curField.getColName() + "] (" + ind + ")", sqle);
}
}
use of org.apache.ofbiz.entity.model.ModelEntity in project ofbiz-framework by apache.
the class ListFinder method runFind.
@Override
public void runFind(Map<String, Object> context, Delegator delegator) throws GeneralException {
String entityName = this.entityNameExdr.expandString(context);
String useCacheStr = this.useCacheStrExdr.expandString(context);
String filterByDateStr = this.filterByDateStrExdr.expandString(context);
String distinctStr = this.distinctStrExdr.expandString(context);
String delegatorName = this.delegatorNameExdr.expandString(context);
ModelEntity modelEntity = delegator.getModelEntity(entityName);
String resultSetTypeString = this.resultSetTypeExdr.expandString(context);
if (modelEntity == null) {
throw new IllegalArgumentException("In find entity by " + label + " could not find definition for entity with name [" + entityName + "].");
}
boolean useCache = "true".equals(useCacheStr);
boolean filterByDate = "true".equals(filterByDateStr);
boolean distinct = "true".equals(distinctStr);
int resultSetType = ResultSet.TYPE_SCROLL_INSENSITIVE;
if ("forward".equals(resultSetTypeString)) {
resultSetType = ResultSet.TYPE_FORWARD_ONLY;
}
if (UtilValidate.isNotEmpty(delegatorName)) {
delegator = DelegatorFactory.getDelegator(delegatorName);
}
EntityCondition whereEntityCondition = getWhereEntityCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity));
EntityCondition havingEntityCondition = getHavingEntityCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity));
if (useCache) {
// if useCache == true && outputHandler instanceof UseIterator, throw exception; not a valid combination
if (outputHandler instanceof UseIterator) {
Debug.logWarning("In find entity by " + label + " cannot have use-cache set to true " + label + " select use-iterator for the output type. Using cache and ignoring use-iterator setting.", module);
outputHandler = new GetAll();
}
if (distinct) {
throw new IllegalArgumentException("In find entity by " + label + " cannot have use-cache set to true " + label + " set distinct to true.");
}
if (havingEntityCondition != null) {
throw new IllegalArgumentException("In find entity by " + label + " cannot have use-cache set to true and specify a having-condition-list (can only use a where condition with condition-expr or condition-list).");
}
}
// 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 query by " + label + " definition, cannot specify select-field elements when use-cache is set to true");
}
// get the list of orderByFields from orderByExpanderList
List<String> orderByFields = EntityFinderUtil.makeOrderByFieldList(this.orderByExpanderList, context);
try {
// if filterByDate, do a date filter on the results based on the now-timestamp
if (filterByDate && !useCache) {
EntityCondition filterByDateCondition = EntityUtil.getFilterByDateExpr();
if (whereEntityCondition != null) {
whereEntityCondition = EntityCondition.makeCondition(UtilMisc.toList(whereEntityCondition, filterByDateCondition));
} else {
whereEntityCondition = filterByDateCondition;
}
}
if (useCache) {
List<GenericValue> results = delegator.findList(entityName, whereEntityCondition, fieldsToSelect, orderByFields, null, true);
if (filterByDate) {
results = EntityUtil.filterByDate(results);
}
this.outputHandler.handleOutput(results, context, listAcsr);
} else {
boolean useTransaction = true;
if (this.outputHandler instanceof UseIterator && !TransactionUtil.isTransactionInPlace()) {
Exception newE = new Exception("Stack Trace");
Debug.logError(newE, "ERROR: Cannot do a by " + label + " find that returns an EntityListIterator with no transaction in place. Wrap this call in a transaction.", module);
useTransaction = false;
}
EntityFindOptions options = new EntityFindOptions();
options.setDistinct(distinct);
options.setResultSetType(resultSetType);
if (outputHandler instanceof LimitRange) {
LimitRange limitRange = (LimitRange) outputHandler;
int start = limitRange.getStart(context);
int size = limitRange.getSize(context);
options.setMaxRows(start + size);
} else if (outputHandler instanceof LimitView) {
LimitView limitView = (LimitView) outputHandler;
int index = limitView.getIndex(context);
int size = limitView.getSize(context);
options.setMaxRows(size * (index + 1));
}
boolean beganTransaction = false;
try {
if (useTransaction) {
beganTransaction = TransactionUtil.begin();
}
EntityListIterator eli = delegator.find(entityName, whereEntityCondition, havingEntityCondition, fieldsToSelect, orderByFields, options);
this.outputHandler.handleOutput(eli, context, listAcsr);
// NOTE: the eli EntityListIterator is not closed here. It SHOULD be closed later after the returned list will be used (eg see EntityAnd.getChildren() in ModelTree.java)
} catch (GenericEntityException e) {
String errMsg = "Failure in by " + label + " find operation, rolling back transaction";
Debug.logError(e, errMsg, module);
try {
// only rollback the transaction if we started one...
TransactionUtil.rollback(beganTransaction, errMsg, e);
} catch (GenericEntityException e2) {
Debug.logError(e2, "Could not rollback transaction: " + e2.toString(), module);
}
// after rolling back, rethrow the exception
throw e;
} finally {
// only commit the transaction if we started one... this will throw an exception if it fails
TransactionUtil.commit(beganTransaction);
}
}
} catch (GenericEntityException e) {
String errMsg = "Error doing find by " + label + ": " + e.toString();
Debug.logError(e, module);
throw new GeneralException(errMsg, e);
}
}
use of org.apache.ofbiz.entity.model.ModelEntity in project ofbiz-framework by apache.
the class LoginWorker method doBasicLogin.
public static void doBasicLogin(GenericValue userLogin, HttpServletRequest request) {
HttpSession session = request.getSession();
session.setAttribute("userLogin", userLogin);
String javaScriptEnabled = null;
try {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
Map<String, Object> result = dispatcher.runSync("getUserPreference", UtilMisc.toMap("userPrefTypeId", "javaScriptEnabled", "userPrefGroupTypeId", "GLOBAL_PREFERENCES", "userLogin", userLogin));
javaScriptEnabled = (String) result.get("userPrefValue");
} catch (GenericServiceException e) {
Debug.logError(e, "Error getting user preference", module);
}
session.setAttribute("javaScriptEnabled", Boolean.valueOf("Y".equals(javaScriptEnabled)));
// init theme from user preference, clean the current visualTheme value in session and restart the resolution
UtilHttp.setVisualTheme(session, null);
UtilHttp.setVisualTheme(session, ThemeFactory.resolveVisualTheme(request));
ModelEntity modelUserLogin = userLogin.getModelEntity();
if (modelUserLogin.isField("partyId")) {
// if partyId is a field, then we should have these relations defined
try {
GenericValue person = userLogin.getRelatedOne("Person", false);
GenericValue partyGroup = userLogin.getRelatedOne("PartyGroup", false);
if (person != null)
session.setAttribute("person", person);
if (partyGroup != null)
session.setAttribute("partyGroup", partyGroup);
} catch (GenericEntityException e) {
Debug.logError(e, "Error getting person/partyGroup info for session, ignoring...", module);
}
}
// let the visit know who the user is
VisitHandler.setUserLogin(session, userLogin, false);
}
use of org.apache.ofbiz.entity.model.ModelEntity in project ofbiz-framework by apache.
the class LoginWorker method autoLoginCheck.
private static String autoLoginCheck(Delegator delegator, HttpSession session, String autoUserLoginId) {
if (autoUserLoginId != null) {
if (Debug.infoOn()) {
Debug.logInfo("Running autoLogin check.", module);
}
try {
GenericValue autoUserLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", autoUserLoginId).queryOne();
GenericValue person = null;
GenericValue group = null;
if (autoUserLogin != null) {
session.setAttribute("autoUserLogin", autoUserLogin);
ModelEntity modelUserLogin = autoUserLogin.getModelEntity();
if (modelUserLogin.isField("partyId")) {
person = EntityQuery.use(delegator).from("Person").where("partyId", autoUserLogin.getString("partyId")).queryOne();
group = EntityQuery.use(delegator).from("PartyGroup").where("partyId", autoUserLogin.getString("partyId")).queryOne();
}
}
if (person != null) {
session.setAttribute("autoName", person.getString("firstName") + " " + person.getString("lastName"));
} else if (group != null) {
session.setAttribute("autoName", group.getString("groupName"));
}
} catch (GenericEntityException e) {
Debug.logError(e, "Cannot get autoUserLogin information: " + e.getMessage(), module);
}
}
return "success";
}
use of org.apache.ofbiz.entity.model.ModelEntity in project ofbiz-framework by apache.
the class EntityAutoEngine method runSync.
/**
* @see org.apache.ofbiz.service.engine.GenericEngine#runSync(java.lang.String, org.apache.ofbiz.service.ModelService, java.util.Map)
*/
@Override
public Map<String, Object> runSync(String localName, ModelService modelService, Map<String, Object> parameters) throws GenericServiceException {
// static java service methods should be: public Map<String, Object> methodName(DispatchContext dctx, Map<String, Object> context)
DispatchContext dctx = dispatcher.getLocalContext(localName);
Locale locale = (Locale) parameters.get("locale");
Map<String, Object> result = ServiceUtil.returnSuccess();
// check the package and method names
if (modelService.invoke == null || !availableInvokeActionNames.contains(modelService.invoke)) {
throw new GenericServiceException("In Service [" + modelService.name + "] the invoke value must be create, update, or delete for entity-auto engine");
}
if (UtilValidate.isEmpty(modelService.defaultEntityName)) {
throw new GenericServiceException("In Service [" + modelService.name + "] you must specify a default-entity-name for entity-auto engine");
}
ModelEntity modelEntity = dctx.getDelegator().getModelEntity(modelService.defaultEntityName);
if (modelEntity == null) {
throw new GenericServiceException("In Service [" + modelService.name + "] the specified default-entity-name [" + modelService.defaultEntityName + "] is not valid");
}
try {
boolean allPksInOnly = true;
List<String> pkFieldNameOutOnly = null;
/* Check for each pk if it's :
* 1. part IN
* 2. or part IN and OUT, but without value but present on parameters map
* Help the engine to determinate the operation to realize for a create call or validate that
* any pk is present for update/delete call.
*/
for (ModelField pkField : modelEntity.getPkFieldsUnmodifiable()) {
ModelParam pkParam = modelService.getParam(pkField.getName());
boolean pkValueInParameters = pkParam.isIn() && UtilValidate.isNotEmpty(parameters.get(pkParam.getFieldName()));
if (pkParam.isOut() && !pkValueInParameters) {
if (pkFieldNameOutOnly == null) {
pkFieldNameOutOnly = new LinkedList<>();
allPksInOnly = false;
}
pkFieldNameOutOnly.add(pkField.getName());
}
}
switch(modelService.invoke) {
case "create":
result = invokeCreate(dctx, parameters, modelService, modelEntity, allPksInOnly, pkFieldNameOutOnly);
break;
case "update":
result = invokeUpdate(dctx, parameters, modelService, modelEntity, allPksInOnly);
break;
case "delete":
result = invokeDelete(dctx, parameters, modelService, modelEntity, allPksInOnly);
break;
case "expire":
result = invokeExpire(dctx, parameters, modelService, modelEntity, allPksInOnly);
if (ServiceUtil.isSuccess(result)) {
result = invokeUpdate(dctx, parameters, modelService, modelEntity, allPksInOnly);
}
break;
default:
break;
}
GenericValue crudValue = (GenericValue) result.get("crudValue");
if (crudValue != null) {
result.remove("crudValue");
result.putAll(modelService.makeValid(crudValue, ModelService.OUT_PARAM));
}
} catch (GeneralException e) {
Debug.logError(e, "Error doing entity-auto operation for entity [" + modelEntity.getEntityName() + "] in service [" + modelService.name + "]: " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ServiceEntityAutoOperation", UtilMisc.toMap("entityName", modelEntity.getEntityName(), "serviceName", modelService.name, "errorString", e.toString()), locale));
}
result.put(ModelService.SUCCESS_MESSAGE, ServiceUtil.makeSuccessMessage(result, "", "", "", ""));
return result;
}
Aggregations