Example usage for java.sql PreparedStatement clearParameters

List of usage examples for java.sql PreparedStatement clearParameters

Introduction

In this page you can find the example usage for java.sql PreparedStatement clearParameters.

Prototype

void clearParameters() throws SQLException;

Source Link

Document

Clears the current parameter values immediately.

Usage

From source file:org.apache.marmotta.kiwi.persistence.KiWiConnection.java

/**
 * Return the prepared statement with the given identifier; first looks in the statement cache and if it does
 * not exist there create a new statement.
 *
 * @param key the id of the statement in statements.properties
 * @return//from   w  w  w .  j av a  2  s.c  om
 * @throws SQLException
 */
public PreparedStatement getPreparedStatement(String key) throws SQLException {
    requireJDBCConnection();

    PreparedStatement statement = statementCache.get(key);
    if (statement == null || statement.isClosed()) {
        statement = connection.prepareStatement(dialect.getStatement(key), ResultSet.TYPE_FORWARD_ONLY,
                ResultSet.CONCUR_READ_ONLY);
        statementCache.put(key, statement);
    }
    statement.clearParameters();
    if (persistence.getDialect().isCursorSupported()) {
        statement.setFetchSize(persistence.getConfiguration().getCursorSize());
    }
    return statement;
}

From source file:dk.netarkivet.harvester.datamodel.DomainDBDAO.java

/**
 * Update the list of harvest info for the given domain, keeping IDs where
 * applicable./*  w w w.j av  a2 s .  co m*/
 * @param c 
 *            A connection to the database
 * @param d
 *            A domain to update.
 * @throws SQLException
 *             If any database problems occur during the update process.
 */
private void updateHarvestInfo(Connection c, Domain d) throws SQLException {
    List<Long> oldIDs = DBUtils.selectLongList(c,
            "SELECT historyinfo.historyinfo_id " + "FROM historyinfo, configurations "
                    + "WHERE historyinfo.config_id " + "= configurations.config_id"
                    + "  AND configurations.domain_id = ?",
            d.getID());
    PreparedStatement s = c.prepareStatement("UPDATE historyinfo SET " + "stopreason = ?, "
            + "objectcount = ?, " + "bytecount = ?, " + "config_id = "
            + " (SELECT config_id FROM configurations, domains" + "  WHERE domains.domain_id = ?"
            + "    AND configurations.name = ?" + "    AND configurations.domain_id = domains.domain_id), "
            + "harvest_id = ?, " + "job_id = ? " + "WHERE historyinfo_id = ?");
    Iterator<HarvestInfo> his = d.getHistory().getHarvestInfo();
    while (his.hasNext()) {
        HarvestInfo hi = his.next();
        if (hi.hasID() && oldIDs.remove(hi.getID())) {
            s.setInt(1, hi.getStopReason().ordinal());
            s.setLong(2, hi.getCountObjectRetrieved());
            s.setLong(3, hi.getSizeDataRetrieved());
            s.setLong(4, d.getID());
            s.setString(5, d.getConfiguration(hi.getDomainConfigurationName()).getName());
            s.setLong(6, hi.getHarvestID());
            if (hi.getJobID() != null) {
                s.setLong(7, hi.getJobID());
            } else {
                s.setNull(7, Types.BIGINT);
            }
            s.setLong(8, hi.getID());
            s.executeUpdate();
            s.clearParameters();
        } else {
            insertHarvestInfo(c, d, hi);
        }
    }
    if (oldIDs.size() != 0) {
        String message = "Not allowed to delete historyinfo " + oldIDs + " on " + d;
        log.debug(message);
        throw new IOFailure(message);
    }
}

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

/**
 * @param conn//from  www  . ja va 2 s.c o  m
 * @param idPId
 * @param claims
 * @throws SQLException
 */
private void addIdPClaims(Connection conn, int idPId, int tenantId, Claim[] claims) throws SQLException {
    PreparedStatement prepStmt = null;

    if (claims == null || claims.length == 0) {
        return;
    }

    try {
        // SP_IDP_ID, SP_IDP_CLAIM
        String sqlStmt = IdPManagementConstants.SQLQueries.ADD_IDP_CLAIMS_SQL;
        prepStmt = conn.prepareStatement(sqlStmt);
        for (Claim claim : claims) {
            prepStmt.setInt(1, idPId);
            prepStmt.setInt(2, tenantId);
            prepStmt.setString(3, CharacterEncoder.getSafeText(claim.getClaimUri()));
            prepStmt.addBatch();
            prepStmt.clearParameters();
        }
        prepStmt.executeBatch();
    } finally {
        IdentityApplicationManagementUtil.closeStatement(prepStmt);
    }
}

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

