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.uas.document.DocumentDAO.java

@Override
public DocumentDTO updateDocument(DocumentDTO dDto) {
    DocumentDTO dtoViejo = getDocument(dDto);
    DocumentDTO objectDto = null;//from   w w  w. j  av  a 2s . c  om
    ResultSet rs = null;
    Connection c = null;
    PreparedStatement preparedStmt = null;

    try {
        c = DataSourceSingleton.getInstance().getConnection();
        String SQL = "update \"public\".\"document\" set \"fileDate\"=?,\"deleted\"=?,\"backedUp\"=?,\"idArea\"=? where \"id\"=? ";
        preparedStmt = c.prepareStatement(SQL);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date parsedDate = dateFormat.parse(dDto.getFileDate().substring(0, 10));
        Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
        preparedStmt.setTimestamp(1, timestamp);
        preparedStmt.setBoolean(2, dDto.getDeleted());
        //System.out.println("dDto.getBackedUp() : " + dDto.getBackedUp());
        preparedStmt.setBoolean(3, dDto.getBackedUp());
        preparedStmt.setInt(4, dDto.getIdArea());
        preparedStmt.setInt(5, dDto.getId());
        preparedStmt.executeUpdate();
        //System.out.println("dDto.getVengoDeRootYPuedoCambiarDeArea() : " + dDto.getVengoDeRootYPuedoCambiarDeArea());
        if ((dtoViejo.getIdArea() != dDto.getIdArea()) && (dDto.getVengoDeRootYPuedoCambiarDeArea())) {
            DocumentDTO dtoNuevo = getDocument(dDto);
            if (dDto.getDeleted()) {
                Files.createDirectories(Paths.get(dtoNuevo.getFullPathToFolderInDeleted()).getParent());
                Files.move(Paths.get(dtoViejo.getFullPathToFolderInDeleted()),
                        Paths.get(dtoNuevo.getFullPathToFolderInDeleted()));
            } else {
                //Si 
                Files.createDirectories(Paths.get(dtoNuevo.getFullPathToFolder()).getParent());
                Files.move(Paths.get(dtoViejo.getFullPathToFolder()),
                        Paths.get(dtoNuevo.getFullPathToFolder()));
            }
        }
        /* if (!dDto.getBackedUp()){
        TransactionRecordFacade tFac = new TransactionRecordFacade();
        TransactionRecordDTO tDto = new TransactionRecordDTO();
        tDto.getObjectDTO().setId(dDto.getId());
        tDto.getTransactionTypeDTO().setId(4);
        tDto.getUsuarioDTO().setId(dDto.getCreatedBy());
        tFac.createTransactionRecord(tDto);
         }
        */

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (c != null) {
                c.close();
            }
            if (preparedStmt != null) {
                preparedStmt.close();
            }

        } catch (Exception e2) {
            e2.printStackTrace();
        }

    }
    return dDto;
}

From source file:edu.jhuapl.openessence.datasource.jdbc.JdbcOeDataSource.java

protected void setArguments(List<Object> arguments, PreparedStatement pStmt) throws SQLException {
    int argCount = 1;
    for (Object o : arguments) {
        // TODO NEED TO ADDRESS THE USE CASES FOR THIS null...POKUAM1...what if not nullable column?
        if (o == null) {
            pStmt.setObject(argCount, null);
        } else if (o instanceof java.sql.Timestamp) {
            pStmt.setTimestamp(argCount, (java.sql.Timestamp) o);
        } else if (o instanceof java.util.Date) {
            pStmt.setTimestamp(argCount, new java.sql.Timestamp(((java.util.Date) o).getTime()));
        } else if (o instanceof Integer) {
            pStmt.setInt(argCount, (Integer) o);
        } else if (o instanceof Long) {
            pStmt.setLong(argCount, (Long) o);
        } else if (o instanceof Float) {
            pStmt.setFloat(argCount, (Float) o);
        } else if (o instanceof Double) {
            pStmt.setDouble(argCount, (Double) o);
        } else if (o instanceof String) {
            pStmt.setString(argCount, (String) o);
        } else if (o instanceof Boolean) {
            pStmt.setBoolean(argCount, (Boolean) o);
        } else {/*from w  w  w  .  jav a2s  .co m*/
            throw new AssertionError("Unexpected object " + o + " " + o.getClass());
        }
        argCount += 1;
    }
}

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

