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.example.etl; 018 019 import java.util.List; 020 021 import org.apache.camel.Converter; 022 import org.apache.commons.logging.Log; 023 import org.apache.commons.logging.LogFactory; 024 025 import org.springframework.orm.jpa.JpaTemplate; 026 027 /** 028 * A Message Transformer of an XML document to a Customer entity bean 029 * 030 * @version $Revision: 1.1 $ 031 */ 032 // START SNIPPET: example 033 @Converter 034 public class CustomerTransformer { 035 private static final transient Log LOG = LogFactory.getLog(CustomerTransformer.class); 036 private JpaTemplate template; 037 038 public CustomerTransformer(JpaTemplate template) { 039 this.template = template; 040 } 041 042 /** 043 * A transformation method to convert a person document into a customer 044 * entity 045 */ 046 @Converter 047 public CustomerEntity toCustomer(PersonDocument doc) { 048 String user = doc.getUser(); 049 CustomerEntity customer = findCustomerByName(user); 050 051 // lets convert information from the document into the entity bean 052 053 customer.setFirstName(doc.getFirstName()); 054 customer.setSurname(doc.getLastName()); 055 customer.setCity(doc.getCity()); 056 057 LOG.debug("Created customer: " + customer); 058 return customer; 059 } 060 061 /** 062 * Finds a customer for the given username, or creates and inserts a new one 063 */ 064 protected CustomerEntity findCustomerByName(String user) { 065 List<CustomerEntity> list = template.find("select x from " + CustomerEntity.class.getName() + " x where x.userName = ?1", user); 066 if (list.isEmpty()) { 067 CustomerEntity answer = new CustomerEntity(); 068 answer.setUserName(user); 069 template.persist(answer); 070 return answer; 071 } else { 072 return list.get(0); 073 } 074 } 075 } 076 // END SNIPPET: example