Example usage for java.sql Types BOOLEAN

List of usage examples for java.sql Types BOOLEAN

Introduction

In this page you can find the example usage for java.sql Types BOOLEAN.

Prototype

int BOOLEAN

To view the source code for java.sql Types BOOLEAN.

Click Source Link

Document

The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type BOOLEAN.

Usage

From source file:org.apache.jmeter.protocol.jdbc.AbstractJDBCTestElement.java

private void setArgument(PreparedStatement pstmt, String argument, int targetSqlType, int index)
        throws SQLException {
    switch (targetSqlType) {
    case Types.INTEGER:
        pstmt.setInt(index, Integer.parseInt(argument));
        break;//from   ww w  .  j  a va 2 s  .c o m
    case Types.DECIMAL:
    case Types.NUMERIC:
        pstmt.setBigDecimal(index, new BigDecimal(argument));
        break;
    case Types.DOUBLE:
    case Types.FLOAT:
        pstmt.setDouble(index, Double.parseDouble(argument));
        break;
    case Types.CHAR:
    case Types.LONGVARCHAR:
    case Types.VARCHAR:
        pstmt.setString(index, argument);
        break;
    case Types.BIT:
    case Types.BOOLEAN:
        pstmt.setBoolean(index, Boolean.parseBoolean(argument));
        break;
    case Types.BIGINT:
        pstmt.setLong(index, Long.parseLong(argument));
        break;
    case Types.DATE:
        pstmt.setDate(index, Date.valueOf(argument));
        break;
    case Types.REAL:
        pstmt.setFloat(index, Float.parseFloat(argument));
        break;
    case Types.TINYINT:
        pstmt.setByte(index, Byte.parseByte(argument));
        break;
    case Types.SMALLINT:
        pstmt.setShort(index, Short.parseShort(argument));
        break;
    case Types.TIMESTAMP:
        pstmt.setTimestamp(index, Timestamp.valueOf(argument));
        break;
    case Types.TIME:
        pstmt.setTime(index, Time.valueOf(argument));
        break;
    case Types.BINARY:
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
        pstmt.setBytes(index, argument.getBytes());
        break;
    case Types.NULL:
        pstmt.setNull(index, targetSqlType);
        break;
    default:
        pstmt.setObject(index, argument, targetSqlType);
    }
}

From source file:org.apache.ode.bpel.extvar.jdbc.JdbcExternalVariableModule.java

private Object downcastValue(Object value, int dataType) {
    if (value == null) {
        return null;
    }/*w  ww  .j av  a  2 s  .  c  o m*/
    // Try down casting the value as per its column type.
    try {
        // Some JDBC 4.0 types have been ignored to avoid compilation errors
        switch (dataType) {
        case Types.ARRAY:
            break;
        case Types.BIGINT:
            if (!(value instanceof BigInteger)) {
                value = new BigDecimal(value.toString()).longValue();
            }
            break;
        case Types.BINARY:
            break;
        case Types.BIT:
            if (!(value instanceof Boolean)) {
                value = new Boolean(value.toString());
            }
            break;
        case Types.BLOB:
            break;
        case Types.BOOLEAN:
            if (!(value instanceof Boolean)) {
                value = new Boolean(value.toString());
            }
            break;
        case Types.CHAR:
            break;
        case Types.CLOB:
            break;
        case Types.DATALINK:
            break;
        case Types.DATE:
            break;
        case Types.DECIMAL:
            //ODE-872: Oracle 9g and 10g has problems with BigDecimal on Java1.5
            value = new BigDecimal(new BigDecimal(value.toString()).toPlainString());
            break;
        case Types.DISTINCT:
            break;
        case Types.DOUBLE:
            if (!(value instanceof Double)) {
                value = Double.valueOf(value.toString()).doubleValue();
            }
            break;
        case Types.FLOAT:
            if (!(value instanceof Float)) {
                value = Float.valueOf(value.toString()).floatValue();
            }
            break;
        case Types.INTEGER:
            if (!(value instanceof Integer)) {
                value = Double.valueOf(value.toString()).intValue();
            }
            break;
        case Types.JAVA_OBJECT:
            break;
        //          case Types.LONGNVARCHAR:
        //             break;
        case Types.LONGVARBINARY:
            break;
        case Types.LONGVARCHAR:
            break;
        //          case Types.NCHAR:
        //             break;
        //          case Types.NCLOB:
        //             break;
        case Types.NUMERIC:
            //ODE-872: Oracle 9g and 10g has problems with BigDecimal on Java1.5
            value = new BigDecimal(new BigDecimal(value.toString()).toPlainString());
            break;
        //          case Types.NVARCHAR:
        //             break;
        case Types.OTHER:
            break;
        case Types.REAL:
            if (!(value instanceof Double)) {
                value = Float.valueOf(value.toString()).floatValue();
            }
            break;
        case Types.REF:
            break;
        //          case Types.ROWID:
        //             break;
        case Types.SMALLINT:
            if (!(value instanceof Short)) {
                value = new Short(value.toString()).shortValue();
            }
            break;
        //          case Types.SQLXML:
        //             break;
        case Types.STRUCT:
            break;
        case Types.TIME:
            break;
        case Types.TIMESTAMP:
            break;
        case Types.TINYINT:
            if (!(value instanceof Short)) {
                value = new Short(value.toString()).shortValue();
            }
            break;
        case Types.VARBINARY:
            break;
        case Types.VARCHAR:
            break;
        default:
            break;
        }
    } catch (Exception e) {
        // couldn't cast... let's just use original value object
    }
    return value;
}