/**
 * Activates or deactivates a partial harvest definition. This method is
 * actually to be used not to have to read from the DB big harvest
 * definitions and optimize the activation / deactivation, it is sort of a
 * lightweight version of update.//from  w ww  . ja v a 2s  . co m
 *
 * @param harvestDefinition
 *            the harvest definition object.
 */
@Override
public synchronized void flipActive(SparsePartialHarvest harvestDefinition) {
    ArgumentNotValid.checkNotNull(harvestDefinition, "HarvestDefinition harvestDefinition");

    Connection c = HarvestDBConnection.get();
    PreparedStatement s = null;
    try {
        if (harvestDefinition.getOid() == null || !exists(c, harvestDefinition.getOid())) {
            final String message = "Cannot update non-existing " + "harvestdefinition '"
                    + harvestDefinition.getName() + "'";
            log.debug(message);
            throw new PermissionDenied(message);
        }

        c.setAutoCommit(false);
        s = c.prepareStatement("UPDATE harvestdefinitions SET " + "name = ?, " + "comments = ?, "
                + "numevents = ?, " + "submitted = ?," + "isactive = ?," + "edition = ?, audience = ? "
                + "WHERE harvest_id = ? AND edition = ?");
        DBUtils.setName(s, 1, harvestDefinition, Constants.MAX_NAME_SIZE);
        DBUtils.setComments(s, 2, harvestDefinition, Constants.MAX_COMMENT_SIZE);
        s.setInt(3, harvestDefinition.getNumEvents());
        s.setTimestamp(4, new Timestamp(harvestDefinition.getSubmissionDate().getTime()));
        s.setBoolean(5, !harvestDefinition.isActive());
        long nextEdition = harvestDefinition.getEdition() + 1;
        s.setLong(6, nextEdition);
        s.setString(7, harvestDefinition.getAudience());
        s.setLong(8, harvestDefinition.getOid());
        s.setLong(9, harvestDefinition.getEdition());
        int rows = s.executeUpdate();
        // Since the HD exists, no rows indicates bad edition
        if (rows == 0) {
            String message = "Somebody else must have updated " + harvestDefinition + " since edition "
                    + harvestDefinition.getEdition() + ", not updating";
            log.debug(message);
            throw new PermissionDenied(message);
        }
        s.close();

        // Now pull more strings
        s = c.prepareStatement(
                "UPDATE partialharvests SET " + "schedule_id = " + "    (SELECT schedule_id FROM schedules "
                        + "WHERE schedules.name = ?), " + "nextdate = ? " + "WHERE harvest_id = ?");
        s.setString(1, harvestDefinition.getScheduleName());
        DBUtils.setDateMaybeNull(s, 2, harvestDefinition.getNextDate());
        s.setLong(3, harvestDefinition.getOid());
        rows = s.executeUpdate();
        log.debug(rows + " partialharvests records updated");
        s.close();
        c.commit();
    } catch (SQLException e) {
        throw new IOFailure("SQL error while updating harvest definition " + harvestDefinition + "\n"
                + ExceptionUtils.getSQLExceptionCause(e), e);
    } finally {
        DBUtils.rollbackIfNeeded(c, "updating", harvestDefinition);
        HarvestDBConnection.release(c);
    }
}

From source file:com.concursive.connect.web.modules.documents.dao.FileItem.java

/**
 * Description of the Method// w  w  w.j  a v  a  2  s  .  com
 *
 * @param db Description of Parameter
 * @return Description of the Returned Value
 * @throws SQLException Description of Exception
 */
