Search in sources :

Example 76 with DataAccessException

use of org.springframework.dao.DataAccessException in project uPortal by Jasig.

the class DbTestImpl method printDbInfo.

@Override
public void printDbInfo() {
    boolean fail = false;
    logger.info("JDBC DataSources");
    for (final Entry<String, JdbcOperations> jdbcEntry : this.jdbcOperations.entrySet()) {
        final String jdbcName = jdbcEntry.getKey();
        try {
            logger.info("\t" + jdbcName);
            final JdbcOperations jdbcOps = jdbcEntry.getValue();
            jdbcOps.execute(new ConnectionCallback<Object>() {

                @Override
                public Object doInConnection(Connection con) throws SQLException, DataAccessException {
                    printInfo(con);
                    return null;
                }
            });
        } catch (Exception e) {
            logger.error("\t" + jdbcName + ": parse info", e);
            fail = true;
        }
        logger.info("");
    }
    logger.info("Hibernate Dialects");
    for (final Entry<String, HibernateConfiguration> configEntry : this.hibernateConfigurations.entrySet()) {
        final String persistenceUnit = configEntry.getKey();
        try {
            final HibernateConfiguration hibernateConfiguration = configEntry.getValue();
            final SessionFactoryImplementor sessionFactory = hibernateConfiguration.getSessionFactory();
            final Dialect dialect = sessionFactory.getDialect();
            logger.info("\t" + persistenceUnit + ": " + dialect);
        } catch (Exception e) {
            logger.error("\t" + persistenceUnit + ": Failed to resolve Dialect", e);
            fail = true;
        }
        logger.info("");
    }
    if (fail) {
        throw new RuntimeException("One or more of the portal data sources is not configured correctly or the target database is not available.");
    }
}
Also used : SQLException(java.sql.SQLException) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) Connection(java.sql.Connection) JdbcOperations(org.springframework.jdbc.core.JdbcOperations) DataAccessException(org.springframework.dao.DataAccessException) SQLException(java.sql.SQLException) Dialect(org.hibernate.dialect.Dialect) HibernateConfiguration(org.apereo.portal.hibernate.DelegatingHibernateIntegrator.HibernateConfiguration) DataAccessException(org.springframework.dao.DataAccessException)

Example 77 with DataAccessException

use of org.springframework.dao.DataAccessException in project opennms by OpenNMS.

the class DefaultRrdGraphService method getInputStreamForCommand.

private InputStream getInputStreamForCommand(String command) {
    boolean debug = true;
    InputStream tempIn = null;
    try {
        LOG.debug("Executing RRD command: {}", command);
        tempIn = m_rrdDao.createGraph(command);
    } catch (final DataAccessException e) {
        LOG.warn("Exception while creating graph.", e);
        if (debug) {
            throw e;
        } else {
            return returnErrorImage(s_rrdError);
        }
    }
    return tempIn;
}
Also used : InputStream(java.io.InputStream) DataAccessException(org.springframework.dao.DataAccessException)

Example 78 with DataAccessException

use of org.springframework.dao.DataAccessException in project opennms by OpenNMS.

the class UdpUuidSender method run.

/**
     * <p>run</p>
     */
