Example usage for java.sql Blob length

List of usage examples for java.sql Blob length

Introduction

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

Prototype

long length() throws SQLException;

Source Link

Document

Returns the number of bytes in the BLOB value designated by this Blob object.

Usage

From source file:org.apache.qpid.server.store.derby.DerbyMessageStore.java

StorableMessageMetaData getMetaData(long messageId) throws SQLException {

    Connection conn = newAutoCommitConnection();
    try {/*from   w  w w.j a v a2 s  .c  o  m*/
        PreparedStatement stmt = conn.prepareStatement(SELECT_FROM_META_DATA);
        try {
            stmt.setLong(1, messageId);
            ResultSet rs = stmt.executeQuery();
            try {

                if (rs.next()) {
                    Blob dataAsBlob = rs.getBlob(1);

                    byte[] dataAsBytes = dataAsBlob.getBytes(1, (int) dataAsBlob.length());
                    java.nio.ByteBuffer buf = java.nio.ByteBuffer.wrap(dataAsBytes);
                    buf.position(1);
                    buf = buf.slice();
                    MessageMetaDataType type = MessageMetaDataType.values()[dataAsBytes[0]];
                    StorableMessageMetaData metaData = type.getFactory().createMetaData(buf);

                    return metaData;
                } else {
                    throw new RuntimeException("Meta data not found for message with id " + messageId);
                }
            } finally {
                rs.close();
            }
        } finally {
            stmt.close();
        }
    } finally {
        conn.close();
    }
}

From source file:net.sourceforge.msscodefactory.v1_10.MSSBamPg8.MSSBamPg8BlobDefTable.java

