Example usage for java.sql ResultSet getBinaryStream

List of usage examples for java.sql ResultSet getBinaryStream

Introduction

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

Prototype

java.io.InputStream getBinaryStream(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a stream of uninterpreted bytes.

Usage

From source file:org.wso2.carbon.ml.database.internal.MLDatabaseService.java

@Override
public List<MLModelData> getAllModels(int tenantId, String userName, long analysisId)
        throws DatabaseHandlerException {

    Connection connection = null;
    ResultSet result = null;
    PreparedStatement statement = null;
    List<MLModelData> models = new ArrayList<MLModelData>();
    try {//from   w w w .ja  v a2 s . c  o m
        connection = dbh.getDataSource().getConnection();
        statement = connection.prepareStatement(SQLQueries.GET_ALL_ML_MODELS_OF_ANALYSIS);
        statement.setLong(1, analysisId);
        statement.setInt(2, tenantId);
        statement.setString(3, userName);
        result = statement.executeQuery();
        while (result.next()) {
            MLModelData model = new MLModelData();
            model.setId(result.getLong(1));
            model.setAnalysisId(result.getLong(2));
            model.setVersionSetId(result.getLong(3));
            model.setCreatedTime(result.getString(4));
            model.setStorageType(result.getString(5));
            model.setStorageDirectory(result.getString(6));
            model.setName(result.getString(7));
            model.setTenantId(tenantId);
            model.setUserName(userName);
            model.setStatus(result.getString(8));
            model.setError(result.getString(9));
            ModelSummary modelSummary = null;
            if (result.getBinaryStream(10) != null) {
                modelSummary = MLDBUtil.getModelSummaryFromInputStream(result.getBinaryStream(10));
            }
            model.setModelSummary(modelSummary);
            models.add(model);
        }
        return models;
    } catch (Exception e) {
        throw new DatabaseHandlerException(
                " An error has occurred while extracting all the models of analysis id: " + analysisId, e);
    } finally {
        // Close the database resources.
        MLDatabaseUtils.closeDatabaseResources(connection, statement, result);
    }
}

From source file:org.obiba.onyx.jade.instrument.gehealthcare.AchillesExpressInstrumentRunner.java

@SuppressWarnings("unchecked")
private List<Map<String, Data>> retrieveDeviceData() {

    log.info("retrieveDeviceData");

    return (List<Map<String, Data>>) achillesExpressDb.query(
            "select assessment, fxrisk, total, tscore, zscore, agematched, percentnormal, sidescanned, stiffnessindex, patients.chart_num, results.SOS, results.BUA, achillesbitmap, appversion, roi_x, roi_y, roi_s, patients.Chart_Num, patients.FName, patients.LName, patients.Sex, patients.DOB from results, patients where results.chart_num = patients.chart_num and patients.chart_num = ?",
            new PreparedStatementSetter() {

                public void setValues(PreparedStatement ps) throws SQLException {
                    ps.setString(1, participantID);
                }/*w w w.  j  a  v  a 2  s.  co m*/

            },

            new ResultSetExtractor() {

                public Object extractData(ResultSet rs) throws SQLException {

                    List<Map<String, Data>> boneDensityDataList = new ArrayList<Map<String, Data>>();

                    while (rs.next()) {
                        Map<String, Data> boneDensityData = new HashMap<String, Data>();

                        boneDensityData.put("OUTPUT_PARTICIPANT_BARCODE",
                                DataBuilder.buildText(rs.getString("Chart_Num")));
                        boneDensityData.put("OUTPUT_PARTICIPANT_FIRST_NAME",
                                DataBuilder.buildText(rs.getString("FName")));
                        boneDensityData.put("OUTPUT_PARTICIPANT_LAST_NAME",
                                DataBuilder.buildText(rs.getString("LName")));
                        boneDensityData.put("OUTPUT_PARTICIPANT_DATE_BIRTH",
                                DataBuilder.buildDate(rs.getDate("DOB")));

                        String gender = rs.getString("Sex").equals("M") ? "MALE" : "FEMALE";
                        boneDensityData.put("OUTPUT_PARTICIPANT_GENDER", DataBuilder.buildText(gender));

                        boneDensityData.put("RES_ASSESSMENT",
                                DataBuilder.buildDecimal(rs.getDouble("assessment")));
                        boneDensityData.put("RES_FRACTURE_RISK",
                                DataBuilder.buildDecimal(rs.getDouble("fxrisk")));
                        boneDensityData.put("RES_STIFFNESS_INDEX_RES",
                                DataBuilder.buildDecimal(rs.getDouble("total")));
                        boneDensityData.put("RES_T-SCORE", DataBuilder.buildDecimal(rs.getDouble("tscore")));
                        boneDensityData.put("RES_Z-SCORE", DataBuilder.buildDecimal(rs.getDouble("zscore")));
                        boneDensityData.put("RES_PERCENT_AGE_MATCHED",
                                DataBuilder.buildDecimal(rs.getDouble("agematched")));
                        boneDensityData.put("RES_PERCENT_YOUNG_ADULT",
                                DataBuilder.buildDecimal(rs.getDouble("percentnormal")));

                        String foot_scanned = rs.getString("sidescanned").equals("L") ? "LEFT_FOOT"
                                : "RIGHT_FOOT";
                        boneDensityData.put("OUTPUT_FOOT_SCANNED", DataBuilder.buildText(foot_scanned));

                        boneDensityData.put("RES_STIFFNESS_INDEX",
                                DataBuilder.buildDecimal(rs.getDouble("stiffnessindex")));
                        boneDensityData.put("RES_SPEED_ULTRASOUND",
                                DataBuilder.buildDecimal(rs.getDouble("SOS")));
                        boneDensityData.put("RES_BROADBAND_ULTRASOUND_ATT",
                                DataBuilder.buildDecimal(rs.getDouble("BUA")));
                        boneDensityData.put("RES_SOFTWARE_VERSION",
                                DataBuilder.buildText(rs.getString("appversion")));
                        boneDensityData.put("RES_REGION_INTERSECTION_X_COOR",
                                DataBuilder.buildInteger(rs.getLong("roi_x")));
                        boneDensityData.put("RES_REGION_INTERSECTION_Y_COOR",
                                DataBuilder.buildInteger(rs.getLong("roi_y")));
                        boneDensityData.put("RES_REGION_INTERSECTION_Z_COOR",
                                DataBuilder.buildInteger(rs.getLong("roi_s")));
                        boneDensityData.put("RES_STIFFNESS_INDEX_GRAPH",
                                DataBuilder.buildBinary(rs.getBinaryStream("achillesbitmap")));

                        boneDensityDataList.add(boneDensityData);
                    }

                    return boneDensityDataList;

                }

            });

}

From source file:com.flexive.core.storage.genericSQL.GenericBinarySQLStorage.java

/**
 * {@inheritDoc}//from  w w  w . j  a  v  a 2s  .  co m
 */
@Override
public BinaryInputStream fetchBinary(Connection con, int divisionId, BinaryDescriptor.PreviewSizes size,
        long binaryId, int binaryVersion, int binaryQuality) {
    Connection _con = con;
    PreparedStatement ps = null;
    String mimeType;
    int datasize;
    try {
        if (_con == null)
            _con = Database.getDbConnection(divisionId);
        String column = "FBLOB";
        String sizeColumn = "BLOBSIZE";
        long previewId = 0;
        ResultSet rs;
        if (size != PreviewSizes.ORIGINAL) {
            //unless the real content is requested, try to find the correct preview image
            //                                 1           2         3         4         5         6     7
            ps = _con.prepareStatement(
                    "SELECT PREVIEW_REF,PREV1SIZE,PREV2SIZE,PREV3SIZE,PREV4SIZE,WIDTH,HEIGHT FROM "
                            + TBL_CONTENT_BINARY + " WHERE ID=? AND VER=? AND QUALITY=?");
            ps.setLong(1, binaryId);
            ps.setInt(2, binaryVersion);
            ps.setInt(3, binaryQuality);
            rs = ps.executeQuery();
            if (rs != null && rs.next()) {
                previewId = rs.getLong(1);
                if (rs.wasNull())
                    previewId = 0;
                boolean found = previewId == 0;
                if (!found) { //fall back to referenced preview
                    rs.close();
                    ps.setLong(1, previewId);
                    ps.setInt(2, binaryVersion);
                    ps.setInt(3, binaryQuality);
                    rs = ps.executeQuery();
                    found = rs != null && rs.next();
                }
                if (found)
                    size = getAvailablePreviewSize(size, rs.getInt(2), rs.getInt(3), rs.getInt(4), rs.getInt(5),
                            rs.getInt(6), rs.getInt(7));
            }
            ps.close();
        }
        switch (size) {
        case PREVIEW1:
            column = "PREV1";
            sizeColumn = "PREV1SIZE";
            break;
        case PREVIEW2:
            column = "PREV2";
            sizeColumn = "PREV2SIZE";
            break;
        case PREVIEW3:
            column = "PREV3";
            sizeColumn = "PREV3SIZE";
            break;
        case SCREENVIEW:
            column = "PREV4";
            sizeColumn = "PREV4SIZE";
            break;
        }
        ps = _con.prepareStatement("SELECT " + column + ",MIMETYPE," + sizeColumn + " FROM "
                + TBL_CONTENT_BINARY + " WHERE ID=? AND VER=? AND QUALITY=?");
        if (previewId != 0)
            ps.setLong(1, previewId);
        else
            ps.setLong(1, binaryId);
        ps.setInt(2, binaryVersion);
        ps.setInt(3, binaryQuality);
        rs = ps.executeQuery();
        if (rs == null || !rs.next()) {
            Database.closeObjects(GenericBinarySQLInputStream.class, _con, ps);
            return new GenericBinarySQLInputStream(false);
        }
        InputStream bin = rs.getBinaryStream(1);
        if (rs.wasNull()) {
            //try from filesystem
            File fsBinary = FxBinaryUtils.getBinaryFile(divisionId, binaryId, binaryVersion, binaryQuality,
                    size.getBlobIndex());

            try {
                if (fsBinary != null)
                    bin = new FileInputStream(fsBinary);
                else {
                    if (size == PreviewSizes.SCREENVIEW) {
                        //since screenview is a new preview size, it might not exist in old versions. Fall back to Preview3
                        Database.closeObjects(GenericBinarySQLInputStream.class, _con, ps);
                        LOG.warn("Screenview for binary #" + binaryId
                                + " not found! Falling back to Preview3 size.");
                        return this.fetchBinary(null, divisionId, PreviewSizes.PREVIEW3, binaryId,
                                binaryVersion, binaryQuality);
                    }
                    LOG.error("Binary file #" + binaryId + "[" + size.name() + "] was not found!");
                    Database.closeObjects(GenericBinarySQLInputStream.class, con == null ? _con : null, ps);
                    return new GenericBinarySQLInputStream(false);
                }
            } catch (FileNotFoundException e) {
                LOG.error("Binary not found on filesystem! Id=" + binaryId + ", version=" + binaryVersion
                        + ", quality=" + binaryQuality + ", size=" + size.name());
                Database.closeObjects(GenericBinarySQLInputStream.class, con == null ? _con : null, ps);
                return new GenericBinarySQLInputStream(false);
            }
        }
        mimeType = rs.getString(2);
        datasize = rs.getInt(3);
        if (rs.wasNull() && size == PreviewSizes.SCREENVIEW) {
            Database.closeObjects(GenericBinarySQLInputStream.class, _con, ps);
            LOG.warn("Screenview for binary #" + binaryId + " not found! Falling back to Preview3 size.");
            return this.fetchBinary(null, divisionId, PreviewSizes.PREVIEW3, binaryId, binaryVersion,
                    binaryQuality);
        }
        return new GenericBinarySQLInputStream(_con, ps, true, bin, mimeType, datasize);
    } catch (SQLException e) {
        Database.closeObjects(GenericBinarySQLInputStream.class, con == null ? _con : null, ps);
        return new GenericBinarySQLInputStream(false);
    }
}

From source file:org.wso2.carbon.idp.mgt.dao.IdPManagementDAO.java

/**
 * @param dbConnection/*  w ww  .j  av  a 2 s .co  m*/
 * @param idPName
 * @param tenantId
 * @param tenantDomain
 * @return
 * @throws IdentityProviderManagementException
 */
public IdentityProvider getIdPByName(Connection dbConnection, String idPName, int tenantId, String tenantDomain)
        throws IdentityProviderManagementException {

    PreparedStatement prepStmt = null;
    ResultSet rs = null;
    IdentityProvider federatedIdp = null;
    boolean dbConnectionInitialized = true;
    if (dbConnection == null) {
        dbConnection = IdentityDatabaseUtil.getDBConnection();
    } else {
        dbConnectionInitialized = false;
    }

    try {
        // SP_IDP_ID, SP_IDP_PRIMARY, SP_IDP_HOME_REALM_ID,SP_IDP_CERTIFICATE,
        // SP_IDP_TOKEN_EP_ALIAS,
        // SP_IDP_INBOUND_PROVISIONING_ENABLED,SP_IDP_INBOUND_PROVISIONING_USER_STORE_ID,
        // SP_IDP_USER_CLAIM_URI,
        // SP_IDP_ROLE_CLAIM_URI,SP_IDP_DEFAULT_AUTHENTICATOR_NAME,SP_IDP_DEFAULT_PRO_CONNECTOR_NAME
        String sqlStmt = IdPManagementConstants.SQLQueries.GET_IDP_BY_NAME_SQL;
        prepStmt = dbConnection.prepareStatement(sqlStmt);
        prepStmt.setInt(1, tenantId);
        prepStmt.setInt(2, MultitenantConstants.SUPER_TENANT_ID);
        prepStmt.setString(3, CharacterEncoder.getSafeText(idPName));
        rs = prepStmt.executeQuery();
        int idpId = -1;

        if (rs.next()) {
            federatedIdp = new IdentityProvider();
            federatedIdp.setIdentityProviderName(idPName);

            idpId = rs.getInt("ID");

            if (("1").equals(rs.getString("IS_PRIMARY"))) {
                federatedIdp.setPrimary(true);
            } else {
                federatedIdp.setPrimary(false);
            }

            federatedIdp.setHomeRealmId(rs.getString("HOME_REALM_ID"));
            federatedIdp.setCertificate(getBlobValue(rs.getBinaryStream("CERTIFICATE")));
            federatedIdp.setAlias(rs.getString("ALIAS"));

            JustInTimeProvisioningConfig jitProConfig = new JustInTimeProvisioningConfig();
            if (("1").equals(rs.getString("INBOUND_PROV_ENABLED"))) {
                jitProConfig.setProvisioningEnabled(true);
            } else {
                jitProConfig.setProvisioningEnabled(false);
            }

            jitProConfig.setProvisioningUserStore(rs.getString("INBOUND_PROV_USER_STORE_ID"));
            federatedIdp.setJustInTimeProvisioningConfig(jitProConfig);

            String userClaimUri = rs.getString("USER_CLAIM_URI");
            String roleClaimUri = rs.getString("ROLE_CLAIM_URI");

            String defaultAuthenticatorName = rs.getString("DEFAULT_AUTHENTICATOR_NAME");
            String defaultProvisioningConnectorConfigName = rs.getString("DEFAULT_PRO_CONNECTOR_NAME");
            federatedIdp.setIdentityProviderDescription(rs.getString("DESCRIPTION"));

            // IS_FEDERATION_HUB_IDP
            if ("1".equals(rs.getString("IS_FEDERATION_HUB"))) {
                federatedIdp.setFederationHub(true);
            } else {
                federatedIdp.setFederationHub(false);
            }

            if (federatedIdp.getClaimConfig() == null) {
                federatedIdp.setClaimConfig(new ClaimConfig());
            }

            // IS_LOCAL_CLAIM_DIALECT
            if ("1".equals(rs.getString("IS_LOCAL_CLAIM_DIALECT"))) {
                federatedIdp.getClaimConfig().setLocalClaimDialect(true);
            } else {
                federatedIdp.getClaimConfig().setLocalClaimDialect(false);
            }

            federatedIdp.setProvisioningRole(rs.getString("PROVISIONING_ROLE"));

            if ("1".equals(rs.getString("IS_ENABLED"))) {
                federatedIdp.setEnable(true);
            } else {
                federatedIdp.setEnable(false);
            }

            federatedIdp.setDisplayName(rs.getString("DISPLAY_NAME"));

            if (defaultAuthenticatorName != null) {
                FederatedAuthenticatorConfig defaultAuthenticator = new FederatedAuthenticatorConfig();
                defaultAuthenticator.setName(defaultAuthenticatorName);
                federatedIdp.setDefaultAuthenticatorConfig(defaultAuthenticator);
            }

            if (defaultProvisioningConnectorConfigName != null) {
                ProvisioningConnectorConfig defaultProConnector = new ProvisioningConnectorConfig();
                defaultProConnector.setName(defaultProvisioningConnectorConfigName);
                federatedIdp.setDefaultProvisioningConnectorConfig(defaultProConnector);
            }

            // get federated authenticators.
            federatedIdp.setFederatedAuthenticatorConfigs(
                    getFederatedAuthenticatorConfigs(dbConnection, idPName, federatedIdp, tenantId));

            if (federatedIdp.getClaimConfig().isLocalClaimDialect()) {
                federatedIdp.setClaimConfig(getLocalIdPDefaultClaimValues(dbConnection, idPName, userClaimUri,
                        roleClaimUri, idpId, tenantId));
            } else {
                // get claim configuration.
                federatedIdp.setClaimConfig(getIdPClaimConfiguration(dbConnection, idPName, userClaimUri,
                        roleClaimUri, idpId, tenantId));
            }

            // get provisioning connectors.
            federatedIdp.setProvisioningConnectorConfigs(
                    getProvisioningConnectorConfigs(dbConnection, idPName, idpId, tenantId));

            // get permission and role configuration.
            federatedIdp.setPermissionAndRoleConfig(
                    getPermissionsAndRoleConfiguration(dbConnection, idPName, idpId, tenantId));

        }
        dbConnection.commit();
        return federatedIdp;
    } catch (SQLException e) {
        IdentityApplicationManagementUtil.rollBack(dbConnection);
        throw new IdentityProviderManagementException("Error occurred while retrieving Identity Provider "
                + "information for tenant : " + tenantDomain + " and Identity Provider name : " + idPName, e);
    } finally {
        if (dbConnectionInitialized) {
            IdentityApplicationManagementUtil.closeConnection(dbConnection);
        }
    }
}

From source file:org.wso2.carbon.idp.mgt.dao.IdPManagementDAO.java

/**
 * @param dbConnection/* www  . ja v  a2  s.com*/
 * @param property     Property which has a unique value like EntityID to specifically identify a IdentityProvider
 *                     Unless it will return first matched IdentityProvider
 * @param value
 * @param tenantId
 * @param tenantDomain
 * @return
 * @throws IdentityProviderManagementException
 */
public IdentityProvider getIdPByAuthenticatorPropertyValue(Connection dbConnection, String property,
        String value, int tenantId, String tenantDomain) throws IdentityProviderManagementException {

    PreparedStatement prepStmt = null;
    ResultSet rs = null;
    IdentityProvider federatedIdp = null;
    boolean dbConnectionInitialized = true;
    if (dbConnection == null) {
        dbConnection = IdentityDatabaseUtil.getDBConnection();
    } else {
        dbConnectionInitialized = false;
    }
    try {
        // SP_IDP_ID, SP_IDP_NAME, SP_IDP_PRIMARY, SP_IDP_HOME_REALM_ID,SP_IDP_CERTIFICATE,
        // SP_IDP_TOKEN_EP_ALIAS,
        // SP_IDP_INBOUND_PROVISIONING_ENABLED,SP_IDP_INBOUND_PROVISIONING_USER_STORE_ID,
        // SP_IDP_USER_CLAIM_URI,
        // SP_IDP_ROLE_CLAIM_URI,SP_IDP_DEFAULT_AUTHENTICATOR_NAME,SP_IDP_DEFAULT_PRO_CONNECTOR_NAME
        String sqlStmt = IdPManagementConstants.SQLQueries.GET_IDP_BY_AUTHENTICATOR_PROPERTY;
        prepStmt = dbConnection.prepareStatement(sqlStmt);
        prepStmt.setString(1, CharacterEncoder.getSafeText(property));
        prepStmt.setString(2, CharacterEncoder.getSafeText(value));
        prepStmt.setInt(3, tenantId);
        rs = prepStmt.executeQuery();
        int idpId = -1;
        String idPName = "";

        if (rs.next()) {
            federatedIdp = new IdentityProvider();

            idpId = rs.getInt("idp.ID");
            idPName = rs.getString("idp.NAME");

            federatedIdp.setIdentityProviderName(idPName);

            if (("1").equals(rs.getString("idp.IS_PRIMARY"))) {
                federatedIdp.setPrimary(true);
            } else {
                federatedIdp.setPrimary(false);
            }

            federatedIdp.setHomeRealmId(rs.getString("idp.HOME_REALM_ID"));
            federatedIdp.setCertificate(getBlobValue(rs.getBinaryStream("idp.CERTIFICATE")));
            federatedIdp.setAlias(rs.getString("idp.ALIAS"));

            JustInTimeProvisioningConfig jitProConfig = new JustInTimeProvisioningConfig();
            if (rs.getString("idp.INBOUND_PROV_ENABLED").equals("1")) {
                jitProConfig.setProvisioningEnabled(true);
            } else {
                jitProConfig.setProvisioningEnabled(false);
            }

            jitProConfig.setProvisioningUserStore(rs.getString("idp.INBOUND_PROV_USER_STORE_ID"));
            federatedIdp.setJustInTimeProvisioningConfig(jitProConfig);

            String userClaimUri = rs.getString("idp.USER_CLAIM_URI");
            String roleClaimUri = rs.getString("idp.ROLE_CLAIM_URI");

            String defaultAuthenticatorName = rs.getString("idp.DEFAULT_AUTHENTICATOR_NAME");
            String defaultProvisioningConnectorConfigName = rs.getString("idp.DEFAULT_PRO_CONNECTOR_NAME");
            federatedIdp.setIdentityProviderDescription(rs.getString("idp.DESCRIPTION"));

            // IS_FEDERATION_HUB_IDP
            if ("1".equals(rs.getString("idp.IS_FEDERATION_HUB"))) {
                federatedIdp.setFederationHub(true);
            } else {
                federatedIdp.setFederationHub(false);
            }

            if (federatedIdp.getClaimConfig() == null) {
                federatedIdp.setClaimConfig(new ClaimConfig());
            }

            // IS_LOCAL_CLAIM_DIALECT
            if ("1".equals(rs.getString("idp.IS_LOCAL_CLAIM_DIALECT"))) {
                federatedIdp.getClaimConfig().setLocalClaimDialect(true);
            } else {
                federatedIdp.getClaimConfig().setLocalClaimDialect(false);
            }

            federatedIdp.setProvisioningRole(rs.getString("idp.PROVISIONING_ROLE"));

            if ("1".equals(rs.getString("idp.IS_ENABLED"))) {
                federatedIdp.setEnable(true);
            } else {
                federatedIdp.setEnable(false);
            }

            federatedIdp.setDisplayName(rs.getString("idp.DISPLAY_NAME"));

            if (defaultAuthenticatorName != null) {
                FederatedAuthenticatorConfig defaultAuthenticator = new FederatedAuthenticatorConfig();
                defaultAuthenticator.setName(defaultAuthenticatorName);
                federatedIdp.setDefaultAuthenticatorConfig(defaultAuthenticator);
            }

            if (defaultProvisioningConnectorConfigName != null) {
                ProvisioningConnectorConfig defaultProConnector = new ProvisioningConnectorConfig();
                defaultProConnector.setName(defaultProvisioningConnectorConfigName);
                federatedIdp.setDefaultProvisioningConnectorConfig(defaultProConnector);
            }

            // get federated authenticators.
            federatedIdp.setFederatedAuthenticatorConfigs(
                    getFederatedAuthenticatorConfigs(dbConnection, idPName, federatedIdp, tenantId));

            if (federatedIdp.getClaimConfig().isLocalClaimDialect()) {
                federatedIdp.setClaimConfig(getLocalIdPDefaultClaimValues(dbConnection, idPName, userClaimUri,
                        roleClaimUri, idpId, tenantId));
            } else {
                // get claim configuration.
                federatedIdp.setClaimConfig(getIdPClaimConfiguration(dbConnection, idPName, userClaimUri,
                        roleClaimUri, idpId, tenantId));
            }

            // get provisioning connectors.
            federatedIdp.setProvisioningConnectorConfigs(
                    getProvisioningConnectorConfigs(dbConnection, idPName, idpId, tenantId));

            // get permission and role configuration.
            federatedIdp.setPermissionAndRoleConfig(
                    getPermissionsAndRoleConfiguration(dbConnection, idPName, idpId, tenantId));

        }
        dbConnection.commit();
        return federatedIdp;
    } catch (SQLException e) {
        IdentityApplicationManagementUtil.rollBack(dbConnection);
        throw new IdentityProviderManagementException("Error occurred while retrieving Identity Provider "
                + "information for Authenticator Property : " + property + " and value : " + value, e);
    } finally {
        if (dbConnectionInitialized) {
            IdentityApplicationManagementUtil.closeConnection(dbConnection);
        }
    }
}

From source file:org.sakaiproject.tool.assessment.facade.AssessmentGradingFacadeQueries.java

private byte[] getMediaStream(Long mediaId) {
    byte[] b = new byte[4000];
    Session session = null;/* w  w  w.  j  a  v  a2s  .c  om*/
    Connection conn = null;
    InputStream in = null;
    ResultSet rs = null;
    PreparedStatement statement = null;
    try {
        session = getSessionFactory().openSession();
        conn = session.connection();
        log.debug("****Connection=" + conn);
        String query = "select MEDIA from SAM_MEDIA_T where MEDIAID=?";
        statement = conn.prepareStatement(query);
        statement.setLong(1, mediaId.longValue());
        rs = statement.executeQuery();
        if (rs.next()) {
            java.lang.Object o = rs.getObject("MEDIA");
            if (o != null) {
                in = rs.getBinaryStream("MEDIA");
                in.mark(0);
                int ch;
                int len = 0;
                while ((ch = in.read()) != -1) {
                    len++;
                }
                b = new byte[len];
                in.reset();
                in.read(b, 0, len);
            }
        }
    } catch (Exception e) {
        log.warn(e.getMessage());
    }

    finally {
        if (session != null) {
            try {
                session.close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }

    return b;
}

From source file:ffsutils.TaskUtils.java

public static ArrayList<Tasks> TaskFile(Connection conn, String tranid, String diaryid, UserAccount userName)
        throws SQLException, FileNotFoundException, IOException {
    String tranid2;//from  ww  w . ja  va  2s  .  co m
    Integer comp = 2;
    Integer tranlen = tranid.length();
    int retval = comp.compareTo(tranlen);
    if (retval > 0) {
        tranid2 = "0" + tranid;
    } else if (retval < 0) {
        tranid2 = tranid.substring(tranid.length() - 2);
    } else {
        tranid2 = tranid;
    }

    System.out.println("tranid2 " + tranid2 + " diaryid " + diaryid + " tranid " + tranid);

    String sql = "Select * from " + userName.getcompany() + ".taskimag" + tranid2
            + " where tranid = ? and taskid = ?";

    PreparedStatement pstm = conn.prepareStatement(sql);
    pstm.setString(1, diaryid);
    pstm.setString(2, tranid);

    ResultSet rs = pstm.executeQuery();
    ArrayList<Tasks> list = new ArrayList<Tasks>();
    if (rs.next()) {
        String thisFile = rs.getString("imagedesc") + rs.getString("imagetype");
        String filename = "C:/java-app/group1/ffsint3/ffsint2/build/web/resources/" + rs.getString("imagedesc")
                + rs.getString("imagetype");

        File file = new File(filename);

        FileOutputStream output = new FileOutputStream(file);
        InputStream input = rs.getBinaryStream("imag1");
        byte[] buffer = new byte[1024];
        while (input.read(buffer) > 0) {
            output.write(buffer);
        }

        Tasks tasks = new Tasks();
        tasks.setTaskfrom(thisFile);
        list.add(tasks);

    }
    return list;
}

From source file:org.wso2.carbon.idp.mgt.dao.IdPManagementDAO.java

/**
 * @param dbConnection/*  w  w  w  .j  av  a  2  s . c o  m*/
 * @param idPName
 * @param tenantId
 * @return
 * @throws IdentityProviderManagementException
 * @throws SQLException
 */
public ProvisioningConnectorConfig[] getProvisioningConnectorConfigs(Connection dbConnection, String idPName,
        int idPId, int tenantId) throws IdentityProviderManagementException, SQLException {

    PreparedStatement prepStmt = null;
    PreparedStatement prepBaseStmt = null;

    ResultSet rs1 = null;
    ResultSet rs2 = null;

    try {
        // SP_IDP_PROV_CONNECTOR_TYPE,SP_IDP_PROV_CONFIG_KEY,
        // SP_IDP_PROV_CONFIG_VALUE,SP_IDP_PROV_CONFIG_IS_SECRET
        String sqlBaseStmt = IdPManagementConstants.SQLQueries.GET_IDP_PROVISIONING_CONFIGS_SQL;
        prepBaseStmt = dbConnection.prepareStatement(sqlBaseStmt);

        prepBaseStmt.setInt(1, idPId);
        rs1 = prepBaseStmt.executeQuery();

        Map<String, ProvisioningConnectorConfig> provisioningConnectorMap = new HashMap<String, ProvisioningConnectorConfig>();

        while (rs1.next()) {

            ProvisioningConnectorConfig provisioningConnector;

            String type = rs1.getString("PROVISIONING_CONNECTOR_TYPE");
            if (!provisioningConnectorMap.containsKey(type)) {
                provisioningConnector = new ProvisioningConnectorConfig();
                provisioningConnector.setName(type);

                if (("1").equals(rs1.getString("IS_ENABLED"))) {
                    provisioningConnector.setEnabled(true);
                } else {
                    provisioningConnector.setEnabled(false);
                }

                if (("1").equals(rs1.getString("IS_BLOCKING"))) {
                    provisioningConnector.setBlocking(true);
                } else {
                    provisioningConnector.setBlocking(false);
                }

                if (provisioningConnector.getProvisioningProperties() == null
                        || provisioningConnector.getProvisioningProperties().length == 0) {

                    String sqlStmt = IdPManagementConstants.SQLQueries.GET_IDP_PROVISIONING_PROPERTY_SQL;
                    prepStmt = dbConnection.prepareStatement(sqlStmt);

                    int configId = rs1.getInt("ID");
                    prepStmt.setInt(1, tenantId);
                    prepStmt.setInt(2, configId);

                    rs2 = prepStmt.executeQuery();

                    List<Property> provisioningProperties = new ArrayList<Property>();
                    while (rs2.next()) {
                        Property Property = new Property();
                        String name = rs2.getString("PROPERTY_KEY");
                        String value = rs2.getString("PROPERTY_VALUE");
                        String blobValue = getBlobValue(rs2.getBinaryStream("PROPERTY_BLOB_VALUE"));

                        String propertyType = rs2.getString("PROPERTY_TYPE");
                        String isSecret = rs2.getString("IS_SECRET");

                        Property.setName(name);
                        if (propertyType != null
                                && IdentityApplicationConstants.ConfigElements.PROPERTY_TYPE_BLOB
                                        .equals(propertyType.trim())) {
                            Property.setValue(blobValue);
                        } else {
                            Property.setValue(value);
                        }

                        Property.setType(propertyType);

                        if (("1").equals(isSecret)) {
                            Property.setConfidential(true);
                        } else {
                            Property.setConfidential(false);
                        }

                        provisioningProperties.add(Property);
                    }
                    provisioningConnector.setProvisioningProperties(
                            provisioningProperties.toArray(new Property[provisioningProperties.size()]));
                }

                provisioningConnectorMap.put(type, provisioningConnector);
            }
        }

        return provisioningConnectorMap.values()
                .toArray(new ProvisioningConnectorConfig[provisioningConnectorMap.size()]);

    } finally {
        IdentityApplicationManagementUtil.closeResultSet(rs1);
        IdentityApplicationManagementUtil.closeResultSet(rs2);
        IdentityApplicationManagementUtil.closeStatement(prepStmt);
        IdentityApplicationManagementUtil.closeStatement(prepBaseStmt);
    }
}

From source file:helma.objectmodel.db.NodeManager.java

/**
 *  Create a new Node from a ResultSet.//  w ww .  ja v a 2s  .c o m
 */
public Node createNode(DbMapping dbm, ResultSet rs, DbColumn[] columns, int offset)
        throws SQLException, IOException, ClassNotFoundException {
    HashMap propBuffer = new HashMap();
    String id = null;
    String name = null;
    String protoName = dbm.getTypeName();
    DbMapping dbmap = dbm;

    Node node = new Node(safe);

    for (int i = 0; i < columns.length; i++) {

        int columnNumber = i + 1 + offset;

        // set prototype?
        if (columns[i].isPrototypeField()) {
            String protoId = rs.getString(columnNumber);
            protoName = dbm.getPrototypeName(protoId);

            if (protoName != null) {
                dbmap = getDbMapping(protoName);

                if (dbmap == null) {
                    // invalid prototype name!
                    app.logError("No prototype defined for prototype mapping \"" + protoName
                            + "\" - Using default prototype \"" + dbm.getTypeName() + "\".");
                    dbmap = dbm;
                    protoName = dbmap.getTypeName();
                }
            }
        }

        // set id?
        if (columns[i].isIdField()) {
            id = rs.getString(columnNumber);
            // if id == null, the object doesn't actually exist - return null
            if (id == null) {
                return null;
            }
        }

        // set name?
        if (columns[i].isNameField()) {
            name = rs.getString(columnNumber);
        }

        Property newprop = new Property(node);

        switch (columns[i].getType()) {
        case Types.BIT:
        case Types.BOOLEAN:
            newprop.setBooleanValue(rs.getBoolean(columnNumber));

            break;

        case Types.TINYINT:
        case Types.BIGINT:
        case Types.SMALLINT:
        case Types.INTEGER:
            newprop.setIntegerValue(rs.getLong(columnNumber));

            break;

        case Types.REAL:
        case Types.FLOAT:
        case Types.DOUBLE:
            newprop.setFloatValue(rs.getDouble(columnNumber));

            break;

        case Types.DECIMAL:
        case Types.NUMERIC:

            BigDecimal num = rs.getBigDecimal(columnNumber);
            if (num == null) {
                break;
            }
            if (num.scale() > 0) {
                newprop.setFloatValue(num.doubleValue());
            } else {
                newprop.setIntegerValue(num.longValue());
            }

            break;

        case Types.VARBINARY:
        case Types.BINARY:
            newprop.setJavaObjectValue(rs.getBytes(columnNumber));

            break;

        case Types.BLOB:
        case Types.LONGVARBINARY: {
            InputStream in = rs.getBinaryStream(columnNumber);
            if (in == null) {
                break;
            }
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] buffer = new byte[2048];
            int read;
            while ((read = in.read(buffer)) > -1) {
                bout.write(buffer, 0, read);
            }
            newprop.setJavaObjectValue(bout.toByteArray());
        }

            break;

        case Types.LONGVARCHAR:
            try {
                newprop.setStringValue(rs.getString(columnNumber));
            } catch (SQLException x) {
                Reader in = rs.getCharacterStream(columnNumber);
                if (in == null) {
                    newprop.setStringValue(null);
                    break;
                }
                StringBuffer out = new StringBuffer();
                char[] buffer = new char[2048];
                int read;
                while ((read = in.read(buffer)) > -1) {
                    out.append(buffer, 0, read);
                }
                newprop.setStringValue(out.toString());
            }

            break;

        case Types.CHAR:
        case Types.VARCHAR:
        case Types.OTHER:
            newprop.setStringValue(rs.getString(columnNumber));

            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            newprop.setDateValue(rs.getTimestamp(columnNumber));

            break;

        case Types.NULL:
            newprop.setStringValue(null);

            break;

        case Types.CLOB:
            Clob cl = rs.getClob(columnNumber);
            if (cl == null) {
                newprop.setStringValue(null);
                break;
            }
            char[] c = new char[(int) cl.length()];
            Reader isr = cl.getCharacterStream();
            isr.read(c);
            newprop.setStringValue(String.copyValueOf(c));
            break;

        default:
            newprop.setStringValue(rs.getString(columnNumber));

            break;
        }

        if (rs.wasNull()) {
            newprop.setStringValue(null);
        }

        propBuffer.put(columns[i].getName(), newprop);

        // mark property as clean, since it's fresh from the db
        newprop.dirty = false;
    }

    if (id == null) {
        return null;
    } else {
        Transactor tx = Transactor.getInstance();
        if (tx != null) {
            // Check if the node is already registered with the transactor -
            // it may be in the process of being DELETED, but do return the
            // new node if the old one has been marked as INVALID.
            DbKey key = new DbKey(dbmap, id);
            Node dirtyNode = tx.getDirtyNode(key);
            if (dirtyNode != null && dirtyNode.getState() != Node.INVALID) {
                return dirtyNode;
            }
        }
    }

    Hashtable propMap = new Hashtable();
    DbColumn[] columns2 = dbmap.getColumns();
    for (int i = 0; i < columns2.length; i++) {
        Relation rel = columns2[i].getRelation();
        if (rel != null && rel.isPrimitiveOrReference()) {
            Property prop = (Property) propBuffer.get(columns2[i].getName());

            if (prop == null) {
                continue;
            }

            prop.setName(rel.propName);

            // if the property is a pointer to another node, change the property type to NODE
            if (rel.isReference() && rel.usesPrimaryKey()) {
                // FIXME: References to anything other than the primary key are not supported
                prop.convertToNodeReference(rel);
            }
            propMap.put(rel.propName, prop);
        }
    }

    node.init(dbmap, id, name, protoName, propMap);
    return node;
}

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

public InputStream getLOBStream(JDBCStore store, ResultSet rs, int column) throws SQLException {
    return rs.getBinaryStream(column);
}