1 | /* |
2 | * Copyright 2012-2013 the original author or authors. |
3 | * |
4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
5 | * you may not use this file except in compliance with the License. |
6 | * You may obtain a copy of the License at |
7 | * |
8 | * http://www.apache.org/licenses/LICENSE-2.0 |
9 | * |
10 | * Unless required by applicable law or agreed to in writing, software |
11 | * distributed under the License is distributed on an "AS IS" BASIS, |
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
13 | * See the License for the specific language governing permissions and |
14 | * limitations under the License. |
15 | */ |
16 | |
17 | package org.springframework.batch.item.amqp; |
18 | |
19 | import org.springframework.amqp.core.AmqpTemplate; |
20 | import org.springframework.amqp.core.Message; |
21 | import org.springframework.batch.item.ItemReader; |
22 | import org.springframework.util.Assert; |
23 | |
24 | /** |
25 | * <p> |
26 | * AMQP {@link ItemReader} implementation using an {@link AmqpTemplate} to |
27 | * receive and/or convert messages. |
28 | * </p> |
29 | * |
30 | * @author Chris Schaefer |
31 | */ |
32 | public class AmqpItemReader<T> implements ItemReader<T> { |
33 | private final AmqpTemplate amqpTemplate; |
34 | private Class<? extends T> itemType; |
35 | |
36 | public AmqpItemReader(final AmqpTemplate amqpTemplate) { |
37 | Assert.notNull(amqpTemplate, "AmpqTemplate must not be null"); |
38 | |
39 | this.amqpTemplate = amqpTemplate; |
40 | } |
41 | |
42 | @Override |
43 | @SuppressWarnings("unchecked") |
44 | public T read() { |
45 | if (itemType != null && itemType.isAssignableFrom(Message.class)) { |
46 | return (T) amqpTemplate.receive(); |
47 | } |
48 | |
49 | Object result = amqpTemplate.receiveAndConvert(); |
50 | |
51 | if (itemType != null && result != null) { |
52 | Assert.state(itemType.isAssignableFrom(result.getClass()), |
53 | "Received message payload of wrong type: expected [" + itemType + "]"); |
54 | } |
55 | |
56 | return (T) result; |
57 | } |
58 | |
59 | public void setItemType(Class<? extends T> itemType) { |
60 | Assert.notNull(itemType, "Item type cannot be null"); |
61 | this.itemType = itemType; |
62 | } |
63 | } |