View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.message;
18  
19  import org.apache.logging.log4j.Logger;
20  import org.apache.logging.log4j.status.StatusLogger;
21  
22  import java.io.IOException;
23  import java.io.ObjectInputStream;
24  import java.io.ObjectOutputStream;
25  import java.text.Format;
26  import java.text.MessageFormat;
27  import java.util.Arrays;
28  import java.util.regex.Pattern;
29  
30  /**
31   * Handles messages that contain a format String. Dynamically determines if the format conforms to
32   * MessageFormat or String.format and if not then uses ParameterizedMessage to format.
33   */
34  public class FormattedMessage implements Message {
35  
36      private static final Logger LOGGER = StatusLogger.getLogger();
37  
38      private static final long serialVersionUID = -665975803997290697L;
39  
40      private static final int HASHVAL = 31;
41  
42      private static final String FORMAT_SPECIFIER = "%(\\d+\\$)?([-#+ 0,(\\<]*)?(\\d+)?(\\.\\d+)?([tT])?([a-zA-Z%])";
43  
44      private static final Pattern MSG_PATTERN = Pattern.compile(FORMAT_SPECIFIER);
45  
46      private String messagePattern;
47      private transient Object[] argArray;
48      private String[] stringArgs;
49      private transient String formattedMessage;
50      private final Throwable throwable;
51  
52      private Message message;
53  
54      public FormattedMessage(final String messagePattern, final Object[] arguments, final Throwable throwable) {
55          this.messagePattern = messagePattern;
56          this.argArray = arguments;
57          this.throwable = throwable;
58      }
59  
60      public FormattedMessage(final String messagePattern, final Object[] arguments) {
61          this.messagePattern = messagePattern;
62          this.argArray = arguments;
63          this.throwable = null;
64      }
65  
66      /**
67       * Constructor with a pattern and a single parameter.
68       * @param messagePattern The message pattern.
69       * @param arg The parameter.
70       */
71      public FormattedMessage(final String messagePattern, final Object arg) {
72          this.messagePattern = messagePattern;
73          this.argArray = new Object[] {arg};
74          this.throwable = null;
75      }
76  
77      /**
78       * Constructor with a pattern and two parameters.
79       * @param messagePattern The message pattern.
80       * @param arg1 The first parameter.
81       * @param arg2 The second parameter.
82       */
83      public FormattedMessage(final String messagePattern, final Object arg1, final Object arg2) {
84          this(messagePattern, new Object[]{arg1, arg2});
85      }
86  
87  
88      /**
89       * Returns the formatted message.
90       * @return the formatted message.
91       */
92      public String getFormattedMessage() {
93          if (formattedMessage == null) {
94              if (message == null) {
95                  message = getMessage(messagePattern, argArray, throwable);
96              }
97              formattedMessage = message.getFormattedMessage();
98          }
99          return formattedMessage;
100     }
101 
102     /**
103      * Returns the message pattern.
104      * @return the message pattern.
105      */
106     public String getFormat() {
107         return messagePattern;
108     }
109 
110     /**
111      * Returns the message parameters.
112      * @return the message parameters.
113      */
114     public Object[] getParameters() {
115         if (argArray != null) {
116             return argArray;
117         }
118         return stringArgs;
119     }
120 
121     protected Message getMessage(final String msgPattern, final Object[] args, final Throwable throwable) {
122         try {
123             final MessageFormat format = new MessageFormat(msgPattern);
124             final Format[] formats = format.getFormats();
125             if (formats != null && formats.length > 0) {
126                 return new MessageFormatMessage(msgPattern, args);
127             }
128         } catch (final Exception ex) {
129             // Obviously, the message is not a proper pattern for MessageFormat.
130         }
131         try {
132             if (MSG_PATTERN.matcher(msgPattern).find()) {
133                 return new StringFormattedMessage(msgPattern, args);
134             }
135         } catch (final Exception ex) {
136             // Also not properly formatted.
137         }
138         return new ParameterizedMessage(msgPattern, args, throwable);
139     }
140 
141     @Override
142     public boolean equals(final Object o) {
143         if (this == o) {
144             return true;
145         }
146         if (o == null || getClass() != o.getClass()) {
147             return false;
148         }
149 
150         final FormattedMessage that = (FormattedMessage) o;
151 
152         if (messagePattern != null ? !messagePattern.equals(that.messagePattern) : that.messagePattern != null) {
153             return false;
154         }
155         if (!Arrays.equals(stringArgs, that.stringArgs)) {
156             return false;
157         }
158 
159         return true;
160     }
161 
162     @Override
163     public int hashCode() {
164         int result = messagePattern != null ? messagePattern.hashCode() : 0;
165         result = HASHVAL * result + (stringArgs != null ? Arrays.hashCode(stringArgs) : 0);
166         return result;
167     }
168 
169 
170     @Override
171     public String toString() {
172         return "FormattedMessage[messagePattern=" + messagePattern + ", args=" +
173             Arrays.toString(argArray) +  "]";
174     }
175 
176     private void writeObject(final ObjectOutputStream out) throws IOException {
177         out.defaultWriteObject();
178         getFormattedMessage();
179         out.writeUTF(formattedMessage);
180         out.writeUTF(messagePattern);
181         out.writeInt(argArray.length);
182         stringArgs = new String[argArray.length];
183         int i = 0;
184         for (final Object obj : argArray) {
185             stringArgs[i] = obj.toString();
186             ++i;
187         }
188     }
189 
190     private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
191         in.defaultReadObject();
192         formattedMessage = in.readUTF();
193         messagePattern = in.readUTF();
194         final int length = in.readInt();
195         stringArgs = new String[length];
196         for (int i = 0; i < length; ++i) {
197             stringArgs[i] = in.readUTF();
198         }
199     }
200 
201     /**
202      * Always returns null.
203      *
204      * @return null
205      */
206     public Throwable getThrowable() {
207         if (throwable != null) {
208             return throwable;
209         }
210         if (message == null) {
211             message = getMessage(messagePattern, argArray, throwable);
212         }
213         return message.getThrowable();
214     }
215 }