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.Arrays;
024    import java.util.HashMap;
025    import java.util.Iterator;
026    import java.util.List;
027    import java.util.Map;
028    import java.util.Scanner;
029    
030    import org.apache.camel.Exchange;
031    import org.apache.camel.dataformat.bindy.BindyCsvFactory;
032    import org.apache.camel.dataformat.bindy.BindyFixedLengthFactory;
033    import org.apache.camel.dataformat.bindy.util.Converter;
034    import org.apache.camel.spi.DataFormat;
035    import org.apache.camel.spi.PackageScanClassResolver;
036    import org.apache.camel.util.ObjectHelper;
037    import org.apache.commons.logging.Log;
038    import org.apache.commons.logging.LogFactory;
039    
040    /**
041     * A <a href="http://camel.apache.org/data-format.html">data format</a> (
042     * {@link DataFormat}) using Bindy to marshal to and from Fixed Length
043     */
044    public class BindyFixedLengthDataFormat implements DataFormat {
045        private static final transient Log LOG = LogFactory.getLog(BindyFixedLengthDataFormat.class);
046    
047        private String[] packages;
048        private BindyFixedLengthFactory modelFactory;
049    
050        public BindyFixedLengthDataFormat() {
051        }
052    
053        public BindyFixedLengthDataFormat(String... packages) {
054            this.packages = packages;
055        }
056    
057        @SuppressWarnings("unchecked")
058        public void marshal(Exchange exchange, Object body, OutputStream outputStream) throws Exception {
059    
060            BindyFixedLengthFactory factory = getFactory(exchange.getContext().getPackageScanClassResolver());
061            ObjectHelper.notNull(factory, "not instantiated");
062    
063            // Get CRLF
064            byte[] bytesCRLF = Converter.getByteReturn(factory.getCarriageReturn());
065    
066            List<Map<String, Object>> models;
067    
068            // the body is not a prepared list so help a bit here and create one for us
069            if (exchange.getContext().getTypeConverter().convertTo(List.class, body) == null) {
070                models = new ArrayList<Map<String, Object>>();
071                Iterator it = ObjectHelper.createIterator(body);
072                while (it.hasNext()) {
073                    Object model = it.next();
074                    String name = model.getClass().getName();
075                    Map<String, Object> row = new HashMap<String, Object>();
076                    row.put(name, body);
077                    models.add(row);
078                }
079            } else {
080                // cast to the expected type
081                models = (List<Map<String, Object>>) body;
082            }
083    
084            for (Map<String, Object> model : models) {
085    
086                String result = factory.unbind(model);
087    
088                byte[] bytes = exchange.getContext().getTypeConverter().convertTo(byte[].class, exchange, result);
089                outputStream.write(bytes);
090    
091                // Add a carriage return
092                outputStream.write(bytesCRLF);
093            }
094        }
095    
096        public Object unmarshal(Exchange exchange, InputStream inputStream) throws Exception {
097            BindyFixedLengthFactory factory = getFactory(exchange.getContext().getPackageScanClassResolver());
098            ObjectHelper.notNull(factory, "not instantiated");
099    
100            // List of Pojos
101            List<Map<String, Object>> models = new ArrayList<Map<String, Object>>();
102    
103            // Pojos of the model
104            Map<String, Object> model;
105    
106            InputStreamReader in = new InputStreamReader(inputStream);
107    
108            // Scanner is used to read big file
109            Scanner scanner = new Scanner(in);
110    
111            int count = 0;
112    
113            try {
114    
115                // TODO Test if we have a Header
116                // TODO Test if we have a Footer (containing by example checksum)
117    
118                while (scanner.hasNextLine()) {
119    
120                    // Read the line
121                    String line = scanner.nextLine().trim();
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                ObjectHelper.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    }