Java Code Examples for org.springframework.dao.DataRetrievalFailureException

The following examples show how to use org.springframework.dao.DataRetrievalFailureException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Loads the {@link Owner} with the supplied <code>id</code>; also loads the
 * {@link Pet Pets} and {@link Visit Visits} for the corresponding owner, if not
 * already loaded.
 */
@Override
public Owner findById(int id) throws DataAccessException {
    Owner owner;
    try {
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        owner = this.namedParameterJdbcTemplate.queryForObject(
                "SELECT id, first_name, last_name, address, city, telephone FROM owners WHERE id= :id", params,
                BeanPropertyRowMapper.newInstance(Owner.class));
    } catch (EmptyResultDataAccessException ex) {
        throw new DataRetrievalFailureException("Cannot find Owner: " + id);
    }
    loadPetsAndVisits(owner);
    return owner;
}
 
Example 2
Source Project: lams   Source File: GeneratedKeyHolder.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public Number getKey() throws InvalidDataAccessApiUsageException, DataRetrievalFailureException {
	if (this.keyList.size() == 0) {
		return null;
	}
	if (this.keyList.size() > 1 || this.keyList.get(0).size() > 1) {
		throw new InvalidDataAccessApiUsageException(
				"The getKey method should only be used when a single key is returned.  " +
				"The current key entry contains multiple keys: " + this.keyList);
	}
	Iterator<Object> keyIter = this.keyList.get(0).values().iterator();
	if (keyIter.hasNext()) {
		Object key = keyIter.next();
		if (!(key instanceof Number)) {
			throw new DataRetrievalFailureException(
					"The generated key is not of a supported numeric type. " +
					"Unable to cast [" + (key != null ? key.getClass().getName() : null) +
					"] to [" + Number.class.getName() + "]");
		}
		return (Number) key;
	}
	else {
		throw new DataRetrievalFailureException("Unable to retrieve the generated key. " +
				"Check that the table has an identity column enabled.");
	}
}
 
Example 3
Source Project: spring4-understanding   Source File: GeneratedKeyHolder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Number getKey() throws InvalidDataAccessApiUsageException, DataRetrievalFailureException {
	if (this.keyList.size() == 0) {
		return null;
	}
	if (this.keyList.size() > 1 || this.keyList.get(0).size() > 1) {
		throw new InvalidDataAccessApiUsageException(
				"The getKey method should only be used when a single key is returned.  " +
				"The current key entry contains multiple keys: " + this.keyList);
	}
	Iterator<Object> keyIter = this.keyList.get(0).values().iterator();
	if (keyIter.hasNext()) {
		Object key = keyIter.next();
		if (!(key instanceof Number)) {
			throw new DataRetrievalFailureException(
					"The generated key is not of a supported numeric type. " +
					"Unable to cast [" + (key != null ? key.getClass().getName() : null) +
					"] to [" + Number.class.getName() + "]");
		}
		return (Number) key;
	}
	else {
		throw new DataRetrievalFailureException("Unable to retrieve the generated key. " +
				"Check that the table has an identity column enabled.");
	}
}
 
Example 4
Source Project: nestedj   Source File: JdbcKeyHolder.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> T getKeyValueAs(Class<T> keyClass) {
    if (this.getKeyList().isEmpty()) {
        return null;
    } else if (this.getKeyList().size() <= 1 && this.getKeyList().get(0).size() <= 1) {
        Iterator<Object> keyIter = ((Map)this.getKeyList().get(0)).values().iterator();
        if (keyIter.hasNext()) {
            Object key = keyIter.next();
            if (!(keyClass.isAssignableFrom(key.getClass()))) {
                throw new DataRetrievalFailureException("The generated key is not of a supported type. Unable to cast [" + key.getClass().getName() + "] to [" + keyClass.getName() + "]");
            } else {
                return keyClass.cast(key);
            }
        } else {
            throw new DataRetrievalFailureException("Unable to retrieve the generated key. Check that the table has an identity column enabled.");
        }
    } else {
        throw new InvalidDataAccessApiUsageException("The getKey method should only be used when a single key is returned.  The current key entry contains multiple keys: " + this.getKeyList());
    }
}
 