protected MSSBamBlobDefBuff unpackBlobDefResultSetToBuff(ResultSet resultSet) throws SQLException {
    final String S_ProcName = "unpackBlobDefResultSetToBuff";
    int idxcol = 1;
    String classCode = resultSet.getString(idxcol);
    idxcol++;/* w w w .j a  va  2s.  co  m*/
    MSSBamBlobDefBuff buff;
    if (classCode.equals("BLB")) {
        buff = schema.getFactoryBlobDef().newBuff();
    } else if (classCode.equals("TBLB")) {
        buff = schema.getFactoryTableBlob().newBuff();
    } else if (classCode.equals("SBLB")) {
        buff = schema.getFactorySchemaBlob().newBuff();
    } else {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Unrecognized class code \"" + classCode + "\"");
    }
    buff.setRequiredId(resultSet.getLong(idxcol));
    idxcol++;
    buff.setRequiredTenantId(resultSet.getLong(idxcol));
    idxcol++;
    {
        long colVal = resultSet.getLong(idxcol);
        if (resultSet.wasNull()) {
            buff.setOptionalScopeId(null);
        } else {
            buff.setOptionalScopeId(colVal);
        }
    }
    idxcol++;
    buff.setRequiredName(resultSet.getString(idxcol));
    idxcol++;
    {
        String colVal = resultSet.getString(idxcol);
        if (resultSet.wasNull()) {
            buff.setOptionalShortName(null);
        } else {
            buff.setOptionalShortName(colVal);
        }
    }
    idxcol++;
    {
        String colVal = resultSet.getString(idxcol);
        if (resultSet.wasNull()) {
            buff.setOptionalLabel(null);
        } else {
            buff.setOptionalLabel(colVal);
        }
    }
    idxcol++;
    {
        String colVal = resultSet.getString(idxcol);
        if (resultSet.wasNull()) {
            buff.setOptionalShortDescription(null);
        } else {
            buff.setOptionalShortDescription(colVal);
        }
    }
    idxcol++;
    {
        String colVal = resultSet.getString(idxcol);
        if (resultSet.wasNull()) {
            buff.setOptionalDescription(null);
        } else {
            buff.setOptionalDescription(colVal);
        }
    }
    idxcol++;
    {
        long colVal = resultSet.getLong(idxcol);
        if (resultSet.wasNull()) {
            buff.setOptionalAuthorId(null);
        } else {
            buff.setOptionalAuthorId(colVal);
        }
    }
    idxcol++;
    buff.setRequiredValueContainerId(resultSet.getLong(idxcol));
    idxcol++;
    buff.setRequiredIsNullable(resultSet.getBoolean(idxcol));
    idxcol++;
    {
        boolean colVal = resultSet.getBoolean(idxcol);
        if (resultSet.wasNull()) {
            buff.setOptionalGenerateId(null);
        } else {
            buff.setOptionalGenerateId(colVal);
        }
    }
    idxcol++;
    {
        short colVal = resultSet.getShort(idxcol);
        if (resultSet.wasNull()) {
            buff.setOptionalDataScopeId(null);
        } else {
            buff.setOptionalDataScopeId(colVal);
        }
    }
    idxcol++;
    {
        short colVal = resultSet.getShort(idxcol);
        if (resultSet.wasNull()) {
            buff.setOptionalViewAccessSecurityId(null);
        } else {
            buff.setOptionalViewAccessSecurityId(colVal);
        }
    }
    idxcol++;
    {
        short colVal = resultSet.getShort(idxcol);
        if (resultSet.wasNull()) {
            buff.setOptionalEditAccessSecurityId(null);
        } else {
            buff.setOptionalEditAccessSecurityId(colVal);
        }
    }
    idxcol++;
    {
        short colVal = resultSet.getShort(idxcol);
        if (resultSet.wasNull()) {
            buff.setOptionalViewAccessFrequencyId(null);
        } else {
            buff.setOptionalViewAccessFrequencyId(colVal);
        }
    }
    idxcol++;
    {
        short colVal = resultSet.getShort(idxcol);
        if (resultSet.wasNull()) {
            buff.setOptionalEditAccessFrequencyId(null);
        } else {
            buff.setOptionalEditAccessFrequencyId(colVal);
        }
    }
    idxcol++;
    {
        long colVal = resultSet.getLong(idxcol);
        if (resultSet.wasNull()) {
            buff.setOptionalPrevId(null);
        } else {
            buff.setOptionalPrevId(colVal);
        }
    }
    idxcol++;
    {
        long colVal = resultSet.getLong(idxcol);
        if (resultSet.wasNull()) {
            buff.setOptionalNextId(null);
        } else {
            buff.setOptionalNextId(colVal);
        }
    }
    idxcol++;
    {
        String colVal = resultSet.getString(idxcol);
        if (resultSet.wasNull()) {
            buff.setOptionalDbName(null);
        } else {
            buff.setOptionalDbName(colVal);
        }
    }
    idxcol++;
    buff.setRequiredMaxLen(resultSet.getInt(idxcol));
    idxcol++;
    {
        Blob binding = resultSet.getBlob(idxcol);
        if (resultSet.wasNull()) {
            buff.setOptionalInitValue(null);
        } else {
            long bindLen = binding.length();
            if (bindLen > Integer.MAX_VALUE) {
                throw CFLib.getDefaultExceptionFactory().newArgumentOverflowException(getClass(), S_ProcName,
                        idxcol, "InitValue", bindLen, (long) (Integer.MAX_VALUE));
            }
            byte[] colVal = binding.getBytes(0, (int) bindLen);
            buff.setOptionalInitValue(colVal);
        }
    }
    idxcol++;
    {
        Blob binding = resultSet.getBlob(idxcol);
        if (resultSet.wasNull()) {
            buff.setOptionalDefaultValue(null);
        } else {
            long bindLen = binding.length();
            if (bindLen > Integer.MAX_VALUE) {
                throw CFLib.getDefaultExceptionFactory().newArgumentOverflowException(getClass(), S_ProcName,
                        idxcol, "DefaultValue", bindLen, (long) (Integer.MAX_VALUE));
            }
            byte[] colVal = binding.getBytes(0, (int) bindLen);
            buff.setOptionalDefaultValue(colVal);
        }
    }
    idxcol++;
    {
        Blob binding = resultSet.getBlob(idxcol);
        if (resultSet.wasNull()) {
            buff.setOptionalNullValue(null);
        } else {
            long bindLen = binding.length();
            if (bindLen > Integer.MAX_VALUE) {
                throw CFLib.getDefaultExceptionFactory().newArgumentOverflowException(getClass(), S_ProcName,
                        idxcol, "NullValue", bindLen, (long) (Integer.MAX_VALUE));
            }
            byte[] colVal = binding.getBytes(0, (int) bindLen);
            buff.setOptionalNullValue(colVal);
        }
    }
    idxcol++;
    {
        Blob binding = resultSet.getBlob(idxcol);
        if (resultSet.wasNull()) {
            buff.setOptionalUnknownValue(null);
        } else {
            long bindLen = binding.length();
            if (bindLen > Integer.MAX_VALUE) {
                throw CFLib.getDefaultExceptionFactory().newArgumentOverflowException(getClass(), S_ProcName,
                        idxcol, "UnknownValue", bindLen, (long) (Integer.MAX_VALUE));
            }
            byte[] colVal = binding.getBytes(0, (int) bindLen);
            buff.setOptionalUnknownValue(colVal);
        }
    }
    idxcol++;
    buff.setRequiredRevision(resultSet.getInt(idxcol));
    return (buff);
}

From source file:org.apache.qpid.server.store.derby.DerbyMessageStore.java

private void recoverMessages(MessageStoreRecoveryHandler recoveryHandler) throws SQLException {
    Connection conn = newAutoCommitConnection();
    try {//from  w ww. j  ava  2  s  .  c  o  m
        MessageStoreRecoveryHandler.StoredMessageRecoveryHandler messageHandler = recoveryHandler.begin();

        Statement stmt = conn.createStatement();
        try {
            ResultSet rs = stmt.executeQuery(SELECT_ALL_FROM_META_DATA);
            try {

                long maxId = 0;

                while (rs.next()) {

                    long messageId = rs.getLong(1);
                    Blob dataAsBlob = rs.getBlob(2);

                    if (messageId > maxId) {
                        maxId = messageId;
                    }

                    byte[] dataAsBytes = dataAsBlob.getBytes(1, (int) dataAsBlob.length());
                    java.nio.ByteBuffer buf = java.nio.ByteBuffer.wrap(dataAsBytes);
                    buf.position(1);
                    buf = buf.slice();
                    MessageMetaDataType type = MessageMetaDataType.values()[dataAsBytes[0]];
                    StorableMessageMetaData metaData = type.getFactory().createMetaData(buf);
                    StoredDerbyMessage message = new StoredDerbyMessage(messageId, metaData, true);
                    messageHandler.message(message);
                }

                _messageId.set(maxId);

                messageHandler.completeMessageRecovery();
            } finally {
                rs.close();
            }
        } finally {
            stmt.close();
        }
    } finally {
        conn.close();
    }
}

