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 */ 017package org.apache.camel.impl; 018 019import java.io.IOException; 020import java.io.InputStream; 021import java.io.OutputStream; 022 023import org.apache.camel.Exchange; 024import org.apache.camel.spi.DataFormat; 025import org.apache.camel.spi.DataFormatName; 026import org.apache.camel.util.ExchangeHelper; 027 028/** 029 * The text based <a href="http://camel.apache.org/data-format.html">data format</a> supporting 030 * charset encoding. 031 * 032 * @version 033 */ 034public class StringDataFormat extends org.apache.camel.support.ServiceSupport implements DataFormat, DataFormatName { 035 036 private String charset; 037 038 public StringDataFormat() { 039 } 040 041 public StringDataFormat(String charset) { 042 this.charset = charset; 043 } 044 045 @Override 046 public String getDataFormatName() { 047 return "string"; 048 } 049 050 public String getCharset() { 051 return charset; 052 } 053 054 public void setCharset(String charset) { 055 this.charset = charset; 056 } 057 058 public void marshal(Exchange exchange, Object graph, OutputStream stream) throws IOException { 059 String text = ExchangeHelper.convertToType(exchange, String.class, graph); 060 061 byte[] bytes; 062 if (charset != null) { 063 bytes = text.getBytes(charset); 064 } else { 065 bytes = text.getBytes(); 066 } 067 stream.write(bytes); 068 } 069 070 public Object unmarshal(Exchange exchange, InputStream stream) throws IOException { 071 byte[] bytes = ExchangeHelper.convertToType(exchange, byte[].class, stream); 072 073 String answer; 074 if (charset != null) { 075 answer = new String(bytes, charset); 076 } else { 077 answer = new String(bytes); 078 } 079 080 return answer; 081 } 082 083 @Override 084 protected void doStart() throws Exception { 085 // noop 086 } 087 088 @Override 089 protected void doStop() throws Exception { 090 // noop 091 } 092}