Example 5
Source Project: effectivejava   Source File: GeneratedKeyHolder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Number getKey() throws InvalidDataAccessApiUsageException, DataRetrievalFailureException {
	if (this.keyList.size() == 0) {
		return null;
	}
	if (this.keyList.size() > 1 || this.keyList.get(0).size() > 1) {
		throw new InvalidDataAccessApiUsageException(
				"The getKey method should only be used when a single key is returned.  " +
				"The current key entry contains multiple keys: " + this.keyList);
	}
	Iterator<Object> keyIter = this.keyList.get(0).values().iterator();
	if (keyIter.hasNext()) {
		Object key = keyIter.next();
		if (!(key instanceof Number)) {
			throw new DataRetrievalFailureException(
					"The generated key is not of a supported numeric type. " +
					"Unable to cast [" + (key != null ? key.getClass().getName() : null) +
					"] to [" + Number.class.getName() + "]");
		}
		return (Number) key;
	}
	else {
		throw new DataRetrievalFailureException("Unable to retrieve the generated key. " +
				"Check that the table has an identity column enabled.");
	}
}
 
Example 6
@Nullable
@Override
public DataAccessException translateExceptionIfPossible(RuntimeException exception) {

	Assert.notNull(exception, "Exception must not be null!");

	if (exception instanceof DataAccessException) {
		return (DataAccessException) exception;
	}

	if (exception instanceof NoSuchElementException || exception instanceof IndexOutOfBoundsException
			|| exception instanceof IllegalStateException) {
		return new DataRetrievalFailureException(exception.getMessage(), exception);
	}

	if (exception.getClass().getName().startsWith("java")) {
		return new UncategorizedKeyValueException(exception.getMessage(), exception);
	}

	return null;
}
 
Example 7
Source Project: gocd   Source File: StageSqlMapDao.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Stage stageById(long id) {
    String key = cacheKeyForStageById(id);
    Stage stage = (Stage) goCache.get(key);

    if (stage == null) {
        synchronized (key) {
            stage = (Stage) goCache.get(key);
            if (stage == null) {
                stage = (Stage) getSqlMapClientTemplate().queryForObject("getStageById", id);
                if (stage == null) {
                    throw new DataRetrievalFailureException("Unable to load related stage data for id " + id);
                }
                goCache.put(key, stage);
            }
        }
    }
    return cloner.deepClone(stage);
}
 
Example 8
Source Project: spring-analysis-note   Source File: MappingCommAreaOperation.java    License: MIT License 5 votes vote down vote up
@Override
protected final Record createInputRecord(RecordFactory recordFactory, Object inObject) {
	try {
		return new CommAreaRecord(objectToBytes(inObject));
	}
	catch (IOException ex) {
		throw new DataRetrievalFailureException("I/O exception during bytes conversion", ex);
	}
}
 
Example 9
Source Project: spring-analysis-note   Source File: MappingCommAreaOperation.java    License: MIT License 5 votes vote down vote up
@Override
protected final Object extractOutputData(Record record) throws DataAccessException {
	CommAreaRecord commAreaRecord = (CommAreaRecord) record;
	try {
		return bytesToObject(commAreaRecord.toByteArray());
	}
	catch (IOException ex) {
		throw new DataRetrievalFailureException("I/O exception during bytes conversion", ex);
	}
}
 
Example 10
Source Project: spring-analysis-note   Source File: CciLocalTransactionTests.java    License: MIT License 5 votes vote down vote up
/**
 * Test if a transaction ( begin / rollback ) is executed on the
 * LocalTransaction when CciLocalTransactionManager is specified as
 * transaction manager and a non-checked exception is thrown.
 */
@Test
public void testLocalTransactionRollback() throws ResourceException {
	final ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
	Connection connection = mock(Connection.class);
	Interaction interaction = mock(Interaction.class);
	LocalTransaction localTransaction = mock(LocalTransaction.class);
	final Record record = mock(Record.class);
	final InteractionSpec interactionSpec = mock(InteractionSpec.class);

	given(connectionFactory.getConnection()).willReturn(connection);
	given(connection.getLocalTransaction()).willReturn(localTransaction);
	given(connection.createInteraction()).willReturn(interaction);
	given(interaction.execute(interactionSpec, record, record)).willReturn(true);
	given(connection.getLocalTransaction()).willReturn(localTransaction);

	CciLocalTransactionManager tm = new CciLocalTransactionManager();
	tm.setConnectionFactory(connectionFactory);
	TransactionTemplate tt = new TransactionTemplate(tm);

	try {
		tt.execute(new TransactionCallback<Void>() {
			@Override
			public Void doInTransaction(TransactionStatus status) {
				assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(connectionFactory));
				CciTemplate ct = new CciTemplate(connectionFactory);
				ct.execute(interactionSpec, record, record);
				throw new DataRetrievalFailureException("error");
			}
		});
	}
	catch (Exception ex) {
	}

	verify(localTransaction).begin();
	verify(interaction).close();
	verify(localTransaction).rollback();
	verify(connection).close();
}
 
