Search in sources :

Example 1 with NucleusDataStoreException

use of org.datanucleus.exceptions.NucleusDataStoreException in project datanucleus-rdbms by datanucleus.

the class AbstractLargeBinaryRDBMSMapping method getObjectForBytes.

protected Object getObjectForBytes(byte[] bytes, int param) {
    String typeName = getJavaTypeMapping().getType();
    if (getJavaTypeMapping() instanceof TypeConverterMapping) {
        // Using TypeConverterMapping so use the datastore type for the converter
        TypeConverter conv = ((TypeConverterMapping) getJavaTypeMapping()).getTypeConverter();
        Class datastoreType = storeMgr.getNucleusContext().getTypeManager().getDatastoreTypeForTypeConverter(conv, getJavaTypeMapping().getJavaType());
        typeName = datastoreType.getName();
    }
    // Use Java serialisation, else byte-streaming, and if not determined then Java serialisation
    if (getJavaTypeMapping().isSerialised()) {
        // Serialised field so just perform basic Java deserialisation for retrieval
        try {
            BlobImpl blob = new BlobImpl(bytes);
            return blob.getObject();
        } catch (SQLException sqle) {
            // Impossible (JDK 1.6 use of free())
            return null;
        }
    } else if (typeName.equals(ClassNameConstants.BOOLEAN_ARRAY)) {
        return TypeConversionHelper.getBooleanArrayFromByteArray(bytes);
    } else if (typeName.equals(ClassNameConstants.BYTE_ARRAY)) {
        return bytes;
    } else if (typeName.equals(ClassNameConstants.CHAR_ARRAY)) {
        return TypeConversionHelper.getCharArrayFromByteArray(bytes);
    } else if (typeName.equals(ClassNameConstants.DOUBLE_ARRAY)) {
        return TypeConversionHelper.getDoubleArrayFromByteArray(bytes);
    } else if (typeName.equals(ClassNameConstants.FLOAT_ARRAY)) {
        return TypeConversionHelper.getFloatArrayFromByteArray(bytes);
    } else if (typeName.equals(ClassNameConstants.INT_ARRAY)) {
        return TypeConversionHelper.getIntArrayFromByteArray(bytes);
    } else if (typeName.equals(ClassNameConstants.LONG_ARRAY)) {
        return TypeConversionHelper.getLongArrayFromByteArray(bytes);
    } else if (typeName.equals(ClassNameConstants.SHORT_ARRAY)) {
        return TypeConversionHelper.getShortArrayFromByteArray(bytes);
    } else if (typeName.equals(ClassNameConstants.JAVA_LANG_BOOLEAN_ARRAY)) {
        return TypeConversionHelper.getBooleanObjectArrayFromByteArray(bytes);
    } else if (typeName.equals(ClassNameConstants.JAVA_LANG_BYTE_ARRAY)) {
        return TypeConversionHelper.getByteObjectArrayFromByteArray(bytes);
    } else if (typeName.equals(ClassNameConstants.JAVA_LANG_CHARACTER_ARRAY)) {
        return TypeConversionHelper.getCharObjectArrayFromByteArray(bytes);
    } else if (typeName.equals(ClassNameConstants.JAVA_LANG_DOUBLE_ARRAY)) {
        return TypeConversionHelper.getDoubleObjectArrayFromByteArray(bytes);
    } else if (typeName.equals(ClassNameConstants.JAVA_LANG_FLOAT_ARRAY)) {
        return TypeConversionHelper.getFloatObjectArrayFromByteArray(bytes);
    } else if (typeName.equals(ClassNameConstants.JAVA_LANG_INTEGER_ARRAY)) {
        return TypeConversionHelper.getIntObjectArrayFromByteArray(bytes);
    } else if (typeName.equals(ClassNameConstants.JAVA_LANG_LONG_ARRAY)) {
        return TypeConversionHelper.getLongObjectArrayFromByteArray(bytes);
    } else if (typeName.equals(ClassNameConstants.JAVA_LANG_SHORT_ARRAY)) {
        return TypeConversionHelper.getShortObjectArrayFromByteArray(bytes);
    } else if (typeName.equals(BigDecimal[].class.getName())) {
        return TypeConversionHelper.getBigDecimalArrayFromByteArray(bytes);
    } else if (typeName.equals(BigInteger[].class.getName())) {
        return TypeConversionHelper.getBigIntegerArrayFromByteArray(bytes);
    } else if (getJavaTypeMapping().getJavaType() != null && getJavaTypeMapping().getJavaType().getName().equals("java.util.BitSet")) {
        return TypeConversionHelper.getBitSetFromBooleanArray(TypeConversionHelper.getBooleanArrayFromByteArray(bytes));
    } else if (getJavaTypeMapping().getJavaType() != null && getJavaTypeMapping().getJavaType().getName().equals("java.awt.image.BufferedImage")) {
        try {
            return ImageIO.read(new ByteArrayInputStream(bytes));
        } catch (IOException e) {
            throw new NucleusDataStoreException(Localiser.msg("055002", "Object", "" + param, column, e.getMessage()), e);
        }
    } else {
        // Fallback to just perform basic Java deserialisation for retrieval
        try {
            BlobImpl blob = new BlobImpl(bytes);
            return blob.getObject();
        } catch (SQLException sqle) {
            // Impossible (JDK 1.6 use of free())
            return null;
        }
    }
}
Also used : TypeConverter(org.datanucleus.store.types.converters.TypeConverter) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) TypeConverterMapping(org.datanucleus.store.rdbms.mapping.java.TypeConverterMapping) SQLException(java.sql.SQLException) ByteArrayInputStream(java.io.ByteArrayInputStream) IOException(java.io.IOException) BigDecimal(java.math.BigDecimal)

