<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.activemq.store.jdbc;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.activemq.util.Handler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Represents an exclusive lock on a database to avoid multiple brokers running
 * against the same logical database.
 * 
 * @org.apache.xbean.XBean element="database-locker"
 * 
 */
public class DefaultDatabaseLocker implements DatabaseLocker {
    public static final long DEFAULT_LOCK_ACQUIRE_SLEEP_INTERVAL = 1000;
    private static final Logger LOG = LoggerFactory.getLogger(DefaultDatabaseLocker.class);
    protected DataSource dataSource;
    protected Statements statements;
    protected long lockAcquireSleepInterval = DEFAULT_LOCK_ACQUIRE_SLEEP_INTERVAL;

    protected Connection connection;
    protected boolean stopping;
    protected Handler<Exception> exceptionHandler;
    
    public DefaultDatabaseLocker() {
    }
    
    public DefaultDatabaseLocker(JDBCPersistenceAdapter persistenceAdapter) throws IOException {
        setPersistenceAdapter(persistenceAdapter);
    }

    public void setPersistenceAdapter(JDBCPersistenceAdapter adapter) throws IOException {
        this.dataSource = adapter.getLockDataSource();
        this.statements = adapter.getStatements();
    }
    
    public void start() throws Exception {
        stopping = false;

        LOG.info("Attempting to acquire the exclusive lock to become the Master broker");
        String sql = statements.getLockCreateStatement();
        LOG.debug("Locking Query is "+sql);
        
        PreparedStatement statement = null;
        while (true) {
            try {
                connection = dataSource.getConnection();
                connection.setAutoCommit(false);
                statement = connection.prepareStatement(sql);
                statement.execute();
                break;
            } catch (Exception e) {
                try {
                    if (stopping) {
                        throw new Exception(
                                "Cannot start broker as being asked to shut down. " 
                                        + "Interrupted attempt to acquire lock: "
                                        + e, e);
                    }
                    if (exceptionHandler != null) {
                        try {
                            exceptionHandler.handle(e);
                        } catch (Throwable handlerException) {
                            LOG.error( "The exception handler "
                                    + exceptionHandler.getClass().getCanonicalName()
                                    + " threw this exception: "
                                    + handlerException
                                    + " while trying to handle this exception: "
                                    + e, handlerException);
                        }

                    } else {
                        LOG.debug("Lock failure: "+ e, e);
                    }
                } finally {
                    // Let's make sure the database connection is properly
                    // closed when an error occurs so that we're not leaking
                    // connections 
                    if (null != connection) {
                        try {
                            connection.close();
                        } catch (SQLException e1) {
                            LOG.error("Caught exception while closing connection: " + e1, e1);
                        }
                        
                        connection = null;
                    }
                }
            } finally {
                if (null != statement) {
                    try {
                        statement.close();
                    } catch (SQLException e1) {
                        LOG.debug("Caught while closing statement: " + e1, e1);
                    }
                    statement = null;
                }
            }

            LOG.info("Failed to acquire lock.  Sleeping for " + lockAcquireSleepInterval + " milli(s) before trying again...");
            try {
                Thread.sleep(lockAcquireSleepInterval);
            } catch (InterruptedException ie) {
                LOG.warn("Master lock retry sleep interrupted", ie);
            }
        }

        LOG.info("Becoming the master on dataSource: " + dataSource);
    }

    public void stop() throws Exception {
        stopping = true;
        try {
            if (connection != null && !connection.isClosed()) {
                try {
                    connection.rollback();
                } catch (SQLException sqle) {
                    LOG.warn("Exception while rollbacking the connection on shutdown", sqle);
                } finally {
                    try {
                        connection.close();
                    } catch (SQLException ignored) {
                        LOG.debug("Exception while closing connection on shutdown", ignored);
                    }
                }
            }
        } catch (SQLException sqle) {
            LOG.warn("Exception while checking close status of connection on shutdown", sqle);
        }
    }

    public boolean keepAlive() {
        PreparedStatement statement = null;
        boolean result = false;
        try {
            statement = connection.prepareStatement(statements.getLockUpdateStatement());
            statement.setLong(1, System.currentTimeMillis());
            int rows = statement.executeUpdate();
            if (rows == 1) {
                result=true;
            }
        } catch (Exception e) {
            LOG.error("Failed to update database lock: " + e, e);
        } finally {
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    LOG.error("Failed to close statement",e);
                }
            }
        }
        return result;
    }
 
    public long getLockAcquireSleepInterval() {
        return lockAcquireSleepInterval;
    }
<commit_msg>Applied patch for https://issues.apache.org/jira/browse/AMQ-3681<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.activemq.store.jdbc;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;

import javax.sql.DataSource;

import org.apache.activemq.util.Handler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Represents an exclusive lock on a database to avoid multiple brokers running
 * against the same logical database.
 * 
 * @org.apache.xbean.XBean element="database-locker"
 * 
 */
public class DefaultDatabaseLocker implements DatabaseLocker {
    public static final long DEFAULT_LOCK_ACQUIRE_SLEEP_INTERVAL = 1000;
    private static final Logger LOG = LoggerFactory.getLogger(DefaultDatabaseLocker.class);
    protected DataSource dataSource;
    protected Statements statements;
    protected long lockAcquireSleepInterval = DEFAULT_LOCK_ACQUIRE_SLEEP_INTERVAL;