From source file:org.kawanfw.sql.jdbc.PreparedStatementHttp.java

@Override
public void setBlob(int parameterIndex, Blob x) throws SQLException {
    testIfClosed();//  ww  w  .  j  av a2  s .c o m

    if (x instanceof BlobHttp) {

        BlobHttp blobHttp = (BlobHttp) x;
        // Close the underlying output stream, cleaner:
        blobHttp.close();

        String rawRemoteFileName = blobHttp.getFile().getName();

        debug("blobHttp.getFile(): " + blobHttp.getFile());
        debug("rawRemoteFileName : " + rawRemoteFileName);

        addFiles(blobHttp.getFile(), rawRemoteFileName);

        // Ok. File is successfully uploaded!
        // Set the parameter using the file name
        InputStream inputStream = new TransportInputStream(rawRemoteFileName);
        // parameterValues.put(parameterIndex, inputStream);
        statementHolder.setParameter(parameterIndex, inputStream);

    } else {
        InputStream in = x.getBinaryStream();
        setBinaryStream(parameterIndex, in, x.length());
    }

}

From source file:org.apache.ddlutils.platform.PlatformImplBase.java

/**
 * This is the core method to retrieve a value for a column from a result set. Its  primary
 * purpose is to call the appropriate method on the result set, and to provide an extension
 * point where database-specific implementations can change this behavior.
 * //from   w ww .j av  a  2  s. c  o m
 * @param resultSet  The result set to extract the value from
 * @param columnName The name of the column; can be <code>null</code> in which case the
  *                   <code>columnIdx</code> will be used instead
  * @param columnIdx  The index of the column's value in the result set; is only used if
  *                   <code>columnName</code> is <code>null</code>
 * @param jdbcType   The jdbc type to extract
 * @return The value
 * @throws SQLException If an error occurred while accessing the result set
 */
protected Object extractColumnValue(ResultSet resultSet, String columnName, int columnIdx, int jdbcType)
        throws SQLException {
    boolean useIdx = (columnName == null);
    Object value;

    switch (jdbcType) {
    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
        value = useIdx ? resultSet.getString(columnIdx) : resultSet.getString(columnName);
        break;
    case Types.NUMERIC:
    case Types.DECIMAL:
        value = useIdx ? resultSet.getBigDecimal(columnIdx) : resultSet.getBigDecimal(columnName);
        break;
    case Types.BIT:
    case Types.BOOLEAN:
        value = new Boolean(useIdx ? resultSet.getBoolean(columnIdx) : resultSet.getBoolean(columnName));
        break;
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
        value = new Integer(useIdx ? resultSet.getInt(columnIdx) : resultSet.getInt(columnName));
        break;
    case Types.BIGINT:
        value = new Long(useIdx ? resultSet.getLong(columnIdx) : resultSet.getLong(columnName));
        break;
    case Types.REAL:
        value = new Float(useIdx ? resultSet.getFloat(columnIdx) : resultSet.getFloat(columnName));
        break;
    case Types.FLOAT:
    case Types.DOUBLE:
        value = new Double(useIdx ? resultSet.getDouble(columnIdx) : resultSet.getDouble(columnName));
        break;
    case Types.BINARY:
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
        value = useIdx ? resultSet.getBytes(columnIdx) : resultSet.getBytes(columnName);
        break;
    case Types.DATE:
        value = useIdx ? resultSet.getDate(columnIdx) : resultSet.getDate(columnName);
        break;
    case Types.TIME:
        value = useIdx ? resultSet.getTime(columnIdx) : resultSet.getTime(columnName);
        break;
    case Types.TIMESTAMP:
        value = useIdx ? resultSet.getTimestamp(columnIdx) : resultSet.getTimestamp(columnName);
        break;
    case Types.CLOB:
        Clob clob = useIdx ? resultSet.getClob(columnIdx) : resultSet.getClob(columnName);

        if (clob == null) {
            value = null;
        } else {
            long length = clob.length();

            if (length > Integer.MAX_VALUE) {
                value = clob;
            } else if (length == 0) {
                // the javadoc is not clear about whether Clob.getSubString
                // can be used with a substring length of 0
                // thus we do the safe thing and handle it ourselves
                value = "";
            } else {
                value = clob.getSubString(1l, (int) length);
            }
        }
        break;
    case Types.BLOB:
        Blob blob = useIdx ? resultSet.getBlob(columnIdx) : resultSet.getBlob(columnName);

        if (blob == null) {
            value = null;
        } else {
            long length = blob.length();

            if (length > Integer.MAX_VALUE) {
                value = blob;
            } else if (length == 0) {
                // the javadoc is not clear about whether Blob.getBytes
                // can be used with for 0 bytes to be copied
                // thus we do the safe thing and handle it ourselves
                value = new byte[0];
            } else {
                value = blob.getBytes(1l, (int) length);
            }
        }
        break;
    case Types.ARRAY:
        value = useIdx ? resultSet.getArray(columnIdx) : resultSet.getArray(columnName);
        break;
    case Types.REF:
        value = useIdx ? resultSet.getRef(columnIdx) : resultSet.getRef(columnName);
        break;
    default:
        value = useIdx ? resultSet.getObject(columnIdx) : resultSet.getObject(columnName);
        break;
    }
    return resultSet.wasNull() ? null : value;
}

