Search in sources :

Example 1 with GenericModelException

use of org.apache.ofbiz.entity.GenericModelException 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 2 with GenericModelException

use of org.apache.ofbiz.entity.GenericModelException 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 "";
}
Also used : ModelKeyMap(org.apache.ofbiz.entity.model.ModelKeyMap) GenericModelException(org.apache.ofbiz.entity.GenericModelException) ModelField(org.apache.ofbiz.entity.model.ModelField) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ModelViewEntity(org.apache.ofbiz.entity.model.ModelViewEntity) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity)

Example 3 with GenericModelException

use of org.apache.ofbiz.entity.GenericModelException 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);
    }
}
Also used : GenericModelException(org.apache.ofbiz.entity.GenericModelException) SQLException(java.sql.SQLException) ModelFieldTypeReader(org.apache.ofbiz.entity.model.ModelFieldTypeReader) Reader(java.io.Reader) SerialBlob(javax.sql.rowset.serial.SerialBlob) ResultSetMetaData(java.sql.ResultSetMetaData) ModelViewEntity(org.apache.ofbiz.entity.model.ModelViewEntity) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) GenericDataSourceException(org.apache.ofbiz.entity.GenericDataSourceException) SerialBlob(javax.sql.rowset.serial.SerialBlob) Blob(java.sql.Blob) IOException(java.io.IOException) SerialClob(javax.sql.rowset.serial.SerialClob) SQLException(java.sql.SQLException) GenericDataSourceException(org.apache.ofbiz.entity.GenericDataSourceException) GenericNotImplementedException(org.apache.ofbiz.entity.GenericNotImplementedException) GenericModelException(org.apache.ofbiz.entity.GenericModelException) IOException(java.io.IOException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) BigDecimal(java.math.BigDecimal) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ModelFieldType(org.apache.ofbiz.entity.model.ModelFieldType) Clob(java.sql.Clob) SerialClob(javax.sql.rowset.serial.SerialClob)

Example 4 with GenericModelException

use of org.apache.ofbiz.entity.GenericModelException 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();
}
Also used : GenericModelException(org.apache.ofbiz.entity.GenericModelException) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) ModelKeyMap(org.apache.ofbiz.entity.model.ModelKeyMap) ModelField(org.apache.ofbiz.entity.model.ModelField) TreeSet(java.util.TreeSet) ModelViewEntity(org.apache.ofbiz.entity.model.ModelViewEntity) Iterator(java.util.Iterator) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity)

Example 5 with GenericModelException

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

the class SqlJdbcUtil method setValue.

