Java 类org.springframework.dao.InvalidDataAccessResourceUsageException 实例源码

项目:eHMP    文件:DefaultRoutingDataStore.java   
@Override
public <T extends IPOMObject> T save(T entity) {
    for (Map.Entry<String, IDataStoreDAO> dataStoreEntry : dataStores.entrySet()) {
        String dataSource = dataStoreEntry.getKey();
        if (!environment.acceptsProfiles(dataSource)) continue;

        IDataStoreDAO dao = dataStoreEntry.getValue();
        if (dao == null) {
            throw new InvalidDataAccessResourceUsageException("No implementation of IDataStoreDAO registered under key '" + dataStoreEntry.getKey() + "'");
        } else {
            Timer.Context timer = metrics.timer(metrics.name("vpr.persist", ClassUtils.getShortNameAsProperty(entity.getClass()), dataSource)).time();
            Stopwatch stopwatch = new Stopwatch().start();
            dao.save(entity);
            LOGGER.debug("TIME ELAPSED saving " + entity.getUid() + " to " + dataStoreEntry.getKey() + " : " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
            timer.stop();
        }
    }
    return entity;
}
项目:eHMP    文件:DefaultRoutingDataStore.java   
@Override
public <T extends IPOMObject> void delete(T entity) {
    for (Map.Entry<String, IDataStoreDAO> dataStoreEntry : dataStores.entrySet()) {
        String dataSource = dataStoreEntry.getKey();
        if (!environment.acceptsProfiles(dataSource)) continue;

        IDataStoreDAO dao = dataStoreEntry.getValue();
        if (dao == null) {
            throw new InvalidDataAccessResourceUsageException("No implementation of IDataStoreDAO registered under key '" + dataStoreEntry.getKey() + "'");
        } else {
            Timer.Context timer = metrics.timer(metrics.name("vpr.delete", ClassUtils.getShortNameAsProperty(entity.getClass()), dataSource)).time();
            dao.delete(entity);
            timer.stop();
        }
    }
}
项目:daikon    文件:MultiTenancyMongoDbFactory.java   
@Override
public DB getDb() {
    // Multi tenancy database name selection
    final String databaseName;
    try {
        databaseName = tenantProvider.getDatabaseName();
    } catch (Exception e) {
        throw new InvalidDataAccessResourceUsageException("Unable to retrieve database name.", e);
    }
    Assert.hasText(databaseName, "Database name must not be empty.");
    LOGGER.debug("Using '{}' as Mongo database.", databaseName);

    // Get MongoDB database using tenant information
    MongoClient mongoClient = mongoClientProvider.get(tenantProvider);
    return MongoDbUtils.getDB(mongoClient, databaseName);
}
项目:graphium    文件:WayGraphVersionMetadataDaoImpl.java   
@Override
public void saveGraphVersion(IWayGraphVersionMetadata graphMetadata) {
    Object[] args = new Object[20];
    try {
        args[0] = convertToArray(getJdbcTemplate().getDataSource().getConnection(), graphMetadata.getAccessTypes());
    } catch (SQLException e) {
        throw new InvalidDataAccessResourceUsageException(e.getMessage(), e);
    }
    args[1] = graphMetadata.getConnectionsCount();
    args[2] = "SRID=4326;"+wktWriter.write(graphMetadata.getCoveredArea());
    args[3] = graphMetadata.getState().name();
    args[4] = graphMetadata.getCreationTimestamp();
    args[5] = graphMetadata.getCreator();
    args[6] = graphMetadata.getDescription();
    args[7] = graphMetadata.getGraphId();
    args[8] = graphMetadata.getGraphName();
    args[9] = graphMetadata.getOriginGraphName();
    args[10] = graphMetadata.getOriginUrl();
    args[11] = graphMetadata.getOriginVersion();
    args[12] = graphMetadata.getSegmentsCount();
    args[13] = graphMetadata.getSource().getId();
    args[14] = graphMetadata.getStorageTimestamp();
    if (graphMetadata.getTags() != null) {
        args[15] = graphMetadata.getTags();
    } else {
        args[15] = null;
    }
    args[16] = graphMetadata.getType();
    args[17] = graphMetadata.getValidFrom();
    args[18] = graphMetadata.getValidTo();
    args[19] = graphMetadata.getVersion();

    getJdbcTemplate().update("INSERT INTO " + schema + METADATA_TABLE_NAME + " (accesstypes, connections_count, covered_area," +
            "state, creation_timestamp, creator, description, graph_id, graphname, origin_graphname, origin_url, origin_version, " +
            "segments_count, source_id, storage_timestamp, tags, type, valid_from, valid_to, version) " +
            "VALUES (?,?,ST_GeomFromEWKT(?),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", args);
}
项目:graphium    文件:WayGraphVersionMetadataDaoImpl.java   
@Override
public void updateGraphVersion(IWayGraphVersionMetadata graphMetadata) {
    Object[] args = new Object[18];
    try {
        args[0] = convertToArray(getJdbcTemplate().getDataSource().getConnection(), graphMetadata.getAccessTypes());
    } catch (SQLException e) {
        throw new InvalidDataAccessResourceUsageException(e.getMessage(), e);
    }
    args[1] = graphMetadata.getConnectionsCount();
    args[2] = "SRID=4326;"+wktWriter.write(graphMetadata.getCoveredArea());
    args[3] = graphMetadata.getCreationTimestamp();
    args[4] = graphMetadata.getCreator();
    args[5] = graphMetadata.getDescription();
    args[6] = graphMetadata.getOriginGraphName();
    args[7] = graphMetadata.getOriginUrl();
    args[8] = graphMetadata.getOriginVersion();
    args[9] = graphMetadata.getSegmentsCount();
    args[10] = graphMetadata.getSource().getId();
    args[11] = graphMetadata.getStorageTimestamp();
    if (graphMetadata.getTags() != null) {
        args[12] = graphMetadata.getTags();
    } else {
        args[12] = null;
    }
    args[13] = graphMetadata.getType();
    args[14] = graphMetadata.getValidFrom();
    args[15] = graphMetadata.getValidTo();
    args[16] = graphMetadata.getGraphName();
    args[17] = graphMetadata.getVersion();

    getJdbcTemplate().update("UPDATE " + schema + METADATA_TABLE_NAME + " SET accesstypes=?, connections_count=?, covered_area=ST_GeomFromEWKT(?)," +
            "creation_timestamp=?, creator=?, description=?, origin_graphname=?, origin_url=?, origin_version=?, " +
            "segments_count=?, source_id=?, storage_timestamp=?, tags=?, type=?, valid_from=?, valid_to=? " +
            "WHERE graphname =? AND version=?", args);
}
项目:lams    文件:PreparedStatementCreatorFactory.java   
@Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
    PreparedStatement ps;
    if (generatedKeysColumnNames != null || returnGeneratedKeys) {
        try {
            if (generatedKeysColumnNames != null) {
                ps = con.prepareStatement(this.actualSql, generatedKeysColumnNames);
            }
            else {
                ps = con.prepareStatement(this.actualSql, PreparedStatement.RETURN_GENERATED_KEYS);
            }
        }
        catch (AbstractMethodError err) {
            throw new InvalidDataAccessResourceUsageException(
                    "Your JDBC driver is not compliant with JDBC 3.0 - " +
                    "it does not support retrieval of auto-generated keys", err);
        }
    }
    else if (resultSetType == ResultSet.TYPE_FORWARD_ONLY && !updatableResults) {
        ps = con.prepareStatement(this.actualSql);
    }
    else {
        ps = con.prepareStatement(this.actualSql, resultSetType,
            updatableResults ? ResultSet.CONCUR_UPDATABLE : ResultSet.CONCUR_READ_ONLY);
    }
    setValues(ps);
    return ps;
}
项目:gorm-redis    文件:RedisQuery.java   
private PersistentProperty getValidProperty(PropertyProjection projection) {
    final String propName = projection.getPropertyName();
    PersistentProperty prop = entityPersister.getPersistentEntity().getPropertyByName(propName);
    if (prop == null) {
        throw new InvalidDataAccessResourceUsageException("Cannot use ["+projection.getClass().getSimpleName()+"] projection on non-existent property: " + propName);
    }
    else if (!isIndexed(prop)) {
        throw new InvalidDataAccessResourceUsageException("Cannot use ["+projection.getClass().getSimpleName()+"] projection on non-indexed property: " + propName);
    }
    return prop;
}
项目:gorm-redis    文件:RedisQuery.java   
private PersistentProperty getAndValidateProperty(RedisEntityPersister entityPersister, String property) {
    final PersistentEntity entity = entityPersister.getPersistentEntity();
    PersistentProperty prop = entity.getPropertyByName(property);
    if (prop == null) {
        throw new InvalidDataAccessResourceUsageException("Cannot execute between query on property [" +
               property + "] of class [" + entity + "]. Property does not exist.");
    }
    return prop;
}
项目:gorm-redis    文件:RedisQuery.java   
private void assertIndexed(String property, PersistentProperty prop) {
    if (prop == null) {
        throw new InvalidDataAccessResourceUsageException("Cannot execute query. Entity [" +
               getEntity() + "] does not declare a property named [" + property + "]");
    }
    if (!isIndexed(prop)) {
        throw new InvalidDataAccessResourceUsageException("Cannot query class [" +
               getEntity() + "] on property [" + prop + "]. The property is not indexed!");
    }
}
项目:xap-openspaces    文件:AbstractEventListenerContainer.java   
/**
 * Initialize this container. If this container is not configured with "activeWhenPrimary" flag
 * set to <code>true</code> will call {@link #doStart()} (if it is set to <code>true</code>,
 * lifecycle of the container will be controlled by the current space mode).
 * {@link #doInitialize()} will be called for additional initialization after the possible
 * {@link #doStart()} call.
 *
 * @see #onApplicationEvent(org.springframework.context.ApplicationEvent)
 */