public boolean insertVersion(Connection db) throws SQLException {
    if (!isValid()) {
        return false;
    }
    boolean result = false;
    boolean doCommit = false;
    try {
        if (doCommit = db.getAutoCommit()) {
            db.setAutoCommit(false);
        }
        //Insert a new version of an existing file
        FileItemVersion thisVersion = new FileItemVersion();
        thisVersion.setId(this.getId());
        thisVersion.setSubject(subject);
        thisVersion.setClientFilename(clientFilename);
        thisVersion.setFilename(filename);
        thisVersion.setVersion(version);
        thisVersion.setSize(size);
        thisVersion.setEnteredBy(enteredBy);
        thisVersion.setModifiedBy(modifiedBy);
        thisVersion.setImageWidth(imageWidth);
        thisVersion.setImageHeight(imageHeight);
        thisVersion.setComment(comment);
        thisVersion.insert(db);

        //Update the master record
        int i = 0;
        PreparedStatement pst = db.prepareStatement("UPDATE project_files "
                + "SET subject = ?, client_filename = ?, filename = ?, version = ?, "
                + "size = ?, modifiedby = ?, modified = CURRENT_TIMESTAMP, comment = ?, image_width = ?, image_height = ? , featured_file = ? "
                + "WHERE item_id = ? ");
        pst.setString(++i, subject);
        pst.setString(++i, clientFilename);
        pst.setString(++i, filename);
        pst.setDouble(++i, version);
        pst.setInt(++i, size);
        pst.setInt(++i, modifiedBy);
        pst.setString(++i, comment);
        pst.setInt(++i, imageWidth);
        pst.setInt(++i, imageHeight);
        pst.setBoolean(++i, featuredFile);
        pst.setInt(++i, this.getId());
        pst.execute();
        pst.close();
        logUpload(db);
        if (doCommit) {
            db.commit();
        }
        result = true;
    } catch (Exception e) {
        LOG.error("Could not insert version", e);
        if (doCommit) {
            db.rollback();
        }
        throw new SQLException(e.getMessage());
    } finally {
        if (doCommit) {
            db.setAutoCommit(true);
        }
    }
    return result;
}

From source file:org.accada.epcis.repository.query.QueryOperationsBackendSQL.java

/**
 * {@inheritDoc}//from w  ww.j a va2  s . c  o  m
 */
public void storeSupscriptions(final QueryOperationsSession session, QueryParams queryParams, String dest,
        String subscrId, SubscriptionControls controls, String trigger,
        QuerySubscriptionScheduled newSubscription, String queryName, Schedule schedule)
        throws SQLException, ImplementationExceptionResponse {
    String insert = "INSERT INTO subscription (subscriptionid, "
            + "params, dest, sched, trigg, initialrecordingtime, "
            + "exportifempty, queryname, lastexecuted) VALUES "
            + "((?), (?), (?), (?), (?), (?), (?), (?), (?))";
    PreparedStatement stmt = session.getConnection().prepareStatement(insert);
    LOG.debug("QUERY: " + insert);
    try {
        stmt.setString(1, subscrId);
        LOG.debug("       query param 1: " + subscrId);

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(outStream);
        out.writeObject(queryParams);
        ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
        stmt.setBinaryStream(2, inStream, inStream.available());
        LOG.debug("       query param 2: [" + inStream.available() + " bytes]");

        stmt.setString(3, dest.toString());
        LOG.debug("       query param 3: " + dest);

        outStream = new ByteArrayOutputStream();
        out = new ObjectOutputStream(outStream);
        out.writeObject(schedule);
        inStream = new ByteArrayInputStream(outStream.toByteArray());
        stmt.setBinaryStream(4, inStream, inStream.available());
        LOG.debug("       query param 4: [" + inStream.available() + " bytes]");

        stmt.setString(5, trigger);
        LOG.debug("       query param 5: " + trigger);

        Calendar cal = newSubscription.getInitialRecordTime();
        Timestamp ts = new Timestamp(cal.getTimeInMillis());
        String time = ts.toString();
        stmt.setString(6, time);
        LOG.debug("       query param 6: " + time);

        stmt.setBoolean(7, controls.isReportIfEmpty());
        LOG.debug("       query param 7: " + controls.isReportIfEmpty());

        stmt.setString(8, queryName);
        LOG.debug("       query param 8: " + queryName);

        stmt.setString(9, time);
        LOG.debug("       query param 9: " + time);

        stmt.executeUpdate();
    } catch (IOException e) {
        String msg = "Unable to store the subscription to the database: " + e.getMessage();
        LOG.error(msg);
        ImplementationException iex = new ImplementationException();
        iex.setReason(msg);
        iex.setSeverity(ImplementationExceptionSeverity.ERROR);
        throw new ImplementationExceptionResponse(msg, iex, e);
    }
}

