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.*; 021import org.apache.juneau.http.*; 022 023/** 024 * An encapsulated MessageFormat-style string and arguments. 025 * 026 * <p> 027 * Useful for delayed serialization of arguments for logging. 028 * Message string will not be constructed until the <code>toString()</code> method is called. 029 */ 030public class StringMessage implements CharSequence, Writable { 031 032 private final String pattern; 033 private final Object[] args; 034 private String results; 035 036 /** 037 * Constructor. 038 * 039 * @param pattern {@link MessageFormat}-style pattern. 040 * @param args Message arguments. 041 */ 042 public StringMessage(String pattern, Object...args) { 043 this.pattern = pattern; 044 this.args = args; 045 } 046 047 @Override /* Writable */ 048 public Writer writeTo(Writer w) throws IOException { 049 w.write(toString()); 050 return w; 051 } 052 053 @Override /* Writable */ 054 public MediaType getMediaType() { 055 // TODO Auto-generated method stub 056 return null; 057 } 058 059 @Override /* CharSequence */ 060 public char charAt(int index) { 061 return toString().charAt(index); 062 } 063 064 @Override /* CharSequence */ 065 public int length() { 066 return toString().length(); 067 } 068 069 @Override /* CharSequence */ 070 public CharSequence subSequence(int start, int end) { 071 return toString().subSequence(start, end); 072 } 073 074 @Override /* Object */ 075 public String toString() { 076 if (results == null) 077 results = format(pattern, args); 078 return results; 079 } 080}