Search in sources :

Example 26 with DataAccessResourceFailureException

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

the class DefaultRrdDao method getPrintValues.

/**
 * <p>getPrintValues</p>
 *
 * @param attribute a {@link org.opennms.netmgt.model.OnmsAttribute} object.
 * @param rraConsolidationFunction a {@link java.lang.String} object.
 * @param startTimeInMillis a long.
 * @param endTimeInMillis a long.
 * @param printFunctions a {@link java.lang.String} object.
 * @return an array of double.
 */
@Override
public double[] getPrintValues(OnmsAttribute attribute, String rraConsolidationFunction, long startTimeInMillis, long endTimeInMillis, String... printFunctions) {
    Assert.notNull(attribute, "attribute argument must not be null");
    Assert.notNull(rraConsolidationFunction, "rraConsolicationFunction argument must not be null");
    Assert.isTrue(endTimeInMillis > startTimeInMillis, "end argument must be after start argument");
    Assert.isAssignable(attribute.getClass(), RrdGraphAttribute.class, "attribute argument must be assignable to RrdGraphAttribute");
    // if no printFunctions are given just use the rraConsolidationFunction
    if (printFunctions.length < 1) {
        printFunctions = new String[] { rraConsolidationFunction };
    }
    RrdGraphAttribute rrdAttribute = (RrdGraphAttribute) attribute;
    String[] command = new String[] { m_rrdBinaryPath, "graph", "-", "--start=" + (startTimeInMillis / 1000), "--end=" + (endTimeInMillis / 1000), "DEF:ds1=" + RrdFileConstants.escapeForGraphing(rrdAttribute.getRrdRelativePath()) + ":" + attribute.getName() + ":" + rraConsolidationFunction };
    String[] printDefs = new String[printFunctions.length];
    for (int i = 0; i < printFunctions.length; i++) {
        printDefs[i] = "PRINT:ds1:" + printFunctions[i] + ":\"%le\"";
    }
    String commandString = StringUtils.arrayToDelimitedString(command, " ") + ' ' + StringUtils.arrayToDelimitedString(printDefs, " ");
    LOG.debug("commandString: {}", commandString);
    RrdGraphDetails graphDetails;
    try {
        graphDetails = m_rrdStrategy.createGraphReturnDetails(commandString, m_rrdBaseDirectory);
    } catch (Throwable e) {
        throw new DataAccessResourceFailureException("Failure when generating graph to get data with command '" + commandString + "'", e);
    }
    String[] printLines;
    try {
        printLines = graphDetails.getPrintLines();
    } catch (Throwable e) {
        throw new DataAccessResourceFailureException("Failure to get print lines from graph after graphing with command '" + commandString + "'", e);
    }
    if (printLines.length != printFunctions.length) {
        throw new DataAccessResourceFailureException("Returned number of print lines should be " + printFunctions.length + ", but was " + printLines.length + " from command: " + commandString);
    }
    double[] values = new double[printLines.length];
    for (int i = 0; i < printLines.length; i++) {
        if (printLines[i].toLowerCase().endsWith("nan")) {
            values[i] = Double.NaN;
        } else {
            try {
                // To avoid NMS-5592 ~ 2,670374e+03 floating point issue.
                values[i] = Double.parseDouble(printLines[i].replace(",", "."));
            } catch (NumberFormatException e) {
                throw new DataAccessResourceFailureException("Value of line " + (i + 1) + " of output from RRD is not a valid floating point number: '" + printLines[i] + "'");
            }
        }
    }
    return values;
}
Also used : DataAccessResourceFailureException(org.springframework.dao.DataAccessResourceFailureException) RrdGraphAttribute(org.opennms.netmgt.model.RrdGraphAttribute) RrdGraphDetails(org.opennms.netmgt.rrd.RrdGraphDetails)

Example 27 with DataAccessResourceFailureException

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

the class ReportDefinition method createReport.

/**
 * <p>createReport</p>
 *
 * @param resourceDao a {@link org.opennms.netmgt.dao.api.ResourceDao} object.
 * @param fetchStrategy an object.
 * @param filterDao a {@link org.opennms.netmgt.filter.api.FilterDao} object.
 * @return a {@link org.opennms.netmgt.statsd.ReportInstance} object.
 * @throws java.lang.Exception if any.
 */