public void initialize() throws DataAccessException {
    initializeTransactionManager();
    initializeTemplate();
    initializeExceptionHandler();
    synchronized (this.lifecycleMonitor) {
        this.active = true;
        this.lifecycleMonitor.notifyAll();
    }

    doInitialize();

    if (!activeWhenPrimary) {
        doStart();
    }

    if (registerSpaceModeListener) {
        SpaceMode currentMode = SpaceMode.PRIMARY;
        if (!SpaceUtils.isRemoteProtocol(gigaSpace.getSpace())) {
            primaryBackupListener = new PrimaryBackupListener();
            try {
                IJSpace clusterMemberSpace = SpaceUtils.getClusterMemberSpace(gigaSpace.getSpace());
                ISpaceModeListener remoteListener = (ISpaceModeListener) clusterMemberSpace.getDirectProxy().getStubHandler()
                        .exportObject(primaryBackupListener);
                currentMode = ((IInternalRemoteJSpaceAdmin) clusterMemberSpace.getAdmin()).addSpaceModeListener(remoteListener);
            } catch (RemoteException e) {
                throw new InvalidDataAccessResourceUsageException("Failed to register space mode listener with space [" + gigaSpace.getSpace()
                        + "]", e);
            }
        }
        SpaceInitializationIndicator.setInitializer();
        try {
            onApplicationEvent(new BeforeSpaceModeChangeEvent(gigaSpace.getSpace(), currentMode));
            onApplicationEvent(new AfterSpaceModeChangeEvent(gigaSpace.getSpace(), currentMode));
        } finally {
            SpaceInitializationIndicator.unsetInitializer();
        }
    }
}
项目:mybatis-spring-1.2.2    文件:MyBatisBatchItemWriter.java   
/**
 * {@inheritDoc}
 */