From source file:com.flexoodb.common.FlexUtils.java

static public String getRDBMSRecordAsXML(String tablename, RecordSet rec, String idcolumn,
        String parentidcolumn, boolean includeidcolumns, boolean listall) throws Exception {
    StringBuffer res = new StringBuffer();
    int size = rec.size();

    if (size > 0) {
        // first we get the table struc
        Enumeration en = rec.getColumnNames();

        ConcurrentHashMap<String, String> columns = new ConcurrentHashMap<String, String>();

        while (en.hasMoreElements()) {
            String cname = (String) en.nextElement();
            String type = rec.getColumnType(cname);
            columns.put(cname.toLowerCase(), type);
        }/*w w  w .j a  v a 2 s .  c om*/

        boolean done = false;

        int i = 0;
        while (i < rec.size() && !done) {

            res.append("<" + tablename + ">");

            en = columns.keys();

            while (en.hasMoreElements()) {

                String cname = ((String) en.nextElement()).toLowerCase();
                String type = columns.get(cname);

                boolean readrec = includeidcolumns;

                if (!readrec) {
                    readrec = (!cname.equalsIgnoreCase(idcolumn) && !cname.equalsIgnoreCase(parentidcolumn));
                }

                if (readrec) {
                    if (type.toUpperCase().indexOf("BLOB") > -1 || type.toUpperCase().indexOf("BINARY") > -1) {
                        Object o = rec.getContent(cname);

                        if (o instanceof com.mysql.jdbc.Blob) {
                            //byte[] b = BufferedInputStreamToString(((com.mysql.jdbc.Blob)o).getBinaryStream()).getBytes();
                            Blob blob = ((Blob) o);
                            byte[] b = blob.getBytes(1, (int) blob.length());

                            res.append("<" + cname + " type=\"byte[]\"><![CDATA[" + new String(b) + "]]></"
                                    + cname + ">");
                        } else {
                            res.append("<" + cname + " type=\"byte[]\"><![CDATA[" + o + "]]></" + cname + ">");
                        }

                    } else if (type.indexOf("CHAR") > -1 || type.indexOf("TEXT") > -1) {
                        res.append("<" + cname + " type=\"String\"><![CDATA["
                                + stripNonValidChars(rec.getString(cname)) + "]]></" + cname + ">");
                    } else if (type.equalsIgnoreCase("DATE") || type.equalsIgnoreCase("DATETIME")
                            || type.equalsIgnoreCase("TIMESTAMP")
                            || (type != null && type.toUpperCase().equals("YEAR"))) {
                        res.append("<" + cname + " type=\"XMLGregorianCalendar\"><![CDATA["
                                + rec.getString(cname) + "]]></" + cname + ">");
                    } else if (type.equalsIgnoreCase("LONG") || type.equalsIgnoreCase("TINY")
                            || type.equalsIgnoreCase("BIT") || type.equalsIgnoreCase("BIGINT")
                            || type.equalsIgnoreCase("SMALLINT") || type.equalsIgnoreCase("TINYINT")
                            || type.equalsIgnoreCase("MEDIUMINT") || type.equalsIgnoreCase("INT")) {
                        res.append("<" + cname + " type=\"BigInteger\"><![CDATA[" + rec.getInt(cname) + "]]></"
                                + cname + ">");
                    } else if (type.equalsIgnoreCase("DOUBLE") || type.equalsIgnoreCase("NUMERIC")
                            || type.equalsIgnoreCase("DECIMAL")) {
                        res.append("<" + cname + " type=\"Double\"><![CDATA[" + rec.getDouble(cname) + "]]></"
                                + cname + ">");
                    } else if (type.equalsIgnoreCase("FLOAT")) {
                        res.append("<" + cname + " type=\"Float\"><![CDATA[" + rec.getFloat(cname) + "]]></"
                                + cname + ">");
                    }
                    /*else if (type.equalsIgnoreCase("LONG"))
                    {
                    res.append("<"+proper(cname)+" type=\"Long\"><![CDATA["+rec.getDouble(cname)+"]]></"+proper(cname)+">");
                    }*/
                    else {
                        //res.append("<"+proper(cname)+" type=\""+cname+"\"><![CDATA["+rec.getString(cname)+"]]></"+proper(cname)+">");
                        throw new Exception(cname + " type " + type + " is not recognized.");
                    }
                }
            }

            res.append("</" + tablename + ">\n");

            if (!listall) {
                done = true;
            } else {
                i++;
                rec.next();
            }
        }
    }

    return new String(res.substring(0).getBytes("UTF8"));
}

From source file:com.flexoodb.common.FlexUtils.java