Example 2 with NucleusDataStoreException

use of org.datanucleus.exceptions.NucleusDataStoreException in project datanucleus-rdbms by datanucleus.

the class ArrayRDBMSMapping method setObject.

public void setObject(PreparedStatement ps, int param, Object value) {
    try {
        if (value == null) {
            ps.setNull(param, getJDBCType());
        } else {
            Array array = null;
            if (value.getClass().isArray()) {
                // Convert the array into a java.sql.Array
                int numElems = java.lang.reflect.Array.getLength(value);
                Object[] elems = new Object[numElems];
                for (int i = 0; i < numElems; i++) {
                    elems[i] = java.lang.reflect.Array.get(value, i);
                }
                array = ps.getConnection().createArrayOf(arrayElemSqlType, elems);
            } else if (value instanceof Collection) {
                // Convert the collection into a java.sql.Array
                Collection coll = (Collection) value;
                Object[] elems = new Object[coll.size()];
                int i = 0;
                for (Object elem : coll) {
                    elems[i++] = elem;
                }
                array = ps.getConnection().createArrayOf(arrayElemSqlType, elems);
            } else {
                throw new NucleusUserException("We do not support persisting values of type " + value.getClass().getName() + " as an ARRAY." + " Member=" + mapping.getMemberMetaData().getFullFieldName());
            }
            ps.setArray(param, array);
        }
    } catch (SQLException e) {
        throw new NucleusDataStoreException(Localiser.msg("055001", "Object", "" + value, column, e.getMessage()), e);
    }
}
Also used : Array(java.sql.Array) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) SQLException(java.sql.SQLException) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) Collection(java.util.Collection)

Example 3 with NucleusDataStoreException

use of org.datanucleus.exceptions.NucleusDataStoreException in project datanucleus-rdbms by datanucleus.

the class ArrayRDBMSMapping method getObject.

public Object getObject(ResultSet rs, int param) {
    Object value = null;
    try {
        Array arr = rs.getArray(param);
        if (!rs.wasNull()) {
            Object javaArray = arr.getArray();
            int length = java.lang.reflect.Array.getLength(javaArray);
            AbstractMemberMetaData mmd = mapping.getMemberMetaData();
            if (mmd.getType().isArray()) {
                // Copy in to an array of the same type as the member
                value = java.lang.reflect.Array.newInstance(mmd.getType().getComponentType(), length);
                for (int i = 0; i < length; i++) {
                    java.lang.reflect.Array.set(value, i, java.lang.reflect.Array.get(javaArray, i));
                }
            } else if (Collection.class.isAssignableFrom(mmd.getType())) {
                Collection<Object> coll;
                try {
                    Class instanceType = SCOUtils.getContainerInstanceType(mmd.getType(), mmd.getOrderMetaData() != null);
                    coll = (Collection<Object>) instanceType.newInstance();
                } catch (Exception e) {
                    throw new NucleusDataStoreException(e.getMessage(), e);
                }
                for (int i = 0; i < length; i++) {
                    coll.add(java.lang.reflect.Array.get(javaArray, i));
                }
                value = coll;
            } else {
                throw new NucleusUserException("We do not support retrieving values of type " + mmd.getTypeName() + " as an ARRAY." + " Member=" + mapping.getMemberMetaData().getFullFieldName());
            }
        }
    } catch (SQLException e) {
        throw new NucleusDataStoreException(Localiser.msg("055002", "Object", "" + param, column, e.getMessage()), e);
    }
    return value;
}
Also used : Array(java.sql.Array) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) SQLException(java.sql.SQLException) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) Collection(java.util.Collection) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) SQLException(java.sql.SQLException) NucleusUserException(org.datanucleus.exceptions.NucleusUserException)

