Example usage for java.sql Blob getBytes

List of usage examples for java.sql Blob getBytes

Introduction

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

Prototype

byte[] getBytes(long pos, int length) throws SQLException;

Source Link

Document

Retrieves all or part of the BLOB value that this Blob object represents, as an array of bytes.

Usage

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 ww  .  j  a  va 2  s  .c o  m

        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 .  co m*/

        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: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 w w.  jav a2  s .  co 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.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;//w w  w . j av a2 s . c  om
    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:edu.umass.cs.gigapaxos.SQLPaxosLogger.java

private static byte[] lobToBytes(Blob blob) throws SQLException, IOException {
    if (blob == null)
        return null;
    byte[] blobBytes = blob.getBytes(1L, (int) blob.length());
    assert (blobBytes != null);
    return inflate(blobBytes);
    // return new String(inflate(blobBytes), CHARSET);
}

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

/**
 * @param id id/*w w w  .  ja v a2  s  . c om*/
 * @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);
        }
    }
}

From source file:org.pentaho.di.core.database.Database.java

public RowMetaAndData callProcedure(String[] arg, String[] argdir, int[] argtype, String resultname,
        int resulttype) throws KettleDatabaseException {
    RowMetaAndData ret;/*from  www . ja  v a  2  s  . com*/
    try {
        boolean moreResults = cstmt.execute();
        ret = new RowMetaAndData();
        int pos = 1;
        if (resultname != null && resultname.length() != 0) {
            ValueMeta vMeta = new ValueMeta(resultname, resulttype);
            Object v = null;
            switch (resulttype) {
            case ValueMetaInterface.TYPE_BOOLEAN:
                v = Boolean.valueOf(cstmt.getBoolean(pos));
                break;
            case ValueMetaInterface.TYPE_NUMBER:
                v = new Double(cstmt.getDouble(pos));
                break;
            case ValueMetaInterface.TYPE_BIGNUMBER:
                v = cstmt.getBigDecimal(pos);
                break;
            case ValueMetaInterface.TYPE_INTEGER:
                v = Long.valueOf(cstmt.getLong(pos));
                break;
            case ValueMetaInterface.TYPE_STRING:
                v = cstmt.getString(pos);
                break;
            case ValueMetaInterface.TYPE_BINARY:
                if (databaseMeta.supportsGetBlob()) {
                    Blob blob = cstmt.getBlob(pos);
                    if (blob != null) {
                        v = blob.getBytes(1L, (int) blob.length());
                    } else {
                        v = null;
                    }
                } else {
                    v = cstmt.getBytes(pos);
                }
                break;
            case ValueMetaInterface.TYPE_DATE:
                if (databaseMeta.supportsTimeStampToDateConversion()) {
                    v = cstmt.getTimestamp(pos);
                } else {
                    v = cstmt.getDate(pos);
                }
                break;
            default:
                break;
            }
            ret.addValue(vMeta, v);
            pos++;
        }
        for (int i = 0; i < arg.length; i++) {
            if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT")) {
                ValueMetaInterface vMeta = ValueMetaFactory.createValueMeta(arg[i], argtype[i]);
                Object v = null;
                switch (argtype[i]) {
                case ValueMetaInterface.TYPE_BOOLEAN:
                    v = Boolean.valueOf(cstmt.getBoolean(pos + i));
                    break;
                case ValueMetaInterface.TYPE_NUMBER:
                    v = new Double(cstmt.getDouble(pos + i));
                    break;
                case ValueMetaInterface.TYPE_BIGNUMBER:
                    v = cstmt.getBigDecimal(pos + i);
                    break;
                case ValueMetaInterface.TYPE_INTEGER:
                    v = Long.valueOf(cstmt.getLong(pos + i));
                    break;
                case ValueMetaInterface.TYPE_STRING:
                    v = cstmt.getString(pos + i);
                    break;
                case ValueMetaInterface.TYPE_BINARY:
                    if (databaseMeta.supportsGetBlob()) {
                        Blob blob = cstmt.getBlob(pos + i);
                        if (blob != null) {
                            v = blob.getBytes(1L, (int) blob.length());
                        } else {
                            v = null;
                        }
                    } else {
                        v = cstmt.getBytes(pos + i);
                    }
                    break;
                case ValueMetaInterface.TYPE_DATE:
                    if (databaseMeta.supportsTimeStampToDateConversion()) {
                        v = cstmt.getTimestamp(pos + i);
                    } else {
                        v = cstmt.getDate(pos + i);
                    }
                    break;
                default:
                    break;
                }
                ret.addValue(vMeta, v);
            }
        }
        ResultSet rs = null;
        int updateCount = -1;

        // CHE: Iterate through the result sets and update counts
        // to receive all error messages from within the stored procedure.
        // This is only the first step to ensure that the stored procedure
        // is properly executed. A future extension would be to return all
        // result sets and update counts properly.

        do {
            rs = null;
            try {
                // Save the result set
                if (moreResults) {
                    rs = cstmt.getResultSet();

                } else {
                    // Save the update count if it is available (> -1)
                    updateCount = cstmt.getUpdateCount();

                }

                moreResults = cstmt.getMoreResults();

            } finally {
                if (rs != null) {
                    rs.close();
                    rs = null;
                }
            }

        } while (moreResults || (updateCount > -1));

        return ret;
    } catch (Exception ex) {
        throw new KettleDatabaseException("Unable to call procedure", ex);
    }

}

