View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.accumulo.core.util;
18  
19  import java.nio.ByteBuffer;
20  import java.util.ArrayList;
21  import java.util.Arrays;
22  import java.util.Collection;
23  import java.util.List;
24  
25  import org.apache.hadoop.io.Text;
26  
27  public class ByteBufferUtil {
28    public static byte[] toBytes(ByteBuffer buffer) {
29      if (buffer == null)
30        return null;
31      return Arrays.copyOfRange(buffer.array(), buffer.position(), buffer.limit());
32    }
33    
34    public static List<ByteBuffer> toByteBuffers(Collection<byte[]> bytesList) {
35      if (bytesList == null)
36        return null;
37      ArrayList<ByteBuffer> result = new ArrayList<ByteBuffer>();
38      for (byte[] bytes : bytesList) {
39        result.add(ByteBuffer.wrap(bytes));
40      }
41      return result;
42    }
43    
44    public static List<byte[]> toBytesList(Collection<ByteBuffer> bytesList) {
45      if (bytesList == null)
46        return null;
47      ArrayList<byte[]> result = new ArrayList<byte[]>();
48      for (ByteBuffer bytes : bytesList) {
49        result.add(toBytes(bytes));
50      }
51      return result;
52    }
53    
54    public static Text toText(ByteBuffer bytes) {
55      if (bytes == null)
56        return null;
57      Text result = new Text();
58      result.set(bytes.array(), bytes.position(), bytes.remaining());
59      return result;
60    }
61    
62    public static String toString(ByteBuffer bytes) {
63      return new String(bytes.array(), bytes.position(), bytes.remaining());
64    }
65  }