Example 4 with NucleusDataStoreException

use of org.datanucleus.exceptions.NucleusDataStoreException in project datanucleus-rdbms by datanucleus.

the class OracleClobRDBMSMapping method getString.

public String getString(ResultSet rs, int param) {
    String value = null;
    try {
        char[] cbuf = null;
        java.sql.Clob clob = rs.getClob(param);
        if (clob != null) {
            // Note: Using clob.stringValue() results in StoreManagerTest
            // exception: "java.sql.SQLException: Conversion to String failed"
            StringBuilder sbuf = new StringBuilder();
            Reader reader = clob.getCharacterStream();
            try {
                final int BUFF_SIZE = 4096;
                cbuf = new char[BUFF_SIZE];
                int charsRead = reader.read(cbuf);
                while (-1 != charsRead) {
                    sbuf.append(cbuf, 0, charsRead);
                    java.util.Arrays.fill(cbuf, (char) 0);
                    charsRead = reader.read(cbuf);
                }
            } catch (IOException e) {
                throw new NucleusDataStoreException("Error reading Oracle CLOB object: param = " + param, e);
            } finally {
                try {
                    reader.close();
                } catch (IOException e) {
                    throw new NucleusDataStoreException("Error reading Oracle CLOB object: param = " + param, e);
                }
            }
            value = sbuf.toString();
            if (value.length() == 0) {
                value = null;
            } else if (value.equals(getDatastoreAdapter().getSurrogateForEmptyStrings())) {
                value = "";
            }
        }
    } catch (SQLException e) {
        throw new NucleusDataStoreException(Localiser.msg("055001", "String", "" + param), e);
    }
    return value;
}
Also used : NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) SQLException(java.sql.SQLException) Reader(java.io.Reader) IOException(java.io.IOException)

Example 5 with NucleusDataStoreException

use of org.datanucleus.exceptions.NucleusDataStoreException in project datanucleus-rdbms by datanucleus.

the class OracleClobRDBMSMapping method updateClobColumn.

/**
 * Convenience method to update the contents of a CLOB column.
 * Oracle requires that a CLOB is initialised with EMPTY_CLOB() and then you retrieve
 * the column and update its CLOB value. Performs a statement
 * <pre>
 * SELECT {clobColumn} FROM TABLE WHERE ID=? FOR UPDATE
 * </pre>
 * and then updates the Clob value returned.
 * @param op ObjectProvider of the object
 * @param table Table storing the CLOB column
 * @param mapping Datastore mapping for the CLOB column
 * @param value The value to store in the CLOB
 * @throws NucleusObjectNotFoundException Thrown if an object is not found
 * @throws NucleusDataStoreException Thrown if an error occurs in datastore communication
 */
