This project has retired. For details please refer to its Attic page.
ByteArrayRequest xref
View Javadoc

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  
19  package org.apache.giraph.comm.requests;
20  
21  import org.apache.giraph.utils.UnsafeByteArrayInputStream;
22  
23  import java.io.ByteArrayInputStream;
24  import java.io.DataInput;
25  import java.io.DataInputStream;
26  import java.io.DataOutput;
27  import java.io.IOException;
28  
29  /**
30   * Abstract request which has a byte array as its data
31   */
32  public abstract class ByteArrayRequest extends WritableRequest {
33    /** Request data */
34    private byte[] data;
35  
36    /**
37     * Constructor
38     *
39     * @param data Request data
40     */
41    ByteArrayRequest(byte[] data) {
42      this.data = data;
43    }
44  
45    /**
46     * Constructor used for reflection only
47     */
48    ByteArrayRequest() {
49    }
50  
51    /**
52     * Get request data
53     *
54     * @return Request data
55     */
56    public byte[] getData() {
57      return data;
58    }
59  
60    /**
61     * Get request data in the form of {@link DataInput}
62     *
63     * @return Request data as {@link DataInput}
64     */
65    public DataInput getDataInput() {
66      return new DataInputStream(new ByteArrayInputStream(data));
67    }
68  
69    /**
70     * Wraps the byte array with UnsafeByteArrayInputStream stream.
71     * @return UnsafeByteArrayInputStream
72     */
73    public UnsafeByteArrayInputStream getUnsafeByteArrayInput() {
74      return new UnsafeByteArrayInputStream(data);
75    }
76  
77    @Override
78    void readFieldsRequest(DataInput input) throws IOException {
79      int dataLength = input.readInt();
80      data = new byte[dataLength];
81      input.readFully(data);
82    }
83  
84    @Override
85    void writeRequest(DataOutput output) throws IOException {
86      output.writeInt(data.length);
87      output.write(data);
88    }
89  
90    @Override
91    public int getSerializedSize() {
92      // 4 for the length of data, plus number of data bytes
93      return super.getSerializedSize() + 4 + data.length;
94    }
95  }