From source file:org.apache.openjpa.jdbc.sql.DBDictionary.java

/**
 * Convert the specified column of the SQL ResultSet to the proper
 * java type.//  w  ww  . j a va 2 s  .c  om
 */
public byte[] getBytes(ResultSet rs, int column) throws SQLException {
    if (useGetBytesForBlobs)
        return rs.getBytes(column);
    if (useGetObjectForBlobs)
        return (byte[]) rs.getObject(column);

    Blob blob = getBlob(rs, column);
    if (blob == null)
        return null;
    int length = (int) blob.length();
    if (length == 0)
        return null;
    return blob.getBytes(1, length);
}

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

public static String loadStartupConfig(int nodeId) {
    ResultSet rs = null;// ww  w  . j ava 2s  .  co m
    try {
        rs = DBHelper.executeQuery("select config from node_current_config where id=" + nodeId
                + " AND conf_type=" + Constants.STARTUP_CONF);
        if (rs.next()) {
            byte b[] = null;
            if (ServerProperties.getInstance().isPostgres()) {
                b = rs.getBytes(1);
            } else {
                Blob blob = rs.getBlob(1);
                if (blob != null) {
                    b = blob.getBytes(1, (int) blob.length());
                }
            }

            if (b != null) {
                return CompressionUtils.getUncompressedString(b);

            }
        }
    } catch (Exception ex) {
        logger.error("Exception while loading startup config for device: " + nodeId, ex);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception ex) {
            }
        }
    }
    return "";
}

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

public static String loadRunningConfig(int nodeId) {
    ResultSet rs = null;// ww w  .  java 2 s.c o  m
    Connection c = null;
    PreparedStatement ps = null;
    try {
        c = DBHelper.getConnection();
        ps = c.prepareStatement(
                "select config from node_current_config where id= ? AND conf_type=" + Constants.RUN_CONF);
        // rs =
        // DBHelper.executeQuery("select config from node_current_config where id="
        // + nodeId +
        // " AND conf_type="
        // + Constants.STARTUP_CONF);
        ps.setInt(1, nodeId);
        rs = ps.executeQuery();
        if (rs.next()) {
            byte b[] = null;
            if (ServerProperties.getInstance().isPostgres()) {
                b = rs.getBytes(1);
            } else {
                Blob blob = rs.getBlob(1);
                if (blob != null) {
                    b = blob.getBytes(1, (int) blob.length());
                }
            }
            if (b != null) {
                return CompressionUtils.getUncompressedString(b);
            }
        }
    } catch (Exception ex) {
        logger.error("Exception while loading running config for device: " + nodeId, ex);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception ex) {
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (Exception e) {

            }
        }
        DBHelper.releaseConnection(c);
    }
    return "";
}