SWIFT MT Code samples

Code samples

Parsing and validating SWIFT MT messages

Parse an MT text and validate the resulting object

 public void parseAndValidateMessage(String messageContent) throws InvalidMessageFormatException {
    //parse message string to the SwiftMessage object
    SwiftMessage message = new SwiftMsgProcessor().ParseMsgStringToObject(messageContent);

    //validate SwiftMessage (parsed from String or built programmatically)
    SwiftMsgValidator validator = new SwiftMsgValidator();
    SwiftValidObj validation = validator.validateMsg(message);
    //swift mt text
    String mtMessageText = validation.getMessage();
    //obtain list of errors from the validation object
    ValidationErrorList errorList = validation.getValidationErrorList();
}

Validate the block 4 alone

SwiftMessage message = new SwiftMessage();
message.setArgMsgtype("103");
message.setBlock4(createTagList(
    ":20:00089",
    ":23B:CRED",
    ":32A:001118USD3,34",
    ":33B:USD1,",
    ":50F:/34x\n" +
        "1/Name\n" +
        "2/AddressLine\n" +
        "3/US/Town",
    ":59:/34x\n" +
        "4X35x",
    ":71A:OUR",
    ":71G:EUR1,"));
ValidationErrorList errorList = new Cat103().validateMessage(message);
errorList.addAll(new Cat103().validateNetworkRules(message));

Validating a block without the peripherals will most likely result in errors/exceptions due to missing information required to perform network validations.

List all validation error messages

public void listAllErrorMessages() {
    for(Map.Entry<String, String> entry : SwiftErrorMsgs.getInstance().entrySet()) {
        System.out.println(entry.getKey() + " => " + entry.getValue());
    }
} 

Output

T51b => T51 - Indicator must contain C or D

T51c => T51 - D/C Mark must contain the code C.

SV40 => SV40 - Message Type Number and Date fields must be present.

...

As one will observe, there are multiple keys per same error code to cover different error message for some fields.

Building SWIFT MT messages

Build an MT103 using bare methods

public SwiftMessage buildMT103() {
    SwiftMessage message = new SwiftMessage();

    // Set Tags for block1
    message.setArgApplid("F");
    message.setArgServid("01");
    message.setArgLTaddrBlk1("COPZBEB0AXXX");

    // Set Tags for block2
    message.setArgInoutind("I");
    message.setArgMsgtype("103");
    message.setArgLTaddrBlk2("LRLRXXXX4A11");
    message.setArgMsgprior("N");

    // Set Tags for block3

    message.getBlock3().add(new Tag("108", new Vector<String>(){{add("MT103 005 OF 020");}}));

    // Set Tags for block4

    Vector<String> data = new Vector<String>();
    data.add("5387354");
    message.getBlock4().add(new Tag("20", data));

    data = new Vector<String>();
    data.add("CRED");
    message.getBlock4().add(new Tag("23B", data));

    data = new Vector<String>();
    data.add("PHOB/20.527.19.60");
    message.getBlock4().add(new Tag("23E", data));

    data = new Vector<String>();
    data.add("000526USD1101,50");
    message.getBlock4().add(new Tag("32A", data));

    data = new Vector<String>();
    data.add("USD1121,50");
    message.getBlock4().add(new Tag("33B", data));

    data = new Vector<String>();
    data.add("FRANZ HOLZAPFEL GMBH");
    data.add("VIENNA");
    message.getBlock4().add(new Tag("50K", data));

    data = new Vector<String>();
    data.add("BKAUATWW");
    message.getBlock4().add(new Tag("52A", data));

    data = new Vector<String>();
    data.add("723491524");
    data.add("C. KLEIN");
    data.add("BLOEMENGRACHT 15");
    data.add("AMSTERDAM");
    message.getBlock4().add(new Tag("59", data));

    data = new Vector<String>();
    data.add("SHA");
    message.getBlock4().add(new Tag("71A", data));

    data = new Vector<String>();
    data.add("USD10,");
    message.getBlock4().add(new Tag("71F", data));

    data = new Vector<String>();
    data.add("USD10,");
    message.getBlock4().add(new Tag("71F", data));

    data = new Vector<String>();
    data.add("/INS/CHASUS33");
    message.getBlock4().add(new Tag("72", data));

    // Set Tags for block5

    message.getBlock5().add(new Tag("MAC", new Vector<String>(){{add("00000000");}}));

    message.getBlock5().add(new Tag("CHK", new Vector<String>(){{add("4BCF59104AF9");}}));

    return message;
}