Example 11
Source Project: spring-analysis-note   Source File: GeneratedKeyHolder.java    License: MIT License 5 votes vote down vote up
@Override
@Nullable
public Number getKey() throws InvalidDataAccessApiUsageException, DataRetrievalFailureException {
	if (this.keyList.isEmpty()) {
		return null;
	}
	if (this.keyList.size() > 1 || this.keyList.get(0).size() > 1) {
		throw new InvalidDataAccessApiUsageException(
				"The getKey method should only be used when a single key is returned.  " +
				"The current key entry contains multiple keys: " + this.keyList);
	}
	Iterator<Object> keyIter = this.keyList.get(0).values().iterator();
	if (keyIter.hasNext()) {
		Object key = keyIter.next();
		if (!(key instanceof Number)) {
			throw new DataRetrievalFailureException(
					"The generated key is not of a supported numeric type. " +
					"Unable to cast [" + (key != null ? key.getClass().getName() : null) +
					"] to [" + Number.class.getName() + "]");
		}
		return (Number) key;
	}
	else {
		throw new DataRetrievalFailureException("Unable to retrieve the generated key. " +
				"Check that the table has an identity column enabled.");
	}
}
 
Example 12
Source Project: spring-analysis-note   Source File: KeyHolderTests.java    License: MIT License 5 votes vote down vote up
@Test
public void singleKeyNonNumeric() {
	kh.getKeyList().addAll(singletonList(singletonMap("key", "1")));

	assertThatExceptionOfType(DataRetrievalFailureException.class).isThrownBy(() ->
			kh.getKey().intValue())
		.withMessageStartingWith("The generated key is not of a supported numeric type.");
}
 
Example 13
Source Project: spring-analysis-note   Source File: KeyHolderTests.java    License: MIT License 5 votes vote down vote up
@Test
public void noKeyReturnedInMap() {
	kh.getKeyList().addAll(singletonList(emptyMap()));

	assertThatExceptionOfType(DataRetrievalFailureException.class).isThrownBy(() ->
			kh.getKey())
		.withMessageStartingWith("Unable to retrieve the generated key.");
}
 
Example 14
@Override
public Pet findById(int id) throws DataAccessException {
    Integer ownerId;
    try {
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        ownerId = this.namedParameterJdbcTemplate.queryForObject("SELECT owner_id FROM pets WHERE id=:id", params,
                Integer.class);
    } catch (EmptyResultDataAccessException ex) {
        throw new DataRetrievalFailureException("Cannot find Pet: " + id);
    }
    Owner owner = this.ownerRepository.findById(ownerId);
    return EntityUtils.getById(owner.getPets(), Pet.class, id);
}
 
Example 15
Source Project: java-technology-stack   Source File: MappingCommAreaOperation.java    License: MIT License 5 votes vote down vote up
@Override
protected final Record createInputRecord(RecordFactory recordFactory, Object inObject) {
	try {
		return new CommAreaRecord(objectToBytes(inObject));
	}
	catch (IOException ex) {
		throw new DataRetrievalFailureException("I/O exception during bytes conversion", ex);
	}
}
 
Example 16
Source Project: java-technology-stack   Source File: MappingCommAreaOperation.java    License: MIT License 5 votes vote down vote up
@Override
protected final Object extractOutputData(Record record) throws DataAccessException {
	CommAreaRecord commAreaRecord = (CommAreaRecord) record;
	try {
		return bytesToObject(commAreaRecord.toByteArray());
	}
	catch (IOException ex) {
		throw new DataRetrievalFailureException("I/O exception during bytes conversion", ex);
	}
}
 
Example 17
Source Project: java-technology-stack   Source File: CciLocalTransactionTests.java    License: MIT License 5 votes vote down vote up
/**
 * Test if a transaction ( begin / rollback ) is executed on the
 * LocalTransaction when CciLocalTransactionManager is specified as
 * transaction manager and a non-checked exception is thrown.
 */
