001 /* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache license, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the license for the specific language governing permissions and 015 * limitations under the license. 016 */ 017 package org.apache.logging.log4j.message; 018 019 import java.io.IOException; 020 import java.io.ObjectInputStream; 021 import java.io.ObjectOutputStream; 022 import java.io.Serializable; 023 024 /** 025 * Handles messages that contain an Object. 026 */ 027 public class ObjectMessage implements Message, Serializable { 028 029 private static final long serialVersionUID = -5903272448334166185L; 030 031 private transient Object obj; 032 033 /** 034 * Create the ObjectMessage. 035 * @param obj The Object to format. 036 */ 037 public ObjectMessage(Object obj) { 038 if (obj == null) { 039 obj = "null"; 040 } 041 this.obj = obj; 042 } 043 044 /** 045 * Returns the formatted object message. 046 * @return the formatted object message. 047 */ 048 public String getFormattedMessage() { 049 return obj.toString(); 050 } 051 052 /** 053 * Returns the object formatted using its toString method. 054 * @return the String representation of the object. 055 */ 056 public String getFormat() { 057 return obj.toString(); 058 } 059 060 /** 061 * Returns the object as if it were a parameter. 062 * @return The object. 063 */ 064 public Object[] getParameters() { 065 return new Object[]{obj}; 066 } 067 068 @Override 069 public boolean equals(Object o) { 070 if (this == o) { 071 return true; 072 } 073 if (o == null || getClass() != o.getClass()) { 074 return false; 075 } 076 077 ObjectMessage that = (ObjectMessage) o; 078 079 return !(obj != null ? !obj.equals(that.obj) : that.obj != null); 080 } 081 082 @Override 083 public int hashCode() { 084 return obj != null ? obj.hashCode() : 0; 085 } 086 087 @Override 088 public String toString() { 089 return "ObjectMessage[obj=" + obj.toString() + "]"; 090 } 091 092 private void writeObject(ObjectOutputStream out) throws IOException { 093 out.defaultWriteObject(); 094 if (obj instanceof Serializable) { 095 out.writeObject(obj); 096 } else { 097 out.writeObject(obj.toString()); 098 } 099 } 100 101 private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { 102 in.defaultReadObject(); 103 obj = in.readObject(); 104 } 105 }