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.fixed;
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.HashMap;
024    import java.util.Iterator;
025    import java.util.List;
026    import java.util.Map;
027    import java.util.Scanner;
028    
029    import org.apache.camel.Exchange;
030    import org.apache.camel.dataformat.bindy.BindyFixedLengthFactory;
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.IOHelper;
035    import org.apache.camel.util.ObjectHelper;
036    import org.apache.commons.logging.Log;
037    import org.apache.commons.logging.LogFactory;
038    
039    /**
040     * A <a href="http://camel.apache.org/data-format.html">data format</a> (
041     * {@link DataFormat}) using Bindy to marshal to and from Fixed Length
042     */
043    public class BindyFixedLengthDataFormat implements DataFormat {
044        private static final transient Log LOG = LogFactory.getLog(BindyFixedLengthDataFormat.class);
045    
046        private String[] packages;
047        private BindyFixedLengthFactory modelFactory;
048    
049        public BindyFixedLengthDataFormat() {
050        }
051    
052        public BindyFixedLengthDataFormat(String... packages) {
053            this.packages = packages;
054        }
055    
056        @SuppressWarnings("unchecked")
057        public void marshal(Exchange exchange, Object body, OutputStream outputStream) throws Exception {
058    
059            BindyFixedLengthFactory factory = getFactory(exchange.getContext().getPackageScanClassResolver());
060            ObjectHelper.notNull(factory, "not instantiated");
061    
062            // Get CRLF
063            byte[] bytesCRLF = Converter.getByteReturn(factory.getCarriageReturn());
064    
065            List<Map<String, Object>> models;
066    
067            // the body is not a prepared list so help a bit here and create one for us
068            if (exchange.getContext().getTypeConverter().convertTo(List.class, body) == null) {
069                models = new ArrayList<Map<String, Object>>();
070                Iterator it = ObjectHelper.createIterator(body);
071                while (it.hasNext()) {
072                    Object model = it.next();
073                    String name = model.getClass().getName();
074                    Map<String, Object> row = new HashMap<String, Object>();
075                    row.put(name, body);
076                    models.add(row);
077                }
078            } else {
079                // cast to the expected type
080                models = (List<Map<String, Object>>) body;
081            }
082    
083            for (Map<String, Object> model : models) {
084    
085                String result = factory.unbind(model);
086    
087                byte[] bytes = exchange.getContext().getTypeConverter().convertTo(byte[].class, exchange, result);
088                outputStream.write(bytes);
089    
090                // Add a carriage return
091                outputStream.write(bytesCRLF);
092            }
093        }
094    
095        public Object unmarshal(Exchange exchange, InputStream inputStream) throws Exception {
096            BindyFixedLengthFactory factory = getFactory(exchange.getContext().getPackageScanClassResolver());
097            ObjectHelper.notNull(factory, "not instantiated");
098    
099            // List of Pojos
100            List<Map<String, Object>> models = new ArrayList<Map<String, Object>>();
101    
102            // Pojos of the model
103            Map<String, Object> model;
104    
105            InputStreamReader in = new InputStreamReader(inputStream);
106    
107            // Scanner is used to read big file
108            Scanner scanner = new Scanner(in);
109    
110            int count = 0;
111    
112            try {
113    
114                // TODO Test if we have a Header
115                // TODO Test if we have a Footer (containing by example checksum)
116    
117                while (scanner.hasNextLine()) {
118    
119                    // Read the line
120                    String line = scanner.nextLine().trim();
121    
122                    if (ObjectHelper.isEmpty(line)) {
123                        // skip if line is empty
124                        continue;
125                    }
126    
127                    // Increment counter
128                    count++;
129                    
130                    // Check if the record length corresponds to the parameter
131                    // provided in the @FixedLengthRecord
132                    if ((line.length() < factory.recordLength()) || (line.length() > factory.recordLength())) {
133                        throw new java.lang.IllegalArgumentException("Size of the record : " + line.length() + " is not equal to the value provided in the model : " + factory.recordLength() + " !");
134                    }
135    
136                    // Create POJO where Fixed data will be stored
137                    model = factory.factory();
138                    
139                    // Bind data from Fixed record with model classes
140                    factory.bind(line, model, count);
141    
142                    // Link objects together
143                    factory.link(model);
144    
145                    // Add objects graph to the list
146                    models.add(model);
147    
148                    if (LOG.isDebugEnabled()) {
149                        LOG.debug("Graph of objects created : " + model);
150                    }
151    
152                }
153    
154                // Test if models list is empty or not
155                // If this is the case (correspond to an empty stream, ...)
156                if (models.size() == 0) {
157                    throw new java.lang.IllegalArgumentException("No records have been defined in the message !");
158                } else {
159                    return models;
160                }
161    
162            } finally {
163                scanner.close();
164                IOHelper.close(in, "in", LOG);
165            }
166    
167        }
168    
169        /**
170         * Method used to create the singleton of the BindyCsvFactory
171         */
172        public BindyFixedLengthFactory getFactory(PackageScanClassResolver resolver) throws Exception {
173            if (modelFactory == null) {
174                modelFactory = new BindyFixedLengthFactory(resolver, packages);
175            }
176            return modelFactory;
177        }
178    
179        public void setModelFactory(BindyFixedLengthFactory modelFactory) {
180            this.modelFactory = modelFactory;
181        }
182    
183        public String[] getPackages() {
184            return packages;
185        }
186    
187        public void setPackages(String[] packages) {
188            this.packages = packages;
189        }
190    
191    }