| 1 |
package org.apache.commons.jcs3.log; |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
import java.text.MessageFormat; |
| 21 |
import java.util.IllegalFormatException; |
| 22 |
import java.util.function.Supplier; |
| 23 |
import java.util.stream.Stream; |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
public class MessageFormatter |
| 30 |
{ |
| 31 |
private final String messagePattern; |
| 32 |
private final transient Object[] parameters; |
| 33 |
private transient String formattedMessage; |
| 34 |
private transient Throwable throwable; |
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
public MessageFormatter(final String messagePattern, final Object... parameters) |
| 45 |
{ |
| 46 |
this.messagePattern = messagePattern; |
| 47 |
this.parameters = parameters; |
| 48 |
final int length = parameters == null ? 0 : parameters.length; |
| 49 |
if (length > 0 && parameters[length - 1] instanceof Throwable) |
| 50 |
{ |
| 51 |
this.throwable = (Throwable) parameters[length - 1]; |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
public MessageFormatter(final String messagePattern, final Supplier<?>... paramSuppliers) |
| 65 |
{ |
| 66 |
this.messagePattern = messagePattern; |
| 67 |
this.parameters = Stream.of(paramSuppliers) |
| 68 |
.map(Supplier::get) |
| 69 |
.toArray(); |
| 70 |
|
| 71 |
final int length = parameters.length; |
| 72 |
if (length > 0 && parameters[length - 1] instanceof Throwable) |
| 73 |
{ |
| 74 |
this.throwable = (Throwable) parameters[length - 1]; |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
public String getFormattedMessage() |
| 84 |
{ |
| 85 |
if (formattedMessage == null) |
| 86 |
{ |
| 87 |
formattedMessage = formatMessage(messagePattern, parameters); |
| 88 |
} |
| 89 |
return formattedMessage; |
| 90 |
} |
| 91 |
|
| 92 |
protected String formatMessage(final String msgPattern, final Object... args) |
| 93 |
{ |
| 94 |
try |
| 95 |
{ |
| 96 |
final MessageFormat temp = new MessageFormat(msgPattern); |
| 97 |
return temp.format(args); |
| 98 |
} |
| 99 |
catch (final IllegalFormatException ife) |
| 100 |
{ |
| 101 |
return msgPattern; |
| 102 |
} |
| 103 |
} |
| 104 |
|
| 105 |
@Override |
| 106 |
public String toString() |
| 107 |
{ |
| 108 |
return getFormattedMessage(); |
| 109 |
} |
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
public Throwable getThrowable() |
| 117 |
{ |
| 118 |
return throwable; |
| 119 |
} |
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
public boolean hasThrowable() |
| 127 |
{ |
| 128 |
return throwable != null; |
| 129 |
} |
| 130 |
} |