From 81e10478d68a8888d6d7f7bd849b9b51f6505802 Mon Sep 17 00:00:00 2001 From: Alejandro Revilla Date: Wed, 10 Apr 2024 17:47:11 -0300 Subject: [PATCH] add ISOUtil.toASCII and toLatin helper methods --- jpos/src/main/java/org/jpos/iso/ISOUtil.java | 28 +++++++++++++++++++ .../test/java/org/jpos/iso/ISOUtilTest.java | 13 +++++++++ 2 files changed, 41 insertions(+) diff --git a/jpos/src/main/java/org/jpos/iso/ISOUtil.java b/jpos/src/main/java/org/jpos/iso/ISOUtil.java index 86d7fb30ce..539d4a3baf 100644 --- a/jpos/src/main/java/org/jpos/iso/ISOUtil.java +++ b/jpos/src/main/java/org/jpos/iso/ISOUtil.java @@ -1733,4 +1733,32 @@ public static String charDecode(String s, char delimiter, int i) { return i < split.length ? split[i] : ""; } } + + public static String toUnicodeString(String input) { + StringBuilder sb = new StringBuilder(); + for (char c : input.toCharArray()) { + sb.append(String.format("\\u%04x", (int) c)); + } + return sb.toString(); + } + + public static String toASCII(String s) { + return toSingleByte (s, 0x7F); + } + public static String toLatin(String s) { + return toSingleByte (s, 0xFF); + } + + private static String toSingleByte(String s, int mask) { + StringBuilder sb = new StringBuilder(); + s.codePoints().forEach(cp -> { + if (cp > mask) { + sb.append(" "); + if (cp > 0xFFFF) // multi-byte character + sb.append(" "); + } else + sb.appendCodePoint(cp); // Append the single-byte character + }); + return sb.toString(); + } } diff --git a/jpos/src/test/java/org/jpos/iso/ISOUtilTest.java b/jpos/src/test/java/org/jpos/iso/ISOUtilTest.java index 3f48c8bb55..888bd8ab19 100644 --- a/jpos/src/test/java/org/jpos/iso/ISOUtilTest.java +++ b/jpos/src/test/java/org/jpos/iso/ISOUtilTest.java @@ -5072,4 +5072,17 @@ public void testCharEncodeAndDecode() { assertEquals("", ISOUtil.charDecode("a:b:c", ':', 4), "error getting part 4 of \"a:b:c\""); assertEquals("b", ISOUtil.charDecode(":b:c", ':', 1), "error getting part 1 of \":b:c\""); } + + @Test + public void testUTF () { + String s = "- \uD83D\uDC7D\uD83D\uDC94LTUS Lei\u0091s 19 Ñandú Rally\u0092sINUS"; + String expectedLatin = "- LTUS Lei\u0091s 19 Ñandú Rally\u0092sINUS"; + String expectedASCII = "- LTUS Lei s 19 and Rally sINUS"; + String d = ISOUtil.toLatin(s); + assertEquals(s.length(), d.length()); + assertEquals(expectedLatin, d); + d = ISOUtil.toASCII(s); + assertEquals(s.length(), d.length()); + assertEquals(expectedASCII, d); + } }