001 /** 002 * 003 * Licensed to the Apache Software Foundation (ASF) under one or more 004 * contributor license agreements. See the NOTICE file distributed with 005 * this work for additional information regarding copyright ownership. 006 * The ASF licenses this file to You under the Apache License, Version 2.0 007 * (the "License"); you may not use this file except in compliance with 008 * the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018 package org.apache.camel.impl; 019 020 import org.apache.camel.Message; 021 022 import java.util.HashMap; 023 import java.util.Map; 024 025 /** 026 * The default implementation of {@link Message} 027 * 028 * @version $Revision: 540969 $ 029 */ 030 public class DefaultMessage extends MessageSupport { 031 private Map<String, Object> headers; 032 033 @Override 034 public String toString() { 035 return "Message: " + getBody(); 036 } 037 038 public Object getHeader(String name) { 039 return getHeaders().get(name); 040 } 041 042 public <T> T getHeader(String name, Class<T> type) { 043 Object value = getHeader(name); 044 return getExchange().getContext().getTypeConverter().convertTo(type, value); 045 } 046 047 public void setHeader(String name, Object value) { 048 if (headers == null) { 049 headers = createHeaders(); 050 } 051 headers.put(name, value); 052 } 053 054 public Map<String, Object> getHeaders() { 055 if (headers == null) { 056 headers = createHeaders(); 057 } 058 return headers; 059 } 060 061 public void setHeaders(Map<String, Object> headers) { 062 this.headers = headers; 063 } 064 065 public DefaultMessage newInstance() { 066 return new DefaultMessage(); 067 } 068 069 /** 070 * A factory method to lazily create the headers to make it easy to create efficient Message implementations 071 * which only construct and populate the Map on demand 072 * 073 * @return return a newly constructed Map possibly containing headers from the underlying inbound transport 074 */ 075 protected Map<String, Object> createHeaders() { 076 HashMap<String, Object> map = new HashMap<String, Object>(); 077 populateInitialHeaders(map); 078 return map; 079 } 080 081 /** 082 * A strategy method populate the initial set of headers on an inbound message from an underlying binding 083 * 084 * @param map is the empty header map to populate 085 */ 086 protected void populateInitialHeaders(Map<String, Object> map) { 087 } 088 }