Search in sources :

Example 1 with GenericEntityNotFoundException

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

the class GenericDAO method select.

public void select(GenericEntity entity, SQLProcessor sqlP) throws GenericEntityException {
    ModelEntity modelEntity = entity.getModelEntity();
    if (modelEntity.getPksSize() <= 0) {
        throw new GenericEntityException("Entity has no primary keys, cannot select by primary key");
    }
    StringBuilder sqlBuffer = new StringBuilder("SELECT ");
    if (modelEntity.getNopksSize() > 0) {
        modelEntity.colNameString(modelEntity.getNopksCopy(), sqlBuffer, "", ", ", "", datasource.getAliasViewColumns());
    } else {
        sqlBuffer.append("*");
    }
    sqlBuffer.append(SqlJdbcUtil.makeFromClause(modelEntity, modelFieldTypeReader, datasource));
    sqlBuffer.append(SqlJdbcUtil.makeWhereClause(modelEntity, modelEntity.getPkFieldsUnmodifiable(), entity, "AND", datasource.getJoinStyle()));
    sqlP.prepareStatement(sqlBuffer.toString(), true, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
    SqlJdbcUtil.setPkValues(sqlP, modelEntity, entity, modelFieldTypeReader);
    sqlP.executeQuery();
    if (sqlP.next()) {
        int idx = 1;
        Iterator<ModelField> nopkIter = modelEntity.getNopksIterator();
        while (nopkIter.hasNext()) {
            ModelField curField = nopkIter.next();
            SqlJdbcUtil.getValue(sqlP.getResultSet(), idx, curField, entity, modelFieldTypeReader);
            idx++;
        }
        entity.synchronizedWithDatasource();
    } else {
        // Debug.logWarning("[GenericDAO.select]: select failed, result set was empty for entity: " + entity.toString(), module);
        throw new GenericEntityNotFoundException("Result set was empty for entity: " + entity.toString());
    }
}
Also used : ModelField(org.apache.ofbiz.entity.model.ModelField) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericEntityNotFoundException(org.apache.ofbiz.entity.GenericEntityNotFoundException) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity)

Example 2 with GenericEntityNotFoundException

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

the class GenericDAO method partialSelect.

public void partialSelect(GenericEntity entity, Set<String> keys) throws GenericEntityException {
    ModelEntity modelEntity = entity.getModelEntity();
    if (modelEntity instanceof ModelViewEntity) {
        throw new org.apache.ofbiz.entity.GenericNotImplementedException("Operation partialSelect not supported yet for view entities");
    }
    // we don't want to select ALL fields, just the nonpk fields that are in the passed GenericEntity
    List<ModelField> partialFields = new LinkedList<ModelField>();
    Set<String> tempKeys = new TreeSet<String>(keys);
    Iterator<ModelField> entityFieldIter = modelEntity.getFieldsIterator();
    while (entityFieldIter.hasNext()) {
        ModelField curField = entityFieldIter.next();
        if (tempKeys.contains(curField.getName())) {
            partialFields.add(curField);
            tempKeys.remove(curField.getName());
        }
    }
    if (tempKeys.size() > 0) {
        throw new GenericModelException("In partialSelect invalid field names specified: " + tempKeys.toString());
    }
    StringBuilder sqlBuffer = new StringBuilder("SELECT ");
    if (partialFields.size() > 0) {
        modelEntity.colNameString(partialFields, sqlBuffer, "", ", ", "", datasource.getAliasViewColumns());
    } else {
        sqlBuffer.append("*");
    }
    sqlBuffer.append(SqlJdbcUtil.makeFromClause(modelEntity, modelFieldTypeReader, datasource));
    sqlBuffer.append(SqlJdbcUtil.makeWhereClause(modelEntity, modelEntity.getPkFieldsUnmodifiable(), entity, "AND", datasource.getJoinStyle()));
    try (SQLProcessor sqlP = new SQLProcessor(entity.getDelegator(), helperInfo)) {
        sqlP.prepareStatement(sqlBuffer.toString(), true, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        SqlJdbcUtil.setPkValues(sqlP, modelEntity, entity, modelFieldTypeReader);
        sqlP.executeQuery();
        if (sqlP.next()) {
            for (int j = 0; j < partialFields.size(); j++) {
                ModelField curField = partialFields.get(j);
                SqlJdbcUtil.getValue(sqlP.getResultSet(), j + 1, curField, entity, modelFieldTypeReader);
            }
            entity.synchronizedWithDatasource();
        } else {
            throw new GenericEntityNotFoundException("Result set was empty for entity: " + entity.toString());
        }
    }
}
Also used : GenericModelException(org.apache.ofbiz.entity.GenericModelException) GenericNotImplementedException(org.apache.ofbiz.entity.GenericNotImplementedException) LinkedList(java.util.LinkedList) SQLProcessor(org.apache.ofbiz.entity.jdbc.SQLProcessor) ModelField(org.apache.ofbiz.entity.model.ModelField) TreeSet(java.util.TreeSet) ModelViewEntity(org.apache.ofbiz.entity.model.ModelViewEntity) GenericEntityNotFoundException(org.apache.ofbiz.entity.GenericEntityNotFoundException) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity)

