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:nl.nn.adapterframework.util.Locker.java

public String lock() throws JdbcException, SQLException, InterruptedException {
    Connection conn = getConnection();
    try {// w w  w  .  j av  a 2 s  .com
        if (!JdbcUtil.tableExists(conn, "ibisLock")) {
            if (isIgnoreTableNotExist()) {
                log.info("table [ibisLock] does not exist, ignoring lock");
                return LOCK_IGNORED;
            } else {
                throw new JdbcException("table [ibisLock] does not exist");
            }
        }
    } finally {
        try {
            conn.close();
        } catch (SQLException e) {
            log.error("error closing JdbcConnection", e);
        }
    }

    String objectIdWithSuffix = null;
    int r = -1;
    while (objectIdWithSuffix == null && (numRetries == -1 || r < numRetries)) {
        r++;
        if (r == 0 && firstDelay > 0) {
            Thread.sleep(firstDelay);
        }
        if (r > 0) {
            Thread.sleep(retryDelay);
        }
        Date date = new Date();
        objectIdWithSuffix = getObjectId();
        if (StringUtils.isNotEmpty(getDateFormatSuffix())) {
            String formattedDate = formatter.format(date);
            objectIdWithSuffix = objectIdWithSuffix.concat(formattedDate);
        }
        log.debug("preparing to set lock [" + objectIdWithSuffix + "]");
        conn = getConnection();
        try {
            PreparedStatement stmt = conn.prepareStatement(insertQuery);
            stmt.clearParameters();
            stmt.setString(1, objectIdWithSuffix);
            stmt.setString(2, getType());
            stmt.setString(3, Misc.getHostname());
            stmt.setTimestamp(4, new Timestamp(date.getTime()));
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            if (getType().equalsIgnoreCase("T")) {
                cal.add(Calendar.HOUR_OF_DAY, getRetention());
            } else {
                cal.add(Calendar.DAY_OF_MONTH, getRetention());
            }
            stmt.setTimestamp(5, new Timestamp(cal.getTime().getTime()));
            stmt.executeUpdate();
            log.debug("lock [" + objectIdWithSuffix + "] set");
        } catch (SQLException e) {
            log.debug(getLogPrefix() + "error executing insert query (as part of locker): " + e.getMessage());
            if (numRetries == -1 || r < numRetries) {
                log.debug(getLogPrefix() + "will try again");
                objectIdWithSuffix = null;
            } else {
                log.debug(getLogPrefix() + "will not try again");
                throw e;
            }
        } finally {
            try {
                conn.close();
            } catch (SQLException e) {
                log.error("error closing JdbcConnection", e);
            }
        }
    }
    return objectIdWithSuffix;
}

From source file:org.sakaiproject.search.journal.impl.DbJournalManager.java

/**
 * @see org.sakaiproject.search.journal.api.JournalManager#commitSave()
 *///from   ww  w  . ja  va2  s. co m
public void commitSave(JournalManagerState jms) throws IndexJournalException {
    Connection connection = ((JournalManagerStateImpl) jms).connection;
    PreparedStatement success = null;
    try {
        success = connection.prepareStatement("update search_journal set status = 'committed' where txid = ? ");
        success.clearParameters();
        success.setLong(1, ((JournalManagerStateImpl) jms).getTransactionId());
        if (success.executeUpdate() != 1) {
            throw new IndexJournalException("Failed to update index journal");
        }

        connection.commit();
    } catch (Exception ex) {
        try {
            connection.rollback();
        } catch (Exception ex2) {
            log.debug(ex);
        }
        throw new IndexJournalException("Failed to commit index ", ex);
    } finally {
        try {
            success.close();
        } catch (Exception ex) {
            log.debug(ex);
        }
        try {
            connection.close();
        } catch (Exception ex) {
            log.debug(ex);
        }
    }

}

From source file:org.sakaiproject.util.conversion.CheckConnection.java

