Search in sources :

Example 1 with GenericHelper

use of org.apache.ofbiz.entity.datasource.GenericHelper in project ofbiz-framework by apache.

the class GenericDelegator method initializeOneGenericHelper.

private void initializeOneGenericHelper(String groupName) {
    GenericHelperInfo helperInfo = this.getGroupHelperInfo(groupName);
    if (helperInfo == null) {
        if (Debug.infoOn()) {
            Debug.logInfo("Delegator \"" + delegatorFullName + "\" NOT initializing helper for entity group \"" + groupName + "\" because the group is not associated to this delegator.", module);
        }
        return;
    }
    String helperBaseName = helperInfo.getHelperBaseName();
    if (Debug.infoOn()) {
        Debug.logInfo("Delegator \"" + delegatorFullName + "\" initializing helper \"" + helperBaseName + "\" for entity group \"" + groupName + "\".", module);
    }
    if (UtilValidate.isNotEmpty(helperInfo.getHelperFullName())) {
        // pre-load field type defs, the return value is ignored
        ModelFieldTypeReader.getModelFieldTypeReader(helperBaseName);
        // get the helper and if configured, do the datasource check
        GenericHelper helper = GenericHelperFactory.getHelper(helperInfo);
        try {
            Datasource datasource = EntityConfig.getDatasource(helperBaseName);
            if (datasource.getCheckOnStart()) {
                if (Debug.infoOn()) {
                    Debug.logInfo("Doing database check as requested in entityengine.xml with addMissing=" + datasource.getAddMissingOnStart(), module);
                }
                helper.checkDataSource(this.getModelEntityMapByGroup(groupName), null, datasource.getAddMissingOnStart());
            }
        } catch (GenericEntityException e) {
            Debug.logWarning(e, e.getMessage(), module);
        }
    }
}
Also used : Datasource(org.apache.ofbiz.entity.config.model.Datasource) GenericHelperInfo(org.apache.ofbiz.entity.datasource.GenericHelperInfo) GenericHelper(org.apache.ofbiz.entity.datasource.GenericHelper)

Example 2 with GenericHelper

use of org.apache.ofbiz.entity.datasource.GenericHelper in project ofbiz-framework by apache.

the class GenericDelegator method getMultiRelation.

/* (non-Javadoc)
     * @see org.apache.ofbiz.entity.Delegator#getMultiRelation(org.apache.ofbiz.entity.GenericValue, java.lang.String, java.lang.String, java.util.List)
     */
@Override
public List<GenericValue> getMultiRelation(GenericValue value, String relationNameOne, String relationNameTwo, List<String> orderBy) throws GenericEntityException {
    boolean beganTransaction = false;
    try {
        if (alwaysUseTransaction) {
            beganTransaction = TransactionUtil.begin();
        }
        // TODO: add eca eval calls
        // traverse the relationships
        ModelEntity modelEntity = value.getModelEntity();
        ModelRelation modelRelationOne = modelEntity.getRelation(relationNameOne);
        ModelEntity modelEntityOne = getModelEntity(modelRelationOne.getRelEntityName());
        ModelRelation modelRelationTwo = modelEntityOne.getRelation(relationNameTwo);
        ModelEntity modelEntityTwo = getModelEntity(modelRelationTwo.getRelEntityName());
        GenericHelper helper = getEntityHelper(modelEntity);
        List<GenericValue> result = helper.findByMultiRelation(value, modelRelationOne, modelEntityOne, modelRelationTwo, modelEntityTwo, orderBy);
        TransactionUtil.commit(beganTransaction);
        return result;
    } catch (GenericEntityException e) {
        String errMsg = "Failure in getMultiRelation operation for entity [" + value.getEntityName() + "]: " + e.toString() + ". Rolling back transaction.";
        Debug.logError(e, errMsg, module);
        TransactionUtil.rollback(beganTransaction, errMsg, e);
        throw new GenericEntityException(e);
    }
}
Also used : ModelRelation(org.apache.ofbiz.entity.model.ModelRelation) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) GenericHelper(org.apache.ofbiz.entity.datasource.GenericHelper)

Example 3 with GenericHelper

use of org.apache.ofbiz.entity.datasource.GenericHelper in project ofbiz-framework by apache.

the class GenericDelegator method findListIteratorByCondition.

/* (non-Javadoc)
     * @see org.apache.ofbiz.entity.Delegator#findListIteratorByCondition(org.apache.ofbiz.entity.model.DynamicViewEntity, org.apache.ofbiz.entity.condition.EntityCondition, org.apache.ofbiz.entity.condition.EntityCondition, java.util.Collection, java.util.List, org.apache.ofbiz.entity.util.EntityFindOptions)
     */
