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 ISOAmountFieldPackager extends ISOFieldPackager
029{
030    private Padder padder;
031    private Interpreter interpreter;
032    private Prefixer prefixer;
033
034    /**
035     * Creates an ISOAmountFieldPackager.
036     * @param maxLength The maximum length of the field in characters or bytes depending on the datatype.
037     * @param description The description of the field. For human readable output.
038     * @param padder The type of padding used.
039     * @param interpreter The interpreter used to encode the field.
040     * @param prefixer The type of length prefixer used to encode this field.
041     */
042    public ISOAmountFieldPackager(int maxLength, String description, Padder padder, 
043                                  Interpreter interpreter, Prefixer prefixer)
044    {
045        super(maxLength, description);
046        this.padder = padder;
047        this.interpreter = interpreter;
048        this.prefixer = prefixer;
049    }
050
051    /**
052     * Constructs a default ISOAmountFieldPackager. There is no padding,
053     * no length prefix and a literal interpretation. The set methods must be called to
054     * make this ISOAmountFieldPackager useful.
055     */
056    public ISOAmountFieldPackager()
057    {
058        super();
059        this.padder = NullPadder.INSTANCE;
060        this.interpreter = LiteralInterpreter.INSTANCE;
061        this.prefixer = NullPrefixer.INSTANCE;
062    }
063
064    /**
065     * Constructs an ISOAmountFieldPackager with a specific Padder, Interpreter and Prefixer.
066     * The length and description should be set with setLength() and setDescription methods.
067     * @param padder The type of padding used.
068     * @param interpreter The interpreter used to encode the field.
069     * @param prefixer The type of length prefixer used to encode this field.
070     */
071    public ISOAmountFieldPackager(Padder padder, Interpreter interpreter, Prefixer prefixer)
072    {
073        super();
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         * Packs 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 sign = data.substring(0, 1);
142            String amount = data.substring(1);
143            String paddedData = padder.pad(amount, getLength()-1);
144            int signLength = interpreter.getPackedLength(1);
145            byte[] rawData = new byte[prefixer.getPackedLength()
146                    + signLength
147                    + interpreter.getPackedLength(paddedData.length())];
148            prefixer.encodeLength(paddedData.length(), rawData);
149            interpreter.interpret(sign, rawData, prefixer.getPackedLength());
150            interpreter.interpret(paddedData, rawData, prefixer.getPackedLength() + signLength);
151            return rawData;
152        } catch(Exception e)
153        {
154            throw new ISOException(makeExceptionMessage(c, "packing"), e);
155        }
156    }
157
158    /**
159     * Unpacks the byte array into the component.
160     * @param c The component to unpack into.
161     * @param b The byte array to unpack.
162     * @param offset The index in the byte array to start unpacking from.
163     * @return The number of bytes consumed unpacking the component.
164     */
165    public int unpack(ISOComponent c, byte[] b, int offset) throws ISOException
166    {
167        try
168        {
169            int len = prefixer.decodeLength(b, offset);
170            if (len == -1) {
171                // The prefixer doesn't know how long the field is, so use
172                // maxLength instead
173                len = getLength();
174            }
175            else if (getLength() > 0 && len > getLength())
176                throw new ISOException("Field length " + len + " too long. Max: " + getLength());
177            int lenLen = prefixer.getPackedLength();
178            String unpacked = interpreter.uninterpret(b, offset + lenLen, len);
179            c.setValue(unpacked);
180            return lenLen + interpreter.getPackedLength(len);
181        } catch(Exception e)
182        {
183            throw new ISOException(makeExceptionMessage(c, "unpacking"), e);
184        }
185    }
186    
187    /**
188     * Unpack the input stream into the component.
189     * @param c  The Component to unpack into.
190     * @param in Input stream where the packed bytes come from.
191     * @exception IOException Thrown if there's a problem reading the input stream.
192     */
193    public void unpack (ISOComponent c, InputStream in) 
194        throws IOException, ISOException
195    {
196        try
197        {
198            int lenLen = prefixer.getPackedLength ();
199            int len;
200            if (lenLen == 0)
201            {
202                len = getLength();
203            } else
204            {
205                len = prefixer.decodeLength (readBytes (in, lenLen), 0);
206                if (getLength() > 0 && len > 0 && len > getLength())
207                    throw new ISOException("Field length " + len + " too long. Max: " + getLength());
208            }
209            int packedLen = interpreter.getPackedLength(len);
210            String unpacked = interpreter.uninterpret(readBytes (in, packedLen), 0, len);
211            c.setValue(unpacked);
212        } catch(ISOException e)
213        {
214            throw new ISOException(makeExceptionMessage(c, "unpacking"), e);
215        }
216    }
217
218    /**
219     * Checks the length of the data against the maximum, and throws an IllegalArgumentException.
220     * This is designed to be called from field Packager constructors and the setLength()
221     * method.
222     * @param len The length of the data for this field packager.
223     * @param maxLength The maximum length allowed for this type of field packager.
224     *          This depends on the prefixer that is used.
225     * @throws IllegalArgumentException If len > maxLength.
226     */
227    protected void checkLength(int len, int maxLength) throws IllegalArgumentException
228    {
229        if (len > maxLength)
230        {
231            throw new IllegalArgumentException("Length " + len + " too long for " + getClass().getName());
232        }
233    }
234}