/**
 * @param conn/*  w  w w . ja  v  a  2s.c o m*/
 * @param idPId
 * @param idpRoleNames
 * @throws SQLException
 */
private void addIdPRoles(Connection conn, int idPId, int tenantId, String[] idpRoleNames) throws SQLException {

    PreparedStatement prepStmt = null;
    // SP_IDP_ID, SP_IDP_ROLE
    String sqlStmt = IdPManagementConstants.SQLQueries.ADD_IDP_ROLES_SQL;

    if (idpRoleNames == null || idpRoleNames.length == 0) {
        return;
    }

    try {
        prepStmt = conn.prepareStatement(sqlStmt);

        for (String idpRole : idpRoleNames) {
            prepStmt.setInt(1, idPId);
            prepStmt.setInt(2, tenantId);
            prepStmt.setString(3, CharacterEncoder.getSafeText(idpRole));
            prepStmt.addBatch();
            prepStmt.clearParameters();
        }

        prepStmt.executeBatch();

    } finally {
        IdentityApplicationManagementUtil.closeStatement(prepStmt);
    }
}

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

/**
 * @param conn/*from   w ww  .ja  va  2 s.  c om*/
 * @param idPId
 * @param tenantId
 * @param roleMappings
 * @throws SQLException
 * @throws IdentityProviderManagementException
 */
private void addIdPRoleMappings(Connection conn, int idPId, int tenantId, RoleMapping[] roleMappings)
        throws SQLException, IdentityProviderManagementException {

    Map<String, Integer> roleIdMap = new HashMap<String, Integer>();
    PreparedStatement prepStmt = null;
    ResultSet rs = null;

    // SP_IDP_ROLE_ID, SP_IDP_ROL
    String sqlStmt = IdPManagementConstants.SQLQueries.GET_IDP_ROLES_SQL;

    try {

        prepStmt = conn.prepareStatement(sqlStmt);
        prepStmt.setInt(1, idPId);
        rs = prepStmt.executeQuery();

        while (rs.next()) {
            int idpRoleId = rs.getInt("ID");
            String roleName = rs.getString("ROLE");
            roleIdMap.put(roleName, idpRoleId);
        }

        prepStmt.clearParameters();
        IdentityApplicationManagementUtil.closeStatement(prepStmt);
        IdentityApplicationManagementUtil.closeResultSet(rs);

        if (roleIdMap.isEmpty()) {
            String message = "No Identity Provider roles defined for tenant " + tenantId;
            throw new IdentityProviderManagementException(message);
        }

        sqlStmt = IdPManagementConstants.SQLQueries.ADD_IDP_ROLE_MAPPINGS_SQL;
        prepStmt = conn.prepareStatement(sqlStmt);

        for (RoleMapping mapping : roleMappings) {
            if (mapping.getRemoteRole() != null && roleIdMap.containsKey(mapping.getRemoteRole())) {

                int idpRoleId = roleIdMap.get(mapping.getRemoteRole());

                String userStoreId = mapping.getLocalRole().getUserStoreId();
                String localRole = mapping.getLocalRole().getLocalRoleName();

                // SP_IDP_ROLE_ID, SP_TENANT_ID, SP_USER_STORE_ID, SP_LOCAL_ROLE
                prepStmt.setInt(1, idpRoleId);
                prepStmt.setInt(2, tenantId);
                prepStmt.setString(3, CharacterEncoder.getSafeText(userStoreId));
                prepStmt.setString(4, CharacterEncoder.getSafeText(localRole));
                prepStmt.addBatch();
            } else {
                throw new IdentityProviderManagementException("Cannot find Identity Provider role "
                        + mapping.getRemoteRole() + " for tenant " + tenantId);
            }
        }

        prepStmt.executeBatch();

    } finally {
        IdentityApplicationManagementUtil.closeStatement(prepStmt);
        IdentityApplicationManagementUtil.closeResultSet(rs);
    }

}

From source file:com.archivas.clienttools.arcutils.utils.database.ManagedJobSchema.java

/**
 * Updates the stats for all of the files passed in, and also updates the general job statistics
 * to reflect how many success/failures there were
 * // w  ww  .ja va2  s . co  m
 * @param files
 *            -
 * @throws DatabaseException
 *             -
 */
