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