Example 3 with GenericEntityNotFoundException

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

the class ContentJsonEvents method moveContent.

public static String moveContent(HttpServletRequest request, HttpServletResponse response) throws GenericEntityException, IOException {
    final Delegator delegator = (Delegator) request.getAttribute("delegator");
    final String contentIdTo = request.getParameter("contentIdTo");
    final String contentIdFrom = request.getParameter("contentIdFrom");
    final String contentIdFromNew = request.getParameter("contentIdFromNew");
    final String contentAssocTypeId = request.getParameter("contentAssocTypeId");
    final Timestamp fromDate = Timestamp.valueOf(request.getParameter("fromDate"));
    final Timestamp now = UtilDateTime.nowTimestamp();
    GenericValue assoc = TransactionUtil.inTransaction(new Callable<GenericValue>() {

        @Override
        public GenericValue call() throws Exception {
            GenericValue oldAssoc = EntityQuery.use(delegator).from("ContentAssoc").where("contentIdTo", contentIdTo, "contentId", contentIdFrom, "contentAssocTypeId", contentAssocTypeId, "fromDate", fromDate).queryOne();
            if (oldAssoc == null) {
                throw new GenericEntityNotFoundException("Could not find ContentAssoc by primary key [contentIdTo: $contentIdTo, contentId: $contentIdFrom, contentAssocTypeId: $contentAssocTypeId, fromDate: $fromDate]");
            }
            GenericValue newAssoc = (GenericValue) oldAssoc.clone();
            oldAssoc.set("thruDate", now);
            oldAssoc.store();
            newAssoc.set("contentId", contentIdFromNew);
            newAssoc.set("fromDate", now);
            newAssoc.set("thruDate", null);
            delegator.clearCacheLine(delegator.create(newAssoc));
            return newAssoc;
        }
    }, String.format("move content [%s] from [%s] to [%s]", contentIdTo, contentIdFrom, contentIdFromNew), 0, true).call();
    IOUtils.write(JSON.from(getTreeNode(assoc)).toString(), response.getOutputStream());
    return "success";
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityNotFoundException(org.apache.ofbiz.entity.GenericEntityNotFoundException) Timestamp(java.sql.Timestamp) Callable(java.util.concurrent.Callable)

Example 4 with GenericEntityNotFoundException

use of org.apache.ofbiz.entity.GenericEntityNotFoundException 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)

Example 5 with GenericEntityNotFoundException

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

the class GenericDAO method singleUpdate.

