Total Pageviews

2017/11/02

[Java] MessageFormat

Problem
How to takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places.

Example 1.



Example 2.



How-To

Here has an example to demonstrate how to do message format:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package albert.practice.stringFormat;

import java.text.Format;
import java.text.MessageFormat;

public class StringFormatExample {
    
    public String getFormattedMessage(String message, String... values) {
       Format messageFormat = new MessageFormat(message);
       return messageFormat.format(values);
    }
    
}


Test case is as bellows:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package albert.practice.stringFormat;

import static org.junit.Assert.assertEquals;

import org.junit.Before;
import org.junit.Test;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class StringFormatExampleTest {

    private StringFormatExample stringFormat;
    private String unformatedMessage = "";
    private String phone = "";
    private String otp;
    private String anotherUnformatedMessage;
    private String error;
    
    @Before
    public void setup() {
        stringFormat = new StringFormatExample();
        unformatedMessage = "驗證碼傳送成功。手機號碼: {0}, 簡訊內容:驗證碼為:{1}";
        anotherUnformatedMessage = "驗證碼傳送失敗,失敗原因:{1}。手機號碼: {0}";
        phone = "0910123456";
        otp = "12345";
        error = "HTTP Server is down";
    }
    
    @Test
    public void testReturnWith1000Separator() {
        String str = stringFormat.returnWith1000Separator(1234567890);
        log.debug(str);
        assertEquals("1,234,567,890", str);
    }
    
    @Test
    public void testGetFormattedMessage() {
        String formatedMsg = stringFormat.getFormattedMessage(unformatedMessage, phone, otp);
        log.debug("formatedMsg = " + formatedMsg);
        assertEquals("驗證碼傳送成功。手機號碼: 0910123456, 簡訊內容:驗證碼為:12345", formatedMsg);
        
        String anotherFormatedMsg = stringFormat.getFormattedMessage(anotherUnformatedMessage, phone, error);
        log.debug("anotherFormatedMsg = " + anotherFormatedMsg);
        assertEquals("驗證碼傳送失敗,失敗原因:HTTP Server is down。手機號碼: 0910123456", anotherFormatedMsg);
    }

}
 

print logs:
1
2
14:57:18.679 [main] DEBUG a.p.s.s - formatedMsg = 驗證碼傳送成功。手機號碼: 0910123456, 簡訊內容:驗證碼為:12345
14:57:18.679 [main] DEBUG a.p.s.s - anotherFormatedMsg = 驗證碼傳送失敗,失敗原因:HTTP Server is down。手機號碼: 0910123456 



No comments: