*/
public byte[] pack(ISOComponent m) throws ISOException {
LogEvent evt = new LogEvent(this, "pack");
try {
ISOComponent c;
List<byte[]> l = new ArrayList<byte[]>();
Map fields = m.getChildren();
fields.remove(new Integer(-1));
int len = 0;
boolean tagsStarted = false;
Iterator iterator = fields.values().iterator();
if (m instanceof OffsetIndexedComposite) {
int offset = ((OffsetIndexedComposite) m).getOffset();
for (int i = 0; i < offset && iterator.hasNext(); i++) {
iterator.next();
}
}
while (iterator.hasNext() && len < this.length) {
Object obj = iterator.next();
c = (ISOComponent) obj;
byte[] b;
if (c.getValue() != null) {
if (c instanceof ISOTaggedField) {
tagsStarted = true;
String tag = ((ISOTaggedField) c).getTag();
if (tag == null) {
evt.addMessage("error packing subfield " + c.getKey());
evt.addMessage(c);
throw new ISOException("Tag should not be null");
} else {
ISOFieldPackager fieldPackager = (ISOFieldPackager) packagerMap.get(tag);
if (fieldPackager == null) {
fieldPackager = (ISOFieldPackager) packagerMap.get("default");
}
if (fieldPackager == null) {
throw new ISOException("No default tag packager and no field packager configured for tag: " + tag);
}
b = fieldPackager.pack(c);
if ((len + b.length) > this.length) {
break;
}
len += b.length;
l.add(b);
}
} else if (numericTag) {
int tagNumber = (Integer) c.getKey();
String tag = ISOUtil.padleft(String.valueOf(tagNumber), this.tag.length(), '0');
ISOTaggedField isoTaggedField = new ISOTaggedField(tag, c);
if (fld.length > tagNumber) {
b = fld[(Integer) c.getKey()].pack(isoTaggedField);
} else {
ISOFieldPackager fieldPackager = (ISOFieldPackager) packagerMap.get(tag);
if (fieldPackager == null) {
fieldPackager = (ISOFieldPackager) packagerMap.get("default");
}
if (fieldPackager == null) {
throw new ISOException("No default tag packager and no field packager configured for tag: " + tag);
}
b = fieldPackager.pack(isoTaggedField);
if ((len + b.length) > this.length) {
break;
}
}
len += b.length;
l.add(b);
} else if (!tagsStarted) {
if (fld.length > (Integer) c.getKey()) {
b = fld[(Integer) c.getKey()].pack(c);
} else {
throw new ISOException("Non ISOTagField without packager definition. Cannot pack as tag is non-numeric");
}
len += b.length;
l.add(b);
} else {
evt.addMessage("error packing sub-field " + c.getKey() + ". Sub-field should be of type ISOTaggedField when tag is non-numeric");
evt.addMessage(c);
throw new ISOException("error packing sub-field " + c.getKey() + ". Sub-field should be of type ISOTaggedField when tag is non-numeric");
}
}
if (m instanceof OffsetIndexedComposite) {
((OffsetIndexedComposite) m).incOffset();
}