static public String getRDBMSRecordAsXML(String tablename, RecordSet rec, String idcolumn,
        String parentidcolumn, boolean includeidcolumns, FlexElement idelement) throws Exception {
    StringBuffer res = new StringBuffer();
    int size = rec.size();

    if (size > 0) {
        // first we get the table struc
        Enumeration en = rec.getColumnNames();

        ConcurrentHashMap<String, String> columns = new ConcurrentHashMap<String, String>();

        while (en.hasMoreElements()) {
            String cname = (String) en.nextElement();
            String type = rec.getColumnType(cname);
            columns.put(cname.toLowerCase(), type);
        }//from  w  w  w  .  j  a v a2 s  .  c om

        res.append("<" + tablename + ">");

        en = columns.keys();

        String cname = "";
        FlexElement aliascolumn = null;

        while (en.hasMoreElements()) {
            aliascolumn = null;
            cname = "";

            cname = (String) en.nextElement();
            String objectField = "";
            aliascolumn = (FlexElement) idelement.getElementByName(cname.trim(), false);

            if (aliascolumn == null) {
                objectField = cname;
            } else {
                if (aliascolumn.getAttribute("alias") == null) {
                    objectField = cname;
                } else {
                    objectField = aliascolumn.getAttribute("alias").getValue();
                }
            }

            String type = columns.get(cname);

            boolean readrec = includeidcolumns;

            if (!readrec) {
                readrec = (!cname.equalsIgnoreCase(idcolumn) && !cname.equalsIgnoreCase(parentidcolumn));
            }

            if (readrec) {
                if (type.toUpperCase().indexOf("BLOB") > -1 || type.toUpperCase().indexOf("BINARY") > -1) {
                    Object o = rec.getContent(cname);

                    if (o != null) {
                        //System.out.print(cname+")type:"+type+" "+o.getClass());

                        Blob blob = ((Blob) o);

                        byte[] b = blob.getBytes(1, (int) blob.length());
                        res.append("<" + objectField + " type=\"byte[]\"><![CDATA[" + new String(b) + "]]></"
                                + objectField + ">");
                    } else {
                        res.append("<" + objectField + " type=\"byte[]\"><![CDATA[]]></" + objectField + ">");
                    }
                } else if (type.indexOf("CHAR") > -1 || type.indexOf("TEXT") > -1
                        || type.toUpperCase().equals("YEAR")) {
                    res.append("<" + objectField + " type=\"String\"><![CDATA[" + rec.getString(cname) + "]]></"
                            + objectField + ">");
                } else if (type.equalsIgnoreCase("DATETIME") || type.equalsIgnoreCase("TIMESTAMP")
                        || type.toUpperCase().equals("DATE") || type.toUpperCase().equals("TIME")) {
                    res.append("<" + objectField + " type=\"XMLGregorianCalendar\"><![CDATA["
                            + rec.getString(cname) + "]]></" + objectField + ">");
                } else if (type.equalsIgnoreCase("LONG") || type.equalsIgnoreCase("TINY")
                        || type.equalsIgnoreCase("BIT") || type.equalsIgnoreCase("BIGINT")
                        || type.equalsIgnoreCase("SMALLINT") || type.equalsIgnoreCase("TINYINT")
                        || type.equalsIgnoreCase("MEDIUMINT") || type.equalsIgnoreCase("INT")) {
                    res.append("<" + objectField + " type=\"BigInteger\"><![CDATA[" + rec.getInt(cname)
                            + "]]></" + objectField + ">");
                } else if (type.equalsIgnoreCase("DOUBLE") || type.equalsIgnoreCase("NUMERIC")
                        || type.equalsIgnoreCase("DECIMAL")) {
                    res.append("<" + objectField + " type=\"Double\"><![CDATA[" + rec.getDouble(cname) + "]]></"
                            + objectField + ">");
                } else if (type.equalsIgnoreCase("FLOAT")) {
                    res.append("<" + objectField + " type=\"Float\"><![CDATA[" + rec.getFloat(cname) + "]]></"
                            + objectField + ">");
                }
                /*else if (type.equalsIgnoreCase("LONG"))
                {
                res.append("<"+proper(cname)+" type=\"Long\"><![CDATA["+rec.getDouble(cname)+"]]></"+proper(cname)+">");
                }*/
                else {
                    //res.append("<"+proper(objectField)+" type=\""+cname+"\"><![CDATA["+rec.getString(cname)+"]]></"+proper(objectField)+">");
                    throw new Exception(objectField + " type " + type + " is not recognized.");
                }
            }
        }
        res.append("</" + tablename + ">");
    }

    //System.out.println(">>>1:"+res.toString());
    return new String(res.substring(0).getBytes("UTF8"));
}

From source file:com.pari.nm.utils.db.ReportDBHelper.java