@Test
public void testLocalTransactionRollback() throws ResourceException {
	final ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
	Connection connection = mock(Connection.class);
	Interaction interaction = mock(Interaction.class);
	LocalTransaction localTransaction = mock(LocalTransaction.class);
	final Record record = mock(Record.class);
	final InteractionSpec interactionSpec = mock(InteractionSpec.class);

	given(connectionFactory.getConnection()).willReturn(connection);
	given(connection.getLocalTransaction()).willReturn(localTransaction);
	given(connection.createInteraction()).willReturn(interaction);
	given(interaction.execute(interactionSpec, record, record)).willReturn(true);
	given(connection.getLocalTransaction()).willReturn(localTransaction);

	CciLocalTransactionManager tm = new CciLocalTransactionManager();
	tm.setConnectionFactory(connectionFactory);
	TransactionTemplate tt = new TransactionTemplate(tm);

	try {
		tt.execute(new TransactionCallback<Void>() {
			@Override
			public Void doInTransaction(TransactionStatus status) {
				assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(connectionFactory));
				CciTemplate ct = new CciTemplate(connectionFactory);
				ct.execute(interactionSpec, record, record);
				throw new DataRetrievalFailureException("error");
			}
		});
	}
	catch (Exception ex) {
	}

	verify(localTransaction).begin();
	verify(interaction).close();
	verify(localTransaction).rollback();
	verify(connection).close();
}
 
Example 18
Source Project: java-technology-stack   Source File: GeneratedKeyHolder.java    License: MIT License 5 votes vote down vote up
@Override
@Nullable
public Number getKey() throws InvalidDataAccessApiUsageException, DataRetrievalFailureException {
	if (this.keyList.isEmpty()) {
		return null;
	}
	if (this.keyList.size() > 1 || this.keyList.get(0).size() > 1) {
		throw new InvalidDataAccessApiUsageException(
				"The getKey method should only be used when a single key is returned.  " +
				"The current key entry contains multiple keys: " + this.keyList);
	}
	Iterator<Object> keyIter = this.keyList.get(0).values().iterator();
	if (keyIter.hasNext()) {
		Object key = keyIter.next();
		if (!(key instanceof Number)) {
			throw new DataRetrievalFailureException(
					"The generated key is not of a supported numeric type. " +
					"Unable to cast [" + (key != null ? key.getClass().getName() : null) +
					"] to [" + Number.class.getName() + "]");
		}
		return (Number) key;
	}
	else {
		throw new DataRetrievalFailureException("Unable to retrieve the generated key. " +
				"Check that the table has an identity column enabled.");
	}
}
 
Example 19
Source Project: java-technology-stack   Source File: KeyHolderTests.java    License: MIT License 5 votes vote down vote up
@Test
public void singleKeyNonNumeric() {
	kh.getKeyList().addAll(singletonList(singletonMap("key", "1")));

	exception.expect(DataRetrievalFailureException.class);
	exception.expectMessage(startsWith("The generated key is not of a supported numeric type."));
	kh.getKey().intValue();
}
 
Example 20
Source Project: java-technology-stack   Source File: KeyHolderTests.java    License: MIT License 5 votes vote down vote up
@Test
public void noKeyReturnedInMap() {
	kh.getKeyList().addAll(singletonList(emptyMap()));

	exception.expect(DataRetrievalFailureException.class);
	exception.expectMessage(startsWith("Unable to retrieve the generated key."));
	kh.getKey();
}
 
Example 21
Source Project: OpenCue   Source File: DependManagerService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void createDepend(PreviousFrame depend) {

    /*
     * Obtain the full layer record so we have access
     * to the frame range and other properties.
     */
    LayerDetail dependErLayer = layerDao.getLayerDetail(
            depend.getDependErLayer().getLayerId());

    LayerDetail dependOnLayer = layerDao.getLayerDetail(
            depend.getDependOnLayer().getLayerId());

    FrameSet dependErFrameSet = new FrameSet(dependErLayer.range);
    FrameSet dependOnFrameSet = new FrameSet(dependOnLayer.range);

    dependDao.insertDepend(depend);
    int dependErFrameSetSize = dependErFrameSet.size();
    for (int idx = 1; idx < dependErFrameSetSize; idx = idx + 1) {

        try {
            FrameInterface dependErFrame = frameDao.findFrame(dependErLayer,
                    dependErFrameSet.get(idx));

            FrameInterface dependOnFrame = frameDao.findFrame(dependOnLayer,
                    dependOnFrameSet.get(idx - 1));

            createDepend(new FrameOnFrame(dependErFrame,
                    dependOnFrame, depend));
        } catch (DataRetrievalFailureException dre) {
            logger.warn("failed to create frame by frame depend, " +
                    "part of a previous frame depend: " +
                    depend.getId() + " reason: " + dre);
        }
    }
}
 
