1 /**
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18 package org.apache.hadoop.hbase.protobuf;
19
20 import java.io.IOException;
21
22 import org.apache.hadoop.hbase.util.Bytes;
23
24 /**
25 * Protobufs utility.
26 */
27 @SuppressWarnings("deprecation")
28 public final class ProtobufUtil {
29
30 private ProtobufUtil() {
31 }
32
33 /**
34 * Magic we put ahead of a serialized protobuf message.
35 * For example, all znode content is protobuf messages with the below magic
36 * for preamble.
37 */
38 public static final byte [] PB_MAGIC = new byte [] {'P', 'B', 'U', 'F'};
39 private static final String PB_MAGIC_STR = Bytes.toString(PB_MAGIC);
40
41 /**
42 * Prepend the passed bytes with four bytes of magic, {@link #PB_MAGIC}, to flag what
43 * follows as a protobuf in hbase. Prepend these bytes to all content written to znodes, etc.
44 * @param bytes Bytes to decorate
45 * @return The passed <code>bytes</codes> with magic prepended (Creates a new
46 * byte array that is <code>bytes.length</code> plus {@link #PB_MAGIC}.length.
47 */
48 public static byte [] prependPBMagic(final byte [] bytes) {
49 return Bytes.add(PB_MAGIC, bytes);
50 }
51
52 /**
53 * @param bytes Bytes to check.
54 * @return True if passed <code>bytes</code> has {@link #PB_MAGIC} for a prefix.
55 */
56 public static boolean isPBMagicPrefix(final byte [] bytes) {
57 if (bytes == null || bytes.length < PB_MAGIC.length) return false;
58 return Bytes.compareTo(PB_MAGIC, 0, PB_MAGIC.length, bytes, 0, PB_MAGIC.length) == 0;
59 }
60
61 /**
62 * @return Length of {@link #PB_MAGIC}
63 */
64 public static int lengthOfPBMagic() {
65 return PB_MAGIC.length;
66 }
67 }