Example usage for java.sql Clob length

List of usage examples for java.sql Clob length

Introduction

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

Prototype

long length() throws SQLException;

Source Link

Document

Retrieves the number of characters in the CLOB value designated by this Clob object.

Usage

From source file:com.quinsoft.zeidon.dbhandler.StandardJdbcTranslator.java

/**
 * Takes a value loaded from the DB and potentially converts it.
 *///  www .j  av a 2 s .  com
@Override
public Object convertDbValue(Domain domain, Object dbValue) throws SQLException {
    if (dbValue instanceof Clob) {
        Clob clob = (Clob) dbValue;
        return clob.getSubString(1L, (int) clob.length());
    }

    if (domain instanceof DateDomain) {
        if (dbValue instanceof CharSequence) {
            String date = dbValue.toString();
            try {
                return this.dateFormatter.parseDateTime(date);
            } catch (IllegalArgumentException e) {
                throw ZeidonException.prependMessage(e,
                        "Invalid date format.  Got '%s' but expected format '%s'", date, dateFormatter);
            }
        } else if (dbValue instanceof Date) {
            return new DateTime(dbValue);
        }
    }

    if (domain instanceof DateTimeDomain) {
        if (dbValue instanceof CharSequence) {
            String date = dbValue.toString();
            try {
                return dateTimeFormatter.parseDateTime(date);
            } catch (IllegalArgumentException e) {
                throw ZeidonException.prependMessage(e,
                        "Invalid datetime format.  Got '%s' but expected format '%s'", date, dateTimeFormatter);
            }
        }
    }

    return dbValue;
}

From source file:com.recomdata.transmart.data.export.util.FileWriterUtil.java

public String getClobAsString(Clob clob) {
    String strVal = "";
    Reader reader = null;/*from ww  w.  j  av a 2s  . co  m*/
    StringBuffer strBuf = null;
    try {
        if (null != clob) {
            Long clobLength = (null != clob) ? clob.length() : 0;
            reader = clob.getCharacterStream();

            if (null != clobLength && clobLength > 0 && null != reader) {
                //Here length of String is being rounded to 5000 * n, this is because the buffer size is 5000
                //Sometimes the cloblength is less than 5000 * n
                char[] buffer = new char[clobLength.intValue()];
                @SuppressWarnings("unused")
                int count = 0;
                strBuf = new StringBuffer();
                while ((count = reader.read(buffer)) > 0) {
                    strBuf.append(buffer);
                }
                strVal = strBuf.toString();
            }
        }
    } catch (IOException e) {
        log.info(e.getMessage());
    } catch (SQLException e2) {
        log.info("SQLException :: " + e2.getMessage());
    } finally {
        try {
            if (null != reader)
                reader.close();

            //Nullify the objects so they become ready for Garbage Collection
            reader = null;
            strBuf = null;
            clob = null;
            super.finalize();
        } catch (IOException e) {
            log.info("Error closing Reader in getClobAsString");
        } catch (Throwable e) {
            log.info("Error during super.finalize()");
        }
    }

    return strVal;
}

From source file:com.mirth.connect.server.mule.transformers.ResultMapToXML.java

public Object doTransform(Object source) throws TransformerException {
    if (source instanceof Map) {
        Map data = (Map) source;

        try {//from   www  .ja va2s  . c  o m
            Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
            Element root = document.createElement("result");
            document.appendChild(root);

            for (Iterator iter = data.keySet().iterator(); iter.hasNext();) {
                String key = (String) iter.next();
                Element child = document.createElement(key);
                String value = new String();
                Object objectValue = data.get(key);
                if (objectValue != null) {
                    if (objectValue instanceof byte[]) {
                        value = new String((byte[]) objectValue);
                    } else if (objectValue instanceof java.sql.Clob) {
                        // convert it to a string
                        java.sql.Clob clobValue = (java.sql.Clob) objectValue;
                        Reader reader = clobValue.getCharacterStream();
                        if (reader == null) {
                            value = "";
                        }
                        StringBuffer sb = new StringBuffer();
                        try {
                            char[] charbuf = new char[(int) clobValue.length()];
                            for (int i = reader.read(charbuf); i > 0; i = reader.read(charbuf)) {
                                sb.append(charbuf, 0, i);
                            }
                        } catch (IOException e) {
                            logger.error("Error reading clob value.\n" + ExceptionUtils.getStackTrace(e));

                        }
                        value = sb.toString();
                    } else if (objectValue instanceof java.sql.Blob) {
                        try {
                            java.sql.Blob blobValue = (java.sql.Blob) objectValue;
                            value = new String(blobValue.getBytes(1, (int) blobValue.length()));
                        } catch (Exception ex) {
                            logger.error("Error reading blob value.\n" + ExceptionUtils.getStackTrace(ex));
                        }
                    } else {
                        value = objectValue.toString();
                    }

                }
                child.appendChild(document.createTextNode(value));
                root.appendChild(child);
            }

            DocumentSerializer docSerializer = new DocumentSerializer();
            return docSerializer.toXML(document);
        } catch (Exception e) {
            throw new TransformerException(
                    org.mule.config.i18n.Message.createStaticMessage("Failed to parse result map"), this);
        }
    } else if (source instanceof String) {
        return source.toString();
    } else {
        throw new TransformerException(
                org.mule.config.i18n.Message.createStaticMessage("Unregistered result type"), this);
    }
}