@SuppressWarnings("deprecation")
public static void updateClobColumn(ObjectProvider op, Table table, DatastoreMapping mapping, String value) {
    ExecutionContext ec = op.getExecutionContext();
    RDBMSStoreManager storeMgr = table.getStoreManager();
    // Don't support join tables yet
    DatastoreClass classTable = (DatastoreClass) table;
    SQLExpressionFactory exprFactory = storeMgr.getSQLExpressionFactory();
    // Generate "SELECT {clobColumn} FROM TABLE WHERE ID=? FOR UPDATE" statement
    SelectStatement sqlStmt = new SelectStatement(storeMgr, table, null, null);
    sqlStmt.setClassLoaderResolver(ec.getClassLoaderResolver());
    sqlStmt.addExtension(SQLStatement.EXTENSION_LOCK_FOR_UPDATE, true);
    SQLTable blobSqlTbl = SQLStatementHelper.getSQLTableForMappingOfTable(sqlStmt, sqlStmt.getPrimaryTable(), mapping.getJavaTypeMapping());
    sqlStmt.select(blobSqlTbl, mapping.getColumn(), null);
    StatementClassMapping mappingDefinition = new StatementClassMapping();
    AbstractClassMetaData cmd = op.getClassMetaData();
    int inputParamNum = 1;
    if (cmd.getIdentityType() == IdentityType.DATASTORE) {
        // Datastore identity value for input
        JavaTypeMapping datastoreIdMapping = classTable.getSurrogateMapping(SurrogateColumnType.DATASTORE_ID, false);
        SQLExpression expr = exprFactory.newExpression(sqlStmt, sqlStmt.getPrimaryTable(), datastoreIdMapping);
        SQLExpression val = exprFactory.newLiteralParameter(sqlStmt, datastoreIdMapping, null, "ID");
        sqlStmt.whereAnd(expr.eq(val), true);
        StatementMappingIndex datastoreIdx = mappingDefinition.getMappingForMemberPosition(SurrogateColumnType.DATASTORE_ID.getFieldNumber());
        if (datastoreIdx == null) {
            datastoreIdx = new StatementMappingIndex(datastoreIdMapping);
            mappingDefinition.addMappingForMember(SurrogateColumnType.DATASTORE_ID.getFieldNumber(), datastoreIdx);
        }
        datastoreIdx.addParameterOccurrence(new int[] { inputParamNum });
    } else if (cmd.getIdentityType() == IdentityType.APPLICATION) {
        // Application identity value(s) for input
        int[] pkNums = cmd.getPKMemberPositions();
        for (int i = 0; i < pkNums.length; i++) {
            AbstractMemberMetaData mmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(pkNums[i]);
            JavaTypeMapping pkMapping = classTable.getMemberMapping(mmd);
            SQLExpression expr = exprFactory.newExpression(sqlStmt, sqlStmt.getPrimaryTable(), pkMapping);
            SQLExpression val = exprFactory.newLiteralParameter(sqlStmt, pkMapping, null, "PK" + i);
            sqlStmt.whereAnd(expr.eq(val), true);
            StatementMappingIndex pkIdx = mappingDefinition.getMappingForMemberPosition(pkNums[i]);
            if (pkIdx == null) {
                pkIdx = new StatementMappingIndex(pkMapping);
                mappingDefinition.addMappingForMember(pkNums[i], pkIdx);
            }
            int[] inputParams = new int[pkMapping.getNumberOfDatastoreMappings()];
            for (int j = 0; j < pkMapping.getNumberOfDatastoreMappings(); j++) {
                inputParams[j] = inputParamNum++;
            }
            pkIdx.addParameterOccurrence(inputParams);
        }
    }
    String textStmt = sqlStmt.getSQLText().toSQL();
    if (op.isEmbedded()) {
        // This mapping is embedded, so navigate back to the real owner since that is the "id" in the table
        ObjectProvider[] embeddedOwners = ec.getOwnersForEmbeddedObjectProvider(op);
        if (embeddedOwners != null) {
            // Just use the first owner
            // TODO Should check if the owner is stored in this table
            op = embeddedOwners[0];
        }
    }
    try {
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        SQLController sqlControl = storeMgr.getSQLController();
        try {
            PreparedStatement ps = sqlControl.getStatementForQuery(mconn, textStmt);
            try {
                // Provide the primary key field(s) to the JDBC statement
                if (cmd.getIdentityType() == IdentityType.DATASTORE) {
                    StatementMappingIndex datastoreIdx = mappingDefinition.getMappingForMemberPosition(SurrogateColumnType.DATASTORE_ID.getFieldNumber());
                    for (int i = 0; i < datastoreIdx.getNumberOfParameterOccurrences(); i++) {
                        classTable.getSurrogateMapping(SurrogateColumnType.DATASTORE_ID, false).setObject(ec, ps, datastoreIdx.getParameterPositionsForOccurrence(i), op.getInternalObjectId());
                    }
                } else if (cmd.getIdentityType() == IdentityType.APPLICATION) {
                    op.provideFields(cmd.getPKMemberPositions(), new ParameterSetter(op, ps, mappingDefinition));
                }
                ResultSet rs = sqlControl.executeStatementQuery(ec, mconn, textStmt, ps);
                try {
                    if (!rs.next()) {
                        throw new NucleusObjectNotFoundException("No such database row", op.getInternalObjectId());
                    }
                    DatastoreAdapter dba = storeMgr.getDatastoreAdapter();
                    int jdbcMajorVersion = dba.getDriverMajorVersion();
                    if (dba.getDatastoreDriverName().equalsIgnoreCase(OracleAdapter.OJDBC_DRIVER_NAME) && jdbcMajorVersion < 10) {
                        // Oracle JDBC drivers version 9 and below use some sh*tty Oracle-specific CLOB type
                        // we have to cast to that, face west, pray whilst saying ommmmmmmmmmm
                        oracle.sql.CLOB clob = (oracle.sql.CLOB) rs.getClob(1);
                        if (clob != null) {
                            // Deprecated but what can you do
                            clob.putString(1, value);
                        }
                    } else {
                        // Oracle JDBC drivers 10 and above supposedly use the JDBC standard class for Clobs
                        java.sql.Clob clob = rs.getClob(1);
                        if (clob != null) {
                            clob.setString(1, value);
                        }
                    }
                } finally {
                    rs.close();
                }
            } finally {
                sqlControl.closeStatement(mconn, ps);
            }
        } finally {
            mconn.release();
        }
    } catch (SQLException e) {
        throw new NucleusDataStoreException("Update of CLOB value failed: " + textStmt, e);
    }
}
Also used : SQLExpressionFactory(org.datanucleus.store.rdbms.sql.expression.SQLExpressionFactory) SQLExpression(org.datanucleus.store.rdbms.sql.expression.SQLExpression) JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) SQLException(java.sql.SQLException) StatementMappingIndex(org.datanucleus.store.rdbms.query.StatementMappingIndex) ParameterSetter(org.datanucleus.store.rdbms.fieldmanager.ParameterSetter) NucleusObjectNotFoundException(org.datanucleus.exceptions.NucleusObjectNotFoundException) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) SQLController(org.datanucleus.store.rdbms.SQLController) SelectStatement(org.datanucleus.store.rdbms.sql.SelectStatement) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) SQLTable(org.datanucleus.store.rdbms.sql.SQLTable) ResultSet(java.sql.ResultSet) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) PreparedStatement(java.sql.PreparedStatement) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager) StatementClassMapping(org.datanucleus.store.rdbms.query.StatementClassMapping) ExecutionContext(org.datanucleus.ExecutionContext) ObjectProvider(org.datanucleus.state.ObjectProvider) DatastoreAdapter(org.datanucleus.store.rdbms.adapter.DatastoreAdapter) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData)

