use of org.apache.ofbiz.entity.model.ModelEntity in project ofbiz-framework by apache.
the class EntitySaxReader method endElement.
public void endElement(String namespaceURI, String localName, String fullNameString) throws SAXException {
if (Debug.verboseOn())
Debug.logVerbose("endElement: localName=" + localName + ", fullName=" + fullNameString + ", numberRead=" + numberRead, module);
if ("entity-engine-xml".equals(fullNameString)) {
return;
}
if ("entity-engine-transform-xml".equals(fullNameString)) {
// transform file & parse it, then return
URL templateUrl = null;
try {
templateUrl = FlexibleLocation.resolveLocation(templatePath.toString());
} catch (MalformedURLException e) {
throw new SAXException("Could not find transform template with resource path [" + templatePath + "]; error was: " + e.toString());
}
if (templateUrl == null) {
throw new SAXException("Could not find transform template with resource path: " + templatePath);
} else {
try {
BufferedReader templateReader = new BufferedReader(new InputStreamReader(templateUrl.openStream(), UtilIO.getUtf8()));
StringWriter outWriter = new StringWriter();
Configuration config = FreeMarkerWorker.newConfiguration();
config.setObjectWrapper(FreeMarkerWorker.getDefaultOfbizWrapper());
config.setSetting("datetime_format", "yyyy-MM-dd HH:mm:ss.SSS");
Template template = new Template("FMImportFilter", templateReader, config);
NodeModel nodeModel = NodeModel.wrap(this.rootNodeForTemplate);
Map<String, Object> context = new HashMap<String, Object>();
TemplateHashModel staticModels = FreeMarkerWorker.getDefaultOfbizWrapper().getStaticModels();
context.put("Static", staticModels);
context.put("doc", nodeModel);
template.process(context, outWriter);
String s = outWriter.toString();
if (Debug.verboseOn())
Debug.logVerbose("transformed xml: " + s, module);
EntitySaxReader reader = new EntitySaxReader(delegator);
reader.setUseTryInsertMethod(this.useTryInsertMethod);
try {
reader.setTransactionTimeout(this.transactionTimeout);
} catch (GenericTransactionException e1) {
Debug.logWarning("couldn't set tx timeout, hopefully shouldn't be a big deal", module);
}
numberRead += reader.parse(s);
} catch (TemplateException | IOException e) {
throw new SAXException("Error storing value", e);
}
}
return;
}
if (isParseForTemplate) {
this.currentNodeForTemplate = this.currentNodeForTemplate.getParentNode();
return;
}
// Test if end action tag, set action to default
if (actionTags.contains(fullNameString)) {
setAction(Action.CREATE_UPDATE);
return;
}
if (currentValue != null) {
if (currentFieldName != null) {
if (UtilValidate.isNotEmpty(currentFieldValue)) {
if (currentValue.getModelEntity().isField(currentFieldName.toString())) {
ModelEntity modelEntity = currentValue.getModelEntity();
ModelField modelField = modelEntity.getField(currentFieldName.toString());
String type = modelField.getType();
if (type != null && "blob".equals(type)) {
byte[] binData = Base64.base64Decode((new String(currentFieldValue)).getBytes());
currentValue.setBytes(currentFieldName.toString(), binData);
} else {
currentValue.setString(currentFieldName.toString(), new String(currentFieldValue));
}
} else {
Debug.logWarning("Ignoring invalid field name [" + currentFieldName + "] found for the entity: " + currentValue.getEntityName() + " with value=" + currentFieldValue, module);
}
currentFieldValue = null;
}
currentFieldName = null;
} else {
// before we write currentValue check to see if PK is there, if not and it is one field, generate it from a sequence using the entity name
if (!currentValue.containsPrimaryKey()) {
if (currentValue.getModelEntity().getPksSize() == 1) {
ModelField modelField = currentValue.getModelEntity().getOnlyPk();
String newSeq = delegator.getNextSeqId(currentValue.getEntityName());
currentValue.setString(modelField.getName(), newSeq);
} else {
throw new SAXException("Cannot store value with incomplete primary key with more than 1 primary key field: " + currentValue);
}
}
try {
boolean exist = true;
boolean skip = false;
// It's necessary to check also for specific action CREATE and DELETE to ensure it's OK
if (Action.CREATE == currentAction || Action.DELETE == currentAction || Debug.verboseOn()) {
GenericHelper helper = delegator.getEntityHelper(currentValue.getEntityName());
if (currentValue.containsPrimaryKey()) {
try {
helper.findByPrimaryKey(currentValue.getPrimaryKey());
} catch (GenericEntityNotFoundException e) {
exist = false;
}
}
if (Action.CREATE == currentAction && exist) {
skip = true;
} else if (Action.DELETE == currentAction && !exist) {
skip = true;
}
}
if (!skip) {
if (this.useTryInsertMethod && !this.checkDataOnly) {
if (Action.DELETE == currentAction) {
currentValue.remove();
} else {
currentValue.create();
}
} else {
if (Action.DELETE == currentAction) {
valuesToDelete.add(currentValue);
if (valuesToDelete.size() >= valuesPerWrite) {
delegator.removeAll(valuesToDelete);
valuesToDelete.clear();
}
} else {
valuesToWrite.add(currentValue);
if (valuesToWrite.size() >= valuesPerWrite) {
writeValues(valuesToWrite);
valuesToWrite.clear();
}
}
}
}
numberRead++;
if (Debug.verboseOn())
countValue(skip, exist);
if ((numberRead % valuesPerMessage) == 0) {
Debug.logImportant("Another " + valuesPerMessage + " values imported: now up to " + numberRead, module);
}
currentValue = null;
} catch (GenericEntityException e) {
String errMsg = "Error performing action " + currentAction;
Debug.logError(e, errMsg, module);
throw new SAXException(errMsg, e);
}
}
}
}
use of org.apache.ofbiz.entity.model.ModelEntity in project ofbiz-framework by apache.
the class EntityTestSuite method testModels.
public void testModels() throws Exception {
ModelEntity modelEntity = delegator.getModelEntity("TestingType");
assertNotNull("TestingType entity model not null", modelEntity);
ModelField modelField = modelEntity.getField("description");
assertNotNull("TestingType.description field model not null", modelField);
modelField = ModelField.create(modelEntity, null, "newDesc", modelField.getType(), "NEW_DESC", null, null, false, false, false, false, false, null);
modelEntity.addField(modelField);
modelField = modelEntity.getField("newDesc");
assertNotNull("TestingType.newDesc field model not null", modelField);
modelEntity.removeField("newDesc");
modelField = modelEntity.getField("newDesc");
assertNull("TestingType.newDesc field model is null", modelField);
}
use of org.apache.ofbiz.entity.model.ModelEntity 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.ModelEntity in project ofbiz-framework by apache.
the class DatabaseUtil method createTable.
/* ====================================================================== */
/* ====================================================================== */
public String createTable(ModelEntity entity, Map<String, ModelEntity> modelEntities, boolean addFks) {
if (entity == null) {
return "ModelEntity was null and is required to create a table";
}
if (entity instanceof ModelViewEntity) {
return "ERROR: Cannot create table for a view entity";
}
StringBuilder sqlBuf = new StringBuilder("CREATE TABLE ");
sqlBuf.append(entity.getTableName(this.datasourceInfo));
sqlBuf.append(" (");
Iterator<ModelField> fieldIter = entity.getFieldsIterator();
while (fieldIter.hasNext()) {
ModelField field = fieldIter.next();
ModelFieldType type = modelFieldTypeReader.getModelFieldType(field.getType());
if (type == null) {
return "Field type [" + type + "] not found for field [" + field.getName() + "] of entity [" + entity.getEntityName() + "], not creating table.";
}
sqlBuf.append(field.getColName());
sqlBuf.append(" ");
sqlBuf.append(type.getSqlType());
if ("String".equals(type.getJavaType()) || "java.lang.String".equals(type.getJavaType())) {
// if there is a characterSet, add the CHARACTER SET arg here
if (UtilValidate.isNotEmpty(this.datasourceInfo.getCharacterSet())) {
sqlBuf.append(" CHARACTER SET ");
sqlBuf.append(this.datasourceInfo.getCharacterSet());
}
// if there is a collate, add the COLLATE arg here
if (UtilValidate.isNotEmpty(this.datasourceInfo.getCollate())) {
sqlBuf.append(" COLLATE ");
sqlBuf.append(this.datasourceInfo.getCollate());
}
}
if (field.getIsNotNull() || field.getIsPk()) {
if (this.datasourceInfo.getAlwaysUseConstraintKeyword()) {
sqlBuf.append(" CONSTRAINT NOT NULL, ");
} else {
sqlBuf.append(" NOT NULL, ");
}
} else {
sqlBuf.append(", ");
}
}
String pkName = makePkConstraintName(entity, this.datasourceInfo.getConstraintNameClipLength());
if (this.datasourceInfo.getUsePkConstraintNames()) {
sqlBuf.append("CONSTRAINT ");
sqlBuf.append(pkName);
}
sqlBuf.append(" PRIMARY KEY (");
entity.colNameString(entity.getPkFieldsUnmodifiable(), sqlBuf, "");
sqlBuf.append(")");
if (addFks) {
// NOTE: This is kind of a bad idea anyway since ordering table creations is crazy, if not impossible
// go through the relationships to see if any foreign keys need to be added
Iterator<ModelRelation> relationsIter = entity.getRelationsIterator();
while (relationsIter.hasNext()) {
ModelRelation modelRelation = relationsIter.next();
if ("one".equals(modelRelation.getType())) {
ModelEntity relModelEntity = modelEntities.get(modelRelation.getRelEntityName());
if (relModelEntity == null) {
Debug.logError("Error adding foreign key: ModelEntity was null for related entity name " + modelRelation.getRelEntityName(), module);
continue;
}
if (relModelEntity instanceof ModelViewEntity) {
Debug.logError("Error adding foreign key: related entity is a view entity for related entity name " + modelRelation.getRelEntityName(), module);
continue;
}
String fkConstraintClause = makeFkConstraintClause(entity, modelRelation, relModelEntity, this.datasourceInfo.getConstraintNameClipLength(), this.datasourceInfo.getFkStyle(), this.datasourceInfo.getUseFkInitiallyDeferred());
if (UtilValidate.isNotEmpty(fkConstraintClause)) {
sqlBuf.append(", ");
sqlBuf.append(fkConstraintClause);
} else {
continue;
}
}
}
}
sqlBuf.append(")");
// if there is a tableType, add the TYPE arg here
if (UtilValidate.isNotEmpty(this.datasourceInfo.getTableType())) {
// jaz:20101229 - This appears to be only used by mysql and now mysql has
// deprecated (and in 5.5.x removed) the use of the TYPE keyword. This is
// changed to ENGINE which is supported starting at 4.1
sqlBuf.append(" ENGINE ");
// sqlBuf.append(" TYPE ");
sqlBuf.append(this.datasourceInfo.getTableType());
}
// if there is a characterSet, add the CHARACTER SET arg here
if (UtilValidate.isNotEmpty(this.datasourceInfo.getCharacterSet())) {
sqlBuf.append(" CHARACTER SET ");
sqlBuf.append(this.datasourceInfo.getCharacterSet());
}
// if there is a collate, add the COLLATE arg here
if (UtilValidate.isNotEmpty(this.datasourceInfo.getCollate())) {
sqlBuf.append(" COLLATE ");
sqlBuf.append(this.datasourceInfo.getCollate());
}
if (Debug.verboseOn())
Debug.logVerbose("[createTable] sql=" + sqlBuf.toString(), module);
try (Connection connection = getConnection();
Statement stmt = connection.createStatement()) {
stmt.executeUpdate(sqlBuf.toString());
} catch (SQLException e) {
String errMsg = "SQL Exception while executing the following:\n" + sqlBuf.toString() + "\nError was: " + e.toString();
Debug.logError(e, errMsg, module);
return errMsg;
} catch (GenericEntityException e) {
String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString();
Debug.logError(e, errMsg, module);
return errMsg;
}
return null;
}
use of org.apache.ofbiz.entity.model.ModelEntity in project ofbiz-framework by apache.
the class DatabaseUtil method createForeignKeys.
public int createForeignKeys(ModelEntity entity, Map<String, ModelEntity> modelEntities, int constraintNameClipLength, String fkStyle, boolean useFkInitiallyDeferred, List<String> messages) {
if (entity == null) {
String errMsg = "ModelEntity was null and is required to create foreign keys for a table";
Debug.logError(errMsg, module);
if (messages != null)
messages.add(errMsg);
return 0;
}
if (entity instanceof ModelViewEntity) {
// if (messages != null) messages.add(errMsg);
return 0;
}
int fksCreated = 0;
// go through the relationships to see if any foreign keys need to be added
Iterator<ModelRelation> relationsIter = entity.getRelationsIterator();
while (relationsIter.hasNext()) {
ModelRelation modelRelation = relationsIter.next();
if ("one".equals(modelRelation.getType())) {
ModelEntity relModelEntity = modelEntities.get(modelRelation.getRelEntityName());
if (relModelEntity == null) {
String errMsg = "Error adding foreign key: ModelEntity was null for related entity name " + modelRelation.getRelEntityName();
Debug.logError(errMsg, module);
if (messages != null)
messages.add(errMsg);
continue;
}
if (relModelEntity instanceof ModelViewEntity) {
String errMsg = "Error adding foreign key: related entity is a view entity for related entity name " + modelRelation.getRelEntityName();
Debug.logError(errMsg, module);
if (messages != null)
messages.add(errMsg);
continue;
}
String retMsg = createForeignKey(entity, modelRelation, relModelEntity, constraintNameClipLength, fkStyle, useFkInitiallyDeferred);
if (UtilValidate.isNotEmpty(retMsg)) {
Debug.logError(retMsg, module);
if (messages != null)
messages.add(retMsg);
continue;
}
fksCreated++;
}
}
if (fksCreated > 0) {
String message = "Created " + fksCreated + " foreign keys for entity [" + entity.getEntityName() + "]";
Debug.logImportant(message, module);
if (messages != null)
messages.add(message);
}
return fksCreated;
}
Aggregations