ProblemUtil { public static String formatMessage(String pattern, Object[] params) { if (Checker.isBlank(pattern)) return null; try { StringBuilder result = new StringBuilder(); int fromIndex = 0; int toIndex; while ((toIndex = pattern.indexOf('{', fromIndex)) >= 0) { result.append(pattern.substring(fromIndex, toIndex)); fromIndex = toIndex + 1; toIndex = pattern.indexOf('}', fromIndex); String argVal = getValue(pattern.substring(fromIndex, toIndex), params); result.append(argVal); fromIndex = toIndex + 1; } result.append(pattern.substring(fromIndex)); return result.toString(); } catch (Exception e) { logger.error(e.toString(), e); return "Wrong log pattern"; } } private  ProblemUtil(); static void checkProblem(Map<Problem, List<Object>> problems); static String getProblemKey(Problem problem); static String formatMessage(String pattern, Object[] params);  }
@Test public void testFormatMessage() { Object[] paramNoValues = new Object[] {}; assertNull(ProblemUtil.formatMessage("", paramNoValues)); assertEquals("No param", ProblemUtil.formatMessage("No param", paramNoValues)); Object[] paramValues = new Object[] { Long.valueOf(1), Double.valueOf(7.8), new TestWrapper("superTruper") }; assertEquals("first param: 1, second param: 7.8, second param again: 7.8, third param value: superTruper", ProblemUtil.formatMessage( "first param: {0}, second param: {1}, second param again: {1}, third param value: {2.firstProp}", paramValues)); assertEquals("superTruper", ProblemUtil.formatMessage("{0}", new Object[] { "superTruper" })); }
@Test public void testFormatMessageNull() { Object[] paramValues = new Object[] { "", null, new TestWrapper(null) }; assertEquals("first param: , second param: null, second param nested: null, third param: null", ProblemUtil.formatMessage( "first param: {0}, second param: {1}, second param nested: {1.prop.val}, third param: {2.firstProp}", paramValues)); }
@Test public void testFormatMessageWrong() { Object[] paramValues = new Object[] { "", null, new TestWrapper(null) }; assertEquals("outOfBounds param: Wrong value specification", ProblemUtil.formatMessage("outOfBounds param: {9}", paramValues)); assertEquals("Wrong log pattern", ProblemUtil.formatMessage("missing curly bracet: {0", paramValues)); assertEquals("missing curly bracet: Wrong value specification", ProblemUtil.formatMessage("missing curly bracet: {0, second param: {1}", paramValues)); assertEquals("missing property: Wrong value specification", ProblemUtil.formatMessage("missing property: {2.missing}", paramValues)); }