@SuppressWarnings({ "ThrowableResultOfMethodCallIgnored" })
public void markFilesProcessed(Collection<FileStats> files) throws DatabaseException {
    synchronized (DatabaseResourceManager.DB_LOCK) {
        PooledDbConnection conn = null;
        try {

            conn = connPool.getConnection();
            PreparedStatement stmt = conn.prepareStatement(MARK_FILE_PROCESSED_STMT_NAME, markFileProcessedSql);
            conn.setAutoCommit(false);
            long totalCnt = 0;
            long totalSize = 0;
            long successCnt = 0;
            long successSize = 0;
            long failCnt = 0;
            long failSize = 0;
            long failDirCnt = 0;
            for (FileStats file : files) {
                FileStatus status = file.getStatus();
                switch (status) {
                case SUCCEEDED: {
                    if (file.includeInStats()) {
                        successCnt++;
                        successSize += file.getSize();
                    }
                    break;
                }
                case FAILED: {
                    if (file.includeInStats()) {
                        failCnt++;
                        failSize += file.getSize();
                        if (file.failedDuringFind()) {
                            // in this case we need to increment the total counts as well
                            totalCnt++;
                            totalSize += file.getSize(); // probably zero since we didn't
                                                         // get that far
                        }
                    }
                    if (file.getArcProcssFile().isDirectory()) {
                        failDirCnt++;
                    }
                    break;
                }
                default:
                    throw new RuntimeException("Unsupported file status: " + status);
                }
                stmt.clearParameters();
                stmt.setInt(1, file.getStatus().ordinal());
                stmt.setInt(2, file.getRetries());
                Date startTime = file.getStartTime();
                if (startTime != null) {
                    stmt.setLong(3, startTime.getTime());
                } else {
                    stmt.setNull(3, java.sql.Types.BIGINT);
                }
                Date endTime = file.getEndTime();
                if (endTime != null) {
                    stmt.setLong(4, endTime.getTime());
                } else {
                    stmt.setNull(4, java.sql.Types.BIGINT);
                }
                stmt.setLong(5, file.getRunTimeMs());

                if (file.getException() == null) {
                    stmt.setNull(6, java.sql.Types.VARCHAR);
                } else {
                    stmt.setString(6, file.getException().getMessage());
                }

                if (file.getStatusCode() == null) {
                    stmt.setNull(7, java.sql.Types.INTEGER);
                } else {
                    stmt.setInt(7, file.getStatusCode());
                }
                stmt.setLong(8, file.getDatabaseRecordId());

                stmt.addBatch();
            }

            // execute the batch statment to update all of the file rows
            stmt.executeBatch();

            // now update overall job stats to reflect these changes
            ManagedJobsSchema.getInstance().updateProcessedFilesStats(conn, jobId, totalCnt, totalSize,
                    successCnt, successSize, failCnt, failSize, failDirCnt);
            conn.commit();

        } catch (Exception e) {
            rollback(conn);
            throw new DatabaseException(DBUtils.getErrorMessage(
                    "An error occurred updating file stats on table " + qualifiedFilesTableName, e), e);
        } finally {
            connPool.returnConnection(conn);
        }
    }
}

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

/**
 * @param conn/*from  w  ww  .j  ava  2s  . c  om*/
 * @param idPId
 * @param tenantId
 * @param claimMappings
 * @throws SQLException
 * @throws IdentityProviderManagementException
 */
