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