Example usage for java.sql PreparedStatement setBoolean

List of usage examples for java.sql PreparedStatement setBoolean

Introduction

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

Prototype

void setBoolean(int parameterIndex, boolean x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java boolean value.

Usage

From source file:com.flexive.ejb.beans.MandatorEngineBean.java

/**
 * {@inheritDoc}//w  w  w. j  a  va 2 s . co m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void activate(long mandatorId) throws FxApplicationException {
    final UserTicket ticket = FxContext.getUserTicket();
    final FxEnvironment environment;
    // Security
    FxPermissionUtils.checkRole(ticket, Role.GlobalSupervisor);
    environment = CacheAdmin.getEnvironment();
    //exist check
    Mandator mand = environment.getMandator(mandatorId);
    if (mand.isActive())
        return; //silently ignore
    Connection con = null;
    PreparedStatement ps = null;
    String sql;

    try {

        // Obtain a database connection
        con = Database.getDbConnection();

        //                                                1              2              3          4
        sql = "UPDATE " + TBL_MANDATORS + " SET IS_ACTIVE=?, MODIFIED_BY=?, MODIFIED_AT=? WHERE ID=?";
        final long NOW = System.currentTimeMillis();
        ps = con.prepareStatement(sql);

        ps.setBoolean(1, true);
        ps.setLong(2, ticket.getUserId());
        ps.setLong(3, NOW);
        ps.setLong(4, mandatorId);
        ps.executeUpdate();
        StructureLoader.updateMandator(FxContext.get().getDivisionId(),
                new Mandator(mand.getId(), mand.getName(), mand.getMetadataId(), true,
                        new LifeCycleInfoImpl(mand.getLifeCycleInfo().getCreatorId(),
                                mand.getLifeCycleInfo().getCreationTime(), ticket.getUserId(), NOW)));
    } catch (SQLException exc) {
        EJBUtils.rollback(ctx);
        throw new FxUpdateException(LOG, exc, "ex.mandator.updateFailed", mand.getName(), exc.getMessage());
    } finally {
        Database.closeObjects(MandatorEngineBean.class, con, ps);
    }
}

From source file:com.flexive.ejb.beans.MandatorEngineBean.java

/**
 * {@inheritDoc}/*from www .ja  va2s. co m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void deactivate(long mandatorId) throws FxApplicationException {
    final UserTicket ticket = FxContext.getUserTicket();
    final FxEnvironment environment;
    // Security
    FxPermissionUtils.checkRole(ticket, Role.GlobalSupervisor);
    environment = CacheAdmin.getEnvironment();
    //exist check
    Mandator mand = environment.getMandator(mandatorId);
    if (!mand.isActive())
        return; //silently ignore
    if (mand.getId() == ticket.getMandatorId())
        throw new FxInvalidParameterException("mandatorId", "ex.mandator.deactivate.own", mand.getName(),
                mand.getId());
    Connection con = null;
    PreparedStatement ps = null;
    String sql;

    try {

        // Obtain a database connection
        con = Database.getDbConnection();

        //                                                1              2              3          4
        sql = "UPDATE " + TBL_MANDATORS + " SET IS_ACTIVE=?, MODIFIED_BY=?, MODIFIED_AT=? WHERE ID=?";
        final long NOW = System.currentTimeMillis();
        ps = con.prepareStatement(sql);

        ps.setBoolean(1, false);
        ps.setLong(2, ticket.getUserId());
        ps.setLong(3, NOW);
        ps.setLong(4, mandatorId);
        ps.executeUpdate();
        StructureLoader.updateMandator(FxContext.get().getDivisionId(),
                new Mandator(mand.getId(), mand.getName(), mand.getMetadataId(), false,
                        new LifeCycleInfoImpl(mand.getLifeCycleInfo().getCreatorId(),
                                mand.getLifeCycleInfo().getCreationTime(), ticket.getUserId(), NOW)));
    } catch (SQLException exc) {
        EJBUtils.rollback(ctx);
        throw new FxUpdateException(LOG, exc, "ex.mandator.updateFailed", mand.getName(), exc.getMessage());
    } finally {
        Database.closeObjects(MandatorEngineBean.class, con, ps);
    }
}

From source file:com.alfaariss.oa.authentication.remote.saml2.idp.storage.jdbc.IDPJDBCStorage.java

private SAML2IDP retrieveByID(String id) throws OAException {
    Connection connection = null;
    PreparedStatement pSelect = null;
    ResultSet resultSet = null;//from   ww w . j a v a 2  s.  c  o  m
    SAML2IDP saml2IDP = null;

    IMetadataProviderManager oMPM = MdMgrManager.getInstance().getMetadataProviderManager(_sId);

    try {
        connection = _dataSource.getConnection();

        pSelect = connection.prepareStatement(_sQuerySelectOnID);
        pSelect.setBoolean(1, true);
        pSelect.setString(2, id);
        resultSet = pSelect.executeQuery();
        if (resultSet.next()) {
            boolean bACSIndex = resultSet.getBoolean(COLUMN_ACS_INDEX);

            Boolean boolAllowCreate = null;
            String sAllowCreate = resultSet.getString(COLUMN_ALLOW_CREATE);
            if (sAllowCreate != null) {
                boolean bAllowCreate = resultSet.getBoolean(COLUMN_ALLOW_CREATE);
                boolAllowCreate = new Boolean(bAllowCreate);
            }

            boolean bScoping = resultSet.getBoolean(COLUMN_SCOPING);
            boolean bNameIDPolicy = resultSet.getBoolean(COLUMN_NAMEIDPOLICY);
            boolean bAvoidSubjectConfirmation = resultSet.getBoolean(COLUMN_AVOID_SUBJCONF);
            boolean bDisableSSOForIDP = resultSet.getBoolean(COLUMN_DISABLE_SSO);

            Date dLastModified = null;
            try {
                dLastModified = resultSet.getTimestamp(COLUMN_DATELASTMODIFIED);
            } catch (Exception e) {
                _oLogger.info(
                        "No " + COLUMN_DATELASTMODIFIED + " column found for SAML2IDP '" + id + "'; ignoring.");
            }

            saml2IDP = new SAML2IDP(id, resultSet.getBytes(COLUMN_SOURCEID),
                    resultSet.getString(COLUMN_FRIENDLYNAME), resultSet.getString(COLUMN_METADATA_FILE),
                    resultSet.getString(COLUMN_METADATA_URL), resultSet.getInt(COLUMN_METADATA_TIMEOUT),
                    bACSIndex, boolAllowCreate, bScoping, bNameIDPolicy,
                    resultSet.getString(COLUMN_NAMEIDFORMAT), bAvoidSubjectConfirmation, bDisableSSOForIDP,
                    dLastModified, oMPM.getId());
        }
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _oLogger.fatal("Internal error during retrieval of organization with ID: " + id, e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } finally {
        try {
            if (pSelect != null)
                pSelect.close();
        } catch (Exception e) {
            _oLogger.error("Could not close select statement", e);
        }

        try {
            if (connection != null)
                connection.close();
        } catch (Exception e) {
            _oLogger.error("Could not close connection", e);
        }
    }
    return saml2IDP;
}

From source file:at.alladin.rmbt.statisticServer.OpenTestSearchResource.java

/**
 * Fills in the given fields in the queue into the given prepared statement
 * @param ps//  w  w  w . j av a 2s  .c  o m
 * @param searchValues
 * @param firstField
 * @return
 * @throws SQLException
 */
private static PreparedStatement fillInWhereClause(PreparedStatement ps,
        Queue<Map.Entry<String, FieldType>> searchValues, int firstField) throws SQLException {
    //insert all values in the prepared statement in the order
    //in which the values had been put in the queue
    for (Map.Entry<String, FieldType> entry : searchValues) {
        switch (entry.getValue()) {
        case STRING:
            ps.setString(firstField, entry.getKey());
            break;
        case DATE:
            ps.setTimestamp(firstField, new Timestamp(Long.parseLong(entry.getKey())));
            break;
        case LONG:
            ps.setLong(firstField, Long.parseLong(entry.getKey()));
            break;
        case DOUBLE:
            ps.setDouble(firstField, Double.parseDouble(entry.getKey()));
            break;
        case UUID:
            ps.setObject(firstField, UUID.fromString(entry.getKey()));
            break;
        case BOOLEAN:
            ps.setBoolean(firstField, Boolean.valueOf(entry.getKey()));
            break;
        }
        firstField++;
    }
    return ps;
}

From source file:com.spvp.dal.MySqlDatabase.java

@Override
public Boolean ucitajGradoveUBazu(ArrayList<Grad> gradovi) throws SQLException {

    Connection conn = null;/*from w w  w  .  j  a  va  2s  .c  o m*/
    Boolean status = false;

    try {
        conn = getConnection();

        PreparedStatement pstmt = conn.prepareStatement(
                "INSERT INTO gradovi (ime, longitude, latitude, veci_centar)" + "VALUES(?,?,?,?)");
        for (Grad x : gradovi) {

            pstmt.clearParameters();
            pstmt.setString(1, x.getImeGrada());
            pstmt.setDouble(2, x.getLongitude());
            pstmt.setDouble(3, x.getLatitude());
            pstmt.setBoolean(4, x.getVeciCentar());

            pstmt.addBatch();
        }

        pstmt.executeBatch();
        status = true;

    } catch (SQLException ex) {
        Logger.getLogger(MySqlDatabase.class.getName()).log(Level.SEVERE, null, ex);

    } finally {

        if (conn != null)
            conn.close();
    }

    return status;
}

From source file:com.alfaariss.oa.authentication.remote.saml2.idp.storage.jdbc.IDPJDBCStorage.java

private SAML2IDP retrieveBySourceID(byte[] baSourceID) throws OAException {
    Connection connection = null;
    PreparedStatement pSelect = null;
    ResultSet resultSet = null;/*from w  ww .  j a  v  a2 s  .c  o m*/
    SAML2IDP saml2IDP = null;

    IMetadataProviderManager oMPM = MdMgrManager.getInstance().getMetadataProviderManager(_sId);

    try {
        connection = _dataSource.getConnection();

        pSelect = connection.prepareStatement(_sQuerySelectOnSourceID);
        pSelect.setBoolean(1, true);
        pSelect.setBytes(2, baSourceID);
        resultSet = pSelect.executeQuery();
        if (resultSet.next()) {
            boolean bACSIndex = resultSet.getBoolean(COLUMN_ACS_INDEX);

            Boolean boolAllowCreate = null;
            String sAllowCreate = resultSet.getString(COLUMN_ALLOW_CREATE);
            if (sAllowCreate != null) {
                boolean bAllowCreate = resultSet.getBoolean(COLUMN_ALLOW_CREATE);
                boolAllowCreate = new Boolean(bAllowCreate);
            }

            boolean bScoping = resultSet.getBoolean(COLUMN_SCOPING);
            boolean bNameIDPolicy = resultSet.getBoolean(COLUMN_NAMEIDPOLICY);
            boolean bAvoidSubjectConfirmation = resultSet.getBoolean(COLUMN_AVOID_SUBJCONF);
            boolean bDisableSSOForIDP = resultSet.getBoolean(COLUMN_DISABLE_SSO);

            Date dLastModified = null;
            try {
                dLastModified = resultSet.getTimestamp(COLUMN_DATELASTMODIFIED);
            } catch (Exception e) {
                _oLogger.info("No " + COLUMN_DATELASTMODIFIED + " column found for SAML2IDP with sourceid '"
                        + baSourceID + "'; ignoring.");
            }

            saml2IDP = new SAML2IDP(resultSet.getString(COLUMN_ID), baSourceID,
                    resultSet.getString(COLUMN_FRIENDLYNAME), resultSet.getString(COLUMN_METADATA_FILE),
                    resultSet.getString(COLUMN_METADATA_URL), resultSet.getInt(COLUMN_METADATA_TIMEOUT),
                    bACSIndex, boolAllowCreate, bScoping, bNameIDPolicy,
                    resultSet.getString(COLUMN_NAMEIDFORMAT), bAvoidSubjectConfirmation, bDisableSSOForIDP,
                    dLastModified, oMPM.getId());
        }
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _oLogger.fatal("Internal error during retrieval of organization with SourceID: " + baSourceID, e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } finally {
        try {
            if (pSelect != null)
                pSelect.close();
        } catch (Exception e) {
            _oLogger.error("Could not close select statement", e);
        }

        try {
            if (connection != null)
                connection.close();
        } catch (Exception e) {
            _oLogger.error("Could not close connection", e);
        }
    }
    return saml2IDP;
}

From source file:org.ensembl.healthcheck.util.ConnectionBasedSqlTemplateImpl.java

private void bindParamsToPreparedStatement(PreparedStatement st, Object[] arguments) throws SQLException {
    int i = 0;/*from   w  w w.j av  a2 s.c  om*/
    if (arguments != null) {

        for (Object arg : arguments) {
            i++;
            if (arg == null) {
                st.setNull(i, Types.NULL);
            } else if (arg instanceof String) {
                st.setString(i, (String) arg);
            } else if (arg instanceof Integer) {
                st.setInt(i, (Integer) arg);
            } else if (arg instanceof Boolean) {
                st.setBoolean(i, (Boolean) arg);
            } else if (arg instanceof Short) {
                st.setShort(i, (Short) arg);
            } else if (arg instanceof Date) {
                st.setTimestamp(i, new java.sql.Timestamp(((Date) arg).getTime()));
            } else if (arg instanceof java.sql.Date) {
                st.setDate(i, new java.sql.Date(((Date) arg).getTime()));
            } else if (arg instanceof Double) {
                st.setDouble(i, (Double) arg);
            } else if (arg instanceof Long) {
                st.setLong(i, (Long) arg);
            } else if (arg instanceof BigDecimal) {
                st.setObject(i, arg);
            } else if (arg instanceof BigInteger) {
                st.setObject(i, arg);
            } else { // Object
                try {
                    ByteArrayOutputStream bytesS = new ByteArrayOutputStream();
                    ObjectOutputStream out = new ObjectOutputStream(bytesS);
                    out.writeObject(arg);
                    out.close();
                    byte[] bytes = bytesS.toByteArray();
                    bytesS.close();
                    st.setBytes(i, bytes);
                } catch (IOException e) {
                    throw new SQLException(
                            "Could not serialize object " + arg + " for use in a PreparedStatement ");
                }
            }
        }
    }
}

From source file:com.alfaariss.oa.engine.user.provisioning.storage.internal.jdbc.JDBCInternalStorage.java

/**
 * Insert the supplied user profile in the profile table.
 * @param oConnection the connection//from   w  ww  .j a v  a  2 s. c o m
 * @param user the user that must be inserted
 * @throws UserException if insertion fails
 */
private void insertProfile(Connection oConnection, ProvisioningUser user, String sMethod) throws UserException {
    PreparedStatement oPreparedStatement = null;
    try {
        oPreparedStatement = oConnection.prepareStatement(_sProfileInsert);
        oPreparedStatement.setString(1, user.getID());
        oPreparedStatement.setString(2, sMethod);
        oPreparedStatement.setBoolean(3, user.isAuthenticationRegistered(sMethod));

        if (oPreparedStatement.executeUpdate() != 1) {
            StringBuffer sbError = new StringBuffer("Could not insert profile (");
            sbError.append(sMethod);
            sbError.append(") for user with id: ");
            sbError.append(user.getID());
            _logger.error(sbError.toString());
            throw new UserException(SystemErrors.ERROR_RESOURCE_INSERT);
        }
    } catch (UserException e) {
        throw e;
    } catch (SQLException e) {
        StringBuffer sbError = new StringBuffer("Could not insert profile for user with id '");
        sbError.append(user.getID());
        sbError.append("'; authentication method '");
        sbError.append(sMethod);
        sbError.append("'; registered: ");
        sbError.append(user.isAuthenticationRegistered(sMethod));
        _logger.error(sbError.toString(), e);
        throw new UserException(SystemErrors.ERROR_RESOURCE_INSERT);
    } catch (Exception e) {
        _logger.fatal("Could not insert profile", e);
        throw new UserException(SystemErrors.ERROR_INTERNAL);
    } finally {
        try {
            if (oPreparedStatement != null)
                oPreparedStatement.close();
        } catch (Exception e) {
            _logger.error("Could not close statement", e);
        }
    }
}

From source file:org.cloudfoundry.identity.uaa.scim.dao.standard.JdbcScimUserProvisioning.java

@Override
public ScimUserInterface create(final ScimUserInterface user) {

    validate(user);//ww w .  j a  v a 2s.co m
    logger.debug("Creating new user: " + user.getUserName());

    final String id = UUID.randomUUID().toString();
    try {
        jdbcTemplate.update(CREATE_USER_SQL, new PreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps) throws SQLException {

                ps.setString(1, id);
                ps.setInt(2, user.getVersion());
                ps.setTimestamp(3, new Timestamp(new Date().getTime()));
                ps.setTimestamp(4, new Timestamp(new Date().getTime()));
                ps.setString(5, user.getUserName());
                ps.setString(6, user.getPrimaryEmail());
                ps.setString(7, user.getGivenName());
                ps.setString(8, user.getFamilyName());
                ps.setBoolean(9, user.isActive());
                String phoneNumber = extractPhoneNumber(user);
                ps.setString(10, phoneNumber);
                ps.setBoolean(11, user.isVerified());
                ps.setString(12, user.getPassword());
            }
        });
    } catch (DuplicateKeyException e) {
        throw new ScimResourceAlreadyExistsException(
                "Username already in use (could be inactive account): " + user.getUserName());
    }
    return retrieve(id);
}

