diff options
author | The Android Open Source Project <initial-contribution@android.com> | 2009-03-03 18:28:14 -0800 |
---|---|---|
committer | The Android Open Source Project <initial-contribution@android.com> | 2009-03-03 18:28:14 -0800 |
commit | 1c0fed63c71ddb230f3b304aac12caffbedf2f21 (patch) | |
tree | 4b825dc642cb6eb9a060e54bf8d69288fbee4904 /nio/src/main/java/org | |
parent | 2fb02ef3025449e24e756a7f645ea6eab7a1fd4f (diff) | |
download | libcore-1c0fed63c71ddb230f3b304aac12caffbedf2f21.zip libcore-1c0fed63c71ddb230f3b304aac12caffbedf2f21.tar.gz libcore-1c0fed63c71ddb230f3b304aac12caffbedf2f21.tar.bz2 |
auto import from //depot/cupcake/@135843
Diffstat (limited to 'nio/src/main/java/org')
21 files changed, 0 insertions, 4969 deletions
diff --git a/nio/src/main/java/org/apache/harmony/nio/AddressUtil.java b/nio/src/main/java/org/apache/harmony/nio/AddressUtil.java deleted file mode 100644 index 7c094e7..0000000 --- a/nio/src/main/java/org/apache/harmony/nio/AddressUtil.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Android Notice - * In this class the address length was changed from long to int. - * This is due to performance optimizations for the device. - */ - -package org.apache.harmony.nio; - -import java.io.FileDescriptor; -import java.nio.Buffer; -import java.nio.channels.Channel; - -import org.apache.harmony.luni.platform.FileDescriptorHandler; -import org.apache.harmony.nio.internal.DirectBuffer; -import org.apache.harmony.nio.internal.FileChannelImpl; - -public class AddressUtil { - - /** - * Gets the start address of a direct buffer. - * <p> - * This method corresponds to the JNI function: - * - * <pre> - * void* GetDirectBufferAddress(JNIEnv* env, jobject buf); - * </pre> - * - * @param buf - * the direct buffer whose address shall be returned must not be - * <code>null</code>. - * @return the address of the buffer given, or zero if the buffer is not a - * direct Buffer. - */ - public static int getDirectBufferAddress(Buffer buf) { - if (!(buf instanceof DirectBuffer)) { - return 0; - } - return ((DirectBuffer) buf).getEffectiveAddress().toInt(); - } - - /** - * Gets the address of native resource held by the given channel, if has - * any. - * - * For network related channel, including SocketChannel, ServerSocketChannel - * and DatagramChannel, this method returns a int of Socket handler in Linux - * while returns a SOCKET (UINT_PTR) in windows. - * - * For FileChannel, this method returns the native file descriptor. - * - * For other channels, this method return 0, which means unsupported - * operation. - * - * @param channel - * the given channel which may holds a native resource address - * @return the address of native resource held by the given channel, if any, - * otherwise return 0 - */ - public static int getChannelAddress(Channel channel){ - if(channel instanceof FileDescriptorHandler){ - return getFDAddress(((FileDescriptorHandler) channel).getFD()); - }else if(channel instanceof FileChannelImpl){ - return ((FileChannelImpl) channel).getHandle(); - } - return 0; - } - - private static native int getFDAddress(FileDescriptor fd); -}
\ No newline at end of file diff --git a/nio/src/main/java/org/apache/harmony/nio/FileChannelFactory.java b/nio/src/main/java/org/apache/harmony/nio/FileChannelFactory.java deleted file mode 100644 index 5abe24a..0000000 --- a/nio/src/main/java/org/apache/harmony/nio/FileChannelFactory.java +++ /dev/null @@ -1,56 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Android Notice - * In this class the address length was changed from long to int. - * This is due to performance optimizations for the device. - */ - -package org.apache.harmony.nio; - - -import java.nio.channels.FileChannel; - -import org.apache.harmony.nio.internal.ReadOnlyFileChannel; -import org.apache.harmony.nio.internal.ReadWriteFileChannel; -import org.apache.harmony.nio.internal.WriteOnlyFileChannel; -import org.apache.harmony.nio.internal.nls.Messages; -import org.apache.harmony.luni.platform.IFileSystem; - -/** - * A simple factory to provide a generic way to create FileChannel - * implementation from within the java.io package. - */ -public class FileChannelFactory { - public static FileChannel getFileChannel(Object stream, int fd, int mode) { - switch(mode){ - case IFileSystem.O_RDONLY: - return new ReadOnlyFileChannel(stream, fd); - case IFileSystem.O_WRONLY: - return new WriteOnlyFileChannel(stream, fd); - case IFileSystem.O_RDWR: - return new ReadWriteFileChannel(stream, fd); - case IFileSystem.O_RDWRSYNC: - return new ReadWriteFileChannel(stream, fd); - case IFileSystem.O_APPEND: - return new WriteOnlyFileChannel(stream, fd, true); - default: - // nio.09=Unknown file channel type: {0} - throw new RuntimeException(Messages.getString("nio.09", mode)); //$NON-NLS-1$ - } - } -} diff --git a/nio/src/main/java/org/apache/harmony/nio/Util.java b/nio/src/main/java/org/apache/harmony/nio/Util.java deleted file mode 100644 index f895a51..0000000 --- a/nio/src/main/java/org/apache/harmony/nio/Util.java +++ /dev/null @@ -1,162 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.harmony.nio; - -import org.apache.harmony.nio.internal.nls.Messages; - -/* - * Static methods. Used by io and nio packages. - * - */ -public final class Util { - - // ------------------------------------------------------------------- - // Constructor - // ------------------------------------------------------------------- - - /* - * No instance. - */ - private Util() { - super(); - } - - // ------------------------------------------------------------------- - // Routine methods. - // ------------------------------------------------------------------- - - /* - * Check array bounds method for methods like doSomething(Object[], offset, - * length). Exception throws order is IndexOutOfBoundsException for negative - * index, NullPointerException for null array, IndexOutOfBoundsException for - * offset+length > array.length - */ - public static void assertArrayIndex(Object[] array, int offset, int length) { - if (offset < 0 || length < 0) { - // nio.05=Negative index specified - throw new IndexOutOfBoundsException(Messages.getString("nio.05")); //$NON-NLS-1$ - } - if ((long) offset + (long) length > array.length) { - // nio.04=Size mismatch - throw new IndexOutOfBoundsException(Messages.getString("nio.04")); //$NON-NLS-1$ - } - } - - public static void assertArrayIndex(boolean[] array, int offset, int length) { - if (offset < 0 || length < 0) { - // nio.05=Negative index specified - throw new IndexOutOfBoundsException(Messages.getString("nio.05")); //$NON-NLS-1$ - } - if ((long) offset + (long) length > array.length) { - // nio.04=Size mismatch - throw new IndexOutOfBoundsException(Messages.getString("nio.04")); //$NON-NLS-1$ - } - } - - public static void assertArrayIndex(byte[] array, int offset, int length) { - if (offset < 0 || length < 0) { - // nio.05=Negative index specified - throw new IndexOutOfBoundsException(Messages.getString("nio.05")); //$NON-NLS-1$ - } - if ((long) offset + (long) length > array.length) { - // nio.04=Size mismatch - throw new IndexOutOfBoundsException(Messages.getString("nio.04")); //$NON-NLS-1$ - } - } - - public static void assertArrayIndex(short[] array, int offset, int length) { - if (offset < 0 || length < 0) { - // nio.05=Negative index specified - throw new IndexOutOfBoundsException(Messages.getString("nio.05")); //$NON-NLS-1$ - } - if ((long) offset + (long) length > array.length) { - // nio.04=Size mismatch - throw new IndexOutOfBoundsException(Messages.getString("nio.04")); //$NON-NLS-1$ - } - } - - public static void assertArrayIndex(int[] array, int offset, int length) { - if (offset < 0 || length < 0) { - // nio.05=Negative index specified - throw new IndexOutOfBoundsException(Messages.getString("nio.05")); //$NON-NLS-1$ - } - if ((long) offset + (long) length > array.length) { - // nio.04=Size mismatch - throw new IndexOutOfBoundsException(Messages.getString("nio.04")); //$NON-NLS-1$ - } - } - - public static void assertArrayIndex(long[] array, int offset, int length) { - if (offset < 0 || length < 0) { - // nio.05=Negative index specified - throw new IndexOutOfBoundsException(Messages.getString("nio.05")); //$NON-NLS-1$ - } - if ((long) offset + (long) length > array.length) { - // nio.04=Size mismatch - throw new IndexOutOfBoundsException(Messages.getString("nio.04")); //$NON-NLS-1$ - } - } - - public static void assertArrayIndex(float[] array, int offset, int length) { - if (offset < 0 || length < 0) { - // nio.05=Negative index specified - throw new IndexOutOfBoundsException(Messages.getString("nio.05")); //$NON-NLS-1$ - } - if ((long) offset + (long) length > array.length) { - // nio.04=Size mismatch - throw new IndexOutOfBoundsException(Messages.getString("nio.04")); //$NON-NLS-1$ - } - } - - public static void assertArrayIndex(double[] array, int offset, int length) { - if (offset < 0 || length < 0) { - // nio.05=Negative index specified - throw new IndexOutOfBoundsException(Messages.getString("nio.05")); //$NON-NLS-1$ - } - if ((long) offset + (long) length > array.length) { - // nio.04=Size mismatch - throw new IndexOutOfBoundsException(Messages.getString("nio.04")); //$NON-NLS-1$ - } - } - - public static void assertArrayIndex(char[] array, int offset, int length) { - if (offset < 0 || length < 0) { - // nio.05=Negative index specified - throw new IndexOutOfBoundsException(Messages.getString("nio.05")); //$NON-NLS-1$ - } - if ((long) offset + (long) length > array.length) { - // nio.04=Size mismatch - throw new IndexOutOfBoundsException(Messages.getString("nio.04")); //$NON-NLS-1$ - } - } - - /* - * Check array bounds method for methods like doSomething(Object[], offset, - * length). Exception throws order is IndexOutOfBoundsException for negative - * index, IndexOutOfBoundsException for offset+length > array.length - */ - public static void assertArrayIndex(int arrayLength, int offset, int length) { - if (offset < 0 || length < 0) { - // nio.05=Negative index specified - throw new IndexOutOfBoundsException(Messages.getString("nio.05")); //$NON-NLS-1$ - } - if ((long) offset + (long) length > arrayLength) { - // nio.04=Size mismatch - throw new IndexOutOfBoundsException(Messages.getString("nio.04")); //$NON-NLS-1$ - } - } -} diff --git a/nio/src/main/java/org/apache/harmony/nio/internal/DatagramChannelImpl.java b/nio/src/main/java/org/apache/harmony/nio/internal/DatagramChannelImpl.java deleted file mode 100644 index ddd56e5..0000000 --- a/nio/src/main/java/org/apache/harmony/nio/internal/DatagramChannelImpl.java +++ /dev/null @@ -1,910 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Android Notice - * In this class the address length was changed from long to int. - * This is due to performance optimizations for the device. - */ - -package org.apache.harmony.nio.internal; - -import java.io.FileDescriptor; -import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.ConnectException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.DatagramSocketImpl; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.net.SocketException; -import java.nio.ByteBuffer; -import java.nio.channels.AlreadyConnectedException; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.DatagramChannel; -import java.nio.channels.IllegalBlockingModeException; -import java.nio.channels.NotYetConnectedException; -import java.nio.channels.spi.SelectorProvider; - -import org.apache.harmony.luni.net.NetUtil; -import org.apache.harmony.luni.net.SocketImplProvider; -import org.apache.harmony.luni.platform.FileDescriptorHandler; -import org.apache.harmony.luni.platform.INetworkSystem; -import org.apache.harmony.luni.platform.Platform; -import org.apache.harmony.luni.util.ErrorCodeException; -import org.apache.harmony.nio.AddressUtil; - -/* - * The default implementation class of java.nio.channels.DatagramChannel. - * - */ -class DatagramChannelImpl extends DatagramChannel implements - FileDescriptorHandler { - - // ------------------------------------------------------------------- - // Class variables - // ------------------------------------------------------------------- - - // The singleton to do the native network operation. - private static final INetworkSystem networkSystem = Platform - .getNetworkSystem(); - - // default timeout used to nonblocking mode. - private static final int DEFAULT_TIMEOUT = 1; - - private static final int ERRCODE_SOCKET_NONBLOCKING_WOULD_BLOCK = -211; - - private static final byte[] stubArray = new byte[0]; - - // ------------------------------------------------------------------- - // Instance variables - // ------------------------------------------------------------------- - - // The fd to interact with native code - private FileDescriptor fd; - - // Our internal DatagramSocket. - private DatagramSocket socket = null; - - // The address to be connected. - InetSocketAddress connectAddress = null; - - // local port - private int localPort; - - // At first, uninitialized. - boolean connected = false; - - // whether the socket is bound - boolean isBound = false; - - private final Object readLock = new Object(); - - private final Object writeLock = new Object(); - - // used to store the trafficClass value which is simply returned - // as the value that was set. We also need it to pass it to methods - // that specify an address packets are going to be sent to - private int trafficClass = 0; - - // ------------------------------------------------------------------- - // Constructor - // ------------------------------------------------------------------- - - /* - * Constructor - */ - protected DatagramChannelImpl(SelectorProvider selectorProvider) - throws IOException { - super(selectorProvider); - fd = new FileDescriptor(); - networkSystem.createDatagramSocket(fd, true); - } - - /* - * for native call - */ - private DatagramChannelImpl(){ - super(SelectorProvider.provider()); - fd = new FileDescriptor(); - connectAddress = new InetSocketAddress(0); - } - - // ------------------------------------------------------------------- - // Methods for getting internal DatagramSocket. - // ------------------------------------------------------------------- - - /* - * Getting the internal DatagramSocket If we have not the socket, we create - * a new one. - */ - @Override - synchronized public DatagramSocket socket() { - if (null == socket) { - socket = new DatagramSocketAdapter(SocketImplProvider - .getDatagramSocketImpl(fd, localPort), this); - } - return socket; - } - - /** - * Answer the local address from the IP stack. This method should not be - * called directly as it does not check the security policy. - * - * @return InetAddress the local address to which the socket is bound. - * @see DatagramSocket - */ - InetAddress getLocalAddress() { - return networkSystem.getSocketLocalAddress(fd, NetUtil - .preferIPv6Addresses()); - } - - // ------------------------------------------------------------------- - // Methods for connect and disconnect - // ------------------------------------------------------------------- - - /* - * - * @see java.nio.channels.DatagramChannel#isConnected() - */ - @Override - synchronized public boolean isConnected() { - return connected; - } - - /* - * - * @see java.nio.channels.DatagramChannel#connect(java.net.SocketAddress) - */ - @Override - synchronized public DatagramChannel connect(SocketAddress address) - throws IOException { - // must open - checkOpen(); - // status must be un-connected. - if (connected) { - throw new IllegalStateException(); - } - - // check the address - InetSocketAddress inetSocketAddress = SocketChannelImpl - .validateAddress(address); - - // security check - SecurityManager sm = System.getSecurityManager(); - if (null != sm) { - if (inetSocketAddress.getAddress().isMulticastAddress()) { - sm.checkMulticast(inetSocketAddress.getAddress()); - } else { - sm.checkConnect(inetSocketAddress.getAddress().getHostName(), - inetSocketAddress.getPort()); - } - } - - try { - begin(); - networkSystem.connectDatagram(fd, inetSocketAddress.getPort(), - trafficClass, inetSocketAddress.getAddress()); - } catch (ConnectException e) { - // ConnectException means connect fail, not exception - } finally { - end(true); - } - - // set the connected address. - connectAddress = inetSocketAddress; - connected = true; - isBound = true; - return this; - } - - /* - * - * @see java.nio.channels.DatagramChannel#disconnect() - */ - @Override - synchronized public DatagramChannel disconnect() throws IOException { - if (!isConnected() || !isOpen()) { - return this; - } - connected = false; - connectAddress = null; - networkSystem.disconnectDatagram(fd); - if (null != socket) { - socket.disconnect(); - } - return this; - } - - // ------------------------------------------------------------------- - // Methods for send and receive - // ------------------------------------------------------------------- - - /* - * - * @see java.nio.channels.DatagramChannel#receive(java.nio.ByteBuffer) - */ - @Override - public SocketAddress receive(ByteBuffer target) throws IOException { - // must not null and not readonly - checkWritable(target); - // must open - checkOpen(); - - if (!isBound) { - return null; - } - - SocketAddress retAddr = null; - try { - begin(); - - // receive real data packet, (not peek) - synchronized (readLock) { - boolean loop = isBlocking(); - if (!target.isDirect()) { - retAddr = receiveImpl(target, loop); - } else { - retAddr = receiveDirectImpl(target, loop); - } - } - } catch (InterruptedIOException e) { - // this line used in Linux - return null; - } finally { - end(null != retAddr); - } - return retAddr; - } - - private SocketAddress receiveImpl(ByteBuffer target, boolean loop) - throws IOException { - SocketAddress retAddr = null; - DatagramPacket receivePacket; - int oldposition = target.position(); - int received = 0; - if (target.hasArray()) { - receivePacket = new DatagramPacket(target.array(), target - .position() - + target.arrayOffset(), target.remaining()); - } else { - receivePacket = new DatagramPacket(new byte[target.remaining()], target.remaining()); - } - do { - if (isConnected()) { - received = networkSystem.recvConnectedDatagram(fd, receivePacket, - receivePacket.getData(), receivePacket.getOffset(), - receivePacket.getLength(), isBlocking() ? 0 - : DEFAULT_TIMEOUT, false); - } else { - received = networkSystem.receiveDatagram(fd, receivePacket, - receivePacket.getData(), receivePacket.getOffset(), - receivePacket.getLength(), isBlocking() ? 0 - : DEFAULT_TIMEOUT, false); - } - - // security check - SecurityManager sm = System.getSecurityManager(); - if (!isConnected() && null != sm) { - try { - sm.checkAccept(receivePacket.getAddress().getHostAddress(), - receivePacket.getPort()); - } catch (SecurityException e) { - // do discard the datagram packet - receivePacket = null; - } - } - if (null != receivePacket && null != receivePacket.getAddress()) { - - if (received > 0) { - if (target.hasArray()) { - target.position(oldposition + received); - } else { - // copy the data of received packet - target.put(receivePacket.getData(), 0, received); - } - } - retAddr = receivePacket.getSocketAddress(); - break; - } - } while (loop); - return retAddr; - } - - private SocketAddress receiveDirectImpl(ByteBuffer target, boolean loop) throws IOException - { - SocketAddress retAddr = null; - DatagramPacket receivePacket = new DatagramPacket( - stubArray, 0); - int oldposition = target.position(); - int received = 0; - do { - int address = AddressUtil.getDirectBufferAddress(target); - if (isConnected()) { - received = networkSystem.recvConnectedDatagramDirect(fd, receivePacket, - address, target.position(), - target.remaining(), isBlocking() ? 0 - : DEFAULT_TIMEOUT, false); - } else { - received = networkSystem.receiveDatagramDirect(fd, receivePacket, - address, target.position(), - target.remaining(), isBlocking() ? 0 - : DEFAULT_TIMEOUT, false); - } - - // security check - SecurityManager sm = System.getSecurityManager(); - if (!isConnected() && null != sm) { - try { - sm.checkAccept(receivePacket.getAddress() - .getHostAddress(), receivePacket.getPort()); - } catch (SecurityException e) { - // do discard the datagram packet - receivePacket = null; - } - } - if (null != receivePacket - && null != receivePacket.getAddress()) { - // copy the data of received packet - if (received > 0) { - target.position(oldposition + received); - } - retAddr = receivePacket.getSocketAddress(); - break; - } - } while (loop); - return retAddr; - } - - /* - * @see java.nio.channels.DatagramChannel#send(java.nio.ByteBuffer, - * java.net.SocketAddress) - */ - @Override - public int send(ByteBuffer source, SocketAddress socketAddress) - throws IOException { - // must not null - checkNotNull(source); - // must open - checkOpen(); - - // transfer socketAddress - InetSocketAddress isa = (InetSocketAddress) socketAddress; - if (null == isa.getAddress()) { - throw new IOException(); - } - - if (isConnected()) { - if (!connectAddress.equals(isa)) { - throw new IllegalArgumentException(); - } - } else { - // not connected, check security - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - if (isa.getAddress().isMulticastAddress()) { - sm.checkMulticast(isa.getAddress()); - } else { - sm.checkConnect(isa.getAddress().getHostAddress(), isa - .getPort()); - } - } - } - - // the return value. - int sendCount = 0; - try { - begin(); - byte[] array = null; - int length = source.remaining(); - int oldposition = source.position(); - int start = oldposition; - if (source.isDirect()) { - synchronized (writeLock) { - int data_address = AddressUtil - .getDirectBufferAddress(source); - sendCount = networkSystem.sendDatagramDirect(fd, - data_address, start, length, isa.getPort(), false, - trafficClass, isa.getAddress()); - } - } else { - if (source.hasArray()) { - array = source.array(); - start += source.arrayOffset(); - } else { - array = new byte[length]; - source.get(array); - start = 0; - } - synchronized (writeLock) { - sendCount = networkSystem.sendDatagram(fd, array, start, - length, isa.getPort(), false, trafficClass, isa - .getAddress()); - } - } - source.position(oldposition + sendCount); - return sendCount; - } finally { - end(sendCount >= 0); - } - } - - // ------------------------------------------------------------------- - // Methods for read and write. - // ------------------------------------------------------------------- - - /* - * - * @see java.nio.channels.DatagramChannel#read(java.nio.ByteBuffer) - */ - @Override - public int read(ByteBuffer target) throws IOException { - if (null == target) { - throw new NullPointerException(); - } - // status must be open and connected - checkOpenConnected(); - // target buffer must be not null and not readonly - checkWritable(target); - - if (!target.hasRemaining()) { - return 0; - } - - int readCount = 0; - if (target.isDirect() || target.hasArray()) { - readCount = readImpl(target); - if(readCount > 0){ - target.position(target.position() + readCount); - } - - } else { - byte[] readArray = new byte[target.remaining()]; - ByteBuffer readBuffer = ByteBuffer.wrap(readArray); - readCount = readImpl(readBuffer); - if(readCount > 0){ - target.put(readArray, 0, readCount); - } - } - return readCount; - } - - /* - * - * @see java.nio.channels.DatagramChannel#read(java.nio.ByteBuffer[], int, - * int) - */ - @Override - public long read(ByteBuffer[] targets, int offset, int length) - throws IOException { - if (length < 0 || offset < 0 - || (long) length + (long) offset > targets.length) { - throw new IndexOutOfBoundsException(); - } - - // status must be open and connected - checkOpenConnected(); - - int totalCount = 0; - for (int val = offset; val < length; val++) { - // target buffer must be not null and not readonly - checkWritable(targets[val]); - totalCount += targets[val].remaining(); - } - - // read data to readBuffer, and then transfer data from readBuffer to - // targets. - ByteBuffer readBuffer = ByteBuffer.allocate(totalCount); - int readCount; - readCount = readImpl(readBuffer); - int left = readCount; - int index = offset; - // transfer data from readBuffer to targets - byte[] readArray = readBuffer.array(); - while (left > 0) { - int putLength = Math.min(targets[index].remaining(), left); - targets[index].put(readArray, readCount - left, putLength); - index++; - left -= putLength; - } - return readCount; - } - - /* - * read from channel, and store the result in the target. - */ - private int readImpl(ByteBuffer readBuffer) throws IOException { - synchronized(readLock){ - int readCount = 0; - try { - begin(); - // timeout == 0 means block read. - // DEFAULT_TIMEOUT is used in non-block mode. - int timeout = isBlocking() ? 0 : DEFAULT_TIMEOUT; - int start = readBuffer.position(); - int length = readBuffer.remaining(); - if (readBuffer.isDirect()) { - int address = AddressUtil.getDirectBufferAddress(readBuffer); - if (isConnected()) { - readCount = networkSystem.recvConnectedDatagramDirect(fd, - null, address, start, length, timeout, false); - } else { - readCount = networkSystem.receiveDatagramDirect(fd, - null, address, start, length, timeout, false); - } - } else { - // the target is assured to have array. - byte[] target = readBuffer.array(); - start += readBuffer.arrayOffset(); - if (isConnected()) { - readCount = networkSystem.recvConnectedDatagram(fd, null, - target, start, length, timeout, false); - } else { - readCount = networkSystem.receiveDatagram(fd, null, target, - start, length, timeout, false); - } - } - return readCount; - } catch (InterruptedIOException e) { - // InterruptedIOException will be thrown when timeout. - return 0; - } finally { - end(readCount > 0); - } - } - } - - /* - * @see java.nio.channels.DatagramChannel#write(java.nio.ByteBuffer) - */ - @Override - public int write(ByteBuffer source) throws IOException { - // source buffer must be not null - checkNotNull(source); - // status must be open and connected - checkOpenConnected(); - // return immediately if source is full - if (!source.hasRemaining()) { - return 0; - } - - ByteBuffer writeBuffer = null; - byte[] writeArray = null; - int oldposition = source.position(); - int result; - if (source.isDirect() || source.hasArray()) { - writeBuffer = source; - } else { - writeArray = new byte[source.remaining()]; - source.get(writeArray); - writeBuffer = ByteBuffer.wrap(writeArray); - } - result = writeImpl(writeBuffer); - if (result > 0) { - source.position(oldposition + result); - } - return result; - } - - /* - * @see java.nio.channels.DatagramChannel#write(java.nio.ByteBuffer[], int, - * int) - */ - @Override - public long write(ByteBuffer[] sources, int offset, int length) - throws IOException { - if (length < 0 || offset < 0 - || (long) length + (long) offset > sources.length) { - throw new IndexOutOfBoundsException(); - } - - // status must be open and connected - checkOpenConnected(); - int count = calculateByteBufferArray(sources, offset, length); - if (0 == count) { - return 0; - } - ByteBuffer writeBuf = ByteBuffer.allocate(count); - for (int val = offset; val < length+offset; val++) { - ByteBuffer source = sources[val]; - int oldPosition = source.position(); - writeBuf.put(source); - source.position(oldPosition); - } - writeBuf.flip(); - int result = writeImpl(writeBuf); - int val = offset; - int written = result; - while (result > 0) { - ByteBuffer source = sources[val]; - int gap = Math.min(result, source.remaining()); - source.position(source.position() + gap); - val++; - result -= gap; - } - return written; - } - - /* - * write the source. return the count of bytes written. - */ - private int writeImpl(ByteBuffer buf) throws IOException { - synchronized(writeLock){ - int result = 0; - try { - begin(); - int length = buf.remaining(); - int start = buf.position(); - - if (buf.isDirect()) { - int address = AddressUtil.getDirectBufferAddress(buf); - result = networkSystem.sendConnectedDatagramDirect(fd, address, - start, length, isBound); - } else { - // buf is assured to have array. - start += buf.arrayOffset(); - result = networkSystem.sendConnectedDatagram(fd, buf.array(), - start, length, isBound); - } - return result; - } catch (SocketException e) { - if (e.getCause() instanceof ErrorCodeException) { - if (ERRCODE_SOCKET_NONBLOCKING_WOULD_BLOCK == ((ErrorCodeException) e - .getCause()).getErrorCode()) { - return result; - } - } - throw e; - } finally { - end(result > 0); - } - } - } - - // ------------------------------------------------------------------- - // Protected Inherited methods - // ------------------------------------------------------------------- - - /* - * do really closing action here - */ - @Override - synchronized protected void implCloseSelectableChannel() throws IOException { - connected = false; - if (null != socket && !socket.isClosed()) { - socket.close(); - } else { - networkSystem.socketClose(fd); - } - } - - /* - * - * @see java.nio.channels.spi.AbstractSelectableChannel#implConfigureBlocking(boolean) - */ - @Override - @SuppressWarnings("unused") - protected void implConfigureBlocking(boolean blockingMode) - throws IOException { - // Do nothing here. For real read/write operation in nonblocking mode, - // it uses select system call. Whether a channel is blocking can be - // decided by isBlocking() method. - } - - // ------------------------------------------------------------------- - // Share methods for checking. - // ------------------------------------------------------------------- - - /* - * status check, must be open. - */ - private void checkOpen() throws IOException { - if (!isOpen()) { - throw new ClosedChannelException(); - } - } - - /* - * status check, must be open and connected, for read and write. - */ - private void checkOpenConnected() throws IOException { - checkOpen(); - if (!isConnected()) { - throw new NotYetConnectedException(); - } - } - - /* - * buffer check, must not null - */ - private void checkNotNull(ByteBuffer source) { - if (null == source) { - throw new NullPointerException(); - } - } - - /* - * buffer check, must not null and not read only buffer, for read and - * receive. - */ - private void checkWritable(ByteBuffer target) { - // including checking of NPE. - if (target.isReadOnly()) { - throw new IllegalArgumentException(); - } - } - - // ------------------------------------------------------------------- - // Adapter classes for internal socket. - // ------------------------------------------------------------------- - - /* - * get the fd for internal use. - */ - public FileDescriptor getFD() { - return fd; - } - - private int calculateByteBufferArray(ByteBuffer[] sources, int offset, - int length) { - int sum = 0; - for (int val = offset; val < offset + length; val++) { - sum += sources[val].remaining(); - } - return sum; - } - - /* - * The adapter class of DatagramSocket - */ - private static class DatagramSocketAdapter extends DatagramSocket { - - /* - * The internal datagramChannelImpl. - */ - private DatagramChannelImpl channelImpl; - - /* - * init the datagramSocketImpl and datagramChannelImpl - */ - DatagramSocketAdapter(DatagramSocketImpl socketimpl, - DatagramChannelImpl channelImpl) { - super(socketimpl); - this.channelImpl = channelImpl; - } - - /* - * get the internal datagramChannelImpl - */ - @Override - public DatagramChannel getChannel() { - return channelImpl; - } - - /* - * @see java.net.DatagramSocket#isBound() - */ - @Override - public boolean isBound() { - return channelImpl.isBound; - } - - /* - * @see java.net.DatagramSocket#isConnected() - */ - @Override - public boolean isConnected() { - return channelImpl.isConnected(); - } - - /* - * @see java.net.DatagramSocket#getInetAddress() - */ - @Override - public InetAddress getInetAddress() { - if (null == channelImpl.connectAddress) { - return null; - } - return channelImpl.connectAddress.getAddress(); - } - - /* - * @see java.net.DatagramSocket#getLocalAddress() - */ - @Override - public InetAddress getLocalAddress() { - return channelImpl.getLocalAddress(); - } - - /* - * @see java.net.DatagramSocket#getPort() - */ - @Override - public int getPort() { - if (null == channelImpl.connectAddress) { - return -1; - } - return channelImpl.connectAddress.getPort(); - } - - /* - * @see java.net.DatagramSocket#bind(java.net.SocketAddress) - */ - @Override - public void bind(SocketAddress localAddr) throws SocketException { - if (channelImpl.isConnected()) { - throw new AlreadyConnectedException(); - } - super.bind(localAddr); - channelImpl.isBound = true; - } - - /* - * @see java.net.DatagramSocket#receive(java.net.DatagramPacket) - */ - @Override - public void receive(DatagramPacket packet) throws IOException { - if (!channelImpl.isBlocking()) { - throw new IllegalBlockingModeException(); - } - super.receive(packet); - } - - /* - * @see java.net.DatagramSocket#send(java.net.DatagramPacket) - */ - @Override - public void send(DatagramPacket packet) throws IOException { - if (!channelImpl.isBlocking()) { - throw new IllegalBlockingModeException(); - } - super.send(packet); - } - - /* - * @see java.net.DatagramSocket#close() - */ - @Override - public void close() { - synchronized (channelImpl) { - if (channelImpl.isOpen()) { - try { - channelImpl.close(); - } catch (IOException e) { - // Ignore - } - } - super.close(); - } - } - - /* - * @see java.net.DatagramSocket#disconnect() - */ - @Override - public void disconnect() { - try { - channelImpl.disconnect(); - } catch (IOException e) { - // Ignore - } - super.disconnect(); - } - } -} diff --git a/nio/src/main/java/org/apache/harmony/nio/internal/DirectBuffer.java b/nio/src/main/java/org/apache/harmony/nio/internal/DirectBuffer.java deleted file mode 100644 index 52a7b65..0000000 --- a/nio/src/main/java/org/apache/harmony/nio/internal/DirectBuffer.java +++ /dev/null @@ -1,35 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.harmony.nio.internal; - -import org.apache.harmony.luni.platform.PlatformAddress; - -public interface DirectBuffer { - // BEGIN android-changed - // Copied from a newer version of harmony - PlatformAddress getEffectiveAddress(); - - PlatformAddress getBaseAddress(); - - boolean isAddressValid(); - - void addressValidityCheck(); - - void free(); - - int getByteCapacity(); - // END android-changed -} diff --git a/nio/src/main/java/org/apache/harmony/nio/internal/FileChannelImpl.java b/nio/src/main/java/org/apache/harmony/nio/internal/FileChannelImpl.java deleted file mode 100644 index 687b438..0000000 --- a/nio/src/main/java/org/apache/harmony/nio/internal/FileChannelImpl.java +++ /dev/null @@ -1,660 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Android Notice - * In this class the address length was changed from long to int. - * This is due to performance optimizations for the device. - * - * Also this class was copied from a newer version of harmony. - */ - -package org.apache.harmony.nio.internal; - -import java.io.Closeable; -import java.io.FileDescriptor; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.MappedByteBuffer; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.FileChannel; -import java.nio.channels.FileLock; -import java.nio.channels.NonWritableChannelException; -import java.nio.channels.ReadableByteChannel; -import java.nio.channels.WritableByteChannel; - -import org.apache.harmony.luni.platform.IFileSystem; -import org.apache.harmony.luni.platform.Platform; -import org.apache.harmony.luni.platform.PlatformAddress; -import org.apache.harmony.luni.platform.PlatformAddressFactory; -import org.apache.harmony.nio.internal.nls.Messages; - -/* - * The file channel impl class is the bridge between the logical channels - * described by the NIO channel framework, and the file system implementation - * provided by the port layer. - * - * This class is non-API, but implements the API of the FileChannel interface. - * - */ -public abstract class FileChannelImpl extends FileChannel { - - // Reference to the portable file system code. - private static final IFileSystem fileSystem = Platform.getFileSystem(); - - private static final int ALLOC_GRANULARITY; - - static { - try { - ALLOC_GRANULARITY = fileSystem.getAllocGranularity(); - } catch (IOException e) { - throw new Error(e); - } - - } - - // Handle to the open file - private final int handle; - - // The object that will track all outstanding locks on this channel. - private final LockManager lockManager = new LockManager(); - - private class RepositioningLock {} - private final Object repositioningLock = new RepositioningLock(); - - private final Object stream; - - /* - * Create a new file channel implementation class that wraps the given file - * handle and operates in the specified mode. - * - */ - public FileChannelImpl(Object stream, int handle) { - super(); - this.handle = handle; - this.stream = stream; - } - - /* - * Helper method to throw an exception if the channel is already closed. - * Note that we don't bother to synchronize on this test since the file may - * be closed by operations beyond our control anyways. - */ - protected final void openCheck() throws ClosedChannelException { - if (!isOpen()) { - throw new ClosedChannelException(); - } - } - - /* - * (non-Javadoc) - * - * @see java.nio.channels.spi.AbstractInterruptibleChannel#implCloseChannel() - */ - protected void implCloseChannel() throws IOException { - if (stream instanceof Closeable) { - ((Closeable) stream).close(); - } - } - - protected FileLock basicLock(long position, long size, boolean shared, - boolean wait) throws IOException { - if ((position < 0) || (size < 0)) { - // nio.0A=Lock position and size must be non-negative. - throw new IllegalArgumentException( - Messages.getString("nio.0A")); //$NON-NLS-1$ - } - int lockType = shared ? IFileSystem.SHARED_LOCK_TYPE - : IFileSystem.EXCLUSIVE_LOCK_TYPE; - FileLock pendingLock = new FileLockImpl(this, position, size, shared); - lockManager.addLock(pendingLock); - - if (fileSystem.lock(handle, position, size, lockType, wait)) { - return pendingLock; - } - - // Lock acquisition failed - lockManager.removeLock(pendingLock); - return null; - } - - /* - * Acquire a lock on the receiver, blocks if the lock cannot be obtained - * immediately. - * - * @see java.nio.channels.FileChannel#lock(long, long, boolean) - */ - public final FileLock lock(long position, long size, boolean shared) - throws IOException { - openCheck(); - FileLock resultLock = null; - { - boolean completed = false; - try { - begin(); - resultLock = basicLock(position, size, shared, true); - completed = true; - } finally { - end(completed); - } - } - return resultLock; - } - - /* - * Attempts to acquire the given lock, but does not block. If the lock - * cannot be acquired the method returns null. - * - * @see java.nio.channels.FileChannel#tryLock(long, long, boolean) - */ - public final FileLock tryLock(long position, long size, boolean shared) - throws IOException { - openCheck(); - return basicLock(position, size, shared, false); - } - - /* - * Non-API method to release a given lock on a file channel. Assumes that - * the lock will mark itself invalid after successful unlocking. - */ - void release(FileLock lock) throws IOException { - openCheck(); - fileSystem.unlock(handle, lock.position(), lock.size()); - lockManager.removeLock(lock); - } - - /* - * Flush the contents of the file to disk, and the metadata if asked. - */ - public void force(boolean metadata) throws IOException { - openCheck(); - // Forcing data-only on a read-only file is a no-op. - if (metadata) { - fileSystem.fflush(handle, metadata); - } - } - - public abstract MappedByteBuffer map(MapMode mode, long position, long size) - throws IOException; - - protected final MappedByteBuffer mapImpl(int mapMode, long position, - long size) throws IOException { - if (position + size > size()) { - fileSystem.truncate(handle, position + size); - } - long alignment = position - position % ALLOC_GRANULARITY; - int offset = (int) (position - alignment); - PlatformAddress address = PlatformAddressFactory.allocMap(handle, alignment, size - + offset, mapMode); - MappedByteBuffer buffer = null; - try { - buffer = MappedByteBufferFactory.getBuffer(address, mapMode, size, - offset); - } catch (Exception e) { - throw new IOException(e.getMessage()); - } - return buffer; - } - - /* - * Returns the current file position. - */ - public long position() throws IOException { - openCheck(); - return fileSystem.seek(handle, 0L, IFileSystem.SEEK_CUR); - } - - /* - * Sets the file pointer. - */ - public FileChannel position(long newPosition) throws IOException { - openCheck(); - if (newPosition < 0) { - // nio.0B=New position must be non-negative. - throw new IllegalArgumentException( - Messages.getString("nio.0B")); //$NON-NLS-1$ - } - - synchronized (repositioningLock) { - fileSystem.seek(handle, newPosition, IFileSystem.SEEK_SET); - } - return this; - } - - public int read(ByteBuffer buffer, long position) throws IOException { - if (null == buffer){ - throw new NullPointerException(); - } - if (position < 0){ - throw new IllegalArgumentException(); - } - openCheck(); - if (!buffer.hasRemaining()){ - return 0; - } - synchronized (repositioningLock) { - int bytesRead = 0; - long preReadPosition = position(); - position(position); - try { - bytesRead = read(buffer); - } finally { - position(preReadPosition); - } - return bytesRead; - } - } - - public int read(ByteBuffer buffer) throws IOException { - openCheck(); - if (!buffer.hasRemaining()){ - return 0; - } - boolean completed = false; - int bytesRead = 0; - synchronized (repositioningLock) { - if (buffer.isDirect()) { - DirectBuffer directBuffer = (DirectBuffer) buffer; - int address = directBuffer.getEffectiveAddress().toInt(); - try { - begin(); - /* - * if (bytesRead <= EOF) delt by read completed = false; - */ - bytesRead = (int) fileSystem.readDirect(handle, address, - buffer.position(), buffer.remaining()); - completed = true; - } finally { - end(completed && bytesRead >= 0); - } - } else { - try { - begin(); - /* - * if (bytesRead <= EOF) delt by read completed = false; - */ - bytesRead = (int) fileSystem.read(handle, buffer.array(), - buffer.arrayOffset() + buffer.position(), buffer - .remaining()); - completed = true; - } finally { - end(completed && bytesRead >= 0); - } - } - if (bytesRead > 0) { - buffer.position(buffer.position() + bytesRead); - } - } - return bytesRead; - } - - public long read(ByteBuffer[] buffers, int offset, int length) - throws IOException { - int count = 0; - if (offset < 0 || length < 0 || offset + length > buffers.length) { - throw new IndexOutOfBoundsException(); - } - openCheck(); - for (int i = offset; i < offset + length; i++) { - count += buffers[i].remaining(); - } - if (0 == count) { - return 0; - } - if (size() == 0) { - return -1; - } - ByteBuffer[] directBuffers = new ByteBuffer[length]; - int[] handles = new int[length]; - int[] offsets = new int[length]; - int[] lengths = new int[length]; - for (int i = 0; i < length; i++) { - ByteBuffer buffer = buffers[i + offset]; - if (!buffer.isDirect()) { - buffer = ByteBuffer.allocateDirect(buffer.remaining()); - directBuffers[i] = buffer; - offsets[i] = 0; - } else { - offsets[i] = buffer.position(); - } - handles[i] = ((DirectBuffer) buffer).getEffectiveAddress().toInt(); - lengths[i] = buffer.remaining(); - } - long bytesRead = 0; - { - boolean completed = false; - try { - begin(); - synchronized (repositioningLock) { - bytesRead = fileSystem.readv(handle, handles, offsets, - lengths, length); - - } - completed = true; - /* - * if (bytesRead < EOF) //delt by readv? completed = false; - */ - } finally { - end(completed); - } - } - int end = offset + length; - long bytesRemaining = bytesRead; - for (int i = offset; i < end && bytesRemaining > 0; i++) { - if (buffers[i].isDirect()) { - if (lengths[i] < bytesRemaining) { - int pos = buffers[i].limit(); - buffers[i].position(pos); - bytesRemaining -= lengths[i]; - } else { - int pos = (int) bytesRemaining; - buffers[i].position(pos); - break; - } - } else { - ByteBuffer buf = directBuffers[i - offset]; - if (bytesRemaining < buf.remaining()){ - // this is the last step. - int pos = buf.position(); - buffers[i].put(buf); - buffers[i].position(pos + (int)bytesRemaining); - bytesRemaining = 0; - } else { - bytesRemaining -= buf.remaining(); - buffers[i].put(buf); - } - } - } - return bytesRead; - } - - /* - * Returns the current file size, as an integer number of bytes. - */ - public long size() throws IOException { - openCheck(); - synchronized (repositioningLock) { - long currentPosition = fileSystem.seek(handle, 0L, - IFileSystem.SEEK_CUR); - long endOfFilePosition = fileSystem.seek(handle, 0L, - IFileSystem.SEEK_END); - fileSystem.seek(handle, currentPosition, IFileSystem.SEEK_SET); - return endOfFilePosition; - } - } - - public long transferFrom(ReadableByteChannel src, long position, long count) - throws IOException { - openCheck(); - if (!src.isOpen()) { - throw new ClosedChannelException(); - } - if (position < 0 || count < 0 || position > Integer.MAX_VALUE - || count > Integer.MAX_VALUE) { - throw new IllegalArgumentException(); - } - if(position > size()) { - return 0; - } - - ByteBuffer buffer = null; - // BEGIN android-changed - try { - if (src instanceof FileChannel) { - FileChannel fileSrc = (FileChannel) src; - long size = fileSrc.size(); - long filePosition = fileSrc.position(); - count = Math.min(count, size - filePosition); - buffer = fileSrc.map(MapMode.READ_ONLY, filePosition, count); - fileSrc.position(filePosition + count); - } else { - buffer = ByteBuffer.allocateDirect((int) count); - src.read(buffer); - buffer.flip(); - } - return write(buffer, position); - } finally { - // unmap the buffer - if (buffer != null) { - // all children of FileChannelImpl currently returns - // an instance of DirectBuffer from map() method - ((DirectBuffer) buffer).free(); - } - } - // END android-changed - } - - public long transferTo(long position, long count, WritableByteChannel target) - throws IOException { - openCheck(); - if (!target.isOpen()) { - throw new ClosedChannelException(); - } - if (target instanceof ReadOnlyFileChannel) { - throw new NonWritableChannelException(); - } - if (position < 0 || count < 0 || position > Integer.MAX_VALUE - || count > Integer.MAX_VALUE) { - throw new IllegalArgumentException(); - } - - if (count == 0 || position >= size()) { - return 0; - } - ByteBuffer buffer = null; - count = Math.min(count, size() - position); - if (target instanceof SocketChannelImpl) { - // only socket can be transfered by system call - return kernelTransfer(handle, ((SocketChannelImpl) target).getFD(), - position, count); - } - // BEGIN android-changed - try { - buffer = map(MapMode.READ_ONLY, position, count); - return target.write(buffer); - } finally { - // unmap the buffer - if (buffer != null) { - // all children of FileChannelImpl currently returns - // an instance of DirectBuffer from map() method - ((DirectBuffer) buffer).free(); - } - } - // END android-changed - } - - private long kernelTransfer(int l, FileDescriptor fd, long position, - long count) throws IOException { - boolean completed = false; - try { - begin(); - long ret = fileSystem.transfer(l, fd, position, count); - completed = true; - return ret; - } finally { - end(completed); - } - } - - public FileChannel truncate(long size) throws IOException { - openCheck(); - if (size < 0) { - throw new IllegalArgumentException(); - } - if (size < size()) { - synchronized (repositioningLock) { - long position = position(); - fileSystem.truncate(handle, size); - /* - * FIXME: currently the port library always modifies the - * position to given size. not sure it is a bug or intended - * behaviour, so I always reset the position to proper value as - * Java Spec. - */ - position(position > size ? size : position); - } - } - return this; - } - - /* - * (non-Javadoc) - * - * @see java.nio.channels.WritableByteChannel#write(java.nio.ByteBuffer) - */ - - public int write(ByteBuffer buffer, long position) throws IOException { - if (null == buffer){ - throw new NullPointerException(); - } - if (position < 0){ - throw new IllegalArgumentException(); - } - openCheck(); - if (!buffer.hasRemaining()){ - return 0; - } - int bytesWritten = 0; - synchronized (repositioningLock) { - long preWritePosition = position(); - position(position); - try { - bytesWritten = writeImpl(buffer); - } finally { - position(preWritePosition); - } - } - return bytesWritten; - } - - public int write(ByteBuffer buffer) throws IOException { - openCheck(); - return writeImpl(buffer); - } - - private int writeImpl(ByteBuffer buffer) throws IOException { - int bytesWritten; - boolean completed = false; - synchronized (repositioningLock) { - if (buffer.isDirect()) { - DirectBuffer directBuffer = (DirectBuffer) buffer; - int address = directBuffer.getEffectiveAddress().toInt(); - try { - begin(); - bytesWritten = (int) fileSystem.writeDirect(handle, - address, buffer.position(), buffer.remaining()); - completed = true; - } finally { - end(completed); - } - } else { - try { - begin(); - bytesWritten = (int) fileSystem.write(handle, buffer - .array(), buffer.arrayOffset() + buffer.position(), - buffer.remaining()); - completed = true; - } finally { - end(completed); - } - } - if (bytesWritten > 0) { - buffer.position(buffer.position() + bytesWritten); - } - } - return bytesWritten; - } - - public long write(ByteBuffer[] buffers, int offset, int length) - throws IOException { - if (offset < 0 || length < 0 || (offset + length) > buffers.length) { - throw new IndexOutOfBoundsException(); - } - openCheck(); - int count = 0; - for (int i = offset; i < offset + length; i++) { - count += buffers[i].remaining(); - } - if (0 == count) { - return 0; - } - int[] handles = new int[length]; - int[] offsets = new int[length]; - int[] lengths = new int[length]; - // BEGIN android-changed - // list of allocated direct ByteBuffers to prevent them from being GC-ed - DirectBuffer[] allocatedBufs = new DirectBuffer[length]; - - for (int i = 0; i < length; i++) { - ByteBuffer buffer = buffers[i + offset]; - if (!buffer.isDirect()) { - ByteBuffer directBuffer = ByteBuffer.allocateDirect(buffer - .remaining()); - directBuffer.put(buffer); - directBuffer.flip(); - buffer = directBuffer; - allocatedBufs[i] = (DirectBuffer) directBuffer; - offsets[i] = 0; - } else { - offsets[i] = buffer.position(); - allocatedBufs[i] = null; - } - handles[i] = ((DirectBuffer) buffer).getEffectiveAddress().toInt(); - lengths[i] = buffer.remaining(); - } - // END android-changed - - long bytesWritten = 0; - boolean completed = false; - synchronized (repositioningLock) { - try { - begin(); - bytesWritten = fileSystem.writev(handle, handles, offsets, - lengths, length); - completed = true; - } finally { - end(completed); - // BEGIN android-added - // free temporary direct buffers - for (int i = 0; i < length; ++i) { - if (allocatedBufs[i] != null) { - allocatedBufs[i].free(); - } - } - // END android-added - } - } - - long bytesRemaining = bytesWritten; - for (int i = offset; i < length + offset; i++) { - if (bytesRemaining > buffers[i].remaining()) { - int pos = buffers[i].limit(); - buffers[i].position(pos); - bytesRemaining -= buffers[i].remaining(); - } else { - int pos = buffers[i].position() + (int) bytesRemaining; - buffers[i].position(pos); - break; - } - } - return bytesWritten; - } - - public int getHandle(){ - return handle; - } -} diff --git a/nio/src/main/java/org/apache/harmony/nio/internal/FileLockImpl.java b/nio/src/main/java/org/apache/harmony/nio/internal/FileLockImpl.java deleted file mode 100644 index 4e0ddc9..0000000 --- a/nio/src/main/java/org/apache/harmony/nio/internal/FileLockImpl.java +++ /dev/null @@ -1,73 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.harmony.nio.internal; - - -import java.io.IOException; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.FileChannel; -import java.nio.channels.FileLock; - -/* - * The concrete implementation of an NIO file lock object. - * - */ -final class FileLockImpl extends FileLock { - - // Remembers if this lock has been released via the API. - private boolean isReleased = false; - - /* - * Returns a new file lock object with the given parameters. - * - * @param channel the file channel hosting the lock. @param position the - * start position of the lock, in bytes @param size the length of the lock, - * in bytes @param shared whether this lock is shared (true) or exclusive - * (false) - */ - public FileLockImpl(FileChannel channel, long position, long size, - boolean shared) { - super(channel, position, size, shared); - } - - /* - * Tests to see if the lock is valid. A lock can be invalidated if the - * channel it is acquired on is closed or if it is released. (non-Javadoc) - * - * @see java.nio.channels.FileLock#isValid() - */ - public boolean isValid() { - return !isReleased && channel().isOpen(); - } - - /* - * Releases the file lock on the channel that acquired it. Releasing an - * invalid lock has no effect. - * - * @see java.nio.channels.FileLock#release() - */ - public void release() throws IOException { - if (!channel().isOpen()) { - throw new ClosedChannelException(); - } - - if (!isReleased) { - ((FileChannelImpl) channel()).release(this); - isReleased = true; - } - } -} diff --git a/nio/src/main/java/org/apache/harmony/nio/internal/IOUtil.java b/nio/src/main/java/org/apache/harmony/nio/internal/IOUtil.java deleted file mode 100644 index 6752732..0000000 --- a/nio/src/main/java/org/apache/harmony/nio/internal/IOUtil.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.harmony.nio.internal; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CharsetEncoder; -import java.nio.charset.CoderResult; - -import org.apache.harmony.nio.Util; -import org.apache.harmony.nio.internal.nls.Messages; - - -/* - * Static methods for I/O util. Used by io package and nio package. - * - */ -public final class IOUtil { - - // ------------------------------------------------------------------- - // Class variables - // ------------------------------------------------------------------- - - private static final int DEFAULT_BUFFER_SIZE = 8192; - - // ------------------------------------------------------------------- - // Constructor - // ------------------------------------------------------------------- - - /* - * No instance. - */ - private IOUtil() { - super(); - } - - // ------------------------------------------------------------------- - // Routine methods. - // ------------------------------------------------------------------- - - /* - * Read method for InputStreamReader and Channels. - */ - public static int readInputStreamReader(InputStream in, ByteBuffer bytes, - CharBuffer chars, CharsetDecoder decoder, Object lock) - throws IOException { - synchronized (lock) { - if (in != null) { - if (chars.limit() == chars.position()) { - fillBuf(in, bytes, chars, decoder); - } - if (chars.limit() == 0) { - return -1; - } - return chars.get(); - } - // nio.06=InputStreamReader is closed. - throw new IOException(Messages.getString("nio.06")); //$NON-NLS-1$ - } - } - - /* - * Read method for InputStreamReader and Channels. - */ - public static int readInputStreamReader(char[] buf, int offset, int length, - InputStream in, ByteBuffer bytes, CharBuffer chars, - CharsetDecoder decoder, Object lock) throws IOException { - synchronized (lock) { - if (in != null) { - if (length == 0) { - return 0; - } - Util.assertArrayIndex(buf, offset, length); - // read at least once - if (chars.limit() == chars.position()) { - fillBuf(in, bytes, chars, decoder); - } - int position = chars.position(); - int availableChars = chars.limit() - position; - // read at least once for one byte - int needChars = length; - while (availableChars < needChars) { - System.arraycopy(chars.array(), position, buf, offset, - availableChars); - chars.position(position + availableChars); - needChars -= availableChars; - offset += availableChars; - if (in.available() <= 0) { - return needChars == length ? -1 : length - needChars; - } - fillBuf(in, bytes, chars, decoder); - position = chars.position(); - availableChars = chars.limit(); - if (availableChars == 0) { - return needChars == length ? -1 : length - needChars; - } - } - System.arraycopy(chars.array(), position, buf, offset, - needChars); - chars.position(chars.position() + needChars); - return length; - } - // nio.06=InputStreamReader is closed. - throw new IOException(Messages.getString("nio.06")); //$NON-NLS-1$ - } - } - - /* - * refill the buffer from wrapped InputStream - */ - private static void fillBuf(InputStream in, ByteBuffer bytes, - CharBuffer chars, CharsetDecoder decoder) throws IOException { - chars.clear(); - int read = 0; - try { - read = in.read(bytes.array()); - } catch (IOException e) { - chars.limit(0); - throw e; - } - if (read == -1) { - chars.limit(0); - return; - } - bytes.limit(read); - boolean endOfInput = read < DEFAULT_BUFFER_SIZE; - CoderResult result = decoder.decode(bytes, chars, endOfInput); - if (result.isError()) { - throw new IOException(result.toString()); - } - bytes.clear(); - chars.flip(); - } - - /* - * Write method for OutputStreamWriter and Channels. - */ - public static void writeOutputStreamWriter(String str, int offset, - int count, OutputStream out, ByteBuffer bytes, - CharsetEncoder encoder, Object lock) throws IOException { - Util.assertArrayIndex(str.length(), offset, count); - CharBuffer chars = CharBuffer.wrap(str, offset, count + offset); - convert(lock, encoder, bytes, chars, out); - } - - /* - * Write method for OutputStreamWriter and Channels. - */ - public static void writeOutputStreamWriter(int oneChar, OutputStream out, - ByteBuffer bytes, CharsetEncoder encoder, Object lock) - throws IOException { - synchronized (lock) { - if (encoder == null) { - // nio.07=Writer is closed. - throw new IOException(Messages.getString("nio.07")); //$NON-NLS-1$ - } - CharBuffer chars = CharBuffer.wrap(new char[] { (char) oneChar }); - convert(lock, encoder, bytes, chars, out); - } - } - - /* - * Write method for OutputStreamWriter and Channels. - */ - public static void writeOutputStreamWriter(char[] buf, int offset, - int count, OutputStream out, ByteBuffer bytes, - CharsetEncoder encoder, Object lock) throws IOException { - Util.assertArrayIndex(buf, offset, count); - CharBuffer chars = CharBuffer.wrap(buf, offset, count); - convert(lock, encoder, bytes, chars, out); - } - - /* - * Flush method for OutputStreamWriter and Channels. - */ - public static void flushOutputStreamWriter(OutputStream out, - ByteBuffer bytes, CharsetEncoder encoder, Object lock) - throws IOException { - synchronized (lock) { - if (encoder == null) { - // nio.07=Writer is closed. - throw new IOException(Messages.getString("nio.07")); //$NON-NLS-1$ - } - int position; - if ((position = bytes.position()) > 0) { - bytes.flip(); - out.write(bytes.array(), 0, position); - bytes.clear(); - } - out.flush(); - } - } - - /* - * convert function used in write. - */ - private static void convert(Object lock, CharsetEncoder encoder, - ByteBuffer bytes, CharBuffer chars, OutputStream out) - throws IOException { - synchronized (lock) { - if (encoder == null) { - // nio.07=Writer is closed. - throw new IOException(Messages.getString("nio.07")); //$NON-NLS-1$ - } - CoderResult result = encoder.encode(chars, bytes, true); - while (true) { - if (result.isError()) { - throw new IOException(result.toString()); - } else if (result.isOverflow()) { - // flush the output buffer - flushOutputStreamWriter(out, bytes, encoder, lock); - result = encoder.encode(chars, bytes, true); - continue; - } - break; - } - } - } -} diff --git a/nio/src/main/java/org/apache/harmony/nio/internal/LockManager.java b/nio/src/main/java/org/apache/harmony/nio/internal/LockManager.java deleted file mode 100644 index 3504460..0000000 --- a/nio/src/main/java/org/apache/harmony/nio/internal/LockManager.java +++ /dev/null @@ -1,80 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.harmony.nio.internal; - -import java.nio.channels.FileLock; -import java.nio.channels.OverlappingFileLockException; -import java.util.Comparator; -import java.util.Iterator; -import java.util.SortedSet; -import java.util.TreeSet; - -/** - * The lock manager is responsible for tracking acquired and pending locks on - * the underlying file channel. - * - */ -final class LockManager { - // The set of acquired and pending locks. - private final Comparator<FileLock> lockComparator = new Comparator<FileLock>() { - public int compare(FileLock lock1, FileLock lock2) { - long position1 = lock1.position(); - long position2 = lock2.position(); - return position1 > position2 ? 1 : (position1 < position2 ? -1 : 0); - } - }; - - private final SortedSet<FileLock> locks = new TreeSet<FileLock>( - lockComparator); - - /* - * Default Constructor. - */ - protected LockManager() { - super(); - } - - /* - * Add a new pending lock to the manager. Throws an exception if the lock - * would overlap an existing lock. Once the lock is acquired it remains in - * this set as an acquired lock. - */ - synchronized void addLock(FileLock lock) - throws OverlappingFileLockException { - long lockEnd = lock.position() + lock.size(); - for (Iterator<FileLock> keyItr = locks.iterator(); keyItr.hasNext();) { - FileLock existingLock = keyItr.next(); - if (existingLock.position() > lockEnd) { - // This, and all remaining locks, start beyond our end (so - // cannot overlap). - break; - } - if (existingLock.overlaps(lock.position(), lock.size())) { - throw new OverlappingFileLockException(); - } - } - locks.add(lock); - } - - /* - * Removes an acquired lock from the lock manager. If the lock did not exist - * in the lock manager the operation is a no-op. - */ - synchronized void removeLock(FileLock lock) { - locks.remove(lock); - } -} diff --git a/nio/src/main/java/org/apache/harmony/nio/internal/MappedByteBufferFactory.java b/nio/src/main/java/org/apache/harmony/nio/internal/MappedByteBufferFactory.java deleted file mode 100644 index f3f5a35..0000000 --- a/nio/src/main/java/org/apache/harmony/nio/internal/MappedByteBufferFactory.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.harmony.nio.internal; - -import java.lang.reflect.Constructor; -import java.nio.MappedByteBuffer; -import java.security.AccessController; -import java.security.PrivilegedAction; - -import org.apache.harmony.luni.platform.PlatformAddress; - -class MappedByteBufferFactory { - - static final Constructor constructor; - - static { - constructor = AccessController - .doPrivileged(new PrivilegedAction<Constructor>() { - public Constructor run() { - try { - Class wrapperClazz = ClassLoader - .getSystemClassLoader().loadClass( - "java.nio.MappedByteBufferAdapter"); //$NON-NLS-1$ - Constructor result = wrapperClazz - .getConstructor(new Class[] { - PlatformAddress.class, int.class, - int.class, int.class }); - result.setAccessible(true); - return result; - } catch (Exception e) { - throw new RuntimeException(e); - } - } - }); - } - - static MappedByteBuffer getBuffer(PlatformAddress addr, int mapmode, - long size, int offset) throws Exception { - // Spec points out explicitly that the size of map should be no greater than - // Integer.MAX_VALUE, so long to int cast is safe here. - return (MappedByteBuffer) constructor.newInstance(new Object[] { addr, - new Integer((int) size), new Integer(offset), - new Integer(mapmode) }); - } -} diff --git a/nio/src/main/java/org/apache/harmony/nio/internal/PipeImpl.java b/nio/src/main/java/org/apache/harmony/nio/internal/PipeImpl.java deleted file mode 100644 index beceac4..0000000 --- a/nio/src/main/java/org/apache/harmony/nio/internal/PipeImpl.java +++ /dev/null @@ -1,194 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.harmony.nio.internal; - -import java.io.FileDescriptor; -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.nio.ByteBuffer; -import java.nio.channels.Pipe; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.spi.SelectorProvider; - -import org.apache.harmony.luni.platform.FileDescriptorHandler; - -/* - * default implementation of Pipe - * - */ - -final class PipeImpl extends Pipe { - - private SinkChannelImpl sink; - - private SourceChannelImpl source; - - private int serverPort; - - public PipeImpl() throws IOException { - super(); - try { - sink = new SinkChannelImpl(SelectorProvider.provider()); - source = new SourceChannelImpl(SelectorProvider.provider()); - sink.finishConnect(); - source.accept(); - source.closeServer(); - } catch(IOException ioe){ - reset(); - throw ioe; - } catch(RuntimeException e){ - reset(); - throw e; - } - } - - private void reset(){ - if(sink != null){ - try { - sink.close(); - } catch (Exception e) { - } - } - if(source != null){ - try { - source.closeServer(); - } catch (Exception e) { - } - try { - source.close(); - } catch (Exception e) { - } - } - } - - /* - * @see java.nio.channels.Pipe#sink() - */ - public SinkChannel sink() { - return sink; - } - - /* - * @see java.nio.channels.Pipe#source() - */ - public SourceChannel source() { - return source; - } - - /* - * default implementation of SourceChannel - */ - private class SourceChannelImpl extends Pipe.SourceChannel implements - FileDescriptorHandler { - - private SocketChannelImpl sourceSocket; - - private ServerSocketChannel sourceServer; - - /* - * constructor - */ - protected SourceChannelImpl(SelectorProvider provider) - throws IOException { - super(provider); - sourceServer = provider.openServerSocketChannel(); - sourceServer.socket().bind( - new InetSocketAddress(InetAddress.getLocalHost(), 0)); - serverPort = sourceServer.socket().getLocalPort(); - } - - void closeServer() throws IOException { - sourceServer.close(); - } - - void accept() throws IOException { - sourceSocket = (SocketChannelImpl) sourceServer.accept(); - } - - protected void implCloseSelectableChannel() throws IOException { - sourceSocket.close(); - } - - protected void implConfigureBlocking(boolean blockingMode) - throws IOException { - sourceSocket.configureBlocking(blockingMode); - } - - public int read(ByteBuffer buffer) throws IOException { - return sourceSocket.read(buffer); - } - - public long read(ByteBuffer[] buffers) throws IOException { - return read(buffers, 0, buffers.length); - } - - public long read(ByteBuffer[] buffers, int offset, int length) - throws IOException { - return sourceSocket.read(buffers, offset, length); - } - - public FileDescriptor getFD() { - return sourceSocket.getFD(); - } - } - - /* - * default implementation of SinkChannel - */ - private class SinkChannelImpl extends Pipe.SinkChannel implements - FileDescriptorHandler { - - private SocketChannelImpl sinkSocket; - - protected SinkChannelImpl(SelectorProvider provider) throws IOException { - super(provider); - sinkSocket = (SocketChannelImpl) provider.openSocketChannel(); - } - - public boolean finishConnect() throws IOException { - return sinkSocket.connect(new InetSocketAddress(InetAddress - .getLocalHost(), serverPort)); - } - - protected void implCloseSelectableChannel() throws IOException { - sinkSocket.close(); - } - - protected void implConfigureBlocking(boolean blockingMode) - throws IOException { - sinkSocket.configureBlocking(blockingMode); - } - - public int write(ByteBuffer buffer) throws IOException { - return sinkSocket.write(buffer); - } - - public long write(ByteBuffer[] buffers) throws IOException { - return write(buffers, 0, buffers.length); - } - - public long write(ByteBuffer[] buffers, int offset, int length) - throws IOException { - return sinkSocket.write(buffers, offset, length); - } - - public FileDescriptor getFD() { - return sinkSocket.getFD(); - } - } -} diff --git a/nio/src/main/java/org/apache/harmony/nio/internal/ReadOnlyFileChannel.java b/nio/src/main/java/org/apache/harmony/nio/internal/ReadOnlyFileChannel.java deleted file mode 100644 index 559fc89..0000000 --- a/nio/src/main/java/org/apache/harmony/nio/internal/ReadOnlyFileChannel.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Android Notice - * In this class the address length was changed from long to int. - * This is due to performance optimizations for the device. - */ - -package org.apache.harmony.nio.internal; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.MappedByteBuffer; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.FileChannel; -import java.nio.channels.FileLock; -import java.nio.channels.NonWritableChannelException; -import java.nio.channels.ReadableByteChannel; - -import org.apache.harmony.luni.platform.IMemorySystem; - -public final class ReadOnlyFileChannel extends FileChannelImpl { - public ReadOnlyFileChannel(Object stream, int handle) { - super(stream, handle); - } - - public final int write(ByteBuffer buffer, long position) throws IOException { - if (null == buffer){ - throw new NullPointerException(); - } - if (position < 0){ - throw new IllegalArgumentException(); - } - throw new NonWritableChannelException(); - } - - public final int write(ByteBuffer buffer) throws IOException { - openCheck(); - throw new NonWritableChannelException(); - } - - public final long write(ByteBuffer[] buffers, int offset, int length) - throws IOException { - if (offset < 0 || length < 0 || (offset + length) > buffers.length) { - throw new IndexOutOfBoundsException(); - } - openCheck(); - throw new NonWritableChannelException(); - } - - public final FileChannel truncate(long size) throws IOException { - openCheck(); - if (size < 0) { - throw new IllegalArgumentException(); - } - throw new NonWritableChannelException(); - } - - public final long transferFrom(ReadableByteChannel src, long position, - long count) throws IOException { - openCheck(); - if (!src.isOpen()) { - throw new ClosedChannelException(); - } - throw new NonWritableChannelException(); - } - - public final MappedByteBuffer map(MapMode mode, long position, long size) - throws IOException { - openCheck(); - if (mode == null) { - throw new NullPointerException(); - } - if (position < 0 || size < 0 || size > Integer.MAX_VALUE) { - throw new IllegalArgumentException(); - } - if (mode != MapMode.READ_ONLY) { - throw new NonWritableChannelException(); - } - return super.mapImpl(IMemorySystem.MMAP_READ_ONLY, position, size); - } - - public final void force(boolean metadata) throws IOException { - openCheck(); - return; - } - - protected final FileLock basicLock(long position, long size, - boolean shared, boolean wait) throws IOException { - if (!shared) { - throw new NonWritableChannelException(); - } - return super.basicLock(position, size, shared, true); - } -} diff --git a/nio/src/main/java/org/apache/harmony/nio/internal/ReadWriteFileChannel.java b/nio/src/main/java/org/apache/harmony/nio/internal/ReadWriteFileChannel.java deleted file mode 100644 index 626cb95..0000000 --- a/nio/src/main/java/org/apache/harmony/nio/internal/ReadWriteFileChannel.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Android Notice - * In this class the address length was changed from long to int. - * This is due to performance optimizations for the device. - */ - -package org.apache.harmony.nio.internal; - -import java.io.IOException; -import java.nio.MappedByteBuffer; - -import org.apache.harmony.luni.platform.IMemorySystem; - -public final class ReadWriteFileChannel extends FileChannelImpl { - public ReadWriteFileChannel(Object stream, int handle) { - super(stream, handle); - } - - public final MappedByteBuffer map(MapMode mode, long position, long size) - throws IOException { - openCheck(); - if (mode == null) { - throw new NullPointerException(); - } - if (position < 0 || size < 0 || size > Integer.MAX_VALUE) { - throw new IllegalArgumentException(); - } - int mapMode; - if (mode == MapMode.READ_ONLY) { - mapMode = IMemorySystem.MMAP_READ_ONLY; - } else if (mode == MapMode.READ_WRITE) { - mapMode = IMemorySystem.MMAP_READ_WRITE; - } else { - mapMode = IMemorySystem.MMAP_WRITE_COPY; - } - return mapImpl(mapMode, position, size); - } -} diff --git a/nio/src/main/java/org/apache/harmony/nio/internal/SelectionKeyImpl.java b/nio/src/main/java/org/apache/harmony/nio/internal/SelectionKeyImpl.java deleted file mode 100644 index f863928..0000000 --- a/nio/src/main/java/org/apache/harmony/nio/internal/SelectionKeyImpl.java +++ /dev/null @@ -1,94 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.harmony.nio.internal; - -import java.nio.channels.CancelledKeyException; -import java.nio.channels.SelectableChannel; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.spi.AbstractSelectableChannel; -import java.nio.channels.spi.AbstractSelectionKey; - -/* - * Default implementation of SelectionKey - */ -final class SelectionKeyImpl extends AbstractSelectionKey { - - private AbstractSelectableChannel channel; - - int oldInterestOps; - - private int interestOps; - - private int readyOps; - - private SelectorImpl selector; - - public SelectionKeyImpl(AbstractSelectableChannel channel, int operations, - Object attachment, SelectorImpl selector) { - super(); - this.channel = channel; - interestOps = operations; - this.selector = selector; - attach(attachment); - } - - public SelectableChannel channel() { - return channel; - } - - public int interestOps() { - checkValid(); - synchronized (selector.keysLock) { - return interestOps; - } - } - - public SelectionKey interestOps(int operations) { - checkValid(); - if ((operations & ~(channel().validOps())) != 0) { - throw new IllegalArgumentException(); - } - synchronized (selector.keysLock) { - interestOps = operations; - } - return this; - } - - public int readyOps() { - checkValid(); - return readyOps; - } - - public Selector selector() { - return selector; - } - - /* - * package private method for setting the ready operation by selector - */ - void setReadyOps(int readyOps) { - this.readyOps = readyOps; - } - - private void checkValid() { - if (!isValid()) { - throw new CancelledKeyException(); - } - } - -}
\ No newline at end of file diff --git a/nio/src/main/java/org/apache/harmony/nio/internal/SelectorImpl.java b/nio/src/main/java/org/apache/harmony/nio/internal/SelectorImpl.java deleted file mode 100644 index f8e7d80..0000000 --- a/nio/src/main/java/org/apache/harmony/nio/internal/SelectorImpl.java +++ /dev/null @@ -1,407 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.harmony.nio.internal; - -import java.io.FileDescriptor; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.ClosedSelectorException; -import java.nio.channels.IllegalSelectorException; -import java.nio.channels.Pipe; -import java.nio.channels.SelectableChannel; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.SocketChannel; -import java.nio.channels.spi.AbstractSelectableChannel; -import java.nio.channels.spi.AbstractSelectionKey; -import java.nio.channels.spi.AbstractSelector; -import java.nio.channels.spi.SelectorProvider; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.apache.harmony.luni.platform.FileDescriptorHandler; -import org.apache.harmony.luni.platform.Platform; - -/* - * Default implementation of java.nio.channels.Selector - * - */ -final class SelectorImpl extends AbstractSelector { - - private static final int MOCK_WRITEBUF_SIZE = 1; - - private static final int MOCK_READBUF_SIZE = 8; - - private static final int NA = 0; - - private static final int READABLE = 1; - - private static final int WRITEABLE = 2; - - private static final int SELECT_BLOCK = -1; - - private static final int SELECT_NOW = 0; - - // keysLock is used to brief synchronization when get selectionKeys snapshot - // before selection - final Object keysLock = new Object(); - - private final Set<SelectionKey> keys = new HashSet<SelectionKey>(); - - private Set<SelectionKey> unmodifiableKeys = Collections - .unmodifiableSet(keys); - - private final Set<SelectionKey> selectedKeys = new HashSet<SelectionKey>(); - - private Set<SelectionKey> unaddableSelectedKeys = new UnaddableSet<SelectionKey>( - selectedKeys); - - // sink and source are used by wakeup() - private Pipe.SinkChannel sink; - - private Pipe.SourceChannel source; - - private FileDescriptor sourcefd; - - private SelectionKey[] readableChannels; - - private SelectionKey[] writableChannels; - - private List<FileDescriptor> readableFDs = new ArrayList<FileDescriptor>(); - - private List<FileDescriptor> writableFDs = new ArrayList<FileDescriptor>(); - - private FileDescriptor[] readable; - - private FileDescriptor[] writable; - - public SelectorImpl(SelectorProvider selectorProvider) { - super(selectorProvider); - try { - Pipe mockSelector = selectorProvider.openPipe(); - sink = mockSelector.sink(); - source = mockSelector.source(); - sourcefd = ((FileDescriptorHandler)source).getFD(); - source.configureBlocking(false); - } catch (IOException e) { - // do nothing - } - } - - /* - * @see java.nio.channels.spi.AbstractSelector#implCloseSelector() - */ - protected void implCloseSelector() throws IOException { - doCancel(); - for (SelectionKey sk : keys) { - deregister((AbstractSelectionKey) sk); - } - wakeup(); - } - - /* - * @see java.nio.channels.spi.AbstractSelector#register(java.nio.channels.spi.AbstractSelectableChannel, - * int, java.lang.Object) - */ - protected SelectionKey register(AbstractSelectableChannel channel, - int operations, Object attachment) { - if (!provider().equals(channel.provider())) { - throw new IllegalSelectorException(); - } - synchronized (this) { - synchronized (keys) { - SelectionKey sk = new SelectionKeyImpl(channel, operations, - attachment, this); - keys.add(sk); - return sk; - } - } - } - - /* - * @see java.nio.channels.Selector#keys() - */ - public synchronized Set<SelectionKey> keys() { - closeCheck(); - return unmodifiableKeys; - } - - private void closeCheck() { - if (!isOpen()) { - throw new ClosedSelectorException(); - } - } - - /* - * @see java.nio.channels.Selector#select() - */ - public int select() throws IOException { - return selectInternal(SELECT_BLOCK); - } - - /* - * @see java.nio.channels.Selector#select(long) - */ - public int select(long timeout) throws IOException { - if (timeout < 0) { - throw new IllegalArgumentException(); - } - return selectInternal((0 == timeout) ? SELECT_BLOCK : timeout); - } - - /* - * @see java.nio.channels.Selector#selectNow() - */ - public int selectNow() throws IOException { - return selectInternal(SELECT_NOW); - } - - private int selectInternal(long timeout) throws IOException { - closeCheck(); - synchronized (this) { - synchronized (keys) { - synchronized (selectedKeys) { - doCancel(); - int[] readyChannels = null; - boolean isBlock = (SELECT_NOW != timeout); - // BEGIN android-removed - // copied from newer version of harmony - // if (keys.size() == 0) { - // return 0; - // } - // END android-removed - prepareChannels(); - try { - if (isBlock) { - begin(); - } - readyChannels = Platform.getNetworkSystem().select(readable, writable, timeout); - } finally { - // clear results for next select - readableFDs.clear(); - writableFDs.clear(); - if (isBlock) { - end(); - } - } - return processSelectResult(readyChannels); - } - } - } - } - - private boolean isConnected(SelectionKeyImpl key) { - SelectableChannel channel = key.channel(); - if (channel instanceof SocketChannel) { - return ((SocketChannel) channel).isConnected(); - } - return true; - } - - // Prepares and adds channels to list for selection - private void prepareChannels() { - readableFDs.add(sourcefd); - List<SelectionKey> readChannelList = new ArrayList<SelectionKey>(); - readChannelList.add(source.keyFor(this)); - List<SelectionKey> writeChannelList = new ArrayList<SelectionKey>(); - synchronized (keysLock) { - for (Iterator<SelectionKey> i = keys.iterator(); i.hasNext();) { - SelectionKeyImpl key = (SelectionKeyImpl) i.next(); - key.oldInterestOps = key.interestOps(); - boolean isReadableChannel = ((SelectionKey.OP_ACCEPT | SelectionKey.OP_READ) & key.oldInterestOps) != 0; - boolean isWritableChannel = ((SelectionKey.OP_CONNECT | SelectionKey.OP_WRITE) & key.oldInterestOps) != 0; - SelectableChannel channel = key.channel(); - if (isReadableChannel) { - readChannelList.add(channel.keyFor(this)); - readableFDs.add(((FileDescriptorHandler)channel).getFD()); - } - if (isWritableChannel) { - writeChannelList.add(channel.keyFor(this)); - writableFDs.add(((FileDescriptorHandler)channel).getFD()); - } - } - } - readableChannels = readChannelList.toArray(new SelectionKey[0]); - writableChannels = writeChannelList.toArray(new SelectionKey[0]); - readable = readableFDs.toArray(new FileDescriptor[0]); - writable = writableFDs.toArray(new FileDescriptor[0]); - } - - // Analyses selected channels and adds keys of ready channels to - // selectedKeys list - private int processSelectResult(int[] readyChannels) throws IOException { - if (0 == readyChannels.length) { - return 0; - } - // if the mock channel is selected, read the content. - if (READABLE == readyChannels[0]) { - ByteBuffer readbuf = ByteBuffer.allocate(MOCK_READBUF_SIZE); - while (source.read(readbuf) > 0) { - readbuf.flip(); - } - } - int selected = 0; - for (int i = 1; i < readyChannels.length; i++) { - SelectionKeyImpl key = (SelectionKeyImpl) (i >= readable.length ? writableChannels[i - - readable.length] - : readableChannels[i]); - if (null == key) { - continue; - } - boolean isOldSelectedKey = selectedKeys.contains(key); - int selectedOp = 0; - // set ready ops - switch (readyChannels[i]) { - case NA: - selectedOp = 0; - break; - case READABLE: - selectedOp = (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT) - & key.oldInterestOps; - break; - case WRITEABLE: - if (isConnected(key)) { - selectedOp = SelectionKey.OP_WRITE & key.oldInterestOps; - } else { - selectedOp = SelectionKey.OP_CONNECT & key.oldInterestOps; - } - break; - } - - if (0 != selectedOp) { - if (isOldSelectedKey && key.readyOps() != selectedOp) { - key.setReadyOps(key.readyOps() | selectedOp); - selected++; - } else if (!isOldSelectedKey) { - key.setReadyOps(selectedOp); - selectedKeys.add(key); - selected++; - } - } - } - readableChannels = null; - writableChannels = null; - return selected; - } - - /* - * @see java.nio.channels.Selector#selectedKeys() - */ - public synchronized Set<SelectionKey> selectedKeys() { - closeCheck(); - return unaddableSelectedKeys; - } - - private void doCancel() { - Set<SelectionKey> cancelledKeys = cancelledKeys(); - synchronized (cancelledKeys) { - if (cancelledKeys.size() > 0) { - for (SelectionKey currentkey : cancelledKeys) { - deregister((AbstractSelectionKey) currentkey); - keys.remove(currentkey); - selectedKeys.remove(currentkey); - } - } - cancelledKeys.clear(); - } - } - - /* - * @see java.nio.channels.Selector#wakeup() - */ - public Selector wakeup() { - try { - sink.write(ByteBuffer.allocate(MOCK_WRITEBUF_SIZE)); - } catch (IOException e) { - // do nothing - } - return this; - } - - private static class UnaddableSet<E> implements Set<E> { - - private Set<E> set; - - UnaddableSet(Set<E> set) { - this.set = set; - } - - public boolean equals(Object object) { - return set.equals(object); - } - - public int hashCode() { - return set.hashCode(); - } - - public boolean add(E object) { - throw new UnsupportedOperationException(); - } - - public boolean addAll(Collection<? extends E> c) { - throw new UnsupportedOperationException(); - } - - public void clear() { - set.clear(); - } - - public boolean contains(Object object) { - return set.contains(object); - } - - public boolean containsAll(Collection<?> c) { - return set.containsAll(c); - } - - public boolean isEmpty() { - return set.isEmpty(); - } - - public Iterator<E> iterator() { - return set.iterator(); - } - - public boolean remove(Object object) { - return set.remove(object); - } - - public boolean removeAll(Collection<?> c) { - return set.removeAll(c); - } - - public boolean retainAll(Collection<?> c) { - return set.retainAll(c); - } - - public int size() { - return set.size(); - } - - public Object[] toArray() { - return set.toArray(); - } - - public <T> T[] toArray(T[] a) { - return set.toArray(a); - } - } -} diff --git a/nio/src/main/java/org/apache/harmony/nio/internal/SelectorProviderImpl.java b/nio/src/main/java/org/apache/harmony/nio/internal/SelectorProviderImpl.java deleted file mode 100644 index d774b3a..0000000 --- a/nio/src/main/java/org/apache/harmony/nio/internal/SelectorProviderImpl.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.harmony.nio.internal; - -import java.io.IOException; -import java.nio.channels.DatagramChannel; -import java.nio.channels.Pipe; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; -import java.nio.channels.spi.AbstractSelector; -import java.nio.channels.spi.SelectorProvider; - - -/* - * Internal implementation of SelectorProvider. - * - */ -public class SelectorProviderImpl extends SelectorProvider { - - /* - * Constructor for this class. - */ - public SelectorProviderImpl() { - super(); - } - - /* - * - * @see java.nio.channels.spi.SelectorProvider#openDatagramChannel() - */ - public DatagramChannel openDatagramChannel() throws IOException { - return new DatagramChannelImpl(this); - } - - /* - * - * @see java.nio.channels.spi.SelectorProvider#openPipe() - */ - public Pipe openPipe() throws IOException { - return new PipeImpl(); - } - - /* - * - * @see java.nio.channels.spi.SelectorProvider#openSelector() - */ - public AbstractSelector openSelector() throws IOException { - return new SelectorImpl(this); - } - - /* - * - * @see java.nio.channels.spi.SelectorProvider#openServerSocketChannel() - */ - public ServerSocketChannel openServerSocketChannel() throws IOException { - return new ServerSocketChannelImpl(this); - } - - /* - * - * @see java.nio.channels.spi.SelectorProvider#openSocketChannel() - */ - public SocketChannel openSocketChannel() throws IOException { - return new SocketChannelImpl(this); - } - -} diff --git a/nio/src/main/java/org/apache/harmony/nio/internal/ServerSocketChannelImpl.java b/nio/src/main/java/org/apache/harmony/nio/internal/ServerSocketChannelImpl.java deleted file mode 100644 index 3bc368f..0000000 --- a/nio/src/main/java/org/apache/harmony/nio/internal/ServerSocketChannelImpl.java +++ /dev/null @@ -1,324 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.harmony.nio.internal; - -import java.io.FileDescriptor; -import java.io.IOException; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.SocketAddress; -import java.net.SocketImpl; -import java.net.SocketTimeoutException; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.IllegalBlockingModeException; -import java.nio.channels.NotYetBoundException; -import java.nio.channels.SelectableChannel; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; -import java.nio.channels.spi.SelectorProvider; - -import org.apache.harmony.luni.net.NetUtil; -import org.apache.harmony.luni.net.SocketImplProvider; -import org.apache.harmony.luni.platform.FileDescriptorHandler; -import org.apache.harmony.luni.platform.Platform; - -/* - * The default implementation class of java.nio.channels.ServerSocketChannel. - */ -public class ServerSocketChannelImpl extends ServerSocketChannel implements - FileDescriptorHandler { - - // ---------------------------------------------------- - // Class variables - // ---------------------------------------------------- - - // status un-init, not initialized. - private static final int SERVER_STATUS_UNINIT = -1; - - // status after open and before closed. - private static final int SERVER_STATUS_OPEN = 0; - - // status closed. - private static final int SERVER_STATUS_CLOSED = 1; - - // ------------------------------------------------------------------- - // Instance variables - // ------------------------------------------------------------------- - - // The fd to interact with native code - private final FileDescriptor fd; - - // The internal ServerSocket - private final ServerSocket socket; - - private final SocketImpl impl; - - int status = SERVER_STATUS_UNINIT; - - // whether the socket is bound - boolean isBound = false; - - // lock for accept - private class AcceptLock {} - private final Object acceptLock = new AcceptLock(); - - // ---------------------------------------------------- - // Constructor - // ---------------------------------------------------- - - /* - * Constructor - */ - public ServerSocketChannelImpl(SelectorProvider sp) throws IOException { - super(sp); - status = SERVER_STATUS_OPEN; - fd = new FileDescriptor(); - Platform.getNetworkSystem().createServerStreamSocket(fd, - NetUtil.preferIPv4Stack()); - impl = SocketImplProvider.getServerSocketImpl(fd); - socket = new ServerSocketAdapter(impl, this); - } - - // for native call - private ServerSocketChannelImpl() throws IOException { - super(SelectorProvider.provider()); - status = SERVER_STATUS_OPEN; - fd = new FileDescriptor(); - impl = SocketImplProvider.getServerSocketImpl(fd); - socket = new ServerSocketAdapter(impl, this); - isBound = false; - } - - // ---------------------------------------------------- - // Methods - // ---------------------------------------------------- - - /* - * Getting the internal Socket If we have not the socket, we create a new - * one. - */ - public ServerSocket socket() { - return socket; - } - - /* - * - * @see java.nio.channels.ServerSocketChannel#accept() - */ - public SocketChannel accept() throws IOException { - if (!isOpen()) { - throw new ClosedChannelException(); - } - if (!isBound) { - throw new NotYetBoundException(); - } - - SocketChannel sockChannel = SocketChannel.open(); - Socket socketGot = sockChannel.socket(); - - try { - begin(); - - synchronized (acceptLock) { - synchronized (blockingLock()) { - boolean isBlocking = isBlocking(); - if (!isBlocking) { - // for non blocking mode, use select to see whether - // there are any pending connections. - int[] tryResult = Platform.getNetworkSystem().select( - new FileDescriptor[] { this.fd }, - new FileDescriptor[0], 0); - if (0 == tryResult.length || 0 == tryResult[0]) { - // no pending connections, returns immediately. - return null; - } - } - // do accept. - do { - try { - ((ServerSocketAdapter) socket).accept(socketGot, - (SocketChannelImpl) sockChannel); - // select successfully, break out immediately. - break; - } catch (SocketTimeoutException e) { - // continue to accept if the channel is in blocking - // mode. - } - } while (isBlocking); - } - } - } finally { - end(socketGot.isConnected()); - } - return sockChannel; - } - - // ------------------------------------------------------------------- - // Protected inherited methods - // ------------------------------------------------------------------- - - /* - * @see java.nio.channels.spi.AbstractSelectableChannel#implConfigureBlocking - * - * (boolean) - */ - protected void implConfigureBlocking(boolean blockingMode) - throws IOException { - // Do nothing here. For real accept() operation in nonblocking mode, - // it uses INetworkSystem.select. Whether a channel is blocking can be - // decided by isBlocking() method. - } - - /* - * - * @see java.nio.channels.spi.AbstractSelectableChannel#implCloseSelectableChannel() - */ - synchronized protected void implCloseSelectableChannel() throws IOException { - status = SERVER_STATUS_CLOSED; - if (!socket.isClosed()) { - socket.close(); - } - } - - /* - * Gets the FileDescriptor - */ - public FileDescriptor getFD() { - return fd; - } - - // ---------------------------------------------------- - // Adapter classes. - // ---------------------------------------------------- - - /* - * The adapter class of ServerSocket. - */ - private class ServerSocketAdapter extends ServerSocket { - /* - * The related ServerSocketChannel. - */ - ServerSocketChannelImpl channelImpl; - - /* - * The Constructor. - */ - ServerSocketAdapter(SocketImpl impl, - ServerSocketChannelImpl aChannelImpl) { - super(impl); - this.channelImpl = aChannelImpl; - } - - /* - * - * @see java.net.ServerSocket#bind(java.net.SocketAddress, int) - */ - public void bind(SocketAddress localAddr, int backlog) - throws IOException { - super.bind(localAddr, backlog); - channelImpl.isBound = true; - } - - /* - * @see java.net.ServerSocket#accept() - * - * If the channel is in non-blocking mode and there is no connection - * ready to be accepted, invoking this method will cause an - * IllegalBlockingModeException. - */ - public Socket accept() throws IOException { - if (!isBound) { - throw new IllegalBlockingModeException(); - } - SocketChannel sc = channelImpl.accept(); - if (null == sc) { - throw new IllegalBlockingModeException(); - } - return sc.socket(); - } - - /* - * do the accept. - */ - private Socket accept(Socket aSocket, SocketChannelImpl sockChannel) - throws IOException { - // a new socket is pass in so we do not need to "Socket aSocket = - // new Socket();" - boolean connectOK = false; - try { - synchronized (this) { - super.implAccept(aSocket); - sockChannel.setConnected(); - // BEGIN android-added - // copied from a newer version of harmony - sockChannel.setBound(true); - // END android-added - } - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkAccept(aSocket.getInetAddress().getHostAddress(), - aSocket.getPort()); - } - connectOK = true; - } finally { - if (!connectOK) { - aSocket.close(); - } - } - return aSocket; - } - - /* - * getting internal channel. - */ - public ServerSocketChannel getChannel() { - return channelImpl; - } - - /* - * - * @see java.net.ServerSocket#isBound() - */ - public boolean isBound() { - return channelImpl.isBound; - } - - /* - * - * @see java.net.ServerSocket#bind(java.net.SocketAddress) - */ - public void bind(SocketAddress localAddr) throws IOException { - super.bind(localAddr); - channelImpl.isBound = true; - } - - /* - * @see java.net.ServerSocket#close() - */ - public void close() throws IOException { - synchronized (channelImpl) { - if (channelImpl.isOpen()) { - channelImpl.close(); - } else { - super.close(); - } - channelImpl.status = SERVER_STATUS_CLOSED; - } - } - } -} diff --git a/nio/src/main/java/org/apache/harmony/nio/internal/SocketChannelImpl.java b/nio/src/main/java/org/apache/harmony/nio/internal/SocketChannelImpl.java deleted file mode 100644 index 8e6c52f..0000000 --- a/nio/src/main/java/org/apache/harmony/nio/internal/SocketChannelImpl.java +++ /dev/null @@ -1,1057 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.harmony.nio.internal; - -import java.io.FileDescriptor; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.ConnectException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.SocketAddress; -import java.net.SocketException; -import java.net.SocketImpl; -import java.net.SocketOptions; -import java.net.UnknownHostException; -import java.nio.ByteBuffer; -import java.nio.channels.AlreadyConnectedException; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.ConnectionPendingException; -import java.nio.channels.IllegalBlockingModeException; -import java.nio.channels.NoConnectionPendingException; -import java.nio.channels.NotYetConnectedException; -import java.nio.channels.SocketChannel; -import java.nio.channels.UnresolvedAddressException; -import java.nio.channels.UnsupportedAddressTypeException; -import java.nio.channels.spi.SelectorProvider; - -import org.apache.harmony.luni.net.SocketImplProvider; -import org.apache.harmony.luni.platform.FileDescriptorHandler; -import org.apache.harmony.luni.platform.INetworkSystem; -import org.apache.harmony.luni.platform.Platform; -import org.apache.harmony.luni.util.ErrorCodeException; -import org.apache.harmony.nio.AddressUtil; -import org.apache.harmony.nio.internal.nls.Messages; - -/* - * - * The default implementation class of java.nio.channels.SocketChannel. - * - */ -class SocketChannelImpl extends SocketChannel implements FileDescriptorHandler { - - // ------------------------------------------------------------------- - // Class variables - // ------------------------------------------------------------------- - - private static final int EOF = -1; - - private static final int ERRCODE_SOCKET_NONBLOCKING_WOULD_BLOCK = -211; - - // The singleton to do the native network operation. - static final INetworkSystem networkSystem = Platform.getNetworkSystem(); - - // status un-init, not initialized. - static final int SOCKET_STATUS_UNINIT = EOF; - - // status before connect. - static final int SOCKET_STATUS_UNCONNECTED = 0; - - // status connection pending - static final int SOCKET_STATUS_PENDING = 1; - - // status after connection success - static final int SOCKET_STATUS_CONNECTED = 2; - - // status closed. - static final int SOCKET_STATUS_CLOSED = 3; - - // timeout used for non-block mode. - private static final int TIMEOUT_NONBLOCK = 0; - - // timeout used for block mode. - private static final int TIMEOUT_BLOCK = EOF; - - // step used for connect - private static final int HY_SOCK_STEP_START = 0; - - // step used for finishConnect - private static final int HY_PORT_SOCKET_STEP_CHECK = 1; - - // connect success - private static final int CONNECT_SUCCESS = 0; - - // ------------------------------------------------------------------- - // Instance Variables - // ------------------------------------------------------------------- - - // The fd to interact with native code - FileDescriptor fd; - - // Our internal Socket. - private Socket socket = null; - - // The address to be connected. - InetSocketAddress connectAddress = null; - - // Local address of the this socket (package private for adapter) - InetAddress localAddress = null; - - // local port - int localPort; - - // At first, uninitialized. - int status = SOCKET_STATUS_UNINIT; - - // BEGIN android-changed - // copied from a newer version of harmony - // whether the socket is bound - volatile boolean isBound = false; - // END adroid-changed - - private final Object readLock = new Object(); - - private final Object writeLock = new Object(); - - // BEGIN android-changed - // this content is a struct used in connect_withtimeout(). - // The structure its holding has a size of 392 bytes. - private byte[] connectContext = new byte[392]; - // END android-changed - - // used to store the trafficClass value which is simply returned - // as the value that was set. We also need it to pass it to methods - // that specify an address packets are going to be sent to - private int trafficClass = 0; - - // ------------------------------------------------------------------- - // Constructor - // ------------------------------------------------------------------- - - /* - * Constructor - */ - public SocketChannelImpl(SelectorProvider selectorProvider) - throws IOException { - super(selectorProvider); - fd = new FileDescriptor(); - status = SOCKET_STATUS_UNCONNECTED; - networkSystem.createSocket(fd, true); - } - - /* - * for native call - */ - private SocketChannelImpl(){ - super(SelectorProvider.provider()); - fd = new FileDescriptor(); - connectAddress = new InetSocketAddress(0); - status = SOCKET_STATUS_CONNECTED; - } - - // Keep this to see if need next version - // SocketChannelImpl(SelectorProvider selectorProvider, FileDescriptor fd, - // SocketImpl si) { - // super(selectorProvider); - // fd = fd; - // networkSystem = OSNetworkSystem.getOSNetworkSystem(); - // status = SOCKET_STATUS_UNCONNECTED; - // networkSystem.createSocket(fd, true); - // } - - /* - * Package private constructor. - */ - SocketChannelImpl(Socket aSocket, FileDescriptor aFd) { - super(SelectorProvider.provider()); - socket = aSocket; - fd = aFd; - status = SOCKET_STATUS_UNCONNECTED; - } - - // ------------------------------------------------------------------- - // Methods for getting internal Socket. - // ------------------------------------------------------------------- - - /* - * Getting the internal Socket If we have not the socket, we create a new - * one. - */ - @Override - synchronized public Socket socket() { - if (null == socket) { - try { - InetAddress addr = null; - int port = 0; - if (connectAddress != null) { - addr = connectAddress.getAddress(); - port = connectAddress.getPort(); - } - socket = new SocketAdapter(SocketImplProvider.getSocketImpl(fd, - localPort, addr, port), this); - } catch (SocketException e) { - return null; - } - } - return socket; - } - - // ------------------------------------------------------------------- - // Methods for connect and finishConnect - // ------------------------------------------------------------------- - - /* - * @see java.nio.channels.SocketChannel#isConnected() - */ - @Override - synchronized public boolean isConnected() { - return status == SOCKET_STATUS_CONNECTED; - } - - /* - * status setting used by other class. - */ - synchronized void setConnected() { - status = SOCKET_STATUS_CONNECTED; - } - - // BEGIN android-added - // copied from a newer version of harmony - void setBound(boolean flag) { - isBound = flag; - } - // END android-added - - /* - * @see java.nio.channels.SocketChannel#isConnectionPending() - */ - @Override - synchronized public boolean isConnectionPending() { - return status == SOCKET_STATUS_PENDING; - } - - /* - * @see java.nio.channels.SocketChannel#connect(java.net.SocketAddress) - */ - @Override - public boolean connect(SocketAddress socketAddress) throws IOException { - // status must be open and unconnected - checkUnconnected(); - - // check the address - InetSocketAddress inetSocketAddress = validateAddress(socketAddress); - - int port = inetSocketAddress.getPort(); - String hostName = inetSocketAddress.getAddress().getHostName(); - // security check - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkConnect(hostName, port); - } - - // connect result - int result = EOF; - boolean finished = false; - - try { - if (!isBound) { - // bind - networkSystem.bind2(fd, 0, true, InetAddress - .getByAddress(new byte[] { 0, 0, 0, 0 })); - isBound = true; - } - - if (isBlocking()) { - begin(); - result = networkSystem.connect(fd, trafficClass, - inetSocketAddress.getAddress(), inetSocketAddress - .getPort()); - - } else { - result = networkSystem.connectWithTimeout(fd, 0, trafficClass, - inetSocketAddress.getAddress(), inetSocketAddress - .getPort(), HY_SOCK_STEP_START, connectContext); - // set back to nonblocking to work around with a bug in portlib - if (!this.isBlocking()) { - networkSystem.setNonBlocking(fd, true); - } - } - finished = (CONNECT_SUCCESS == result); - isBound = finished; - } catch (IOException e) { - if (e instanceof ConnectException && !isBlocking()) { - status = SOCKET_STATUS_PENDING; - } else { - if (isOpen()) { - close(); - finished = true; - } - throw e; - } - } finally { - if (isBlocking()) { - end(finished); - } - } - - // set local port - localPort = networkSystem.getSocketLocalPort(fd, false); - localAddress = networkSystem.getSocketLocalAddress(fd, false); - - // set the connected address. - connectAddress = inetSocketAddress; - synchronized (this) { - if (isBlocking()) { - status = (finished ? SOCKET_STATUS_CONNECTED - : SOCKET_STATUS_UNCONNECTED); - } else { - status = SOCKET_STATUS_PENDING; - } - } - return finished; - } - - /* - * @see java.nio.channels.SocketChannel#finishConnect() - */ - @Override - public boolean finishConnect() throws IOException { - // status check - synchronized (this) { - if (!isOpen()) { - throw new ClosedChannelException(); - } - if (status == SOCKET_STATUS_CONNECTED) { - return true; - } - if (status != SOCKET_STATUS_PENDING) { - throw new NoConnectionPendingException(); - } - } - - // finish result - int result = EOF; - boolean finished = false; - - try { - begin(); - result = networkSystem.connectWithTimeout(fd, - isBlocking() ? -1 : 0, trafficClass, connectAddress - .getAddress(), connectAddress.getPort(), - HY_PORT_SOCKET_STEP_CHECK, connectContext); - finished = (result == CONNECT_SUCCESS); - isBound = finished; - localAddress = networkSystem.getSocketLocalAddress(fd, false); - } catch (ConnectException e) { - if (isOpen()) { - close(); - finished = true; - } - throw e; - } finally { - end(finished); - } - - synchronized (this) { - status = (finished ? SOCKET_STATUS_CONNECTED : status); - isBound = finished; - } - return finished; - } - - // ------------------------------------------------------------------- - // Methods for read and write - // ------------------------------------------------------------------- - /* - * @see java.nio.channels.SocketChannel#read(java.nio.ByteBuffer) - */ - @Override - public int read(ByteBuffer target) throws IOException { - if (null == target) { - throw new NullPointerException(); - } - checkOpenConnected(); - if (!target.hasRemaining()) { - return 0; - } - - int readCount; - if (target.isDirect() || target.hasArray()) { - readCount = readImpl(target); - if (readCount > 0) { - target.position(target.position() + readCount); - } - } else { - ByteBuffer readBuffer = null; - byte[] readArray = null; - readArray = new byte[target.remaining()]; - readBuffer = ByteBuffer.wrap(readArray); - readCount = readImpl(readBuffer); - if (readCount > 0) { - target.put(readArray, 0, readCount); - } - } - return readCount; - } - - /* - * @see java.nio.channels.SocketChannel#read(java.nio.ByteBuffer[], int, - * int) - */ - @Override - public long read(ByteBuffer[] targets, int offset, int length) - throws IOException { - if (!isIndexValid(targets, offset, length)) { - throw new IndexOutOfBoundsException(); - } - - checkOpenConnected(); - int totalCount = calculateByteBufferArray(targets, offset, length); - if (0 == totalCount) { - return 0; - } - byte[] readArray = new byte[totalCount]; - ByteBuffer readBuffer = ByteBuffer.wrap(readArray); - int readCount; - // read data to readBuffer, and then transfer data from readBuffer to - // targets. - readCount = readImpl(readBuffer); - if (readCount > 0) { - int left = readCount; - int index = offset; - // transfer data from readArray to targets - while (left > 0) { - int putLength = Math.min(targets[index].remaining(), left); - targets[index].put(readArray, readCount - left, putLength); - index++; - left -= putLength; - } - } - return readCount; - } - - private boolean isIndexValid(ByteBuffer[] targets, int offset, int length) { - return (length >= 0) && (offset >= 0) - && ((long)length + (long)offset <= targets.length); - } - - /* - * read from channel, and store the result in the target. - * - * @param target output parameter - */ - private int readImpl(ByteBuffer target) throws IOException { - synchronized(readLock){ - int readCount = 0; - try { - if (isBlocking()) { - begin(); - } - int offset = target.position(); - int length = target.remaining(); - if (target.isDirect()) { - int address = AddressUtil.getDirectBufferAddress(target); - readCount = networkSystem.readDirect(fd, address, offset, - length, (isBlocking() ? TIMEOUT_BLOCK - : TIMEOUT_NONBLOCK)); - } else { - // target is assured to have array. - byte[] array = target.array(); - offset += target.arrayOffset(); - readCount = networkSystem.read(fd, array, offset, length, - (isBlocking() ? TIMEOUT_BLOCK : TIMEOUT_NONBLOCK)); - } - return readCount; - } finally { - if (isBlocking()) { - end(readCount > 0); - } - } - } - } - - /* - * - * @see java.nio.channels.SocketChannel#write(java.nio.ByteBuffer) - */ - @Override - public int write(ByteBuffer source) throws IOException { - if (null == source) { - throw new NullPointerException(); - } - checkOpenConnected(); - if (!source.hasRemaining()) { - return 0; - } - return writeImpl(source); - } - - /* - * @see java.nio.channels.SocketChannel#write(java.nio.ByteBuffer[], int, - * int) - */ - @Override - public long write(ByteBuffer[] sources, int offset, int length) - throws IOException { - if (!isIndexValid(sources, offset, length)) { - throw new IndexOutOfBoundsException(); - } - - checkOpenConnected(); - int count = calculateByteBufferArray(sources, offset, length); - if (0 == count) { - return 0; - } - ByteBuffer writeBuf = ByteBuffer.allocate(count); - for (int val = offset; val < length+offset; val++) { - ByteBuffer source = sources[val]; - int oldPosition = source.position(); - writeBuf.put(source); - source.position(oldPosition); - } - writeBuf.flip(); - int result = writeImpl(writeBuf); - int val = offset; - int written = result; - while (result > 0) { - ByteBuffer source = sources[val]; - int gap = Math.min(result, source.remaining()); - source.position(source.position() + gap); - val++; - result -= gap; - } - return written; - } - - private int calculateByteBufferArray(ByteBuffer[] sources, int offset, - int length) { - int sum = 0; - for (int val = offset; val < offset + length; val++) { - sum = sum + sources[val].remaining(); - } - return sum; - } - - /* - * write the source. return the count of bytes written. - */ - private int writeImpl(ByteBuffer source) throws IOException { - synchronized(writeLock){ - if (!source.hasRemaining()) { - return 0; - } - int writeCount = 0; - try { - int pos = source.position(); - int length = source.remaining(); - if (isBlocking()) { - begin(); - } - if (source.isDirect()) { - int address = AddressUtil.getDirectBufferAddress(source); - writeCount = networkSystem - .writeDirect(fd, address, pos, length); - } else if (source.hasArray()) { - pos += source.arrayOffset(); - writeCount = networkSystem.write(fd, source.array(), pos, - length); - } else { - byte[] array = new byte[length]; - source.get(array); - writeCount = networkSystem.write(fd, array, 0, length); - } - source.position(pos + writeCount); - } catch (SocketException e) { - if (e.getCause() instanceof ErrorCodeException) { - if (ERRCODE_SOCKET_NONBLOCKING_WOULD_BLOCK == ((ErrorCodeException) e - .getCause()).getErrorCode()) { - return writeCount; - } - } - throw e; - } finally { - if (isBlocking()) { - end(writeCount >= 0); - } - } - return writeCount; - } - } - - // ------------------------------------------------------------------- - // Shared methods - // ------------------------------------------------------------------- - - /* - * status check, open and "connected", when read and write. - */ - synchronized private void checkOpenConnected() - throws ClosedChannelException { - if (!isOpen()) { - throw new ClosedChannelException(); - } - if (!isConnected()) { - throw new NotYetConnectedException(); - } - } - - /* - * status check, open and "unconnected", before connection. - */ - synchronized private void checkUnconnected() throws IOException { - if (!isOpen()) { - throw new ClosedChannelException(); - } - if (status == SOCKET_STATUS_CONNECTED) { - throw new AlreadyConnectedException(); - } - if (status == SOCKET_STATUS_PENDING) { - throw new ConnectionPendingException(); - } - } - - /* - * shared by this class and DatagramChannelImpl, to do the address transfer - * and check. - */ - static InetSocketAddress validateAddress(SocketAddress socketAddress) { - if (null == socketAddress) { - throw new IllegalArgumentException(); - } - if (!(socketAddress instanceof InetSocketAddress)) { - throw new UnsupportedAddressTypeException(); - } - InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress; - if (inetSocketAddress.isUnresolved()) { - throw new UnresolvedAddressException(); - } - return inetSocketAddress; - } - - /* - * get local address - */ - public InetAddress getLocalAddress() throws UnknownHostException { - byte[] any_bytes = { 0, 0, 0, 0 }; - if (!isBound) { - return InetAddress.getByAddress(any_bytes); - } - return localAddress; - } - - // ------------------------------------------------------------------- - // Protected inherited methods - // ------------------------------------------------------------------- - /* - * do really closing action here - */ - @Override - synchronized protected void implCloseSelectableChannel() throws IOException { - if (SOCKET_STATUS_CLOSED != status) { - status = SOCKET_STATUS_CLOSED; - if (null != socket && !socket.isClosed()) { - socket.close(); - } else { - networkSystem.socketClose(fd); - } - } - } - - /* - * @see java.nio.channels.spi.AbstractSelectableChannel#implConfigureBlocking(boolean) - */ - @Override - protected void implConfigureBlocking(boolean blockMode) throws IOException { - synchronized (blockingLock()) { - networkSystem.setNonBlocking(fd, !blockMode); - } - } - - /* - * get the fd - */ - public FileDescriptor getFD() { - return fd; - } - - // ------------------------------------------------------------------- - // Adapter classes for internal socket. - // ------------------------------------------------------------------- - - private static class SocketAdapter extends Socket { - - // ---------------------------------------------------- - // Class Variables - // ---------------------------------------------------- - - SocketChannelImpl channel; - - SocketImpl socketImpl; - - // ---------------------------------------------------- - // Methods - // ---------------------------------------------------- - - SocketAdapter(SocketImpl socketimpl, SocketChannelImpl channel) - throws SocketException { - super(socketimpl); - socketImpl = socketimpl; - this.channel = channel; - } - - /* - * - * @see java.net.Socket#getChannel() - */ - @Override - public SocketChannel getChannel() { - return channel; - } - - /* - * - * @see java.net.Socket#isBound() - */ - @Override - public boolean isBound() { - return channel.isBound; - } - - /* - * - * @see java.net.Socket#isConnected() - */ - @Override - public boolean isConnected() { - return channel.isConnected(); - } - - /* - * - * @see java.net.Socket#getLocalAddress() - */ - @Override - public InetAddress getLocalAddress() { - try { - return channel.getLocalAddress(); - } catch (UnknownHostException e) { - return null; - } - } - - /* - * - * @see java.net.Socket#connect(java.net.SocketAddress, int) - */ - @Override - public void connect(SocketAddress remoteAddr, int timeout) - throws IOException { - if (!channel.isBlocking()) { - throw new IllegalBlockingModeException(); - } - if (isConnected()) { - throw new AlreadyConnectedException(); - } - super.connect(remoteAddr, timeout); - channel.localAddress = networkSystem.getSocketLocalAddress( - channel.fd, false); - if (super.isConnected()) { - channel.setConnected(); - channel.isBound = super.isBound(); - } - } - - /* - * - * @see java.net.Socket#bind(java.net.SocketAddress) - */ - @Override - public void bind(SocketAddress localAddr) throws IOException { - if (channel.isConnected()) { - throw new AlreadyConnectedException(); - } - if (SocketChannelImpl.SOCKET_STATUS_PENDING == channel.status) { - throw new ConnectionPendingException(); - } - super.bind(localAddr); - // keep here to see if need next version - // channel.Address = getLocalSocketAddress(); - // channel.localport = getLocalPort(); - channel.isBound = true; - - } - - /* - * - * @see java.net.Socket#close() - */ - @Override - public void close() throws IOException { - synchronized (channel) { - if (channel.isOpen()) { - channel.close(); - } else { - super.close(); - } - channel.status = SocketChannelImpl.SOCKET_STATUS_CLOSED; - } - } - - @Override - public boolean getReuseAddress() throws SocketException { - checkOpen(); - return ((Boolean) socketImpl.getOption(SocketOptions.SO_REUSEADDR)) - .booleanValue(); - } - - @Override - public synchronized int getReceiveBufferSize() throws SocketException { - checkOpen(); - return ((Integer) socketImpl.getOption(SocketOptions.SO_RCVBUF)) - .intValue(); - } - - @Override - public synchronized int getSendBufferSize() throws SocketException { - checkOpen(); - return ((Integer) socketImpl.getOption(SocketOptions.SO_SNDBUF)) - .intValue(); - } - - @Override - public synchronized int getSoTimeout() throws SocketException { - checkOpen(); - return ((Integer) socketImpl.getOption(SocketOptions.SO_TIMEOUT)) - .intValue(); - } - - @Override - public int getTrafficClass() throws SocketException { - checkOpen(); - return ((Number) socketImpl.getOption(SocketOptions.IP_TOS)) - .intValue(); - } - - /* - * - * @see java.net.Socket#getKeepAlive() - */ - @Override - public boolean getKeepAlive() throws SocketException { - checkOpen(); - return ((Boolean) socketImpl.getOption(SocketOptions.SO_KEEPALIVE)) - .booleanValue(); - } - - /* - * - * @see java.net.Socket#getOOBInline() - */ - @Override - public boolean getOOBInline() throws SocketException { - checkOpen(); - return ((Boolean) socketImpl.getOption(SocketOptions.SO_OOBINLINE)) - .booleanValue(); - } - - /* - * - * @see java.net.Socket#getSoLinger() - */ - @Override - public int getSoLinger() throws SocketException { - checkOpen(); - return ((Integer) socketImpl.getOption(SocketOptions.SO_LINGER)) - .intValue(); - } - - /* - * @see java.net.Socket#getTcpNoDelay() - */ - @Override - public boolean getTcpNoDelay() throws SocketException { - checkOpen(); - return ((Boolean) socketImpl.getOption(SocketOptions.TCP_NODELAY)) - .booleanValue(); - } - - /* - * @see java.net.Socket#getOutputStream() - */ - @Override - public OutputStream getOutputStream() throws IOException { - if (!channel.isOpen()) { - // nio.00=Socket is closed - throw new SocketException(Messages.getString("nio.00")); //$NON-NLS-1$ - } - if (!channel.isConnected()) { - // nio.01=Socket is not connected - throw new SocketException(Messages.getString("nio.01")); //$NON-NLS-1$ - } - if (isOutputShutdown()) { - // nio.02=Socket output is shutdown - throw new SocketException(Messages.getString("nio.02")); //$NON-NLS-1$ - } - return new SocketChannelOutputStream(channel); - } - - /* - * - * @see java.net.Socket#getInputStream() - */ - @Override - public InputStream getInputStream() throws IOException { - if (!channel.isOpen()) { - // nio.00=Socket is closed - throw new SocketException(Messages.getString("nio.00")); //$NON-NLS-1$ - } - if (!channel.isConnected()) { - // nio.01=Socket is not connected - throw new SocketException(Messages.getString("nio.01")); //$NON-NLS-1$ - } - if (isInputShutdown()) { - // nio.03=Socket input is shutdown - throw new SocketException(Messages.getString("nio.03")); //$NON-NLS-1$ - } - return new SocketChannelInputStream(channel); - } - - /* - * Checks whether the channel is open - */ - private void checkOpen() throws SocketException { - if (isClosed()) { - // nio.00=Socket is closed - throw new SocketException(Messages.getString("nio.00")); //$NON-NLS-1$ - } - } - - /* - * used for net and nio exchange - */ - public SocketImpl getImpl() { - return socketImpl; - } - } - - /* - * This output stream delegates all operations to the associated channel. - * Throws an IllegalBlockingModeException if the channel is in non-blocking - * mode when performing write operations. - */ - private static class SocketChannelOutputStream extends OutputStream { - SocketChannel channel; - - public SocketChannelOutputStream(SocketChannel channel) { - this.channel = channel; - } - - /* - * Closes this stream and channel - * - * @exception IOException thrown if an error occurs during the close - */ - @Override - public void close() throws IOException { - channel.close(); - } - - /* - * @see java.io.OutputStream#write(byte[], int, int) - */ - @Override - public void write(byte[] buffer, int offset, int count) - throws IOException { - if (0 > offset || 0 > count || count + offset > buffer.length) { - throw new IndexOutOfBoundsException(); - } - ByteBuffer buf = ByteBuffer.wrap(buffer, offset, count); - if (!channel.isBlocking()) { - throw new IllegalBlockingModeException(); - } - channel.write(buf); - } - - /* - * @see java.io.OutputStream#write(int) - */ - @Override - public void write(int oneByte) throws IOException { - if (!channel.isBlocking()) { - throw new IllegalBlockingModeException(); - } - ByteBuffer buffer = ByteBuffer.allocate(1); - buffer.put(0, (byte) (oneByte & 0xFF)); - channel.write(buffer); - } - } - - /* - * This input stream delegates all operations to the associated channel. - * Throws an IllegalBlockingModeException if the channel is in non-blocking - * mode when performing read operations. - */ - private static class SocketChannelInputStream extends InputStream { - SocketChannel channel; - - public SocketChannelInputStream(SocketChannel channel) { - this.channel = channel; - } - - /* - * Closes this stream and channel. - */ - @Override - public void close() throws IOException { - channel.close(); - } - - /* - * @see java.io.InputStream#read() - */ - @Override - public int read() throws IOException { - if (!channel.isBlocking()) { - throw new IllegalBlockingModeException(); - } - ByteBuffer buf = ByteBuffer.allocate(1); - int result = channel.read(buf); - // BEGIN android-changed: input was already consumed - return (-1 == result) ? result : buf.get(0) & 0xFF; - // END android-changed - } - - /* - * @see java.io.InputStream#read(byte[], int, int) - */ - @Override - public int read(byte[] buffer, int offset, int count) - throws IOException { - if (0 > offset || 0 > count || count + offset > buffer.length) { - throw new IndexOutOfBoundsException(); - } - if (!channel.isBlocking()) { - throw new IllegalBlockingModeException(); - } - ByteBuffer buf = ByteBuffer.wrap(buffer, offset, count); - return channel.read(buf); - } - } -} diff --git a/nio/src/main/java/org/apache/harmony/nio/internal/WriteOnlyFileChannel.java b/nio/src/main/java/org/apache/harmony/nio/internal/WriteOnlyFileChannel.java deleted file mode 100644 index ffcdd14..0000000 --- a/nio/src/main/java/org/apache/harmony/nio/internal/WriteOnlyFileChannel.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Android Notice - * In this class the address length was changed from long to int. - * This is due to performance optimizations for the device. - */ - -package org.apache.harmony.nio.internal; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.MappedByteBuffer; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.FileLock; -import java.nio.channels.NonReadableChannelException; -import java.nio.channels.WritableByteChannel; - -public final class WriteOnlyFileChannel extends FileChannelImpl { - - private boolean append = false; - - public WriteOnlyFileChannel(Object stream, int handle) { - super(stream, handle); - } - - public WriteOnlyFileChannel(Object stream, int handle, boolean isAppend) { - super(stream, handle); - append = isAppend; - } - - /* - * (non-Javadoc) - * @see org.apache.harmony.nio.internal.FileChannelImpl#position() - */ - public long position() throws IOException { - return append ? size() : super.position(); - } - - public long transferTo(long position, long count, WritableByteChannel target) - throws IOException { - openCheck(); - if (!target.isOpen()) { - throw new ClosedChannelException(); - } - throw new NonReadableChannelException(); - } - - public long read(ByteBuffer[] buffers, int offset, int length) - throws IOException { - if (offset < 0 || length < 0 || offset + length > buffers.length) { - throw new IndexOutOfBoundsException(); - } - openCheck(); - throw new NonReadableChannelException(); - } - - public int read(ByteBuffer buffer) throws IOException { - openCheck(); - throw new NonReadableChannelException(); - } - - public int read(ByteBuffer buffer, long position) throws IOException { - if (null == buffer) { - throw new NullPointerException(); - } - if (position < 0){ - throw new IllegalArgumentException(); - } - throw new NonReadableChannelException(); - } - - public MappedByteBuffer map(MapMode mode, long position, long size) - throws IOException { - openCheck(); - if (mode == null) { - throw new NullPointerException(); - } - if (position < 0 || size < 0 || size > Integer.MAX_VALUE) { - throw new IllegalArgumentException(); - } - throw new NonReadableChannelException(); - } - - public int write(ByteBuffer buffer) throws IOException { - if (append) { - position(size()); - } - return super.write(buffer); - } - - protected final FileLock basicLock(long position, long size, - boolean shared, boolean wait) throws IOException { - if (shared) { - throw new NonReadableChannelException(); - } - return super.basicLock(position, size, shared, wait); - } - -} diff --git a/nio/src/main/java/org/apache/harmony/nio/internal/nls/Messages.java b/nio/src/main/java/org/apache/harmony/nio/internal/nls/Messages.java deleted file mode 100644 index d291f12..0000000 --- a/nio/src/main/java/org/apache/harmony/nio/internal/nls/Messages.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * THE FILE HAS BEEN AUTOGENERATED BY MSGTOOL TOOL. - * All changes made to this file manually will be overwritten - * if this tool runs again. Better make changes in the template file. - */ - -package org.apache.harmony.nio.internal.nls; - - -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -// BEGIN android-changed -import org.apache.harmony.luni.util.MsgHelp; -// END android-changed - -/** - * This class retrieves strings from a resource bundle and returns them, - * formatting them with MessageFormat when required. - * <p> - * It is used by the system classes to provide national language support, by - * looking up messages in the <code> - * org.apache.harmony.nio.internal.nls.messages - * </code> - * resource bundle. Note that if this file is not available, or an invalid key - * is looked up, or resource bundle support is not available, the key itself - * will be returned as the associated message. This means that the <em>KEY</em> - * should a reasonable human-readable (english) string. - * - */ -public class Messages { - - // BEGIN android-changed - private static final String sResource = - "org.apache.harmony.nio.internal.nls.messages"; //$NON-NLS-1$ - // END android-changed - - /** - * Retrieves a message which has no arguments. - * - * @param msg - * String the key to look up. - * @return String the message for that key in the system message bundle. - */ - static public String getString(String msg) { - // BEGIN android-changed - return MsgHelp.getString(sResource, msg); - // END android-changed - } - - /** - * Retrieves a message which takes 1 argument. - * - * @param msg - * String the key to look up. - * @param arg - * Object the object to insert in the formatted output. - * @return String the message for that key in the system message bundle. - */ - static public String getString(String msg, Object arg) { - return getString(msg, new Object[] { arg }); - } - - /** - * Retrieves a message which takes 1 integer argument. - * - * @param msg - * String the key to look up. - * @param arg - * int the integer to insert in the formatted output. - * @return String the message for that key in the system message bundle. - */ - static public String getString(String msg, int arg) { - return getString(msg, new Object[] { Integer.toString(arg) }); - } - - /** - * Retrieves a message which takes 1 character argument. - * - * @param msg - * String the key to look up. - * @param arg - * char the character to insert in the formatted output. - * @return String the message for that key in the system message bundle. - */ - static public String getString(String msg, char arg) { - return getString(msg, new Object[] { String.valueOf(arg) }); - } - - /** - * Retrieves a message which takes 2 arguments. - * - * @param msg - * String the key to look up. - * @param arg1 - * Object an object to insert in the formatted output. - * @param arg2 - * Object another object to insert in the formatted output. - * @return String the message for that key in the system message bundle. - */ - static public String getString(String msg, Object arg1, Object arg2) { - return getString(msg, new Object[] { arg1, arg2 }); - } - - /** - * Retrieves a message which takes several arguments. - * - * @param msg - * String the key to look up. - * @param args - * Object[] the objects to insert in the formatted output. - * @return String the message for that key in the system message bundle. - */ - static public String getString(String msg, Object[] args) { - // BEGIN android-changed - return MsgHelp.getString(sResource, msg, args); - // END android-changed - } - - // BEGIN android-note - // Duplicate code was dropped in favor of using MsgHelp. - // END android-note -} diff --git a/nio/src/main/java/org/apache/harmony/nio/internal/nls/messages.properties b/nio/src/main/java/org/apache/harmony/nio/internal/nls/messages.properties deleted file mode 100644 index 79d1c84..0000000 --- a/nio/src/main/java/org/apache/harmony/nio/internal/nls/messages.properties +++ /dev/null @@ -1,28 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# messages for EN locale -nio.00=Socket is closed -nio.01=Socket is not connected -nio.02=Socket output is shutdown -nio.03=Socket input is shutdown -nio.04=Size mismatch -nio.05=Negative index specified -nio.06=InputStreamReader is closed. -nio.07=Writer is closed. -nio.08=Cannot use the direct byte buffer after it has been explicitly freed. -nio.09=Unknown file channel type: {0} -nio.0A=Lock position and size must be non-negative. -nio.0B=New position must be non-negative. |