public void testUTF8Transport(Connection connection) throws Exception {
    /*/*from  www . j a v a  2 s.  co m*/
     * byte[] b = new byte[102400]; byte[] b2 = new byte[102400]; byte[] b3 =
     * new byte[102400]; char[] cin = new char[102400]; Random r = new
     * Random(); r.nextBytes(b);
     */
    byte[] bin = new byte[102400];
    char[] cin = new char[102400];
    byte[] bout = new byte[102400];

    {
        int i = 0;
        for (int bx = 0; i < bin.length; bx++) {
            bin[i++] = (byte) bx;
        }
    }
    ByteStorageConversion.toChar(bin, 0, cin, 0, cin.length);
    String sin = new String(cin);

    char[] cout = sin.toCharArray();
    ByteStorageConversion.toByte(cout, 0, bout, 0, cout.length);

    for (int i = 0; i < bin.length; i++) {
        if (bin[i] != bout[i]) {
            throw new Exception(
                    "Internal Byte conversion failed at " + bin[i] + "=>" + (int) cin[i] + "=>" + bout[i]);
        }
    }

    PreparedStatement statement = null;
    PreparedStatement statement2 = null;
    ResultSet rs = null;
    try {
        statement = connection.prepareStatement("insert into blobtest ( id, bval ) values ( ?, ? )");
        statement.clearParameters();
        statement.setInt(1, 20);
        statement.setString(2, sin);
        statement.executeUpdate();

        statement2 = connection.prepareStatement("select bval from blobtest where id =  ? ");
        statement2.clearParameters();
        statement2.setInt(1, 20);
        rs = statement2.executeQuery();
        String sout = null;
        if (rs.next()) {
            sout = rs.getString(1);
        }

        if (sout == null)
            throw new IllegalStateException("String sout == null!");
        cout = sout.toCharArray();
        ByteStorageConversion.toByte(cout, 0, bout, 0, cout.length);

        if (sin.length() != sout.length()) {
            throw new Exception("UTF-8 Data was lost communicating with the database, please "
                    + "check connection string and default table types (Truncation/Expansion)");
        }

        for (int i = 0; i < bin.length; i++) {
            if (bin[i] != bout[i]) {
                throw new Exception("UTF-8 Data was corrupted communicating with the database, "
                        + "please check connectionstring and default table types (Conversion)" + "" + bin[i]
                        + "=>" + (int) cin[i] + "=>" + bout[i]);
            }
        }

        log.info("DB Connection passes UTF-8 tests");

    } finally {
        try {
            rs.close();
        } catch (Exception ex) {

        }
        try {
            statement2.close();
        } catch (Exception ex) {

        }
        try {
            statement.close();
        } catch (Exception ex) {

        }
    }

}

From source file:com.adaptris.core.services.jdbc.JdbcDataQueryService.java

/**
 * The main service method, which sees the specified query executed and the results returned in an XML message.
 * //from w  ww .  j av a 2s  .  c  om
 * @see com.adaptris.core.Service#doService(com.adaptris.core.AdaptrisMessage)
 */
@Override
public void doService(AdaptrisMessage msg) throws ServiceException {
    log.trace("Beginning doService");
    JdbcResult result = null;
    Connection conn = null;
    try {
        Connection c = getConnection(msg);
        if (!c.equals(actor.getSqlConnection())) {
            actor.reInitialise(c);
        }
        conn = actor.getSqlConnection();
        initXmlHelper(msg);
        String statement = getStatementCreator().createStatement(msg);
        PreparedStatement preparedStatement = actor.getQueryStatement(statement);
        preparedStatement.clearParameters();
        log.trace("Executing statement [{}]", statement);

        this.getParameterApplicator().applyStatementParameters(msg, preparedStatement, getStatementParameters(),
                statement);
        try {
            // closed by the finally block which closes the JdbcResult
            ResultSet rs = preparedStatement.executeQuery(); // lgtm [java/database-resource-leak]
            result = new JdbcResultBuilder().setHasResultSet(true).setResultSet(rs).build();
        } catch (SQLException e) {
            if (ignoreExecuteQueryErrors()) {
                log.debug("Ignore ExecuteQuery Errors enabled); using empty ResultSet");
                result = new JdbcResultBuilder().setHasResultSet(false).build();
            } else {
                throw e;
            }
        }
        resultSetTranslator.translate(result, msg);
        destroyXmlHelper(msg);
        commit(conn, msg);
    } catch (Exception e) {
        rollback(conn, msg);
        throw ExceptionHelper.wrapServiceException(e);
    } finally {
        JdbcUtil.closeQuietly(result);
        JdbcUtil.closeQuietly(conn);
    }
}

From source file:org.sakaiproject.content.impl.serialize.impl.test.MySQLByteStorage.java

