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.camel.impl; 018 019 import java.util.HashMap; 020 import java.util.Map; 021 022 import org.apache.camel.Message; 023 024 /** 025 * The default implementation of {@link Message} 026 * 027 * @version $Revision: 640438 $ 028 */ 029 public class DefaultMessage extends MessageSupport { 030 private Map<String, Object> headers; 031 032 @Override 033 public String toString() { 034 return "Message: " + getBody(); 035 } 036 037 public Object getHeader(String name) { 038 return getHeaders().get(name); 039 } 040 041 public <T> T getHeader(String name, Class<T> type) { 042 Object value = getHeader(name); 043 return getExchange().getContext().getTypeConverter().convertTo(type, value); 044 } 045 046 public void setHeader(String name, Object value) { 047 if (headers == null) { 048 headers = createHeaders(); 049 } 050 headers.put(name, value); 051 } 052 053 public Object removeHeader(String name) { 054 if (headers != null) { 055 return headers.remove(name); 056 } else { 057 return null; 058 } 059 } 060 061 public Map<String, Object> getHeaders() { 062 if (headers == null) { 063 headers = createHeaders(); 064 } 065 return headers; 066 } 067 068 public void setHeaders(Map<String, Object> headers) { 069 this.headers = headers; 070 } 071 072 public DefaultMessage newInstance() { 073 return new DefaultMessage(); 074 } 075 076 /** 077 * A factory method to lazily create the headers to make it easy to create 078 * efficient Message implementations which only construct and populate the 079 * Map on demand 080 * 081 * @return return a newly constructed Map possibly containing headers from 082 * the underlying inbound transport 083 */ 084 protected Map<String, Object> createHeaders() { 085 HashMap<String, Object> map = new HashMap<String, Object>(); 086 populateInitialHeaders(map); 087 return map; 088 } 089 090 /** 091 * A strategy method populate the initial set of headers on an inbound 092 * message from an underlying binding 093 * 094 * @param map is the empty header map to populate 095 */ 096 protected void populateInitialHeaders(Map<String, Object> map) { 097 } 098 }