From source file:org.wso2.carbon.event.output.adaptor.mysql.MysqlEventAdaptorType.java

private TableInfo initializeDatabaseTableInfo(String tableName, String executionMode, String updateColumnKeys,
        Object message, OutputEventAdaptorConfiguration adaptorConfig) throws SQLException {
    TableInfo tableInfo = new TableInfo();
    tableInfo.setTableName(tableName);//  ww  w  .j a v  a 2 s  .c o  m
    if (resourceBundle.getString(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_EXECUTION_MODE_UPDATE)
            .equalsIgnoreCase(executionMode)) {
        tableInfo.setUpdateMode(true);
    }
    Connection con = null;
    Statement stmt = null;

    try {
        DataSource dataSource = pooledDataSources.get(adaptorConfig.getOutputProperties()
                .get(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_DATASOURCE_NAME));
        if (dataSource == null) {
            CarbonDataSource carbonDataSource = EventAdaptorValueHolder.getDataSourceService()
                    .getDataSource(adaptorConfig.getOutputProperties()
                            .get(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_DATASOURCE_NAME));
            if (carbonDataSource == null) {
                throw new OutputEventAdaptorEventProcessingException(
                        "There is no any data-source found called : " + adaptorConfig.getOutputProperties()
                                .get(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_DATASOURCE_NAME));
            } else {
                dataSource = (DataSource) carbonDataSource.getDSObject();
                pooledDataSources.put(adaptorConfig, dataSource);
            }
        }

        con = dataSource.getConnection();
        String databaseName = con.getCatalog();
        tableInfo.setDatabaseName(databaseName);

        // create the table.
        StringBuilder statementBuilder = new StringBuilder("CREATE TABLE IF NOT EXISTS ");
        statementBuilder.append(databaseName + "." + tableName);
        statementBuilder.append(" (");
        boolean appendComma = false;
        for (Map.Entry<String, Object> entry : (((Map<String, Object>) message).entrySet())) {
            if (appendComma) {
                statementBuilder.append(",");
            } else {
                appendComma = true;
            }
            statementBuilder.append(entry.getKey()).append("  ");
            if (entry.getValue() instanceof Integer) {
                statementBuilder.append("INT");
            } else if (entry.getValue() instanceof Long) {
                statementBuilder.append("BIGINT");
            } else if (entry.getValue() instanceof Float) {
                statementBuilder.append("FLOAT");
            } else if (entry.getValue() instanceof Double) {
                statementBuilder.append("DOUBLE");
            } else if (entry.getValue() instanceof String) {
                statementBuilder.append("VARCHAR(255)");
            } else if (entry.getValue() instanceof Boolean) {
                statementBuilder.append("BOOL");
            }
        }
        statementBuilder.append(")");

        stmt = con.createStatement();
        stmt.execute("CREATE SCHEMA IF NOT EXISTS " + databaseName);
        stmt.executeUpdate(statementBuilder.toString());

        ArrayList<Attribute> tableInsertColumnList = new ArrayList<Attribute>();
        statementBuilder = new StringBuilder("INSERT INTO ");
        statementBuilder.append(databaseName + "." + tableName);
        statementBuilder.append(" ( ");

        StringBuilder valuePositionsBuilder = new StringBuilder("");

        appendComma = false;
        DatabaseMetaData databaseMetaData = con.getMetaData();
        ResultSet rs = databaseMetaData.getColumns(databaseName, null, tableName, null);
        while (rs.next()) {
            AttributeType type = null;
            int colType = rs.getInt("DATA_TYPE");
            switch (colType) {
            case Types.VARCHAR:
                type = AttributeType.STRING;
                break;
            case Types.INTEGER:
                type = AttributeType.INT;
                break;
            case Types.BIGINT:
                type = AttributeType.LONG;
                break;
            case Types.DOUBLE:
                type = AttributeType.DOUBLE;
                break;
            case Types.FLOAT:
                type = AttributeType.FLOAT;
                break;
            case Types.TINYINT:
            case Types.BOOLEAN:
            case MysqlEventAdaptorConstants.TINYINT_MYSQL_VALUE:
                type = AttributeType.BOOL;
                break;

            }
            Attribute attribute = new Attribute(rs.getString("COLUMN_NAME"), type);
            tableInsertColumnList.add(attribute);

            if (appendComma) {
                statementBuilder.append(",");
                valuePositionsBuilder.append(",");
            } else {
                appendComma = true;
            }
            statementBuilder.append(attribute.getName());
            valuePositionsBuilder.append("?");
        }
        statementBuilder.append(") VALUES (");
        statementBuilder.append(valuePositionsBuilder.toString());
        statementBuilder.append(")");
        tableInfo.setPreparedInsertStatement(statementBuilder.toString());
        tableInfo.setInsertColumnOrder(tableInsertColumnList);

        if (executionMode.equalsIgnoreCase(
                resourceBundle.getString(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_EXECUTION_MODE_UPDATE))) {

            // existence check query.
            StringBuilder existenceQueryBuilder = new StringBuilder("SELECT 1 FROM ");
            existenceQueryBuilder.append(databaseName + "." + tableName);
            existenceQueryBuilder.append(" WHERE ");
            String[] queryAttributes = updateColumnKeys.trim().split(",");
            ArrayList<Attribute> queryAttributeList = new ArrayList<Attribute>(queryAttributes.length);

            for (int i = 0; i < queryAttributes.length; i++) {
                if (i > 0) {
                    existenceQueryBuilder.append(" AND ");
                }
                existenceQueryBuilder.append(queryAttributes[i]);
                existenceQueryBuilder.append(" = ? ");
                for (Attribute at : tableInfo.getInsertColumnOrder()) {
                    if (queryAttributes[i].equalsIgnoreCase(at.getName())) {
                        queryAttributeList.add(at);
                        break;
                    }
                }
            }
            tableInfo.setExistenceCheckColumnOrder(queryAttributeList);
            tableInfo.setPreparedExistenceCheckStatement(existenceQueryBuilder.toString());

            // update query.
            StringBuilder updateQueryBuilder = new StringBuilder("UPDATE  ");
            ArrayList<Attribute> updateAttributes = new ArrayList<Attribute>();
            updateQueryBuilder.append(tableInfo.getDatabaseName() + "." + tableInfo.getTableName());
            updateQueryBuilder.append(" SET ");
            appendComma = false;
            for (Attribute at : tableInfo.getInsertColumnOrder()) {
                if (!tableInfo.getExistenceCheckColumnOrder().contains(at)) {
                    if (appendComma) {
                        updateQueryBuilder.append(" , ");
                    }
                    updateQueryBuilder.append(at.getName());
                    updateQueryBuilder.append(" = ? ");
                    updateAttributes.add(at);
                    appendComma = true;
                }
            }
            updateQueryBuilder.append(" WHERE ");
            boolean appendAnd = false;
            for (Attribute at : tableInfo.getExistenceCheckColumnOrder()) {
                if (appendAnd) {
                    updateQueryBuilder.append(" AND ");
                }
                updateQueryBuilder.append(at.getName());
                updateQueryBuilder.append(" = ? ");
                updateAttributes.add(at);
                appendAnd = true;
            }
            tableInfo.setUpdateColumnOrder(updateAttributes);
            tableInfo.setPreparedUpdateStatement(updateQueryBuilder.toString());

        }
        return tableInfo;
    } catch (SQLException e) {
        pooledDataSources.remove(adaptorConfig.getOutputProperties()
                .get(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_DATASOURCE_NAME));
        log.error("error while initializing the table", e);
    } catch (DataSourceException e) {
        pooledDataSources.remove(adaptorConfig.getOutputProperties()
                .get(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_DATASOURCE_NAME));
        log.error("error while accessing the datasource:", e);
    } finally {
        cleanupConnections(stmt, con);
    }
    return null;
}