@Test
public void testBlobData() throws SQLException {
    // run the test 10 times to make really certain there is no problem
    for (int k = 0; k < 10; k++) {
        byte[] bin = new byte[102400];
        char[] cin = new char[102400];

        byte[] bout = new byte[102400];
        Random r = new Random();
        r.nextBytes(bin);/*from w ww.  j a v  a  2 s  .c  o m*/

        ByteStorageConversion.toChar(bin, 0, cin, 0, cin.length);
        String sin = new String(cin);

        char[] cout = sin.toCharArray();
        ByteStorageConversion.toByte(cout, 0, bout, 0, cout.length);

        for (int i = 0; i < bin.length; i++) {
            Assert.assertEquals(
                    "Internal Byte conversion failed at " + bin[i] + "=>" + (int) cin[i] + "=>" + bout[i],
                    bin[i], bout[i]);
        }

        Connection connection = null;
        PreparedStatement statement = null;
        PreparedStatement statement2 = null;
        ResultSet rs = null;
        try {
            connection = tds.getConnection();
            statement = connection.prepareStatement("insert into blobtest ( id, bval ) values ( ?, ? )");
            statement.clearParameters();
            statement.setInt(1, k);
            statement.setString(2, sin);
            statement.executeUpdate();

            statement2 = connection.prepareStatement("select bval from blobtest where id =  ? ");
            statement2.clearParameters();
            statement2.setInt(1, k);
            rs = statement2.executeQuery();
            String sout = null;
            if (rs.next()) {
                sout = rs.getString(1);
            }

            // ensure no NPE, but maybe this is not ok because cout current value may be invalid
            if (sout != null) {
                cout = sout.toCharArray();
            }
            ByteStorageConversion.toByte(cout, 0, bout, 0, cout.length);

            if (sout != null) {
                Assert.assertEquals("Input and Output Lenghts are not the same ", sin.length(), sout.length());
            }

            for (int i = 0; i < bin.length; i++) {
                Assert.assertEquals(
                        "Database Byte conversion failed at " + bin[i] + "=>" + (int) cin[i] + "=>" + bout[i],
                        bin[i], bout[i]);
            }
        } finally {
            try {
                rs.close();
            } catch (Exception ex) {

            }
            try {
                statement2.close();
            } catch (Exception ex) {

            }
            try {
                statement.close();
            } catch (Exception ex) {

            }
            try {
                connection.close();
            } catch (Exception ex) {

            }
        }
    }
}

From source file:nl.nn.adapterframework.jdbc.JdbcListener.java

protected void execute(Connection conn, String query, String parameter) throws ListenerException {
    if (StringUtils.isNotEmpty(query)) {
        if (trace && log.isDebugEnabled())
            log.debug("executing statement [" + query + "]");
        PreparedStatement stmt = null;
        try {/*from  w  w  w.  ja va  2  s. c o  m*/
            stmt = conn.prepareStatement(query);
            stmt.clearParameters();
            if (StringUtils.isNotEmpty(parameter)) {
                log.debug("setting parameter 1 to [" + parameter + "]");
                stmt.setString(1, parameter);
            }
            stmt.execute();

        } catch (SQLException e) {
            throw new ListenerException(getLogPrefix() + "exception executing statement [" + query + "]", e);
        } finally {
            if (stmt != null) {
                try {
                    //                  log.debug("closing statement for ["+query+"]");
                    stmt.close();
                } catch (SQLException e) {
                    log.warn(getLogPrefix() + "exception closing statement [" + query + "]", e);
                }
            }
        }
    }
}

From source file:org.apache.hadoop.yarn.server.applicationhistoryservice.metrics.timeline.AbstractMiniHBaseClusterTest.java

