001// *************************************************************************************************************************** 002// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * 003// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * 004// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * 005// * with the License. You may obtain a copy of the License at * 006// * * 007// * http://www.apache.org/licenses/LICENSE-2.0 * 008// * * 009// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * 010// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * 011// * specific language governing permissions and limitations under the License. * 012// *************************************************************************************************************************** 013package org.apache.juneau.utils; 014 015import static org.apache.juneau.internal.StringUtils.*; 016 017import java.io.*; 018import java.text.*; 019 020import org.apache.juneau.*; 021 022/** 023 * An encapsulated MessageFormat-style string and arguments. 024 * 025 * <p> 026 * Useful for delayed serialization of arguments for logging. 027 * Message string will not be constructed until the <c>toString()</c> method is called. 028 */ 029public class StringMessage implements CharSequence, Writable { 030 031 private final String pattern; 032 private final Object[] args; 033 private String results; 034 035 /** 036 * Constructor. 037 * 038 * @param pattern {@link MessageFormat}-style pattern. 039 * @param args Message arguments. 040 */ 041 public StringMessage(String pattern, Object...args) { 042 this.pattern = pattern; 043 this.args = args; 044 } 045 046 @Override /* Writable */ 047 public Writer writeTo(Writer w) throws IOException { 048 w.write(toString()); 049 return w; 050 } 051 052 @Override /* Writable */ 053 public String getMediaType() { 054 return null; 055 } 056 057 @Override /* CharSequence */ 058 public char charAt(int index) { 059 return toString().charAt(index); 060 } 061 062 @Override /* CharSequence */ 063 public int length() { 064 return toString().length(); 065 } 066 067 @Override /* CharSequence */ 068 public CharSequence subSequence(int start, int end) { 069 return toString().subSequence(start, end); 070 } 071 072 @Override /* Object */ 073 public String toString() { 074 if (results == null) 075 results = format(pattern, args); 076 return results; 077 } 078}