Example usage for java.sql ResultSet getBytes

List of usage examples for java.sql ResultSet getBytes

Introduction

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

Prototype

byte[] getBytes(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a byte array in the Java programming language.

Usage

From source file:org.plasma.sdo.access.provider.jdbc.JDBCDataConverter.java

public Object fromJDBCDataType(ResultSet rs, int columnIndex, int sourceType, PlasmaProperty targetProperty)
        throws SQLException {

    Object result = null;/*from   ww w .  j  a v  a  2  s .  co m*/

    if (targetProperty.getType().isDataType()) {
        DataType targetDataType = DataType.valueOf(targetProperty.getType().getName());

        switch (targetDataType) {
        case String:
        case URI:
        case Month:
        case MonthDay:
        case Day:
        case Time:
        case Year:
        case YearMonth:
        case YearMonthDay:
        case Duration:
            result = rs.getString(columnIndex);
            break;
        case Date:
            java.sql.Timestamp ts = rs.getTimestamp(columnIndex);
            if (ts != null)
                result = new java.util.Date(ts.getTime());
            break;
        case DateTime:
            ts = rs.getTimestamp(columnIndex);
            if (ts != null)
                result = new java.util.Date(ts.getTime());
            break;
        case Decimal:
            result = rs.getBigDecimal(columnIndex);
            break;
        case Bytes:
            result = rs.getBytes(columnIndex);
            break;
        case Byte:
            result = rs.getByte(columnIndex);
            break;
        case Boolean:
            result = rs.getBoolean(columnIndex);
            break;
        case Character:
            result = rs.getInt(columnIndex);
            break;
        case Double:
            result = rs.getDouble(columnIndex);
            break;
        case Float:
            result = rs.getFloat(columnIndex);
            break;
        case Int:
            result = rs.getInt(columnIndex);
            break;
        case Integer:
            result = new BigInteger(rs.getString(columnIndex));
            break;
        case Long:
            result = rs.getLong(columnIndex);
            break;
        case Short:
            result = rs.getShort(columnIndex);
            break;
        case Strings:
            String value = rs.getString(columnIndex);
            String[] values = value.split("\\s");
            List<String> list = new ArrayList<String>(values.length);
            for (int i = 0; i < values.length; i++)
                list.add(values[i]); // what no Java 5 sugar for this ??
            result = list;
            break;
        case Object:
        default:
            result = rs.getObject(columnIndex);
            break;
        }
    } else {
        // FIXME: or get the opposite containing type
        // of the property and get its pri-key(s)
        result = rs.getObject(columnIndex);
    }

    return result;
}

From source file:org.zenoss.zep.dao.impl.EventSummaryDaoImplIT.java

@Test
public void testDeidentifyComponent()
        throws ZepException, NoSuchAlgorithmException, UnsupportedEncodingException {
    EventSummary summary = createSummaryNew(createUniqueEvent());
    Event occurrence = summary.getOccurrence(0);
    EventActor actor = occurrence.getActor();
    assertTrue(occurrence.getActor().hasElementSubUuid());

    int numRows = this.eventSummaryDao.deidentify(actor.getElementSubUuid());
    assertEquals(1, numRows);/*ww w  . java 2s.  c  o  m*/
    EventSummary summaryFromDb = this.eventSummaryDao.findByUuid(summary.getUuid());
    assertTrue(summaryFromDb.getUpdateTime() > summary.getUpdateTime());
    assertFalse(summaryFromDb.getOccurrence(0).getActor().hasElementSubUuid());
    // Ensure clear_fingerprint_hash was updated
    String clearHashString = EventDaoUtils.join('|', actor.getElementIdentifier(),
            actor.getElementSubIdentifier(), occurrence.getEventClass(), occurrence.getEventKey());
    byte[] clearHash = DaoUtils.sha1(clearHashString);
    Map<String, Object> fields = Collections.singletonMap(COLUMN_UUID,
            databaseCompatibility.getUUIDConverter().toDatabaseType(summary.getUuid()));
    byte[] clearHashFromDb = this.simpleJdbcTemplate.query(
            "SELECT clear_fingerprint_hash FROM event_summary WHERE uuid=:uuid", new RowMapper<byte[]>() {
                @Override
                public byte[] mapRow(ResultSet rs, int rowNum) throws SQLException {
                    return rs.getBytes("clear_fingerprint_hash");
                }
            }, fields).get(0);
    assertArrayEquals(clearHash, clearHashFromDb);
}

From source file:org.wso2.carbon.identity.workflow.mgt.dao.WorkflowRequestDAO.java

/**
 * Get requests of a given user./*from  w  w  w . jav a  2 s .  c  o m*/
 *
 * @param userName user name of user to get requests
 * @param tenantId user's tenant id
 * @return
 * @throws InternalWorkflowException
 */
public org.wso2.carbon.identity.workflow.mgt.bean.WorkflowRequest[] getRequestsOfUser(String userName,
        int tenantId) throws InternalWorkflowException {

    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;
    String query = SQLConstants.GET_REQUESTS_OF_USER;
    ResultSet resultSet = null;
    try {
        prepStmt = connection.prepareStatement(query);
        prepStmt.setString(1, userName);
        prepStmt.setInt(2, tenantId);
        resultSet = prepStmt.executeQuery();
        ArrayList<org.wso2.carbon.identity.workflow.mgt.bean.WorkflowRequest> requestDTOs = new ArrayList<>();
        while (resultSet.next()) {
            org.wso2.carbon.identity.workflow.mgt.bean.WorkflowRequest requestDTO = new org.wso2.carbon.identity.workflow.mgt.bean.WorkflowRequest();
            requestDTO.setRequestId(resultSet.getString(SQLConstants.REQUEST_UUID_COLUMN));
            requestDTO.setEventType(resultSet.getString(SQLConstants.REQUEST_OPERATION_TYPE_COLUMN));
            requestDTO.setCreatedAt(resultSet.getTimestamp(SQLConstants.REQUEST_CREATED_AT_COLUMN).toString());
            requestDTO.setUpdatedAt(resultSet.getTimestamp(SQLConstants.REQUEST_UPDATED_AT_COLUMN).toString());
            requestDTO.setStatus(resultSet.getString(SQLConstants.REQUEST_STATUS_COLUMN));
            requestDTO.setRequestParams(
                    (deserializeWorkflowRequest(resultSet.getBytes(SQLConstants.REQUEST_COLUMN)))
                            .getRequestParameterAsString());
            requestDTO.setCreatedBy(resultSet.getString(SQLConstants.CREATED_BY_COLUMN));
            requestDTOs.add(requestDTO);
        }
        org.wso2.carbon.identity.workflow.mgt.bean.WorkflowRequest[] requestArray = new org.wso2.carbon.identity.workflow.mgt.bean.WorkflowRequest[requestDTOs
                .size()];
        for (int i = 0; i < requestDTOs.size(); i++) {
            requestArray[i] = requestDTOs.get(i);
        }
        return requestArray;
    } catch (SQLException e) {
        throw new InternalWorkflowException("Error when executing the sql query:" + query, e);
    } catch (ClassNotFoundException | IOException e) {
        throw new InternalWorkflowException("Error when deserializing a workflow request.", e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt);
    }
}

From source file:org.zenoss.zep.dao.impl.EventSummaryDaoImplIT.java

@Test
public void testReidentifyComponent()
        throws ZepException, NoSuchAlgorithmException, UnsupportedEncodingException {
    Event.Builder builder = Event.newBuilder(createUniqueEvent());
    EventActor.Builder actorBuilder = EventActor.newBuilder(builder.getActor());
    actorBuilder.clearElementSubUuid();// w ww  .  j av a  2  s  .  co m
    builder.setActor(actorBuilder.build());

    EventSummary summary = createSummaryNew(builder.build());
    Event occurrence = summary.getOccurrence(0);
    EventActor actor = occurrence.getActor();
    assertFalse(occurrence.getActor().hasElementSubUuid());

    final String elementSubUuid = UUID.randomUUID().toString();
    int numRows = this.eventSummaryDao.reidentify(actor.getElementSubTypeId(), actor.getElementSubIdentifier(),
            elementSubUuid, actor.getElementSubTitle(), actor.getElementUuid());
    assertEquals(1, numRows);
    EventSummary summaryFromDb = this.eventSummaryDao.findByUuid(summary.getUuid());
    assertTrue(summaryFromDb.getUpdateTime() > summary.getUpdateTime());
    assertEquals(elementSubUuid, summaryFromDb.getOccurrence(0).getActor().getElementSubUuid());
    // Ensure clear_fingerprint_hash was updated
    String clearHashString = EventDaoUtils.join('|', elementSubUuid, occurrence.getEventClass(),
            occurrence.getEventKey());
    byte[] clearHash = DaoUtils.sha1(clearHashString);
    Map<String, Object> fields = Collections.singletonMap(COLUMN_UUID,
            databaseCompatibility.getUUIDConverter().toDatabaseType(summary.getUuid()));
    byte[] clearHashFromDb = this.simpleJdbcTemplate.query(
            "SELECT clear_fingerprint_hash FROM event_summary WHERE uuid=:uuid", new RowMapper<byte[]>() {
                @Override
                public byte[] mapRow(ResultSet rs, int rowNum) throws SQLException {
                    return rs.getBytes("clear_fingerprint_hash");
                }
            }, fields).get(0);
    assertArrayEquals(clearHash, clearHashFromDb);
}

From source file:com.act.lcms.db.model.MS1ScanForWellAndMassCharge.java

@Override
protected List<MS1ScanForWellAndMassCharge> fromResultSet(ResultSet resultSet)
        throws SQLException, IOException, ClassNotFoundException {
    List<MS1ScanForWellAndMassCharge> results = new ArrayList<>();
    while (resultSet.next()) {
        Integer id = resultSet.getInt(DB_FIELD.ID.getOffset());
        Integer plateId = resultSet.getInt(DB_FIELD.PLATE_ID.getOffset());
        Integer plateRow = resultSet.getInt(DB_FIELD.PLATE_ROW.getOffset());
        Integer plateColumn = resultSet.getInt(DB_FIELD.PLATE_COLUMN.getOffset());
        Double maxYAxis = resultSet.getDouble(DB_FIELD.MAX_Y_AXIS.getOffset());
        Boolean useSNR = resultSet.getBoolean(DB_FIELD.USE_SNR.getOffset());
        String lcmsScanFilePath = resultSet.getString(DB_FIELD.SCAN_FILE.getOffset());
        String chemicalName = resultSet.getString(DB_FIELD.CHEMICAL_NAME.getOffset());
        List<String> metlinIons = MS1ScanForWellAndMassCharge
                .deserializeMetlinIons(resultSet.getString(DB_FIELD.METLIN_IONS.getOffset()));
        Map<String, List<XZ>> ionsToSpectra = MS1ScanForWellAndMassCharge
                .deserialize(resultSet.getBytes(DB_FIELD.IONS_TO_SPECTRA.getOffset()));
        Map<String, Double> ionsToIntegral = MS1ScanForWellAndMassCharge
                .deserialize(resultSet.getBytes(DB_FIELD.IONS_TO_INTEGRAL.getOffset()));
        Map<String, Double> ionsToMax = MS1ScanForWellAndMassCharge
                .deserialize(resultSet.getBytes(DB_FIELD.IONS_TO_MAX.getOffset()));
        Map<String, Double> ionsToLogSNR = MS1ScanForWellAndMassCharge
                .deserialize(resultSet.getBytes(DB_FIELD.IONS_TO_LOG_SNR.getOffset()));
        Map<String, Double> ionsToAvgSignal = MS1ScanForWellAndMassCharge
                .deserialize(resultSet.getBytes(DB_FIELD.IONS_TO_AVG_SIGNAL.getOffset()));
        Map<String, Double> ionsToAvgAmbient = MS1ScanForWellAndMassCharge
                .deserialize(resultSet.getBytes(DB_FIELD.IONS_TO_AVG_AMBIENT.getOffset()));
        Map<String, Double> individualMaxIntensities = MS1ScanForWellAndMassCharge
                .deserialize(resultSet.getBytes(DB_FIELD.INDIVIDUAL_MAX_INTENSITIES.getOffset()));

        results.add(new MS1ScanForWellAndMassCharge(id, plateId, plateColumn, plateRow, useSNR,
                lcmsScanFilePath, chemicalName, metlinIons, ionsToSpectra, ionsToIntegral, ionsToMax,
                ionsToLogSNR, ionsToAvgSignal, ionsToAvgAmbient, individualMaxIntensities, maxYAxis));
    }// w w  w  .j av  a2  s .co m

    return results;
}

From source file:com.alfaariss.oa.engine.tgt.jdbc.JDBCTGTFactory.java

/**
 * Retrieve the TGT with the given id./* w w w .  j  av  a 2s  .  com*/
 * @param id The TGT id.
 * @return The TGT, or null if a TGT with the given id does not exist.
 * @throws PersistenceException If retrieving fails.
 */
@SuppressWarnings("unchecked") //Serialize value can not be checked
public JDBCTGT retrieve(Object id) throws PersistenceException {
    if (id == null || !(id instanceof String))
        throw new IllegalArgumentException("Suplied id is empty or invalid");

    JDBCTGT tgt = null;
    Connection oConnection = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        oConnection = _oDataSource.getConnection();
        ps = oConnection.prepareStatement(_sSearchQuery);
        ps.setString(1, (String) id);
        rs = ps.executeQuery();
        if (rs.next()) {
            byte[] baUser = rs.getBytes(_sColumnUSER);
            tgt = new JDBCTGT(this, (IUser) Serialize.decode(baUser));
            tgt.setId((String) id);
            tgt.setTgtExpTime(rs.getTimestamp(_sColumnEXPIRATION).getTime());
            tgt.setAuthenticationProfile(
                    (AuthenticationProfile) Serialize.decode(rs.getBytes(_sColumnAUTHN_PROFILE)));
            tgt.setAuthNProfileIDs((List) Serialize.decode(rs.getBytes(_sColumnAUTHN_PROFILES)));
            tgt.setRequestorIDs((List) Serialize.decode(rs.getBytes(_sColumnREQUESTOR_IDS)));

            TGTAttributes oAttributes = (TGTAttributes) Serialize.decode(rs.getBytes(_sColumnATTRIBUTES));
            if (oAttributes != null)
                tgt.setAttributes(oAttributes);
        }
    } catch (SQLException e) {
        _logger.error("Could not execute search query", e);
        throw new PersistenceException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
    } catch (ClassCastException e) {
        _logger.error("Could not decode, invalid class type", e);
        throw new PersistenceException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
    } catch (Exception e) {
        _logger.error("Internal error during retrieval of tgt with id: " + id, e);
        throw new PersistenceException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
    } finally {
        try {
            if (rs != null)
                rs.close();
        } catch (SQLException e) {
            _logger.debug("Could not close resultset", e);
        }
        try {
            if (ps != null)
                ps.close();
        } catch (SQLException e) {
            _logger.debug("Could not close statement", e);
        }
        try {
            if (oConnection != null)
                oConnection.close();
        } catch (SQLException e) {
            _logger.debug("Could not close connection", e);
        }
    }
    return tgt;
}

