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:org.apache.nifi.processors.standard.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);
            }//  w  w w  .  ja v  a  2  s  .c  om
            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"
                    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:org.batoo.jpa.jdbc.AbstractColumn.java

private Object readLob(Object value) {
    try {/*w  ww  .  j av a2s.c o m*/
        if (value instanceof Clob) {
            final Clob clob = (Clob) value;

            if (this.javaType == String.class) {
                final StringWriter w = new StringWriter();
                IOUtils.copy(clob.getAsciiStream(), w);
                value = w.toString();
            } else {
                final CharArrayWriter w = new CharArrayWriter((int) clob.length());
                IOUtils.copy(clob.getCharacterStream(), w);
                value = w.toCharArray();
            }
        } else if (value instanceof byte[]) {
            if (this.javaType == String.class) {
                final StringWriter w = new StringWriter();
                IOUtils.copy(new ByteArrayInputStream((byte[]) value), w);
                value = w.toString();
            } else if (this.javaType == char[].class) {
                final byte[] byteArray = (byte[]) value;

                final char[] charArray = new char[byteArray.length];

                for (int i = 0; i < charArray.length; i++) {
                    charArray[i] = (char) byteArray[i];
                }

                value = charArray;
            } else if (this.javaType != byte[].class) {
                final ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream((byte[]) value));
                try {
                    return is.readObject();
                } finally {
                    is.close();
                }
            }
        } else if (value instanceof String) {
            return value;
        } else {
            final Blob blob = (Blob) value;

            if (this.javaType == byte[].class) {
                final ByteArrayOutputStream os = new ByteArrayOutputStream();

                IOUtils.copy(blob.getBinaryStream(), os);

                value = os.toByteArray();
            } else {

                final ObjectInputStream is = new ObjectInputStream(blob.getBinaryStream());
                try {
                    value = is.readObject();
                } finally {
                    is.close();
                }
            }
        }
        return value;
    } catch (final Exception e) {
        throw new PersistenceException("Cannot read sql data", e);
    }
}

From source file:org.batoo.jpa.jdbc.ValueConverter.java

private static Object readLob(Object value, Class<?> javaType) {
    try {//from  www.  j av  a  2  s.c o  m
        if (value instanceof Clob) {
            final Clob clob = (Clob) value;

            if (javaType == String.class) {
                final StringWriter w = new StringWriter();
                IOUtils.copy(clob.getAsciiStream(), w);
                value = w.toString();
            } else {
                final CharArrayWriter w = new CharArrayWriter((int) clob.length());
                IOUtils.copy(clob.getCharacterStream(), w);
                value = w.toCharArray();
            }
        } else if (value instanceof byte[]) {
            if (javaType == String.class) {
                final StringWriter w = new StringWriter();
                IOUtils.copy(new ByteArrayInputStream((byte[]) value), w);
                value = w.toString();
            } else if (javaType == char[].class) {
                final byte[] byteArray = (byte[]) value;

                final char[] charArray = new char[byteArray.length];

                for (int i = 0; i < charArray.length; i++) {
                    charArray[i] = (char) byteArray[i];
                }

                value = charArray;
            } else if (javaType != byte[].class) {
                final ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream((byte[]) value));
                try {
                    return is.readObject();
                } finally {
                    is.close();
                }
            }
        } else if (value instanceof String) {
            return value;
        } else {
            final Blob blob = (Blob) value;

            if (javaType == byte[].class) {
                final ByteArrayOutputStream os = new ByteArrayOutputStream();

                IOUtils.copy(blob.getBinaryStream(), os);

                value = os.toByteArray();
            } else {

                final ObjectInputStream is = new ObjectInputStream(blob.getBinaryStream());
                try {
                    value = is.readObject();
                } finally {
                    is.close();
                }
            }
        }
        return value;
    } catch (final Exception e) {
        throw new PersistenceException("Cannot read sql data", e);
    }
}

From source file:org.eclipse.smila.connectivity.framework.crawler.jdbc.JdbcCrawler.java

