Example usage for java.sql Clob getAsciiStream

List of usage examples for java.sql Clob getAsciiStream

Introduction

In this page you can find the example usage for java.sql Clob getAsciiStream.

Prototype

java.io.InputStream getAsciiStream() throws SQLException;

Source Link

Document

Retrieves the CLOB value designated by this Clob object as an ascii stream.

Usage

From source file:com.mycompany.ssms.dao.ClobHelperClass.java

public static String ClobToString(Clob c) {
    try {/*w  ww. j  av  a 2  s. com*/
        return IOUtils.toString(c.getAsciiStream());
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:io.lavagna.service.SearchService.java

public static boolean searchTextClob(Clob data, String toSearch) {
    try (InputStream is = data.getAsciiStream()) {
        String res = StreamUtils.copyToString(is, StandardCharsets.UTF_8);
        return searchText(res, toSearch);
    } catch (IOException | SQLException e) {
        LOG.warn("error while reading clob", e);
        return false;
    }//  ww w . jav a 2 s . c  o  m
}

From source file:be.dataminded.nifi.plugins.util.JdbcCommon.java

public static long convertToAvroStream(final ResultSet rs, final OutputStream outStream, String recordName,
        ResultSetRowCallback callback, final int maxRows, boolean convertNames)
        throws SQLException, IOException {
    final Schema schema = createSchema(rs, recordName, convertNames);
    final GenericRecord rec = new GenericData.Record(schema);

    final DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(schema);
    try (final DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter)) {
        dataFileWriter.create(schema, outStream);

        final ResultSetMetaData meta = rs.getMetaData();
        final int nrOfColumns = meta.getColumnCount();
        long nrOfRows = 0;
        while (rs.next()) {
            if (callback != null) {
                callback.processRow(rs);
            }//from  www .j  a  v a2 s. c o  m
            for (int i = 1; i <= nrOfColumns; i++) {
                final int javaSqlType = meta.getColumnType(i);

                // Need to handle CLOB and BLOB before getObject() is called, due to ResultSet's maximum portability statement
                if (javaSqlType == CLOB) {
                    Clob clob = rs.getClob(i);
                    if (clob != null) {
                        long numChars = clob.length();
                        char[] buffer = new char[(int) numChars];
                        InputStream is = clob.getAsciiStream();
                        int index = 0;
                        int c = is.read();
                        while (c > 0) {
                            buffer[index++] = (char) c;
                            c = is.read();
                        }
                        rec.put(i - 1, new String(buffer));
                        clob.free();
                    } else {
                        rec.put(i - 1, null);
                    }
                    continue;
                }

                if (javaSqlType == BLOB) {
                    Blob blob = rs.getBlob(i);
                    if (blob != null) {
                        long numChars = blob.length();
                        byte[] buffer = new byte[(int) numChars];
                        InputStream is = blob.getBinaryStream();
                        int index = 0;
                        int c = is.read();
                        while (c > 0) {
                            buffer[index++] = (byte) c;
                            c = is.read();
                        }
                        ByteBuffer bb = ByteBuffer.wrap(buffer);
                        rec.put(i - 1, bb);
                        blob.free();
                    } else {
                        rec.put(i - 1, null);
                    }
                    continue;
                }

                final Object value = rs.getObject(i);

                if (value == null) {
                    rec.put(i - 1, null);

                } else if (javaSqlType == BINARY || javaSqlType == VARBINARY || javaSqlType == LONGVARBINARY
                        || javaSqlType == ARRAY) {
                    // bytes requires little bit different handling
                    byte[] bytes = rs.getBytes(i);
                    ByteBuffer bb = ByteBuffer.wrap(bytes);
                    rec.put(i - 1, bb);

                } else if (value instanceof Byte) {
                    // tinyint(1) type is returned by JDBC driver as java.sql.Types.TINYINT
                    // But value is returned by JDBC as java.lang.Byte
                    // (at least H2 JDBC works this way)
                    // direct put to avro record results:
                    // org.apache.avro.AvroRuntimeException: Unknown datum type java.lang.Byte
                    rec.put(i - 1, ((Byte) value).intValue());
                } else if (value instanceof Short) {
                    //MS SQL returns TINYINT as a Java Short, which Avro doesn't understand.
                    rec.put(i - 1, ((Short) value).intValue());
                } else if (value instanceof BigDecimal) {
                    // Avro can't handle BigDecimal as a number - it will throw an AvroRuntimeException such as: "Unknown datum type: java.math.BigDecimal: 38"
                    try {
                        int scale = meta.getScale(i);
                        BigDecimal bigDecimal = ((BigDecimal) value);
                        if (scale == 0) {
                            if (meta.getPrecision(i) < 10) {
                                rec.put(i - 1, bigDecimal.intValue());
                            } else {
                                rec.put(i - 1, bigDecimal.longValue());
                            }
                        } else {
                            rec.put(i - 1, bigDecimal.doubleValue());
                        }
                    } catch (Exception e) {
                        rec.put(i - 1, value.toString());
                    }
                } else if (value instanceof BigInteger) {
                    // Check the precision of the BIGINT. Some databases allow arbitrary precision (> 19), but Avro won't handle that.
                    // It the SQL type is BIGINT and the precision is between 0 and 19 (inclusive); if so, the BigInteger is likely a
                    // long (and the schema says it will be), so try to get its value as a long.
                    // Otherwise, Avro can't handle BigInteger as a number - it will throw an AvroRuntimeException
                    // such as: "Unknown datum type: java.math.BigInteger: 38". In this case the schema is expecting a string.
                    if (javaSqlType == BIGINT) {
                        int precision = meta.getPrecision(i);
                        if (precision < 0 || precision > MAX_DIGITS_IN_BIGINT) {
                            rec.put(i - 1, value.toString());
                        } else {
                            try {
                                rec.put(i - 1, ((BigInteger) value).longValueExact());
                            } catch (ArithmeticException ae) {
                                // Since the value won't fit in a long, convert it to a string
                                rec.put(i - 1, value.toString());
                            }
                        }
                    } else {
                        rec.put(i - 1, value.toString());
                    }

                } else if (value instanceof Number || value instanceof Boolean) {
                    if (javaSqlType == BIGINT) {
                        int precision = meta.getPrecision(i);
                        if (precision < 0 || precision > MAX_DIGITS_IN_BIGINT) {
                            rec.put(i - 1, value.toString());
                        } else {
                            rec.put(i - 1, value);
                        }
                    } else {
                        rec.put(i - 1, value);
                    }

                } else {
                    // The different types that we support are numbers (int, long, double, float),
                    // as well as boolean values and Strings. Since Avro doesn't provide
                    // timestamp types, we want to convert those to Strings. So we will cast anything other
                    // than numbers or booleans to strings by using the toString() method.
                    rec.put(i - 1, value.toString());
                }
            }
            dataFileWriter.append(rec);
            nrOfRows += 1;

            if (maxRows > 0 && nrOfRows == maxRows)
                break;
        }

        return nrOfRows;
    }
}

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

private void write(Clob blob, OutputStream out) throws SQLException, IOException {
    try (InputStream input = blob.getAsciiStream()) {
        copy(input, out);//from  w w w . j  ava  2 s .  co m
    }
}

From source file:com.gs.obevo.dbmetadata.impl.dialects.Db2MetadataDialect.java

private String clobToString(Clob clob) {
    if (clob == null) {
        return null;
    }/*from   w  w  w. j av a  2s .c  om*/

    try {
        InputStream in = clob.getAsciiStream();
        StringWriter w = new StringWriter();
        IOUtils.copy(in, w);
        return w.toString();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.gs.obevo.db.impl.platforms.oracle.OracleReveng.java

@Override
protected File printInstructions(PrintStream out, AquaRevengArgs args) {
    DbEnvironment env = getDbEnvironment(args);

    JdbcDataSourceFactory jdbcFactory = new OracleJdbcDataSourceFactory();
    DataSource ds = jdbcFactory.createDataSource(env, new Credential(args.getUsername(), args.getPassword()),
            1);/*  w ww .  j  ava2 s.c om*/
    JdbcHelper jdbc = new JdbcHelper(null, false);

    Path interim = new File(args.getOutputPath(), "interim").toPath();
    interim.toFile().mkdirs();
    try (Connection conn = ds.getConnection();
            BufferedWriter fileWriter = Files.newBufferedWriter(interim.resolve("output.sql"),
                    Charset.defaultCharset())) {
        // https://docs.oracle.com/database/121/ARPLS/d_metada.htm#BGBJBFGE
        // Note - can't remap schema name, object name, tablespace name within JDBC calls; we will leave that to the existing code in AbstractDdlReveng
        jdbc.update(conn,
                "{ CALL DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'STORAGE',false) }");

        MutableList<Map<String, Object>> maps = jdbc.queryForList(conn,
                "SELECT CASE WHEN OBJECT_TYPE = 'TABLE' THEN 1 WHEN OBJECT_TYPE = 'INDEX' THEN 2 ELSE 3 END SORT_ORDER,\n"
                        + "    OBJECT_TYPE,\n"
                        + "    dbms_metadata.get_ddl(REPLACE(object_type,' ','_'), object_name, owner) || ';' AS object_ddl\n"
                        + "FROM DBA_OBJECTS WHERE OWNER = '" + args.getDbSchema()
                        + "' AND OBJECT_TYPE NOT IN ('PACKAGE BODY', 'LOB','MATERIALIZED VIEW', 'TABLE PARTITION')\n"
                        + "ORDER BY 1");

        for (Map<String, Object> map : maps) {
            Clob clobObject = (Clob) map.get("OBJECT_DDL");
            InputStream in = clobObject.getAsciiStream();
            StringWriter w = new StringWriter();
            try {
                IOUtils.copy(in, w);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            String clobAsString = w.toString();
            clobAsString = clobAsString.replaceAll(";.*$", "");

            LOG.debug("Content for {}: ", map.get("OBJECT_TYPE"), clobAsString);
            fileWriter.write(clobAsString);
            fileWriter.newLine();
            fileWriter.write("~");
            fileWriter.newLine();
        }
    } catch (SQLException | IOException e) {
        throw new RuntimeException(e);
    }

    return interim.toFile();
}

From source file:com.headstrong.fusion.services.config.ConfigurationServiceImpl.java

/**
 * Reloads the schema definition from STRIDEHub Database.
 * //from w  w  w . j  a v  a2s.c  o m
 * @precondition
 * @postcondition
 * @throws SQLException
 * @throws ServiceConfigurationParseException
 * @throws ServiceUnavailableException
 * @throws ServiceNotFoundException
 */

public synchronized void reloadConfiguration(String processId)
        throws SQLException, ServiceConfigurationParseException, ServiceUnavailableException {
    ServiceConfigurationCache cache = ServiceConfigurationCache.getInstance();
    Connection connection = null;
    try {
        connection = DatabaseManager.getInstance(FusionConstants.FUSIONDB).getConnection();
    } catch (SQLException e1) {
        logger.error("Error getting the Fusion database connection", e1);
        throw e1;
    }

    if (connection != null) {

        /**
         * Schema table statement and result set
         */
        PreparedStatement serviceConfigStmt = null;
        ResultSet serviceConfigRs = null;

        try {

            serviceConfigStmt = connection.prepareStatement(serviceConfigurationQueryProcessIdCheck);
            serviceConfigStmt.setInt(1, Integer.parseInt(processId));
            serviceConfigRs = serviceConfigStmt.executeQuery();

            while (serviceConfigRs.next()) {
                ServiceConfiguration serviceConfiguration = new ServiceConfiguration();
                serviceConfiguration.setProcessId(serviceConfigRs.getString("prcs_id"));
                serviceConfiguration.setServiceId(serviceConfigRs.getString("service_id"));
                serviceConfiguration.setPropertyId(serviceConfigRs.getString("property_id"));

                Clob clob = serviceConfigRs.getClob("property_config");
                InputStream inputStream = clob.getAsciiStream();
                StringWriter writer = new StringWriter();
                IOUtils.copy(inputStream, writer, "UTF-8");

                Object propertyConfig = null;

                /*Object propertyConfig = serviceConfigRs
                      .getObject("property_config");*/
                String serviceType = serviceConfigRs.getString("service_type");
                // If config type is present search for the corresponding
                // parser.
                if (serviceType != null) {
                    try {
                        String parserType = serviceConfigurationParserRegistry.getServiceConfigurationParser(
                                serviceType, serviceConfiguration.getPropertyId());
                        ServiceConfigParser configurationParser = (ServiceConfigParser) ServiceAliasManager
                                .getInstance().getServiceByAlias(parserType, 0);
                        if (configurationParser != null) {
                            propertyConfig = configurationParser.parseConfiguration(writer.toString());
                        }
                    } catch (ServiceConfigurationParserNotFoundException e) {
                        // Currently being ignored. Need relook.
                        logger.error("No configuration parser found for service type " + serviceType
                                + " and property type " + serviceConfiguration.getPropertyId(), e);
                    }

                }
                cache.addPropertyConfiguration(serviceConfiguration, propertyConfig);
            }
        } catch (SQLException e) {
            logger.error("Error reading the service configuration.", e);
            throw e;
        } catch (ServiceConfigurationParseException e) {
            logger.error("Error parsing the service configuration.", e);
            throw e;
        } catch (IOException e) {
            logger.error("Error parsing the service configuration.", e);
            throw new ServiceConfigurationParseException("Error parsing the service configuration.", e);
        } catch (ServiceUnavailableException e) {
            logger.error("Error parsing the service configuration. "
                    + "No configuration parser service found for the config type.", e);
            throw e;
        } finally {
            DatabaseManager.releaseResources(connection, serviceConfigStmt, serviceConfigRs);
        }
    }
}

From source file:com.headstrong.fusion.services.config.ConfigurationServiceImpl.java

/**
 * Reloads the schema definition from STRIDEHub Database.
 * //  w  w  w  .j a va  2  s  . c o  m
 * @precondition
 * @postcondition
 * @throws SQLException
 * @throws ServiceConfigurationParseException
 * @throws ServiceUnavailableException
 * @throws ServiceNotFoundException
 */

public synchronized void reloadConfiguration()
        throws SQLException, ServiceConfigurationParseException, ServiceUnavailableException {
    ServiceConfigurationCache cache = ServiceConfigurationCache.getInstance();
    Connection connection = null;
    try {
        connection = DatabaseManager.getInstance(FusionConstants.FUSIONDB).getConnection();
    } catch (SQLException e1) {
        logger.error("Error getting the Fusion database connection", e1);
        throw e1;
    }

    if (connection != null) {

        /**
         * Schema table statement and result set
         */
        Statement serviceConfigStmt = null;
        ResultSet serviceConfigRs = null;

        try {

            serviceConfigStmt = connection.createStatement();
            serviceConfigRs = serviceConfigStmt.executeQuery(serviceConfigurationQuery);

            while (serviceConfigRs.next()) {
                ServiceConfiguration serviceConfiguration = new ServiceConfiguration();
                serviceConfiguration.setProcessId(serviceConfigRs.getString("prcs_id"));
                serviceConfiguration.setServiceId(serviceConfigRs.getString("service_id"));
                serviceConfiguration.setPropertyId(serviceConfigRs.getString("property_id"));

                Clob clob = serviceConfigRs.getClob("property_config");
                InputStream inputStream = clob.getAsciiStream();
                StringWriter writer = new StringWriter();
                IOUtils.copy(inputStream, writer, "UTF-8");
                Object propertyConfig = null;

                // TODO - Data type of property_config changed to CLOB to 
                // handle issue with data type size.
                /*Object propertyConfig = serviceConfigRs
                      .getObject("property_config");*/
                String serviceType = serviceConfigRs.getString("service_type");
                // If config type is present search for the corresponding
                // parser.
                if (serviceType != null) {
                    try {
                        String parserType = serviceConfigurationParserRegistry.getServiceConfigurationParser(
                                serviceType, serviceConfiguration.getPropertyId());
                        ServiceConfigParser configurationParser = (ServiceConfigParser) ServiceAliasManager
                                .getInstance().getServiceByAlias(parserType, 0);

                        if (configurationParser != null) {
                            propertyConfig = configurationParser.parseConfiguration(writer.toString());
                        }

                    } catch (ServiceConfigurationParserNotFoundException e) {
                        // Currently being ignored. Need relook.
                        logger.error("No configuration parser found for service type " + serviceType
                                + " and property type " + serviceConfiguration.getPropertyId(), e);
                    }

                }
                cache.addPropertyConfiguration(serviceConfiguration, propertyConfig);
            }
        } catch (SQLException e) {
            logger.error("Error reading the service configuration.", e);
            throw e;
        } catch (IOException e) {
            logger.error("Error parsing the service configuration.", e);
            throw new ServiceConfigurationParseException("Error parsing the service configuration.", e);
        } catch (ServiceConfigurationParseException e) {
            logger.error("Error parsing the service configuration.", e);
            throw e;
        } catch (ServiceUnavailableException e) {
            logger.error("Error parsing the service configuration. "
                    + "No configuration parser service found for the config type.", e);
            throw e;
        } finally {
            DatabaseManager.releaseResources(connection, serviceConfigStmt, serviceConfigRs);
        }
    }
}

From source file:nl.nn.adapterframework.util.JdbcUtil.java

public static InputStream getClobInputStream(Clob clob) throws SQLException, JdbcException {
    return clob.getAsciiStream();
}

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

/**
 * Get the Statement column so that the results are mapped correctly.
 * (this has been copied from AbstractDatabaseAction and modified slightly)
 *///from   w  w  w.  j a v a  2  s .  com
public static Object getColumn(ResultSet set, Configuration column) throws Exception {

    Integer type = (Integer) JDBCTypeConversions.typeConstants.get(column.getAttribute("type"));
    String dbcol = column.getAttribute("name");
    Object value = null;

    switch (type.intValue()) {
    case Types.CLOB:
    case Types.CHAR:
        Clob dbClob = set.getClob(dbcol);
        int length = (int) dbClob.length();
        InputStream asciiStream = new BufferedInputStream(dbClob.getAsciiStream());
        byte[] buffer = new byte[length];
        asciiStream.read(buffer);
        String str = new String(buffer);
        asciiStream.close();
        value = str;
        break;
    case Types.BIGINT:
        value = set.getBigDecimal(dbcol);
        break;
    case Types.TINYINT:
        value = new Byte(set.getByte(dbcol));
        break;
    case Types.VARCHAR:
        value = set.getString(dbcol);
        break;
    case Types.DATE:
        value = set.getDate(dbcol);
        break;
    case Types.DOUBLE:
        value = new Double(set.getDouble(dbcol));
        break;
    case Types.FLOAT:
        value = new Float(set.getFloat(dbcol));
        break;
    case Types.INTEGER:
        value = new Integer(set.getInt(dbcol));
        break;
    case Types.NUMERIC:
        value = new Long(set.getLong(dbcol));
        break;
    case Types.SMALLINT:
        value = new Short(set.getShort(dbcol));
        break;
    case Types.TIME:
        value = set.getTime(dbcol);
        break;
    case Types.TIMESTAMP:
        value = set.getTimestamp(dbcol);
        break;
    case Types.ARRAY:
        value = set.getArray(dbcol); // new Integer(set.getInt(dbcol));
        break;
    case Types.BIT:
        value = BooleanUtils.toBooleanObject(set.getBoolean(dbcol));
        break;
    case Types.STRUCT:
        value = (Struct) set.getObject(dbcol);
        break;
    case Types.OTHER:
        value = set.getObject(dbcol);
        break;

    default:
        // The blob types have to be requested separately, via a Reader.
        value = "";
        break;
    }

    return value;
}