From source file:com.oracle.tutorial.jdbc.ClobSample.java

public String retrieveExcerpt(String coffeeName, int numChar) throws SQLException {

    String description = null;/* w w  w.  j  av  a  2 s.  c  om*/
    Clob myClob = null;
    PreparedStatement pstmt = null;

    try {
        String sql = "select COF_DESC from COFFEE_DESCRIPTIONS " + "where COF_NAME = ?";
        pstmt = this.con.prepareStatement(sql);
        pstmt.setString(1, coffeeName);
        ResultSet rs = pstmt.executeQuery();
        if (rs.next()) {
            myClob = rs.getClob(1);
            System.out.println("Length of retrieved Clob: " + myClob.length());
        }
        description = myClob.getSubString(1, numChar);
    } catch (SQLException sqlex) {
        JDBCTutorialUtilities.printSQLException(sqlex);
    } catch (Exception ex) {
        System.out.println("Unexpected exception: " + ex.toString());
    } finally {
        if (pstmt != null)
            pstmt.close();
    }
    return description;
}

From source file:ca.hec.cdm.jobs.ImportZC1CatalogDescriptionJob.java

public void execute(JobExecutionContext arg0) throws JobExecutionException {

    Connection connex = getZC1Connection();
    PreparedStatement ps = null;//from  w  ww .j av  a2  s . c  om

    try {
        ps = connex.prepareStatement(ZC1_REQUEST);

        ResultSet rs = ps.executeQuery();

        while (rs.next()) {

            String koid = rs.getString(1);
            Clob htmlClob = rs.getClob(2);

            // ajouter pour la table plancours
            if (koid.substring(0, 2).equalsIgnoreCase("a-")) {
                koid = koid.substring(2);
            }

            String courseId = FormatUtils.formatCourseId(koid);

            String html = htmlClob.getSubString((long) 1, (int) htmlClob.length());
            String desc = formatHtml(html);

            if (desc != null) {
                saveInZC2(courseId, desc);
            } else {
                log.error("No description found in ZC1 for: " + courseId);
                noDesc++;
            }

        } // end while

        log.error("----------------------------------------------------------------------------------");
        log.error("FIN DE LA JOB");
        log.error("saved desc:" + savedDesc);
        log.error("unknow desc:" + unknownDesc);
        log.error("no desc found:" + noDesc);
        log.error("Description is not null:" + notNullDesc);
    } catch (SQLException sqex) {
        log.error("Error database: " + sqex.toString());
    } finally {
        try {
            ps.close();
        } catch (Exception ex) {
        }
        try {
            connex.close();
        } catch (Exception ex) {
        }
    }

}

From source file:com.oracle.tutorial.jdbc.ClobSample.java

public void addRowToCoffeeDescriptions(String coffeeName, String fileName) throws SQLException {
    PreparedStatement pstmt = null;
    try {/* w  w w  .  j a va2 s . c  o m*/
        Clob myClob = this.con.createClob();

        Writer clobWriter = myClob.setCharacterStream(1);
        String str = this.readFile(fileName, clobWriter);
        System.out.println("Wrote the following: " + clobWriter.toString());
        if (this.settings.dbms.equals("mysql")) {
            System.out.println("MySQL, setting String in Clob object with setString method");
            myClob.setString(1, str);
        }
        System.out.println("Length of Clob: " + myClob.length());
        String sql = "INSERT INTO COFFEE_DESCRIPTIONS VALUES(?,?)";
        pstmt = this.con.prepareStatement(sql);
        pstmt.setString(1, coffeeName);
        pstmt.setClob(2, myClob);
        pstmt.executeUpdate();
    } catch (SQLException sqlex) {
        JDBCTutorialUtilities.printSQLException(sqlex);
    } catch (Exception ex) {
        System.out.println("Unexpected exception: " + ex.toString());
    } finally {
        if (pstmt != null) {
            pstmt.close();
        }
    }
}