public ReportInstance createReport(NodeDao nodeDao, ResourceDao resourceDao, MeasurementFetchStrategy fetchStrategy, FilterDao filterDao) throws Exception {
    Assert.notNull(resourceDao, "resourceDao argument must not be null");
    Assert.notNull(fetchStrategy, "fetchStrategy argument must not be null");
    Assert.notNull(filterDao, "filterDao argument must not be null");
    AttributeStatisticVisitorWithResults visitor;
    try {
        visitor = getReportClass().newInstance();
    } catch (Throwable e) {
        throw new DataAccessResourceFailureException("Could not instantiate visitor object; nested exception: " + e, e);
    }
    ReportInstance report;
    if (getReport().getPackage().getFilter() != null) {
        FilteredReportInstance thisReport = new FilteredReportInstance(visitor);
        thisReport.setNodeDao(nodeDao);
        thisReport.setResourceDao(resourceDao);
        thisReport.setFetchStrategy(fetchStrategy);
        thisReport.setFilterDao(filterDao);
        thisReport.setFilter(getReport().getPackage().getFilter());
        report = thisReport;
    } else {
        UnfilteredReportInstance thisReport = new UnfilteredReportInstance(visitor);
        thisReport.setResourceDao(resourceDao);
        thisReport.setFetchStrategy(fetchStrategy);
        report = thisReport;
    }
    report.setReportDefinition(this);
    report.setStartTime(getRelativeTime().getStart().getTime());
    report.setEndTime(getRelativeTime().getEnd().getTime());
    report.setCount(getCount());
    report.setConsolidationFunction(getConsolidationFunction());
    report.setResourceTypeMatch(getResourceTypeMatch());
    report.setAttributeMatch(getAttributeMatch());
    report.setResourceAttributeKey(m_resourceAttributeKey);
    report.setResourceAttributeValueMatch(m_resourceAttributeValueMatch);
    if (report instanceof InitializingBean) {
        ((InitializingBean) report).afterPropertiesSet();
    }
    return report;
}
Also used : DataAccessResourceFailureException(org.springframework.dao.DataAccessResourceFailureException) AttributeStatisticVisitorWithResults(org.opennms.netmgt.model.AttributeStatisticVisitorWithResults) InitializingBean(org.springframework.beans.factory.InitializingBean)

Example 28 with DataAccessResourceFailureException

use of org.springframework.dao.DataAccessResourceFailureException in project spring-framework by spring-projects.

the class PersistenceExceptionTranslationPostProcessorTests method proxiesCorrectly.

@Test
@SuppressWarnings("resource")
public void proxiesCorrectly() {
    GenericApplicationContext gac = new GenericApplicationContext();
    gac.registerBeanDefinition("translator", new RootBeanDefinition(PersistenceExceptionTranslationPostProcessor.class));
    gac.registerBeanDefinition("notProxied", new RootBeanDefinition(RepositoryInterfaceImpl.class));
    gac.registerBeanDefinition("proxied", new RootBeanDefinition(StereotypedRepositoryInterfaceImpl.class));
    gac.registerBeanDefinition("classProxied", new RootBeanDefinition(RepositoryWithoutInterface.class));
    gac.registerBeanDefinition("classProxiedAndAdvised", new RootBeanDefinition(RepositoryWithoutInterfaceAndOtherwiseAdvised.class));
    gac.registerBeanDefinition("myTranslator", new RootBeanDefinition(MyPersistenceExceptionTranslator.class));
    gac.registerBeanDefinition("proxyCreator", BeanDefinitionBuilder.rootBeanDefinition(AnnotationAwareAspectJAutoProxyCreator.class).addPropertyValue("order", 50).getBeanDefinition());
    gac.registerBeanDefinition("logger", new RootBeanDefinition(LogAllAspect.class));
    gac.refresh();
    RepositoryInterface shouldNotBeProxied = (RepositoryInterface) gac.getBean("notProxied");
    assertFalse(AopUtils.isAopProxy(shouldNotBeProxied));
    RepositoryInterface shouldBeProxied = (RepositoryInterface) gac.getBean("proxied");
    assertTrue(AopUtils.isAopProxy(shouldBeProxied));
    RepositoryWithoutInterface rwi = (RepositoryWithoutInterface) gac.getBean("classProxied");
    assertTrue(AopUtils.isAopProxy(rwi));
    checkWillTranslateExceptions(rwi);
    Additional rwi2 = (Additional) gac.getBean("classProxiedAndAdvised");
    assertTrue(AopUtils.isAopProxy(rwi2));
    rwi2.additionalMethod(false);
    checkWillTranslateExceptions(rwi2);
    try {
        rwi2.additionalMethod(true);
        fail("Should have thrown DataAccessResourceFailureException");
    } catch (DataAccessResourceFailureException ex) {
        assertEquals("my failure", ex.getMessage());
    }
}
Also used : DataAccessResourceFailureException(org.springframework.dao.DataAccessResourceFailureException) GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) RepositoryInterfaceImpl(org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisorTests.RepositoryInterfaceImpl) StereotypedRepositoryInterfaceImpl(org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisorTests.StereotypedRepositoryInterfaceImpl) AnnotationAwareAspectJAutoProxyCreator(org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator) StereotypedRepositoryInterfaceImpl(org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisorTests.StereotypedRepositoryInterfaceImpl) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) RepositoryInterface(org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisorTests.RepositoryInterface) Test(org.junit.Test)