Aggregations

NucleusDataStoreException (org.datanucleus.exceptions.NucleusDataStoreException)288 SQLException (java.sql.SQLException)185 ExecutionContext (org.datanucleus.ExecutionContext)139 ManagedConnection (org.datanucleus.store.connection.ManagedConnection)131 PreparedStatement (java.sql.PreparedStatement)128 SQLController (org.datanucleus.store.rdbms.SQLController)126 ResultSet (java.sql.ResultSet)73 Iterator (java.util.Iterator)43 StatementMappingIndex (org.datanucleus.store.rdbms.query.StatementMappingIndex)38 CollectionAddOperation (org.datanucleus.flush.CollectionAddOperation)34 JavaTypeMapping (org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping)33 ArrayList (java.util.ArrayList)32 RDBMSStoreManager (org.datanucleus.store.rdbms.RDBMSStoreManager)30 Collection (java.util.Collection)27 CollectionRemoveOperation (org.datanucleus.flush.CollectionRemoveOperation)26 StatementClassMapping (org.datanucleus.store.rdbms.query.StatementClassMapping)24 List (java.util.List)23 ObjectProvider (org.datanucleus.state.ObjectProvider)22 SelectStatement (org.datanucleus.store.rdbms.sql.SelectStatement)22 MappedDatastoreException (org.datanucleus.store.rdbms.exceptions.MappedDatastoreException)21