public static ServiceContainerImpl getDataFromTempTable(String reportId, String sessionId, int start,
        int pageLength, ServiceDescriptor descriptor, TableDefinition tableDef,
        ArrayList<String> childColumnsList, Map<String, String> mapOfConditions,
        Map<String, String> sortingFilters, List<ColumnLevelFilter> columnLevelFilters, String uniqueColumn)
        throws Exception {
    Connection connection = null;
    Statement statement = null;/*  ww w  .ja  v a 2s . co m*/
    ResultSet rs = null;

    String tblName = getTempPaginationTblName(reportId, sessionId);
    if (tblName == null) {
        throw new Exception("No Table Exist with ReportId:\t" + reportId + " and SessionId:\t" + sessionId);
    }
    logger.info("Getting Data from the following Table Name:\t" + tblName);
    ServiceContainerImpl sImpl = new ServiceContainerImpl(descriptor, null);
    Def[] childDefArr = descriptor.getAllChildRefs();
    ArrayList<String> childIdentifersList = null;
    String childIdentifierName = null;
    if (childDefArr != null && childDefArr.length > 0) {
        childIdentifersList = new ArrayList<String>();
        for (Def def : childDefArr) {
            childIdentifierName = def.getName();
            childIdentifersList.add(childIdentifierName);
        }
    }
    connection = DBHelper.getConnection();
    if (connection == null) {
        logger.info("Unable to get Connection.");
        return null;
    }
    // StringBuffer sb = getQuery(reportId, start, pageLength, tblName, mapOfConditions, tableDef, sortingFilters,
    // columnLevelFilters, uniqueColumn);
    // StringBuffer sb = getQuery(reportId, start, pageLength, tblName, mapOfConditions, tableDef, sortingFilters);
    String childTblName = getTempPaginationTblName(reportId, sessionId, childIdentifierName);
    // Create child columns list from child table definition object instead of using
    // childColumnsList which incorrectly includes all child columns names. So previous
    // implementation bombs when more than one child is present.
    List<String> childColList = new ArrayList<>();
    if (tableDef != null) {
        TableDefinition childTable = tableDef.getChildTableById(childIdentifierName);
        if (childTable != null) {
            ColumnDefinition[] columnDefs = childTable.getColumnDefs();
            for (ColumnDefinition columnDef : columnDefs) {
                childColList.add(columnDef.getId());
            }
        }
    }
    StringBuffer sb = getQuery(reportId, start, pageLength, tblName, mapOfConditions, tableDef, sortingFilters,
            childTblName, childColList, columnLevelFilters, uniqueColumn);
    try {
        statement = connection.createStatement();
        rs = statement.executeQuery(sb.toString());
        ArrayList<String> columnList = null;
        if (reportId.equals("extended_device_attributes_report")) {

            columnList = getColumnInfo(tableDef);
        } else {
            columnList = getColumnInfo(descriptor);
        }

        while ((rs != null) && rs.next()) {
            ServiceImpl service = new ServiceImpl(descriptor);
            if (columnList != null) {
                for (String column : uniqueColumn != null ? new String[] { uniqueColumn }
                        : columnList.toArray(new String[] {})) {
                    // Need to add Code to update for Child Tables:
                    // if (column.equalsIgnoreCase("JobRunSummary"))
                    if (childIdentifersList != null && childIdentifersList.contains(column)) {
                        HashMap<String, String> parentKeyValueMap = new HashMap<String, String>();
                        AttrDef[] attrDefArr = descriptor.getKeys();
                        if (attrDefArr != null) {
                            for (AttrDef attDef : attrDefArr) {
                                String key = attDef.getName();
                                String value = rs.getString(attDef.getName());
                                parentKeyValueMap.put(key, value);
                            }
                        }
                        // we need to populate Child Table Information
                        // 1. get ChildTableName
                        // String childInfoName = "JobRunSummary";
                        String childInfoName = childIdentifierName;
                        // String childTblName = getTempPaginationTblName(reportId, sessionId, childInfoName);
                        childTblName = getTempPaginationTblName(reportId, sessionId, column);
                        if (childTblName == null) {
                            throw new Exception("No Table Exist with ReportId:\t" + reportId
                                    + "and SessionId:\t" + sessionId + " and ChildTblName:\t" + childInfoName);
                        }
                        logger.info("Getting Data from the following Table Name:\t" + childTblName);

                        // Create child columns list from child table definition object instead of using
                        // childColumnsList which incorrectly includes all child columns names. So previous
                        // implementation bombs when more than one child is present.
                        if (tableDef != null) {
                            TableDefinition childTable = tableDef.getChildTableById(column);
                            ColumnDefinition[] columnDefs = childTable.getColumnDefs();
                            List<String> childColumns = new ArrayList<>();
                            for (ColumnDefinition columnDef : columnDefs) {
                                childColumns.add(columnDef.getId());
                            }

                            ServiceContainerImpl servImpl = getChildTblInformation1(childTblName,
                                    parentKeyValueMap, sImpl, childColumns);
                            logger.info("========================================================"
                                    + servImpl.size());
                            if (servImpl != null && servImpl.size() > 0) {
                                service.setAttribute(column, servImpl);
                            }
                        }
                    } else if (column.equalsIgnoreCase("RowId")) {
                        // In ProfileRunSummary Report, column named RowId, it is conflicting with RowId in Oracle,
                        // so appended 123 to RowId.
                        service.setAttribute("RowId", rs.getString(column + "123"));
                    } else if (column.equalsIgnoreCase("User")) {
                        // In Unmanaged Device Report, column named User, it is conflicting with User in Oracle, so
                        // appended 123 to User.
                        service.setAttribute("User", rs.getString(column + "123"));
                    } else if (column.equalsIgnoreCase("Comment")) {
                        // In My Pending Approvals Report, column named Comment, it is conflicting with Comment in
                        // Oracle, so appended 123 to Comment.
                        service.setAttribute("Comment", rs.getString(column + "123"));
                    } else if (column.equalsIgnoreCase("Size")) {
                        // Manage script repository export contains size, which is conflicting with Oracle reserved
                        // word, and this column changed to 'size123'
                        service.setAttribute("Size", rs.getString(column + "123"));
                    } else if (column.equalsIgnoreCase("Timestamp")) {
                        service.setAttribute(column, rs.getString(column + "123"));
                    } else if (column.equalsIgnoreCase("ChildrenCount")) {
                        service.setAttribute("ChildrenCount", rs.getInt("childCount"));
                    } else if ((!(reportId.equals("swim_install_analysis_report")))
                            && column.equalsIgnoreCase("Details")) {
                        String columnName = getRenderColumnName(column, tableDef);
                        columnName = (null == columnName) ? column : columnName;
                        String value = CompressionUtils.getUncompressedDecoded(rs.getString(columnName));
                        service.setAttribute(column, value);
                    } else if (column.equalsIgnoreCase("ViolationDetails")) {
                        Blob blob = rs.getBlob(column);
                        byte b[] = null;
                        if (blob != null) {
                            b = blob.getBytes(1, (int) blob.length());
                        }
                        if (b != null) {
                            BASE64Encoder encoder = new BASE64Encoder();
                            service.setAttribute(column, encoder.encode(b));
                        }

                    } else {
                        String columnName = getRenderColumnName(column, tableDef);
                        columnName = (null == columnName) ? column : columnName;
                        service.setAttribute(column, rs.getString(columnName));
                    }
                }
            }
            sImpl.addService(service);
            service.setServiceContainer(sImpl);
        }
    } catch (Exception ex) {
        logger.error("Error while creating customer upload details report.", ex);
        try {
            throw ex;
        } catch (Exception e) {
            e.printStackTrace();
        }
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (Exception ee) {
        }
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException sqlEx) {
            logger.error("Exception while closing statement", sqlEx);
        }

        DBHelper.releaseConnection(connection);
    }
    return sImpl;
}

