001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.camel.component.jpa;
018
019 import java.lang.reflect.Method;
020 import java.util.LinkedList;
021 import java.util.List;
022 import java.util.Queue;
023
024 import javax.persistence.Entity;
025 import javax.persistence.EntityManager;
026 import javax.persistence.LockModeType;
027 import javax.persistence.PersistenceException;
028 import javax.persistence.Query;
029
030 import org.apache.camel.BatchConsumer;
031 import org.apache.camel.Exchange;
032 import org.apache.camel.Processor;
033 import org.apache.camel.ShutdownRunningTask;
034 import org.apache.camel.impl.ScheduledPollConsumer;
035 import org.apache.camel.spi.ShutdownAware;
036 import org.apache.camel.util.CastUtils;
037 import org.apache.camel.util.ObjectHelper;
038 import org.apache.commons.logging.Log;
039 import org.apache.commons.logging.LogFactory;
040 import org.springframework.orm.jpa.JpaCallback;
041
042 /**
043 * @version $Revision: 893983 $
044 */
045 public class JpaConsumer extends ScheduledPollConsumer implements BatchConsumer, ShutdownAware {
046
047 private static final transient Log LOG = LogFactory.getLog(JpaConsumer.class);
048 private final JpaEndpoint endpoint;
049 private final TransactionStrategy template;
050 private QueryFactory queryFactory;
051 private DeleteHandler<Object> deleteHandler;
052 private String query;
053 private String namedQuery;
054 private String nativeQuery;
055 private int maxMessagesPerPoll;
056 private volatile ShutdownRunningTask shutdownRunningTask;
057 private volatile int pendingExchanges;
058
059 private final class DataHolder {
060 private Exchange exchange;
061 private Object result;
062 private EntityManager manager;
063 private DataHolder() {
064 }
065 }
066
067 public JpaConsumer(JpaEndpoint endpoint, Processor processor) {
068 super(endpoint, processor);
069 this.endpoint = endpoint;
070 this.template = endpoint.createTransactionStrategy();
071 }
072
073 @Override
074 protected void poll() throws Exception {
075 // must reset for each poll
076 shutdownRunningTask = null;
077 pendingExchanges = 0;
078
079 template.execute(new JpaCallback() {
080 public Object doInJpa(EntityManager entityManager) throws PersistenceException {
081 Queue<DataHolder> answer = new LinkedList<DataHolder>();
082
083 Query query = getQueryFactory().createQuery(entityManager);
084 configureParameters(query);
085 List<Object> results = CastUtils.cast(query.getResultList());
086 for (Object result : results) {
087 DataHolder holder = new DataHolder();
088 holder.manager = entityManager;
089 holder.result = result;
090 holder.exchange = createExchange(result);
091 answer.add(holder);
092 }
093
094 try {
095 processBatch(CastUtils.cast(answer));
096 } catch (Exception e) {
097 throw new PersistenceException(e);
098 }
099
100 entityManager.flush();
101 return null;
102 }
103 });
104 }
105
106 public void setMaxMessagesPerPoll(int maxMessagesPerPoll) {
107 this.maxMessagesPerPoll = maxMessagesPerPoll;
108 }
109
110 public void processBatch(Queue<Object> exchanges) throws Exception {
111 if (exchanges.isEmpty()) {
112 return;
113 }
114
115 int total = exchanges.size();
116
117 // limit if needed
118 if (maxMessagesPerPoll > 0 && total > maxMessagesPerPoll) {
119 LOG.debug("Limiting to maximum messages to poll " + maxMessagesPerPoll + " as there was " + total + " messages in this poll.");
120 total = maxMessagesPerPoll;
121 }
122
123 for (int index = 0; index < total && isBatchAllowed(); index++) {
124 // only loop if we are started (allowed to run)
125 DataHolder holder = ObjectHelper.cast(DataHolder.class, exchanges.poll());
126 EntityManager entityManager = holder.manager;
127 Exchange exchange = holder.exchange;
128 Object result = holder.result;
129
130 // add current index and total as properties
131 exchange.setProperty(Exchange.BATCH_INDEX, index);
132 exchange.setProperty(Exchange.BATCH_SIZE, total);
133 exchange.setProperty(Exchange.BATCH_COMPLETE, index == total - 1);
134
135 // update pending number of exchanges
136 pendingExchanges = total - index - 1;
137
138 if (lockEntity(result, entityManager)) {
139
140 // process the current exchange
141 if (LOG.isDebugEnabled()) {
142 LOG.debug("Processing exchange: " + exchange);
143 }
144 try {
145 getProcessor().process(exchange);
146 } catch (Exception e) {
147 throw new PersistenceException(e);
148 }
149
150 getDeleteHandler().deleteObject(entityManager, result);
151 }
152 }
153 }
154
155 public boolean deferShutdown(ShutdownRunningTask shutdownRunningTask) {
156 // store a reference what to do in case when shutting down and we have pending messages
157 this.shutdownRunningTask = shutdownRunningTask;
158 // do not defer shutdown
159 return false;
160 }
161
162 public int getPendingExchangesSize() {
163 // only return the real pending size in case we are configured to complete all tasks
164 if (ShutdownRunningTask.CompleteAllTasks == shutdownRunningTask) {
165 return pendingExchanges;
166 } else {
167 return 0;
168 }
169 }
170
171 public boolean isBatchAllowed() {
172 // stop if we are not running
173 boolean answer = isRunAllowed();
174 if (!answer) {
175 return false;
176 }
177
178 if (shutdownRunningTask == null) {
179 // we are not shutting down so continue to run
180 return true;
181 }
182
183 // we are shutting down so only continue if we are configured to complete all tasks
184 return ShutdownRunningTask.CompleteAllTasks == shutdownRunningTask;
185 }
186
187 // Properties
188 // -------------------------------------------------------------------------
189 @Override
190 public JpaEndpoint getEndpoint() {
191 return endpoint;
192 }
193
194 public QueryFactory getQueryFactory() {
195 if (queryFactory == null) {
196 queryFactory = createQueryFactory();
197 if (queryFactory == null) {
198 throw new IllegalArgumentException("No queryType property configured on this consumer, nor an entityType configured on the endpoint so cannot consume");
199 }
200 }
201 return queryFactory;
202 }
203
204 public void setQueryFactory(QueryFactory queryFactory) {
205 this.queryFactory = queryFactory;
206 }
207
208 public DeleteHandler<Object> getDeleteHandler() {
209 if (deleteHandler == null) {
210 deleteHandler = createDeleteHandler();
211 }
212 return deleteHandler;
213 }
214
215 public void setDeleteHandler(DeleteHandler<Object> deleteHandler) {
216 this.deleteHandler = deleteHandler;
217 }
218
219 public String getNamedQuery() {
220 return namedQuery;
221 }
222
223 public void setNamedQuery(String namedQuery) {
224 this.namedQuery = namedQuery;
225 }
226
227 public String getNativeQuery() {
228 return nativeQuery;
229 }
230
231 public void setNativeQuery(String nativeQuery) {
232 this.nativeQuery = nativeQuery;
233 }
234
235 public String getQuery() {
236 return query;
237 }
238
239 public void setQuery(String query) {
240 this.query = query;
241 }
242
243 // Implementation methods
244 // -------------------------------------------------------------------------
245
246 /**
247 * A strategy method to lock an object with an exclusive lock so that it can
248 * be processed
249 *
250 * @param entity the entity to be locked
251 * @param entityManager entity manager
252 * @return true if the entity was locked
253 */
254 protected boolean lockEntity(Object entity, EntityManager entityManager) {
255 if (!getEndpoint().isConsumeDelete() || !getEndpoint().isConsumeLockEntity()) {
256 return true;
257 }
258 try {
259 if (LOG.isDebugEnabled()) {
260 LOG.debug("Acquiring exclusive lock on entity: " + entity);
261 }
262 entityManager.lock(entity, LockModeType.WRITE);
263 return true;
264 } catch (Exception e) {
265 if (LOG.isDebugEnabled()) {
266 LOG.debug("Failed to achieve lock on entity: " + entity + ". Reason: " + e, e);
267 }
268 return false;
269 }
270 }
271
272 protected QueryFactory createQueryFactory() {
273 if (query != null) {
274 return QueryBuilder.query(query);
275 } else if (namedQuery != null) {
276 return QueryBuilder.namedQuery(namedQuery);
277 } else if (nativeQuery != null) {
278 return QueryBuilder.nativeQuery(nativeQuery);
279 } else {
280 Class<?> entityType = endpoint.getEntityType();
281
282 if (entityType == null) {
283 return null;
284 } else {
285
286 // Check if we have a property name on the @Entity annotation
287 String name = getEntityName(entityType);
288
289 if (name != null) {
290 return QueryBuilder.query("select x from " + name + " x");
291 } else {
292 // Remove package name of the entity to be conform with JPA 1.0 spec
293 return QueryBuilder.query("select x from " + entityType.getSimpleName() + " x");
294 }
295
296
297
298 }
299 }
300 }
301
302 protected String getEntityName(Class<?> clazz) {
303
304 Entity entity = clazz.getAnnotation(Entity.class);
305
306 // Check if the property name has been defined for Entity annotation
307 if (!entity.name().equals("")) {
308 return entity.name();
309 } else {
310 return null;
311 }
312
313 }
314
315 protected DeleteHandler<Object> createDeleteHandler() {
316 // look for @Consumed to allow custom callback when the Entity has been consumed
317 Class<?> entityType = getEndpoint().getEntityType();
318 if (entityType != null) {
319 List<Method> methods = ObjectHelper.findMethodsWithAnnotation(entityType, Consumed.class);
320 if (methods.size() > 1) {
321 throw new IllegalArgumentException("Only one method can be annotated with the @Consumed annotation but found: " + methods);
322 } else if (methods.size() == 1) {
323 final Method method = methods.get(0);
324
325 return new DeleteHandler<Object>() {
326 public void deleteObject(EntityManager entityManager, Object entityBean) {
327 ObjectHelper.invokeMethod(method, entityBean);
328 }
329 };
330 }
331 }
332 if (getEndpoint().isConsumeDelete()) {
333 return new DeleteHandler<Object>() {
334 public void deleteObject(EntityManager entityManager, Object entityBean) {
335 entityManager.remove(entityBean);
336 }
337 };
338 } else {
339 return new DeleteHandler<Object>() {
340 public void deleteObject(EntityManager entityManager, Object entityBean) {
341 // do nothing
342 }
343 };
344 }
345 }
346
347 protected void configureParameters(Query query) {
348 int maxResults = endpoint.getMaximumResults();
349 if (maxResults > 0) {
350 query.setMaxResults(maxResults);
351 }
352 }
353
354 protected Exchange createExchange(Object result) {
355 Exchange exchange = endpoint.createExchange();
356 exchange.getIn().setBody(result);
357 exchange.getIn().setHeader(JpaConstants.JPA_TEMPLATE, endpoint.getTemplate());
358 return exchange;
359 }
360 }