From source file:edu.pitt.apollo.db.ApolloDbUtils.java

private int getRoleKey(int softwareIdKey, boolean canRun, boolean canViewCache)
        throws ApolloDatabaseKeyNotFoundException, ApolloDatabaseException {
    if (softwareIdKey >= 1) {
        // software statusId found...now lets see if this specific role
        // exists...
        String query = "SELECT id FROM roles WHERE software_id = ? AND can_run = ? AND can_view_cached_results = ?";
        try (Connection conn = datasource.getConnection()) {
            PreparedStatement pstmt = conn.prepareStatement(query);

            pstmt.setInt(1, softwareIdKey);
            pstmt.setBoolean(2, canRun);
            pstmt.setBoolean(3, canViewCache);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                throw new ApolloDatabaseKeyNotFoundException(
                        "No entry found in the roles table where software_id = " + softwareIdKey
                                + " and can_run = " + canRun + " and can_view_cached_resuls = " + canViewCache);
            } else {
                return rs.getInt(1);
            }/*w w w  .  j  a v  a  2  s.c o  m*/
        } catch (SQLException ex) {
            throw new ApolloDatabaseException("SQLException getting role key: " + ex.getMessage());
        }
    } else {
        throw new ApolloDatabaseKeyNotFoundException(
                "getRoleKey() called with invalid softwareIdKey: " + softwareIdKey);
    }
}

From source file:org.cerberus.crud.dao.impl.TestCaseExecutionInQueueDAO.java

@Override
public void insert(TestCaseExecutionInQueue inQueue) throws CerberusException {
    Connection connection = this.databaseSpring.connect();
    if (connection == null) {
        throw new CerberusException(new MessageGeneral(MessageGeneralEnum.NO_DATA_FOUND));
    }/*from   w  w  w  . j a v  a 2 s. co m*/

    PreparedStatement statementInsert = null;

    try {
        statementInsert = connection.prepareStatement(QUERY_INSERT);
        statementInsert.setString(1, inQueue.getTest());
        statementInsert.setString(2, inQueue.getTestCase());
        statementInsert.setString(3, inQueue.getCountry());
        statementInsert.setString(4, inQueue.getEnvironment());
        statementInsert.setString(5, inQueue.getRobot());
        statementInsert.setString(6, inQueue.getRobotIP());
        statementInsert.setString(7, inQueue.getRobotPort());
        statementInsert.setString(8, inQueue.getBrowser());
        statementInsert.setString(9, inQueue.getBrowserVersion());
        statementInsert.setString(10, inQueue.getPlatform());
        statementInsert.setBoolean(11, inQueue.isManualURL());
        statementInsert.setString(12, inQueue.getManualHost());
        statementInsert.setString(13, inQueue.getManualContextRoot());
        statementInsert.setString(14, inQueue.getManualLoginRelativeURL());
        statementInsert.setString(15, inQueue.getManualEnvData());
        statementInsert.setString(16, inQueue.getTag());
        statementInsert.setString(17, inQueue.getOutputFormat());
        statementInsert.setInt(18, inQueue.getScreenshot());
        statementInsert.setInt(19, inQueue.getVerbose());
        statementInsert.setString(20, inQueue.getTimeout());
        statementInsert.setBoolean(21, inQueue.isSynchroneous());
        statementInsert.setInt(22, inQueue.getPageSource());
        statementInsert.setInt(23, inQueue.getSeleniumLog());
        statementInsert.setTimestamp(24, new Timestamp(inQueue.getRequestDate().getTime()));
        statementInsert.setInt(25, inQueue.getRetries());
        statementInsert.setString(26, inQueue.isManualExecution() ? "Y" : "N");
        statementInsert.setString(27, inQueue.getState() == null ? TestCaseExecutionInQueue.State.WAITING.name()
                : inQueue.getState().name());

        statementInsert.executeUpdate();
    } catch (SQLException exception) {
        LOG.warn("Unable to execute query : " + exception.getMessage());
        throw new CerberusException(new MessageGeneral(MessageGeneralEnum.NO_DATA_FOUND));
    } finally {
        if (statementInsert != null) {
            try {
                statementInsert.close();
            } catch (SQLException e) {
                LOG.warn("Unable to close insert statement due to " + e.getMessage());
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                LOG.warn("Unable to close connection due to " + e.getMessage());
            }
        }
    }
}

