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