From source file:org.cloudgraph.rdb.service.RDBDataConverter.java

private Object convertFrom(ResultSet rs, int columnIndex, int sourceType, Property property)
        throws SQLException {
    Object result = null;//from   www.  ja  v  a 2 s.com
    if (!property.getType().isDataType())
        throw new IllegalArgumentException("expected data type property, not " + property.toString());
    DataType targetDataType = DataType.valueOf(property.getType().getName());
    switch (targetDataType) {
    case String:
    case URI:
    case Month:
    case MonthDay:
    case Day:
    case Time:
    case Year:
    case YearMonth:
    case YearMonthDay:
    case Duration:
        result = rs.getString(columnIndex);
        break;
    case Date:
        java.sql.Timestamp ts = rs.getTimestamp(columnIndex);
        if (ts != null)
            result = new java.util.Date(ts.getTime());
        break;
    case DateTime:
        ts = rs.getTimestamp(columnIndex);
        if (ts != null) {
            // format DateTime String for SDO
            java.util.Date date = new java.util.Date(ts.getTime());
            result = DataConverter.INSTANCE.getDateTimeFormat().format(date);
        }
        break;
    case Decimal:
        result = rs.getBigDecimal(columnIndex);
        break;
    case Bytes:
        if (sourceType != Types.BLOB) {
            result = rs.getBytes(columnIndex);
        } else if (sourceType == Types.BLOB) {
            Blob blob = rs.getBlob(columnIndex);
            if (blob != null) {
                long blobLen = blob.length(); // for debugging
                // Note: blob.getBytes(columnIndex, blob.length()); is
                // somehow truncating the array
                // by something like 14 bytes (?!!) even though
                // blob.length() returns the expected length
                // using getBinaryStream which is preferred anyway
                InputStream is = blob.getBinaryStream();
                try {
                    byte[] bytes = IOUtils.toByteArray(is);
                    long len = bytes.length; // for debugging
                    result = bytes;
                } catch (IOException e) {
                    throw new RDBServiceException(e);
                } finally {
                    try {
                        is.close();
                    } catch (IOException e) {
                        log.error(e.getMessage(), e);
                    }
                }
            }
        }
        break;
    case Byte:
        result = rs.getByte(columnIndex);
        break;
    case Boolean:
        result = rs.getBoolean(columnIndex);
        break;
    case Character:
        result = rs.getInt(columnIndex);
        break;
    case Double:
        result = rs.getDouble(columnIndex);
        break;
    case Float:
        result = rs.getFloat(columnIndex);
        break;
    case Int:
        result = rs.getInt(columnIndex);
        break;
    case Integer:
        result = new BigInteger(rs.getString(columnIndex));
        break;
    case Long:
        result = rs.getLong(columnIndex);
        break;
    case Short:
        result = rs.getShort(columnIndex);
        break;
    case Strings:
        String value = rs.getString(columnIndex);
        if (value != null) {
            String[] values = value.split("\\s");
            List<String> list = new ArrayList<String>(values.length);
            for (int i = 0; i < values.length; i++)
                list.add(values[i]); // what no Java 5 sugar for this ??
            result = list;
        }
        break;
    case Object:
    default:
        result = rs.getObject(columnIndex);
        break;
    }
    return result;
}