Example 22
Source Project: jpetstore-kubernetes   Source File: SqlMapSequenceDao.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This is a generic sequence ID generator that is based on a database
 * table called 'SEQUENCE', which contains two columns (NAME, NEXTID).
 * This approach should work with any database.
 * @param name the name of the sequence
 * @return the next ID
 */
public int getNextId(String name) throws DataAccessException {
  Sequence sequence = new Sequence(name, -1);
  sequence = (Sequence) getSqlMapClientTemplate().queryForObject("getSequence", sequence);
  if (sequence == null) {
    throw new DataRetrievalFailureException(
			"Could not get next value of sequence '" + name + "': sequence does not exist");
  }
  Object parameterObject = new Sequence(name, sequence.getNextId() + 1);
  getSqlMapClientTemplate().update("updateSequence", parameterObject, 1);
  return sequence.getNextId();
}
 
Example 23
@Override
protected final Record createInputRecord(RecordFactory recordFactory, Object inObject) {
	try {
		return new CommAreaRecord(objectToBytes(inObject));
	}
	catch (IOException ex) {
		throw new DataRetrievalFailureException("I/O exception during bytes conversion", ex);
	}
}
 
Example 24
@Override
protected final Object extractOutputData(Record record) throws DataAccessException {
	CommAreaRecord commAreaRecord = (CommAreaRecord) record;
	try {
		return bytesToObject(commAreaRecord.toByteArray());
	}
	catch (IOException ex) {
		throw new DataRetrievalFailureException("I/O exception during bytes conversion", ex);
	}
}
 
Example 25
/**
 * Converts the given {@link String JSON} containing multiple objects into an array of {@link PdxInstance} objects.
 *
 * @param json {@link String JSON} data to convert.
 * @return an array of {@link PdxInstance} objects from the given {@link String JSON}.
 * @throws IllegalStateException if the {@link String JSON} does not start with
 * either a JSON array or a JSON object.
 * @see org.apache.geode.pdx.PdxInstance
 */
@Nullable @Override
public PdxInstance[] convert(String json) {

	try {
		JsonNode jsonNode = getObjectMapper().readTree(json);

		List<PdxInstance> pdxList = new ArrayList<>();

		if (isArray(jsonNode)) {

			ArrayNode arrayNode = (ArrayNode) jsonNode;

			JsonToPdxConverter converter = getJsonToPdxConverter();

			for (JsonNode object : asIterable(CollectionUtils.nullSafeIterator(arrayNode.elements()))) {
				pdxList.add(converter.convert(object.toString()));
			}
		}
		else if (isObject(jsonNode)) {

			ObjectNode objectNode = (ObjectNode) jsonNode;

			pdxList.add(getJsonToPdxConverter().convert(objectNode.toString()));
		}
		else {

			String message = String.format("Unable to process JSON node of type [%s];"
				+ " expected either an [%s] or an [%s]", jsonNode.getNodeType(),
					JsonNodeType.OBJECT, JsonNodeType.ARRAY);

			throw new IllegalStateException(message);
		}

		return pdxList.toArray(new PdxInstance[0]);
	}
	catch (JsonProcessingException cause) {
		throw new DataRetrievalFailureException("Failed to read JSON content", cause);
	}
}
 
