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                    // Increment counter
106                    count++;
107    
108                    // Create POJO
109                    model = factory.factory();
110    
111                    // Split the message according to the pair separator defined in
112                    // annotated class @Message
113                    List<String> result = Arrays.asList(line.split(separator));
114    
115                    if (result.size() == 0 || result.isEmpty()) {
116                        throw new java.lang.IllegalArgumentException("No records have been defined in the KVP !");
117                    }
118    
119                    if (result.size() > 0) {
120    
121                        // Bind data from message with model classes
122                        // Counter is used to detect line where error occurs
123                        factory.bind(result, model, count);
124    
125                        // Link objects together
126                        factory.link(model);
127    
128                        // Add objects graph to the list
129                        models.add(model);
130    
131                        if (LOG.isDebugEnabled()) {
132                            LOG.debug("Graph of objects created : " + model);
133                        }
134                    }
135    
136                }
137    
138                // Test if models list is empty or not
139                // If this is the case (correspond to an empty stream, ...)
140                if (models.size() == 0) {
141                    throw new java.lang.IllegalArgumentException("No records have been defined in the KVP !");
142                } else {
143                    return models;
144                }
145    
146            } finally {
147                scanner.close();
148                ObjectHelper.close(in, "in", LOG);
149            }
150        }
151    
152        /**
153         * Method used to create the singleton of the BindyKeyValuePairFactory
154         */
155        public BindyKeyValuePairFactory getFactory(PackageScanClassResolver resolver) throws Exception {
156            if (modelFactory == null) {
157                modelFactory = new BindyKeyValuePairFactory(resolver, this.packages);
158            }
159            return modelFactory;
160        }
161    
162        public void setModelFactory(BindyKeyValuePairFactory modelFactory) {
163            this.modelFactory = modelFactory;
164        }
165    
166        public String[] getPackages() {
167            return packages;
168        }
169    
170        public void setPackages(String... packages) {
171            this.packages = packages;
172        }
173    
174    }