Example usage for java.sql Types NUMERIC

List of usage examples for java.sql Types NUMERIC

Introduction

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

Prototype

int NUMERIC

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

Click Source Link

Document

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

Usage

From source file:nl.nn.adapterframework.jdbc.JdbcFacade.java

protected void applyParameters(PreparedStatement statement, ParameterValueList parameters)
        throws SQLException, SenderException {
    // statement.clearParameters();

    /*/* ww w.  j  a v a  2  s.  c  o m*/
          // getParameterMetaData() is not supported on the WebSphere java.sql.PreparedStatement implementation.
          int senderParameterCount = parameters.size();
          int statementParameterCount = statement.getParameterMetaData().getParameterCount();
          if (statementParameterCount<senderParameterCount) {
             throw new SenderException(getLogPrefix()+"statement has more ["+statementParameterCount+"] parameters defined than sender ["+senderParameterCount+"]");
          }
    */

    for (int i = 0; i < parameters.size(); i++) {
        ParameterValue pv = parameters.getParameterValue(i);
        String paramType = pv.getDefinition().getType();
        Object value = pv.getValue();
        //      log.debug("applying parameter ["+(i+1)+","+parameters.getParameterValue(i).getDefinition().getName()+"], value["+parameterValue+"]");

        if (Parameter.TYPE_DATE.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.DATE);
            } else {
                statement.setDate(i + 1, new java.sql.Date(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_DATETIME.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIMESTAMP);
            } else {
                statement.setTimestamp(i + 1, new Timestamp(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_TIMESTAMP.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIMESTAMP);
            } else {
                statement.setTimestamp(i + 1, new Timestamp(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_TIME.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIME);
            } else {
                statement.setTime(i + 1, new java.sql.Time(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_XMLDATETIME.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIMESTAMP);
            } else {
                statement.setTimestamp(i + 1, new Timestamp(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_NUMBER.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.NUMERIC);
            } else {
                statement.setDouble(i + 1, ((Number) value).doubleValue());
            }
        } else if (Parameter.TYPE_INTEGER.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.INTEGER);
            } else {
                statement.setInt(i + 1, (Integer) value);
            }
        } else if (Parameter.TYPE_INPUTSTREAM.equals(paramType)) {
            if (value instanceof FileInputStream) {
                FileInputStream fis = (FileInputStream) value;
                long len = 0;
                try {
                    len = fis.getChannel().size();
                } catch (IOException e) {
                    log.warn(getLogPrefix() + "could not determine file size", e);
                }
                statement.setBinaryStream(i + 1, fis, (int) len);
            } else if (value instanceof ByteArrayInputStream) {
                ByteArrayInputStream bais = (ByteArrayInputStream) value;
                long len = bais.available();
                statement.setBinaryStream(i + 1, bais, (int) len);
            } else {
                throw new SenderException(getLogPrefix() + "unknown inputstream [" + value.getClass()
                        + "] for parameter [" + pv.getDefinition().getName() + "]");
            }
        } else if ("string2bytes".equals(paramType)) {
            statement.setBytes(i + 1, ((String) value).getBytes());
        } else if ("bytes".equals(paramType)) {
            statement.setBytes(i + 1, (byte[]) value);
        } else {
            statement.setString(i + 1, (String) value);
        }
    }
}

From source file:com.opensymphony.module.propertyset.database.JDBCPropertySet.java

private void setValues(PreparedStatement ps, int type, String key, Object value)
        throws SQLException, PropertyException {
    // Patched by Edson Richter for MS SQL Server JDBC Support!
    String driverName;/*w  w  w  .j a v  a  2s  .  com*/

    try {
        driverName = ps.getConnection().getMetaData().getDriverName().toUpperCase();
    } catch (Exception e) {
        driverName = "";
    }

    ps.setNull(1, Types.VARCHAR);
    ps.setNull(2, Types.TIMESTAMP);

    // Patched by Edson Richter for MS SQL Server JDBC Support!
    // Oracle support suggestion also Michael G. Slack
    if ((driverName.indexOf("SQLSERVER") >= 0) || (driverName.indexOf("ORACLE") >= 0)) {
        ps.setNull(3, Types.BINARY);
    } else {
        ps.setNull(3, Types.BLOB);
    }

    ps.setNull(4, Types.FLOAT);
    ps.setNull(5, Types.NUMERIC);
    ps.setInt(6, type);
    ps.setString(7, globalKey);
    ps.setString(8, key);

    switch (type) {
    case PropertySet.BOOLEAN:

        Boolean boolVal = (Boolean) value;
        ps.setInt(5, boolVal.booleanValue() ? 1 : 0);

        break;

    case PropertySet.DATA:

        Data data = (Data) value;
        ps.setBytes(3, data.getBytes());

        break;

    case PropertySet.DATE:

        Date date = (Date) value;
        ps.setTimestamp(2, new Timestamp(date.getTime()));

        break;

    case PropertySet.DOUBLE:

        Double d = (Double) value;
        ps.setDouble(4, d.doubleValue());

        break;

    case PropertySet.INT:

        Integer i = (Integer) value;
        ps.setInt(5, i.intValue());

        break;

    case PropertySet.LONG:

        Long l = (Long) value;
        ps.setLong(5, l.longValue());

        break;

    case PropertySet.STRING:
        ps.setString(1, (String) value);

        break;

    default:
        throw new PropertyException("This type isn't supported!");
    }
}

From source file:org.apache.nifi.processors.standard.util.TestJdbcCommon.java

@Test
public void testConvertToAvroStreamForBigDecimal() throws SQLException, IOException {
    final ResultSetMetaData metadata = mock(ResultSetMetaData.class);
    when(metadata.getColumnCount()).thenReturn(1);
    when(metadata.getColumnType(1)).thenReturn(Types.NUMERIC);
    when(metadata.getColumnName(1)).thenReturn("The.Chairman");
    when(metadata.getTableName(1)).thenReturn("1the::table");

    final ResultSet rs = mock(ResultSet.class);
    when(rs.getMetaData()).thenReturn(metadata);

    final AtomicInteger counter = new AtomicInteger(1);
    Mockito.doAnswer(new Answer<Boolean>() {
        @Override//ww w  . j av a 2  s  .com
        public Boolean answer(InvocationOnMock invocation) throws Throwable {
            return counter.getAndDecrement() > 0;
        }
    }).when(rs).next();

    final BigDecimal bigDecimal = new BigDecimal(38D);
    when(rs.getObject(Mockito.anyInt())).thenReturn(bigDecimal);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    JdbcCommon.convertToAvroStream(rs, baos, true);

    final byte[] serializedBytes = baos.toByteArray();

    final InputStream instream = new ByteArrayInputStream(serializedBytes);

    final DatumReader<GenericRecord> datumReader = new GenericDatumReader<>();
    try (final DataFileStream<GenericRecord> dataFileReader = new DataFileStream<>(instream, datumReader)) {
        GenericRecord record = null;
        while (dataFileReader.hasNext()) {
            record = dataFileReader.next(record);
            assertEquals("_1the__table", record.getSchema().getName());
            assertEquals(bigDecimal.toString(), record.get("The_Chairman").toString());
        }
    }
}

From source file:org.executequery.gui.importexport.AbstractImportExportWorker.java

/**
 * Sets the specified value in the specified position for the
 * specified java.sql.Type within the prepared statement.
 *
 * @param value - the value/*from  w  ww .  j  av a2  s.  co m*/
 * @param index - the position within the statement
 * @param sqlType - the SQL type
 * @param trim - whether to trim the whitespace from the value
 * @param df - the DataFormat object for date values
 */
protected void setValue(String value, int index, int sqlType, boolean trim, DateFormat df) throws Exception {

    if (value == null) {

        prepStmnt.setNull(index, sqlType);

    } else {

        switch (sqlType) {

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

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

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

        case Types.LONGVARCHAR:
        case Types.CHAR:
        case Types.VARCHAR:
            if (trim) {
                value = value.trim();
            }
            prepStmnt.setString(index, value);
            break;

        case Types.BIT:
        case Types.BOOLEAN:

            String booleanValue = value;
            if ("t".equalsIgnoreCase(value)) {

                booleanValue = "true";

            } else if ("f".equalsIgnoreCase(value)) {

                booleanValue = "false";
            }

            boolean _boolean = Boolean.valueOf(booleanValue).booleanValue();
            prepStmnt.setBoolean(index, _boolean);
            break;

        case Types.NUMERIC:
        case Types.DECIMAL:
            prepStmnt.setBigDecimal(index, new BigDecimal(value));
            break;

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

        case Types.FLOAT:
        case Types.DOUBLE:
            prepStmnt.setDouble(index, Double.parseDouble(value));
            break;

        case Types.INTEGER:
            prepStmnt.setInt(index, Integer.parseInt(value));
            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            // if the date format is null, insert as a char value
            if (df != null) {
                java.util.Date j_datetime = df.parse(value);
                prepStmnt.setDate(index, new java.sql.Date(j_datetime.getTime()));
            } else {
                try {
                    prepStmnt.setObject(index, value, sqlType);
                    /*
                    if (sqlType == Types.TIMESTAMP) {
                        prepStmnt.setTimestamp(index,
                                java.sql.Timestamp.valueOf(value));
                    }
                    else if (sqlType == Types.TIME) {
                        prepStmnt.setTime(index,
                                java.sql.Time.valueOf(value));
                    }
                    else {
                        prepStmnt.setDate(index,
                                java.sql.Date.valueOf(value));
                    }
                     */
                }
                // want a more useful message here than what will likely
                // be returned due to internal driver code on formatting
                // a SQL date value from string
                // (ie. could be parsing error, number format etc...)
                catch (Exception e) {
                    throw new IllegalArgumentException("[ " + MiscUtils.getExceptionName(e) + " ] "
                            + getBundle().getString("AbstractImportExportWorker.dateConversionError"));
                }

            }
            break;

        case Types.LONGVARBINARY:
        case Types.BINARY:
        case Types.BLOB:
        case Types.CLOB:
            prepStmnt.setBytes(index, Base64.decode(value));
            break;

        default:
            prepStmnt.setObject(index, value);
            break;
        }
    }
}

From source file:org.apache.oozie.command.SchemaCheckXCommand.java

private String getSQLTypeFromInt(int t) {
    switch (t) {/*from  ww  w .  j  a  v a 2  s. co m*/
    case Types.BIT:
        return "BIT";
    case Types.TINYINT:
        return "TINYINT";
    case Types.SMALLINT:
        return "SMALLINT";
    case Types.INTEGER:
        return "INTEGER";
    case Types.BIGINT:
        return "BIGINT";
    case Types.FLOAT:
        return "FLOAT";
    case Types.REAL:
        return "REAL";
    case Types.DOUBLE:
        return "DOUBLE";
    case Types.NUMERIC:
        return "NUMERIC";
    case Types.DECIMAL:
        return "DECIMAL";
    case Types.CHAR:
        return "CHAR";
    case Types.VARCHAR:
        return "VARCHAR";
    case Types.LONGVARCHAR:
        return "LONGVARCHAR";
    case Types.DATE:
        return "DATE";
    case Types.TIME:
        return "TIME";
    case Types.TIMESTAMP:
        return "TIMESTAMP";
    case Types.BINARY:
        return "BINARY";
    case Types.VARBINARY:
        return "VARBINARY";
    case Types.LONGVARBINARY:
        return "LONGVARBINARY";
    case Types.NULL:
        return "NULL";
    case Types.OTHER:
        return "OTHER";
    case Types.JAVA_OBJECT:
        return "JAVA_OBJECT";
    case Types.DISTINCT:
        return "DISTINCT";
    case Types.STRUCT:
        return "STRUCT";
    case Types.ARRAY:
        return "ARRAY";
    case Types.BLOB:
        return "BLOB";
    case Types.CLOB:
        return "CLOB";
    case Types.REF:
        return "REF";
    case Types.DATALINK:
        return "DATALINK";
    case Types.BOOLEAN:
        return "BOOLEAN";
    case Types.ROWID:
        return "ROWID";
    case Types.NCHAR:
        return "NCHAR";
    case Types.NVARCHAR:
        return "NVARCHAR";
    case Types.LONGNVARCHAR:
        return "LONGNVARCHAR";
    case Types.NCLOB:
        return "NCLOB";
    case Types.SQLXML:
        return "SQLXML";
    default:
        return "unknown";
    }
}

From source file:com.mapd.utility.SQLImporter.java

private String getColType(int cType, int precision, int scale) {
    if (precision > 19) {
        precision = 19;//from   ww  w  . j  av  a2  s.  co  m
    }
    if (scale > 19) {
        scale = 18;
    }
    switch (cType) {
    case java.sql.Types.TINYINT:
    case java.sql.Types.SMALLINT:
        return ("SMALLINT");
    case java.sql.Types.INTEGER:
        return ("INTEGER");
    case java.sql.Types.BIGINT:
        return ("BIGINT");
    case java.sql.Types.FLOAT:
        return ("FLOAT");
    case java.sql.Types.DECIMAL:
        return ("DECIMAL(" + precision + "," + scale + ")");
    case java.sql.Types.DOUBLE:
        return ("DOUBLE");
    case java.sql.Types.REAL:
        return ("REAL");
    case java.sql.Types.NUMERIC:
        return ("NUMERIC(" + precision + "," + scale + ")");
    case java.sql.Types.TIME:
        return ("TIME");
    case java.sql.Types.TIMESTAMP:
        return ("TIMESTAMP");
    case java.sql.Types.DATE:
        return ("DATE");
    case java.sql.Types.BOOLEAN:
    case java.sql.Types.BIT: // deal with postgress treating boolean as bit... this will bite me
        return ("BOOLEAN");
    case java.sql.Types.NVARCHAR:
    case java.sql.Types.VARCHAR:
    case java.sql.Types.NCHAR:
    case java.sql.Types.CHAR:
    case java.sql.Types.LONGVARCHAR:
    case java.sql.Types.LONGNVARCHAR:
        return ("TEXT ENCODING DICT");
    default:
        throw new AssertionError("Column type " + cType + " not Supported");
    }
}

From source file:org.apache.sqoop.hcat.HCatalogImportTest.java

public void testNumberTypes() throws Exception {
    final int TOTAL_RECORDS = 1 * 10;
    String table = getTableName().toUpperCase();
    ColumnGenerator[] cols = new ColumnGenerator[] {
            HCatalogTestUtils.colGenerator(HCatalogTestUtils.forIdx(0), "numeric(18,2)", Types.NUMERIC,
                    HCatFieldSchema.Type.STRING, 0, 0, "1000", new BigDecimal("1000"), KeyType.NOT_A_KEY),
            HCatalogTestUtils.colGenerator(HCatalogTestUtils.forIdx(1), "decimal(18,2)", Types.DECIMAL,
                    HCatFieldSchema.Type.STRING, 0, 0, "2000", new BigDecimal("2000"), KeyType.NOT_A_KEY),
            HCatalogTestUtils.colGenerator(HCatalogTestUtils.forIdx(2), "decimal(18,2)", Types.DECIMAL,
                    HCatFieldSchema.Type.DECIMAL, 18, 2, HiveDecimal.create(new BigDecimal("2000")),
                    new BigDecimal("2000"), KeyType.NOT_A_KEY), };
    List<String> addlArgsArray = new ArrayList<String>();
    setExtraArgs(addlArgsArray);/* w ww  . j a  va2 s  .  c  o  m*/
    runHCatImport(addlArgsArray, TOTAL_RECORDS, table, cols, null);
}

From source file:com.squid.core.domain.operators.ExtendedType.java

public static IDomain computeDomain(int data_type, int size, int scale) {
    switch (data_type) {
    case Types.BOOLEAN:
    case Types.BIT:// on PG systems, this is how a boolean is actually represented by the driver
        return IDomain.BOOLEAN;
    case Types.TINYINT:
    case Types.BIGINT:
    case Types.INTEGER:
    case Types.SMALLINT:
        return IDomain.NUMERIC;
    ///////////////////////////
    case Types.REAL:
    case Types.DOUBLE:
    case Types.FLOAT:
        return IDomain.CONTINUOUS;
    case Types.NUMERIC:
    case Types.DECIMAL:
        return scale > 0 || size == 0 ? IDomain.CONTINUOUS : IDomain.NUMERIC;
    case Types.CHAR:
    case Types.NCHAR:
    case Types.VARCHAR:
    case Types.NVARCHAR:
    case Types.LONGVARCHAR:
    case Types.CLOB:
        return IDomain.STRING;
    ///////////////////////////
    case Types.TIME:
        return IDomain.TIME;
    case Types.DATE:
        return IDomain.DATE;
    case Types.TIMESTAMP:
        return IDomain.TIMESTAMP;
    ///////////////////////////
    default:// w  w  w .  j  a v  a2s.c  o  m
        return IDomain.UNKNOWN;
    }
}

From source file:org.apache.cocoon.util.JDBCTypeConversions.java

/**
 * Set the Statement column so that the results are mapped correctly.
 *
 * @param statement the prepared statement
 * @param position the position of the column
 * @param value the value of the column/* www. ja  v a  2 s  .  co  m*/
 */
public static void setColumn(PreparedStatement statement, int position, Object value, Integer typeObject)
        throws Exception {
    if (value instanceof String) {
        value = ((String) value).trim();
    }
    if (typeObject == null) {
        throw new SQLException("Can't set column because the type is unrecognized");
    }
    if (value == null) {
        /** If the value is null, set the column value null and return **/
        statement.setNull(position, typeObject.intValue());
        return;
    }
    if ("".equals(value)) {
        switch (typeObject.intValue()) {
        case Types.CHAR:
        case Types.CLOB:
        case Types.VARCHAR:
            /** If the value is an empty string and the column is
            a string type, we can continue **/
            break;
        default:
            /** If the value is an empty string and the column
            is something else, we treat it as a null value **/
            statement.setNull(position, typeObject.intValue());
            return;
        }
    }

    File file = null;
    int length = -1;
    InputStream asciiStream = null;

    //System.out.println("========================================================================");
    //System.out.println("JDBCTypeConversions: setting type "+typeObject.intValue());
    switch (typeObject.intValue()) {
    case Types.CLOB:
        //System.out.println("CLOB");
        Clob clob = null;
        if (value instanceof Clob) {
            clob = (Clob) value;
        } else if (value instanceof File) {
            File asciiFile = (File) value;
            asciiStream = new BufferedInputStream(new FileInputStream(asciiFile));
            length = (int) asciiFile.length();
            clob = new ClobHelper(asciiStream, length);
        } else if (value instanceof Part) {
            Part anyFile = (Part) value;
            asciiStream = new BufferedInputStream(anyFile.getInputStream());
            length = anyFile.getSize();
            clob = new ClobHelper(asciiStream, length);
        } else if (value instanceof JDBCxlobHelper) {
            asciiStream = ((JDBCxlobHelper) value).inputStream;
            length = ((JDBCxlobHelper) value).length;
            clob = new ClobHelper(asciiStream, length);
        } else if (value instanceof Source) {
            asciiStream = ((Source) value).getInputStream();
            length = (int) ((Source) value).getContentLength();
            clob = new ClobHelper(asciiStream, length);
        } else {
            String asciiText = value.toString();
            asciiStream = new ByteArrayInputStream(asciiText.getBytes());
            length = asciiText.length();
            clob = new ClobHelper(asciiStream, length);
        }

        statement.setClob(position, clob);
        break;
    case Types.CHAR:
        // simple large object, e.g. Informix's TEXT
        //System.out.println("CHAR");

        if (value instanceof File) {
            File asciiFile = (File) value;
            asciiStream = new BufferedInputStream(new FileInputStream(asciiFile));
            length = (int) asciiFile.length();
        } else if (value instanceof JDBCxlobHelper) {
            asciiStream = ((JDBCxlobHelper) value).inputStream;
            length = ((JDBCxlobHelper) value).length;
        } else if (value instanceof Source) {
            asciiStream = ((Source) value).getInputStream();
            length = (int) ((Source) value).getContentLength();
        } else if (value instanceof Part) {
            Part anyFile = (Part) value;
            asciiStream = new BufferedInputStream(anyFile.getInputStream());
            length = anyFile.getSize();
            clob = new ClobHelper(asciiStream, length);
        } else {
            String asciiText = value.toString();
            asciiStream = new BufferedInputStream(new ByteArrayInputStream(asciiText.getBytes()));
            length = asciiText.length();
        }

        statement.setAsciiStream(position, asciiStream, length);
        break;
    case Types.BIGINT:
        //System.out.println("BIGINT");
        BigDecimal bd = null;

        if (value instanceof BigDecimal) {
            bd = (BigDecimal) value;
        } else if (value instanceof Number) {
            bd = BigDecimal.valueOf(((Number) value).longValue());
        } else {
            bd = new BigDecimal(value.toString());
        }

        statement.setBigDecimal(position, bd);
        break;
    case Types.TINYINT:
        //System.out.println("TINYINT");
        Byte b = null;

        if (value instanceof Byte) {
            b = (Byte) value;
        } else if (value instanceof Number) {
            b = new Byte(((Number) value).byteValue());
        } else {
            b = new Byte(value.toString());
        }

        statement.setByte(position, b.byteValue());
        break;
    case Types.DATE:
        //System.out.println("DATE");
        Date d = null;

        if (value instanceof Date) {
            d = (Date) value;
        } else if (value instanceof java.util.Date) {
            d = new Date(((java.util.Date) value).getTime());
        } else if (value instanceof Calendar) {
            d = new Date(((Calendar) value).getTime().getTime());
        } else {
            d = Date.valueOf(value.toString());
        }

        statement.setDate(position, d);
        break;
    case Types.DOUBLE:
        //System.out.println("DOUBLE");
        double db;

        if (value instanceof Number) {
            db = (((Number) value).doubleValue());
        } else {
            db = Double.parseDouble(value.toString());
        }
        statement.setDouble(position, db);
        break;
    case Types.FLOAT:
        //System.out.println("FLOAT");
        float f;

        if (value instanceof Number) {
            f = (((Number) value).floatValue());
        } else {
            f = Float.parseFloat(value.toString());
        }
        statement.setFloat(position, f);
        break;
    case Types.NUMERIC:
        //System.out.println("NUMERIC");
        long l;

        if (value instanceof Number) {
            l = (((Number) value).longValue());
        } else {
            l = Long.parseLong(value.toString());
        }

        statement.setLong(position, l);
        break;
    case Types.SMALLINT:
        //System.out.println("SMALLINT");
        Short s = null;

        if (value instanceof Short) {
            s = (Short) value;
        } else if (value instanceof Number) {
            s = new Short(((Number) value).shortValue());
        } else {
            s = new Short(value.toString());
        }

        statement.setShort(position, s.shortValue());
        break;
    case Types.TIME:
        //System.out.println("TIME");
        Time t = null;

        if (value instanceof Time) {
            t = (Time) value;
        } else if (value instanceof java.util.Date) {
            t = new Time(((java.util.Date) value).getTime());
        } else {
            t = Time.valueOf(value.toString());
        }

        statement.setTime(position, t);
        break;
    case Types.TIMESTAMP:
        //System.out.println("TIMESTAMP");
        Timestamp ts = null;

        if (value instanceof Time) {
            ts = (Timestamp) value;
        } else if (value instanceof java.util.Date) {
            ts = new Timestamp(((java.util.Date) value).getTime());
        } else {
            ts = Timestamp.valueOf(value.toString());
        }

        statement.setTimestamp(position, ts);
        break;
    case Types.ARRAY:
        //System.out.println("ARRAY");
        statement.setArray(position, (Array) value); // no way to convert string to array
        break;
    case Types.STRUCT:
        //System.out.println("STRUCT");
    case Types.OTHER:
        //System.out.println("OTHER");
        statement.setObject(position, value);
        break;
    case Types.LONGVARBINARY:
        //System.out.println("LONGVARBINARY");
        statement.setTimestamp(position, new Timestamp((new java.util.Date()).getTime()));
        break;
    case Types.VARCHAR:
        //System.out.println("VARCHAR");
        statement.setString(position, value.toString());
        break;
    case Types.BLOB:
        //System.out.println("BLOB");
        if (value instanceof JDBCxlobHelper) {
            statement.setBinaryStream(position, ((JDBCxlobHelper) value).inputStream,
                    ((JDBCxlobHelper) value).length);
        } else if (value instanceof Source) {
            statement.setBinaryStream(position, ((Source) value).getInputStream(),
                    (int) ((Source) value).getContentLength());
        } else {
            Blob blob = null;
            if (value instanceof Blob) {
                blob = (Blob) value;
            } else if (value instanceof File) {
                file = (File) value;
                blob = new BlobHelper(new FileInputStream(file), (int) file.length());
            } else if (value instanceof String) {
                file = new File((String) value);
                blob = new BlobHelper(new FileInputStream(file), (int) file.length());
            } else if (value instanceof Part) {
                Part anyFile = (Part) value;
                blob = new BlobHelper(new BufferedInputStream(anyFile.getInputStream()), anyFile.getSize());
            } else {
                throw new SQLException("Invalid type for blob: " + value.getClass().getName());
            }
            //InputStream input = new BufferedInputStream(new FileInputStream(file));
            statement.setBlob(position, blob);
        }
        break;
    case Types.VARBINARY:
        //System.out.println("VARBINARY");
        if (value instanceof JDBCxlobHelper) {
            statement.setBinaryStream(position, ((JDBCxlobHelper) value).inputStream,
                    ((JDBCxlobHelper) value).length);
        } else if (value instanceof Source) {
            statement.setBinaryStream(position, ((Source) value).getInputStream(),
                    (int) ((Source) value).getContentLength());
        } else if (value instanceof Part) {
            statement.setBinaryStream(position, ((Part) value).getInputStream(), ((Part) value).getSize());
        } else {
            if (value instanceof File) {
                file = (File) value;
            } else if (value instanceof String) {
                file = new File((String) value);
            } else {
                throw new SQLException("Invalid type for blob: " + value.getClass().getName());
            }
            //InputStream input = new BufferedInputStream(new FileInputStream(file));
            FileInputStream input = new FileInputStream(file);
            statement.setBinaryStream(position, input, (int) file.length());
        }
        break;
    case Types.INTEGER:
        //System.out.println("INTEGER");
        Integer i = null;
        if (value instanceof Integer) {
            i = (Integer) value;
        } else if (value instanceof Number) {
            i = new Integer(((Number) value).intValue());
        } else {
            i = new Integer(value.toString());
        }
        statement.setInt(position, i.intValue());
        break;
    case Types.BIT:
        //System.out.println("BIT");
        Boolean bo = null;
        if (value instanceof Boolean) {
            bo = (Boolean) value;
        } else if (value instanceof Number) {
            bo = BooleanUtils.toBooleanObject(((Number) value).intValue() == 1);
        } else {
            bo = BooleanUtils.toBooleanObject(value.toString());
        }
        statement.setBoolean(position, bo.booleanValue());
        break;

    default:
        //System.out.println("default");
        throw new SQLException("Impossible exception - invalid type ");
    }
    //System.out.println("========================================================================");
}

From source file:com.redhat.rhn.domain.user.UserFactory.java

/**
 * Insert a new user.  Invalid to call this when updating a user
 * TODO: mmccune fill out the other fields in the user object.
 * @param usr The object we are commiting.
 * @param addr The address to add to the User
 * @param orgId Org this new user is a member of
 * @return User The freshly commited user.
 *///from   www.  j a  va2  s. co m
protected User addNewUser(User usr, Address addr, Long orgId) {
    LOG.debug("Starting addNewUser");
    if (addr != null) {
        usr.setAddress1(addr.getAddress1());
        usr.setAddress2(addr.getAddress2());
        usr.setCity(addr.getCity());
        usr.setCountry(addr.getCountry());
        usr.setFax(addr.getFax());
        usr.setIsPoBox(addr.getIsPoBox());
        usr.setPhone(addr.getPhone());
        usr.setState(addr.getState());
        usr.setZip(addr.getZip());
    }
    // save the user
    CallableMode m = ModeFactory.getCallableMode("User_queries", "create_new_user");
    Map<String, Object> inParams = new HashMap<String, Object>();
    Map<String, Integer> outParams = new HashMap<String, Integer>();

    // Can't add the orgId to the object until the User has been
    // successfully added to the DB. Doing so will mean that if
    // there are problems, the user won't be rolled back properly.
    inParams.put("orgId", orgId);
    inParams.put("login", usr.getLogin());
    inParams.put("password", usr.getPassword());
    inParams.put("contactId", null);
    inParams.put("prefix", StringUtils.defaultString(usr.getPrefix(), " "));
    inParams.put("fname", StringUtils.defaultString(usr.getFirstNames(), null));
    inParams.put("lname", StringUtils.defaultString(usr.getLastName(), null));
    inParams.put("genqual", null);
    inParams.put("parentCompany", StringUtils.defaultIfEmpty(usr.getCompany(), null));
    inParams.put("company", StringUtils.defaultIfEmpty(usr.getCompany(), null));
    inParams.put("title", StringUtils.defaultIfEmpty(usr.getTitle(), null));
    inParams.put("phone", StringUtils.defaultIfEmpty(usr.getPhone(), null));
    inParams.put("fax", StringUtils.defaultIfEmpty(usr.getFax(), null));
    inParams.put("email", StringUtils.defaultIfEmpty(usr.getEmail(), null));
    inParams.put("pin", new Integer(0));
    inParams.put("fnameOl", " ");
    inParams.put("lnameOl", " ");
    inParams.put("addr1", StringUtils.defaultIfEmpty(usr.getAddress1(), null));
    inParams.put("addr2", StringUtils.defaultIfEmpty(usr.getAddress2(), null));
    inParams.put("addr3", " ");
    inParams.put("city", StringUtils.defaultIfEmpty(usr.getCity(), null));
    inParams.put("state", StringUtils.defaultIfEmpty(usr.getState(), null));
    inParams.put("zip", StringUtils.defaultIfEmpty(usr.getZip(), null));
    inParams.put("country", StringUtils.defaultIfEmpty(usr.getCountry(), null));
    inParams.put("altFnames", null);
    inParams.put("altLnames", null);
    inParams.put("contCall", "N");
    inParams.put("contMail", "N");
    inParams.put("contFax", "N");
    inParams.put("contEmail", "N");

    outParams.put("userId", new Integer(Types.NUMERIC));
    Map<String, Object> result = m.execute(inParams, outParams);

    Org org = OrgFactory.lookupById(orgId);
    if (org != null) {
        usr.setOrg(org);
    }

    long userId = ((Long) result.get("userId")).longValue();

    // We need to lookup the User to make sure that the Address in the
    // User object has an Id and that the User has an org_id.
    User retval = lookupById(new Long(userId));
    saveObject(retval);
    return retval;
}