private void addIdPClaimMappings(Connection conn, int idPId, int tenantId, ClaimMapping[] claimMappings)
        throws SQLException, IdentityProviderManagementException {

    Map<String, Integer> claimIdMap = new HashMap<String, Integer>();
    PreparedStatement prepStmt = null;
    ResultSet rs = null;

    try {

        if (claimMappings == null || claimMappings.length == 0) {
            return;
        }

        String sqlStmt = IdPManagementConstants.SQLQueries.GET_IDP_CLAIMS_SQL;
        prepStmt = conn.prepareStatement(sqlStmt);
        prepStmt.setInt(1, idPId);
        rs = prepStmt.executeQuery();

        while (rs.next()) {
            int id = rs.getInt("ID");
            String claim = rs.getString("CLAIM");
            claimIdMap.put(claim, id);
        }

        prepStmt.clearParameters();
        IdentityApplicationManagementUtil.closeStatement(prepStmt);
        IdentityApplicationManagementUtil.closeResultSet(rs);

        if (claimIdMap.isEmpty()) {
            String message = "No Identity Provider claim URIs defined for tenant " + tenantId;
            throw new IdentityProviderManagementException(message);
        }

        sqlStmt = IdPManagementConstants.SQLQueries.ADD_IDP_CLAIM_MAPPINGS_SQL;
        prepStmt = conn.prepareStatement(sqlStmt);
        for (ClaimMapping mapping : claimMappings) {
            if (mapping != null && mapping.getRemoteClaim() != null
                    && claimIdMap.containsKey(mapping.getRemoteClaim().getClaimUri())) {

                int idpClaimId = claimIdMap.get(mapping.getRemoteClaim().getClaimUri());
                String localClaimURI = mapping.getLocalClaim().getClaimUri();

                prepStmt.setInt(1, idpClaimId);
                prepStmt.setInt(2, tenantId);
                prepStmt.setString(3, CharacterEncoder.getSafeText(localClaimURI));
                prepStmt.setString(4, CharacterEncoder.getSafeText(mapping.getDefaultValue()));

                if (mapping.isRequested()) {
                    prepStmt.setString(5, "1");
                } else {
                    prepStmt.setString(5, "0");
                }

                prepStmt.addBatch();
            } else {
                throw new IdentityProviderManagementException(
                        "Cannot find Identity Provider claim mapping for tenant " + tenantId);
            }
        }

        prepStmt.executeBatch();

    } finally {
        IdentityApplicationManagementUtil.closeStatement(prepStmt);
        IdentityApplicationManagementUtil.closeResultSet(rs);
        IdentityApplicationManagementUtil.closeStatement(prepStmt);
    }
}

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

/**
 * @param dbConnection// ww  w.ja  va 2  s  .c om
 * @param idPName
 * @param tenantId
 * @return
 * @throws IdentityProviderManagementException
 * @throws SQLException
 */
public PermissionsAndRoleConfig getPermissionsAndRoleConfiguration(Connection dbConnection, String idPName,
        int idPId, int tenantId) throws IdentityProviderManagementException, SQLException {

    PreparedStatement prepStmt = null;
    ResultSet rs = null;
    PermissionsAndRoleConfig permissionRoleConfiguration = new PermissionsAndRoleConfig();

    try {

        List<String> idpRoleList = new ArrayList<String>();
        // SP_IDP_ROLE
        String sqlStmt = IdPManagementConstants.SQLQueries.GET_IDP_ROLES_SQL;
        prepStmt = dbConnection.prepareStatement(sqlStmt);
        prepStmt.setInt(1, idPId);
        rs = prepStmt.executeQuery();
        while (rs.next()) {
            idpRoleList.add(rs.getString("ROLE"));
        }

        permissionRoleConfiguration.setIdpRoles(idpRoleList.toArray(new String[idpRoleList.size()]));

        prepStmt.clearParameters();
        IdentityApplicationManagementUtil.closeResultSet(rs);
        IdentityApplicationManagementUtil.closeStatement(prepStmt);

        List<RoleMapping> roleMappings = new ArrayList<RoleMapping>();
        // SP_IDP_ROLE_MAPPINGS.SP_USER_STORE_ID, SP_IDP_ROLE_MAPPINGS.SP_LOCAL_ROLE,
        // SP_IDP_ROLES.SP_IDP_ROLE

        sqlStmt = IdPManagementConstants.SQLQueries.GET_IDP_ROLE_MAPPINGS_SQL;
        prepStmt = dbConnection.prepareStatement(sqlStmt);
        prepStmt.setInt(1, idPId);
        rs = prepStmt.executeQuery();
        while (rs.next()) {
            LocalRole localRole = new LocalRole(rs.getString("IDP_ROLE_MAPPING.USER_STORE_ID"),
                    rs.getString("IDP_ROLE_MAPPING.LOCAL_ROLE"));
            RoleMapping roleMapping = new RoleMapping(localRole, rs.getString("IDP_ROLE.ROLE"));
            roleMappings.add(roleMapping);
        }

        permissionRoleConfiguration.setRoleMappings(roleMappings.toArray(new RoleMapping[roleMappings.size()]));
        return permissionRoleConfiguration;
    } finally {
        IdentityApplicationManagementUtil.closeResultSet(rs);
        IdentityApplicationManagementUtil.closeStatement(prepStmt);
    }
}

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