    protected PreparedStatement lockCreateStatement;
    protected PreparedStatement lockUpdateStatement;
    protected Connection connection;
    protected boolean stopping;
    protected Handler<Exception> exceptionHandler;
    
    public DefaultDatabaseLocker() {
    }
    
    public DefaultDatabaseLocker(JDBCPersistenceAdapter persistenceAdapter) throws IOException {
        setPersistenceAdapter(persistenceAdapter);
    }

    public void setPersistenceAdapter(JDBCPersistenceAdapter adapter) throws IOException {
        this.dataSource = adapter.getLockDataSource();
        this.statements = adapter.getStatements();
    }
    
    public void start() throws Exception {
        stopping = false;

        LOG.info("Attempting to acquire the exclusive lock to become the Master broker");
        String sql = statements.getLockCreateStatement();
        LOG.debug("Locking Query is "+sql);
        
        while (true) {
            try {
                connection = dataSource.getConnection();
                connection.setAutoCommit(false);
                lockCreateStatement = connection.prepareStatement(sql);
                lockCreateStatement.execute();
                break;
            } catch (Exception e) {
                try {
                    if (stopping) {
                        throw new Exception(
                                "Cannot start broker as being asked to shut down. " 
                                        + "Interrupted attempt to acquire lock: "
                                        + e, e);
                    }
                    if (exceptionHandler != null) {
                        try {
                            exceptionHandler.handle(e);
                        } catch (Throwable handlerException) {
                            LOG.error( "The exception handler "
                                    + exceptionHandler.getClass().getCanonicalName()
                                    + " threw this exception: "
                                    + handlerException
                                    + " while trying to handle this exception: "
                                    + e, handlerException);
                        }

                    } else {
                        LOG.debug("Lock failure: "+ e, e);
                    }
                } finally {
                    // Let's make sure the database connection is properly
                    // closed when an error occurs so that we're not leaking
                    // connections 
                    if (null != connection) {
                        try {
                            connection.close();
                        } catch (SQLException e1) {
                            LOG.error("Caught exception while closing connection: " + e1, e1);
                        }
                        
                        connection = null;
                    }
                }
            } finally {
                if (null != lockCreateStatement) {
                    try {
                        lockCreateStatement.close();
                    } catch (SQLException e1) {
                        LOG.debug("Caught while closing statement: " + e1, e1);
                    }
                    lockCreateStatement = null;
                }
            }

            LOG.info("Failed to acquire lock.  Sleeping for " + lockAcquireSleepInterval + " milli(s) before trying again...");
            try {
                Thread.sleep(lockAcquireSleepInterval);
            } catch (InterruptedException ie) {
                LOG.warn("Master lock retry sleep interrupted", ie);
            }
        }

        LOG.info("Becoming the master on dataSource: " + dataSource);
    }

    public void stop() throws Exception {
        stopping = true;
        try {
            if (lockCreateStatement != null) {
                lockCreateStatement.cancel();    			
            }
        } catch (SQLFeatureNotSupportedException e) {
            LOG.warn("Failed to cancel locking query on dataSource" + dataSource, e);    		
        }
        try {
    	    if (lockUpdateStatement != null) {
        	    lockUpdateStatement.cancel();    			
    	    }
        } catch (SQLFeatureNotSupportedException e) {
            LOG.warn("Failed to cancel locking query on dataSource" + dataSource, e);    		
        }
        try {
            if (connection != null && !connection.isClosed()) {
                try {
                    connection.rollback();
                } catch (SQLException sqle) {
                    LOG.warn("Exception while rollbacking the connection on shutdown", sqle);
                } finally {
                    try {
                        connection.close();
                    } catch (SQLException ignored) {
                        LOG.debug("Exception while closing connection on shutdown", ignored);
                    }
                    lockCreateStatement = null;
                }
            }
        } catch (SQLException sqle) {
            LOG.warn("Exception while checking close status of connection on shutdown", sqle);
        }
    }

    public boolean keepAlive() {
        boolean result = false;
        try {
            lockUpdateStatement = connection.prepareStatement(statements.getLockUpdateStatement());
            lockUpdateStatement.setLong(1, System.currentTimeMillis());
            lockUpdateStatement.setQueryTimeout(10);
            int rows = lockUpdateStatement.executeUpdate();
            if (rows == 1) {
                result=true;
            }
        } catch (Exception e) {
            LOG.error("Failed to update database lock: " + e, e);
        } finally {
            if (lockUpdateStatement != null) {
                try {
                    lockUpdateStatement.close();
                } catch (SQLException e) {
                    LOG.error("Failed to close statement",e);
                }
                lockUpdateStatement = null;
            }
        }
        return result;
    }
 
    public long getLockAcquireSleepInterval() {
        return lockAcquireSleepInterval;
    }

{'fraction_non_alphanumeric': 0.07470265936121877, 'fraction_numerical': 0.002806361085126286, 'mean_word_length': 1.5536597850196212, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 1, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 20, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2147974', 'n_tokens_mistral': 3446, 'n_tokens_neox': 3237, 'n_words': 1008}