From source file:org.fosstrak.epcis.repository.query.QueryOperationsBackendSQL.java

/**
 * {@inheritDoc}//from   w ww .  jav  a2s  .  c  o m
 */
public void storeSupscriptions(final QueryOperationsSession session, QueryParams queryParams, String dest,
        String subscrId, SubscriptionControls controls, String trigger,
        QuerySubscriptionScheduled newSubscription, String queryName, Schedule schedule)
        throws SQLException, ImplementationExceptionResponse {
    String insert = "INSERT INTO subscription (subscriptionid, "
            + "params, dest, sched, trigg, initialrecordingtime, "
            + "exportifempty, queryname, lastexecuted) VALUES "
            + "((?), (?), (?), (?), (?), (?), (?), (?), (?))";
    PreparedStatement stmt = session.getConnection().prepareStatement(insert);
    LOG.debug("QUERY: " + insert);
    try {
        stmt.setString(1, subscrId);
        LOG.debug("       query param 1: " + subscrId);

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(outStream);
        out.writeObject(queryParams);
        ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
        stmt.setBinaryStream(2, inStream, inStream.available());
        LOG.debug("       query param 2: [" + inStream.available() + " bytes]");

        stmt.setString(3, dest.toString());
        LOG.debug("       query param 3: " + dest);

        outStream = new ByteArrayOutputStream();
        out = new ObjectOutputStream(outStream);
        out.writeObject(schedule);
        inStream = new ByteArrayInputStream(outStream.toByteArray());
        stmt.setBinaryStream(4, inStream, inStream.available());
        LOG.debug("       query param 4: [" + inStream.available() + " bytes]");

        stmt.setString(5, trigger);
        LOG.debug("       query param 5: " + trigger);

        Calendar cal = newSubscription.getInitialRecordTime();
        Timestamp ts = new Timestamp(cal.getTimeInMillis());
        String time = ts.toString();
        stmt.setString(6, time);
        LOG.debug("       query param 6: " + time);

        stmt.setBoolean(7, controls.isReportIfEmpty());
        LOG.debug("       query param 7: " + controls.isReportIfEmpty());

        stmt.setString(8, queryName);
        LOG.debug("       query param 8: " + queryName);

        stmt.setString(9, time);
        LOG.debug("       query param 9: " + time);

        stmt.executeUpdate();
        session.commit();
    } catch (IOException e) {
        String msg = "Unable to store the subscription to the database: " + e.getMessage();
        LOG.error(msg);
        ImplementationException iex = new ImplementationException();
        iex.setReason(msg);
        iex.setSeverity(ImplementationExceptionSeverity.ERROR);
        throw new ImplementationExceptionResponse(msg, iex, e);
    }
}

From source file:org.apache.sqoop.repository.common.CommonRepositoryHandler.java

/**
 * {@inheritDoc}/*from   w  ww . ja v  a 2 s  . c  o m*/
 */
@Override
public void enableJob(long jobId, boolean enabled, Connection conn) {
    PreparedStatement enableConn = null;

    try {
        enableConn = conn.prepareStatement(crudQueries.getStmtEnableJob());
        enableConn.setBoolean(1, enabled);
        enableConn.setLong(2, jobId);
        enableConn.executeUpdate();
    } catch (SQLException ex) {
        logException(ex, jobId);
        throw new SqoopException(CommonRepositoryError.COMMON_0039, ex);
    } finally {
        closeStatements(enableConn);
    }
}

From source file:org.apache.sqoop.repository.common.CommonRepositoryHandler.java

/**
 * {@inheritDoc}/*from   w ww .j  a  va2  s .  c  om*/
 */
@Override
public void enableLink(long linkId, boolean enabled, Connection conn) {
    PreparedStatement enableConn = null;

    try {
        enableConn = conn.prepareStatement(crudQueries.getStmtEnableLink());
        enableConn.setBoolean(1, enabled);
        enableConn.setLong(2, linkId);
        enableConn.executeUpdate();
    } catch (SQLException ex) {
        logException(ex, linkId);
        throw new SqoopException(CommonRepositoryError.COMMON_0038, ex);
    } finally {
        closeStatements(enableConn);
    }
}