From source file:com.icsshs.datatransfer.database.impl.QueryBeanProcessor.java

/**
 * Convert a <code>ResultSet</code> column into an object.  Simple
 * implementations could just call <code>rs.getObject(index)</code> while
 * more complex implementations could perform type manipulation to match
 * the column's type to the bean property type.
 *
 * <p>//from   w w w.  j a  v a2  s .com
 * This implementation calls the appropriate <code>ResultSet</code> getter
 * method for the given property type to perform the type conversion.  If
 * the property type doesn't match one of the supported
 * <code>ResultSet</code> types, <code>getObject</code> is called.
 * </p>
 *
 * @param rs The <code>ResultSet</code> currently being processed.  It is
 * positioned on a valid row before being passed into this method.
 *
 * @param index The current column index being processed.
 *
 * @param propType The bean property type that this column needs to be
 * converted into.
 *
 * @throws SQLException if a database access error occurs
 *
 * @return The object from the <code>ResultSet</code> at the given column
 * index after optional type processing or <code>null</code> if the column
 * value was SQL NULL.
 */
protected Object processColumn(ResultSet rs, int index, Class<?> propType) throws SQLException {

    if (!propType.isPrimitive() && rs.getObject(index) == null) {
        return null;
    }

    if (propType.equals(String.class)) {
        return rs.getString(index);

    } else if (propType.equals(Integer.TYPE) || propType.equals(Integer.class)) {
        return Integer.valueOf(rs.getInt(index));

    } else if (propType.equals(Boolean.TYPE) || propType.equals(Boolean.class)) {
        return Boolean.valueOf(rs.getBoolean(index));

    } else if (propType.equals(Long.TYPE) || propType.equals(Long.class)) {
        return Long.valueOf(rs.getLong(index));

    } else if (propType.equals(Double.TYPE) || propType.equals(Double.class)) {
        return Double.valueOf(rs.getDouble(index));

    } else if (propType.equals(Float.TYPE) || propType.equals(Float.class)) {
        return Float.valueOf(rs.getFloat(index));

    } else if (propType.equals(Short.TYPE) || propType.equals(Short.class)) {
        return Short.valueOf(rs.getShort(index));

    } else if (propType.equals(Byte.TYPE) || propType.equals(Byte.class)) {
        return Byte.valueOf(rs.getByte(index));

    } else if (propType.equals(Timestamp.class)) {
        return rs.getTimestamp(index);

    } else if (propType.equals(byte[].class)) {
        return rs.getBytes(index);

    } else {
        return rs.getObject(index);

    }

}