Example 29 with DataAccessResourceFailureException

use of org.springframework.dao.DataAccessResourceFailureException in project spring-framework by spring-projects.

the class AbstractSequenceMaxValueIncrementer method getNextKey.

/**
	 * Executes the SQL as specified by {@link #getSequenceQuery()}.
	 */
@Override
protected long getNextKey() throws DataAccessException {
    Connection con = DataSourceUtils.getConnection(getDataSource());
    Statement stmt = null;
    ResultSet rs = null;
    try {
        stmt = con.createStatement();
        DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
        rs = stmt.executeQuery(getSequenceQuery());
        if (rs.next()) {
            return rs.getLong(1);
        } else {
            throw new DataAccessResourceFailureException("Sequence query did not return a result");
        }
    } catch (SQLException ex) {
        throw new DataAccessResourceFailureException("Could not obtain sequence value", ex);
    } finally {
        JdbcUtils.closeResultSet(rs);
        JdbcUtils.closeStatement(stmt);
        DataSourceUtils.releaseConnection(con, getDataSource());
    }
}
Also used : DataAccessResourceFailureException(org.springframework.dao.DataAccessResourceFailureException) SQLException(java.sql.SQLException) Statement(java.sql.Statement) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet)

Example 30 with DataAccessResourceFailureException

use of org.springframework.dao.DataAccessResourceFailureException in project spring-framework by spring-projects.

the class HibernateTransactionManager method doGetTransaction.

@Override
protected Object doGetTransaction() {
    HibernateTransactionObject txObject = new HibernateTransactionObject();
    txObject.setSavepointAllowed(isNestedTransactionAllowed());
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());
    if (sessionHolder != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Found thread-bound Session [" + sessionHolder.getSession() + "] for Hibernate transaction");
        }
        txObject.setSessionHolder(sessionHolder);
    } else if (this.hibernateManagedSession) {
        try {
            Session session = this.sessionFactory.getCurrentSession();
            if (logger.isDebugEnabled()) {
                logger.debug("Found Hibernate-managed Session [" + session + "] for Spring-managed transaction");
            }
            txObject.setExistingSession(session);
        } catch (HibernateException ex) {
            throw new DataAccessResourceFailureException("Could not obtain Hibernate-managed Session for Spring-managed transaction", ex);
        }
    }
    if (getDataSource() != null) {
        ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(getDataSource());
        txObject.setConnectionHolder(conHolder);
    }
    return txObject;
}
Also used : HibernateException(org.hibernate.HibernateException) DataAccessResourceFailureException(org.springframework.dao.DataAccessResourceFailureException) Session(org.hibernate.Session) ConnectionHolder(org.springframework.jdbc.datasource.ConnectionHolder)

Aggregations

DataAccessResourceFailureException (org.springframework.dao.DataAccessResourceFailureException)36 SQLException (java.sql.SQLException)10 Connection (java.sql.Connection)6 IOException (java.io.IOException)5 HibernateException (org.hibernate.HibernateException)4 Session (org.hibernate.Session)4 File (java.io.File)3 ResultSet (java.sql.ResultSet)3 Statement (java.sql.Statement)3 Test (org.junit.Test)3 EventProxyException (org.opennms.netmgt.events.api.EventProxyException)3 EventBuilder (org.opennms.netmgt.model.events.EventBuilder)3 FileOutputStream (java.io.FileOutputStream)2 Clob (java.sql.Clob)2 DatabaseMetaData (java.sql.DatabaseMetaData)2 Date (java.util.Date)2 EntityManager (javax.persistence.EntityManager)2 PersistenceException (javax.persistence.PersistenceException)2 PrefabGraph (org.opennms.netmgt.model.PrefabGraph)2 DatabaseMetaDataCallback (org.springframework.jdbc.support.DatabaseMetaDataCallback)2