From source file:org.jumpmind.metl.core.runtime.component.DataDiff.java

protected void createDatabase() {
    if (databasePlatform == null) {
        ResettableBasicDataSource ds = new ResettableBasicDataSource();
        ds.setDriverClassName(Driver.class.getName());
        ds.setMaxActive(1);/*w  w  w. j av  a  2 s.c  o  m*/
        ds.setInitialSize(1);
        ds.setMinIdle(1);
        ds.setMaxIdle(1);
        databaseName = UUID.randomUUID().toString();
        if (inMemoryCompare) {
            ds.setUrl("jdbc:h2:mem:" + databaseName);
        } else {
            ds.setUrl("jdbc:h2:file:./" + databaseName);
        }
        databasePlatform = JdbcDatabasePlatformFactory.createNewPlatformInstance(ds, new SqlTemplateSettings(),
                true, false);

        Model inputModel = context.getFlowStep().getComponent().getInputModel();
        List<ModelEntity> entities = inputModel.getModelEntities();
        for (ModelEntity entity : entities) {
            Table table = new Table();
            table.setName(entity.getName() + "_1");
            List<ModelAttribute> attributes = entity.getModelAttributes();
            for (ModelAttribute attribute : attributes) {
                DataType dataType = attribute.getDataType();
                Column column = new Column(attribute.getName());
                if (dataType.isNumeric()) {
                    column.setTypeCode(Types.DECIMAL);
                } else if (dataType.isBoolean()) {
                    column.setTypeCode(Types.BOOLEAN);
                } else if (dataType.isTimestamp()) {
                    column.setTypeCode(Types.TIMESTAMP);
                } else if (dataType.isBinary()) {
                    column.setTypeCode(Types.BLOB);
                } else {
                    column.setTypeCode(Types.LONGVARCHAR);
                }

                column.setPrimaryKey(attribute.isPk());
                table.addColumn(column);
            }
            alterCaseToMatchLogicalCase(table);
            databasePlatform.createTables(false, false, table);

            table.setName(entity.getName().toUpperCase() + "_2");
            databasePlatform.createTables(false, false, table);

        }

        log(LogLevel.INFO, "Creating databasePlatform with the following url: %s", ds.getUrl());
    }
}

From source file:org.jumpmind.db.platform.AbstractDatabasePlatform.java

