@Override public void setClobAsAsciiStream( PreparedStatement ps, int paramIndex, InputStream asciiStream, int contentLength) throws SQLException { Clob clob = ps.getConnection().createClob(); try { FileCopyUtils.copy(asciiStream, clob.setAsciiStream(1)); } catch (IOException ex) { throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex); } this.temporaryClobs.add(clob); ps.setClob(paramIndex, clob); if (logger.isDebugEnabled()) { logger.debug(asciiStream != null ? "Copied ASCII stream into temporary CLOB with length " + contentLength : "Set CLOB to null"); } }
@Override public void setClobAsCharacterStream( PreparedStatement ps, int paramIndex, Reader characterStream, int contentLength) throws SQLException { Clob clob = ps.getConnection().createClob(); try { FileCopyUtils.copy(characterStream, clob.setCharacterStream(1)); } catch (IOException ex) { throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex); } this.temporaryClobs.add(clob); ps.setClob(paramIndex, clob); if (logger.isDebugEnabled()) { logger.debug(characterStream != null ? "Copied character stream into temporary CLOB with length " + contentLength : "Set CLOB to null"); } }
@Override public void setBlobAsBinaryStream( PreparedStatement ps, int paramIndex, InputStream binaryStream, int contentLength) throws SQLException { Blob blob = ps.getConnection().createBlob(); try { FileCopyUtils.copy(binaryStream, blob.setBinaryStream(1)); } catch (IOException ex) { throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex); } this.temporaryBlobs.add(blob); ps.setBlob(paramIndex, blob); if (logger.isDebugEnabled()) { logger.debug(binaryStream != null ? "Copied binary stream into temporary BLOB with length " + contentLength : "Set BLOB to null"); } }
/** * 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()); } }
@Override protected DataAccessException doTranslate(String task, String sql, SQLException ex) { String sqlState = getSqlState(ex); if (sqlState != null && sqlState.length() >= 2) { String classCode = sqlState.substring(0, 2); if (logger.isDebugEnabled()) { logger.debug("Extracted SQL state class '" + classCode + "' from value '" + sqlState + "'"); } if (BAD_SQL_GRAMMAR_CODES.contains(classCode)) { return new BadSqlGrammarException(task, sql, ex); } else if (DATA_INTEGRITY_VIOLATION_CODES.contains(classCode)) { return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex); } else if (DATA_ACCESS_RESOURCE_FAILURE_CODES.contains(classCode)) { return new DataAccessResourceFailureException(buildMessage(task, sql, ex), ex); } else if (TRANSIENT_DATA_ACCESS_RESOURCE_CODES.contains(classCode)) { return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex); } else if (CONCURRENCY_FAILURE_CODES.contains(classCode)) { return new ConcurrencyFailureException(buildMessage(task, sql, ex), ex); } } return null; }
/** * Return a Session for use by this template. * <p>Returns a new Session in case of "alwaysUseNewSession" (using the same * JDBC Connection as a transactional Session, if applicable), a pre-bound * Session in case of "allowCreate" turned off, and a pre-bound or new Session * otherwise (new only if no transactional or otherwise pre-bound Session exists). * @return the Session to use (never {@code null}) * @see SessionFactoryUtils#getSession * @see SessionFactoryUtils#getNewSession * @see #setAlwaysUseNewSession * @see #setAllowCreate */ protected Session getSession() { if (isAlwaysUseNewSession()) { return SessionFactoryUtils.getNewSession(getSessionFactory(), getEntityInterceptor()); } else if (isAllowCreate()) { return SessionFactoryUtils.getSession( getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator()); } else if (SessionFactoryUtils.hasTransactionalSession(getSessionFactory())) { return SessionFactoryUtils.getSession(getSessionFactory(), false); } else { try { return getSessionFactory().getCurrentSession(); } catch (HibernateException ex) { throw new DataAccessResourceFailureException("Could not obtain current Hibernate Session", ex); } } }
public SpringSessionSynchronization( SessionHolder sessionHolder, SessionFactory sessionFactory, SQLExceptionTranslator jdbcExceptionTranslator, boolean newSession) { this.sessionHolder = sessionHolder; this.sessionFactory = sessionFactory; this.jdbcExceptionTranslator = jdbcExceptionTranslator; this.newSession = newSession; // Check whether the SessionFactory has a JTA TransactionManager. TransactionManager jtaTm = SessionFactoryUtils.getJtaTransactionManager(sessionFactory, sessionHolder.getAnySession()); if (jtaTm != null) { this.hibernateTransactionCompletion = true; // Fetch current JTA Transaction object // (just necessary for JTA transaction suspension, with an individual // Hibernate Session per currently active/suspended transaction). try { this.jtaTransaction = jtaTm.getTransaction(); } catch (SystemException ex) { throw new DataAccessResourceFailureException("Could not access JTA transaction", ex); } } }
@Test public void testExecuteWithNotAllowCreate() { reset(sessionFactory); given(sessionFactory.getCurrentSession()).willThrow(new HibernateException("")); HibernateTemplate ht = new HibernateTemplate(); ht.setSessionFactory(sessionFactory); ht.setAllowCreate(false); try { ht.execute(new HibernateCallback<Object>() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { return null; } }); fail("Should have thrown DataAccessException"); } catch (DataAccessResourceFailureException ex) { // expected } }
/** * This really does not work for most cases so be very careful with it * @param object */ protected void forceEvict(Serializable object) { boolean active = false; try { Session session = currentSession(); if (session.isOpen() && session.isConnected()) { if (session.contains(object)) { active = true; session.evict(object); } } else { LOG.warn("Session is not open OR not connected, cannot evict objects"); } if (!active) { LOG.info("Unable to evict object ("+object.getClass().getName()+") from session, it is not persistent: "+object); } } catch (DataAccessResourceFailureException | IllegalStateException | HibernateException e) { LOG.warn("Failure while attempting to evict object ("+object.getClass().getName()+") from session", e); } }
/** * Writes the EndDocument tag manually. * * @param writer * XML event writer * @throws XMLStreamException if there is a problem ending the document */ protected final void endDocument(final XMLEventWriter writer) throws XMLStreamException { // writer.writeEndDocument(); <- this doesn't work after restart // we need to write end tag of the root element manually String nsPrefix = null; if (!StringUtils.hasText(getRootTagNamespacePrefix())) { nsPrefix = ""; } else { nsPrefix = getRootTagNamespacePrefix() + ":"; } try { bufferedWriter.write("</" + nsPrefix + getRootTagName() + ">"); } catch (IOException ioe) { throw new DataAccessResourceFailureException( "Unable to close file resource: [" + resource + "]", ioe); } }
/** * Get the actual position in file channel. This method flushes any buffered * data before position is read. * * @return byte offset in file channel */ private long getPosition() { long position; try { eventWriter.flush(); position = channel.position(); if (bufferedWriter instanceof TransactionAwareBufferedWriter) { position += ((TransactionAwareBufferedWriter) bufferedWriter) .getBufferSize(); } } catch (Exception e) { throw new DataAccessResourceFailureException( "Unable to write to file resource: [" + resource + "]", e); } return position; }
private long getPosition() { long position; try { eventWriter.flush(); position = channel.position(); if (bufferedWriter instanceof TransactionAwareBufferedWriter) { position += ((TransactionAwareBufferedWriter) bufferedWriter) .getBufferSize(); } } catch (Exception e) { throw new DataAccessResourceFailureException( "Unable to write to file resource: [" + resource + "]", e); } return position; }
protected synchronized List<VistaAccount> getVistaAccounts() { InputStream is = null; try { Resource vistaAccountConfig = getVistaAccountConfig(); is = vistaAccountConfig.getInputStream(); JsonNode json = jsonMapper.readTree(is); JsonNode items = json.path("data").path("items"); List<VistaAccount> accounts = jsonMapper.convertValue(items, jsonMapper.getTypeFactory().constructCollectionType(List.class, VistaAccount.class)); // quick and dirty way to set VistaAccount.id to its index in the list. Might be a fancier way to do it with Jackson... for (int i = 0; i < accounts.size(); i++) { accounts.get(i).setId(i); accounts.get(i).decrypt(hmpEncryption); } return accounts; } catch (Exception e) { throw new DataAccessResourceFailureException("unable to load vista-account config", e); } finally { IOUtils.closeSilently(is); } }
public String getPrimaryVistaSystemId() { InputStream is = null; try { Resource vistaAccountConfig = getVistaAccountConfig(); is = vistaAccountConfig.getInputStream(); JsonNode json = jsonMapper.readTree(is); JsonNode items = json.path("data").path("items"); List<VistaAccount> accounts = jsonMapper.convertValue(items, jsonMapper.getTypeFactory().constructCollectionType(List.class, VistaAccount.class)); // quick and dirty way to set VistaAccount.id to its index in the list. Might be a fancier way to do it with Jackson... if(accounts.size()>0) { return accounts.get(0).getVistaId(); } } catch (Exception e) { throw new DataAccessResourceFailureException("unable to load vista-account config", e); } finally { IOUtils.closeSilently(is); } return ""; }
@Override public VistaAccount findByDivisionHostAndPort(String division, String host, int port) { List<VistaAccount> allAccounts = getVistaAccounts(); try { for (VistaAccount account : allAccounts) { if (division!=null && division.equalsIgnoreCase(account.getDivision()) && host!=null && host.equalsIgnoreCase(account.getHost()) && port == account.getPort()) { return account; } } } catch (Exception e) { throw new DataAccessResourceFailureException("unable to load vista-account config", e); } return null; }
protected <T> T getBean(Class<T> clazz, Node node) { try { T instance = clazz.newInstance(); Iterable<String> propertyKeys = node.getPropertyKeys(); for (String key : propertyKeys) { if (!key.equals(clazz.getName() + ID_SUFFIX)) { BeanUtils.setProperty(instance, key, node.getProperty(key)); } else { BeanProperty prop = ReflectionUtils.getAnnotatedProperty(instance, Id.class); BeanUtils.setProperty(instance, prop.getName(), node.getProperty(key)); } } return instance; } catch (Exception e) { throw new DataAccessResourceFailureException("Problem obtainig bean from node", e); } }
/** * Apply the current transaction timeout, if any, to the given * Guzz Query object. * @param query the Guzz Query object * @param transactionManager Guzz TransactionManager that the Query was created for * (may be <code>null</code>) * @see org.hibernate.Query#setTimeout */ public static void applyTransactionTimeout(PreparedStatement pstm, TransactionManager transactionManager) { Assert.notNull(pstm, "No PreparedStatement object specified"); if (transactionManager != null) { WriteTranSessionHolder writeTranSessionHolder = (WriteTranSessionHolder) TransactionSynchronizationManager.getResource(transactionManager); if (writeTranSessionHolder != null && writeTranSessionHolder.hasTimeout()) { try { pstm.setQueryTimeout(writeTranSessionHolder.getTimeToLiveInSeconds()); } catch (SQLException e) { throw new DataAccessResourceFailureException(e.getMessage(), e); } } } }
/** * Execute the given DatabasePopulator against the given DataSource. * @param populator the DatabasePopulator to execute * @param dataSource the DataSource to execute against */ public static void execute(DatabasePopulator populator, DataSource dataSource) { Assert.notNull(populator, "DatabasePopulator must be provided"); Assert.notNull(dataSource, "DataSource must be provided"); try { Connection connection = DataSourceUtils.getConnection(dataSource); try { populator.populate(connection); } finally { if (connection != null) { DataSourceUtils.releaseConnection(connection, dataSource); } } } catch (Exception ex) { throw new DataAccessResourceFailureException("Failed to execute database script", ex); } }
public void setBlobAsBinaryStream( PreparedStatement ps, int paramIndex, InputStream binaryStream, int contentLength) throws SQLException { Blob blob = ps.getConnection().createBlob(); try { FileCopyUtils.copy(binaryStream, blob.setBinaryStream(1)); } catch (IOException ex) { throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex); } this.temporaryBlobs.add(blob); ps.setBlob(paramIndex, blob); if (logger.isDebugEnabled()) { logger.debug(binaryStream != null ? "Copied binary stream into temporary BLOB with length " + contentLength : "Set BLOB to null"); } }
public void setClobAsAsciiStream( PreparedStatement ps, int paramIndex, InputStream asciiStream, int contentLength) throws SQLException { Clob clob = ps.getConnection().createClob(); try { FileCopyUtils.copy(asciiStream, clob.setAsciiStream(1)); } catch (IOException ex) { throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex); } this.temporaryClobs.add(clob); ps.setClob(paramIndex, clob); if (logger.isDebugEnabled()) { logger.debug(asciiStream != null ? "Copied ASCII stream into temporary CLOB with length " + contentLength : "Set CLOB to null"); } }
public void setClobAsCharacterStream( PreparedStatement ps, int paramIndex, Reader characterStream, int contentLength) throws SQLException { Clob clob = ps.getConnection().createClob(); try { FileCopyUtils.copy(characterStream, clob.setCharacterStream(1)); } catch (IOException ex) { throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex); } this.temporaryClobs.add(clob); ps.setClob(paramIndex, clob); if (logger.isDebugEnabled()) { logger.debug(characterStream != null ? "Copied character stream into temporary CLOB with length " + contentLength : "Set CLOB to null"); } }
public static RuntimeException doTranslate(final Exception ex) { if (ex instanceof JpoException) { throw (JpoException) ex; } if (ex instanceof BadSqlGrammarException) { return new JpoSqlBadGrammarException(ex); } else if (ex instanceof DataIntegrityViolationException) { return new JpoSqlDataIntegrityViolationException(ex); } else if (ex instanceof DataAccessResourceFailureException) { return new JpoSqlDataAccessResourceFailureException(ex); } else if (ex instanceof TransientDataAccessResourceException) { return new JpoSqlTransientDataAccessResourceException(ex); } else if (ex instanceof ConcurrencyFailureException) { return new JpoSqlConcurrencyFailureException(ex); } else if (ex instanceof TransactionTimedOutException) { return new JpoTransactionTimedOutException(ex); } return new JpoSqlException(ex); }
private String getReportProperty(Properties props, String key, String suffix, boolean required) { String propertyName; String graphName; if (key != null) { propertyName = "report." + key + "." + suffix; graphName = key; } else { propertyName = "report." + suffix; // It's lightly evil to know this from this method, but we can be // confident that report.id will exist graphName = props.getProperty("report.id"); } String property = props.getProperty(propertyName); if (property == null && required == true) { throw new DataAccessResourceFailureException("Properties for " + "report '" + graphName + "' must contain \'" + propertyName + "\' property"); } return property; }
private Integer getIntegerReportProperty(Properties props, String key, String suffix, boolean required) { String value = getReportProperty(props, key, suffix, required); if (value == null) { return null; } try { return new Integer(value); } catch (NumberFormatException e) { throw new DataAccessResourceFailureException( "Property value for '" + suffix + "' on report '" + key + "' must be an integer. '" + value + "' is not a valid value"); } }
/** {@inheritDoc} */ public Double getLastFetchValue(OnmsAttribute attribute, int interval, int range) throws DataAccessResourceFailureException { Assert.notNull(attribute, "attribute argument must not be null"); Assert.isTrue(interval > 0, "interval argument must be greater than zero"); Assert.isTrue(range > 0, "range argument must be greater than zero"); Assert.isAssignable(attribute.getClass(), RrdGraphAttribute.class, "attribute argument must be assignable to RrdGraphAttribute"); RrdGraphAttribute rrdAttribute = (RrdGraphAttribute) attribute; File rrdFile = new File(m_rrdBaseDirectory, rrdAttribute.getRrdRelativePath()); try { return m_rrdStrategy.fetchLastValueInRange(rrdFile.getAbsolutePath(), attribute.getName(), interval, range); } catch (Throwable e) { throw new DataAccessResourceFailureException("Failure to fetch last value from file '" + rrdFile + "' with interval " + interval + " and range " + range, e); } }
public void testPrintValueWithBogusLine() throws Exception { long end = System.currentTimeMillis(); long start = end - (24 * 60 * 60 * 1000); String printLine = "blah blah blah this should be a floating point number blah blah blah"; OnmsResource childResource = preparePrintValueTest(start, end, printLine); m_mocks.replayAll(); ThrowableAnticipator ta = new ThrowableAnticipator(); ta.anticipate(new DataAccessResourceFailureException("Value of line 1 of output from RRD is not a valid floating point number: '" + printLine + "'")); try { m_dao.getPrintValue(childResource.getAttributes().iterator().next(), "AVERAGE", start, end); } catch (Throwable t) { ta.throwableReceived(t); } m_mocks.verifyAll(); ta.verifyAnticipated(); }
public void importRequisition(final String foreignSource, final Boolean rescanExisting) { final URL activeUrl = createSnapshot(foreignSource); final String url = activeUrl.toString(); debug("importRequisition: Sending import event with URL %s", url); final EventBuilder bldr = new EventBuilder(EventConstants.RELOAD_IMPORT_UEI, "Web"); bldr.addParam(EventConstants.PARM_URL, url); if (rescanExisting != null) { bldr.addParam(EventConstants.PARM_IMPORT_RESCAN_EXISTING, rescanExisting); } try { getEventProxy().send(bldr.getEvent()); } catch (final EventProxyException e) { throw new DataAccessResourceFailureException("Unable to send event to import group " + foreignSource, e); } }
public final void executeWithRetries() { try { AmazonClientException serviceUnavailableException = null; serviceUnavailableException = tryExecute(); while ((serviceUnavailableException != null) && currentRetry < serviceUnavailableRetries) { try { Thread.sleep(RETRY_TIME); } catch (InterruptedException e) { LOGGER.debug(e.getLocalizedMessage()); } LOGGER.debug("Retrying operation"); currentRetry++; serviceUnavailableException = tryExecute(); } if (currentRetry == serviceUnavailableRetries) { throw new DataAccessResourceFailureException( "SimpleDB operation failed for " + currentRetry + " times", serviceUnavailableException); } } catch (AmazonClientException exception) { throw SimpleDbExceptionTranslator.getTranslatorInstance().translateAmazonClientException(exception); } }
@Test public void executeWithRetries_should_fail_for_exceeded_retries() throws Exception { AbstractServiceUnavailableOperationRetrier retrier = new AbstractServiceUnavailableOperationRetrier(SERVICE_UNAVAILABLE_RETRIES) { @Override public void execute() { AmazonServiceException serviceException = new AmazonServiceException("Test message"); serviceException.setStatusCode(SERVICE_UNAVAILABLE_STATUS_CODE); serviceException.setErrorType(AmazonServiceException.ErrorType.Service); throw serviceException; } }; try { retrier.executeWithRetries(); fail("Number of retries should be exceeded"); } catch(DataAccessResourceFailureException e) { // Our Exception -- ...times assertThat(e.getMessage(), StringContains.containsString("times")); } }