From source file:com.alfaariss.oa.engine.session.jdbc.JDBCSessionFactory.java

/**
 * Retrieve the Session with the given id.
 * @param id The Session id./* ww  w.  j  a  v  a 2  s .  co m*/
 * @return The Session, or null if a Session with the given id does not exist.
 * @throws PersistenceException If retrieving fails.
 */
@SuppressWarnings("unchecked") //Serialize value can not be checked
public JDBCSession retrieve(Object id) throws PersistenceException {
    if (id == null || !(id instanceof String))
        throw new IllegalArgumentException("Suplied id is empty or invalid");

    Connection oConnection = null;
    JDBCSession session = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        oConnection = _oDataSource.getConnection();
        ps = oConnection.prepareStatement(_sSearchQuery);
        ps.setString(1, (String) id);
        rs = ps.executeQuery();
        if (rs.next()) {
            session = new JDBCSession(this, rs.getString(_sColumnREQUESTOR));
            session.setId((String) id);

            String sTGTID = rs.getString(_sColumnTGT_ID);
            if (sTGTID != null)
                session.setTGTId(sTGTID);

            session.setState(SessionState.values()[rs.getInt(_sColumnSTATE)]);

            String sUrl = rs.getString(_sColumnURL);
            if (sUrl != null)
                session.setProfileURL(sUrl);

            IUser oUser = (IUser) Serialize.decode(rs.getBytes(_sColumnOWNER));
            if (oUser != null)
                session.setUser(oUser);

            session.setExpTime(rs.getTimestamp(_sColumnEXPIRATION).getTime());
            session.setForcedAuthentication(rs.getBoolean(_sColumnFORCED_AUTHENTICATE));
            session.setPassive(rs.getBoolean(_sColumnPASSIVE));

            SessionAttributes oAttributes = (SessionAttributes) Serialize
                    .decode(rs.getBytes(_sColumnATTRIBUTES));
            if (oAttributes != null)
                session.setAttributes(oAttributes);

            String sForcedUid = rs.getString(_sColumnFORCED_USERID);
            if (sForcedUid != null)
                session.setForcedUserID(sForcedUid);

            Locale oLocale = (Locale) Serialize.decode(rs.getBytes(_sColumnLOCALE));
            if (oLocale != null)
                session.setLocale(oLocale);

            List listProfiles = (List) Serialize.decode(rs.getBytes(_sColumnAUTHN_PROFILES));
            if (listProfiles != null)
                session.setAuthNProfiles(listProfiles);

            AuthenticationProfile oProfile = (AuthenticationProfile) Serialize
                    .decode(rs.getBytes(_sColumnSELECTED_AUTHN_PROFILE));
            if (oProfile != null)
                session.setSelectedAuthNProfile(oProfile);
        }
    } catch (SQLException e) {
        _logger.error("Could not execute search query: " + _sSearchQuery, e);
        throw new PersistenceException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
    } catch (ClassCastException e) {
        _logger.error("Could not decode, invalid class type", e);
        throw new PersistenceException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
    } catch (Exception e) {
        _logger.error("Internal error during retrieve of session id: " + id, e);
        throw new PersistenceException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
    } finally {
        try {
            if (rs != null)
                rs.close();
        } catch (SQLException e) {
            _logger.debug("Could not close resultset", e);
        }
        try {
            if (ps != null)
                ps.close();
        } catch (SQLException e) {
            _logger.debug("Could not close statement", e);
        }
        try {
            if (oConnection != null)
                oConnection.close();
        } catch (SQLException e) {
            _logger.debug("Could not close connection", e);
        }
    }
    return session;
}

