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.util.Iterator;
020    
021    import javax.persistence.EntityManager;
022    import javax.persistence.PersistenceException;
023    
024    import org.apache.camel.Exchange;
025    import org.apache.camel.Expression;
026    import org.apache.camel.impl.DefaultProducer;
027    import org.apache.camel.util.ObjectHelper;
028    import org.springframework.orm.jpa.JpaCallback;
029    
030    /**
031     * @version $Revision: 787911 $
032     */
033    public class JpaProducer extends DefaultProducer {
034        private final TransactionStrategy template;
035        private final JpaEndpoint endpoint;
036        private final Expression expression;
037    
038        public JpaProducer(JpaEndpoint endpoint, Expression expression) {
039            super(endpoint);
040            this.endpoint = endpoint;
041            this.expression = expression;
042            this.template = endpoint.createTransactionStrategy();
043        }
044    
045        public void process(Exchange exchange) {
046            exchange.getIn().setHeader(JpaConstants.JPA_TEMPLATE, endpoint.getTemplate());
047            final Object values = expression.evaluate(exchange, Object.class);
048            if (values != null) {
049                template.execute(new JpaCallback() {
050                    public Object doInJpa(EntityManager entityManager) throws PersistenceException {
051                        Iterator iter = ObjectHelper.createIterator(values);
052                        while (iter.hasNext()) {
053                            Object value = iter.next();
054                            entityManager.merge(value);
055                        }
056                        if (endpoint.isFlushOnSend()) {
057                            entityManager.flush();
058                        }
059                        return null;
060                    }
061                });
062            }
063            exchange.getIn().removeHeader(JpaConstants.JPA_TEMPLATE);
064        }
065    }