01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * 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:
18: /**
19: * @author Alexander Y. Kleymenov
20: * @version $Revision$
21: */package org.apache.harmony.xnet.provider.jsse;
22:
23: import java.nio.ByteBuffer;
24:
25: /**
26: * This class provides the DataStream functionality
27: * implemented over the array of ByteBuffer instances.
28: * Among with the data chunks read functionality
29: * it provides the info about amount of consumed data.
30: * The source ByteBuffer objects can be replaced by other.
31: * So one instance of this wrapper can be reused for several
32: * data sources.
33: */
34: public class SSLEngineDataStream implements DataStream {
35:
36: private ByteBuffer[] srcs;
37: private int offset;
38: private int limit;
39:
40: private int available;
41: private int consumed;
42:
43: protected SSLEngineDataStream() {
44: }
45:
46: protected void setSourceBuffers(ByteBuffer[] srcs, int offset,
47: int length) {
48: this .srcs = srcs;
49: this .offset = offset;
50: this .limit = offset + length;
51: this .consumed = 0;
52: this .available = 0;
53: for (int i = offset; i < limit; i++) {
54: if (srcs[i] == null) {
55: throw new IllegalStateException(
56: "Some of the input parameters are null");
57: }
58: available += srcs[i].remaining();
59: }
60: }
61:
62: public int available() {
63: return available;
64: }
65:
66: public boolean hasData() {
67: return available > 0;
68: }
69:
70: public byte[] getData(int length) {
71: // TODO: optimization work:
72: // use ByteBuffer.get(byte[],int,int)
73: // and ByteBuffer.hasArray() methods
74: int len = (length < available) ? length : available;
75: available -= len;
76: consumed += len;
77: byte[] res = new byte[len];
78: int pos = 0;
79: loop: for (; offset < limit; offset++) {
80: while (srcs[offset].hasRemaining()) {
81: res[pos++] = srcs[offset].get();
82: len--;
83: if (len == 0) {
84: break loop;
85: }
86: }
87: }
88: return res;
89: }
90:
91: protected int consumed() {
92: return consumed;
93: }
94: }
|