MessagePatternUtil { public static String applyCustomMessagePattern(String msg, String pattern) { final StringBuilder result = new StringBuilder(); if ((pattern == null) || pattern.isEmpty() || msg == null || msg.isEmpty()) { return msg; } byte[] msgBytes, patternBytes; msgBytes = msg.getBytes(); patternBytes = pattern.getBytes(); int msgIndex = 0; char currentPatternChar; boolean escapeCharEncountered = false; boolean msgFinished = false; for (int patternIndex = 0; patternIndex < patternBytes.length; patternIndex++) { currentPatternChar = (char) patternBytes[patternIndex]; if ((!escapeCharEncountered) && isEscapeChar(currentPatternChar)) { escapeCharEncountered = true; continue; } if ((!msgFinished) && (!escapeCharEncountered) && (isPlaceholder(currentPatternChar) || isDeleteholder(currentPatternChar))) { if (!isDeleteholder(currentPatternChar)) { result.append((char) msgBytes[msgIndex]); } msgIndex++; if (msgIndex == msgBytes.length) { msgFinished = true; } } else { if (escapeCharEncountered || !isPlaceholder(currentPatternChar)) { result.append(currentPatternChar); } escapeCharEncountered = false; } } for (; msgIndex < msgBytes.length; msgIndex++) { result.append((char) msgBytes[msgIndex]); } return result.toString(); }  static String applyCustomMessagePattern(String msg, String pattern);  }
@Test public void testMessagePattern() throws Exception { String msg, pattern; String result; pattern = "__:____/__/__"; msg = "0120070119"; result = MessagePatternUtil.applyCustomMessagePattern(msg, pattern); assertEquals("01:2007/01/19", result); msg = "0120070119abc"; result = MessagePatternUtil.applyCustomMessagePattern(msg, pattern); assertEquals("01:2007/01/19abc", result); msg = "123"; result = MessagePatternUtil.applyCustomMessagePattern(msg, null); assertEquals("123", result); msg = "123"; result = MessagePatternUtil.applyCustomMessagePattern(msg, ""); assertEquals("123", result); result = MessagePatternUtil.applyCustomMessagePattern(null, pattern); assertNull(result); result = MessagePatternUtil.applyCustomMessagePattern("", pattern); assertEquals("", result); pattern = "_\\__"; result = MessagePatternUtil.applyCustomMessagePattern("AB", pattern); assertEquals("A_B", result); pattern = "____>>>>"; result = MessagePatternUtil.applyCustomMessagePattern("ABCD", pattern); assertEquals("ABCD>>>>", result); pattern = "____>>>>"; result = MessagePatternUtil.applyCustomMessagePattern("AB", pattern); assertEquals("AB>>>>", result); pattern = "____>>>>\\_"; result = MessagePatternUtil.applyCustomMessagePattern("AB", pattern); assertEquals("AB>>>>_", result); }
@Test public void testDeletion() throws Exception { String msg; String result; String pattern = "____#/__#/__"; msg = "2008-11-28"; result = MessagePatternUtil.applyCustomMessagePattern(msg, pattern); assertEquals("2008/11/28", result); }