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: package org.apache.harmony.nio.tests.java.nio;
19:
20: import java.io.File;
21: import java.io.FileInputStream;
22: import java.io.FileOutputStream;
23: import java.io.IOException;
24: import java.nio.ByteBuffer;
25: import java.nio.IntBuffer;
26: import java.nio.MappedByteBuffer;
27: import java.nio.channels.FileChannel;
28:
29: import junit.framework.TestCase;
30:
31: public class MappedByteBufferTest extends TestCase {
32:
33: /**
34: * A regression test for failing to correctly set capacity of underlying
35: * wrapped buffer from a mapped byte buffer.
36: */
37: public void testasIntBuffer() throws IOException {
38: // Create temp file with 26 bytes and 5 ints
39: File tmpFile = File.createTempFile("harmony", "test"); //$NON-NLS-1$//$NON-NLS-2$
40: tmpFile.deleteOnExit();
41: FileOutputStream fileOutputStream = new FileOutputStream(
42: tmpFile);
43: FileChannel fileChannel = fileOutputStream.getChannel();
44: ByteBuffer byteBuffer = ByteBuffer.allocateDirect(26 + 20);
45: for (int i = 0; i < 26; i++) {
46: byteBuffer.put((byte) ('A' + i));
47: }
48: for (int i = 0; i < 5; i++) {
49: byteBuffer.putInt(i + 1);
50: }
51: byteBuffer.rewind();
52: fileChannel.write(byteBuffer);
53: fileChannel.close();
54: fileOutputStream.close();
55:
56: // Map file
57: FileInputStream fis = new FileInputStream(tmpFile);
58: FileChannel fc = fis.getChannel();
59: MappedByteBuffer mmb = fc.map(FileChannel.MapMode.READ_ONLY, 0,
60: fc.size());
61: int len = mmb.capacity();
62: assertEquals("Got wrong number of bytes", 46, len); //$NON-NLS-1$
63:
64: // Read in our 26 bytes
65: for (int i = 0; i < 26; i++) {
66: byte b = mmb.get();
67: assertEquals("Got wrong byte value", (byte) 'A' + i, b); //$NON-NLS-1$
68: }
69:
70: // Now convert to an IntBuffer to read our ints
71: IntBuffer ibuffer = mmb.asIntBuffer();
72: for (int i = 0; i < 5; i++) {
73: int val = ibuffer.get();
74: assertEquals("Got wrong int value", i + 1, val); //$NON-NLS-1$
75: }
76: }
77: }
|