public void write(final List<? extends T> items) {

  if (!items.isEmpty()) {

    if (logger.isDebugEnabled()) {
      logger.debug("Executing batch with " + items.size() + " items.");
    }

    for (T item : items) {
      sqlSessionTemplate.update(statementId, item);
    }

    List<BatchResult> results = sqlSessionTemplate.flushStatements();

    if (assertUpdates) {
      if (results.size() != 1) {
        throw new InvalidDataAccessResourceUsageException("Batch execution returned invalid results. " +
            "Expected 1 but number of BatchResult objects returned was " + results.size());
      }

      int[] updateCounts = results.get(0).getUpdateCounts();

      for (int i = 0; i < updateCounts.length; i++) {
        int value = updateCounts[i];
        if (value == 0) {
          throw new EmptyResultDataAccessException("Item " + i + " of " + updateCounts.length
              + " did not update any rows: [" + items.get(i) + "]", 1);
        }
      }
    }
  }
}
项目:dubbox-solr    文件:SolrJsonResponse.java   
@Override
public void setResponse(NamedList<Object> response) {

    super.setResponse(response);
    try {
        root = new ObjectMapper().readTree((String) getResponse().get("json"));
    } catch (Exception e) {
        throw new InvalidDataAccessResourceUsageException("Unable to parse json from response.", e);
    }
}
项目:dubbox-solr    文件:MappingJacksonResponseParser.java   
@Override
public NamedList<Object> processResponse(InputStream body, String encoding) {

    NamedList<Object> result = new NamedList<Object>();
    try {
        result.add("json", StreamUtils.copyToString(body, Charset.forName(encoding)));
    } catch (IOException e) {
        throw new InvalidDataAccessResourceUsageException("Unable to read json from stream.", e);
    }
    return result;
}
项目:daikon    文件:SimpleMongoClientProvider.java   
protected MongoClient createMongoClient(MongoClientURI uri) {
    try {
        return new MongoClient(uri);
    } catch (Exception e) {
        // 3.x client throws UnknownHostException, keep catch block for compatibility with 3.x version
        throw new InvalidDataAccessResourceUsageException("Unable to retrieve host information.", e);
    }
}
项目:daikon    文件:CachedMongoClientProvider.java   
@Override
public MongoClient get(TenantInformationProvider provider) {
    try {
        return cache.get(provider.getDatabaseURI());
    } catch (Exception e) {
        throw new InvalidDataAccessResourceUsageException("Unable to retrieve client.", e);
    }
}
项目:daikon    文件:MultiTenantMongoDbFactoryTest.java   
@Test(expected = InvalidDataAccessResourceUsageException.class)
public void shouldFailOnDatabaseNameProviderFailure() throws Exception {
    // Given
    final TestData tenant1 = new TestData();
    tenant1.setId("1");
    tenant1.setValue("tenant1");

    // When
    changeTenant("failure");
    mongoTemplate.insert(tenant1);
}
项目:spring-data-crate    文件:CratePersistentEntitySchemaManagerTest.java   
@Test
public void shouldNotStopSchemaExportOnError() throws Exception {

    initializeMappingContext(Person.class);

    when(crateOperations.execute(isA(CrateAction.class))).thenThrow(new NoSuchTableException("table does not exist", null)).
                                                             thenThrow(new InvalidDataAccessResourceUsageException("Error!!"));

    CratePersistentEntitySchemaManager manager = new CratePersistentEntitySchemaManager(crateOperations, CREATE);
    manager.setIgnoreFailures(true);
    manager.afterPropertiesSet();

    verify(crateOperations, times(2)).execute(any(CrateAction.class));
}
项目:class-guard    文件:PreparedStatementCreatorFactory.java   
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
    PreparedStatement ps;
    if (generatedKeysColumnNames != null || returnGeneratedKeys) {
        try {
            if (generatedKeysColumnNames != null) {
                ps = con.prepareStatement(this.actualSql, generatedKeysColumnNames);
            }
            else {
                ps = con.prepareStatement(this.actualSql, PreparedStatement.RETURN_GENERATED_KEYS);
            }
        }
        catch (AbstractMethodError err) {
            throw new InvalidDataAccessResourceUsageException(
                    "Your JDBC driver is not compliant with JDBC 3.0 - " +
                    "it does not support retrieval of auto-generated keys", err);
        }
    }
    else if (resultSetType == ResultSet.TYPE_FORWARD_ONLY && !updatableResults) {
        ps = con.prepareStatement(this.actualSql);
    }
    else {
        ps = con.prepareStatement(this.actualSql, resultSetType,
            updatableResults ? ResultSet.CONCUR_UPDATABLE : ResultSet.CONCUR_READ_ONLY);
    }
    setValues(ps);
    return ps;
}
项目:mybatis-spring    文件:MyBatisBatchItemWriter.java   
/**
 * {@inheritDoc}
 */