From source file:at.bestsolution.persistence.java.Util.java

public static void setValue(PreparedStatement pstmt, int parameterIndex, TypedValue value) throws SQLException {
    if (value.value == null) {
        int sqlType;
        switch (value.type) {
        case INT:
            sqlType = Types.INTEGER;
            break;
        case DOUBLE:
            sqlType = Types.DECIMAL;
            break;
        case FLOAT:
            sqlType = Types.FLOAT;
            break;
        case BOOLEAN:
            sqlType = Types.BOOLEAN;
            break;
        case LONG:
            sqlType = Types.BIGINT;
            break;
        case STRING:
            sqlType = Types.VARCHAR;
            break;
        case BLOB:
            sqlType = Types.BLOB;
            break;
        case CLOB:
            sqlType = Types.CLOB;
            break;
        case TIMESTAMP:
            sqlType = Types.TIMESTAMP;
            break;
        default:/*from  w w w  .j a  v a2s .c o  m*/
            sqlType = Types.OTHER;
            break;
        }
        pstmt.setNull(parameterIndex, sqlType);
    } else {
        switch (value.type) {
        case INT:
            pstmt.setInt(parameterIndex, ((Number) value.value).intValue());
            break;
        case DOUBLE:
            pstmt.setDouble(parameterIndex, ((Number) value.value).doubleValue());
            break;
        case FLOAT:
            pstmt.setDouble(parameterIndex, ((Number) value.value).doubleValue());
            break;
        case BOOLEAN:
            pstmt.setBoolean(parameterIndex, Boolean.TRUE.equals(value.value));
            break;
        case LONG:
            pstmt.setLong(parameterIndex, ((Number) value.value).longValue());
            break;
        case STRING:
            pstmt.setString(parameterIndex, (String) value.value);
            break;
        case TIMESTAMP:
            if (value.value instanceof Timestamp) {
                pstmt.setTimestamp(parameterIndex, (Timestamp) value.value);
            } else {
                pstmt.setTimestamp(parameterIndex, new Timestamp(((Date) value.value).getTime()));
            }
            break;
        case UNKNOWN:
            pstmt.setObject(parameterIndex, value.value);
            break;
        default:
            throw new IllegalStateException("Unknown type");
        }
    }
}