From source file:com.netspective.axiom.sql.StoredProcedureParameter.java

/**
 * Extract the OUT parameter values from the callable statment and
 * assign them to the value of the parameter.
 *//*from  w  w  w. j  a  v a 2  s  .  c om*/
public void extract(ConnectionContext cc, CallableStatement stmt) throws SQLException {
    if (getType().getValueIndex() == StoredProcedureParameter.Type.IN)
        return;

    int index = this.getIndex();
    QueryParameterType paramType = getSqlType();
    int jdbcType = paramType.getJdbcType();
    String identifier = paramType.getIdentifier();

    // result sets are special
    if (identifier.equals(QueryParameterType.RESULTSET_IDENTIFIER)) {
        ResultSet rs = (ResultSet) stmt.getObject(index);
        QueryResultSet qrs = new QueryResultSet(getParent().getProcedure(), cc, rs);
        value.getValue(cc).setValue(qrs);
        return;
    }

    switch (jdbcType) {
    case Types.VARCHAR:
        value.getValue(cc).setTextValue(stmt.getString(index));
        break;
    case Types.INTEGER:
        value.getValue(cc).setValue(new Integer(stmt.getInt(index)));
        break;
    case Types.DOUBLE:
        value.getValue(cc).setValue(new Double(stmt.getDouble(index)));
        break;
    case Types.CLOB:
        Clob clob = stmt.getClob(index);
        value.getValue(cc).setTextValue(clob.getSubString(1, (int) clob.length()));
        break;
    case java.sql.Types.ARRAY:
        Array array = stmt.getArray(index);
        value.getValue(cc).setValue(array);
        break;
    case java.sql.Types.BIGINT:
        long bigint = stmt.getLong(index);
        value.getValue(cc).setValue(new Long(bigint));
        break;
    case java.sql.Types.BINARY:
        value.getValue(cc).setTextValue(new String(stmt.getBytes(index)));
        break;
    case java.sql.Types.BIT:
        boolean bit = stmt.getBoolean(index);
        value.getValue(cc).setValue(new Boolean(bit));
    case java.sql.Types.BLOB:
        value.getValue(cc).setValue(stmt.getBlob(index));
        break;
    case java.sql.Types.CHAR:
        value.getValue(cc).setTextValue(stmt.getString(index));
        break;
    case java.sql.Types.DATE:
        value.getValue(cc).setValue(stmt.getDate(index));
        break;
    case java.sql.Types.DECIMAL:
        value.getValue(cc).setValue(stmt.getBigDecimal(index));
        break;
    case java.sql.Types.DISTINCT:
        value.getValue(cc).setValue(stmt.getObject(index));
        break;
    case java.sql.Types.FLOAT:
        value.getValue(cc).setValue(new Float(stmt.getFloat(index)));
        break;
    case java.sql.Types.JAVA_OBJECT:
        value.getValue(cc).setValue(stmt.getObject(index));
        break;
    case java.sql.Types.LONGVARBINARY:
        value.getValue(cc).setTextValue(new String(stmt.getBytes(index)));
        break;
    case java.sql.Types.LONGVARCHAR:
        value.getValue(cc).setTextValue(stmt.getString(index));
        break;
    //case java.sql.Types.NULL:
    //    value.getValue(cc).setValue(null);
    //    break;
    case java.sql.Types.NUMERIC:
        value.getValue(cc).setValue(stmt.getBigDecimal(index));
        break;
    case java.sql.Types.OTHER:
        value.getValue(cc).setValue(stmt.getObject(index));
        break;
    case java.sql.Types.REAL:
        value.getValue(cc).setValue(new Float(stmt.getFloat(index)));
        break;
    //case java.sql.Types.REF:
    //    Ref ref = stmt.getRef(index);
    //    break;
    case java.sql.Types.SMALLINT:
        short sh = stmt.getShort(index);
        value.getValue(cc).setValue(new Short(sh));
        break;
    case java.sql.Types.STRUCT:
        value.getValue(cc).setValue(stmt.getObject(index));
        break;
    case java.sql.Types.TIME:
        value.getValue(cc).setValue(stmt.getTime(index));
        break;
    case java.sql.Types.TIMESTAMP:
        value.getValue(cc).setValue(stmt.getTimestamp(index));
        break;
    case java.sql.Types.TINYINT:
        byte b = stmt.getByte(index);
        value.getValue(cc).setValue(new Byte(b));
        break;
    case java.sql.Types.VARBINARY:
        value.getValue(cc).setValue(stmt.getBytes(index));
        break;
    default:
        throw new RuntimeException(
                "Unknown JDBC Type set for stored procedure parameter '" + this.getName() + "'.");
    }
}