Build an MT103 using additional methods

 public SwiftMessage buildMT103() {
    SwiftMessage message = new SwiftMessage();

    // Set Tags for block1
    message.setArgApplid("F");
    message.setArgServid("01");
    message.setArgLTaddrBlk1("COPZBEB0AXXX");

    // Set Tags for block2
    message.setArgInoutind("I");
    message.setArgMsgtype("103");
    message.setArgLTaddrBlk2("LRLRXXXX4A11");
    message.setArgMsgprior("N");

    message.getBlock3().addAll(createTagList("108:MT103 005 OF 020"));

    message.getBlock4().addAll(createTagList(":20:5387354\n" +
            ":23B:CRED\n" +
            ":23E:PHOB/20.527.19.60\n"+
            ":32A:000526USD1101,50\n" +
            ":33B:USD1121,50\n" +
            ":50K:FRANZ HOLZAPFEL GMBH\n" +
            "VIENNA\n" +
            ":52A:BKAUATWW\n" +
            ":59:723491524\n" +
            "C. KLEIN\n" +
            "BLOEMENGRACHT 15\n" +
            "AMSTERDAM\n" +
            ":71A:SHA\n" +
            ":71F:USD10,\n" +
            ":71F:USD10,\n" +
            ":72:/INS/CHASUS33"));

    message.getBlock5().addAll(createTagList("MAC:00000000", "CHK:4BCF59104AF9"));

    return message;
}

public static RepSeq createRepSeq(String repSeqString) {
    return new RepSeq(createTagList(repSeqString.split("\n:")));
}

public static Vector<Tag> createTagList(String block4Text) {
    return createTagList(block4Text.split("\n:"));
}

public static Vector<Tag> createTagList(String... tagValues) {
    Vector<Tag> tagList = new Vector<Tag>();
    for(String tag : tagValues) {
        tagList.add(createTag(tag));
    }
    return tagList;
}

public static Tag createTag(String tag) {
    String tagKey = tag.replaceAll("(?s):?(.*):.*", "$1");
    String tagValueString = tag.replaceAll("(?s):?.*:(.*)", "$1");
    String[] lines = tagValueString.split("\n");

    Vector tagValue = new Vector();
    Collections.addAll(tagValue, lines);

    return new Tag(tagKey, tagValue);
}

Build and validate an MT205COV using some additional methods

public void buildAndValidate205COV() {
    SwiftMessage message = new SwiftMessage();

    // Set Tags for block1
    message.setArgApplid("F");
    message.setArgServid("01");
    message.setArgLTaddrBlk1("AAAABEBBAXXX");

    // Set Tags for block2
    message.setArgInoutind("I");
    message.setArgMsgtype("205");
    message.setArgLTaddrBlk2("CCCCUS33AXXX");
    message.setArgMsgprior("N");

    addTagsToBlock(message.getBlock3(), ":119:COV");//this tag tells SWIFT that this is a COV message

    addTagsToBlock(message.getBlock4(),
            ":20:987COV",
            ":21:090525/123COV",
            ":32A:090527USD10500,00",
            ":52A:AAAABEBB",
            ":58A:BBBBGB22",
            ":50F:/123564982101\n1/MR. BIG\n2/HIGH STREET 3\n3/BE/BRUSSELS",
            ":59:/987654321\nMR. SMALL\nLOW STREET 15\nLONDON GB",
            ":70:/INV/1234",
            ":33B:USD10500,00");

    // Set Tags for block5 (This block is optional)
    addTagsToBlock(message.getBlock5(), ":MAC:75D138E4", ":CHK:DE1B0D71FA96"); //add MAC and CHK to block5 vector

    // Now validate and build the outgoing message in a string format as SWIFT expects it.
    SwiftValidObj validation = new SwiftMsgValidator().validateMsg(message);

    if (validation.hasErrors()){  //If validation error
        ValidationErrorList errorList = validation.getValidationErrorList();
        for(ValidationError error : errorList) { //Print error messages
            System.out.println(error);
        }

    } else {
        String swiftMessage = validation.getMessage();
        System.out.println(swiftMessage); //Print the constructed Swift message.
    }
}

private static void addTagsToBlock(List block, String... tags) {
    for(String tag : tags) {
        String tagKey = tag.replaceAll("(?s):(.*):.*", "$1");
        String tagValueString = tag.replaceAll("(?s):.*:(.*)", "$1");
        String[] lines = tagValueString.split("\n");

        Vector tagValue = new Vector();
        for(String line : lines) {
            tagValue.add(line);
        }
        block.add(new Tag(tagKey, tagValue));
    }
}

Build an MT 527 message

SwiftMessage message = new SwiftMessage();

// Set Tags for block1
message.setArgApplid("F");
message.setArgServid("01");
message.setArgLTaddrBlk1("COPZBEB0AXXX");