Example 26
/**
 * Decorates the given {@link String JSON} to include the {@literal @type} metadata property in order to
 * indicate the type of the {@literal JSON} object, which is required for deserialization back to PDX.
 *
 * If an {@link JsonProcessingException} is thrown during this operation and if the {@link PdxInstance}
 * has a {@link #hasValidClassName(PdxInstance) valid class name}, then an attempt is made to serialize
 * the {@link PdxInstance#getObject() object instance} of the {@link PdxInstance} to {@link String JSON}
 * using Jackson's {@link ObjectMapper}.
 *
 * @param pdxInstance required {@link PdxInstance} from which the {@link String JSON} was serialized;
 * must not be {@literal null}.
 * @param json {@link String JSON} generated from the serialization of the {@link PdxInstance};
 * must not be {@literal null}.
 * @return the decorated {@link String JSON} including the {@literal @type} metadata property.
 * @throws DataRetrievalFailureException if {@link String JSON} cannot be decorated with type metadata
 * and the {@link PdxInstance} is not based on a valid {@link Class} type.
 * @see JacksonObjectToJsonConverter#convert(Object)
 * @see org.apache.geode.pdx.PdxInstance
 * @see #newObjectMapper(Object)
 */
@SuppressWarnings("unused")
protected @NonNull String decorate(@NonNull PdxInstance pdxInstance, @NonNull String json) {

	if (isDecorationRequired(pdxInstance, json)) {
		try {

			ObjectMapper objectMapper = newObjectMapper(json);

			JsonNode jsonNode = objectMapper.readTree(json);

			if (isMissingObjectTypeMetadata(jsonNode)) {
				((ObjectNode) jsonNode).put(AT_TYPE_METADATA_PROPERTY_NAME, pdxInstance.getClassName());
				json = objectMapper.writeValueAsString(jsonNode);
			}

			return json;
		}
		catch (JsonProcessingException cause) {

			if (hasValidClassName(pdxInstance)) {
				return convertPojoToJson(pdxInstance.getObject());
			}

			String message = String.format("Failed to parse JSON [%s]", json);

			throw new DataRetrievalFailureException(message, cause);
		}
	}

	return json;
}
 
Example 27
@Override
protected final Record createInputRecord(RecordFactory recordFactory, Object inObject) {
	try {
		return new CommAreaRecord(objectToBytes(inObject));
	}
	catch (IOException ex) {
		throw new DataRetrievalFailureException("I/O exception during bytes conversion", ex);
	}
}
 
Example 28
@Override
protected final Object extractOutputData(Record record) throws DataAccessException {
	CommAreaRecord commAreaRecord = (CommAreaRecord) record;
	try {
		return bytesToObject(commAreaRecord.toByteArray());
	}
	catch (IOException ex) {
		throw new DataRetrievalFailureException("I/O exception during bytes conversion", ex);
	}
}
 
Example 29
/**
 * Test if a transaction ( begin / rollback ) is executed on the
 * LocalTransaction when CciLocalTransactionManager is specified as
 * transaction manager and a non-checked exception is thrown.
 */
@Test
public void testLocalTransactionRollback() throws ResourceException {
	final ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
	Connection connection = mock(Connection.class);
	Interaction interaction = mock(Interaction.class);
	LocalTransaction localTransaction = mock(LocalTransaction.class);
	final Record record = mock(Record.class);
	final InteractionSpec interactionSpec = mock(InteractionSpec.class);

	given(connectionFactory.getConnection()).willReturn(connection);
	given(connection.getLocalTransaction()).willReturn(localTransaction);
	given(connection.createInteraction()).willReturn(interaction);
	given(interaction.execute(interactionSpec, record, record)).willReturn(true);
	given(connection.getLocalTransaction()).willReturn(localTransaction);

	CciLocalTransactionManager tm = new CciLocalTransactionManager();
	tm.setConnectionFactory(connectionFactory);
	TransactionTemplate tt = new TransactionTemplate(tm);

	try {
		tt.execute(new TransactionCallback<Void>() {
			@Override
			public Void doInTransaction(TransactionStatus status) {
				assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(connectionFactory));
				CciTemplate ct = new CciTemplate(connectionFactory);
				ct.execute(interactionSpec, record, record);
				throw new DataRetrievalFailureException("error");
			}
		});
	}
	catch (Exception ex) {
	}

	verify(localTransaction).begin();
	verify(interaction).close();
	verify(localTransaction).rollback();
	verify(connection).close();
}
 
Example 30
Source Project: spring4-understanding   Source File: KeyHolderTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void singleKeyNonNumeric() {
	kh.getKeyList().addAll(singletonList(singletonMap("key", "1")));

	exception.expect(DataRetrievalFailureException.class);
	exception.expectMessage(startsWith("The generated key is not of a supported numeric type."));
	kh.getKey().intValue();
}