protected Object getObjectValue(String value, Column column, BinaryEncoding encoding, boolean useVariableDates,
        boolean fitToColumn) throws DecoderException {
    Object objectValue = value;// ww w.ja v  a  2 s .c o  m
    int type = column.getMappedTypeCode();
    if ((value == null || (getDdlBuilder().getDatabaseInfo().isEmptyStringNulled() && value.equals("")))
            && column.isRequired() && column.isOfTextType()) {
        objectValue = REQUIRED_FIELD_NULL_SUBSTITUTE;
    }
    if (value != null) {
        if (type == Types.DATE || type == Types.TIMESTAMP || type == Types.TIME) {
            objectValue = parseDate(type, value, useVariableDates);
        } else if (type == Types.CHAR) {
            String charValue = value.toString();
            if ((StringUtils.isBlank(charValue)
                    && getDdlBuilder().getDatabaseInfo().isBlankCharColumnSpacePadded())
                    || (StringUtils.isNotBlank(charValue)
                            && getDdlBuilder().getDatabaseInfo().isNonBlankCharColumnSpacePadded())) {
                objectValue = StringUtils.rightPad(value.toString(), column.getSizeAsInt(), ' ');
            }
        } else if (type == Types.BIGINT) {
            objectValue = parseBigInteger(value);
        } else if (type == Types.INTEGER || type == Types.SMALLINT || type == Types.BIT
                || type == Types.TINYINT) {
            objectValue = parseInteger(value);
        } else if (type == Types.NUMERIC || type == Types.DECIMAL || type == Types.FLOAT || type == Types.DOUBLE
                || type == Types.REAL) {
            objectValue = parseBigDecimal(value);
        } else if (type == Types.BOOLEAN) {
            objectValue = value.equals("1") ? Boolean.TRUE : Boolean.FALSE;
        } else if (!(column.getJdbcTypeName() != null
                && column.getJdbcTypeName().toUpperCase().contains(TypeMap.GEOMETRY))
                && !(column.getJdbcTypeName() != null
                        && column.getJdbcTypeName().toUpperCase().contains(TypeMap.GEOGRAPHY))
                && (type == Types.BLOB || type == Types.LONGVARBINARY || type == Types.BINARY
                        || type == Types.VARBINARY ||
                        // SQLServer ntext type
                        type == -10)) {
            if (encoding == BinaryEncoding.NONE) {
                objectValue = value.getBytes();
            } else if (encoding == BinaryEncoding.BASE64) {
                objectValue = Base64.decodeBase64(value.getBytes());
            } else if (encoding == BinaryEncoding.HEX) {
                objectValue = Hex.decodeHex(value.toCharArray());
            }
        } else if (type == Types.ARRAY) {
            objectValue = createArray(column, value);
        }
    }
    if (objectValue instanceof String) {
        String stringValue = cleanTextForTextBasedColumns((String) objectValue);
        int size = column.getSizeAsInt();
        if (fitToColumn && size > 0 && stringValue.length() > size) {
            stringValue = stringValue.substring(0, size);
        }
        objectValue = stringValue;
    }

    return objectValue;

}

From source file:org.apache.cassandra.cql.jdbc.HandleObjects.java