@Override
public void run() {
    // get the context
    m_context = Thread.currentThread();
    Logging.putPrefix(m_logPrefix);
    if (m_stop) {
        LOG.debug("Stop flag set before thread started, exiting");
        return;
    } else {
        LOG.debug("Thread context started");
    }
    /*
         * This loop is labeled so that it can be
         * exited quickly when the thread is interrupted.
         */
    List<UdpReceivedEvent> eventHold = new ArrayList<UdpReceivedEvent>(30);
    Map<UdpReceivedEvent, EventReceipt> receipts = new HashMap<UdpReceivedEvent, EventReceipt>();
    RunLoop: while (!m_stop) {
        LOG.debug("Waiting on event receipts to be generated");
        synchronized (m_eventUuidsOut) {
            // wait for an event to show up.  wait in 1 second intervals
            while (m_eventUuidsOut.isEmpty()) {
                try {
                    // use wait instead of sleep to release the lock!
                    m_eventUuidsOut.wait(1000);
                } catch (InterruptedException ie) {
                    LOG.debug("Thread context interrupted");
                    break RunLoop;
                }
            }
            eventHold.addAll(m_eventUuidsOut);
            m_eventUuidsOut.clear();
        }
        LOG.debug("Received {} event receipts to process", eventHold.size());
        LOG.debug("Processing receipts");
        // build an event-receipt
        for (UdpReceivedEvent re : eventHold) {
            for (Event e : re.getAckedEvents()) {
                if (e.getUuid() != null) {
                    EventReceipt receipt = receipts.get(re);
                    if (receipt == null) {
                        receipt = new EventReceipt();
                        receipts.put(re, receipt);
                    }
                    receipt.addUuid(e.getUuid());
                }
            }
        }
        eventHold.clear();
        LOG.debug("Event receipts sorted, transmitting receipts");
        // turn them into XML and send it out the socket
        for (Map.Entry<UdpReceivedEvent, EventReceipt> entry : receipts.entrySet()) {
            UdpReceivedEvent re = entry.getKey();
            EventReceipt receipt = entry.getValue();
            StringWriter writer = new StringWriter();
            try {
                JaxbUtils.marshal(receipt, writer);
            } catch (DataAccessException e) {
                LOG.warn("Failed to build event receipt for agent {}:{}", InetAddressUtils.str(re.getSender()), re.getPort(), e);
            }
            String xml = writer.getBuffer().toString();
            try {
                byte[] xml_bytes = xml.getBytes(StandardCharsets.US_ASCII);
                DatagramPacket pkt = new DatagramPacket(xml_bytes, xml_bytes.length, re.getSender(), re.getPort());
                LOG.debug("Transmitting receipt to destination {}:{}", InetAddressUtils.str(re.getSender()), re.getPort());
                m_dgSock.send(pkt);
                synchronized (m_handlers) {
                    for (EventHandler handler : m_handlers) {
                        try {
                            handler.receiptSent(receipt);
                        } catch (Throwable t) {
                            LOG.warn("Error processing event receipt", t);
                        }
                    }
                }
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Receipt transmitted OK {");
                    LOG.debug(xml);
                    LOG.debug("}");
                }
            } catch (IOException e) {
                LOG.warn("Failed to send packet to host {}:{}", InetAddressUtils.str(re.getSender()), re.getPort(), e);
            }
        }
        receipts.clear();
    }
    LOG.debug("Context finished, returning");
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) EventHandler(org.opennms.netmgt.eventd.adaptors.EventHandler) IOException(java.io.IOException) EventReceipt(org.opennms.netmgt.xml.event.EventReceipt) StringWriter(java.io.StringWriter) DatagramPacket(java.net.DatagramPacket) Event(org.opennms.netmgt.xml.event.Event) DataAccessException(org.springframework.dao.DataAccessException)

Example 79 with DataAccessException

use of org.springframework.dao.DataAccessException in project cas by apereo.

the class QueryAndEncodeDatabaseAuthenticationHandler method authenticateUsernamePasswordInternal.

