Example usage for java.sql Types BLOB

List of usage examples for java.sql Types BLOB

Introduction

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

Prototype

int BLOB

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

Click Source Link

Document

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

Usage

From source file:org.jumpmind.db.platform.sqlite.SqliteJdbcSqlTemplate.java

@Override
public void setValues(PreparedStatement ps, Object[] args, int[] argTypes, LobHandler lobHandler)
        throws SQLException {
    for (int i = 1; i <= args.length; i++) {
        Object arg = args[i - 1];
        int argType = argTypes != null && argTypes.length >= i ? argTypes[i - 1] : SqlTypeValue.TYPE_UNKNOWN;

        if (argType == Types.BLOB && lobHandler != null && arg instanceof byte[]) {
            lobHandler.getLobCreator().setBlobAsBytes(ps, i, (byte[]) arg);
        } else if (argType == Types.BLOB && lobHandler != null && arg instanceof String) {
            lobHandler.getLobCreator().setBlobAsBytes(ps, i, arg.toString().getBytes());
        } else if (argType == Types.CLOB && lobHandler != null) {
            lobHandler.getLobCreator().setClobAsString(ps, i, (String) arg);
        } else if (arg != null && argType == Types.DATE && arg instanceof Date) {
            Date clone = (Date) (((Date) arg).clone());
            arg = FormatUtils.TIMESTAMP_FORMATTER.format(DateUtils.truncate(clone, Calendar.DATE));
            args[i - 1] = arg;/*from   www .  jav  a 2  s.  c  o m*/
            StatementCreatorUtils.setParameterValue(ps, i, verifyArgType(arg, argType), arg);
        } else if (arg != null && (arg instanceof Date || arg instanceof Timestamp)) {
            arg = FormatUtils.TIMESTAMP_FORMATTER.format(arg);
            args[i - 1] = arg;
            StatementCreatorUtils.setParameterValue(ps, i, verifyArgType(arg, argType), arg);
        } else {
            if (arg instanceof BigDecimal) {
                arg = ((BigDecimal) arg).doubleValue();
                args[i - 1] = arg;
            }
            StatementCreatorUtils.setParameterValue(ps, i, verifyArgType(arg, argType), arg);
        }
    }
}

From source file:org.sakuli.services.receiver.database.dao.impl.DaoTestCaseImpl.java