@Override
public EntityListIterator findListIteratorByCondition(DynamicViewEntity dynamicViewEntity, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, Collection<String> fieldsToSelect, List<String> orderBy, EntityFindOptions findOptions) throws GenericEntityException {
    // if there is no transaction throw an exception, we don't want to create a transaction here since closing it would mess up the ELI
    if (!TransactionUtil.isTransactionInPlace()) {
        // throw new GenericEntityException("ERROR: Cannot do a find that returns an EntityListIterator with no transaction in place. Wrap this call in a transaction.");
        // throwing an exception is a little harsh for now, just display a really big error message since we want to get all of these fixed...
        Exception newE = new Exception("Stack Trace");
        Debug.logError(newE, "ERROR: Cannot do a find that returns an EntityListIterator with no transaction in place. Wrap this call in a transaction.", module);
    }
    ModelViewEntity modelViewEntity = dynamicViewEntity.makeModelViewEntity(this);
    if (whereEntityCondition != null) {
        whereEntityCondition.checkCondition(modelViewEntity);
    }
    if (havingEntityCondition != null) {
        havingEntityCondition.checkCondition(modelViewEntity);
    }
    GenericHelper helper = getEntityHelper(dynamicViewEntity.getOneRealEntityName());
    EntityListIterator eli = helper.findListIteratorByCondition(this, modelViewEntity, whereEntityCondition, havingEntityCondition, fieldsToSelect, orderBy, findOptions);
    eli.setDelegator(this);
    // TODO: add decrypt fields
    return eli;
}
Also used : ModelViewEntity(org.apache.ofbiz.entity.model.ModelViewEntity) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) GenericHelper(org.apache.ofbiz.entity.datasource.GenericHelper) SerializeException(org.apache.ofbiz.entity.serialize.SerializeException) SAXException(org.xml.sax.SAXException) GeneralRuntimeException(org.apache.ofbiz.base.util.GeneralRuntimeException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 4 with GenericHelper

use of org.apache.ofbiz.entity.datasource.GenericHelper in project ofbiz-framework by apache.

the class GenericDelegator method find.

/* (non-Javadoc)
     * @see org.apache.ofbiz.entity.Delegator#find(java.lang.String, org.apache.ofbiz.entity.condition.EntityCondition, org.apache.ofbiz.entity.condition.EntityCondition, java.util.Set, java.util.List, org.apache.ofbiz.entity.util.EntityFindOptions)
     */
@Override
public EntityListIterator find(String entityName, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, Set<String> fieldsToSelect, List<String> orderBy, EntityFindOptions findOptions) throws GenericEntityException {
    // if there is no transaction throw an exception, we don't want to create a transaction here since closing it would mess up the ELI
    if (!TransactionUtil.isTransactionInPlace()) {
        // throw new GenericEntityException("ERROR: Cannot do a find that returns an EntityListIterator with no transaction in place. Wrap this call in a transaction.");
        // throwing an exception is a little harsh for now, just display a really big error message since we want to get all of these fixed...
        Exception newE = new Exception("Stack Trace");
        Debug.logError(newE, "ERROR: Cannot do a find that returns an EntityListIterator with no transaction in place. Wrap this call in a transaction.", module);
    }
    ModelEntity modelEntity = getModelReader().getModelEntity(entityName);
    GenericValue dummyValue = GenericValue.create(modelEntity);
    EntityEcaRuleRunner<?> ecaRunner = this.getEcaRuleRunner(modelEntity.getEntityName());
    ecaRunner.evalRules(EntityEcaHandler.EV_VALIDATE, EntityEcaHandler.OP_FIND, dummyValue, false);
    if (whereEntityCondition != null) {
        whereEntityCondition.checkCondition(modelEntity);
    }
    if (havingEntityCondition != null) {
        havingEntityCondition.checkCondition(modelEntity);
    }
    ecaRunner.evalRules(EntityEcaHandler.EV_RUN, EntityEcaHandler.OP_FIND, dummyValue, false);
    GenericHelper helper = getEntityHelper(modelEntity.getEntityName());
    EntityListIterator eli = helper.findListIteratorByCondition(this, modelEntity, whereEntityCondition, havingEntityCondition, fieldsToSelect, orderBy, findOptions);
    eli.setDelegator(this);
    ecaRunner.evalRules(EntityEcaHandler.EV_RETURN, EntityEcaHandler.OP_FIND, dummyValue, false);
    return eli;
}
Also used : ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) GenericHelper(org.apache.ofbiz.entity.datasource.GenericHelper) SerializeException(org.apache.ofbiz.entity.serialize.SerializeException) SAXException(org.xml.sax.SAXException) GeneralRuntimeException(org.apache.ofbiz.base.util.GeneralRuntimeException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 5 with GenericHelper

use of org.apache.ofbiz.entity.datasource.GenericHelper 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);
            }
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) Configuration(freemarker.template.Configuration) HashMap(java.util.HashMap) URL(java.net.URL) SAXException(org.xml.sax.SAXException) Template(freemarker.template.Template) NodeModel(freemarker.ext.dom.NodeModel) StringWriter(java.io.StringWriter) TemplateHashModel(freemarker.template.TemplateHashModel) ModelField(org.apache.ofbiz.entity.model.ModelField) GenericEntityNotFoundException(org.apache.ofbiz.entity.GenericEntityNotFoundException) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) InputStreamReader(java.io.InputStreamReader) TemplateException(freemarker.template.TemplateException) IOException(java.io.IOException) GenericHelper(org.apache.ofbiz.entity.datasource.GenericHelper) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) BufferedReader(java.io.BufferedReader) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException)

Aggregations

GenericHelper (org.apache.ofbiz.entity.datasource.GenericHelper)16 ModelEntity (org.apache.ofbiz.entity.model.ModelEntity)7 IOException (java.io.IOException)3 SAXException (org.xml.sax.SAXException)3 ExecutionException (java.util.concurrent.ExecutionException)2 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)2 GeneralRuntimeException (org.apache.ofbiz.base.util.GeneralRuntimeException)2 ModelField (org.apache.ofbiz.entity.model.ModelField)2 SerializeException (org.apache.ofbiz.entity.serialize.SerializeException)2 EntityListIterator (org.apache.ofbiz.entity.util.EntityListIterator)2 NodeModel (freemarker.ext.dom.NodeModel)1 Configuration (freemarker.template.Configuration)1 Template (freemarker.template.Template)1 TemplateException (freemarker.template.TemplateException)1 TemplateHashModel (freemarker.template.TemplateHashModel)1 BufferedReader (java.io.BufferedReader)1 InputStreamReader (java.io.InputStreamReader)1 StringWriter (java.io.StringWriter)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1