protected void insertMetricRecords(Connection conn, TimelineMetrics metrics, long currentTime)
        throws SQLException, IOException {

    List<TimelineMetric> timelineMetrics = metrics.getMetrics();
    if (timelineMetrics == null || timelineMetrics.isEmpty()) {
        LOG.debug("Empty metrics insert request.");
        return;//from   w w w.java 2s .  c o  m
    }

    PreparedStatement metricRecordStmt = null;

    try {
        metricRecordStmt = conn.prepareStatement(String.format(UPSERT_METRICS_SQL, METRICS_RECORD_TABLE_NAME));

        for (TimelineMetric metric : timelineMetrics) {
            metricRecordStmt.clearParameters();

            if (LOG.isTraceEnabled()) {
                LOG.trace("host: " + metric.getHostName() + ", " + "metricName = " + metric.getMetricName()
                        + ", " + "values: " + metric.getMetricValues());
            }
            double[] aggregates = AggregatorUtils.calculateAggregates(metric.getMetricValues());

            metricRecordStmt.setString(1, metric.getMetricName());
            metricRecordStmt.setString(2, metric.getHostName());
            metricRecordStmt.setString(3, metric.getAppId());
            metricRecordStmt.setString(4, metric.getInstanceId());
            metricRecordStmt.setLong(5, currentTime);
            metricRecordStmt.setLong(6, metric.getStartTime());
            metricRecordStmt.setString(7, metric.getType());
            metricRecordStmt.setDouble(8, aggregates[0]);
            metricRecordStmt.setDouble(9, aggregates[1]);
            metricRecordStmt.setDouble(10, aggregates[2]);
            metricRecordStmt.setLong(11, (long) aggregates[3]);
            String json = TimelineUtils.dumpTimelineRecordtoJSON(metric.getMetricValues());
            metricRecordStmt.setString(12, json);

            try {
                metricRecordStmt.executeUpdate();
            } catch (SQLException sql) {
                LOG.error(sql);
            }
        }

        conn.commit();

    } finally {
        if (metricRecordStmt != null) {
            try {
                metricRecordStmt.close();
            } catch (SQLException e) {
                // Ignore
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException sql) {
                // Ignore
            }
        }
    }
}

From source file:org.sakaiproject.util.conversion.SchemaConversionController.java

private void insertErrorReport(PreparedStatement reportError, String id, String handler, String description) {
    if (reportError != null) {
        try {/*w w w  .j  a v  a2s  .  com*/
            reportError.clearParameters();
            reportError.setString(1, id);
            reportError.setString(2, handler);
            reportError.setString(3, description);
            reportError.execute();
        } catch (SQLException e) {
            log.warn("Unable to insert error report [" + id + " " + handler + " \"" + description + "\" " + e);
        }
    }
}

From source file:org.sakaiproject.search.journal.impl.DbJournalManager.java

/**
 * @throws JournalErrorException//from www  .j  a v  a 2  s .c  o m
 * @see org.sakaiproject.search.journal.api.JournalManager#getLaterSavePoints(long)
 */
public long getNextSavePoint(long savePoint) throws JournalErrorException {
    Connection connection = null;
    PreparedStatement listLaterSavePoints = null;
    ResultSet rs = null;
    try {
        connection = datasource.getConnection();
        listLaterSavePoints = connection.prepareStatement(
                "select txid from search_journal where txid > ? and (status = 'commited' or status = 'committed') order by txid asc ");
        listLaterSavePoints.clearParameters();
        listLaterSavePoints.setLong(1, savePoint);
        try {
            rs = listLaterSavePoints.executeQuery();
            if (rs.next()) {
                return rs.getLong(1);
            }
        } catch (Exception ex) {
            log.warn("Shared Index Optimization in progress, pausing updates to this index :" + ex);
        }
        throw new JournalExhausetedException("No More savePoints available");
    } catch (SQLException ex) {
        log.error("Failed to retrieve list of journal items ", ex);
        throw new JournalErrorException("Journal Error ", ex);
    } finally {
        try {
            rs.close();
        } catch (Exception ex) {
            log.debug(ex);
        }
        try {
            listLaterSavePoints.close();
        } catch (Exception ex) {
            log.debug(ex);
        }
        try {
            connection.close();
        } catch (Exception ex) {
            log.debug(ex);
        }
    }
}

From source file:org.sakaiproject.search.mock.MockSearchService.java

public int getPendingDocs() {
    int pendingDocs = 0;
    Connection connection = null;
    PreparedStatement countPST = null;
    ResultSet rs = null;/*w  ww .  j  av  a  2  s  .c  o  m*/
    try {
        connection = datasource.getConnection();
        countPST = connection
                .prepareStatement("select count(*) from searchbuilderitem  where searchstate = ? ");

        countPST.clearParameters();
        countPST.setLong(1, SearchBuilderItem.STATE_PENDING);
        rs = countPST.executeQuery();
        if (rs.next()) {
            pendingDocs = rs.getInt(1);
        }
        connection.commit();
    } catch (Exception ex) {
        log.error("Failed to get pending docs ", ex);
    } finally {
        try {
            rs.close();
        } catch (Exception ex2) {
            log.debug(ex2);
        }
        try {
            countPST.close();
        } catch (Exception ex2) {
            log.debug(ex2);
        }
        try {
            connection.close();
        } catch (Exception ex2) {
            log.debug(ex2);
        }
    }
    return pendingDocs;
}