@Override
public void saveTestCaseResult(final TestCase testCase) {
    logger.info("Save results for test case \"" + testCase.getId() + "\"");

    //create a map for the sql parameters
    MapSqlParameterSource tcParameters = new MapSqlParameterSource();
    tcParameters.addValue("sahi_suites_id", testSuite.getDbPrimaryKey());
    tcParameters.addValue("caseID", testCase.getId());
    tcParameters.addValue("result", testCase.getState().getErrorCode());
    tcParameters.addValue("result_desc", testCase.getState());
    tcParameters.addValue("name", testCase.getName());
    tcParameters.addValue("guid", testSuite.getGuid());
    tcParameters.addValue("start", testCase.getStartDateAsUnixTimestamp());
    tcParameters.addValue("stop", testCase.getStopDateAsUnixTimestamp());
    tcParameters.addValue("warning", testCase.getWarningTime());
    tcParameters.addValue("critical", testCase.getCriticalTime());
    tcParameters.addValue("browser", testSuite.getBrowserInfo());
    tcParameters.addValue("lastpage", testCase.getLastURL());

    //try to save the screenshot
    try {//ww w . j a va2s. c o  m
        if (testCase.getScreenShotPath() != null) {
            final InputStream blobIs = Files.newInputStream(testCase.getScreenShotPath());
            final int length = (int) testCase.getScreenShotPath().toFile().length();
            tcParameters.addValue("screenshot", new SqlLobValue(blobIs, length, lobHandler), Types.BLOB);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    tcParameters.addValue("duration", testCase.getDuration());
    tcParameters.addValue("msg", testCase.getExceptionMessages());

    //generate the sql-statement
    SimpleJdbcInsert insertTCResults = new SimpleJdbcInsert(getDataSource()).withTableName("sahi_cases")
            .usingGeneratedKeyColumns("id");

    logger.info(
            "write the following values to 'sahi_cases': " + tcParameters.getValues() + " => now execute ....");

    int dbPrimaryKey = insertTCResults.executeAndReturnKey(tcParameters).intValue();

    logger.info("test case '" + testCase.getId() + "' has been written to 'sahi_cases' with  primaryKey="
            + dbPrimaryKey);
    testCase.setDbPrimaryKey(dbPrimaryKey);
}

From source file:com.adaptris.core.services.jdbc.types.BlobColumnTranslatorTest.java

@Test
public void testBlobWrite_WithEncoding() throws Exception {
    BlobColumnTranslator translator = new BlobColumnTranslator("UTF-8");
    TestBlob blob = new TestBlob();
    String myData = new String("SomeData");
    blob.setBytes(0, myData.getBytes("UTF-8"));

    JdbcResultRow row = new JdbcResultRow();
    row.setFieldValue("testField", blob, Types.BLOB);

    StringWriter writer = new StringWriter();
    try (OutputStream out = new WriterOutputStream(writer)) {
        translator.write(row, 0, out);//from  w ww. j a  v  a 2s  .  c  o  m
    }
    String translated = writer.toString();

    assertEquals("SomeData", translated);
}

From source file:org.apache.openjpa.jdbc.schema.Schemas.java

/**
 * Return the {@link Types} constant for the given SQL type name.
 *///w  w w  . j ava 2  s  .  c o m
public static int getJDBCType(String name) {
    if ("array".equalsIgnoreCase(name))
        return Types.ARRAY;
    if ("bigint".equalsIgnoreCase(name))
        return Types.BIGINT;
    if ("binary".equalsIgnoreCase(name))
        return Types.BINARY;
    if ("bit".equalsIgnoreCase(name))
        return Types.BIT;
    if ("blob".equalsIgnoreCase(name))
        return Types.BLOB;
    if ("char".equalsIgnoreCase(name))
        return Types.CHAR;
    if ("clob".equalsIgnoreCase(name))
        return Types.CLOB;
    if ("date".equalsIgnoreCase(name))
        return Types.DATE;
    if ("decimal".equalsIgnoreCase(name))
        return Types.DECIMAL;
    if ("distinct".equalsIgnoreCase(name))
        return Types.DISTINCT;
    if ("double".equalsIgnoreCase(name))
        return Types.DOUBLE;
    if ("float".equalsIgnoreCase(name))
        return Types.FLOAT;
    if ("integer".equalsIgnoreCase(name))
        return Types.INTEGER;
    if ("java_object".equalsIgnoreCase(name))
        return Types.JAVA_OBJECT;
    if ("longvarbinary".equalsIgnoreCase(name))
        return Types.LONGVARBINARY;
    if ("longvarchar".equalsIgnoreCase(name))
        return Types.LONGVARCHAR;
    if ("null".equalsIgnoreCase(name))
        return Types.NULL;
    if ("numeric".equalsIgnoreCase(name))
        return Types.NUMERIC;
    if ("other".equalsIgnoreCase(name))
        return Types.OTHER;
    if ("real".equalsIgnoreCase(name))
        return Types.REAL;
    if ("ref".equalsIgnoreCase(name))
        return Types.REF;
    if ("smallint".equalsIgnoreCase(name))
        return Types.SMALLINT;
    if ("struct".equalsIgnoreCase(name))
        return Types.STRUCT;
    if ("time".equalsIgnoreCase(name))
        return Types.TIME;
    if ("timestamp".equalsIgnoreCase(name))
        return Types.TIMESTAMP;
    if ("tinyint".equalsIgnoreCase(name))
        return Types.TINYINT;
    if ("varbinary".equalsIgnoreCase(name))
        return Types.VARBINARY;
    if ("varchar".equalsIgnoreCase(name))
        return Types.VARCHAR;
    if (name == null || name.toLowerCase().startsWith("unknown"))
        return Types.OTHER;
    throw new IllegalArgumentException("name = " + name);
}

From source file:it.greenvulcano.gvesb.utils.ResultSetUtils.java

/**
 * Returns all values from the ResultSet as an XML.
 * For instance, if the ResultSet has 3 values, the returned XML will have following fields:
 *                                <RowSet>
 *                                  <data>
 *                                    <row>
 *                                      <col>value1</col>
 *                                      <col>value2</col>
 *                                      <col>value3</col>
 *                                    </row>
 *                                    <row>
 *                                      <col>value4</col>
 *                                      <col>value5</col>
 *                                      <col>value6</col>
 *                                    </row>
 *                                  ../*w ww.  ja  va2  s. co  m*/
 *                                    <row>
 *                                      <col>valuex</col>
 *                                      <col>valuey</col>
 *                                      <col>valuez</col>
 *                                    </row>
 *                                  </data>
 *                                </RowSet>
 * @param rs
 * @return
 * @throws Exception
 */
public static Document getResultSetAsDOM(ResultSet rs) throws Exception {
    XMLUtils xml = XMLUtils.getParserInstance();
    try {
        Document doc = xml.newDocument("RowSet");
        Element docRoot = doc.getDocumentElement();

        if (rs != null) {
            try {
                ResultSetMetaData metadata = rs.getMetaData();
                Element data = null;
                Element row = null;
                Element col = null;
                Text text = null;
                String textVal = null;
                while (rs.next()) {
                    boolean restartResultset = false;
                    for (int j = 1; j <= metadata.getColumnCount() && !restartResultset; j++) {
                        col = xml.createElement(doc, "col");
                        restartResultset = false;
                        switch (metadata.getColumnType(j)) {
                        case Types.CLOB: {
                            Clob clob = rs.getClob(j);
                            if (clob != null) {
                                Reader is = clob.getCharacterStream();
                                StringWriter strW = new StringWriter();

                                IOUtils.copy(is, strW);
                                is.close();
                                textVal = strW.toString();
                            } else {
                                textVal = "";
                            }
                        }
                            break;
                        case Types.BLOB: {
                            Blob blob = rs.getBlob(j);
                            if (blob != null) {
                                InputStream is = blob.getBinaryStream();
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                IOUtils.copy(is, baos);
                                is.close();
                                try {
                                    byte[] buffer = Arrays.copyOf(baos.toByteArray(), (int) blob.length());
                                    textVal = new String(Base64.getEncoder().encode(buffer));
                                } catch (SQLFeatureNotSupportedException exc) {
                                    textVal = new String(Base64.getEncoder().encode(baos.toByteArray()));
                                }
                            } else {
                                textVal = "";
                            }
                        }
                            break;
                        case -10: { // OracleTypes.CURSOR
                            Object obj = rs.getObject(j);
                            if (obj instanceof ResultSet) {
                                rs = (ResultSet) obj;
                                metadata = rs.getMetaData();
                            }
                            restartResultset = true;
                        }
                            break;
                        default: {
                            textVal = rs.getString(j);
                            if (textVal == null) {
                                textVal = "";
                            }
                        }
                        }
                        if (restartResultset) {
                            continue;
                        }
                        if (row == null || j == 1) {
                            row = xml.createElement(doc, "row");
                        }
                        if (textVal != null) {
                            text = doc.createTextNode(textVal);
                            col.appendChild(text);
                        }
                        row.appendChild(col);
                    }
                    if (row != null) {
                        if (data == null) {
                            data = xml.createElement(doc, "data");
                        }
                        data.appendChild(row);
                    }
                }
                if (data != null) {
                    docRoot.appendChild(data);
                }
            } finally {
                if (rs != null) {
                    try {
                        rs.close();
                    } catch (Exception exc) {
                        // do nothing
                    }
                    rs = null;
                }
            }
        }

        return doc;
    } finally {
        XMLUtils.releaseParserInstance(xml);
    }
}

From source file:org.apache.tika.parser.jdbc.JDBCTableReader.java

private void handleCell(ResultSetMetaData rsmd, int i, ContentHandler handler, ParseContext context)
        throws SQLException, IOException, SAXException {
    switch (rsmd.getColumnType(i)) {
    case Types.BLOB:
        handleBlob(tableName, rsmd.getColumnName(i), rows, results, i, handler, context);
        break;//ww  w.  ja  v  a  2s. c  om
    case Types.CLOB:
        handleClob(tableName, rsmd.getColumnName(i), rows, results, i, handler, context);
        break;
    case Types.BOOLEAN:
        handleBoolean(results, i, handler);
        break;
    case Types.DATE:
        handleDate(results, i, handler);
        break;
    case Types.TIMESTAMP:
        handleTimeStamp(results, i, handler);
        break;
    case Types.INTEGER:
        handleInteger(results, i, handler);
        break;
    case Types.FLOAT:
        //this is necessary to handle rounding issues in presentation
        //Should we just use getString(i)?
        float f = results.getFloat(i);
        if (!results.wasNull()) {
            addAllCharacters(Float.toString(f), handler);
        }
        break;
    case Types.DOUBLE:
        double d = results.getDouble(i);
        if (!results.wasNull()) {
            addAllCharacters(Double.toString(d), handler);
        }
        break;
    default:
        String s = results.getString(i);
        if (!results.wasNull()) {
            addAllCharacters(s, handler);
        }
        break;
    }
}

From source file:org.apache.ddlutils.platform.sybase.SybasePlatform.java

/**
 * Creates a new platform instance.//from  w ww  . java  2  s . co m
 */
public SybasePlatform() {
    PlatformInfo info = getPlatformInfo();

    info.setMaxIdentifierLength(28);
    info.setNullAsDefaultValueRequired(true);
    info.setIdentityColumnAutomaticallyRequired(true);
    info.setMultipleIdentityColumnsSupported(false);
    info.setPrimaryKeyColumnsHaveToBeRequired(true);
    info.setCommentPrefix("/*");
    info.setCommentSuffix("*/");

    info.addNativeTypeMapping(Types.ARRAY, "IMAGE");
    // BIGINT is mapped back in the model reader
    info.addNativeTypeMapping(Types.BIGINT, "DECIMAL(19,0)");
    // we're not using the native BIT type because it is rather limited (cannot be NULL, cannot be indexed)
    info.addNativeTypeMapping(Types.BIT, "SMALLINT", Types.SMALLINT);
    info.addNativeTypeMapping(Types.BLOB, "IMAGE", Types.LONGVARBINARY);
    info.addNativeTypeMapping(Types.BOOLEAN, "SMALLINT", Types.SMALLINT);
    info.addNativeTypeMapping(Types.CLOB, "TEXT", Types.LONGVARCHAR);
    info.addNativeTypeMapping(Types.DATALINK, "IMAGE", Types.LONGVARBINARY);
    info.addNativeTypeMapping(Types.DATE, "DATETIME", Types.TIMESTAMP);
    info.addNativeTypeMapping(Types.DISTINCT, "IMAGE", Types.LONGVARBINARY);
    info.addNativeTypeMapping(Types.DOUBLE, "DOUBLE PRECISION");
    info.addNativeTypeMapping(Types.FLOAT, "DOUBLE PRECISION", Types.DOUBLE);
    info.addNativeTypeMapping(Types.INTEGER, "INT");
    info.addNativeTypeMapping(Types.JAVA_OBJECT, "IMAGE", Types.LONGVARBINARY);
    info.addNativeTypeMapping(Types.LONGVARBINARY, "IMAGE");
    info.addNativeTypeMapping(Types.LONGVARCHAR, "TEXT");
    info.addNativeTypeMapping(Types.NULL, "IMAGE", Types.LONGVARBINARY);
    info.addNativeTypeMapping(Types.OTHER, "IMAGE", Types.LONGVARBINARY);
    info.addNativeTypeMapping(Types.REF, "IMAGE", Types.LONGVARBINARY);
    info.addNativeTypeMapping(Types.STRUCT, "IMAGE", Types.LONGVARBINARY);
    info.addNativeTypeMapping(Types.TIME, "DATETIME", Types.TIMESTAMP);
    info.addNativeTypeMapping(Types.TIMESTAMP, "DATETIME", Types.TIMESTAMP);
    info.addNativeTypeMapping(Types.TINYINT, "SMALLINT", Types.SMALLINT);

    info.setDefaultSize(Types.BINARY, 254);
    info.setDefaultSize(Types.VARBINARY, 254);
    info.setDefaultSize(Types.CHAR, 254);
    info.setDefaultSize(Types.VARCHAR, 254);

    setSqlBuilder(new SybaseBuilder(this));
    setModelReader(new SybaseModelReader(this));
}

From source file:org.georepublic.db.utils.ResultSetConverter.java

public static StringBuffer convertCsv(ResultSet rs) throws SQLException {

    String column_name = new String();
    StringBuffer retval = new StringBuffer();
    ResultSetMetaData rsmd = rs.getMetaData();
    int numColumns = rsmd.getColumnCount();

    for (int h = 1; h < numColumns + 1; h++) {
        column_name = rsmd.getColumnName(h);

        if (h > 1) {
            retval.append(",");
        }//  w w w .j a va  2s  . co m

        retval.append(column_name);
    }
    retval.append("\n");

    while (rs.next()) {

        for (int i = 1; i < numColumns + 1; i++) {
            column_name = rsmd.getColumnName(i);

            if (StringUtils.equals(column_name, "the_geom")) {
                continue;
            }
            if (StringUtils.equals(column_name, "geojson")) {
                continue;
            }
            if (i > 1) {
                retval.append(",");
            }

            if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) {
                retval.append(rs.getArray(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) {
                retval.append(rs.getInt(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) {
                retval.append(rs.getBoolean(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) {
                retval.append(rs.getBlob(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) {
                retval.append(rs.getDouble(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) {
                retval.append(rs.getFloat(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) {
                retval.append(rs.getInt(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) {
                retval.append(rs.getNString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.VARCHAR) {
                retval.append(rs.getString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) {
                retval.append(rs.getInt(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) {
                retval.append(rs.getInt(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) {
                retval.append(rs.getDate(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) {
                retval.append(rs.getTimestamp(column_name));
            } else {
                retval.append(rs.getObject(column_name));
            }

        }
        retval.append("\n");
    }

    return retval;
}

From source file:io.lightlink.types.BlobConverter.java

@Override
public Integer getSQLType() {
    return Types.BLOB;
}

From source file:com.adaptris.core.services.jdbc.types.BlobColumnTranslatorTest.java

@Test
public void testBlobWrite() throws Exception {
    BlobColumnTranslator translator = new BlobColumnTranslator();
    TestBlob blob = new TestBlob();
    String myData = new String("SomeData");
    blob.setBytes(0, myData.getBytes());

    JdbcResultRow row = new JdbcResultRow();
    row.setFieldValue("testField", blob, Types.BLOB);
    StringWriter writer = new StringWriter();
    try (OutputStream out = new WriterOutputStream(writer)) {
        translator.write(row, 0, out);//from  w  w  w. j a va 2s  .c  o m
    }
    String translated = writer.toString();
    assertEquals("SomeData", translated);
}