public static <T> void setValue(SQLProcessor sqlP, ModelField modelField, String entityName, Object fieldValue, ModelFieldTypeReader modelFieldTypeReader) throws GenericEntityException {
    ModelFieldType mft = modelFieldTypeReader.getModelFieldType(modelField.getType());
    if (mft == null) {
        throw new GenericModelException("GenericDAO.getValue: definition fieldType " + modelField.getType() + " not found, cannot setValue for field " + entityName + "." + modelField.getName() + ".");
    }
    // if the value is the GenericEntity.NullField, treat as null
    if (fieldValue == GenericEntity.NULL_FIELD) {
        fieldValue = null;
    }
    // ----- Try out the new handler code -----
    ModelField.EncryptMethod encryptMethod = modelField.getEncryptMethod();
    if (encryptMethod.isEncrypted()) {
        fieldValue = sqlP.getDelegator().encryptFieldValue(entityName, encryptMethod, fieldValue);
    }
    JdbcValueHandler<T> handler = UtilGenerics.cast(mft.getJdbcValueHandler());
    if (handler != null) {
        try {
            sqlP.setValue(handler, handler.getJavaClass().cast(fieldValue));
            return;
        } catch (SQLException e) {
            throw new GenericDataSourceException("SQL Exception while setting value on field [" + modelField.getName() + "] of entity " + entityName + ": ", e);
        }
    } else {
        Debug.logWarning("JdbcValueHandler not found for java-type " + mft.getJavaType() + ", falling back on switch statement. Entity = " + modelField.getModelEntity().getEntityName() + ", field = " + modelField.getName() + ".", module);
    }
    // ------------------------------------------
    String fieldType = mft.getJavaType();
    if (fieldValue != null) {
        if (!ObjectType.instanceOf(fieldValue, fieldType)) {
            // this is only an info level message because under normal operation for most JDBC
            // drivers this will be okay, but if not then the JDBC driver will throw an exception
            // and when lower debug levels are on this should help give more info on what happened
            String fieldClassName = fieldValue.getClass().getName();
            if (fieldValue instanceof byte[]) {
                fieldClassName = "byte[]";
            }
            if (Debug.verboseOn())
                Debug.logVerbose("type of field " + entityName + "." + modelField.getName() + " is " + fieldClassName + ", was expecting " + mft.getJavaType() + "; this may " + "indicate an error in the configuration or in the class, and may result " + "in an SQL-Java data conversion error. Will use the real field type: " + fieldClassName + ", not the definition.", module);
            fieldType = fieldClassName;
        }
    }
    try {
        int typeValue = getType(fieldType);
        switch(typeValue) {
            case 1:
                sqlP.setValue((String) fieldValue);
                break;
            case 2:
                sqlP.setValue((java.sql.Timestamp) fieldValue);
                break;
            case 3:
                sqlP.setValue((java.sql.Time) fieldValue);
                break;
            case 4:
                sqlP.setValue((java.sql.Date) fieldValue);
                break;
            case 5:
                sqlP.setValue((java.lang.Integer) fieldValue);
                break;
            case 6:
                sqlP.setValue((java.lang.Long) fieldValue);
                break;
            case 7:
                sqlP.setValue((java.lang.Float) fieldValue);
                break;
            case 8:
                sqlP.setValue((java.lang.Double) fieldValue);
                break;
            case 9:
                sqlP.setValue((java.math.BigDecimal) fieldValue);
                break;
            case 10:
                sqlP.setValue((java.lang.Boolean) fieldValue);
                break;
            case 11:
                sqlP.setBinaryStream(fieldValue);
                break;
            case 12:
                if (fieldValue instanceof byte[]) {
                    sqlP.setBytes((byte[]) fieldValue);
                } else if (fieldValue instanceof ByteBuffer) {
                    sqlP.setBytes(((ByteBuffer) fieldValue).array());
                } else {
                    sqlP.setValue((java.sql.Blob) fieldValue);
                }
                break;
            case 13:
                sqlP.setValue((java.sql.Clob) fieldValue);
                break;
            case 14:
                if (fieldValue != null) {
                    sqlP.setValue(new java.sql.Date(((java.util.Date) fieldValue).getTime()));
                } else {
                    sqlP.setValue((java.sql.Date) null);
                }
                break;
            case 15:
                sqlP.setValue(UtilGenerics.<Collection<?>>cast(fieldValue));
                break;
        }
    } catch (GenericNotImplementedException e) {
        throw new GenericNotImplementedException("Not Implemented Exception while setting value on field [" + modelField.getName() + "] of entity " + entityName + ": " + e.toString(), e);
    } catch (SQLException sqle) {
        throw new GenericDataSourceException("SQL Exception while setting value on field [" + modelField.getName() + "] of entity " + entityName + ": ", sqle);
    }
}
Also used : GenericModelException(org.apache.ofbiz.entity.GenericModelException) SerialBlob(javax.sql.rowset.serial.SerialBlob) Blob(java.sql.Blob) SQLException(java.sql.SQLException) GenericNotImplementedException(org.apache.ofbiz.entity.GenericNotImplementedException) ByteBuffer(java.nio.ByteBuffer) ModelField(org.apache.ofbiz.entity.model.ModelField) ModelFieldType(org.apache.ofbiz.entity.model.ModelFieldType) GenericDataSourceException(org.apache.ofbiz.entity.GenericDataSourceException)

Aggregations

GenericModelException (org.apache.ofbiz.entity.GenericModelException)7 ModelField (org.apache.ofbiz.entity.model.ModelField)5 ModelViewEntity (org.apache.ofbiz.entity.model.ModelViewEntity)5 ModelEntity (org.apache.ofbiz.entity.model.ModelEntity)4 LinkedList (java.util.LinkedList)3 TreeSet (java.util.TreeSet)3 GenericNotImplementedException (org.apache.ofbiz.entity.GenericNotImplementedException)3 Blob (java.sql.Blob)2 SQLException (java.sql.SQLException)2 HashSet (java.util.HashSet)2 SerialBlob (javax.sql.rowset.serial.SerialBlob)2 GenericDataSourceException (org.apache.ofbiz.entity.GenericDataSourceException)2 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)2 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)2 SQLProcessor (org.apache.ofbiz.entity.jdbc.SQLProcessor)2 ModelFieldType (org.apache.ofbiz.entity.model.ModelFieldType)2 ModelKeyMap (org.apache.ofbiz.entity.model.ModelKeyMap)2 IOException (java.io.IOException)1 Reader (java.io.Reader)1 BigDecimal (java.math.BigDecimal)1