public void write(final List<? extends T> items) {

  if (!items.isEmpty()) {

    if (logger.isDebugEnabled()) {
      logger.debug("Executing batch with " + items.size() + " items.");
    }

    for (T item : items) {
      sqlSessionTemplate.update(statementId, item);
    }

    List<BatchResult> results = sqlSessionTemplate.flushStatements();

    if (assertUpdates) {
      if (results.size() != 1) {
        throw new InvalidDataAccessResourceUsageException("Batch execution returned invalid results. " +
            "Expected 1 but number of BatchResult objects returned was " + results.size());
      }

      int[] updateCounts = results.get(0).getUpdateCounts();

      for (int i = 0; i < updateCounts.length; i++) {
        int value = updateCounts[i];
        if (value == 0) {
          throw new EmptyResultDataAccessException("Item " + i + " of " + updateCounts.length
              + " did not update any rows: [" + items.get(i) + "]", 1);
        }
      }
    }
  }
}
项目:spring-data-solr    文件:SolrJsonResponse.java   
@Override
public void setResponse(NamedList<Object> response) {

    super.setResponse(response);
    try {
        root = new ObjectMapper().readTree((String) getResponse().get("json"));
    } catch (Exception e) {
        throw new InvalidDataAccessResourceUsageException("Unable to parse json from response.", e);
    }
}
项目:spring-data-solr    文件:MappingJacksonResponseParser.java   
@Override
public NamedList<Object> processResponse(InputStream body, String encoding) {

    NamedList<Object> result = new NamedList<Object>();
    try {
        result.add("json", StreamUtils.copyToString(body, Charset.forName(encoding)));
    } catch (IOException e) {
        throw new InvalidDataAccessResourceUsageException("Unable to read json from stream.", e);
    }
    return result;
}
项目:gorm-redis    文件:RedisQuery.java   
private List unsupportedProjection(String projectionType) {
    throw new InvalidDataAccessResourceUsageException("Cannot use ["+ projectionType +"] projection. ["+projectionType+"] projections are not currently supported.");
}
项目:eHMP    文件:VistaVprDataExtractEventStreamDAO.java   
/**
 * This method will retrieve the patient status information..   It first checks to see if the status is already
 * in the status map that we are tracking.  If it is, then it uses that one.  If it is not, then it checks to
 * see if it is in the database.  If it is not, then it creates one.
 *
 * @param statMap The SyncStatus objects we are tracking as part of this set of data chunks we are processing.
 * @param pid The patient ID.
 * @param pt The patient demographics.
 * @param vistaId The vista site hash code.
 * @return The SyncStatus for this patient.
 */