@Override
protected AuthenticationHandlerExecutionResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential transformedCredential, final String originalPassword) throws GeneralSecurityException, PreventedException {
    if (StringUtils.isBlank(this.sql) || StringUtils.isBlank(this.algorithmName) || getJdbcTemplate() == null) {
        throw new GeneralSecurityException("Authentication handler is not configured correctly");
    }
    final String username = transformedCredential.getUsername();
    try {
        final Map<String, Object> values = getJdbcTemplate().queryForMap(this.sql, username);
        final String digestedPassword = digestEncodedPassword(transformedCredential.getPassword(), values);
        if (!values.get(this.passwordFieldName).equals(digestedPassword)) {
            throw new FailedLoginException("Password does not match value on record.");
        }
        if (StringUtils.isNotBlank(this.expiredFieldName)) {
            final Object dbExpired = values.get(this.expiredFieldName);
            if (dbExpired != null && (Boolean.TRUE.equals(BooleanUtils.toBoolean(dbExpired.toString())) || dbExpired.equals(Integer.valueOf(1)))) {
                throw new AccountPasswordMustChangeException("Password has expired");
            }
        }
        if (StringUtils.isNotBlank(this.disabledFieldName)) {
            final Object dbDisabled = values.get(this.disabledFieldName);
            if (dbDisabled != null && (Boolean.TRUE.equals(BooleanUtils.toBoolean(dbDisabled.toString())) || dbDisabled.equals(1))) {
                throw new AccountDisabledException("Account has been disabled");
            }
        }
        return createHandlerResult(transformedCredential, this.principalFactory.createPrincipal(username), new ArrayList<>(0));
    } catch (final IncorrectResultSizeDataAccessException e) {
        if (e.getActualSize() == 0) {
            throw new AccountNotFoundException(username + " not found with SQL query");
        }
        throw new FailedLoginException("Multiple records found for " + username);
    } catch (final DataAccessException e) {
        throw new PreventedException("SQL exception while executing query for " + username, e);
    }
}
Also used : FailedLoginException(javax.security.auth.login.FailedLoginException) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException) GeneralSecurityException(java.security.GeneralSecurityException) PreventedException(org.apereo.cas.authentication.PreventedException) AccountPasswordMustChangeException(org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException) AccountDisabledException(org.apereo.cas.authentication.exceptions.AccountDisabledException) DataAccessException(org.springframework.dao.DataAccessException) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException)

Example 80 with DataAccessException

use of org.springframework.dao.DataAccessException in project cas by apereo.

the class SearchModeSearchDatabaseAuthenticationHandler method authenticateUsernamePasswordInternal.

@Override
protected AuthenticationHandlerExecutionResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential, final String originalPassword) throws GeneralSecurityException, PreventedException {
    String sql = null;
    if (StringUtils.isNotBlank(tableUsers) || StringUtils.isNotBlank(fieldUser) || StringUtils.isNotBlank(fieldPassword)) {
        sql = "SELECT COUNT('x') FROM ".concat(this.tableUsers).concat(" WHERE ").concat(this.fieldUser).concat(" = ? AND ").concat(this.fieldPassword).concat("= ?");
    }
    if (StringUtils.isBlank(sql) || getJdbcTemplate() == null) {
        throw new GeneralSecurityException("Authentication handler is not configured correctly. " + "No SQL statement or JDBC template found");
    }
    final String username = credential.getUsername();
    try {
        LOGGER.debug("Executing SQL query [{}]", sql);
        final int count = getJdbcTemplate().queryForObject(sql, Integer.class, username, credential.getPassword());
        if (count == 0) {
            throw new FailedLoginException(username + " not found with SQL query.");
        }
        return createHandlerResult(credential, this.principalFactory.createPrincipal(username), new ArrayList<>(0));
    } catch (final DataAccessException e) {
        throw new PreventedException("SQL exception while executing query for " + username, e);
    }
}
Also used : FailedLoginException(javax.security.auth.login.FailedLoginException) GeneralSecurityException(java.security.GeneralSecurityException) PreventedException(org.apereo.cas.authentication.PreventedException) DataAccessException(org.springframework.dao.DataAccessException)

Aggregations

DataAccessException (org.springframework.dao.DataAccessException)89 SQLException (java.sql.SQLException)40 Test (org.junit.Test)26 Connection (java.sql.Connection)17 ResultSet (java.sql.ResultSet)16 PreparedStatement (java.sql.PreparedStatement)14 MongoException (com.mongodb.MongoException)13 Document (org.bson.Document)8 TransactionStatus (org.springframework.transaction.TransactionStatus)7 HashMap (java.util.HashMap)6 DataIntegrityViolationException (org.springframework.dao.DataIntegrityViolationException)5 DeadlockLoserDataAccessException (org.springframework.dao.DeadlockLoserDataAccessException)5 IOException (java.io.IOException)4 ConnectionCallback (org.springframework.jdbc.core.ConnectionCallback)4 SpringSqlParams (com.opengamma.elsql.SpringSqlParams)3 DatabaseMetaData (java.sql.DatabaseMetaData)3 Statement (java.sql.Statement)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 IJoinQueryString (org.apereo.portal.jdbc.IJoinQueryString)3