/**
 * /*from  www  . jav  a 2 s.c  o  m*/
 * Creates a {@link Record}-object for the passed data and metadata.
 * 
 * @param data
 *          The data to be used for the {@link Record} - an {@link Object[]} constituting a database row.
 * @return The created {@link Record}-object.
 * @throws CrawlerCriticalException
 *           If any of the specified {@link #_attributes} could not be extracted from the {@code data}.
 * 
 */
private Record createRecord(final Object[] data) throws CrawlerCriticalException {
    final Record record = _dataFactory.createRecord();
    final AnyMap metaData = record.getMetadata();

    for (final Attribute attribute : _attributes) {
        if (attribute.isAttachment()) {
            // set Attachment attributes as Attachments to the record
            final Object attachmentValue = readAttribute(data, attribute);
            if (attachmentValue != null) {
                if (attachmentValue instanceof String) {
                    try {
                        record.setAttachment(attribute.getName(), ((String) attachmentValue).getBytes("utf-8"));
                    } catch (final UnsupportedEncodingException exception) {
                        _log.warn("UTF-8 Encoding ist not supported by this VM. (Very unlikely...)", exception);
                    }
                } else if (attachmentValue instanceof byte[]) {
                    record.setAttachment(attribute.getName(), (byte[]) attachmentValue);
                } else if (attachmentValue instanceof Blob) {
                    final Blob blob = (Blob) attachmentValue;
                    byte[] byteValue = null;
                    try {
                        byteValue = IOUtils.toByteArray(blob.getBinaryStream());
                    } catch (final IOException exception) {
                        _log.error(
                                "Encountered IOException when getting byte[]-Value of BLOB-Stream for attribute ["
                                        + attribute.getName() + "]. Assigning null-Value.",
                                exception);
                        byteValue = null;
                    } catch (final SQLException exception) {
                        _log.error("Encountered SQLException when retrieving BLOB-Stream for attribute ["
                                + attribute.getName() + "]. Assigning null-Value.", exception);
                        byteValue = null;
                    }
                    record.setAttachment(attribute.getName(), byteValue);

                } else if (attachmentValue instanceof Clob) {
                    final Clob clob = (Clob) attachmentValue;
                    byte[] byteValue = null;
                    try {
                        byteValue = IOUtils.toByteArray(clob.getAsciiStream());
                    } catch (final IOException exception) {
                        _log.error(
                                "Encountered IOException when getting byte[]-Value of CLOB-Stream for attribute ["
                                        + attribute.getName() + "]. Assigning null-Value.",
                                exception);
                        byteValue = null;
                    } catch (final SQLException exception) {
                        _log.error("Encountered SQLException when retrieving CLOB-Stream for attribute ["
                                + attribute.getName() + "]. Assigning null-Value.", exception);
                        byteValue = null;
                    }
                    record.setAttachment(attribute.getName(), byteValue);
                } else {
                    throw new IllegalArgumentException(
                            "Unsupported Attachment type [" + attachmentValue.getClass().getName() + "]");
                }
            }
            // else: attribute is NOT an attachment ...
        } else {
            final Object value = readAttribute(data, attribute);
            if (value != null) {
                if (value instanceof Object[]) {
                    try {
                        final AnySeq anySeq = record.getFactory().createAnySeq();
                        for (Object object : (Object[]) value) {
                            anySeq.add(record.getFactory().parseFromObject(object));
                        }
                        metaData.put(attribute.getName(), anySeq);
                    } catch (final InvalidValueTypeException exception) {
                        _log.error("Could not set value of attribute [" + attribute.getName()
                                + "] as LiteralArrayAttribute.", exception);
                    }
                } else {
                    try {
                        metaData.put(attribute.getName(), record.getFactory().parseFromObject(value));
                    } catch (final InvalidValueTypeException exception) {
                        _log.error("Could not set value of attribute [" + attribute.getName()
                                + "] as SimpleLiteralAttribute.", exception);
                    }
                }
            }
        }

    }
    return record;
}

From source file:org.jboss.bqt.client.results.xml.XMLCompareResults.java

/**
 * Compare actual results, identifiers and types with expected. <br>
 * <strong>Note </strong>: result list are expected to match element for
 * element.</br>//www.j a  va2  s. co m
 * 
 * @param actualResults
 * @param actualDatatypes
 * @param actualIdentifiers
 * @param expectedResults
 * @param expectedDatatypes
 * @param expectedIdentifiers
 * @param eMsg
 * @throws QueryTestFailedException
 *             If comparison fails.
 */
private static void compareResultSets(final List actualResults, final List actualDatatypes,
        final List actualIdentifiers, final List expectedResults, final List expectedDatatypes,
        final List expectedIdentifiers, final String eMsg) throws QueryTestFailedException {
    // Compare column names and types
    compareIdentifiers(actualIdentifiers, expectedIdentifiers, actualDatatypes, expectedDatatypes);

    // Walk through records and compare actual against expected
    final int actualRowCount = actualResults.size();
    final int expectedRowCount = expectedResults.size();
    final int actualColumnCount = actualIdentifiers.size();

    // Check for less records than in expected results
    if (actualRowCount < expectedRowCount) {
        throw new QueryTestFailedException(eMsg + "Expected " + expectedRowCount + //$NON-NLS-1$
                " records but received only " + actualRowCount); //$NON-NLS-1$
    } else if (actualRowCount > expectedRowCount) {
        // Check also for more records than expected
        throw new QueryTestFailedException(eMsg + "Expected " + expectedRowCount + //$NON-NLS-1$
                " records but received " + actualRowCount); //$NON-NLS-1$
    }

    // DEBUG:
    // debugOut.println("================== Compariing Rows ===================");

    // Loop through rows
    for (int row = 0; row < actualRowCount; row++) {

        // Get actual record
        final List actualRecord = (List) actualResults.get(row);

        // Get expected record
        final List expectedRecord = (List) expectedResults.get(row);

        // DEBUG:
        // debugOut.println("Row: " + (row + 1));
        // debugOut.println(" expectedRecord: " + expectedRecord);
        // debugOut.println(" actualRecord: " + actualRecord);
        // Loop through columns
        // Compare actual elements with expected elements column by column
        // in this row
        for (int col = 0; col < actualColumnCount; col++) {
            // Get actual value
            Object actualValue = actualRecord.get(col);
            // Get expected value
            Object expectedValue = expectedRecord.get(col);

            // DEBUG:
            // debugOut.println(" Col: " +(col +1) + ": expectedValue:[" +
            // expectedValue + "] actualValue:[" + actualValue +
            // "]");

            // Compare these values
            if ((expectedValue == null && actualValue != null)
                    || (actualValue == null && expectedValue != null)) {
                // Compare nulls
                throw new QueryTestFailedException(eMsg + "Value mismatch at row " + (row + 1) //$NON-NLS-1$
                        + " and column " + (col + 1) //$NON-NLS-1$
                        + ": expected = [" //$NON-NLS-1$
                        + (expectedValue != null ? expectedValue : "null") + "], actual = [" //$NON-NLS-1$
                        + (actualValue != null ? actualValue : "null") + "]"); //$NON-NLS-1$

            }

            if (expectedValue == null && actualValue == null) {
                continue;
            }

            if (actualValue instanceof Blob || actualValue instanceof Clob || actualValue instanceof SQLXML) {

                if (actualValue instanceof Clob) {
                    Clob c = (Clob) actualValue;
                    try {
                        actualValue = ObjectConverterUtil.convertToString(c.getAsciiStream());

                    } catch (Throwable e) {
                        // TODO Auto-generated catch block
                        throw new QueryTestFailedException(e);
                    }
                } else if (actualValue instanceof Blob) {
                    Blob b = (Blob) actualValue;
                    try {
                        byte[] ba = ObjectConverterUtil.convertToByteArray(b.getBinaryStream());

                        actualValue = String.valueOf(ba.length);

                        // actualValue =
                        // ObjectConverterUtil.convertToString(b.getBinaryStream());

                    } catch (Throwable e) {
                        // TODO Auto-generated catch block
                        throw new QueryTestFailedException(e);
                    }
                } else if (actualValue instanceof SQLXML) {
                    SQLXML s = (SQLXML) actualValue;
                    try {
                        actualValue = ObjectConverterUtil.convertToString(s.getBinaryStream());

                    } catch (Throwable e) {
                        // TODO Auto-generated catch block
                        throw new QueryTestFailedException(e);
                    }
                }

                if (!(expectedValue instanceof String)) {
                    expectedValue = expectedValue.toString();
                }
            }

            // Compare values with equals
            if (!expectedValue.equals(actualValue)) {
                // DEBUG:

                if (expectedValue instanceof java.sql.Date) {
                    expectedValue = expectedValue.toString();
                    actualValue = actualValue.toString();

                } else if (expectedValue instanceof java.sql.Time) {
                    expectedValue = expectedValue.toString();
                    actualValue = actualValue.toString();

                }

                if (expectedValue instanceof String) {
                    final String expectedString = (String) expectedValue;

                    if (!(actualValue instanceof String)) {
                        throw new QueryTestFailedException(eMsg + "Value (types) mismatch at row " + (row + 1) //$NON-NLS-1$
                                + " and column " + (col + 1) //$NON-NLS-1$
                                + ": expected = [" //$NON-NLS-1$
                                + expectedValue + ", (String) ], actual = [" //$NON-NLS-1$
                                + actualValue + ", (" + actualValue.getClass().getName() + ") ]"); //$NON-NLS-1$
                    }

                    // Check for String difference
                    assertStringsMatch(expectedString, (String) actualValue, (row + 1), (col + 1), eMsg);

                } else {

                    throw new QueryTestFailedException(eMsg + "Value mismatch at row " + (row + 1) //$NON-NLS-1$
                            + " and column " + (col + 1) //$NON-NLS-1$
                            + ": expected = [" //$NON-NLS-1$
                            + expectedValue + "], actual = [" //$NON-NLS-1$
                            + actualValue + "]"); //$NON-NLS-1$

                }
            }

        } // end loop through columns
    } // end loop through rows
}

From source file:org.jboss.bqt.client.xml.XMLQueryVisitationStrategy.java

/**
 * Produce an XML message for an instance of the Object.
 * <br>//from   w w  w .  jav  a  2 s.c o  m
 * @param object the instance for which the message is to be produced.
 * @param parent the XML element that is to be the parent of the produced XML message.
 * @return the root element of the XML segment that was produced.
 * @exception JDOMException if there is an error producing the message.
 * @throws SQLException 
 */
private Element produceObject(Object object, Element parent) throws JDOMException, SQLException {

    // ----------------------
    // Create the Object element ...
    // ----------------------
    Element objectElement = new Element(TagNames.Elements.OBJECT);

    String result = null;
    if (object instanceof Blob || object instanceof Clob || object instanceof SQLXML) {

        if (object instanceof Clob) {
            Clob c = (Clob) object;
            try {
                result = ObjectConverterUtil.convertToString(c.getAsciiStream());

            } catch (Throwable e) {
                // TODO Auto-generated catch block
                throw new SQLException(e);
            }
        } else if (object instanceof Blob) {
            Blob b = (Blob) object;
            try {
                byte[] ba = ObjectConverterUtil.convertToByteArray(b.getBinaryStream());

                result = String.valueOf(ba.length);

            } catch (Throwable e) {
                // TODO Auto-generated catch block
                throw new SQLException(e);
            }
        } else if (object instanceof SQLXML) {

            SQLXML s = (SQLXML) object;
            try {
                result = ObjectConverterUtil.convertToString(s.getBinaryStream());

            } catch (Throwable e) {
                // TODO Auto-generated catch block
                throw new SQLException(e);
            }
        }
    } else {
        result = object.toString();
    }

    objectElement.setText(result);

    if (parent != null) {
        objectElement = parent.addContent(objectElement);
    }

    return objectElement;
}

From source file:org.kawanfw.test.api.client.InsertAndUpdateClobTestAsciiStream.java

/**
 * Test that the blob was were correctly inserted
 * /*w w w .ja  va 2s.  c om*/
 * @param connection
 */
public void selectClobTestAlternateSyntax(Connection connection, String originalFileName, String shaHexa)
        throws Exception {

    int item_id;
    Clob clob;

    String sql = "select * from documentation where item_id >= ? ";

    PreparedStatement prepStatement = connection.prepareStatement(sql);

    int i = 1;
    prepStatement.setInt(i++, 1);

    ResultSet rs = prepStatement.executeQuery();

    MessageDisplayer.display("");

    InputStream in = null;
    Writer writer = null;

    while (rs.next()) {

        item_id = rs.getInt("item_id");

        i = 1;
        item_id = rs.getInt(i++);
        clob = rs.getClob(i++);

        File originalFile = SqlTestParms.getFileFromUserHome(originalFileName);
        // String extension = "."
        // + StringUtils.substringAfterLast(originalFile.toString(),
        // ".");

        File file = InsertAndUpdateBlobTest.createTempFile(originalFile.toString());

        try {
            in = clob.getAsciiStream();

            if (in != null) {
                Reader reader = new InputStreamReader(in);
                writer = new BufferedWriter(new FileWriter(file));
                IOUtils.copy(reader, writer);
            } else {
                MessageDisplayer.display("item_doc column is null!");
            }

        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(writer);
            try {
                clob.free();
            } catch (Throwable e) {
                MessageDisplayer.display("clob.free() not done: " + e.toString());
            }
        }

        MessageDisplayer.display("");
        MessageDisplayer.display("item_id     : " + item_id);

        // Compute the hash of the file
        Sha1Util sha1 = new Sha1Util();
        String shaHexaNew = sha1.getHexFileHash(file);

        Assert.assertEquals(shaHexa, shaHexaNew);

        file.delete();

        MessageDisplayer.display("");
        MessageDisplayer.display("Ok, SHA-1 value of read file " + file + " is same as inserted file "
                + SqlTestParms.getFileFromUserHome(originalFileName));

    }

    prepStatement.close();
    rs.close();

    MessageDisplayer.display("Select done!");

}

From source file:org.sakaiproject.chat2.model.impl.ChatDataMigration.java

protected void runChannelMigration(Connection con) {
    logger.debug("runChannelMigration()");
    printDebug("*******GETTING CHANNELS");

    String sql = getMessageFromBundle("select.oldchannels");

    int oldChannelsFound = 0;
    int newChannelsWritten = 0;

    try {/*from   w ww. ja  v a  2 s .co m*/
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(sql);

        try {
            while (rs.next()) {
                oldChannelsFound++;

                if ((oldChannelsFound % 5000) == 0) {
                    logger.info("Processed channels: " + oldChannelsFound);
                }
                /* 
                 * CHANNEL_ID
                 * XML
                 */
                String oldId = rs.getString("CHANNEL_ID");
                Object xml = rs.getObject("XML");

                printDebug("*******FOUND CHANNEL: " + oldId);
                printDebug("*******FOUND CHANNEL: " + xml);

                Document doc = null;
                try {
                    doc = Xml.readDocumentFromString((String) xml);
                } catch (ClassCastException cce) {
                    Clob xmlClob = (Clob) xml;
                    doc = Xml.readDocumentFromStream(xmlClob.getAsciiStream());
                }

                if (doc == null) {
                    logger.error("error converting chat channel. skipping CHANNEL_ID: [" + oldId + "] XML: ["
                            + xml + "]");
                    continue;
                }

                // verify the root element
                Element root = doc.getDocumentElement();
                String context = root.getAttribute("context");
                String title = root.getAttribute("id");
                String newChannelId = escapeSpecialCharsForId(oldId);

                //TODO Chat lookup the config params?

                newChannelsWritten++;
                String runSql = getMessageFromBundle("insert.channel");
                Object[] fields = new Object[] { newChannelId, context, null, title, "", "SelectMessagesByTime",
                        3, 0, 1, oldId, oldId };

                /* 
                 * CHANNEL_ID, 
                 * CONTEXT, 
                 * CREATION_DATE, 
                 * title, 
                 * description, 
                 * filterType, 
                 * filterParam, 
                 * placementDefaultChannel, 
                 * migratedChannelId,
                 * ENABLE_USER_OVERRIDE
                 */

                if (chatMigrationExecuteImmediate) {
                    sqlService.dbWrite(null, runSql, fields);
                }
            }
        } finally {
            rs.close();
        }
    } catch (Exception e) {
        logger.error("error selecting data with this sql: " + sql);
        logger.error("", e);
    } finally {
        try {
            stmt.close();
        } catch (Exception e) {
            logger.error("Unexpected error in chat channel conversion:" + e);
        }
    }
    logger.debug("Migration task fininshed: runChannelMigration()");
    logger.info("chat channel conversion done.  Old channels found: " + oldChannelsFound
            + " New channels written: " + newChannelsWritten);
}

From source file:org.sakaiproject.chat2.model.impl.ChatDataMigration.java

protected void runMessageMigration(Connection con) {
    logger.debug("runMessageMigration()");
    printDebug("*******GETTING MESSAGES");

    String sql = getMessageFromBundle("select.oldmessages");

    int oldMessagesFound = 0;
    int newMessagesWritten = 0;

    try {//from  ww w.j ava 2  s  .  c  o m
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(sql);

        try {
            while (rs.next()) {
                oldMessagesFound++;

                if ((oldMessagesFound % 5000) == 0) {
                    logger.info("Processed messages: " + oldMessagesFound);
                }
                /*
                 * MESSAGE_ID
                 * CHANNEL_ID                            
                 * XML
                 * OWNER                          
                 * MESSAGE_DATE
                 */
                String oldMessageId = rs.getString("MESSAGE_ID");
                String oldChannelId = rs.getString("CHANNEL_ID");
                Object xml = rs.getObject("XML");
                String owner = rs.getString("OWNER");
                Date messageDate = rs.getTimestamp("MESSAGE_DATE");

                printDebug("*******FOUND MESSAGE: " + oldMessageId);
                printDebug("*******FOUND MESSAGE: " + xml);

                Document doc = null;
                try {
                    doc = Xml.readDocumentFromString((String) xml);
                } catch (ClassCastException cce) {
                    Clob xmlClob = (Clob) xml;
                    doc = Xml.readDocumentFromStream(xmlClob.getAsciiStream());
                }

                if (doc == null) {
                    logger.error("error converting chat message. " + "skipping CHANNEL_ID: [" + oldChannelId
                            + "] MESSAGE_ID: [" + oldMessageId + "]" + " xml: " + xml);
                    continue;
                }

                // verify the root element
                Element root = doc.getDocumentElement();
                String body = Xml.decodeAttribute(root, "body");

                String newMessageId = oldMessageId;
                String runSql = getMessageFromBundle("insert.message");

                newMessagesWritten++;

                Object[] fields = new Object[] { escapeSpecialCharsForId(newMessageId),
                        escapeSpecialCharsForId(oldChannelId), owner, messageDate, body, oldMessageId };

                /*
                 * insert into CHAT2_MESSAGE (MESSAGE_ID, CHANNEL_ID, OWNER, MESSAGE_DATE, BODY) \
                values ('{0}', '{1}', '{2}', '{3}', '{4}');
                        
                */

                if (chatMigrationExecuteImmediate) {
                    getChatManager().migrateMessage(runSql, fields);
                }
            }
        } finally {
            rs.close();
        }
    } catch (Exception e) {
        logger.error("error selecting data with this sql: " + sql);
        logger.error("", e);
    } finally {
        try {
            stmt.close();
        } catch (Exception e) {
            logger.error("Unexpected error in chat message conversion:" + e);
        }
    }
    logger.debug("Migration task fininshed: runMessageMigration()");
    logger.info("chat message conversion done.  Old messages found: " + oldMessagesFound
            + " New messages written: " + newMessagesWritten);
}

From source file:org.sonar.db.AbstractDbTester.java

private static List<Map<String, Object>> getHashMap(ResultSet resultSet) throws Exception {
    ResultSetMetaData metaData = resultSet.getMetaData();
    int colCount = metaData.getColumnCount();
    List<Map<String, Object>> rows = newArrayList();
    while (resultSet.next()) {
        Map<String, Object> columns = newHashMap();
        for (int i = 1; i <= colCount; i++) {
            Object value = resultSet.getObject(i);
            if (value instanceof Clob) {
                Clob clob = (Clob) value;
                value = IOUtils.toString((clob.getAsciiStream()));
                doClobFree(clob);//  w  ww .jav a 2s  . co m
            } else if (value instanceof BigDecimal) {
                // In Oracle, INTEGER types are mapped as BigDecimal
                BigDecimal bgValue = ((BigDecimal) value);
                if (bgValue.scale() == 0) {
                    value = bgValue.longValue();
                } else {
                    value = bgValue.doubleValue();
                }
            } else if (value instanceof Integer) {
                // To be consistent, all INTEGER types are mapped as Long
                value = ((Integer) value).longValue();
            } else if (value instanceof Timestamp) {
                value = new Date(((Timestamp) value).getTime());
            }
            columns.put(metaData.getColumnLabel(i), value);
        }
        rows.add(columns);
    }
    return rows;
}