View Javadoc

1   /*
2    * This file is part of AceLogger.
3    * 
4    * AceLogger is free software: you can redistribute it and/or modify it under the terms of the GNU
5    * Lesser General Public License as published by the Free Software Foundation, either version 3 of
6    * the License, or (at your option) any later version.
7    * 
8    * AceLogger is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
9    * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10   * Lesser General Public License for more details.
11   * 
12   * You should have received a copy of the GNU Lesser General Public License along with AceLogger.
13   * If not, see <http://www.gnu.org/licenses/lgpl-3.0.html>.
14   */
15  package net.sourceforge.acelogger.interpolator;
16  
17  import java.text.MessageFormat;
18  
19  import net.sourceforge.acelogger.execution.LogController;
20  
21  /**
22   * An implementation of TextInterpolator for the {@link MessageFormat} class.
23   * 
24   * @author Zardi (https://sourceforge.net/users/daniel_zardi)
25   * @version 1.0.0
26   * @since 1.0.0
27   */
28  public final class JavaTextFormatInterpolator implements TextInterpolator {
29  
30  	/**
31  	 * An instance of this class (the only one).
32  	 */
33  	private static final JavaTextFormatInterpolator INSTANCE = new JavaTextFormatInterpolator();
34  
35  	/**
36  	 * Creates a new JavaTextFormatInterpolator (This class is a singleton).
37  	 * 
38  	 * @since 1.0.0
39  	 */
40  	private JavaTextFormatInterpolator() {}
41  
42  	/**
43  	 * Gets a instance of this class. The returned instance is always the same, synchronization
44  	 * issues are dealt by the methods of this class.
45  	 * 
46  	 * @return A instance of this class.
47  	 * @since 1.0.0
48  	 */
49  	public static TextInterpolator getInstance() {
50  		return INSTANCE;
51  	}
52  
53  	/** {@inheritDoc} */
54  	public String interpolate(String pattern, Object... params) {
55  		String formatted = "";
56  		if (pattern == null) {
57  			LogController.getInternalLogger().warn("Received a null pattern");
58  			throw new IllegalArgumentException("The pattern should not be null");
59  		} else {
60  			try {
61  				formatted = new MessageFormat(pattern).format(params);
62  			} catch (Exception e) {
63  				LogController.getInternalLogger().error(
64  						"It was not possible to format \"{0}\" with \"{1}\"", e, pattern, params);
65  				throw new IllegalArgumentException("The pattern is invalid", e);
66  			}
67  		}
68  		return formatted;
69  	}
70  
71  }