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 * Marker interface for field packagers that handle ISO-8583 amount fields.
026 * @author joconnor
027 * @version $Revision$ $Date$
028 */
029public class ISOAmountFieldPackager extends ISOFieldPackager
030{
031    private Padder padder;
032    private Interpreter interpreter;
033    private Prefixer prefixer;
034
035    /**
036     * Creates an ISOAmountFieldPackager.
037     * @param maxLength The maximum length of the field in characters or bytes depending on the datatype.
038     * @param description The description of the field. For human readable output.
039     * @param padder The type of padding used.
040     * @param interpreter The interpreter used to encode the field.
041     * @param prefixer The type of length prefixer used to encode this field.
042     */
043    public ISOAmountFieldPackager(int maxLength, String description, Padder padder, 
044                                  Interpreter interpreter, Prefixer prefixer)
045    {
046        super(maxLength, description);
047        this.padder = padder;
048        this.interpreter = interpreter;
049        this.prefixer = prefixer;
050    }
051
052    /**
053     * Constructs a default ISOAmountFieldPackager. There is no padding,
054     * no length prefix and a literal interpretation. The set methods must be called to
055     * make this ISOAmountFieldPackager useful.
056     */
057    public ISOAmountFieldPackager()
058    {
059        super();
060        this.padder = NullPadder.INSTANCE;
061        this.interpreter = LiteralInterpreter.INSTANCE;
062        this.prefixer = NullPrefixer.INSTANCE;
063    }
064
065    /**
066     * Constructs an ISOAmountFieldPackager with a specific Padder, Interpreter and Prefixer.
067     * The length and description should be set with setLength() and setDescription methods.
068     * @param padder The type of padding used.
069     * @param interpreter The interpreter used to encode the field.
070     * @param prefixer The type of length prefixer used to encode this field.
071     */
072    public ISOAmountFieldPackager(Padder padder, Interpreter interpreter, Prefixer prefixer)
073    {
074        super();
075        this.padder = padder;
076        this.interpreter = interpreter;
077        this.prefixer = prefixer;
078    }
079
080    /**
081     * Sets the Padder.
082     * @param padder The padder to use during packing and unpacking.
083     */
084    public void setPadder(Padder padder)
085    {
086        this.padder = padder;
087    }
088
089    /**
090     * Sets the Interpreter.
091     * @param interpreter The interpreter to use in packing and unpacking.
092     */
093    public void setInterpreter(Interpreter interpreter)
094    {
095        this.interpreter = interpreter;
096    }
097
098    /**
099     * Sets the length prefixer.
100     * @param prefixer The length prefixer to use during packing and unpacking.
101     */
102    public void setPrefixer(Prefixer prefixer)
103    {
104        this.prefixer = prefixer;
105    }
106
107    /**
108     * Returns the prefixer's packed length and the interpreter's packed length.
109     */
110    public int getMaxPackedLength()
111    {
112        return prefixer.getPackedLength() + interpreter.getPackedLength(getLength());
113    }
114
115    /** Create a nice readable message for errors */
116    private String makeExceptionMessage(ISOComponent c, String operation) {
117        Object fieldKey = "unknown";
118        if (c != null)
119        {
120            try
121            {
122                fieldKey = c.getKey();
123            } catch (Exception ignore)
124            {
125            }
126        }
127        return this.getClass().getName() + ": Problem " + operation + " field " + fieldKey;
128    }
129
130    /**
131         * Packs the component into a byte[].
132         */
133    public byte[] pack(ISOComponent c) throws ISOException
134    {
135        try
136        {
137            String data = (String)c.getValue();
138            if (data.length() > getLength())
139            {
140                throw new ISOException("Field length " + data.length() + " too long. Max: " + getLength());
141            }
142            String sign = data.substring(0, 1);
143            String amount = data.substring(1);
144            String paddedData = padder.pad(amount, getLength()-1);
145            int signLength = interpreter.getPackedLength(1);
146            byte[] rawData = new byte[prefixer.getPackedLength()
147                    + signLength
148                    + interpreter.getPackedLength(paddedData.length())];
149            prefixer.encodeLength(paddedData.length(), rawData);
150            interpreter.interpret(sign, rawData, prefixer.getPackedLength());
151            interpreter.interpret(paddedData, rawData, prefixer.getPackedLength() + signLength);
152            return rawData;
153        } catch(Exception e)
154        {
155            throw new ISOException(makeExceptionMessage(c, "packing"), e);
156        }
157    }
158
159    /**
160     * Unpacks the byte array into the component.
161     * @param c The component to unpack into.
162     * @param b The byte array to unpack.
163     * @param offset The index in the byte array to start unpacking from.
164     * @return The number of bytes consumed unpacking the component.
165     */
166    public int unpack(ISOComponent c, byte[] b, int offset) throws ISOException
167    {
168        try
169        {
170            int len = prefixer.decodeLength(b, offset);
171            if (len == -1) {
172                // The prefixer doesn't know how long the field is, so use
173                // maxLength instead
174                len = getLength();
175            }
176            else if (getLength() > 0 && len > getLength())
177                throw new ISOException("Field length " + len + " too long. Max: " + getLength());
178            int lenLen = prefixer.getPackedLength();
179            String unpacked = interpreter.uninterpret(b, offset + lenLen, len);
180            c.setValue(unpacked);
181            return lenLen + interpreter.getPackedLength(len);
182        } catch(Exception e)
183        {
184            throw new ISOException(makeExceptionMessage(c, "unpacking"), e);
185        }
186    }
187    
188    /**
189     * Unpack the input stream into the component.
190     * @param c  The Component to unpack into.
191     * @param in Input stream where the packed bytes come from.
192     * @exception IOException Thrown if there's a problem reading the input stream.
193     */
194    public void unpack (ISOComponent c, InputStream in) 
195        throws IOException, ISOException
196    {
197        try
198        {
199            int lenLen = prefixer.getPackedLength ();
200            int len;
201            if (lenLen == 0)
202            {
203                len = getLength();
204            } else
205            {
206                len = prefixer.decodeLength (readBytes (in, lenLen), 0);
207                if (getLength() > 0 && len > 0 && len > getLength())
208                    throw new ISOException("Field length " + len + " too long. Max: " + getLength());
209            }
210            int packedLen = interpreter.getPackedLength(len);
211            String unpacked = interpreter.uninterpret(readBytes (in, packedLen), 0, len);
212            c.setValue(unpacked);
213        } catch(ISOException e)
214        {
215            throw new ISOException(makeExceptionMessage(c, "unpacking"), e);
216        }
217    }
218
219    /**
220     * Checks the length of the data against the maximum, and throws an IllegalArgumentException.
221     * This is designed to be called from field Packager constructors and the setLength()
222     * method.
223     * @param len The length of the data for this field packager.
224     * @param maxLength The maximum length allowed for this type of field packager.
225     *          This depends on the prefixer that is used.
226     * @throws IllegalArgumentException If len > maxLength.
227     */
228    protected void checkLength(int len, int maxLength) throws IllegalArgumentException
229    {
230        if (len > maxLength)
231        {
232            throw new IllegalArgumentException("Length " + len + " too long for " + getClass().getName());
233        }
234    }
235}