public static final ByteBuffer makeBytes(Object object, int baseType, int scaleOrLength) throws SQLException {
    Class<? extends Object> objectClass = object.getClass();
    boolean isCollection = (Collection.class.isAssignableFrom(objectClass));
    int targetSqlType = isCollection ? Types.OTHER : baseType;
    // Type check first
    switch (targetSqlType) {
    case Types.TINYINT:
        // Only Numeric classes, Strings and Booleans are supported for transformation to TINYINT
        if (!(objectClass == String.class || objectClass == Boolean.class
                || Number.class.isAssignableFrom(object.getClass())))
            throw makeBadMapping(objectClass, STR_BOOL_NUMERIC, "TINYINT");
        break;/*from www  .  ja v a2  s.c  o  m*/

    case Types.SMALLINT:
        // Only Numeric classes, Strings and Booleans are supported for transformation to SMALLINT
        if (!(objectClass == String.class || objectClass == Boolean.class
                || Number.class.isAssignableFrom(object.getClass())))
            throw makeBadMapping(objectClass, STR_BOOL_NUMERIC, "SMALLINT");
        break;

    case Types.INTEGER:
        // Only Numeric classes, Strings and Booleans are supported for transformation to INTEGER
        if (!(objectClass == String.class || objectClass == Boolean.class
                || Number.class.isAssignableFrom(object.getClass())))
            throw makeBadMapping(objectClass, STR_BOOL_NUMERIC, "INTEGER");
        break;

    case Types.BIGINT:
        // Only Numeric classes, Strings and Booleans are supported for transformation to BIGINT
        if (!(objectClass == String.class || objectClass == Boolean.class
                || Number.class.isAssignableFrom(object.getClass())))
            throw makeBadMapping(objectClass, STR_BOOL_NUMERIC, "BIGINT");
        break;

    case Types.REAL:
    case Types.FLOAT:
    case Types.DOUBLE:
    case Types.DECIMAL:
        // Only Numeric classes Strings and Booleans are supported for transformation to REAL,FLOAT,DOUBLE,DECIMAL
        if (!(objectClass == String.class || objectClass == Boolean.class
                || Number.class.isAssignableFrom(object.getClass())))
            throw makeBadMapping(objectClass, STR_BOOL_NUMERIC, "the floating point types");
        break;

    case Types.NUMERIC:
        //NB This as a special case variation for Cassandra!! NUMERIC is transformed to java BigInteger (varint CQL type)
        //
        // Only Numeric classes Strings and Booleans are supported for transformation to NUMERIC
        if (!(objectClass == String.class || objectClass == Boolean.class
                || Number.class.isAssignableFrom(object.getClass())))
            throw makeBadMapping(objectClass, STR_BOOL_NUMERIC, "NUMERIC");
        break;

    case Types.BIT:
        // Only Numeric classes Strings and Booleans are supported for transformation to BIT
        if (!(objectClass == String.class || objectClass == Boolean.class
                || Number.class.isAssignableFrom(object.getClass())))
            throw makeBadMapping(objectClass, STR_BOOL_NUMERIC, "BIT");
        break;

    case Types.BOOLEAN:
        // Only Numeric classes Strings and Booleans are supported for transformation to BOOLEAN
        if (!(objectClass == String.class || objectClass == Boolean.class
                || Number.class.isAssignableFrom(object.getClass())))
            throw makeBadMapping(objectClass, STR_BOOL_NUMERIC, "BOOLEAN");
        break;

    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
    case Types.NVARCHAR:
    case Types.LONGNVARCHAR:
        if (!objectClass.isAssignableFrom(String.class))
            throw makeBadMapping(objectClass, "String", "the various VARCHAR types");
        break;

    case Types.BINARY:
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
        if (!(objectClass.isAssignableFrom(ByteBuffer.class) || objectClass.getSimpleName().equals("byte[]")))
            throw makeBadMapping(objectClass, "ByteBuffer or byte[]", "the BINARY Types");
        break;

    case Types.DATE:
        if (!(objectClass == String.class || objectClass == java.util.Date.class || objectClass == Date.class
                || objectClass == Timestamp.class))
            throw makeBadMapping(objectClass, "String, Date(java and sql) or Timestamp types", "DATE");
        break;

    case Types.TIME:
        if (!(objectClass == String.class || objectClass == java.util.Date.class || objectClass == Time.class
                || objectClass == Timestamp.class))
            throw makeBadMapping(objectClass, "String, Date (java), Time or Timestamp types", "TIME");
        break;

    case Types.TIMESTAMP:
        if (!(objectClass == String.class || objectClass == java.util.Date.class || objectClass == Date.class
                || objectClass == Timestamp.class))
            throw makeBadMapping(objectClass, "String, Date(java and sql) or Timestamp types", "TIMESTAMP");
        break;

    case Types.DATALINK:
        if (objectClass != URL.class)
            throw makeBadMapping(objectClass, "a URL type", "DATALINK");
        break;

    case Types.JAVA_OBJECT:
        break;

    case Types.OTHER:
        // Only Collection classes for transformation to OTHER
        if (!(List.class.isAssignableFrom(object.getClass()) || Set.class.isAssignableFrom(object.getClass())
                || Map.class.isAssignableFrom(object.getClass())))
            throw makeBadMapping(objectClass, STR_BOOL_NUMERIC, "OTHER");
        break;

    case Types.ROWID:
        if (objectClass != RowId.class)
            throw makeBadMapping(objectClass, "a RowId type", "ROWID");
        break;

    default:
        throw new SQLNonTransientException("Unsupported transformation to Jdbc Type: " + targetSqlType);
    }

    // see if we can map to an supported Type
    switch (targetSqlType) {
    case Types.BIT:
        BigInteger bitvalue = objectToBITorTINYINTorSMALLINTorNUMERIC(objectClass, object);
        assert bitvalue != null;
        return JdbcInteger.instance.decompose((bitvalue == BigInteger.ZERO) ? BigInteger.ZERO : BigInteger.ONE);

    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.NUMERIC:
        BigInteger varint = objectToBITorTINYINTorSMALLINTorNUMERIC(objectClass, object);
        assert varint != null;
        return JdbcInteger.instance.decompose(varint);

    case Types.INTEGER:
        Integer value = objectToINTEGER(objectClass, object);
        assert value != null;
        return JdbcInt32.instance.decompose(value);

    case Types.BIGINT:
        Long longvalue = objectToBIGINT(objectClass, object);
        assert longvalue != null;
        return JdbcLong.instance.decompose(longvalue);

    case Types.BOOLEAN:
        Boolean bool = objectToBOOLEAN(objectClass, object);
        assert bool != null;
        return JdbcBoolean.instance.decompose(bool);

    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
    case Types.NVARCHAR:
    case Types.LONGNVARCHAR:
        return ByteBufferUtil.bytes((String) object);

    case Types.BINARY:
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
        if (objectClass.isAssignableFrom(ByteBuffer.class)) {
            return ((ByteBuffer) object);
        } else if (objectClass.getSimpleName().equals("byte[]")) {
            return ByteBuffer.wrap((byte[]) object);
        } else
            return null; // this should not happen

    case Types.DATE:
    case Types.TIME:
    case Types.TIMESTAMP:
        Long millis = objectToDATEorTIMEorTIMESTAMP(objectClass, object);
        assert millis != null;
        return JdbcLong.instance.decompose(millis);

    case Types.DATALINK:
        String urlAsString = ((URL) object).toExternalForm();
        return JdbcUTF8.instance.decompose(urlAsString);

    case Types.JAVA_OBJECT:
        return javaObject(object);

    case Types.OTHER:
        if (List.class.isAssignableFrom(objectClass)) {
            return handleAsList(objectClass, object);
        } else if (Set.class.isAssignableFrom(objectClass)) {
            return handleAsSet(objectClass, object);
        } else if (Map.class.isAssignableFrom(objectClass)) {
            return handleAsMap(objectClass, object);
        } else
            return null;

    case Types.ROWID:
        byte[] bytes = ((RowId) object).getBytes();
        return ByteBuffer.wrap(bytes);

    default:
        LOG.warn("Unhandled JDBC type: " + targetSqlType);
        return null;
    }
}