From source file:org.quartz.impl.jdbcjobstore.StdJDBCDelegate.java

/**
 * <p>/*from  ww w.  j a v a 2s  .c om*/
 * This method should be overridden by any delegate subclasses that need
 * special handling for BLOBs. The default implementation uses standard
 * JDBC <code>java.sql.Blob</code> operations.
 * </p>
 * 
 * @param rs
 *          the result set, already queued to the correct row
 * @param colName
 *          the column name for the BLOB
 * @return the deserialized Object from the ResultSet BLOB
 * @throws ClassNotFoundException
 *           if a class found during deserialization cannot be found
 * @throws IOException
 *           if deserialization causes an error
 */
protected Object getObjectFromBlob(ResultSet rs, String colName)
        throws ClassNotFoundException, IOException, SQLException {
    Object obj = null;

    Blob blobLocator = rs.getBlob(colName);
    if (blobLocator != null && blobLocator.length() != 0) {
        InputStream binaryInput = blobLocator.getBinaryStream();

        if (null != binaryInput) {
            if (binaryInput instanceof ByteArrayInputStream
                    && ((ByteArrayInputStream) binaryInput).available() == 0) {
                //do nothing
            } else {
                ObjectInputStream in = new ObjectInputStream(binaryInput);
                try {
                    obj = in.readObject();
                } finally {
                    in.close();
                }
            }
        }

    }
    return obj;
}

From source file:org.globus.workspace.persistence.PersistenceAdapterImpl.java

/**
 * @param id id//from  ww w  .  j a v  a  2 s.c  o  m
 * @param resource resource
 * @throws DoesNotExistException
 * @throws WorkspaceDatabaseException
 */
