use of org.apache.ofbiz.entity.model.ModelViewEntity in project ofbiz-framework by apache.
the class SqlJdbcUtil method makeViewWhereClause.
public static String makeViewWhereClause(ModelEntity modelEntity, String joinStyle) throws GenericEntityException {
if (modelEntity instanceof ModelViewEntity) {
StringBuilder whereString = new StringBuilder();
ModelViewEntity modelViewEntity = (ModelViewEntity) modelEntity;
if ("ansi".equals(joinStyle) || "ansi-no-parenthesis".equals(joinStyle)) {
// nothing to do here, all done in the JOIN clauses
} else if ("theta-oracle".equals(joinStyle) || "theta-mssql".equals(joinStyle)) {
boolean isOracleStyle = "theta-oracle".equals(joinStyle);
boolean isMssqlStyle = "theta-mssql".equals(joinStyle);
for (int i = 0; i < modelViewEntity.getViewLinksSize(); i++) {
ModelViewEntity.ModelViewLink viewLink = modelViewEntity.getViewLink(i);
ModelEntity linkEntity = modelViewEntity.getMemberModelEntity(viewLink.getEntityAlias());
ModelEntity relLinkEntity = modelViewEntity.getMemberModelEntity(viewLink.getRelEntityAlias());
if (linkEntity == null) {
throw new GenericEntityException("Link entity not found with alias: " + viewLink.getEntityAlias() + " for entity: " + modelViewEntity.getEntityName());
}
if (relLinkEntity == null) {
throw new GenericEntityException("Rel-Link entity not found with alias: " + viewLink.getRelEntityAlias() + " for entity: " + modelViewEntity.getEntityName());
}
for (int j = 0; j < viewLink.getKeyMapsSize(); j++) {
ModelKeyMap keyMap = viewLink.getKeyMap(j);
ModelField linkField = linkEntity.getField(keyMap.getFieldName());
ModelField relLinkField = relLinkEntity.getField(keyMap.getRelFieldName());
if (whereString.length() > 0) {
whereString.append(" AND ");
}
whereString.append(viewLink.getEntityAlias());
whereString.append(".");
whereString.append(linkField.getColName());
// if (isOracleStyle && linkMemberEntity.getOptional()) whereString.append(" (+) ");
if (isMssqlStyle && viewLink.isRelOptional())
whereString.append("*");
whereString.append("=");
// if (isMssqlStyle && linkMemberEntity.getOptional()) whereString.append("*");
if (isOracleStyle && viewLink.isRelOptional())
whereString.append(" (+) ");
whereString.append(viewLink.getRelEntityAlias());
whereString.append(".");
whereString.append(relLinkField.getColName());
}
}
} else {
throw new GenericModelException("The join-style " + joinStyle + " is not supported");
}
if (whereString.length() > 0) {
return "(" + whereString.toString() + ")";
}
}
return "";
}
use of org.apache.ofbiz.entity.model.ModelViewEntity 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.ModelViewEntity in project ofbiz-framework by apache.
the class EntityDataLoader method generateData.
public static int generateData(Delegator delegator, List<Object> errorMessages) throws GenericEntityException {
int rowsChanged = 0;
ModelReader reader = delegator.getModelReader();
for (String entityName : reader.getEntityNames()) {
ModelEntity entity = reader.getModelEntity(entityName);
String baseName = entity.getPlainTableName();
if (entity instanceof ModelViewEntity) {
baseName = ModelUtil.javaNameToDbName(entity.getEntityName());
}
if (baseName != null) {
try {
List<GenericValue> toBeStored = new LinkedList<GenericValue>();
toBeStored.add(delegator.makeValue("SecurityPermission", "permissionId", baseName + "_ADMIN", "description", "Permission to Administer a " + entity.getEntityName() + " entity."));
toBeStored.add(delegator.makeValue("SecurityGroupPermission", "groupId", "FULLADMIN", "permissionId", baseName + "_ADMIN", "fromDate", UtilDateTime.nowTimestamp()));
rowsChanged += delegator.storeAll(toBeStored);
} catch (GenericEntityException e) {
errorMessages.add("[generateData] ERROR: Failed Security Generation for entity \"" + baseName + "\"");
}
/*
toStore.add(delegator.makeValue("SecurityPermission", "permissionId", baseName + "_VIEW", "description", "Permission to View a " + entity.getEntityName() + " entity."));
toStore.add(delegator.makeValue("SecurityPermission", "permissionId", baseName + "_CREATE", "description", "Permission to Create a " + entity.getEntityName() + " entity."));
toStore.add(delegator.makeValue("SecurityPermission", "permissionId", baseName + "_UPDATE", "description", "Permission to Update a " + entity.getEntityName() + " entity."));
toStore.add(delegator.makeValue("SecurityPermission", "permissionId", baseName + "_DELETE", "description", "Permission to Delete a " + entity.getEntityName() + " entity."));
toStore.add(delegator.makeValue("SecurityGroupPermission", "groupId", "FLEXADMIN", "permissionId", baseName + "_VIEW"));
toStore.add(delegator.makeValue("SecurityGroupPermission", "groupId", "FLEXADMIN", "permissionId", baseName + "_CREATE"));
toStore.add(delegator.makeValue("SecurityGroupPermission", "groupId", "FLEXADMIN", "permissionId", baseName + "_UPDATE"));
toStore.add(delegator.makeValue("SecurityGroupPermission", "groupId", "FLEXADMIN", "permissionId", baseName + "_DELETE"));
*/
}
}
return rowsChanged;
}
use of org.apache.ofbiz.entity.model.ModelViewEntity in project ofbiz-framework by apache.
the class SqlJdbcUtil method makeFromClause.
/**
* Makes the FROM clause and when necessary the JOIN clause(s) as well
*/
public static String makeFromClause(ModelEntity modelEntity, ModelFieldTypeReader modelFieldTypeReader, Datasource datasourceInfo) throws GenericEntityException {
StringBuilder sql = new StringBuilder(" FROM ");
if (modelEntity instanceof ModelViewEntity) {
ModelViewEntity modelViewEntity = (ModelViewEntity) modelEntity;
if ("ansi".equals(datasourceInfo.getJoinStyle()) || "ansi-no-parenthesis".equals(datasourceInfo.getJoinStyle())) {
boolean useParenthesis = true;
if ("ansi-no-parenthesis".equals(datasourceInfo.getJoinStyle())) {
useParenthesis = false;
}
// FROM clause: in this case will be a bunch of joins that correspond with the view-links
// BIG NOTE on the JOIN clauses: the order of joins is determined by the order of the
// view-links; for more flexible order we'll have to figure something else out and
// extend the DTD for the nested view-link elements or something
// At this point it is assumed that in each view-link the left hand alias will
// either be the first alias in the series or will already be in a previous
// view-link and already be in the big join; SO keep a set of all aliases
// in the join so far and if the left entity alias isn't there yet, and this
// isn't the first one, throw an exception
Set<String> joinedAliasSet = new TreeSet<String>();
// TODO: at view-link read time make sure they are ordered properly so that each
// left hand alias after the first view-link has already been linked before
StringBuilder openParens = null;
if (useParenthesis)
openParens = new StringBuilder();
StringBuilder restOfStatement = new StringBuilder();
for (int i = 0; i < modelViewEntity.getViewLinksSize(); i++) {
// don't put starting parenthesis
if (i > 0 && useParenthesis)
openParens.append('(');
ModelViewEntity.ModelViewLink viewLink = modelViewEntity.getViewLink(i);
ModelEntity linkEntity = modelViewEntity.getMemberModelEntity(viewLink.getEntityAlias());
ModelEntity relLinkEntity = modelViewEntity.getMemberModelEntity(viewLink.getRelEntityAlias());
if (i == 0) {
// this is the first referenced member alias, so keep track of it for future use...
restOfStatement.append(makeViewTable(linkEntity, modelFieldTypeReader, datasourceInfo));
// another possible one that some dbs might need, but not sure of any yet: restOfStatement.append(" AS ");
restOfStatement.append(" ");
restOfStatement.append(viewLink.getEntityAlias());
joinedAliasSet.add(viewLink.getEntityAlias());
} else {
// make sure the left entity alias is already in the join...
if (!joinedAliasSet.contains(viewLink.getEntityAlias())) {
throw new GenericModelException("Tried to link the " + viewLink.getEntityAlias() + " alias to the " + viewLink.getRelEntityAlias() + " alias of the " + modelViewEntity.getEntityName() + " view-entity, but it is not the first view-link and has not been included in a previous view-link. In other words, the left/main alias isn't connected to the rest of the member-entities yet.");
}
}
// now put the rel (right) entity alias into the set that is in the join
joinedAliasSet.add(viewLink.getRelEntityAlias());
if (viewLink.isRelOptional()) {
restOfStatement.append(" LEFT OUTER JOIN ");
} else {
restOfStatement.append(" INNER JOIN ");
}
restOfStatement.append(makeViewTable(relLinkEntity, modelFieldTypeReader, datasourceInfo));
// another possible one that some dbs might need, but not sure of any yet: restOfStatement.append(" AS ");
restOfStatement.append(" ");
restOfStatement.append(viewLink.getRelEntityAlias());
restOfStatement.append(" ON ");
StringBuilder condBuffer = new StringBuilder();
for (int j = 0; j < viewLink.getKeyMapsSize(); j++) {
ModelKeyMap keyMap = viewLink.getKeyMap(j);
ModelField linkField = linkEntity.getField(keyMap.getFieldName());
if (linkField == null) {
throw new GenericModelException("Invalid field name in view-link key-map for the " + viewLink.getEntityAlias() + " and the " + viewLink.getRelEntityAlias() + " member-entities of the " + modelViewEntity.getEntityName() + " view-entity; the field [" + keyMap.getFieldName() + "] does not exist on the [" + linkEntity.getEntityName() + "] entity.");
}
ModelField relLinkField = relLinkEntity.getField(keyMap.getRelFieldName());
if (relLinkField == null) {
throw new GenericModelException("Invalid related field name in view-link key-map for the " + viewLink.getEntityAlias() + " and the " + viewLink.getRelEntityAlias() + " member-entities of the " + modelViewEntity.getEntityName() + " view-entity; the field [" + keyMap.getRelFieldName() + "] does not exist on the [" + relLinkEntity.getEntityName() + "] entity.");
}
if (condBuffer.length() > 0) {
condBuffer.append(" AND ");
}
condBuffer.append(viewLink.getEntityAlias());
condBuffer.append(".");
condBuffer.append(linkField.getColName());
condBuffer.append(" = ");
condBuffer.append(viewLink.getRelEntityAlias());
condBuffer.append(".");
condBuffer.append(relLinkField.getColName());
}
if (condBuffer.length() == 0) {
throw new GenericModelException("No view-link/join key-maps found for the " + viewLink.getEntityAlias() + " and the " + viewLink.getRelEntityAlias() + " member-entities of the " + modelViewEntity.getEntityName() + " view-entity.");
}
ModelViewEntity.ViewEntityCondition viewEntityCondition = viewLink.getViewEntityCondition();
if (viewEntityCondition != null) {
EntityCondition whereCondition = viewEntityCondition.getWhereCondition(modelFieldTypeReader, null);
condBuffer.append(" AND ");
condBuffer.append(whereCondition.makeWhereString(modelEntity, null, datasourceInfo));
}
restOfStatement.append(condBuffer.toString());
// don't put ending parenthesis
if (i < (modelViewEntity.getViewLinksSize() - 1) && useParenthesis)
restOfStatement.append(')');
}
if (useParenthesis)
sql.append(openParens.toString());
sql.append(restOfStatement.toString());
// handle tables not included in view-link
boolean fromEmpty = restOfStatement.length() == 0;
for (String aliasName : modelViewEntity.getMemberModelMemberEntities().keySet()) {
ModelEntity fromEntity = modelViewEntity.getMemberModelEntity(aliasName);
if (!joinedAliasSet.contains(aliasName)) {
if (!fromEmpty)
sql.append(", ");
fromEmpty = false;
sql.append(makeViewTable(fromEntity, modelFieldTypeReader, datasourceInfo));
sql.append(" ");
sql.append(aliasName);
}
}
} else if ("theta-oracle".equals(datasourceInfo.getJoinStyle()) || "theta-mssql".equals(datasourceInfo.getJoinStyle())) {
// FROM clause
Iterator<String> meIter = modelViewEntity.getMemberModelMemberEntities().keySet().iterator();
while (meIter.hasNext()) {
String aliasName = meIter.next();
ModelEntity fromEntity = modelViewEntity.getMemberModelEntity(aliasName);
sql.append(makeViewTable(fromEntity, modelFieldTypeReader, datasourceInfo));
sql.append(" ");
sql.append(aliasName);
if (meIter.hasNext())
sql.append(", ");
}
// JOIN clause(s): none needed, all the work done in the where clause for theta-oracle
} else {
throw new GenericModelException("The join-style " + datasourceInfo.getJoinStyle() + " is not yet supported");
}
} else {
sql.append(modelEntity.getTableName(datasourceInfo));
}
return sql.toString();
}
use of org.apache.ofbiz.entity.model.ModelViewEntity in project ofbiz-framework by apache.
the class SqlJdbcUtil method makeViewTable.
public static String makeViewTable(ModelEntity modelEntity, ModelFieldTypeReader modelFieldTypeReader, Datasource datasourceInfo) throws GenericEntityException {
if (modelEntity instanceof ModelViewEntity) {
StringBuilder sql = new StringBuilder("(SELECT ");
Iterator<ModelField> fieldsIter = modelEntity.getFieldsIterator();
if (fieldsIter.hasNext()) {
ModelField curField = fieldsIter.next();
sql.append(curField.getColValue());
sql.append(" AS ");
sql.append(curField.getColName());
while (fieldsIter.hasNext()) {
curField = fieldsIter.next();
sql.append(", ");
sql.append(curField.getColValue());
sql.append(" AS ");
sql.append(curField.getColName());
}
}
sql.append(makeFromClause(modelEntity, modelFieldTypeReader, datasourceInfo));
String viewWhereClause = makeViewWhereClause(modelEntity, datasourceInfo.getJoinStyle());
ModelViewEntity modelViewEntity = (ModelViewEntity) modelEntity;
List<EntityCondition> whereConditions = new LinkedList<EntityCondition>();
List<EntityCondition> havingConditions = new LinkedList<EntityCondition>();
List<String> orderByList = new LinkedList<String>();
modelViewEntity.populateViewEntityConditionInformation(modelFieldTypeReader, whereConditions, havingConditions, orderByList, null);
String viewConditionClause;
if (!whereConditions.isEmpty()) {
viewConditionClause = EntityCondition.makeCondition(whereConditions, EntityOperator.AND).makeWhereString(modelViewEntity, null, datasourceInfo);
} else {
viewConditionClause = null;
}
if (UtilValidate.isNotEmpty(viewWhereClause) || UtilValidate.isNotEmpty(viewConditionClause)) {
sql.append(" WHERE ");
if (UtilValidate.isNotEmpty(viewWhereClause)) {
sql.append("(").append(viewWhereClause).append(")");
if (UtilValidate.isNotEmpty(viewConditionClause)) {
sql.append(" AND ");
}
}
if (UtilValidate.isNotEmpty(viewConditionClause)) {
sql.append("(").append(viewConditionClause).append(")");
}
}
// FIXME: handling HAVING, don't need ORDER BY for nested views
modelViewEntity.colNameString(modelViewEntity.getGroupBysCopy(), sql, " GROUP BY ", ", ", "", false);
sql.append(")");
return sql.toString();
} else {
return modelEntity.getTableName(datasourceInfo);
}
}
Aggregations