From source file:com.cedarsoftware.ncube.NCubeManager.java

/**
 * This API creates a SNAPSHOT set of cubes by copying all of
 * the RELEASE ncubes that match the oldVersion and app to
 * the new version in SNAPSHOT mode.  Basically, it duplicates
 * an entire set of NCubes and places a new version label on them,
 * in SNAPSHOT status./*from   w w  w  . ja v a2 s  .co m*/
 */
public static int createSnapshotCubes(Connection connection, String app, String relVersion, String newSnapVer) {
    validate(connection, app, relVersion);
    validateVersion(newSnapVer);

    if (relVersion.equals(newSnapVer)) {
        throw new IllegalArgumentException(
                "New SNAPSHOT version " + relVersion + " cannot be the same as the RELEASE version.");
    }

    synchronized (cubeList) {
        PreparedStatement stmt0 = null;
        PreparedStatement stmt1 = null;
        PreparedStatement stmt2 = null;

        try {
            stmt0 = connection
                    .prepareStatement("SELECT n_cube_id FROM n_cube WHERE app_cd = ? AND version_no_cd = ?");
            stmt0.setString(1, app);
            stmt0.setString(2, newSnapVer);
            ResultSet rs = stmt0.executeQuery();
            if (rs.next()) {
                throw new IllegalStateException("New SNAPSHOT Version specified (" + newSnapVer
                        + ") matches an existing version.  Specify new SNAPSHOT version that does not exist.");
            }
            rs.close();

            stmt1 = connection.prepareStatement(
                    "SELECT n_cube_nm, cube_value_bin, create_dt, update_dt, create_hid, update_hid, version_no_cd, status_cd, sys_effective_dt, sys_expiration_dt, business_effective_dt, business_expiration_dt, app_cd, test_data_bin, notes_bin\n"
                            + "FROM n_cube\n" + "WHERE app_cd = ? AND version_no_cd = ? AND status_cd = '"
                            + ReleaseStatus.RELEASE + "'");

            stmt1.setString(1, app);
            stmt1.setString(2, relVersion);
            rs = stmt1.executeQuery();

            stmt2 = connection.prepareStatement(
                    "INSERT INTO n_cube (n_cube_id, n_cube_nm, cube_value_bin, create_dt, update_dt, create_hid, update_hid, version_no_cd, status_cd, sys_effective_dt, sys_expiration_dt, business_effective_dt, business_expiration_dt, app_cd, test_data_bin, notes_bin)\n"
                            + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            int count = 0;

            while (rs.next()) {
                count++;
                stmt2.setLong(1, UniqueIdGenerator.getUniqueId());
                stmt2.setString(2, rs.getString("n_cube_nm"));
                stmt2.setBytes(3, rs.getBytes("cube_value_bin"));
                stmt2.setDate(4, new java.sql.Date(System.currentTimeMillis()));
                stmt2.setDate(5, new java.sql.Date(System.currentTimeMillis()));
                stmt2.setString(6, rs.getString("create_hid"));
                stmt2.setString(7, rs.getString("update_hid"));
                stmt2.setString(8, newSnapVer);
                stmt2.setString(9, ReleaseStatus.SNAPSHOT.name());
                stmt2.setDate(10, rs.getDate("sys_effective_dt"));
                stmt2.setDate(11, rs.getDate("sys_expiration_dt"));
                stmt2.setDate(12, rs.getDate("business_effective_dt"));
                stmt2.setDate(13, rs.getDate("business_expiration_dt"));
                stmt2.setString(14, rs.getString("app_cd"));
                stmt2.setBytes(15, rs.getBytes("test_data_bin"));
                stmt2.setBytes(16, rs.getBytes("notes_bin"));
                stmt2.executeUpdate();
            }
            return count;
        } catch (IllegalStateException e) {
            throw e;
        } catch (Exception e) {
            String s = "Unable to create SNAPSHOT NCubes for app: " + app + ", version: " + newSnapVer
                    + ", due to an error: " + e.getMessage();
            LOG.error(s, e);
            throw new RuntimeException(s, e);
        } finally {
            jdbcCleanup(stmt0);
            jdbcCleanup(stmt1);
            jdbcCleanup(stmt2);
        }
    }
}