// Set Tags for block2
message.setArgInoutind("I");
message.setArgMsgtype("527");
message.setArgLTaddrBlk2("LRLRXXXX4A11");
message.setArgMsgprior("N");

// Set Tags for block3

message.getBlock3().add(new Tag("108", new Vector<String>(){{add("MT527 005 OF 020");}}));

// Set Tags for block4

//GENL BLOCK
Block genlBlock = new Block();

genlBlock.addTag(new Tag("16R", new Vector<String>((Arrays.asList(new String[]{"GENL"})))));

Tag tag28E = new Tag("28E");
tag28E.addDataLine("12345/ONLY");
genlBlock.addTag(tag28E);

Tag tag20C = new Tag("20C");
tag20C.addDataLine(":SEME//01357");
genlBlock.addTag(tag20C);

Tag tag23G = new Tag("23G");
tag23G.addDataLine("NEWM/CODU");
genlBlock.addTag(tag23G);

Tag tag98A = new Tag("98A");
tag98A.addDataLine(":EXRQ//20001202");
genlBlock.addTag(tag98A);

Tag tag22F = new Tag("22F");
tag22F.addDataLine(":CINT//TERM");
genlBlock.addTag(tag22F);


genlBlock.addTag(new Tag("16S", new Vector<String>((Arrays.asList(new String[]{ "GENL" })))));

//COLLPRTY BLOCK
BlockRepSeq collPrtryBlock = new BlockRepSeq();

collPrtryBlock.addTag(new Tag("16R", new Vector<String>((Arrays.asList(new String[]{ "COLLPRTY" })))));

Tag tag95P = new Tag("95P");
tag95P.addDataLine(":CLPA//TESTUSVT");
collPrtryBlock.addTag(tag95P);

collPrtryBlock.addTag(new Tag("16S", new Vector<String>((Arrays.asList(new String[]{ "COLLPRTY" })))));

//DEALTRAN BLOCK
Block dealTranBlock = new Block();

dealTranBlock.addTag(new Tag("16R", new Vector<String>((Arrays.asList(new String[]{ "DEALTRAN" })))));

Tag tag98ADT = new Tag("98A");
tag98ADT.addDataLine(":TERM//20001231");
dealTranBlock.addTag(tag98ADT);

Tag tag19A = new Tag("19A");
tag19A.addDataLine(":TRAA//USD1000000,");
dealTranBlock.addTag(tag19A);

dealTranBlock.addTag(new Tag("16S", new Vector<String>((Arrays.asList(new String[]{ "DEALTRAN" })))));
//Add all blocks/tags to block4
genlBlock.addRepetitive(collPrtryBlock);
message.getBlock4().add(genlBlock);
message.getBlock4().add(dealTranBlock);

//Add block 5 tags
message.getBlock5().add(new Tag("MAC", new Vector<String>(){{add("00000000");}}));
message.getBlock5().add(new Tag("CHK", new Vector<String>(){{add("4BCF59104AF9");}}));

SwiftMsgValidator smv = new SwiftMsgValidator();
SwiftValidObj vobj = null;
try {
    vobj = smv.validateMsg(message);
} catch (Exception e) {
    e.printStackTrace();
}

System.out.println(vobj.getErrorMessage());
System.out.println(vobj.getMessage());

Utilities

Getting Tag description

public void testTagDescription() throws IOException {

    String messageContent = "";

    List<String> lines =  Files.readAllLines(FileSystems.getDefault().getPath("/path/to/5670.txt"), StandardCharsets.UTF_8);
    for (String line : lines)  {
        messageContent += line + "\r\n";
    }
    try {
        SwiftMessage message = new SwiftMsgProcessor().ParseMsgStringToObject(messageContent);

        Tag aTag = message.getTag("23G");

        assert aTag != null;

        System.out.println(aTag.getDescription("567"));

    } catch (InvalidMessageFormatException e) {
        e.printStackTrace();
    }
}

XML

This feature allows you to serialize MT messages to XML.

Serialize MT object to XML

public void SwiftToXML(String messageText) throws Exception {
    SwiftMsgProcessor smp = new SwiftMsgProcessor();
    SwiftMessage msgObject = smp.ParseMsgStringToObject(messageText);
    XMLWriter writer = new XMLWriter();
    writer.buildXML(msgObject, ".", "test.xml");
    SwiftMsgValidator SMV = new SwiftMsgValidator();
    SwiftValidObj validation = SMV.validateMsg(msgObject);
    if (validation.hasErrors()) {
        ValidationErrorList errorList = validation.getValidationErrorList();
        for (ValidationError error : errorList) {
            System.out.println(error);
        }
    } else {
        System.out.println("SWIFT message is valid!");
    }
}