public void load(int id, InstanceResource resource) throws DoesNotExistException, WorkspaceDatabaseException {

    if (this.dbTrace) {
        logger.trace("load(): " + Lager.id(id) + ", WorkspaceResource = " + resource);
    }

    if (id < 0) {
        throw new DoesNotExistException("id is less than zero");
    }

    Connection c = null;
    PreparedStatement pstmt = null;
    PreparedStatement[] pstmts = null;
    ResultSet rs = null;
    try {
        c = getConnection();

        pstmt = c.prepareStatement(SQL_LOAD_RESOURCE);
        pstmt.setInt(1, id);
        rs = pstmt.executeQuery();
        if (rs == null || !rs.next()) {
            final String err = "resource with id = " + id + " not found";
            logger.debug(err);
            throw new DoesNotExistException(err);
        } else {
            final String name = rs.getString(1);
            resource.setName(name);
            final int state = rs.getInt(2);
            final int targetState = rs.getInt(3);
            resource.setInitialTargetState(targetState);
            final long t = rs.getLong(4);
            if (t == 0) {
                resource.setTerminationTime(null);
            } else {
                final Calendar term = Calendar.getInstance();
                term.setTimeInMillis(t);
                resource.setTerminationTime(term);
            }
            final boolean opsEnabled = rs.getBoolean(5);
            resource.setInitialOpsEnabled(opsEnabled);

            final String dn = rs.getString(6);
            resource.setCreatorID(dn);

            final long s = rs.getLong(7);
            if (s == 0) {
                resource.setStartTime(null);
            } else {
                final Calendar start = Calendar.getInstance();
                start.setTimeInMillis(s);
                resource.setStartTime(start);
            }

            final boolean vmmAccessOK = rs.getBoolean(8);
            resource.setInitialVMMaccessOK(vmmAccessOK);

            final String ensembleid = rs.getString(9);
            resource.setEnsembleId(ensembleid);

            final String groupid = rs.getString(10);
            resource.setGroupId(groupid);

            final int groupsize = rs.getInt(11);
            resource.setGroupSize(groupsize);

            final boolean isLastInGroup = rs.getBoolean(12);
            resource.setLastInGroup(isLastInGroup);

            final int launchIndex = rs.getInt(13);
            resource.setLaunchIndex(launchIndex);

            final Blob errBlob = rs.getBlob(14);
            if (errBlob != null) {
                // getBytes requires int, cast from long
                final int length = (int) errBlob.length();
                final Throwable err = ErrorUtil.getThrowable(errBlob.getBytes(1, length));
                resource.setInitialState(state, err);
            } else {
                resource.setInitialState(state, null);
            }

            final String clientToken = rs.getString(15);
            resource.setClientToken(clientToken);

            final double chargeRatio = rs.getDouble(16);
            resource.setChargeRatio(chargeRatio);

            if (this.dbTrace) {
                logger.trace("found " + Lager.id(id) + ": name = " + name + ", state = " + state
                        + ", targetState = " + targetState + ", termination time = " + t + ", opsEnabled = "
                        + opsEnabled + ", creator ID = " + dn + ", start time = " + s + ", vmmAccessOK = "
                        + vmmAccessOK + ", ensembleid = " + ensembleid + ", groupid = " + groupid
                        + ", groupsize = " + groupsize + ", isLastInGroup = " + isLastInGroup
                        + ", launchIndex = " + launchIndex + ", clientToken = " + clientToken
                        + ", chargeRatio = " + chargeRatio + ", error present = " + (errBlob != null));
            }

            rs.close();

            if (resource instanceof VMPersistence) {
                if (this.dbTrace) {
                    logger.trace(Lager.id(id) + ": load virtual machine");
                }

                pstmts = VirtualMachinePersistenceUtil.getVMQuery(id, c);

                rs = pstmts[0].executeQuery();
                if (rs == null || !rs.next()) {
                    logger.error("resource with id=" + id + " not found");
                    throw new DoesNotExistException();
                }

                final VirtualMachine vm = VirtualMachinePersistenceUtil.newVM(id, rs);

                if (this.dbTrace) {
                    logger.trace(Lager.id(id) + ", created vm:\n" + vm.toString());
                }

                rs.close();

                rs = pstmts[1].executeQuery();
                if (rs == null || !rs.next()) {
                    logger.debug("resource with id=" + id + " has no" + " deployment information");
                } else {
                    VirtualMachinePersistenceUtil.addDeployment(vm, rs);
                    if (this.dbTrace) {
                        logger.trace("added deployment info to vm object");
                    }
                    rs.close();
                }

                rs = pstmts[2].executeQuery();

                if (rs == null || !rs.next()) {
                    logger.warn("resource with id=" + id + " has no" + " partitions");
                } else {
                    final ArrayList partitions = new ArrayList(8);
                    do {
                        partitions.add(VirtualMachinePersistenceUtil.getPartition(rs));
                    } while (rs.next());

                    final VirtualMachinePartition[] parts = (VirtualMachinePartition[]) partitions
                            .toArray(new VirtualMachinePartition[partitions.size()]);
                    vm.setPartitions(parts);
                }

                rs = pstmts[3].executeQuery();

                if (rs == null || !rs.next()) {
                    if (this.lager.dbLog) {
                        logger.debug("resource with id=" + id + " has no" + " customization needs");
                    }
                } else {
                    do {
                        vm.addFileCopyNeed(VirtualMachinePersistenceUtil.getNeed(rs));
                    } while (rs.next());
                }

                ((VMPersistence) resource).setWorkspace(vm);
            }
        }
    } catch (SQLException e) {
        logger.error("", e);
        throw new WorkspaceDatabaseException(e);
    } catch (DoesNotExistException e) {
        throw e;
    } catch (IOException e) {
        logger.error("", e);
        throw new WorkspaceDatabaseException(e);
    } catch (ClassNotFoundException e) {
        logger.error("", e);
        throw new WorkspaceDatabaseException(e);
    } finally {
        try {
            if (pstmt != null) {
                pstmt.close();
            }
            if (pstmts != null) {
                for (int i = 0; i < pstmts.length; i++) {
                    pstmts[i].close();
                }
            }
            if (rs != null) {
                rs.close();
            }
            if (c != null) {
                returnConnection(c);
            }
        } catch (SQLException sql) {
            logger.error("SQLException in finally cleanup", sql);
        }
    }
}