/**
 * @param dbConnection/*from w  w w  .j  a v  a2 s .  c  om*/
 * @param idPName
 * @param tenantId
 * @return
 * @throws IdentityProviderManagementException
 * @throws SQLException
 */
private ClaimConfig getIdPClaimConfiguration(Connection dbConnection, String idPName, String userClaimUri,
        String roleClaimUri, int idPId, int tenantId) throws IdentityProviderManagementException, SQLException {

    PreparedStatement prepStmt = null;
    ResultSet rs = null;

    try {

        List<Claim> claimList = new ArrayList<Claim>();
        // SP_IDP_CLAIM_ID, SP_IDP_CLAIM
        String sqlStmt = IdPManagementConstants.SQLQueries.GET_IDP_CLAIMS_SQL;
        prepStmt = dbConnection.prepareStatement(sqlStmt);
        prepStmt.setInt(1, idPId);
        rs = prepStmt.executeQuery();

        ClaimConfig claimConfig = new ClaimConfig();

        while (rs.next()) {
            Claim identityProviderClaim = new Claim();
            identityProviderClaim.setClaimId(rs.getInt(1));
            identityProviderClaim.setClaimUri(rs.getString(2));
            claimList.add(identityProviderClaim);
        }

        prepStmt.clearParameters();
        IdentityApplicationManagementUtil.closeResultSet(rs);
        IdentityApplicationManagementUtil.closeStatement(prepStmt);

        // populate claim configuration with identity provider claims.
        claimConfig.setIdpClaims(claimList.toArray(new Claim[claimList.size()]));

        claimConfig.setUserClaimURI(userClaimUri);
        claimConfig.setRoleClaimURI(roleClaimUri);

        List<ClaimMapping> claimMappings = new ArrayList<ClaimMapping>();

        // SP_IDP_CLAIMS.SP_IDP_CLAIM SP_IDP_CLAIM_MAPPINGS.SP_LOCAL_CLAIM
        sqlStmt = IdPManagementConstants.SQLQueries.GET_IDP_CLAIM_MAPPINGS_SQL;
        prepStmt = dbConnection.prepareStatement(sqlStmt);
        prepStmt.setInt(1, idPId);
        rs = prepStmt.executeQuery();

        while (rs.next()) {
            ClaimMapping claimMapping = new ClaimMapping();

            Claim idpClaim = new Claim();
            idpClaim.setClaimUri(rs.getString("IDP_CLAIM.CLAIM"));

            Claim localClaim = new Claim();
            localClaim.setClaimUri(rs.getString("IDP_CLAIM_MAPPING.LOCAL_CLAIM"));

            claimMapping.setLocalClaim(localClaim);
            claimMapping.setRemoteClaim(idpClaim);
            claimMapping.setDefaultValue(rs.getString("IDP_CLAIM_MAPPING.DEFAULT_VALUE"));
            if (("1").equals(rs.getString("IDP_CLAIM_MAPPING.IS_REQUESTED"))) {
                claimMapping.setRequested(true);
            } else if (("0").equals(rs.getString("IDP_CLAIM_MAPPING.IS_REQUESTED"))) {
                claimMapping.setRequested(false);
            }
            claimMappings.add(claimMapping);

        }

        claimConfig.setClaimMappings(claimMappings.toArray(new ClaimMapping[claimMappings.size()]));

        return claimConfig;
    } finally {
        IdentityApplicationManagementUtil.closeResultSet(rs);
        IdentityApplicationManagementUtil.closeStatement(prepStmt);
    }
}

From source file:com.mirth.connect.donkey.server.data.jdbc.JdbcDao.java

private void insertContent(String channelId, long messageId, int metaDataId, ContentType contentType,
        String content, String dataType, boolean encrypted) {
    try {/*  w ww .j  av a 2 s  . co m*/
        // Only encrypt if the content is not already encrypted
        if (encryptData && encryptor != null && !encrypted) {
            content = encryptor.encrypt(content);
            encrypted = true;
        }

        PreparedStatement statement = prepareStatement("insertMessageContent", channelId);
        statement.setInt(1, metaDataId);
        statement.setLong(2, messageId);
        statement.setInt(3, contentType.getContentTypeCode());
        statement.setString(4, content);
        statement.setString(5, dataType);
        statement.setBoolean(6, encrypted);

        statement.executeUpdate();
        statement.clearParameters();
    } catch (SQLException e) {
        throw new DonkeyDaoException(e);
    }
}