001/*
002 * jPOS Project [http://jpos.org]
003 * Copyright (C) 2000-2026 jPOS Software SRL
004 *
005 * This program is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Affero General Public License as
007 * published by the Free Software Foundation, either version 3 of the
008 * License, or (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013 * GNU Affero General Public License for more details.
014 *
015 * You should have received a copy of the GNU Affero General Public License
016 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jpos.iso;
020
021import java.io.IOException;
022import java.io.InputStream;
023
024/**
025 * @author joconnor
026 * @version $Revision$ $Date$
027 */
028public class ISOFilledStringFieldPackager extends ISOFieldPackager
029{
030    private Interpreter interpreter;
031    private Padder padder;
032    private Prefixer prefixer;
033
034    /**
035     * Constructs a default ISOFilledStringFieldPackager. There is no padding,
036     * no length prefix and a literal interpretation. The set methods must be called to
037     * make this useful.
038     */
039    public ISOFilledStringFieldPackager()
040    {
041        super();
042        this.padder = NullPadder.INSTANCE;
043        this.interpreter = LiteralInterpreter.INSTANCE;
044        this.prefixer = NullPrefixer.INSTANCE;
045    }
046
047    /**
048     * Constructs an ISOFilledStringFieldPackager with a specific Padder, Interpreter and Prefixer.
049     * The length and description should be set with setLength() and setDescription methods.
050     * @param padder The type of padding used.
051     * @param interpreter The interpreter used to encode the field.
052     * @param prefixer The type of length prefixer used to encode this field.
053     */
054    public ISOFilledStringFieldPackager(Padder padder, Interpreter interpreter, Prefixer prefixer)
055    {
056        super();
057        this.padder = padder;
058        this.interpreter = interpreter;
059        this.prefixer = prefixer;
060    }
061
062    /**
063     * Creates an ISOFilledStringFieldPackager.
064     * @param maxLength The maximum length of the field in characters or bytes depending on the datatype.
065     * @param description The description of the field. For human readable output.
066     * @param interpreter The interpreter used to encode the field.
067     * @param padder The type of padding used.
068     * @param prefixer The type of length prefixer used to encode this field.
069     */
070    public ISOFilledStringFieldPackager(int maxLength, String description, Padder padder,
071                                  Interpreter interpreter, Prefixer prefixer)
072    {
073        super(maxLength, description);
074        this.padder = padder;
075        this.interpreter = interpreter;
076        this.prefixer = prefixer;
077    }
078
079    /**
080     * Sets the Padder.
081     * @param padder The padder to use during packing and unpacking.
082     */
083    public void setPadder(Padder padder)
084    {
085        this.padder = padder;
086    }
087
088    /**
089     * Sets the Interpreter.
090     * @param interpreter The interpreter to use in packing and unpacking.
091     */
092    public void setInterpreter(Interpreter interpreter)
093    {
094        this.interpreter = interpreter;
095    }
096
097    /**
098     * Sets the length prefixer.
099     * @param prefixer The length prefixer to use during packing and unpacking.
100     */
101    public void setPrefixer(Prefixer prefixer)
102    {
103        this.prefixer = prefixer;
104    }
105
106    /**
107     * Returns the prefixer's packed length and the interpreter's packed length.
108     */
109    public int getMaxPackedLength()
110    {
111        return prefixer.getPackedLength() + interpreter.getPackedLength(getLength());
112    }
113
114    /** Create a nice readable message for errors */
115    private String makeExceptionMessage(ISOComponent c, String operation) {
116        Object fieldKey = "unknown";
117        if (c != null)
118        {
119            try
120            {
121                fieldKey = c.getKey();
122            } catch (Exception ignore)
123            {
124            }
125        }
126        return this.getClass().getName() + ": Problem " + operation + " field " + fieldKey;
127    }
128
129    /**
130         * Convert the component into a byte[].
131         */
132    public byte[] pack(ISOComponent c) throws ISOException
133    {
134        try
135        {
136            String data = (String)c.getValue();
137            if (data.length() > getLength())
138            {
139                throw new ISOException("Field length " + data.length() + " too long. Max: " + getLength());
140            }
141            String paddedData = padder.pad(data, getLength());
142            byte[] rawData = new byte[prefixer.getPackedLength()
143                    + interpreter.getPackedLength(paddedData.length())];
144            prefixer.encodeLength(data.length(), rawData);
145            interpreter.interpret(paddedData, rawData, prefixer.getPackedLength());
146            return rawData;
147        } catch(Exception e)
148        {
149            throw new ISOException(makeExceptionMessage(c, "packing"), e);
150        }
151    }
152
153    /**
154     * Unpacks the byte array into the component.
155     * @param c The component to unpack into.
156     * @param b The byte array to unpack.
157     * @param offset The index in the byte array to start unpacking from.
158     * @return The number of bytes consumed unpacking the component.
159     */
160    public int unpack(ISOComponent c, byte[] b, int offset) throws ISOException
161    {
162        try
163        {
164            int len = prefixer.decodeLength(b, offset);
165            if (len == -1) {
166                // The prefixer doesn't know how long the field is, so use
167                // maxLength instead
168                len = getLength();
169            }
170            else if (getLength() > 0 && len > getLength())
171                throw new ISOException("Field length " + len + " too long. Max: " + getLength());
172            int lenLen = prefixer.getPackedLength();
173            String unpacked = interpreter.uninterpret(b, offset + lenLen, len);
174            c.setValue(unpacked);
175            return lenLen + interpreter.getPackedLength(getLength());
176        } catch(Exception e)
177        {
178            throw new ISOException(makeExceptionMessage(c, "unpacking"), e);
179        }
180    }
181
182    /**
183     * Unpack the input stream into the component.
184     * @param c  The Component to unpack into.
185     * @param in Input stream where the packed bytes come from.
186     * @exception IOException Thrown if there's a problem reading the input stream.
187     */
188    public void unpack (ISOComponent c, InputStream in) 
189        throws IOException, ISOException
190    {
191        try
192        {
193            int lenLen = prefixer.getPackedLength ();
194            int len;
195            if (lenLen == 0)
196            {
197                len = getLength();
198            } else
199            {
200                len = prefixer.decodeLength (readBytes (in, lenLen), 0);
201                if (getLength() > 0 && len > 0 && len > getLength())
202                    throw new ISOException("Field length " + len + " too long. Max: " + getLength());
203            }
204            int packedLen = interpreter.getPackedLength(len);
205            String unpacked = interpreter.uninterpret(readBytes (in, packedLen), 0, len);
206            c.setValue(unpacked);
207            in.skip(interpreter.getPackedLength(getLength()) - packedLen);
208        } catch(ISOException e)
209        {
210            throw new ISOException(makeExceptionMessage(c, "unpacking"), e);
211        }
212    }
213
214    /**
215     * Checks the length of the data against the maximum, and throws an IllegalArgumentException.
216     * This is designed to be called from field Packager constructors and the setLength()
217     * method.
218     * @param len The length of the data for this field packager.
219     * @param maxLength The maximum length allowed for this type of field packager.
220     *          This depends on the prefixer that is used.
221     * @throws IllegalArgumentException If len > maxLength.
222     */
223    protected void checkLength(int len, int maxLength) throws IllegalArgumentException
224    {
225        if (len > maxLength)
226        {
227            throw new IllegalArgumentException("Length " + len + " too long for " + getClass().getName());
228        }
229    }
230}