From source file:org.h2gis.drivers.geojson.GeoJsonWriteDriver.java

/**
 * Return true is the SQL type is supported by the GeoJSON driver.
 *
 * @param sqlTypeId//from w  ww .java2s .c o m
 * @param sqlTypeName
 * @return
 * @throws SQLException
 */
public boolean isSupportedPropertyType(int sqlTypeId, String sqlTypeName) throws SQLException {
    switch (sqlTypeId) {
    case Types.BOOLEAN:
    case Types.DOUBLE:
    case Types.FLOAT:
    case Types.INTEGER:
    case Types.BIGINT:
    case Types.SMALLINT:
    case Types.DATE:
    case Types.VARCHAR:
    case Types.NCHAR:
    case Types.CHAR:
        return true;
    default:
        throw new SQLException("Field type not supported by GeoJSON driver: " + sqlTypeName);
    }
}

From source file:org.jumpmind.symmetric.io.data.DbFill.java

private Object generateRandomValueForColumn(Column column) {
    Object objectValue = null;/*  w  w w  .  ja  v a 2s.  c o m*/
    int type = column.getMappedTypeCode();
    if (column.isEnum()) {
        objectValue = column.getEnumValues()[new Random().nextInt(column.getEnumValues().length)];
    } else if (column.isTimestampWithTimezone()) {
        objectValue = String.format("%s %s", FormatUtils.TIMESTAMP_FORMATTER.format(randomDate()),
                AppUtils.getTimezoneOffset());
    } else if (type == Types.DATE) {
        objectValue = DateUtils.truncate(randomDate(), Calendar.DATE);
    } else if (type == Types.TIMESTAMP || type == Types.TIME) {
        objectValue = randomTimestamp();
    } else if (type == Types.INTEGER || type == Types.BIGINT) {
        objectValue = randomInt();
    } else if (type == Types.SMALLINT) {
        objectValue = randomSmallInt(column.getJdbcTypeName().toLowerCase().contains("unsigned"));
    } else if (type == Types.FLOAT) {
        objectValue = randomFloat();
    } else if (type == Types.DOUBLE) {
        objectValue = randomDouble();
    } else if (type == Types.TINYINT) {
        objectValue = randomTinyInt();
    } else if (type == Types.NUMERIC || type == Types.DECIMAL || type == Types.REAL) {
        objectValue = randomBigDecimal(column.getSizeAsInt(), column.getScale());
    } else if (type == Types.BOOLEAN || type == Types.BIT) {
        objectValue = randomBoolean();
    } else if (type == Types.BLOB || type == Types.LONGVARBINARY || type == Types.BINARY
            || type == Types.VARBINARY ||
            // SQLServer text type
            type == -10) {
        objectValue = randomBytes();
    } else if (type == Types.ARRAY) {
        objectValue = null;
    } else if (type == Types.VARCHAR || type == Types.LONGVARCHAR || type == Types.CHAR || type == Types.CLOB) {
        int size = 0;
        // Assume if the size is 0 there is no max size configured.
        if (column.getSizeAsInt() != 0) {
            size = column.getSizeAsInt() > 50 ? 50 : column.getSizeAsInt();
        } else {
            // No max length so default to 50
            size = 50;
        }
        objectValue = randomString(size);
    } else if (type == Types.OTHER) {
        if ("UUID".equalsIgnoreCase(column.getJdbcTypeName())) {
            objectValue = randomUUID();
        }
    }
    return objectValue;
}

From source file:com.cloudera.sqoop.manager.SqlManager.java

/**
 * Resolve a database-specific type to the Java type that should contain it.
 * @param sqlType//  w w w . j a  va 2 s .  com
 * @return the name of a Java type to hold the sql datatype, or null if none.
 */
public String toJavaType(int sqlType) {
    // Mappings taken from:
    // http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html
    if (sqlType == Types.INTEGER) {
        return "Integer";
    } else if (sqlType == Types.VARCHAR) {
        return "String";
    } else if (sqlType == Types.CHAR) {
        return "String";
    } else if (sqlType == Types.LONGVARCHAR) {
        return "String";
    } else if (sqlType == Types.NUMERIC) {
        return "java.math.BigDecimal";
    } else if (sqlType == Types.DECIMAL) {
        return "java.math.BigDecimal";
    } else if (sqlType == Types.BIT) {
        return "Boolean";
    } else if (sqlType == Types.BOOLEAN) {
        return "Boolean";
    } else if (sqlType == Types.TINYINT) {
        return "Integer";
    } else if (sqlType == Types.SMALLINT) {
        return "Integer";
    } else if (sqlType == Types.BIGINT) {
        return "Long";
    } else if (sqlType == Types.REAL) {
        return "Float";
    } else if (sqlType == Types.FLOAT) {
        return "Double";
    } else if (sqlType == Types.DOUBLE) {
        return "Double";
    } else if (sqlType == Types.DATE) {
        return "java.sql.Date";
    } else if (sqlType == Types.TIME) {
        return "java.sql.Time";
    } else if (sqlType == Types.TIMESTAMP) {
        return "java.sql.Timestamp";
    } else if (sqlType == Types.BINARY || sqlType == Types.VARBINARY) {
        return BytesWritable.class.getName();
    } else if (sqlType == Types.CLOB) {
        return ClobRef.class.getName();
    } else if (sqlType == Types.BLOB || sqlType == Types.LONGVARBINARY) {
        return BlobRef.class.getName();
    } else {
        // TODO(aaron): Support DISTINCT, ARRAY, STRUCT, REF, JAVA_OBJECT.
        // Return null indicating database-specific manager should return a
        // java data type if it can find one for any nonstandard type.
        return null;
    }
}

