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