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.component.mina;
018
019 import java.io.IOException;
020 import java.io.InputStream;
021 import java.io.ObjectInput;
022 import java.io.ObjectInputStream;
023
024 import org.apache.camel.Converter;
025 import org.apache.camel.Exchange;
026 import org.apache.mina.common.ByteBuffer;
027
028 /**
029 * A set of converter methods for working with MINA types
030 *
031 * @version $Revision: 19494 $
032 */
033 @Converter
034 public final class MinaConverter {
035
036 private MinaConverter() {
037 //Utility Class
038 }
039
040 @Converter
041 public static byte[] toByteArray(ByteBuffer buffer) {
042 buffer.mark();
043 try {
044 byte[] answer = new byte[buffer.remaining()];
045 buffer.get(answer);
046 return answer;
047 } finally {
048 buffer.reset();
049 }
050 }
051
052 @Converter
053 public static String toString(ByteBuffer buffer, Exchange exchange) {
054 byte[] bytes = toByteArray(buffer);
055 // use type converter as it can handle encoding set on the Exchange
056 return exchange.getContext().getTypeConverter().convertTo(String.class, exchange, bytes);
057 }
058
059 @Converter
060 public static InputStream toInputStream(ByteBuffer buffer) {
061 return buffer.asInputStream();
062 }
063
064 @Converter
065 public static ObjectInput toObjectInput(ByteBuffer buffer) throws IOException {
066 InputStream is = toInputStream(buffer);
067 return new ObjectInputStream(is);
068 }
069
070 @Converter
071 public static ByteBuffer toByteBuffer(byte[] bytes) {
072 ByteBuffer buf = ByteBuffer.allocate(bytes.length);
073 buf.put(bytes);
074 return buf;
075 }
076 }