From source file:org.executequery.databasemediators.spi.DefaultStatementExecutor.java

/** <p>Executes the specified procedure.
 *
 *  @param  the SQL procedure to execute
 *  @return the query result//  w w w. j  a  v a2s.  c o m
 */
public SqlStatementResult execute(DatabaseExecutable databaseExecutable) throws SQLException {

    if (!prepared()) {

        return statementResult;
    }

    ProcedureParameter[] param = databaseExecutable.getParametersArray();
    Arrays.sort(param, new ProcedureParameterSorter());

    String procQuery = null;
    boolean hasOut = false;
    boolean hasParameters = (param != null && param.length > 0);

    List<ProcedureParameter> outs = null;
    List<ProcedureParameter> ins = null;

    if (hasParameters) {

        // split the params into ins and outs
        outs = new ArrayList<ProcedureParameter>();
        ins = new ArrayList<ProcedureParameter>();

        int type = -1;
        for (int i = 0; i < param.length; i++) {
            type = param[i].getType();
            if (type == DatabaseMetaData.procedureColumnIn || type == DatabaseMetaData.procedureColumnInOut) {

                // add to the ins list
                ins.add(param[i]);

            } else if (type == DatabaseMetaData.procedureColumnOut
                    || type == DatabaseMetaData.procedureColumnResult
                    || type == DatabaseMetaData.procedureColumnReturn
                    || type == DatabaseMetaData.procedureColumnUnknown
                    || type == DatabaseMetaData.procedureColumnInOut) {

                // add to the outs list
                outs.add(param[i]);

            }
        }

        char QUESTION_MARK = '?';
        String COMMA = ", ";

        // init the string buffer
        StringBuilder sb = new StringBuilder("{ ");
        if (!outs.isEmpty()) {

            // build the out params place holders
            for (int i = 0, n = outs.size(); i < n; i++) {

                sb.append(QUESTION_MARK);

                if (i < n - 1) {

                    sb.append(COMMA);
                }

            }

            sb.append(" = ");
        }

        sb.append(" call ");

        if (databaseExecutable.supportCatalogOrSchemaInFunctionOrProcedureCalls()) {

            String namePrefix = null;
            if (databaseExecutable.supportCatalogInFunctionOrProcedureCalls()) {

                namePrefix = databaseExecutable.getCatalogName();

            }
            if (databaseExecutable.supportSchemaInFunctionOrProcedureCalls()) {

                namePrefix = databaseExecutable.getSchemaName();

            }

            if (namePrefix != null) {

                sb.append(namePrefix).append('.');
            }
        }

        sb.append(databaseExecutable.getName()).append("( ");

        // build the ins params place holders
        for (int i = 0, n = ins.size(); i < n; i++) {
            sb.append(QUESTION_MARK);
            if (i < n - 1) {
                sb.append(COMMA);
            }
        }

        sb.append(" ) }");

        // determine if we have out params
        hasOut = !(outs.isEmpty());
        procQuery = sb.toString();
    } else {
        StringBuilder sb = new StringBuilder();
        sb.append("{ call ");

        if (databaseExecutable.getSchemaName() != null) {
            sb.append(databaseExecutable.getSchemaName()).append('.');
        }

        sb.append(databaseExecutable.getName()).append("( ) }");

        procQuery = sb.toString();
    }

    //Log.debug(procQuery);

    // null value literal
    String NULL = "null";

    // clear any warnings
    conn.clearWarnings();

    Log.info("Executing: " + procQuery);

    CallableStatement cstmnt = null;
    try {
        // prepare the statement
        cstmnt = conn.prepareCall(procQuery);
        stmnt = cstmnt;
    } catch (SQLException e) {
        handleException(e);
        statementResult.setSqlException(e);
        return statementResult;
    }

    // check if we are passing parameters
    if (hasParameters) {
        // the parameter index counter
        int index = 1;

        // the java.sql.Type value
        int dataType = -1;

        // the parameter input value
        String value = null;

        // register the out params
        for (int i = 0, n = outs.size(); i < n; i++) {
            //Log.debug("setting out at index: " + index);
            cstmnt.registerOutParameter(index, outs.get(i).getDataType());
            index++;
        }

        try {

            // register the in params
            for (int i = 0, n = ins.size(); i < n; i++) {

                ProcedureParameter procedureParameter = ins.get(i);
                value = procedureParameter.getValue();
                dataType = procedureParameter.getDataType();

                // try infer a type if OTHER
                if (dataType == Types.OTHER) {

                    // checking only for bit/bool for now

                    if (isTrueFalse(value)) {

                        dataType = Types.BOOLEAN;

                    } else if (isBit(value)) {

                        dataType = Types.BIT;
                        value = value.substring(2, value.length() - 1);
                    }

                }

                if (MiscUtils.isNull(value) || value.equalsIgnoreCase(NULL)) {

                    cstmnt.setNull(index, dataType);

                } else {

                    switch (dataType) {

                    case Types.TINYINT:
                        byte _byte = Byte.valueOf(value).byteValue();
                        cstmnt.setShort(index, _byte);
                        break;

                    case Types.SMALLINT:
                        short _short = Short.valueOf(value).shortValue();
                        cstmnt.setShort(index, _short);
                        break;

                    case Types.LONGVARCHAR:
                    case Types.CHAR:
                    case Types.VARCHAR:
                        cstmnt.setString(index, value);
                        break;

                    case Types.BIT:
                    case Types.BOOLEAN:

                        boolean _boolean = false;
                        if (NumberUtils.isNumber(value)) {

                            int number = Integer.valueOf(value);
                            if (number > 0) {

                                _boolean = true;
                            }

                        } else {

                            _boolean = Boolean.valueOf(value).booleanValue();
                        }

                        cstmnt.setBoolean(index, _boolean);
                        break;

                    case Types.BIGINT:
                        long _long = Long.valueOf(value).longValue();
                        cstmnt.setLong(index, _long);
                        break;

                    case Types.INTEGER:
                        int _int = Integer.valueOf(value).intValue();
                        cstmnt.setInt(index, _int);
                        break;

                    case Types.REAL:
                        float _float = Float.valueOf(value).floatValue();
                        cstmnt.setFloat(index, _float);
                        break;

                    case Types.NUMERIC:
                    case Types.DECIMAL:
                        cstmnt.setBigDecimal(index, new BigDecimal(value));
                        break;
                    /*
                                      case Types.DATE:
                                      case Types.TIMESTAMP:
                                      case Types.TIME:
                                        cstmnt.setTimestamp(index, new Timestamp( BigDecimal(value));
                    */
                    case Types.FLOAT:
                    case Types.DOUBLE:
                        double _double = Double.valueOf(value).doubleValue();
                        cstmnt.setDouble(index, _double);
                        break;

                    default:
                        cstmnt.setObject(index, value);

                    }

                }

                // increment the index
                index++;
            }

        } catch (Exception e) {

            statementResult.setOtherErrorMessage(e.getClass().getName() + ": " + e.getMessage());
            return statementResult;
        }

    }

    /*
    test creating function for postgres:
            
    CREATE FUNCTION concat_lower_or_upper(a text, b text, uppercase boolean DEFAULT false)
    RETURNS text
    AS
    $$
     SELECT CASE
        WHEN $3 THEN UPPER($1 || ' ' || $2)
        ELSE LOWER($1 || ' ' || $2)
        END;
    $$
    LANGUAGE SQL IMMUTABLE STRICT;
    */

    try {
        cstmnt.clearWarnings();
        boolean hasResultSet = cstmnt.execute();
        Map<String, Object> results = new HashMap<String, Object>();

        if (hasOut) {
            // incrementing index
            int index = 1;

            // return value from each registered out
            String returnValue = null;

            for (int i = 0; i < param.length; i++) {

                int type = param[i].getType();
                int dataType = param[i].getDataType();

                if (type == DatabaseMetaData.procedureColumnOut
                        || type == DatabaseMetaData.procedureColumnResult
                        || type == DatabaseMetaData.procedureColumnReturn
                        || type == DatabaseMetaData.procedureColumnUnknown
                        || type == DatabaseMetaData.procedureColumnInOut) {

                    switch (dataType) {

                    case Types.TINYINT:
                        returnValue = Byte.toString(cstmnt.getByte(index));
                        break;

                    case Types.SMALLINT:
                        returnValue = Short.toString(cstmnt.getShort(index));
                        break;

                    case Types.LONGVARCHAR:
                    case Types.CHAR:
                    case Types.VARCHAR:
                        returnValue = cstmnt.getString(index);
                        break;

                    case Types.BIT:
                    case Types.BOOLEAN:
                        returnValue = Boolean.toString(cstmnt.getBoolean(index));
                        break;

                    case Types.INTEGER:
                        returnValue = Integer.toString(cstmnt.getInt(index));
                        break;

                    case Types.BIGINT:
                        returnValue = Long.toString(cstmnt.getLong(index));
                        break;

                    case Types.REAL:
                        returnValue = Float.toString(cstmnt.getFloat(index));
                        break;

                    case Types.NUMERIC:
                    case Types.DECIMAL:
                        returnValue = cstmnt.getBigDecimal(index).toString();
                        break;

                    case Types.DATE:
                    case Types.TIME:
                    case Types.TIMESTAMP:
                        returnValue = cstmnt.getDate(index).toString();
                        break;

                    case Types.FLOAT:
                    case Types.DOUBLE:
                        returnValue = Double.toString(cstmnt.getDouble(index));
                        break;

                    }

                    if (returnValue == null) {
                        returnValue = "NULL";
                    }

                    results.put(param[i].getName(), returnValue);
                    index++;
                }

            }

        }

        if (!hasResultSet) {

            statementResult.setUpdateCount(cstmnt.getUpdateCount());

        } else {

            statementResult.setResultSet(cstmnt.getResultSet());
        }

        useCount++;
        statementResult.setOtherResult(results);

    } catch (SQLException e) {

        statementResult.setSqlException(e);

    } catch (Exception e) {

        statementResult.setMessage(e.getMessage());
    }

    return statementResult;
}