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.dataformat.bindy.kvp;
018    
019    import java.io.InputStream;
020    import java.io.InputStreamReader;
021    import java.io.OutputStream;
022    import java.util.ArrayList;
023    import java.util.Arrays;
024    import java.util.List;
025    import java.util.Map;
026    import java.util.Scanner;
027    
028    import org.apache.camel.Exchange;
029    import org.apache.camel.dataformat.bindy.BindyCsvFactory;
030    import org.apache.camel.dataformat.bindy.BindyKeyValuePairFactory;
031    import org.apache.camel.dataformat.bindy.util.Converter;
032    import org.apache.camel.spi.DataFormat;
033    import org.apache.camel.spi.PackageScanClassResolver;
034    import org.apache.camel.util.ObjectHelper;
035    import org.apache.commons.logging.Log;
036    import org.apache.commons.logging.LogFactory;
037    
038    /**
039     * A <a href="http://camel.apache.org/data-format.html">data format</a>
040     * ({@link DataFormat}) using Bindy to marshal to and from CSV files
041     */
042    public class BindyKeyValuePairDataFormat implements DataFormat {
043        
044        private static final transient Log LOG = LogFactory.getLog(BindyKeyValuePairDataFormat.class);
045        
046        private String packageName;
047        private BindyKeyValuePairFactory modelFactory;
048    
049        public BindyKeyValuePairDataFormat() {
050        }
051    
052        public BindyKeyValuePairDataFormat(String packageName) {
053            this.packageName = packageName;
054        }
055    
056        @SuppressWarnings("unchecked")
057        public void marshal(Exchange exchange, Object body, OutputStream outputStream) throws Exception {
058            BindyKeyValuePairFactory factory = getFactory(exchange.getContext().getPackageScanClassResolver());
059            List<Map<String, Object>> models = (ArrayList<Map<String, Object>>) body;
060            byte[] crlf;
061            
062            // Get CRLF
063            crlf = Converter.getByteReturn(factory.getCarriageReturn());
064            
065            for (Map<String, Object> model : models) {
066                String result = factory.unbind(model);
067                byte[] bytes = exchange.getContext().getTypeConverter().convertTo(byte[].class, exchange, result);
068                outputStream.write(bytes);
069                
070                // Add a carriage return
071                outputStream.write(crlf);
072            }
073        }
074    
075        public Object unmarshal(Exchange exchange, InputStream inputStream) throws Exception {
076            BindyKeyValuePairFactory factory = getFactory(exchange.getContext().getPackageScanClassResolver());
077    
078            // List of Pojos
079            List<Map<String, Object>> models = new ArrayList<Map<String, Object>>();
080    
081            // Pojos of the model
082            Map<String, Object> model;
083    
084            InputStreamReader in = new InputStreamReader(inputStream);
085    
086            // Scanner is used to read big file
087            Scanner scanner = new Scanner(in);
088    
089            // Retrieve the pair separator defined to split the record
090            ObjectHelper.notEmpty(factory.getPairSeparator(), "The separator has not been defined in the annotation @Message.");
091            String separator = factory.getPairSeparator();
092    
093            int count = 0;
094            try {
095    
096                while (scanner.hasNextLine()) {
097    
098                    // Read the line
099                    String line = scanner.nextLine().trim();
100    
101                    if (ObjectHelper.isEmpty(line)) {
102                        // skip if line is empty
103                        continue;
104                    }
105    
106                    if (LOG.isDebugEnabled()) {
107                        LOG.debug("Counter " + count++ + " : content : " + line);
108                    }
109                    
110                    // Create POJO where CSV data will be stored
111                    model = factory.factory();
112    
113                    // Split the message according to the pair separator defined in
114                    // annotated class @Message
115                    List<String> result = Arrays.asList(line.split(separator));
116                    
117                    // Bind data from message with model classes
118                    factory.bind(result, model);
119    
120                    // Link objects together
121                    factory.link(model);
122    
123                    // Add objects graph to the list
124                    models.add(model);
125    
126                    if (LOG.isDebugEnabled()) {
127                        LOG.debug("Graph of objects created : " + model);
128                    }
129    
130                }
131    
132                return models;
133    
134            } finally {
135                scanner.close();
136                ObjectHelper.close(in, "in", LOG);
137            }
138        }
139    
140        /**
141         * Method used to create the singleton of the BindyKeyValuePairFactory
142         */
143        public BindyKeyValuePairFactory getFactory(PackageScanClassResolver resolver) throws Exception {
144            if (modelFactory == null) {
145                modelFactory = new BindyKeyValuePairFactory(resolver, this.packageName);
146            }
147            return modelFactory;
148        }
149    
150        public void setModelFactory(BindyKeyValuePairFactory modelFactory) {
151            this.modelFactory = modelFactory;
152        }
153    
154        public String getPackageName() {
155            return packageName;
156        }
157    
158        public void setPackageName(String packageName) {
159            this.packageName = packageName;
160        }
161    
162    }