private int singleUpdate(GenericEntity entity, ModelEntity modelEntity, List<ModelField> fieldsToSave, SQLProcessor sqlP) throws GenericEntityException {
    if (modelEntity instanceof ModelViewEntity) {
        return singleUpdateView(entity, (ModelViewEntity) modelEntity, fieldsToSave, sqlP);
    }
    // no non-primaryKey fields, update doesn't make sense, so don't do it
    if (fieldsToSave.size() <= 0) {
        if (Debug.verboseOn())
            Debug.logVerbose("Trying to do an update on an entity with no non-PK fields, returning having done nothing; entity=" + entity, module);
        // returning one because it was effectively updated, ie the same thing, so don't trigger any errors elsewhere
        return 1;
    }
    if (modelEntity.lock()) {
        GenericEntity entityCopy = GenericEntity.createGenericEntity(entity);
        select(entityCopy, sqlP);
        Object stampField = entity.get(ModelEntity.STAMP_FIELD);
        if ((stampField != null) && (!stampField.equals(entityCopy.get(ModelEntity.STAMP_FIELD)))) {
            String lockedTime = entityCopy.getTimestamp(ModelEntity.STAMP_FIELD).toString();
            throw new EntityLockedException("You tried to update an old version of this data. Version locked: (" + lockedTime + ")");
        }
    }
    // 2. don't set the stamp values if it is from an EntitySync (ie maintain original values), unless the stamps are null then set it anyway, ie even if it was from an EntitySync (also used for imports and such)
    if (modelEntity.isField(ModelEntity.STAMP_TX_FIELD) && (!entity.getIsFromEntitySync() || entity.get(ModelEntity.STAMP_TX_FIELD) == null)) {
        entity.set(ModelEntity.STAMP_TX_FIELD, TransactionUtil.getTransactionStartStamp());
        addFieldIfMissing(fieldsToSave, ModelEntity.STAMP_TX_FIELD, modelEntity);
    }
    // if we have a STAMP_FIELD then update it with NOW.
    if (modelEntity.isField(ModelEntity.STAMP_FIELD) && (!entity.getIsFromEntitySync() || entity.get(ModelEntity.STAMP_FIELD) == null)) {
        entity.set(ModelEntity.STAMP_FIELD, TransactionUtil.getTransactionUniqueNowStamp());
        addFieldIfMissing(fieldsToSave, ModelEntity.STAMP_FIELD, modelEntity);
    }
    StringBuilder sql = new StringBuilder().append("UPDATE ").append(modelEntity.getTableName(datasource)).append(" SET ");
    modelEntity.colNameString(fieldsToSave, sql, "", "=?, ", "=?", false);
    sql.append(" WHERE ");
    SqlJdbcUtil.makeWhereStringFromFields(sql, modelEntity.getPkFieldsUnmodifiable(), entity, "AND");
    int retVal = 0;
    try {
        sqlP.prepareStatement(sql.toString());
        SqlJdbcUtil.setValues(sqlP, fieldsToSave, entity, modelFieldTypeReader);
        SqlJdbcUtil.setPkValues(sqlP, modelEntity, entity, modelFieldTypeReader);
        retVal = sqlP.executeUpdate();
        entity.synchronizedWithDatasource();
    } catch (GenericEntityException e) {
        throw new GenericEntityException("Error while updating: " + entity.toString(), e);
    }
    if (retVal == 0) {
        throw new GenericEntityNotFoundException("Tried to update an entity that does not exist, entity: " + entity.toString());
    }
    return retVal;
}
Also used : GenericEntity(org.apache.ofbiz.entity.GenericEntity) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ModelViewEntity(org.apache.ofbiz.entity.model.ModelViewEntity) GenericEntityNotFoundException(org.apache.ofbiz.entity.GenericEntityNotFoundException) EntityLockedException(org.apache.ofbiz.entity.EntityLockedException)

Aggregations

GenericEntityNotFoundException (org.apache.ofbiz.entity.GenericEntityNotFoundException)5 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)3 ModelEntity (org.apache.ofbiz.entity.model.ModelEntity)3 ModelField (org.apache.ofbiz.entity.model.ModelField)3 ModelViewEntity (org.apache.ofbiz.entity.model.ModelViewEntity)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 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 StringWriter (java.io.StringWriter)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 Timestamp (java.sql.Timestamp)1 HashMap (java.util.HashMap)1 LinkedList (java.util.LinkedList)1 TreeSet (java.util.TreeSet)1