From source file:net.sf.jasperreports.engine.JRResultSetDataSource.java

protected String clobToString(Clob clob) throws JRException {
    try {/*from www  .  j a  v  a2s. c o  m*/
        int bufSize = 8192;
        char[] buf = new char[bufSize];

        Reader reader = new BufferedReader(clob.getCharacterStream(), bufSize);
        StringBuilder str = new StringBuilder((int) clob.length());

        for (int read = reader.read(buf); read > 0; read = reader.read(buf)) {
            str.append(buf, 0, read);
        }

        return str.toString();
    } catch (SQLException e) {
        throw new JRException(EXCEPTION_MESSAGE_KEY_RESULT_SET_CLOB_VALUE_READ_FAILURE, null, e);
    } catch (IOException e) {
        throw new JRException(EXCEPTION_MESSAGE_KEY_RESULT_SET_CLOB_VALUE_READ_FAILURE, null, e);
    }
}

From source file:DisplayClobServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    Clob fileAsCLOB = null;
    Connection conn = null;/*  ww  w.  ja  v a  2s . c o m*/
    Statement stmt = null;
    ResultSet rs = null;

    String id = "001";
    String query = "select fileBody from DataFiles where id = " + id;
    ServletOutputStream out = response.getOutputStream();

    // all responses will be in text/html format
    response.setContentType("text/html");

    try {
        conn = getHSQLConnection();
    } catch (Exception e) {
        out.println("<html><head><title>CLOB Example</title></head>");
        out.println("<body><h4>Database Connection Problem.</h4>");
        out.println("<h5>" + e.getMessage() + "</h5></body></html>");
        return;
    }

    try {
        stmt = conn.createStatement();
        rs = stmt.executeQuery(query);
        if (rs.next()) {
            fileAsCLOB = rs.getClob(1);
        } else {
            out.println("<html><head><title>CLOB Example</title></head>");
            out.println("<body><h4>No file found for id=" + id + "</h4></body></html>");
            return;
        }

        // Materialize the CLOB as a String object (get the whole clob).
        long length = fileAsCLOB.length();
        // note that the first character is at position 1
        String fileAsString = fileAsCLOB.getSubString(1, (int) length);

        // write it for display
        out.println(fileAsString);
        System.out.println("CLOB writing done.");
    } catch (SQLException e) {
        out.println("<html><head><title>Error: CLOB Example</title></head>");
        out.println("<body><h4>Error=" + e.getMessage() + "</h4></body></html>");
        return;
    } finally {
        try {
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.healthmarketscience.jackcess.Column.java

/**
 * @return an appropriate CharSequence representation of the given object.
 * @usage _advanced_method_/* w w  w  . j a v a  2s. c o m*/
 */
public static CharSequence toCharSequence(Object value) throws IOException {
    if (value == null) {
        return null;
    } else if (value instanceof CharSequence) {
        return (CharSequence) value;
    } else if (value instanceof Clob) {
        try {
            Clob c = (Clob) value;
            // note, start pos is 1-based
            return c.getSubString(1L, (int) c.length());
        } catch (SQLException e) {
            throw (IOException) (new IOException(e.getMessage())).initCause(e);
        }
    } else if (value instanceof Reader) {
        char[] buf = new char[8 * 1024];
        StringBuilder sout = new StringBuilder();
        Reader in = (Reader) value;
        int read = 0;
        while ((read = in.read(buf)) != -1) {
            sout.append(buf, 0, read);
        }
        return sout;
    }

    return value.toString();
}