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                    String line;
119                    
120                    // Read the line (should not trim as its fixed length)
121                    line = scanner.nextLine();
122    
123                    if (ObjectHelper.isEmpty(line)) {
124                        // skip if line is empty
125                        continue;
126                    }
127    
128                    // Increment counter
129                    count++;
130                    
131                    // Check if the record length corresponds to the parameter
132                    // provided in the @FixedLengthRecord
133                    if ((line.length() < factory.recordLength()) || (line.length() > factory.recordLength())) {
134                        throw new java.lang.IllegalArgumentException("Size of the record : " + line.length() + " is not equal to the value provided in the model : " + factory.recordLength() + " !");
135                    }
136    
137                    // Create POJO where Fixed data will be stored
138                    model = factory.factory();
139                    
140                    // Bind data from Fixed record with model classes
141                    factory.bind(line, model, count);
142    
143                    // Link objects together
144                    factory.link(model);
145    
146                    // Add objects graph to the list
147                    models.add(model);
148    
149                    if (LOG.isDebugEnabled()) {
150                        LOG.debug("Graph of objects created : " + model);
151                    }
152    
153                }
154    
155                // Test if models list is empty or not
156                // If this is the case (correspond to an empty stream, ...)
157                if (models.size() == 0) {
158                    throw new java.lang.IllegalArgumentException("No records have been defined in the message !");
159                } else {
160                    return models;
161                }
162    
163            } finally {
164                scanner.close();
165                IOHelper.close(in, "in", LOG);
166            }
167    
168        }
169    
170        /**
171         * Method used to create the singleton of the BindyCsvFactory
172         */
173        public BindyFixedLengthFactory getFactory(PackageScanClassResolver resolver) throws Exception {
174            if (modelFactory == null) {
175                modelFactory = new BindyFixedLengthFactory(resolver, packages);
176            }
177            return modelFactory;
178        }
179    
180        public void setModelFactory(BindyFixedLengthFactory modelFactory) {
181            this.modelFactory = modelFactory;
182        }
183    
184        public String[] getPackages() {
185            return packages;
186        }
187    
188        public void setPackages(String[] packages) {
189            this.packages = packages;
190        }
191    
192    }