private SyncStatus getPtSyncStatus(Map<String, SyncStatus> statMap, String pid, PatientDemographics pt, String vistaId, String patientUid) {
    SyncStatus syncStat = null;

    // First check to see if we have all the data that we are expecting.
    //-------------------------------------------------------------------
    if ((statMap == null) || (NullChecker.isNullish(pid)) || (pt == null)) {
        throw new InvalidDataAccessResourceUsageException("Unable to locate sync status - the pid, pt, or statMap was not available.");
    }

    syncStat = statMap.get(pid);
    if (syncStat == null) {
        // Not in the map, so lets get it from the database.
        //--------------------------------------------------
        LOG.debug("getPtSyncStatus: statMap did NOT contain the syncStatus for pid: " + pid);
        syncStat = syncStatusDao.findOneByPid(pt.getPid());
    }
    else {
        LOG.debug("getPtSyncStatus: statMap contained the syncStatus for pid: " + pid);
    }

    // Not in the map or the database - create it.
    //---------------------------------------------
    if (syncStat == null) {
        LOG.debug("getPtSyncStatus: sync status was not in the map or the database for pid: " + pid + ".  Creating it now from scratch.");
        syncStat = createSyncStatus(PidUtils.getVistaId(pt.getPid()), pt);
    }

    // Now lets verify that there is an entry for the facility that we are processing.
    //---------------------------------------------------------------------------------
    VistaAccountSyncStatus siteSyncStatus = syncStat.getVistaAccountSyncStatusForSystemId(vistaId);
    if (siteSyncStatus == null) {
        String localPatientUid = "";
        if (NullChecker.isNotNullish(patientUid)){
            LOG.debug("Using patientUid");
            localPatientUid = patientUid;
        }
        else{
            localPatientUid = pt.getUid();
            LOG.debug("Using pt.getUid()");
        }

        syncStat.addSite(localPatientUid, PidUtils.getDfn(pid), vistaId);

        LOG.debug("getPtSyncStatus: SyncStatus did NOT contain an entry for vistaId: " + vistaId + " for pid: " + pid + ".  Adding a new one now.");
    }
    else {
        LOG.debug("getPtSyncStatus: SyncStatus contained an entry for vistaId: " + vistaId + " for pid: " + pid);
        if (!isVistaSite(vistaId) && syncStat.needsSync(vistaId)) {
            syncStat.setSyncComplete(vistaId, false);
        }
    }

    return syncStat;
}
项目:spring-data-crate    文件:CrateExceptionTranslator.java   
@Override
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {

    if(ex instanceof NoNodeAvailableException) {
        return new DataAccessResourceFailureException(ex.getMessage(), ex);
    }

    if(ex instanceof SQLActionException) {

        int errorCode = ((SQLActionException)ex).errorCode();

        switch (errorCode) {
        case DUPLICATE_PRIMARY_KEY:
            return new DuplicateKeyException(ex.getMessage(), ex);
        case VERSION_CONFLICT:
            return new OptimisticLockingFailureException(ex.getMessage(), ex);
        case FIELD_VALIDATION_FAILED:
            return new DataIntegrityViolationException(ex.getMessage(), ex);
        case DUPLICATE_TABLE_NAME:
            return new DuplicateTableException(ex.getMessage(), ex);
        case UNKNOWN_TABLE:
            return new NoSuchTableException(ex.getMessage(), ex);
        case INVALID_SQL_STATEMENT_OR_SYNTAX:
        case INVALID_TABLE_NAME:
        case UNKNOWN_ANALYZER:
        case UNKNOWN_COLUMN:
        case UNKNOWN_TYPE:
        case UNKNOWN_SCHEMA:
        case UNKNOWN_PARTITION:
        case COLUMN_ALIAS_AMBIGUOUS:
        case FEATURE_NOT_SUPPORTED_YET:
        case INVALID_ANALYZER_DEFINITION:
        case ALTER_TABLE_ALIAS_NOT_SUPPORTED:
        case TABLE_ALIAS_CONTAINS_TABLES_WITH_DIFFERENT_SCHEMA:
            return new InvalidDataAccessResourceUsageException(ex.getMessage(), ex);
        case UNHANDLED_SERVER_ERROR:
        case TASKS_EXECUTION_FAILED:
        case SHARDS_NOT_AVAILABLE:
        case QUERY_FAILED_ON_SHARDS:
            return new DataAccessResourceFailureException(ex.getMessage(), ex);
        default:
            return new UncategorizedCrateException(ex.getMessage(), ex);
        }
    }

    return null;
}
项目:spring-data-crate    文件:CratePersistentEntitySchemaManagerTest.java   
@Test(expected=DataAccessException.class)
public void shouldNotAlterTableOnError() throws Exception {

    initializeMappingContext(Person.class);

    List<ColumnMetadata> columns = asList(createColumnMetadata("['name']", STRING),
                                          createColumnMetadata("['age']", INTEGER));

    TableMetadata metadata = new TableMetadata("person", columns, DEFAULT_PARAMS);

    when(crateOperations.execute(isA(ColumnMetadataAction.class),
                                 isA(ColumnMetadataAction.class))).thenReturn(columns);

    when(crateOperations.execute(isA(TableMetadataAction.class),
                                 isA(TableMetadataAction.class))).thenReturn(metadata);

    when(crateOperations.execute(isA(CrateAction.class))).thenThrow(new InvalidDataAccessResourceUsageException("Error!!"));

    CratePersistentEntitySchemaManager manager = new CratePersistentEntitySchemaManager(crateOperations, UPDATE);
    manager.afterPropertiesSet();
}