Merge "Hide java.security.Signatue#getCurrentSpi"
diff --git a/JavaLibrary.mk b/JavaLibrary.mk
index bbe2345..5f9cceb 100644
--- a/JavaLibrary.mk
+++ b/JavaLibrary.mk
@@ -87,6 +87,7 @@
LOCAL_JAVACFLAGS := $(local_javac_flags)
LOCAL_DX_FLAGS := --core-library
LOCAL_MODULE_TAGS := optional
+LOCAL_JAVA_LANGUAGE_VERSION := 1.8
LOCAL_MODULE := core-all
LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/JavaLibrary.mk
LOCAL_REQUIRED_MODULES := tzdata
@@ -101,6 +102,7 @@
LOCAL_JAVACFLAGS := $(local_javac_flags)
LOCAL_DX_FLAGS := --core-library
LOCAL_MODULE_TAGS := optional
+LOCAL_JAVA_LANGUAGE_VERSION := 1.8
LOCAL_MODULE := core-oj
LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/JavaLibrary.mk
LOCAL_JAVA_LIBRARIES := core-all
@@ -117,6 +119,7 @@
LOCAL_JAVACFLAGS := $(local_javac_flags)
LOCAL_DX_FLAGS := --core-library
LOCAL_MODULE_TAGS := optional
+LOCAL_JAVA_LANGUAGE_VERSION := 1.8
LOCAL_MODULE := core-libart
LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/JavaLibrary.mk
LOCAL_JAVA_LIBRARIES := core-all
@@ -135,6 +138,7 @@
LOCAL_DX_FLAGS := --core-library
LOCAL_MODULE_TAGS := optional
LOCAL_DEX_PREOPT := false
+LOCAL_JAVA_LANGUAGE_VERSION := 1.8
LOCAL_MODULE := core-oj-testdex
LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/JavaLibrary.mk
LOCAL_JAVA_LIBRARIES := core-all
@@ -151,6 +155,7 @@
LOCAL_DX_FLAGS := --core-library
LOCAL_MODULE_TAGS := optional
LOCAL_DEX_PREOPT := false
+LOCAL_JAVA_LANGUAGE_VERSION := 1.8
LOCAL_MODULE := core-libart-testdex
LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/JavaLibrary.mk
LOCAL_JAVA_LIBRARIES := core-all
@@ -218,6 +223,7 @@
LOCAL_JAVACFLAGS := $(local_javac_flags)
LOCAL_DX_FLAGS := --core-library
LOCAL_MODULE_TAGS := optional
+LOCAL_JAVA_LANGUAGE_VERSION := 1.8
LOCAL_MODULE := core-all-hostdex
LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/JavaLibrary.mk
LOCAL_REQUIRED_MODULES := tzdata-host
@@ -232,6 +238,7 @@
LOCAL_JAVACFLAGS := $(local_javac_flags)
LOCAL_DX_FLAGS := --core-library
LOCAL_MODULE_TAGS := optional
+LOCAL_JAVA_LANGUAGE_VERSION := 1.8
LOCAL_MODULE := core-oj-hostdex
LOCAL_NOTICE_FILE := $(LOCAL_PATH)/ojluni/NOTICE
LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/JavaLibrary.mk
@@ -248,6 +255,7 @@
LOCAL_JAVACFLAGS := $(local_javac_flags)
LOCAL_DX_FLAGS := --core-library
LOCAL_MODULE_TAGS := optional
+LOCAL_JAVA_LANGUAGE_VERSION := 1.8
LOCAL_MODULE := core-libart-hostdex
LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/JavaLibrary.mk
LOCAL_JAVA_LIBRARIES := core-oj-hostdex
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/MockDatagramChannel.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/MockDatagramChannel.java
index db5815f..5d5140e 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/MockDatagramChannel.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/MockDatagramChannel.java
@@ -25,7 +25,6 @@
import java.net.SocketOption;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
-import java.nio.channels.MembershipKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Set;
@@ -108,34 +107,7 @@
}
@Override
- public <T> T getOption(SocketOption<T> name) throws IOException {
- return null;
- }
-
- @Override
public DatagramChannel bind(SocketAddress local) throws IOException {
return null;
}
-
- @Override
- public MembershipKey join(InetAddress group, NetworkInterface interf) {
- return null;
- }
-
- @Override
- public MembershipKey join(InetAddress group, NetworkInterface interf, InetAddress source)
- throws IOException {
- return null;
- }
-
- @Override
- public Set<SocketOption<?>> supportedOptions() {
- return null;
- }
-
- @Override
- public SocketAddress getLocalAddress() throws IOException {
- return null;
- }
-
}
diff --git a/java_tests_blacklist b/java_tests_blacklist
index 97782ea..c0fbc88 100644
--- a/java_tests_blacklist
+++ b/java_tests_blacklist
@@ -1,7 +1,5 @@
luni/src/test/java/tests/security/cert/X509CRLSelector2Test.java
luni/src/test/java/tests/security/cert/X509CertSelectorTest.java
-luni/src/test/java/libcore/net/url/UrlUtilsTest.java
luni/src/test/java/libcore/java/util/zip/Zip64Test.java
luni/src/test/java/libcore/java/util/zip/Zip64FileTest.java
-luni/src/test/java/libcore/java/util/zip/ZipEntryTest.java
luni/src/test/java/libcore/java/security/cert/X509CertificateTest.java
diff --git a/luni/src/main/native/NetworkUtilities.cpp b/luni/src/main/native/NetworkUtilities.cpp
index e357b4a..b285a01 100644
--- a/luni/src/main/native/NetworkUtilities.cpp
+++ b/luni/src/main/native/NetworkUtilities.cpp
@@ -116,8 +116,11 @@
}
// Get the byte array that stores the IP address bytes in the InetAddress.
- static jmethodID bytesMid = env->GetMethodID(JniConstants::inetAddressClass, "getAddressInternal", "()[B");
+ static jmethodID bytesMid = env->GetMethodID(JniConstants::inetAddressClass, "getAddress", "()[B");
ScopedLocalRef<jbyteArray> addressBytes(env, reinterpret_cast<jbyteArray>(env->CallObjectMethod(inetAddress, bytesMid)));
+ if (env->ExceptionCheck()) {
+ return false;
+ }
if (addressBytes.get() == NULL) {
jniThrowNullPointerException(env, NULL);
return false;
diff --git a/luni/src/test/java/libcore/io/OsTest.java b/luni/src/test/java/libcore/io/OsTest.java
index d2c4058..552c2a1 100644
--- a/luni/src/test/java/libcore/io/OsTest.java
+++ b/luni/src/test/java/libcore/io/OsTest.java
@@ -49,7 +49,7 @@
fis.close();
ServerSocket s = new ServerSocket();
- assertTrue(S_ISSOCK(Libcore.os.fstat(s.getImpl().getFileDescriptor()).st_mode));
+ assertTrue(S_ISSOCK(Libcore.os.fstat(s.getImpl().getFD$()).st_mode));
s.close();
}
diff --git a/luni/src/test/java/libcore/java/io/FileDescriptorTest.java b/luni/src/test/java/libcore/java/io/FileDescriptorTest.java
index adaa931..3e82690 100644
--- a/luni/src/test/java/libcore/java/io/FileDescriptorTest.java
+++ b/luni/src/test/java/libcore/java/io/FileDescriptorTest.java
@@ -37,7 +37,7 @@
fis.close();
ServerSocket s = new ServerSocket();
- assertTrue(s.getImpl().getFileDescriptor().isSocket$());
+ assertTrue(s.getImpl().getFD$().isSocket$());
s.close();
}
}
diff --git a/luni/src/test/java/libcore/java/net/NetworkInterfaceTest.java b/luni/src/test/java/libcore/java/net/NetworkInterfaceTest.java
index ef3a228..73cb7ac 100644
--- a/luni/src/test/java/libcore/java/net/NetworkInterfaceTest.java
+++ b/luni/src/test/java/libcore/java/net/NetworkInterfaceTest.java
@@ -31,6 +31,9 @@
import java.util.Set;
import libcore.io.IoUtils;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
public class NetworkInterfaceTest extends TestCase {
// http://code.google.com/p/android/issues/detail?id=13784
private final static int ARPHRD_ETHER = 1; // from if_arp.h
@@ -143,13 +146,9 @@
}
}
- // Returns true if interface by name ifName is Ethernet
- private boolean isEthernet(String ifName) throws Exception {
- String s = IoUtils.readFileAsString("/sys/class/net/" + ifName + "/type").trim();
- if (s.startsWith("0x")) {
- return (Integer.parseInt(s.substring(2), 16) == ARPHRD_ETHER);
- } else {
- return (Integer.parseInt(s) == ARPHRD_ETHER);
- }
+ // Is ifName a name of a Ethernet device?
+ private static Pattern ethernetNamePattern = Pattern.compile("^(eth|wlan)[0-9]+$");
+ private static boolean isEthernet(String ifName) throws Exception {
+ return ethernetNamePattern.matcher(ifName).matches();
}
}
diff --git a/luni/src/test/java/libcore/java/sql/OldPreparedStatementTest.java b/luni/src/test/java/libcore/java/sql/OldPreparedStatementTest.java
index 8fd8665..9c99e62 100755
--- a/luni/src/test/java/libcore/java/sql/OldPreparedStatementTest.java
+++ b/luni/src/test/java/libcore/java/sql/OldPreparedStatementTest.java
@@ -272,8 +272,7 @@
String[] queries2 = {
"update zoo set name='Masha', family='cat' where id=;",
"insert into hutch (id, animal_id, address) values (1, ?,'Birds-house, 1');",
- "insert into hutch (id, animal_id, address) values (?, 1, 'Horse-house, 5');",
- "create view address as select address from hutch where animal_id=?"};
+ "insert into hutch (id, animal_id, address) values (?, 1, 'Horse-house, 5');"};
for (int i = 0; i < queries2.length; i++) {
PreparedStatement ps = null;
@@ -324,41 +323,40 @@
// TODO Crashes VM. Fix later.
public void testExecuteUpdate() throws SQLException {
- String[] queries1 = { "insert into hutch (id, animal_id, address) values (1, ?, 'Birds-house, 1');",
- "insert into hutch (id, animal_id, address) values (?, 1, 'Horse-house, 5');",
- "create view address as select address from hutch where animal_id=2" };
+ String[] queries1 = { "insert into hutch (id, animal_id, address) values (1, ?, 'Birds-house, 1');",
+ "insert into hutch (id, animal_id, address) values (?, 1, 'Horse-house, 5');"};
- for (int i = 0; i < queries1.length; i++) {
- PreparedStatement ps = null;
- try {
- ps = conn.prepareStatement(queries1[i]);
- ps.executeUpdate();
- fail("SQLException is not thrown for query: " + queries1[i]);
- } catch(SQLException sqle) {
- // expected
- } finally {
- try {
- ps.close();
- } catch(Exception ee) {}
- }
- }
+ for (int i = 0; i < queries1.length; i++) {
+ PreparedStatement ps = null;
+ try {
+ ps = conn.prepareStatement(queries1[i]);
+ ps.executeUpdate();
+ fail("SQLException is not thrown for query: " + queries1[i]);
+ } catch(SQLException sqle) {
+ // expected
+ } finally {
+ try {
+ ps.close();
+ } catch(Exception ee) {}
+ }
+ }
- String query = "update zoo set name='Masha', family='cat' where id=?;";
- PreparedStatement ps = null;
- try {
- ps = conn.prepareStatement(query);
- ps.setInt(1, 2);
- int updateCount = ps.executeUpdate();
- assertEquals(1, updateCount);
- ps.setInt(1, 1);
- int updateCount1 = ps.executeUpdate();
- assertEquals(1, updateCount1);
- } finally {
- try {
- ps.close();
- } catch(Exception ee) {}
- }
- }
+ String query = "update zoo set name='Masha', family='cat' where id=?;";
+ PreparedStatement ps = null;
+ try {
+ ps = conn.prepareStatement(query);
+ ps.setInt(1, 2);
+ int updateCount = ps.executeUpdate();
+ assertEquals(1, updateCount);
+ ps.setInt(1, 1);
+ int updateCount1 = ps.executeUpdate();
+ assertEquals(1, updateCount1);
+ } finally {
+ try {
+ ps.close();
+ } catch(Exception ee) {}
+ }
+ }
/**
* TODO Doesn't pass. according to spec, it is possible to invoke the
diff --git a/luni/src/test/java/libcore/java/util/zip/ZipEntryTest.java b/luni/src/test/java/libcore/java/util/zip/ZipEntryTest.java
index c7667b9..bf10c3e 100644
--- a/luni/src/test/java/libcore/java/util/zip/ZipEntryTest.java
+++ b/luni/src/test/java/libcore/java/util/zip/ZipEntryTest.java
@@ -145,23 +145,28 @@
zipFile.close();
}
- public void testMaxLengthExtra_zip64() throws Exception {
- // Not quite the max length (65535), but large enough that there's no space
- // for the zip64 extended info header.
- byte[] maxLengthExtra = new byte[65530];
- File f = createTemporaryZipFile();
- ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(f)),
- true /* forceZip64 */);
- ZipEntry ze = new ZipEntry("x");
-
- ze.setExtra(maxLengthExtra);
- try {
- out.putNextEntry(ze);
- fail();
- } catch (ZipException expected) {
- }
- }
+ // TODO: This test does not compile because we need to add a ZipOutputStream constructor
+ // that forces zip64. This also needs followup changes in ZipInputStream et al. to assume zip64
+ // if the header says so, and to not depend purely on the entry length.
+ //
+ // public void testMaxLengthExtra_zip64() throws Exception {
+ // // Not quite the max length (65535), but large enough that there's no space
+ // // for the zip64 extended info header.
+ // byte[] maxLengthExtra = new byte[65530];
+ //
+ // File f = createTemporaryZipFile();
+ // ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(f)),
+ // true /* forceZip64 */);
+ // ZipEntry ze = new ZipEntry("x");
+ //
+ // ze.setExtra(maxLengthExtra);
+ // try {
+ // out.putNextEntry(ze);
+ // fail();
+ // } catch (ZipException expected) {
+ // }
+ // }
public void testTooLongComment() throws Exception {
diff --git a/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParametersTestDSA.java b/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParametersTestDSA.java
index 24820ed..4918fdc 100644
--- a/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParametersTestDSA.java
+++ b/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParametersTestDSA.java
@@ -22,46 +22,78 @@
public class AlgorithmParametersTestDSA extends AlgorithmParametersTest {
+ /*
+ * Parameters generated with OpenSSL:
+ * openssl dsaparam -genkey 1024 -C
+ */
private static final byte[] P = new byte[] {
- (byte) 0x00, (byte) 0xB9, (byte) 0x53, (byte) 0xA4, (byte) 0xBB,
- (byte) 0xC8, (byte) 0xFD, (byte) 0x94, (byte) 0x4B, (byte) 0xC0,
- (byte) 0xD4, (byte) 0x6B, (byte) 0xA9, (byte) 0xAB, (byte) 0x5A,
- (byte) 0x1E, (byte) 0x85, (byte) 0x7E, (byte) 0x87, (byte) 0x38,
- (byte) 0x79, (byte) 0x1C, (byte) 0xBF, (byte) 0xCF, (byte) 0x32,
- (byte) 0x5A, (byte) 0x45, (byte) 0xF8, (byte) 0xE4, (byte) 0x08,
- (byte) 0x28, (byte) 0xA4, (byte) 0x12, (byte) 0x8A, (byte) 0x9D,
- (byte) 0x06, (byte) 0x53, (byte) 0x1C, (byte) 0xAA, (byte) 0x6A,
- (byte) 0x21, (byte) 0xC1, (byte) 0x95, (byte) 0xF8, (byte) 0xAA,
- (byte) 0xB2, (byte) 0xB8, (byte) 0x43, (byte) 0x38, (byte) 0x86,
- (byte) 0x15, (byte) 0x94, (byte) 0xCF, (byte) 0x40, (byte) 0xA5,
- (byte) 0x0D, (byte) 0xF3, (byte) 0x9A, (byte) 0x49, (byte) 0x12,
- (byte) 0x72, (byte) 0x64, (byte) 0x11, (byte) 0xDD, (byte) 0x85};
+ (byte) 0xE6, (byte) 0x41, (byte) 0x58, (byte) 0x77, (byte) 0x76,
+ (byte) 0x5A, (byte) 0x4A, (byte) 0x53, (byte) 0xF1, (byte) 0xD6,
+ (byte) 0xC8, (byte) 0x7D, (byte) 0x67, (byte) 0x1F, (byte) 0x2F,
+ (byte) 0xFA, (byte) 0xDE, (byte) 0xB7, (byte) 0xAA, (byte) 0xCD,
+ (byte) 0xD7, (byte) 0x5D, (byte) 0xD0, (byte) 0xE9, (byte) 0xB1,
+ (byte) 0xDA, (byte) 0xFE, (byte) 0x42, (byte) 0xBE, (byte) 0xCC,
+ (byte) 0x42, (byte) 0x52, (byte) 0x2E, (byte) 0x01, (byte) 0xD2,
+ (byte) 0x16, (byte) 0xB1, (byte) 0x5B, (byte) 0xC4, (byte) 0x42,
+ (byte) 0xF9, (byte) 0x55, (byte) 0x0F, (byte) 0xE2, (byte) 0xD5,
+ (byte) 0x01, (byte) 0xD2, (byte) 0x7E, (byte) 0x22, (byte) 0xF6,
+ (byte) 0xC1, (byte) 0xFE, (byte) 0x5C, (byte) 0x6A, (byte) 0xCF,
+ (byte) 0x82, (byte) 0x1B, (byte) 0x5C, (byte) 0x46, (byte) 0x66,
+ (byte) 0x8B, (byte) 0xAF, (byte) 0xDF, (byte) 0x44, (byte) 0xE2,
+ (byte) 0x0E, (byte) 0xA3, (byte) 0x58, (byte) 0xF7, (byte) 0xA3,
+ (byte) 0x24, (byte) 0xE3, (byte) 0x84, (byte) 0xA6, (byte) 0x16,
+ (byte) 0xE0, (byte) 0xCA, (byte) 0x72, (byte) 0x55, (byte) 0x07,
+ (byte) 0xA0, (byte) 0x99, (byte) 0x7B, (byte) 0xF8, (byte) 0xB1,
+ (byte) 0x5A, (byte) 0x84, (byte) 0x36, (byte) 0x5A, (byte) 0xC8,
+ (byte) 0x6A, (byte) 0xFE, (byte) 0xA6, (byte) 0xB4, (byte) 0x1B,
+ (byte) 0x3A, (byte) 0x0A, (byte) 0x00, (byte) 0x6B, (byte) 0x72,
+ (byte) 0xDC, (byte) 0x0C, (byte) 0xD1, (byte) 0x09, (byte) 0x25,
+ (byte) 0x11, (byte) 0x68, (byte) 0x6B, (byte) 0x75, (byte) 0xDE,
+ (byte) 0x2C, (byte) 0x1A, (byte) 0xC2, (byte) 0x3A, (byte) 0xCB,
+ (byte) 0xA0, (byte) 0x17, (byte) 0xCA, (byte) 0x2D, (byte) 0xEE,
+ (byte) 0xA2, (byte) 0x5A, (byte) 0x9D, (byte) 0x1F, (byte) 0x33,
+ (byte) 0x1B, (byte) 0x07, (byte) 0x6D,
+ };
private static final byte[] Q = new byte[] {
- (byte) 0x00, (byte) 0xF8, (byte) 0x51, (byte) 0x6A, (byte) 0x92,
- (byte) 0xCB, (byte) 0x47, (byte) 0x95, (byte) 0x18, (byte) 0x1F,
- (byte) 0x7E, (byte) 0xD8, (byte) 0x71, (byte) 0x05, (byte) 0xB6,
- (byte) 0x26, (byte) 0x4D, (byte) 0x52, (byte) 0x94, (byte) 0xFA,
- (byte) 0x5D};
+ (byte) 0x9B, (byte) 0x39, (byte) 0xD0, (byte) 0x02, (byte) 0x0F,
+ (byte) 0xE9, (byte) 0x96, (byte) 0x16, (byte) 0xC5, (byte) 0x25,
+ (byte) 0xF7, (byte) 0x94, (byte) 0xA9, (byte) 0x2C, (byte) 0xD0,
+ (byte) 0x25, (byte) 0x5B, (byte) 0x6E, (byte) 0xE0, (byte) 0x8F,
+ };
private static final byte[] G = new byte[] {
- (byte) 0x2B, (byte) 0xF5, (byte) 0x91, (byte) 0x47, (byte) 0xC8,
- (byte) 0xF1, (byte) 0x79, (byte) 0x75, (byte) 0x2A, (byte) 0x8E,
- (byte) 0x40, (byte) 0x7E, (byte) 0xF5, (byte) 0xA5, (byte) 0x14,
- (byte) 0x98, (byte) 0x97, (byte) 0xE8, (byte) 0xC5, (byte) 0x5E,
- (byte) 0x7A, (byte) 0x39, (byte) 0xFE, (byte) 0x3B, (byte) 0x68,
- (byte) 0x06, (byte) 0x85, (byte) 0xD4, (byte) 0xDC, (byte) 0xA5,
- (byte) 0xF1, (byte) 0xC1, (byte) 0x82, (byte) 0x45, (byte) 0x98,
- (byte) 0xD3, (byte) 0x06, (byte) 0xE2, (byte) 0x4A, (byte) 0x45,
- (byte) 0xD7, (byte) 0xF5, (byte) 0x57, (byte) 0x18, (byte) 0x55,
- (byte) 0x05, (byte) 0xD4, (byte) 0x74, (byte) 0x6A, (byte) 0x9E,
- (byte) 0x2D, (byte) 0x42, (byte) 0xDF, (byte) 0xC2, (byte) 0x88,
- (byte) 0x95, (byte) 0x97, (byte) 0xA8, (byte) 0x7D, (byte) 0x11,
- (byte) 0x55, (byte) 0x9C, (byte) 0x7C, (byte) 0x9F};
+ (byte) 0x5E, (byte) 0x9C, (byte) 0x95, (byte) 0x5F, (byte) 0x7E,
+ (byte) 0x91, (byte) 0x47, (byte) 0x4D, (byte) 0x68, (byte) 0xA4,
+ (byte) 0x1C, (byte) 0x44, (byte) 0x3B, (byte) 0xEC, (byte) 0x0A,
+ (byte) 0x7E, (byte) 0x59, (byte) 0x54, (byte) 0xF7, (byte) 0xEF,
+ (byte) 0x42, (byte) 0xFB, (byte) 0x63, (byte) 0x95, (byte) 0x08,
+ (byte) 0x2F, (byte) 0x4A, (byte) 0xD3, (byte) 0xBC, (byte) 0x79,
+ (byte) 0x9D, (byte) 0xBA, (byte) 0xD8, (byte) 0x8A, (byte) 0x83,
+ (byte) 0x84, (byte) 0xAE, (byte) 0x5B, (byte) 0x26, (byte) 0x80,
+ (byte) 0xB3, (byte) 0xFB, (byte) 0x9C, (byte) 0xA3, (byte) 0xCF,
+ (byte) 0xF4, (byte) 0x0A, (byte) 0xD5, (byte) 0xB6, (byte) 0x65,
+ (byte) 0x65, (byte) 0x1A, (byte) 0x4F, (byte) 0xC0, (byte) 0x86,
+ (byte) 0x3B, (byte) 0xE6, (byte) 0xFB, (byte) 0x4E, (byte) 0x9E,
+ (byte) 0x49, (byte) 0x0A, (byte) 0x8C, (byte) 0x77, (byte) 0x2D,
+ (byte) 0x93, (byte) 0x0B, (byte) 0xCA, (byte) 0x81, (byte) 0x07,
+ (byte) 0x09, (byte) 0xC4, (byte) 0x71, (byte) 0xFD, (byte) 0xC8,
+ (byte) 0xC7, (byte) 0xD1, (byte) 0xA3, (byte) 0xD0, (byte) 0xBB,
+ (byte) 0x7D, (byte) 0x92, (byte) 0x74, (byte) 0x8B, (byte) 0x3B,
+ (byte) 0x2A, (byte) 0x45, (byte) 0x1F, (byte) 0x5D, (byte) 0x85,
+ (byte) 0x90, (byte) 0xE3, (byte) 0xFB, (byte) 0x0E, (byte) 0x16,
+ (byte) 0xBA, (byte) 0x8A, (byte) 0xDE, (byte) 0x10, (byte) 0x0F,
+ (byte) 0xE0, (byte) 0x0F, (byte) 0x37, (byte) 0xA7, (byte) 0xC1,
+ (byte) 0xDC, (byte) 0xBC, (byte) 0x00, (byte) 0xB8, (byte) 0x24,
+ (byte) 0x0F, (byte) 0xF6, (byte) 0x5F, (byte) 0xB1, (byte) 0xA8,
+ (byte) 0x9A, (byte) 0xDB, (byte) 0x9F, (byte) 0x36, (byte) 0x54,
+ (byte) 0x45, (byte) 0xBD, (byte) 0xC0, (byte) 0xE8, (byte) 0x27,
+ (byte) 0x82, (byte) 0xC9, (byte) 0x75,
+ };
public AlgorithmParametersTestDSA() {
super("DSA", new AlgorithmParameterSignatureHelper<DSAParameterSpec>(
"DSA", DSAParameterSpec.class), new DSAParameterSpec(
- new BigInteger(P), new BigInteger(Q), new BigInteger(G)));
+ new BigInteger(1, P), new BigInteger(1, Q), new BigInteger(1, G)));
}
}
diff --git a/ojluni/src/main/java/java/lang/System.java b/ojluni/src/main/java/java/lang/System.java
index 4635ae5..f296bf8 100755
--- a/ojluni/src/main/java/java/lang/System.java
+++ b/ojluni/src/main/java/java/lang/System.java
@@ -106,6 +106,22 @@
public final static PrintStream err;
/**
+ * Dedicated lock for GC / Finalization logic.
+ */
+ private static final Object LOCK = new Object();
+
+ /**
+ * Whether or not we need to do a GC before running the finalizers.
+ */
+ private static boolean runGC;
+
+ /**
+ * If we just ran finalization, we might want to do a GC to free the finalized objects.
+ * This lets us do gc/runFinlization/gc sequences but prevents back to back System.gc().
+ */
+ private static boolean justRanFinalization;
+
+ /**
* Reassigns the "standard" input stream.
*
* <p>First, if there is a security manager, its <code>checkPermission</code>
@@ -1497,7 +1513,18 @@
* @see java.lang.Runtime#gc()
*/
public static void gc() {
- Runtime.getRuntime().gc();
+ boolean shouldRunGC;
+ synchronized (LOCK) {
+ shouldRunGC = justRanFinalization;
+ if (shouldRunGC) {
+ justRanFinalization = false;
+ } else {
+ runGC = true;
+ }
+ }
+ if (shouldRunGC) {
+ Runtime.getRuntime().gc();
+ }
}
/**
@@ -1519,7 +1546,18 @@
* @see java.lang.Runtime#runFinalization()
*/
public static void runFinalization() {
+ boolean shouldRunGC;
+ synchronized (LOCK) {
+ shouldRunGC = runGC;
+ runGC = false;
+ }
+ if (shouldRunGC) {
+ Runtime.getRuntime().gc();
+ }
Runtime.getRuntime().runFinalization();
+ synchronized (LOCK) {
+ justRanFinalization = true;
+ }
}
/**
diff --git a/ojluni/src/main/java/java/net/AbstractPlainDatagramSocketImpl.java b/ojluni/src/main/java/java/net/AbstractPlainDatagramSocketImpl.java
index e7ad94c..8133554 100755
--- a/ojluni/src/main/java/java/net/AbstractPlainDatagramSocketImpl.java
+++ b/ojluni/src/main/java/java/net/AbstractPlainDatagramSocketImpl.java
@@ -304,8 +304,11 @@
throw new SocketException("bad argument for IP_MULTICAST_IF");
break;
case IP_MULTICAST_IF2:
- if (o == null || !(o instanceof NetworkInterface))
+ if (o == null || !(o instanceof Integer || o instanceof NetworkInterface))
throw new SocketException("bad argument for IP_MULTICAST_IF2");
+ if (o instanceof NetworkInterface) {
+ o = new Integer(((NetworkInterface)o).getIndex());
+ }
break;
case IP_MULTICAST_LOOP:
if (o == null || !(o instanceof Boolean))
@@ -349,6 +352,10 @@
case SO_REUSEADDR:
case SO_BROADCAST:
result = socketGetOption(optID);
+
+ if (optID == IP_MULTICAST_IF) {
+ return getNIFirstAddress((Integer)result);
+ }
break;
default:
@@ -358,6 +365,20 @@
return result;
}
+ /** Return the first address bound to NetworkInterface with given ID.
+ * In case of niIndex == 0 or no address return anyLocalAddress
+ */
+ static InetAddress getNIFirstAddress(int niIndex) throws SocketException {
+ if (niIndex > 0) {
+ NetworkInterface networkInterface = NetworkInterface.getByIndex(niIndex);
+ Enumeration<InetAddress> addressesEnum = networkInterface.getInetAddresses();
+ if (addressesEnum.hasMoreElements()) {
+ return addressesEnum.nextElement();
+ }
+ }
+ return InetAddress.anyLocalAddress();
+ }
+
protected abstract void datagramSocketCreate() throws SocketException;
protected abstract void datagramSocketClose();
protected abstract void socketSetOption(int opt, Object val)
diff --git a/ojluni/src/main/java/java/net/Inet4Address.java b/ojluni/src/main/java/java/net/Inet4Address.java
index 11ee7c7..57da1c4 100755
--- a/ojluni/src/main/java/java/net/Inet4Address.java
+++ b/ojluni/src/main/java/java/net/Inet4Address.java
@@ -332,11 +332,6 @@
return addr;
}
- @Override
- public byte[] getAddressInternal() {
- return getAddress();
- }
-
/**
* Returns the IP address string in textual presentation form.
*
diff --git a/ojluni/src/main/java/java/net/Inet6Address.java b/ojluni/src/main/java/java/net/Inet6Address.java
index 67487ff..ca19211 100755
--- a/ojluni/src/main/java/java/net/Inet6Address.java
+++ b/ojluni/src/main/java/java/net/Inet6Address.java
@@ -622,11 +622,6 @@
return ipaddress.clone();
}
- @Override
- public byte[] getAddressInternal() {
- return ipaddress;
- }
-
/**
* Returns the numeric scopeId, if this instance is associated with
* an interface. If no scoped_id is set, the returned value is zero.
diff --git a/ojluni/src/main/java/java/net/InetAddress.java b/ojluni/src/main/java/java/net/InetAddress.java
index 019c4ac..d8057ff 100755
--- a/ojluni/src/main/java/java/net/InetAddress.java
+++ b/ojluni/src/main/java/java/net/InetAddress.java
@@ -577,16 +577,6 @@
}
/**
- * Called from native code. Same as {@code getAddress}, but for internal users.
- *
- * @return
- */
- public byte[] getAddressInternal() {
- return null;
- }
-
-
- /**
* Returns the IP address string in textual presentation.
*
* @return the raw IP address in a string format.
@@ -1005,4 +995,4 @@
String getHostName(boolean check) {
throw new UnsupportedOperationException();
}
-}
\ No newline at end of file
+}
diff --git a/ojluni/src/main/java/java/net/MulticastSocket.java b/ojluni/src/main/java/java/net/MulticastSocket.java
index 28bc58e..f39d3e9 100755
--- a/ojluni/src/main/java/java/net/MulticastSocket.java
+++ b/ojluni/src/main/java/java/net/MulticastSocket.java
@@ -563,14 +563,14 @@
* @since 1.4
*/
public NetworkInterface getNetworkInterface() throws SocketException {
- NetworkInterface ni
- = (NetworkInterface)getImpl().getOption(SocketOptions.IP_MULTICAST_IF2);
- if (ni.getIndex() == 0) {
+ Integer niIndex
+ = (Integer)getImpl().getOption(SocketOptions.IP_MULTICAST_IF2);
+ if (niIndex == 0) {
InetAddress[] addrs = new InetAddress[1];
addrs[0] = InetAddress.anyLocalAddress();
return new NetworkInterface(addrs[0].getHostName(), 0, addrs);
} else {
- return ni;
+ return NetworkInterface.getByIndex(niIndex);
}
}
diff --git a/ojluni/src/main/java/java/net/NetworkInterface.java b/ojluni/src/main/java/java/net/NetworkInterface.java
index b641b5c..1f5825f 100755
--- a/ojluni/src/main/java/java/net/NetworkInterface.java
+++ b/ojluni/src/main/java/java/net/NetworkInterface.java
@@ -49,6 +49,7 @@
private NetworkInterface childs[];
private NetworkInterface parent = null;
private boolean virtual = false;
+ private byte[] hardwareAddr;
private static final NetworkInterface defaultInterface;
private static final int defaultIndex; /* index of defaultInterface */
@@ -431,23 +432,7 @@
* @since 1.6
*/
public byte[] getHardwareAddress() throws SocketException {
- SecurityManager sec = System.getSecurityManager();
- if (sec != null) {
- try {
- sec.checkPermission(new NetPermission("getNetworkInformation"));
- } catch (SecurityException e) {
- if (!getInetAddresses().hasMoreElements()) {
- // don't have connect permission to any local address
- return null;
- }
- }
- }
- for (InetAddress addr : addrs) {
- if (addr instanceof Inet4Address) {
- return getMacAddr0(((Inet4Address)addr).getAddress(), name, index);
- }
- }
- return getMacAddr0(null, name, index);
+ return (hardwareAddr != null) ? hardwareAddr.clone() : null;
}
/**
@@ -482,7 +467,6 @@
private native static boolean isLoopback0(String name, int ind) throws SocketException;
private native static boolean supportsMulticast0(String name, int ind) throws SocketException;
private native static boolean isP2P0(String name, int ind) throws SocketException;
- private native static byte[] getMacAddr0(byte[] inAddr, String name, int ind) throws SocketException;
private native static int getMTU0(String name, int ind) throws SocketException;
/**
diff --git a/ojluni/src/main/java/java/net/SocketImpl.java b/ojluni/src/main/java/java/net/SocketImpl.java
index 18044ab..d2123e2 100755
--- a/ojluni/src/main/java/java/net/SocketImpl.java
+++ b/ojluni/src/main/java/java/net/SocketImpl.java
@@ -222,7 +222,14 @@
* @return the value of this socket's <code>fd</code> field.
* @see java.net.SocketImpl#fd
*/
- public FileDescriptor getFileDescriptor() {
+ protected FileDescriptor getFileDescriptor() {
+ return fd;
+ }
+
+ /**
+ * @hide used by java.nio tests
+ */
+ public FileDescriptor getFD$() {
return fd;
}
diff --git a/ojluni/src/main/java/java/nio/channels/AcceptPendingException.java b/ojluni/src/main/java/java/nio/channels/AcceptPendingException.java
deleted file mode 100644
index dc357f0..0000000
--- a/ojluni/src/main/java/java/nio/channels/AcceptPendingException.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
- *
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-// -- This file was mechanically generated: Do not edit! -- //
-
-package java.nio.channels;
-
-
-/**
- * Unchecked exception thrown when an attempt is made to initiate an accept
- * operation on a channel and a previous accept operation has not completed.
- *
- * @since 1.7
- */
-
-public class AcceptPendingException
- extends IllegalStateException
-{
-
- private static final long serialVersionUID = 2721339977965416421L;
-
- /**
- * Constructs an instance of this class.
- */
- public AcceptPendingException() { }
-
-}
diff --git a/ojluni/src/main/java/java/nio/channels/AsynchronousByteChannel.java b/ojluni/src/main/java/java/nio/channels/AsynchronousByteChannel.java
deleted file mode 100755
index 9fdf753..0000000
--- a/ojluni/src/main/java/java/nio/channels/AsynchronousByteChannel.java
+++ /dev/null
@@ -1,209 +0,0 @@
-/*
- * Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package java.nio.channels;
-
-import java.nio.ByteBuffer;
-import java.util.concurrent.Future;
-
-/**
- * An asynchronous channel that can read and write bytes.
- *
- * <p> Some channels may not allow more than one read or write to be outstanding
- * at any given time. If a thread invokes a read method before a previous read
- * operation has completed then a {@link ReadPendingException} will be thrown.
- * Similarly, if a write method is invoked before a previous write has completed
- * then {@link WritePendingException} is thrown. Whether or not other kinds of
- * I/O operations may proceed concurrently with a read operation depends upon
- * the type of the channel.
- *
- * <p> Note that {@link java.nio.ByteBuffer ByteBuffers} are not safe for use by
- * multiple concurrent threads. When a read or write operation is initiated then
- * care must be taken to ensure that the buffer is not accessed until the
- * operation completes.
- *
- * @see Channels#newInputStream(AsynchronousByteChannel)
- * @see Channels#newOutputStream(AsynchronousByteChannel)
- *
- * @since 1.7
- */
-
-public interface AsynchronousByteChannel
- extends AsynchronousChannel
-{
- /**
- * Reads a sequence of bytes from this channel into the given buffer.
- *
- * <p> This method initiates an asynchronous read operation to read a
- * sequence of bytes from this channel into the given buffer. The {@code
- * handler} parameter is a completion handler that is invoked when the read
- * operation completes (or fails). The result passed to the completion
- * handler is the number of bytes read or {@code -1} if no bytes could be
- * read because the channel has reached end-of-stream.
- *
- * <p> The read operation may read up to <i>r</i> bytes from the channel,
- * where <i>r</i> is the number of bytes remaining in the buffer, that is,
- * {@code dst.remaining()} at the time that the read is attempted. Where
- * <i>r</i> is 0, the read operation completes immediately with a result of
- * {@code 0} without initiating an I/O operation.
- *
- * <p> Suppose that a byte sequence of length <i>n</i> is read, where
- * <tt>0</tt> <tt><</tt> <i>n</i> <tt><=</tt> <i>r</i>.
- * This byte sequence will be transferred into the buffer so that the first
- * byte in the sequence is at index <i>p</i> and the last byte is at index
- * <i>p</i> <tt>+</tt> <i>n</i> <tt>-</tt> <tt>1</tt>,
- * where <i>p</i> is the buffer's position at the moment the read is
- * performed. Upon completion the buffer's position will be equal to
- * <i>p</i> <tt>+</tt> <i>n</i>; its limit will not have changed.
- *
- * <p> Buffers are not safe for use by multiple concurrent threads so care
- * should be taken to not access the buffer until the operation has
- * completed.
- *
- * <p> This method may be invoked at any time. Some channel types may not
- * allow more than one read to be outstanding at any given time. If a thread
- * initiates a read operation before a previous read operation has
- * completed then a {@link ReadPendingException} will be thrown.
- *
- * @param dst
- * The buffer into which bytes are to be transferred
- * @param attachment
- * The object to attach to the I/O operation; can be {@code null}
- * @param handler
- * The completion handler
- *
- * @throws IllegalArgumentException
- * If the buffer is read-only
- * @throws ReadPendingException
- * If the channel does not allow more than one read to be outstanding
- * and a previous read has not completed
- * @throws ShutdownChannelGroupException
- * If the channel is associated with a {@link AsynchronousChannelGroup
- * group} that has terminated
- */
- <A> void read(ByteBuffer dst,
- A attachment,
- CompletionHandler<Integer,? super A> handler);
-
- /**
- * Reads a sequence of bytes from this channel into the given buffer.
- *
- * <p> This method initiates an asynchronous read operation to read a
- * sequence of bytes from this channel into the given buffer. The method
- * behaves in exactly the same manner as the {@link
- * #read(ByteBuffer,Object,CompletionHandler)
- * read(ByteBuffer,Object,CompletionHandler)} method except that instead
- * of specifying a completion handler, this method returns a {@code Future}
- * representing the pending result. The {@code Future}'s {@link Future#get()
- * get} method returns the number of bytes read or {@code -1} if no bytes
- * could be read because the channel has reached end-of-stream.
- *
- * @param dst
- * The buffer into which bytes are to be transferred
- *
- * @return A Future representing the result of the operation
- *
- * @throws IllegalArgumentException
- * If the buffer is read-only
- * @throws ReadPendingException
- * If the channel does not allow more than one read to be outstanding
- * and a previous read has not completed
- */
- Future<Integer> read(ByteBuffer dst);
-
- /**
- * Writes a sequence of bytes to this channel from the given buffer.
- *
- * <p> This method initiates an asynchronous write operation to write a
- * sequence of bytes to this channel from the given buffer. The {@code
- * handler} parameter is a completion handler that is invoked when the write
- * operation completes (or fails). The result passed to the completion
- * handler is the number of bytes written.
- *
- * <p> The write operation may write up to <i>r</i> bytes to the channel,
- * where <i>r</i> is the number of bytes remaining in the buffer, that is,
- * {@code src.remaining()} at the time that the write is attempted. Where
- * <i>r</i> is 0, the write operation completes immediately with a result of
- * {@code 0} without initiating an I/O operation.
- *
- * <p> Suppose that a byte sequence of length <i>n</i> is written, where
- * <tt>0</tt> <tt><</tt> <i>n</i> <tt><=</tt> <i>r</i>.
- * This byte sequence will be transferred from the buffer starting at index
- * <i>p</i>, where <i>p</i> is the buffer's position at the moment the
- * write is performed; the index of the last byte written will be
- * <i>p</i> <tt>+</tt> <i>n</i> <tt>-</tt> <tt>1</tt>.
- * Upon completion the buffer's position will be equal to
- * <i>p</i> <tt>+</tt> <i>n</i>; its limit will not have changed.
- *
- * <p> Buffers are not safe for use by multiple concurrent threads so care
- * should be taken to not access the buffer until the operation has
- * completed.
- *
- * <p> This method may be invoked at any time. Some channel types may not
- * allow more than one write to be outstanding at any given time. If a thread
- * initiates a write operation before a previous write operation has
- * completed then a {@link WritePendingException} will be thrown.
- *
- * @param src
- * The buffer from which bytes are to be retrieved
- * @param attachment
- * The object to attach to the I/O operation; can be {@code null}
- * @param handler
- * The completion handler object
- *
- * @throws WritePendingException
- * If the channel does not allow more than one write to be outstanding
- * and a previous write has not completed
- * @throws ShutdownChannelGroupException
- * If the channel is associated with a {@link AsynchronousChannelGroup
- * group} that has terminated
- */
- <A> void write(ByteBuffer src,
- A attachment,
- CompletionHandler<Integer,? super A> handler);
-
- /**
- * Writes a sequence of bytes to this channel from the given buffer.
- *
- * <p> This method initiates an asynchronous write operation to write a
- * sequence of bytes to this channel from the given buffer. The method
- * behaves in exactly the same manner as the {@link
- * #write(ByteBuffer,Object,CompletionHandler)
- * write(ByteBuffer,Object,CompletionHandler)} method except that instead
- * of specifying a completion handler, this method returns a {@code Future}
- * representing the pending result. The {@code Future}'s {@link Future#get()
- * get} method returns the number of bytes written.
- *
- * @param src
- * The buffer from which bytes are to be retrieved
- *
- * @return A Future representing the result of the operation
- *
- * @throws WritePendingException
- * If the channel does not allow more than one write to be outstanding
- * and a previous write has not completed
- */
- Future<Integer> write(ByteBuffer src);
-}
diff --git a/ojluni/src/main/java/java/nio/channels/AsynchronousChannel.java b/ojluni/src/main/java/java/nio/channels/AsynchronousChannel.java
deleted file mode 100755
index 5aa9fe2..0000000
--- a/ojluni/src/main/java/java/nio/channels/AsynchronousChannel.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package java.nio.channels;
-
-import java.io.IOException;
-import java.util.concurrent.Future; // javadoc
-
-/**
- * A channel that supports asynchronous I/O operations. Asynchronous I/O
- * operations will usually take one of two forms:
- *
- * <ol>
- * <li><pre>{@link Future}<V> <em>operation</em>(<em>...</em>)</pre></li>
- * <li><pre>void <em>operation</em>(<em>...</em> A attachment, {@link
- * CompletionHandler}<V,? super A> handler)</pre></li>
- * </ol>
- *
- * where <i>operation</i> is the name of the I/O operation (read or write for
- * example), <i>V</i> is the result type of the I/O operation, and <i>A</i> is
- * the type of an object attached to the I/O operation to provide context when
- * consuming the result. The attachment is important for cases where a
- * <em>state-less</em> {@code CompletionHandler} is used to consume the result
- * of many I/O operations.
- *
- * <p> In the first form, the methods defined by the {@link Future Future}
- * interface may be used to check if the operation has completed, wait for its
- * completion, and to retrieve the result. In the second form, a {@link
- * CompletionHandler} is invoked to consume the result of the I/O operation when
- * it completes or fails.
- *
- * <p> A channel that implements this interface is <em>asynchronously
- * closeable</em>: If an I/O operation is outstanding on the channel and the
- * channel's {@link #close close} method is invoked, then the I/O operation
- * fails with the exception {@link AsynchronousCloseException}.
- *
- * <p> Asynchronous channels are safe for use by multiple concurrent threads.
- * Some channel implementations may support concurrent reading and writing, but
- * may not allow more than one read and one write operation to be outstanding at
- * any given time.
- *
- * <h4>Cancellation</h4>
- *
- * <p> The {@code Future} interface defines the {@link Future#cancel cancel}
- * method to cancel execution. This causes all threads waiting on the result of
- * the I/O operation to throw {@link java.util.concurrent.CancellationException}.
- * Whether the underlying I/O operation can be cancelled is highly implementation
- * specific and therefore not specified. Where cancellation leaves the channel,
- * or the entity to which it is connected, in an inconsistent state, then the
- * channel is put into an implementation specific <em>error state</em> that
- * prevents further attempts to initiate I/O operations that are <i>similar</i>
- * to the operation that was cancelled. For example, if a read operation is
- * cancelled but the implementation cannot guarantee that bytes have not been
- * read from the channel then it puts the channel into an error state; further
- * attempts to initiate a {@code read} operation cause an unspecified runtime
- * exception to be thrown. Similarly, if a write operation is cancelled but the
- * implementation cannot guarantee that bytes have not been written to the
- * channel then subsequent attempts to initiate a {@code write} will fail with
- * an unspecified runtime exception.
- *
- * <p> Where the {@link Future#cancel cancel} method is invoked with the {@code
- * mayInterruptIfRunning} parameter set to {@code true} then the I/O operation
- * may be interrupted by closing the channel. In that case all threads waiting
- * on the result of the I/O operation throw {@code CancellationException} and
- * any other I/O operations outstanding on the channel complete with the
- * exception {@link AsynchronousCloseException}.
- *
- * <p> Where the {@code cancel} method is invoked to cancel read or write
- * operations then it is recommended that all buffers used in the I/O operations
- * be discarded or care taken to ensure that the buffers are not accessed while
- * the channel remains open.
- *
- * @since 1.7
- */
-
-public interface AsynchronousChannel
- extends Channel
-{
- /**
- * Closes this channel.
- *
- * <p> Any outstanding asynchronous operations upon this channel will
- * complete with the exception {@link AsynchronousCloseException}. After a
- * channel is closed, further attempts to initiate asynchronous I/O
- * operations complete immediately with cause {@link ClosedChannelException}.
- *
- * <p> This method otherwise behaves exactly as specified by the {@link
- * Channel} interface.
- *
- * @throws IOException
- * If an I/O error occurs
- */
- @Override
- void close() throws IOException;
-}
diff --git a/ojluni/src/main/java/java/nio/channels/AsynchronousChannelGroup.java b/ojluni/src/main/java/java/nio/channels/AsynchronousChannelGroup.java
deleted file mode 100755
index 2eb4b52..0000000
--- a/ojluni/src/main/java/java/nio/channels/AsynchronousChannelGroup.java
+++ /dev/null
@@ -1,344 +0,0 @@
-/*
- * Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package java.nio.channels;
-
-import java.nio.channels.spi.AsynchronousChannelProvider;
-import java.io.IOException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.TimeUnit;
-
-/**
- * A grouping of asynchronous channels for the purpose of resource sharing.
- *
- * <p> An asynchronous channel group encapsulates the mechanics required to
- * handle the completion of I/O operations initiated by {@link AsynchronousChannel
- * asynchronous channels} that are bound to the group. A group has an associated
- * thread pool to which tasks are submitted to handle I/O events and dispatch to
- * {@link CompletionHandler completion-handlers} that consume the result of
- * asynchronous operations performed on channels in the group. In addition to
- * handling I/O events, the pooled threads may also execute other tasks required
- * to support the execution of asynchronous I/O operations.
- *
- * <p> An asynchronous channel group is created by invoking the {@link
- * #withFixedThreadPool withFixedThreadPool} or {@link #withCachedThreadPool
- * withCachedThreadPool} methods defined here. Channels are bound to a group by
- * specifying the group when constructing the channel. The associated thread
- * pool is <em>owned</em> by the group; termination of the group results in the
- * shutdown of the associated thread pool.
- *
- * <p> In addition to groups created explicitly, the Java virtual machine
- * maintains a system-wide <em>default group</em> that is constructed
- * automatically. Asynchronous channels that do not specify a group at
- * construction time are bound to the default group. The default group has an
- * associated thread pool that creates new threads as needed. The default group
- * may be configured by means of system properties defined in the table below.
- * Where the {@link java.util.concurrent.ThreadFactory ThreadFactory} for the
- * default group is not configured then the pooled threads of the default group
- * are {@link Thread#isDaemon daemon} threads.
- *
- * <table border>
- * <tr>
- * <th>System property</th>
- * <th>Description</th>
- * </tr>
- * <tr>
- * <tr>
- * <td> {@code java.nio.channels.DefaultThreadPool.threadFactory} </td>
- * <td> The value of this property is taken to be the fully-qualified name
- * of a concrete {@link java.util.concurrent.ThreadFactory ThreadFactory}
- * class. The class is loaded using the system class loader and instantiated.
- * The factory's {@link java.util.concurrent.ThreadFactory#newThread
- * newThread} method is invoked to create each thread for the default
- * group's thread pool. If the process to load and instantiate the value
- * of the property fails then an unspecified error is thrown during the
- * construction of the default group. </td>
- * </tr>
- * <tr>
- * <td> {@code java.nio.channels.DefaultThreadPool.initialSize} </td>
- * <td> The value of the {@code initialSize} parameter for the default
- * group (see {@link #withCachedThreadPool withCachedThreadPool}).
- * The value of the property is taken to be the {@code String}
- * representation of an {@code Integer} that is the initial size parameter.
- * If the value cannot be parsed as an {@code Integer} it causes an
- * unspecified error to be thrown during the construction of the default
- * group. </td>
- * </tr>
- * </table>
- *
- * <a name="threading"><h4>Threading</h4></a>
- *
- * <p> The completion handler for an I/O operation initiated on a channel bound
- * to a group is guaranteed to be invoked by one of the pooled threads in the
- * group. This ensures that the completion handler is run by a thread with the
- * expected <em>identity</em>.
- *
- * <p> Where an I/O operation completes immediately, and the initiating thread
- * is one of the pooled threads in the group then the completion handler may
- * be invoked directly by the initiating thread. To avoid stack overflow, an
- * implementation may impose a limit as to the number of activations on the
- * thread stack. Some I/O operations may prohibit invoking the completion
- * handler directly by the initiating thread (see {@link
- * AsynchronousServerSocketChannel#accept(Object,CompletionHandler) accept}).
- *
- * <a name="shutdown"><h4>Shutdown and Termination</h4></a>
- *
- * <p> The {@link #shutdown() shutdown} method is used to initiate an <em>orderly
- * shutdown</em> of a group. An orderly shutdown marks the group as shutdown;
- * further attempts to construct a channel that binds to the group will throw
- * {@link ShutdownChannelGroupException}. Whether or not a group is shutdown can
- * be tested using the {@link #isShutdown() isShutdown} method. Once shutdown,
- * the group <em>terminates</em> when all asynchronous channels that are bound to
- * the group are closed, all actively executing completion handlers have run to
- * completion, and resources used by the group are released. No attempt is made
- * to stop or interrupt threads that are executing completion handlers. The
- * {@link #isTerminated() isTerminated} method is used to test if the group has
- * terminated, and the {@link #awaitTermination awaitTermination} method can be
- * used to block until the group has terminated.
- *
- * <p> The {@link #shutdownNow() shutdownNow} method can be used to initiate a
- * <em>forceful shutdown</em> of the group. In addition to the actions performed
- * by an orderly shutdown, the {@code shutdownNow} method closes all open channels
- * in the group as if by invoking the {@link AsynchronousChannel#close close}
- * method.
- *
- * @since 1.7
- *
- * @see AsynchronousSocketChannel#open(AsynchronousChannelGroup)
- * @see AsynchronousServerSocketChannel#open(AsynchronousChannelGroup)
- */
-
-public abstract class AsynchronousChannelGroup {
- private final AsynchronousChannelProvider provider;
-
- /**
- * Initialize a new instance of this class.
- *
- * @param provider
- * The asynchronous channel provider for this group
- */
- protected AsynchronousChannelGroup(AsynchronousChannelProvider provider) {
- this.provider = provider;
- }
-
- /**
- * Returns the provider that created this channel group.
- *
- * @return The provider that created this channel group
- */
- public final AsynchronousChannelProvider provider() {
- return provider;
- }
-
- /**
- * Creates an asynchronous channel group with a fixed thread pool.
- *
- * <p> The resulting asynchronous channel group reuses a fixed number of
- * threads. At any point, at most {@code nThreads} threads will be active
- * processing tasks that are submitted to handle I/O events and dispatch
- * completion results for operations initiated on asynchronous channels in
- * the group.
- *
- * <p> The group is created by invoking the {@link
- * AsynchronousChannelProvider#openAsynchronousChannelGroup(int,ThreadFactory)
- * openAsynchronousChannelGroup(int,ThreadFactory)} method of the system-wide
- * default {@link AsynchronousChannelProvider} object.
- *
- * @param nThreads
- * The number of threads in the pool
- * @param threadFactory
- * The factory to use when creating new threads
- *
- * @return A new asynchronous channel group
- *
- * @throws IllegalArgumentException
- * If {@code nThreads <= 0}
- * @throws IOException
- * If an I/O error occurs
- */
- public static AsynchronousChannelGroup withFixedThreadPool(int nThreads,
- ThreadFactory threadFactory)
- throws IOException
- {
- return AsynchronousChannelProvider.provider()
- .openAsynchronousChannelGroup(nThreads, threadFactory);
- }
-
- /**
- * Creates an asynchronous channel group with a given thread pool that
- * creates new threads as needed.
- *
- * <p> The {@code executor} parameter is an {@code ExecutorService} that
- * creates new threads as needed to execute tasks that are submitted to
- * handle I/O events and dispatch completion results for operations initiated
- * on asynchronous channels in the group. It may reuse previously constructed
- * threads when they are available.
- *
- * <p> The {@code initialSize} parameter may be used by the implementation
- * as a <em>hint</em> as to the initial number of tasks it may submit. For
- * example, it may be used to indictae the initial number of threads that
- * wait on I/O events.
- *
- * <p> The executor is intended to be used exclusively by the resulting
- * asynchronous channel group. Termination of the group results in the
- * orderly {@link ExecutorService#shutdown shutdown} of the executor
- * service. Shutting down the executor service by other means results in
- * unspecified behavior.
- *
- * <p> The group is created by invoking the {@link
- * AsynchronousChannelProvider#openAsynchronousChannelGroup(ExecutorService,int)
- * openAsynchronousChannelGroup(ExecutorService,int)} method of the system-wide
- * default {@link AsynchronousChannelProvider} object.
- *
- * @param executor
- * The thread pool for the resulting group
- * @param initialSize
- * A value {@code >=0} or a negative value for implementation
- * specific default
- *
- * @return A new asynchronous channel group
- *
- * @throws IOException
- * If an I/O error occurs
- *
- * @see java.util.concurrent.Executors#newCachedThreadPool
- */
- public static AsynchronousChannelGroup withCachedThreadPool(ExecutorService executor,
- int initialSize)
- throws IOException
- {
- return AsynchronousChannelProvider.provider()
- .openAsynchronousChannelGroup(executor, initialSize);
- }
-
- /**
- * Creates an asynchronous channel group with a given thread pool.
- *
- * <p> The {@code executor} parameter is an {@code ExecutorService} that
- * executes tasks submitted to dispatch completion results for operations
- * initiated on asynchronous channels in the group.
- *
- * <p> Care should be taken when configuring the executor service. It
- * should support <em>direct handoff</em> or <em>unbounded queuing</em> of
- * submitted tasks, and the thread that invokes the {@link
- * ExecutorService#execute execute} method should never invoke the task
- * directly. An implementation may mandate additional constraints.
- *
- * <p> The executor is intended to be used exclusively by the resulting
- * asynchronous channel group. Termination of the group results in the
- * orderly {@link ExecutorService#shutdown shutdown} of the executor
- * service. Shutting down the executor service by other means results in
- * unspecified behavior.
- *
- * <p> The group is created by invoking the {@link
- * AsynchronousChannelProvider#openAsynchronousChannelGroup(ExecutorService,int)
- * openAsynchronousChannelGroup(ExecutorService,int)} method of the system-wide
- * default {@link AsynchronousChannelProvider} object with an {@code
- * initialSize} of {@code 0}.
- *
- * @param executor
- * The thread pool for the resulting group
- *
- * @return A new asynchronous channel group
- *
- * @throws IOException
- * If an I/O error occurs
- */
- public static AsynchronousChannelGroup withThreadPool(ExecutorService executor)
- throws IOException
- {
- return AsynchronousChannelProvider.provider()
- .openAsynchronousChannelGroup(executor, 0);
- }
-
- /**
- * Tells whether or not this asynchronous channel group is shutdown.
- *
- * @return {@code true} if this asynchronous channel group is shutdown or
- * has been marked for shutdown.
- */
- public abstract boolean isShutdown();
-
- /**
- * Tells whether or not this group has terminated.
- *
- * <p> Where this method returns {@code true}, then the associated thread
- * pool has also {@link ExecutorService#isTerminated terminated}.
- *
- * @return {@code true} if this group has terminated
- */
- public abstract boolean isTerminated();
-
- /**
- * Initiates an orderly shutdown of the group.
- *
- * <p> This method marks the group as shutdown. Further attempts to construct
- * channel that binds to this group will throw {@link ShutdownChannelGroupException}.
- * The group terminates when all asynchronous channels in the group are
- * closed, all actively executing completion handlers have run to completion,
- * and all resources have been released. This method has no effect if the
- * group is already shutdown.
- */
- public abstract void shutdown();
-
- /**
- * Shuts down the group and closes all open channels in the group.
- *
- * <p> In addition to the actions performed by the {@link #shutdown() shutdown}
- * method, this method invokes the {@link AsynchronousChannel#close close}
- * method on all open channels in the group. This method does not attempt to
- * stop or interrupt threads that are executing completion handlers. The
- * group terminates when all actively executing completion handlers have run
- * to completion and all resources have been released. This method may be
- * invoked at any time. If some other thread has already invoked it, then
- * another invocation will block until the first invocation is complete,
- * after which it will return without effect.
- *
- * @throws IOException
- * If an I/O error occurs
- */
- public abstract void shutdownNow() throws IOException;
-
- /**
- * Awaits termination of the group.
-
- * <p> This method blocks until the group has terminated, or the timeout
- * occurs, or the current thread is interrupted, whichever happens first.
- *
- * @param timeout
- * The maximum time to wait, or zero or less to not wait
- * @param unit
- * The time unit of the timeout argument
- *
- * @return {@code true} if the group has terminated; {@code false} if the
- * timeout elapsed before termination
- *
- * @throws InterruptedException
- * If interrupted while waiting
- */
- public abstract boolean awaitTermination(long timeout, TimeUnit unit)
- throws InterruptedException;
-}
diff --git a/ojluni/src/main/java/java/nio/channels/AsynchronousServerSocketChannel.java b/ojluni/src/main/java/java/nio/channels/AsynchronousServerSocketChannel.java
deleted file mode 100755
index 1b5a67f..0000000
--- a/ojluni/src/main/java/java/nio/channels/AsynchronousServerSocketChannel.java
+++ /dev/null
@@ -1,300 +0,0 @@
-/*
- * Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package java.nio.channels;
-
-import java.nio.channels.spi.*;
-import java.net.SocketOption;
-import java.net.SocketAddress;
-import java.util.concurrent.Future;
-import java.io.IOException;
-
-/**
- * An asynchronous channel for stream-oriented listening sockets.
- *
- * <p> An asynchronous server-socket channel is created by invoking the
- * {@link #open open} method of this class.
- * A newly-created asynchronous server-socket channel is open but not yet bound.
- * It can be bound to a local address and configured to listen for connections
- * by invoking the {@link #bind(SocketAddress,int) bind} method. Once bound,
- * the {@link #accept(Object,CompletionHandler) accept} method
- * is used to initiate the accepting of connections to the channel's socket.
- * An attempt to invoke the <tt>accept</tt> method on an unbound channel will
- * cause a {@link NotYetBoundException} to be thrown.
- *
- * <p> Channels of this type are safe for use by multiple concurrent threads
- * though at most one accept operation can be outstanding at any time.
- * If a thread initiates an accept operation before a previous accept operation
- * has completed then an {@link AcceptPendingException} will be thrown.
- *
- * <p> Socket options are configured using the {@link #setOption(SocketOption,Object)
- * setOption} method. Channels of this type support the following options:
- * <blockquote>
- * <table border>
- * <tr>
- * <th>Option Name</th>
- * <th>Description</th>
- * </tr>
- * <tr>
- * <td> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </td>
- * <td> The size of the socket receive buffer </td>
- * </tr>
- * <tr>
- * <td> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </td>
- * <td> Re-use address </td>
- * </tr>
- * </table>
- * </blockquote>
- * Additional (implementation specific) options may also be supported.
- *
- * <p> <b>Usage Example:</b>
- * <pre>
- * final AsynchronousServerSocketChannel listener =
- * AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(5000));
- *
- * listener.accept(null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
- * public void completed(AsynchronousSocketChannel ch, Void att) {
- * // accept the next connection
- * listener.accept(null, this);
- *
- * // handle this connection
- * handle(ch);
- * }
- * public void failed(Throwable exc, Void att) {
- * ...
- * }
- * });
- * </pre>
- *
- * @since 1.7
- */
-
-public abstract class AsynchronousServerSocketChannel
- implements AsynchronousChannel, NetworkChannel
-{
- private final AsynchronousChannelProvider provider;
-
- /**
- * Initializes a new instance of this class.
- */
- protected AsynchronousServerSocketChannel(AsynchronousChannelProvider provider) {
- this.provider = provider;
- }
-
- /**
- * Returns the provider that created this channel.
- */
- public final AsynchronousChannelProvider provider() {
- return provider;
- }
-
- /**
- * Opens an asynchronous server-socket channel.
- *
- * <p> The new channel is created by invoking the {@link
- * java.nio.channels.spi.AsynchronousChannelProvider#openAsynchronousServerSocketChannel
- * openAsynchronousServerSocketChannel} method on the {@link
- * java.nio.channels.spi.AsynchronousChannelProvider} object that created
- * the given group. If the group parameter is <tt>null</tt> then the
- * resulting channel is created by the system-wide default provider, and
- * bound to the <em>default group</em>.
- *
- * @param group
- * The group to which the newly constructed channel should be bound,
- * or <tt>null</tt> for the default group
- *
- * @return A new asynchronous server socket channel
- *
- * @throws ShutdownChannelGroupException
- * If the channel group is shutdown
- * @throws IOException
- * If an I/O error occurs
- */
- public static AsynchronousServerSocketChannel open(AsynchronousChannelGroup group)
- throws IOException
- {
- AsynchronousChannelProvider provider = (group == null) ?
- AsynchronousChannelProvider.provider() : group.provider();
- return provider.openAsynchronousServerSocketChannel(group);
- }
-
- /**
- * Opens an asynchronous server-socket channel.
- *
- * <p> This method returns an asynchronous server socket channel that is
- * bound to the <em>default group</em>. This method is equivalent to evaluating
- * the expression:
- * <blockquote><pre>
- * open((AsynchronousChannelGroup)null);
- * </pre></blockquote>
- *
- * @return A new asynchronous server socket channel
- *
- * @throws IOException
- * If an I/O error occurs
- */
- public static AsynchronousServerSocketChannel open()
- throws IOException
- {
- return open(null);
- }
-
- /**
- * Binds the channel's socket to a local address and configures the socket to
- * listen for connections.
- *
- * <p> An invocation of this method is equivalent to the following:
- * <blockquote><pre>
- * bind(local, 0);
- * </pre></blockquote>
- *
- * @param local
- * The local address to bind the socket, or <tt>null</tt> to bind
- * to an automatically assigned socket address
- *
- * @return This channel
- *
- * @throws AlreadyBoundException {@inheritDoc}
- * @throws UnsupportedAddressTypeException {@inheritDoc}
- * @throws SecurityException {@inheritDoc}
- * @throws ClosedChannelException {@inheritDoc}
- * @throws IOException {@inheritDoc}
- */
- public final AsynchronousServerSocketChannel bind(SocketAddress local)
- throws IOException
- {
- return bind(local, 0);
- }
-
- /**
- * Binds the channel's socket to a local address and configures the socket to
- * listen for connections.
- *
- * <p> This method is used to establish an association between the socket and
- * a local address. Once an association is established then the socket remains
- * bound until the associated channel is closed.
- *
- * <p> The {@code backlog} parameter is the maximum number of pending
- * connections on the socket. Its exact semantics are implementation specific.
- * In particular, an implementation may impose a maximum length or may choose
- * to ignore the parameter altogther. If the {@code backlog} parameter has
- * the value {@code 0}, or a negative value, then an implementation specific
- * default is used.
- *
- * @param local
- * The local address to bind the socket, or {@code null} to bind
- * to an automatically assigned socket address
- * @param backlog
- * The maximum number of pending connections
- *
- * @return This channel
- *
- * @throws AlreadyBoundException
- * If the socket is already bound
- * @throws UnsupportedAddressTypeException
- * If the type of the given address is not supported
- * @throws SecurityException
- * If a security manager has been installed and its {@link
- * SecurityManager#checkListen checkListen} method denies the operation
- * @throws ClosedChannelException
- * If the channel is closed
- * @throws IOException
- * If some other I/O error occurs
- */
- public abstract AsynchronousServerSocketChannel bind(SocketAddress local, int backlog)
- throws IOException;
-
- /**
- * @throws IllegalArgumentException {@inheritDoc}
- * @throws ClosedChannelException {@inheritDoc}
- * @throws IOException {@inheritDoc}
- */
- public abstract <T> AsynchronousServerSocketChannel setOption(SocketOption<T> name, T value)
- throws IOException;
-
- /**
- * Accepts a connection.
- *
- * <p> This method initiates an asynchronous operation to accept a
- * connection made to this channel's socket. The {@code handler} parameter is
- * a completion handler that is invoked when a connection is accepted (or
- * the operation fails). The result passed to the completion handler is
- * the {@link AsynchronousSocketChannel} to the new connection.
- *
- * <p> When a new connection is accepted then the resulting {@code
- * AsynchronousSocketChannel} will be bound to the same {@link
- * AsynchronousChannelGroup} as this channel. If the group is {@link
- * AsynchronousChannelGroup#isShutdown shutdown} and a connection is accepted,
- * then the connection is closed, and the operation completes with an {@code
- * IOException} and cause {@link ShutdownChannelGroupException}.
- *
- * <p> To allow for concurrent handling of new connections, the completion
- * handler is not invoked directly by the initiating thread when a new
- * connection is accepted immediately (see <a
- * href="AsynchronousChannelGroup.html#threading">Threading<a>).
- *
- * <p> If a security manager has been installed then it verifies that the
- * address and port number of the connection's remote endpoint are permitted
- * by the security manager's {@link SecurityManager#checkAccept checkAccept}
- * method. The permission check is performed with privileges that are restricted
- * by the calling context of this method. If the permission check fails then
- * the connection is closed and the operation completes with a {@link
- * SecurityException}.
- *
- * @param attachment
- * The object to attach to the I/O operation; can be {@code null}
- * @param handler
- * The handler for consuming the result
- *
- * @throws AcceptPendingException
- * If an accept operation is already in progress on this channel
- * @throws NotYetBoundException
- * If this channel's socket has not yet been bound
- * @throws ShutdownChannelGroupException
- * If the channel group has terminated
- */
- public abstract <A> void accept(A attachment,
- CompletionHandler<AsynchronousSocketChannel,? super A> handler);
-
- /**
- * Accepts a connection.
- *
- * <p> This method initiates an asynchronous operation to accept a
- * connection made to this channel's socket. The method behaves in exactly
- * the same manner as the {@link #accept(Object, CompletionHandler)} method
- * except that instead of specifying a completion handler, this method
- * returns a {@code Future} representing the pending result. The {@code
- * Future}'s {@link Future#get() get} method returns the {@link
- * AsynchronousSocketChannel} to the new connection on successful completion.
- *
- * @return a {@code Future} object representing the pending result
- *
- * @throws AcceptPendingException
- * If an accept operation is already in progress on this channel
- * @throws NotYetBoundException
- * If this channel's socket has not yet been bound
- */
- public abstract Future<AsynchronousSocketChannel> accept();
-}
diff --git a/ojluni/src/main/java/java/nio/channels/AsynchronousSocketChannel.java b/ojluni/src/main/java/java/nio/channels/AsynchronousSocketChannel.java
deleted file mode 100755
index d78800b..0000000
--- a/ojluni/src/main/java/java/nio/channels/AsynchronousSocketChannel.java
+++ /dev/null
@@ -1,648 +0,0 @@
-/*
- * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package java.nio.channels;
-
-import java.nio.channels.spi.*;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.Future;
-import java.io.IOException;
-import java.net.SocketOption;
-import java.net.SocketAddress;
-import java.nio.ByteBuffer;
-
-/**
- * An asynchronous channel for stream-oriented connecting sockets.
- *
- * <p> Asynchronous socket channels are created in one of two ways. A newly-created
- * {@code AsynchronousSocketChannel} is created by invoking one of the {@link
- * #open open} methods defined by this class. A newly-created channel is open but
- * not yet connected. A connected {@code AsynchronousSocketChannel} is created
- * when a connection is made to the socket of an {@link AsynchronousServerSocketChannel}.
- * It is not possible to create an asynchronous socket channel for an arbitrary,
- * pre-existing {@link java.net.Socket socket}.
- *
- * <p> A newly-created channel is connected by invoking its {@link #connect connect}
- * method; once connected, a channel remains connected until it is closed. Whether
- * or not a socket channel is connected may be determined by invoking its {@link
- * #getRemoteAddress getRemoteAddress} method. An attempt to invoke an I/O
- * operation upon an unconnected channel will cause a {@link NotYetConnectedException}
- * to be thrown.
- *
- * <p> Channels of this type are safe for use by multiple concurrent threads.
- * They support concurrent reading and writing, though at most one read operation
- * and one write operation can be outstanding at any time.
- * If a thread initiates a read operation before a previous read operation has
- * completed then a {@link ReadPendingException} will be thrown. Similarly, an
- * attempt to initiate a write operation before a previous write has completed
- * will throw a {@link WritePendingException}.
- *
- * <p> Socket options are configured using the {@link #setOption(SocketOption,Object)
- * setOption} method. Asynchronous socket channels support the following options:
- * <blockquote>
- * <table border>
- * <tr>
- * <th>Option Name</th>
- * <th>Description</th>
- * </tr>
- * <tr>
- * <td> {@link java.net.StandardSocketOptions#SO_SNDBUF SO_SNDBUF} </td>
- * <td> The size of the socket send buffer </td>
- * </tr>
- * <tr>
- * <td> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </td>
- * <td> The size of the socket receive buffer </td>
- * </tr>
- * <tr>
- * <td> {@link java.net.StandardSocketOptions#SO_KEEPALIVE SO_KEEPALIVE} </td>
- * <td> Keep connection alive </td>
- * </tr>
- * <tr>
- * <td> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </td>
- * <td> Re-use address </td>
- * </tr>
- * <tr>
- * <td> {@link java.net.StandardSocketOptions#TCP_NODELAY TCP_NODELAY} </td>
- * <td> Disable the Nagle algorithm </td>
- * </tr>
- * </table>
- * </blockquote>
- * Additional (implementation specific) options may also be supported.
- *
- * <h4>Timeouts</h4>
- *
- * <p> The {@link #read(ByteBuffer,long,TimeUnit,Object,CompletionHandler) read}
- * and {@link #write(ByteBuffer,long,TimeUnit,Object,CompletionHandler) write}
- * methods defined by this class allow a timeout to be specified when initiating
- * a read or write operation. If the timeout elapses before an operation completes
- * then the operation completes with the exception {@link
- * InterruptedByTimeoutException}. A timeout may leave the channel, or the
- * underlying connection, in an inconsistent state. Where the implementation
- * cannot guarantee that bytes have not been read from the channel then it puts
- * the channel into an implementation specific <em>error state</em>. A subsequent
- * attempt to initiate a {@code read} operation causes an unspecified runtime
- * exception to be thrown. Similarly if a {@code write} operation times out and
- * the implementation cannot guarantee bytes have not been written to the
- * channel then further attempts to {@code write} to the channel cause an
- * unspecified runtime exception to be thrown. When a timeout elapses then the
- * state of the {@link ByteBuffer}, or the sequence of buffers, for the I/O
- * operation is not defined. Buffers should be discarded or at least care must
- * be taken to ensure that the buffers are not accessed while the channel remains
- * open. All methods that accept timeout parameters treat values less than or
- * equal to zero to mean that the I/O operation does not timeout.
- *
- * @since 1.7
- */
-
-public abstract class AsynchronousSocketChannel
- implements AsynchronousByteChannel, NetworkChannel
-{
- private final AsynchronousChannelProvider provider;
-
- /**
- * Initializes a new instance of this class.
- */
- protected AsynchronousSocketChannel(AsynchronousChannelProvider provider) {
- this.provider = provider;
- }
-
- /**
- * Returns the provider that created this channel.
- */
- public final AsynchronousChannelProvider provider() {
- return provider;
- }
-
- /**
- * Opens an asynchronous socket channel.
- *
- * <p> The new channel is created by invoking the {@link
- * AsynchronousChannelProvider#openAsynchronousSocketChannel
- * openAsynchronousSocketChannel} method on the {@link
- * AsynchronousChannelProvider} that created the group. If the group parameter
- * is {@code null} then the resulting channel is created by the system-wide
- * default provider, and bound to the <em>default group</em>.
- *
- * @param group
- * The group to which the newly constructed channel should be bound,
- * or {@code null} for the default group
- *
- * @return A new asynchronous socket channel
- *
- * @throws ShutdownChannelGroupException
- * If the channel group is shutdown
- * @throws IOException
- * If an I/O error occurs
- */
- public static AsynchronousSocketChannel open(AsynchronousChannelGroup group)
- throws IOException
- {
- AsynchronousChannelProvider provider = (group == null) ?
- AsynchronousChannelProvider.provider() : group.provider();
- return provider.openAsynchronousSocketChannel(group);
- }
-
- /**
- * Opens an asynchronous socket channel.
- *
- * <p> This method returns an asynchronous socket channel that is bound to
- * the <em>default group</em>.This method is equivalent to evaluating the
- * expression:
- * <blockquote><pre>
- * open((AsynchronousChannelGroup)null);
- * </pre></blockquote>
- *
- * @return A new asynchronous socket channel
- *
- * @throws IOException
- * If an I/O error occurs
- */
- public static AsynchronousSocketChannel open()
- throws IOException
- {
- return open(null);
- }
-
-
- // -- socket options and related --
-
- /**
- * @throws ConnectionPendingException
- * If a connection operation is already in progress on this channel
- * @throws AlreadyBoundException {@inheritDoc}
- * @throws UnsupportedAddressTypeException {@inheritDoc}
- * @throws ClosedChannelException {@inheritDoc}
- * @throws IOException {@inheritDoc}
- */
- @Override
- public abstract AsynchronousSocketChannel bind(SocketAddress local)
- throws IOException;
-
- /**
- * @throws IllegalArgumentException {@inheritDoc}
- * @throws ClosedChannelException {@inheritDoc}
- * @throws IOException {@inheritDoc}
- */
- @Override
- public abstract <T> AsynchronousSocketChannel setOption(SocketOption<T> name, T value)
- throws IOException;
-
- /**
- * Shutdown the connection for reading without closing the channel.
- *
- * <p> Once shutdown for reading then further reads on the channel will
- * return {@code -1}, the end-of-stream indication. If the input side of the
- * connection is already shutdown then invoking this method has no effect.
- * The effect on an outstanding read operation is system dependent and
- * therefore not specified. The effect, if any, when there is data in the
- * socket receive buffer that has not been read, or data arrives subsequently,
- * is also system dependent.
- *
- * @return The channel
- *
- * @throws NotYetConnectedException
- * If this channel is not yet connected
- * @throws ClosedChannelException
- * If this channel is closed
- * @throws IOException
- * If some other I/O error occurs
- */
- public abstract AsynchronousSocketChannel shutdownInput() throws IOException;
-
- /**
- * Shutdown the connection for writing without closing the channel.
- *
- * <p> Once shutdown for writing then further attempts to write to the
- * channel will throw {@link ClosedChannelException}. If the output side of
- * the connection is already shutdown then invoking this method has no
- * effect. The effect on an outstanding write operation is system dependent
- * and therefore not specified.
- *
- * @return The channel
- *
- * @throws NotYetConnectedException
- * If this channel is not yet connected
- * @throws ClosedChannelException
- * If this channel is closed
- * @throws IOException
- * If some other I/O error occurs
- */
- public abstract AsynchronousSocketChannel shutdownOutput() throws IOException;
-
- // -- state --
-
- /**
- * Returns the remote address to which this channel's socket is connected.
- *
- * <p> Where the channel is bound and connected to an Internet Protocol
- * socket address then the return value from this method is of type {@link
- * java.net.InetSocketAddress}.
- *
- * @return The remote address; {@code null} if the channel's socket is not
- * connected
- *
- * @throws ClosedChannelException
- * If the channel is closed
- * @throws IOException
- * If an I/O error occurs
- */
- public abstract SocketAddress getRemoteAddress() throws IOException;
-
- // -- asynchronous operations --
-
- /**
- * Connects this channel.
- *
- * <p> This method initiates an operation to connect this channel. The
- * {@code handler} parameter is a completion handler that is invoked when
- * the connection is successfully established or connection cannot be
- * established. If the connection cannot be established then the channel is
- * closed.
- *
- * <p> This method performs exactly the same security checks as the {@link
- * java.net.Socket} class. That is, if a security manager has been
- * installed then this method verifies that its {@link
- * java.lang.SecurityManager#checkConnect checkConnect} method permits
- * connecting to the address and port number of the given remote endpoint.
- *
- * @param remote
- * The remote address to which this channel is to be connected
- * @param attachment
- * The object to attach to the I/O operation; can be {@code null}
- * @param handler
- * The handler for consuming the result
- *
- * @throws UnresolvedAddressException
- * If the given remote address is not fully resolved
- * @throws UnsupportedAddressTypeException
- * If the type of the given remote address is not supported
- * @throws AlreadyConnectedException
- * If this channel is already connected
- * @throws ConnectionPendingException
- * If a connection operation is already in progress on this channel
- * @throws ShutdownChannelGroupException
- * If the channel group has terminated
- * @throws SecurityException
- * If a security manager has been installed
- * and it does not permit access to the given remote endpoint
- *
- * @see #getRemoteAddress
- */
- public abstract <A> void connect(SocketAddress remote,
- A attachment,
- CompletionHandler<Void,? super A> handler);
-
- /**
- * Connects this channel.
- *
- * <p> This method initiates an operation to connect this channel. This
- * method behaves in exactly the same manner as the {@link
- * #connect(SocketAddress, Object, CompletionHandler)} method except that
- * instead of specifying a completion handler, this method returns a {@code
- * Future} representing the pending result. The {@code Future}'s {@link
- * Future#get() get} method returns {@code null} on successful completion.
- *
- * @param remote
- * The remote address to which this channel is to be connected
- *
- * @return A {@code Future} object representing the pending result
- *
- * @throws UnresolvedAddressException
- * If the given remote address is not fully resolved
- * @throws UnsupportedAddressTypeException
- * If the type of the given remote address is not supported
- * @throws AlreadyConnectedException
- * If this channel is already connected
- * @throws ConnectionPendingException
- * If a connection operation is already in progress on this channel
- * @throws SecurityException
- * If a security manager has been installed
- * and it does not permit access to the given remote endpoint
- */
- public abstract Future<Void> connect(SocketAddress remote);
-
- /**
- * Reads a sequence of bytes from this channel into the given buffer.
- *
- * <p> This method initiates an asynchronous read operation to read a
- * sequence of bytes from this channel into the given buffer. The {@code
- * handler} parameter is a completion handler that is invoked when the read
- * operation completes (or fails). The result passed to the completion
- * handler is the number of bytes read or {@code -1} if no bytes could be
- * read because the channel has reached end-of-stream.
- *
- * <p> If a timeout is specified and the timeout elapses before the operation
- * completes then the operation completes with the exception {@link
- * InterruptedByTimeoutException}. Where a timeout occurs, and the
- * implementation cannot guarantee that bytes have not been read, or will not
- * be read from the channel into the given buffer, then further attempts to
- * read from the channel will cause an unspecific runtime exception to be
- * thrown.
- *
- * <p> Otherwise this method works in the same manner as the {@link
- * AsynchronousByteChannel#read(ByteBuffer,Object,CompletionHandler)}
- * method.
- *
- * @param dst
- * The buffer into which bytes are to be transferred
- * @param timeout
- * The maximum time for the I/O operation to complete
- * @param unit
- * The time unit of the {@code timeout} argument
- * @param attachment
- * The object to attach to the I/O operation; can be {@code null}
- * @param handler
- * The handler for consuming the result
- *
- * @throws IllegalArgumentException
- * If the buffer is read-only
- * @throws ReadPendingException
- * If a read operation is already in progress on this channel
- * @throws NotYetConnectedException
- * If this channel is not yet connected
- * @throws ShutdownChannelGroupException
- * If the channel group has terminated
- */
- public abstract <A> void read(ByteBuffer dst,
- long timeout,
- TimeUnit unit,
- A attachment,
- CompletionHandler<Integer,? super A> handler);
-
- /**
- * @throws IllegalArgumentException {@inheritDoc}
- * @throws ReadPendingException {@inheritDoc}
- * @throws NotYetConnectedException
- * If this channel is not yet connected
- * @throws ShutdownChannelGroupException
- * If the channel group has terminated
- */
- @Override
- public final <A> void read(ByteBuffer dst,
- A attachment,
- CompletionHandler<Integer,? super A> handler)
- {
- read(dst, 0L, TimeUnit.MILLISECONDS, attachment, handler);
- }
-
- /**
- * @throws IllegalArgumentException {@inheritDoc}
- * @throws ReadPendingException {@inheritDoc}
- * @throws NotYetConnectedException
- * If this channel is not yet connected
- */
- @Override
- public abstract Future<Integer> read(ByteBuffer dst);
-
- /**
- * Reads a sequence of bytes from this channel into a subsequence of the
- * given buffers. This operation, sometimes called a <em>scattering read</em>,
- * is often useful when implementing network protocols that group data into
- * segments consisting of one or more fixed-length headers followed by a
- * variable-length body. The {@code handler} parameter is a completion
- * handler that is invoked when the read operation completes (or fails). The
- * result passed to the completion handler is the number of bytes read or
- * {@code -1} if no bytes could be read because the channel has reached
- * end-of-stream.
- *
- * <p> This method initiates a read of up to <i>r</i> bytes from this channel,
- * where <i>r</i> is the total number of bytes remaining in the specified
- * subsequence of the given buffer array, that is,
- *
- * <blockquote><pre>
- * dsts[offset].remaining()
- * + dsts[offset+1].remaining()
- * + ... + dsts[offset+length-1].remaining()</pre></blockquote>
- *
- * at the moment that the read is attempted.
- *
- * <p> Suppose that a byte sequence of length <i>n</i> is read, where
- * <tt>0</tt> <tt><</tt> <i>n</i> <tt><=</tt> <i>r</i>.
- * Up to the first <tt>dsts[offset].remaining()</tt> bytes of this sequence
- * are transferred into buffer <tt>dsts[offset]</tt>, up to the next
- * <tt>dsts[offset+1].remaining()</tt> bytes are transferred into buffer
- * <tt>dsts[offset+1]</tt>, and so forth, until the entire byte sequence
- * is transferred into the given buffers. As many bytes as possible are
- * transferred into each buffer, hence the final position of each updated
- * buffer, except the last updated buffer, is guaranteed to be equal to
- * that buffer's limit. The underlying operating system may impose a limit
- * on the number of buffers that may be used in an I/O operation. Where the
- * number of buffers (with bytes remaining), exceeds this limit, then the
- * I/O operation is performed with the maximum number of buffers allowed by
- * the operating system.
- *
- * <p> If a timeout is specified and the timeout elapses before the operation
- * completes then it completes with the exception {@link
- * InterruptedByTimeoutException}. Where a timeout occurs, and the
- * implementation cannot guarantee that bytes have not been read, or will not
- * be read from the channel into the given buffers, then further attempts to
- * read from the channel will cause an unspecific runtime exception to be
- * thrown.
- *
- * @param dsts
- * The buffers into which bytes are to be transferred
- * @param offset
- * The offset within the buffer array of the first buffer into which
- * bytes are to be transferred; must be non-negative and no larger than
- * {@code dsts.length}
- * @param length
- * The maximum number of buffers to be accessed; must be non-negative
- * and no larger than {@code dsts.length - offset}
- * @param timeout
- * The maximum time for the I/O operation to complete
- * @param unit
- * The time unit of the {@code timeout} argument
- * @param attachment
- * The object to attach to the I/O operation; can be {@code null}
- * @param handler
- * The handler for consuming the result
- *
- * @throws IndexOutOfBoundsException
- * If the pre-conditions for the {@code offset} and {@code length}
- * parameter aren't met
- * @throws IllegalArgumentException
- * If the buffer is read-only
- * @throws ReadPendingException
- * If a read operation is already in progress on this channel
- * @throws NotYetConnectedException
- * If this channel is not yet connected
- * @throws ShutdownChannelGroupException
- * If the channel group has terminated
- */
- public abstract <A> void read(ByteBuffer[] dsts,
- int offset,
- int length,
- long timeout,
- TimeUnit unit,
- A attachment,
- CompletionHandler<Long,? super A> handler);
-
- /**
- * Writes a sequence of bytes to this channel from the given buffer.
- *
- * <p> This method initiates an asynchronous write operation to write a
- * sequence of bytes to this channel from the given buffer. The {@code
- * handler} parameter is a completion handler that is invoked when the write
- * operation completes (or fails). The result passed to the completion
- * handler is the number of bytes written.
- *
- * <p> If a timeout is specified and the timeout elapses before the operation
- * completes then it completes with the exception {@link
- * InterruptedByTimeoutException}. Where a timeout occurs, and the
- * implementation cannot guarantee that bytes have not been written, or will
- * not be written to the channel from the given buffer, then further attempts
- * to write to the channel will cause an unspecific runtime exception to be
- * thrown.
- *
- * <p> Otherwise this method works in the same manner as the {@link
- * AsynchronousByteChannel#write(ByteBuffer,Object,CompletionHandler)}
- * method.
- *
- * @param src
- * The buffer from which bytes are to be retrieved
- * @param timeout
- * The maximum time for the I/O operation to complete
- * @param unit
- * The time unit of the {@code timeout} argument
- * @param attachment
- * The object to attach to the I/O operation; can be {@code null}
- * @param handler
- * The handler for consuming the result
- *
- * @throws WritePendingException
- * If a write operation is already in progress on this channel
- * @throws NotYetConnectedException
- * If this channel is not yet connected
- * @throws ShutdownChannelGroupException
- * If the channel group has terminated
- */
- public abstract <A> void write(ByteBuffer src,
- long timeout,
- TimeUnit unit,
- A attachment,
- CompletionHandler<Integer,? super A> handler);
-
- /**
- * @throws WritePendingException {@inheritDoc}
- * @throws NotYetConnectedException
- * If this channel is not yet connected
- * @throws ShutdownChannelGroupException
- * If the channel group has terminated
- */
- @Override
- public final <A> void write(ByteBuffer src,
- A attachment,
- CompletionHandler<Integer,? super A> handler)
-
- {
- write(src, 0L, TimeUnit.MILLISECONDS, attachment, handler);
- }
-
- /**
- * @throws WritePendingException {@inheritDoc}
- * @throws NotYetConnectedException
- * If this channel is not yet connected
- */
- @Override
- public abstract Future<Integer> write(ByteBuffer src);
-
- /**
- * Writes a sequence of bytes to this channel from a subsequence of the given
- * buffers. This operation, sometimes called a <em>gathering write</em>, is
- * often useful when implementing network protocols that group data into
- * segments consisting of one or more fixed-length headers followed by a
- * variable-length body. The {@code handler} parameter is a completion
- * handler that is invoked when the write operation completes (or fails).
- * The result passed to the completion handler is the number of bytes written.
- *
- * <p> This method initiates a write of up to <i>r</i> bytes to this channel,
- * where <i>r</i> is the total number of bytes remaining in the specified
- * subsequence of the given buffer array, that is,
- *
- * <blockquote><pre>
- * srcs[offset].remaining()
- * + srcs[offset+1].remaining()
- * + ... + srcs[offset+length-1].remaining()</pre></blockquote>
- *
- * at the moment that the write is attempted.
- *
- * <p> Suppose that a byte sequence of length <i>n</i> is written, where
- * <tt>0</tt> <tt><</tt> <i>n</i> <tt><=</tt> <i>r</i>.
- * Up to the first <tt>srcs[offset].remaining()</tt> bytes of this sequence
- * are written from buffer <tt>srcs[offset]</tt>, up to the next
- * <tt>srcs[offset+1].remaining()</tt> bytes are written from buffer
- * <tt>srcs[offset+1]</tt>, and so forth, until the entire byte sequence is
- * written. As many bytes as possible are written from each buffer, hence
- * the final position of each updated buffer, except the last updated
- * buffer, is guaranteed to be equal to that buffer's limit. The underlying
- * operating system may impose a limit on the number of buffers that may be
- * used in an I/O operation. Where the number of buffers (with bytes
- * remaining), exceeds this limit, then the I/O operation is performed with
- * the maximum number of buffers allowed by the operating system.
- *
- * <p> If a timeout is specified and the timeout elapses before the operation
- * completes then it completes with the exception {@link
- * InterruptedByTimeoutException}. Where a timeout occurs, and the
- * implementation cannot guarantee that bytes have not been written, or will
- * not be written to the channel from the given buffers, then further attempts
- * to write to the channel will cause an unspecific runtime exception to be
- * thrown.
- *
- * @param srcs
- * The buffers from which bytes are to be retrieved
- * @param offset
- * The offset within the buffer array of the first buffer from which
- * bytes are to be retrieved; must be non-negative and no larger
- * than {@code srcs.length}
- * @param length
- * The maximum number of buffers to be accessed; must be non-negative
- * and no larger than {@code srcs.length - offset}
- * @param timeout
- * The maximum time for the I/O operation to complete
- * @param unit
- * The time unit of the {@code timeout} argument
- * @param attachment
- * The object to attach to the I/O operation; can be {@code null}
- * @param handler
- * The handler for consuming the result
- *
- * @throws IndexOutOfBoundsException
- * If the pre-conditions for the {@code offset} and {@code length}
- * parameter aren't met
- * @throws WritePendingException
- * If a write operation is already in progress on this channel
- * @throws NotYetConnectedException
- * If this channel is not yet connected
- * @throws ShutdownChannelGroupException
- * If the channel group has terminated
- */
- public abstract <A> void write(ByteBuffer[] srcs,
- int offset,
- int length,
- long timeout,
- TimeUnit unit,
- A attachment,
- CompletionHandler<Long,? super A> handler);
-}
diff --git a/ojluni/src/main/java/java/nio/channels/Channels.java b/ojluni/src/main/java/java/nio/channels/Channels.java
index f27f0ab..204eafd 100755
--- a/ojluni/src/main/java/java/nio/channels/Channels.java
+++ b/ojluni/src/main/java/java/nio/channels/Channels.java
@@ -181,155 +181,6 @@
};
}
-
- /**
- * Constructs a stream that reads bytes from the given channel.
- *
- * <p> The stream will not be buffered, and it will not support the {@link
- * InputStream#mark mark} or {@link InputStream#reset reset} methods. The
- * stream will be safe for access by multiple concurrent threads. Closing
- * the stream will in turn cause the channel to be closed. </p>
- *
- * @param ch
- * The channel from which bytes will be read
- *
- * @return A new input stream
- *
- * @since 1.7
- */
- public static InputStream newInputStream(final AsynchronousByteChannel ch) {
- checkNotNull(ch, "ch");
- return new InputStream() {
-
- private ByteBuffer bb = null;
- private byte[] bs = null; // Invoker's previous array
- private byte[] b1 = null;
-
- @Override
- public synchronized int read() throws IOException {
- if (b1 == null)
- b1 = new byte[1];
- int n = this.read(b1);
- if (n == 1)
- return b1[0] & 0xff;
- return -1;
- }
-
- @Override
- public synchronized int read(byte[] bs, int off, int len)
- throws IOException
- {
- if ((off < 0) || (off > bs.length) || (len < 0) ||
- ((off + len) > bs.length) || ((off + len) < 0)) {
- throw new IndexOutOfBoundsException();
- } else if (len == 0)
- return 0;
-
- ByteBuffer bb = ((this.bs == bs)
- ? this.bb
- : ByteBuffer.wrap(bs));
- bb.position(off);
- bb.limit(Math.min(off + len, bb.capacity()));
- this.bb = bb;
- this.bs = bs;
-
- boolean interrupted = false;
- try {
- for (;;) {
- try {
- return ch.read(bb).get();
- } catch (ExecutionException ee) {
- throw new IOException(ee.getCause());
- } catch (InterruptedException ie) {
- interrupted = true;
- }
- }
- } finally {
- if (interrupted)
- Thread.currentThread().interrupt();
- }
- }
-
- @Override
- public void close() throws IOException {
- ch.close();
- }
- };
- }
-
- /**
- * Constructs a stream that writes bytes to the given channel.
- *
- * <p> The stream will not be buffered. The stream will be safe for access
- * by multiple concurrent threads. Closing the stream will in turn cause
- * the channel to be closed. </p>
- *
- * @param ch
- * The channel to which bytes will be written
- *
- * @return A new output stream
- *
- * @since 1.7
- */
- public static OutputStream newOutputStream(final AsynchronousByteChannel ch) {
- checkNotNull(ch, "ch");
- return new OutputStream() {
-
- private ByteBuffer bb = null;
- private byte[] bs = null; // Invoker's previous array
- private byte[] b1 = null;
-
- @Override
- public synchronized void write(int b) throws IOException {
- if (b1 == null)
- b1 = new byte[1];
- b1[0] = (byte)b;
- this.write(b1);
- }
-
- @Override
- public synchronized void write(byte[] bs, int off, int len)
- throws IOException
- {
- if ((off < 0) || (off > bs.length) || (len < 0) ||
- ((off + len) > bs.length) || ((off + len) < 0)) {
- throw new IndexOutOfBoundsException();
- } else if (len == 0) {
- return;
- }
- ByteBuffer bb = ((this.bs == bs)
- ? this.bb
- : ByteBuffer.wrap(bs));
- bb.limit(Math.min(off + len, bb.capacity()));
- bb.position(off);
- this.bb = bb;
- this.bs = bs;
-
- boolean interrupted = false;
- try {
- while (bb.remaining() > 0) {
- try {
- ch.write(bb).get();
- } catch (ExecutionException ee) {
- throw new IOException(ee.getCause());
- } catch (InterruptedException ie) {
- interrupted = true;
- }
- }
- } finally {
- if (interrupted)
- Thread.currentThread().interrupt();
- }
- }
-
- @Override
- public void close() throws IOException {
- ch.close();
- }
- };
- }
-
-
// -- Channels from streams --
/**
diff --git a/ojluni/src/main/java/java/nio/channels/CompletionHandler.java b/ojluni/src/main/java/java/nio/channels/CompletionHandler.java
deleted file mode 100755
index 2574dbf..0000000
--- a/ojluni/src/main/java/java/nio/channels/CompletionHandler.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package java.nio.channels;
-
-/**
- * A handler for consuming the result of an asynchronous I/O operation.
- *
- * <p> The asynchronous channels defined in this package allow a completion
- * handler to be specified to consume the result of an asynchronous operation.
- * The {@link #completed completed} method is invoked when the I/O operation
- * completes successfully. The {@link #failed failed} method is invoked if the
- * I/O operations fails. The implementations of these methods should complete
- * in a timely manner so as to avoid keeping the invoking thread from dispatching
- * to other completion handlers.
- *
- * @param <V> The result type of the I/O operation
- * @param <A> The type of the object attached to the I/O operation
- *
- * @since 1.7
- */
-
-public interface CompletionHandler<V,A> {
-
- /**
- * Invoked when an operation has completed.
- *
- * @param result
- * The result of the I/O operation.
- * @param attachment
- * The object attached to the I/O operation when it was initiated.
- */
- void completed(V result, A attachment);
-
- /**
- * Invoked when an operation fails.
- *
- * @param exc
- * The exception to indicate why the I/O operation failed
- * @param attachment
- * The object attached to the I/O operation when it was initiated.
- */
- void failed(Throwable exc, A attachment);
-}
diff --git a/ojluni/src/main/java/java/nio/channels/DatagramChannel.java b/ojluni/src/main/java/java/nio/channels/DatagramChannel.java
index f4a6110..31883fb7 100755
--- a/ojluni/src/main/java/java/nio/channels/DatagramChannel.java
+++ b/ojluni/src/main/java/java/nio/channels/DatagramChannel.java
@@ -112,7 +112,7 @@
public abstract class DatagramChannel
extends AbstractSelectableChannel
- implements ByteChannel, ScatteringByteChannel, GatheringByteChannel, MulticastChannel
+ implements ByteChannel, ScatteringByteChannel, GatheringByteChannel
{
/**
diff --git a/ojluni/src/main/java/java/nio/channels/IllegalChannelGroupException.java b/ojluni/src/main/java/java/nio/channels/IllegalChannelGroupException.java
deleted file mode 100644
index dd47105..0000000
--- a/ojluni/src/main/java/java/nio/channels/IllegalChannelGroupException.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
- *
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-// -- This file was mechanically generated: Do not edit! -- //
-
-package java.nio.channels;
-
-
-/**
- * Unchecked exception thrown when an attempt is made to open a channel
- * in a group that was not created by the same provider.
- *
- * @since 1.7
- */
-
-public class IllegalChannelGroupException
- extends IllegalArgumentException
-{
-
- private static final long serialVersionUID = -2495041211157744253L;
-
- /**
- * Constructs an instance of this class.
- */
- public IllegalChannelGroupException() { }
-
-}
diff --git a/ojluni/src/main/java/java/nio/channels/InterruptedByTimeoutException.java b/ojluni/src/main/java/java/nio/channels/InterruptedByTimeoutException.java
deleted file mode 100644
index ae2018d..0000000
--- a/ojluni/src/main/java/java/nio/channels/InterruptedByTimeoutException.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
- *
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-// -- This file was mechanically generated: Do not edit! -- //
-
-package java.nio.channels;
-
-
-/**
- * Checked exception received by a thread when a timeout elapses before an
- * asynchronous operation completes.
- *
- * @since 1.7
- */
-
-public class InterruptedByTimeoutException
- extends java.io.IOException
-{
-
- private static final long serialVersionUID = -4268008601014042947L;
-
- /**
- * Constructs an instance of this class.
- */
- public InterruptedByTimeoutException() { }
-
-}
diff --git a/ojluni/src/main/java/java/nio/channels/MembershipKey.java b/ojluni/src/main/java/java/nio/channels/MembershipKey.java
deleted file mode 100755
index ea7536a..0000000
--- a/ojluni/src/main/java/java/nio/channels/MembershipKey.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package java.nio.channels;
-
-import java.net.InetAddress;
-import java.net.NetworkInterface;
-import java.io.IOException;
-
-/**
- * A token representing the membership of an Internet Protocol (IP) multicast
- * group.
- *
- * <p> A membership key may represent a membership to receive all datagrams sent
- * to the group, or it may be <em>source-specific</em>, meaning that it
- * represents a membership that receives only datagrams from a specific source
- * address. Whether or not a membership key is source-specific may be determined
- * by invoking its {@link #sourceAddress() sourceAddress} method.
- *
- * <p> A membership key is valid upon creation and remains valid until the
- * membership is dropped by invoking the {@link #drop() drop} method, or
- * the channel is closed. The validity of the membership key may be tested
- * by invoking its {@link #isValid() isValid} method.
- *
- * <p> Where a membership key is not source-specific and the underlying operation
- * system supports source filtering, then the {@link #block block} and {@link
- * #unblock unblock} methods can be used to block or unblock multicast datagrams
- * from particular source addresses.
- *
- * @see MulticastChannel
- *
- * @since 1.7
- */
-public abstract class MembershipKey {
-
- /**
- * Initializes a new instance of this class.
- */
- protected MembershipKey() {
- }
-
- /**
- * Tells whether or not this membership is valid.
- *
- * <p> A multicast group membership is valid upon creation and remains
- * valid until the membership is dropped by invoking the {@link #drop() drop}
- * method, or the channel is closed.
- *
- * @return {@code true} if this membership key is valid, {@code false}
- * otherwise
- */
- public abstract boolean isValid();
-
- /**
- * Drop membership.
- *
- * <p> If the membership key represents a membership to receive all datagrams
- * then the membership is dropped and the channel will no longer receive any
- * datagrams sent to the group. If the membership key is source-specific
- * then the channel will no longer receive datagrams sent to the group from
- * that source address.
- *
- * <p> After membership is dropped it may still be possible to receive
- * datagrams sent to the group. This can arise when datagrams are waiting to
- * be received in the socket's receive buffer. After membership is dropped
- * then the channel may {@link MulticastChannel#join join} the group again
- * in which case a new membership key is returned.
- *
- * <p> Upon return, this membership object will be {@link #isValid() invalid}.
- * If the multicast group membership is already invalid then invoking this
- * method has no effect. Once a multicast group membership is invalid,
- * it remains invalid forever.
- */
- public abstract void drop();
-
- /**
- * Block multicast datagrams from the given source address.
- *
- * <p> If this membership key is not source-specific, and the underlying
- * operating system supports source filtering, then this method blocks
- * multicast datagrams from the given source address. If the given source
- * address is already blocked then this method has no effect.
- * After a source address is blocked it may still be possible to receive
- * datagams from that source. This can arise when datagrams are waiting to
- * be received in the socket's receive buffer.
- *
- * @param source
- * The source address to block
- *
- * @return This membership key
- *
- * @throws IllegalArgumentException
- * If the {@code source} parameter is not a unicast address or
- * is not the same address type as the multicast group
- * @throws IllegalStateException
- * If this membership key is source-specific or is no longer valid
- * @throws UnsupportedOperationException
- * If the underlying operating system does not support source
- * filtering
- * @throws IOException
- * If an I/O error occurs
- */
- public abstract MembershipKey block(InetAddress source) throws IOException;
-
- /**
- * Unblock multicast datagrams from the given source address that was
- * previously blocked using the {@link #block(InetAddress) block} method.
- *
- * @param source
- * The source address to unblock
- *
- * @return This membership key
- *
- * @throws IllegalStateException
- * If the given source address is not currently blocked or the
- * membership key is no longer valid
- */
- public abstract MembershipKey unblock(InetAddress source);
-
- /**
- * Returns the channel for which this membership key was created. This
- * method will continue to return the channel even after the membership
- * becomes {@link #isValid invalid}.
- *
- * @return the channel
- */
- public abstract MulticastChannel channel();
-
- /**
- * Returns the multicast group for which this membership key was created.
- * This method will continue to return the group even after the membership
- * becomes {@link #isValid invalid}.
- *
- * @return the multicast group
- */
- public abstract InetAddress group();
-
- /**
- * Returns the network interface for which this membership key was created.
- * This method will continue to return the network interface even after the
- * membership becomes {@link #isValid invalid}.
- *
- * @return the network interface
- */
- public abstract NetworkInterface networkInterface();
-
- /**
- * Returns the source address if this membership key is source-specific,
- * or {@code null} if this membership is not source-specific.
- *
- * @return The source address if this membership key is source-specific,
- * otherwise {@code null}
- */
- public abstract InetAddress sourceAddress();
-}
diff --git a/ojluni/src/main/java/java/nio/channels/MulticastChannel.java b/ojluni/src/main/java/java/nio/channels/MulticastChannel.java
deleted file mode 100755
index 5b61f77..0000000
--- a/ojluni/src/main/java/java/nio/channels/MulticastChannel.java
+++ /dev/null
@@ -1,230 +0,0 @@
-/*
- * Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package java.nio.channels;
-
-import java.net.InetAddress;
-import java.net.NetworkInterface;
-import java.io.IOException;
-import java.net.ProtocolFamily; // javadoc
-import java.net.StandardProtocolFamily; // javadoc
-import java.net.StandardSocketOptions; // javadoc
-
-/**
- * A network channel that supports Internet Protocol (IP) multicasting.
- *
- * <p> IP multicasting is the transmission of IP datagrams to members of
- * a <em>group</em> that is zero or more hosts identified by a single destination
- * address.
- *
- * <p> In the case of a channel to an {@link StandardProtocolFamily#INET IPv4} socket,
- * the underlying operating system supports <a href="http://www.ietf.org/rfc/rfc2236.txt">
- * <i>RFC 2236: Internet Group Management Protocol, Version 2 (IGMPv2)</i></a>.
- * It may optionally support source filtering as specified by <a
- * href="http://www.ietf.org/rfc/rfc3376.txt"> <i>RFC 3376: Internet Group
- * Management Protocol, Version 3 (IGMPv3)</i></a>.
- * For channels to an {@link StandardProtocolFamily#INET6 IPv6} socket, the equivalent
- * standards are <a href="http://www.ietf.org/rfc/rfc2710.txt"> <i>RFC 2710:
- * Multicast Listener Discovery (MLD) for IPv6</i></a> and <a
- * href="http://www.ietf.org/rfc/rfc3810.txt"> <i>RFC 3810: Multicast Listener
- * Discovery Version 2 (MLDv2) for IPv6</i></a>.
- *
- * <p> The {@link #join(InetAddress,NetworkInterface)} method is used to
- * join a group and receive all multicast datagrams sent to the group. A channel
- * may join several multicast groups and may join the same group on several
- * {@link NetworkInterface interfaces}. Membership is dropped by invoking the {@link
- * MembershipKey#drop drop} method on the returned {@link MembershipKey}. If the
- * underlying platform supports source filtering then the {@link MembershipKey#block
- * block} and {@link MembershipKey#unblock unblock} methods can be used to block or
- * unblock multicast datagrams from particular source addresses.
- *
- * <p> The {@link #join(InetAddress,NetworkInterface,InetAddress)} method
- * is used to begin receiving datagrams sent to a group whose source address matches
- * a given source address. This method throws {@link UnsupportedOperationException}
- * if the underlying platform does not support source filtering. Membership is
- * <em>cumulative</em> and this method may be invoked again with the same group
- * and interface to allow receiving datagrams from other source addresses. The
- * method returns a {@link MembershipKey} that represents membership to receive
- * datagrams from the given source address. Invoking the key's {@link
- * MembershipKey#drop drop} method drops membership so that datagrams from the
- * source address can no longer be received.
- *
- * <h4>Platform dependencies</h4>
- *
- * The multicast implementation is intended to map directly to the native
- * multicasting facility. Consequently, the following items should be considered
- * when developing an application that receives IP multicast datagrams:
- *
- * <ol>
- *
- * <li><p> The creation of the channel should specify the {@link ProtocolFamily}
- * that corresponds to the address type of the multicast groups that the channel
- * will join. There is no guarantee that a channel to a socket in one protocol
- * family can join and receive multicast datagrams when the address of the
- * multicast group corresponds to another protocol family. For example, it is
- * implementation specific if a channel to an {@link StandardProtocolFamily#INET6 IPv6}
- * socket can join an {@link StandardProtocolFamily#INET IPv4} multicast group and receive
- * multicast datagrams sent to the group. </p></li>
- *
- * <li><p> The channel's socket should be bound to the {@link
- * InetAddress#isAnyLocalAddress wildcard} address. If the socket is bound to
- * a specific address, rather than the wildcard address then it is implementation
- * specific if multicast datagrams are received by the socket. </p></li>
- *
- * <li><p> The {@link StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} option should be
- * enabled prior to {@link NetworkChannel#bind binding} the socket. This is
- * required to allow multiple members of the group to bind to the same
- * address. </p></li>
- *
- * </ol>
- *
- * <p> <b>Usage Example:</b>
- * <pre>
- * // join multicast group on this interface, and also use this
- * // interface for outgoing multicast datagrams
- * NetworkInterface ni = NetworkInterface.getByName("hme0");
- *
- * DatagramChannel dc = DatagramChannel.open(StandardProtocolFamily.INET)
- * .setOption(StandardSocketOptions.SO_REUSEADDR, true)
- * .bind(new InetSocketAddress(5000))
- * .setOption(StandardSocketOptions.IP_MULTICAST_IF, ni);
- *
- * InetAddress group = InetAddress.getByName("225.4.5.6");
- *
- * MembershipKey key = dc.join(group, ni);
- * </pre>
- *
- * @since 1.7
- */
-
-public interface MulticastChannel
- extends NetworkChannel
-{
- /**
- * Closes this channel.
- *
- * <p> If the channel is a member of a multicast group then the membership
- * is {@link MembershipKey#drop dropped}. Upon return, the {@link
- * MembershipKey membership-key} will be {@link MembershipKey#isValid
- * invalid}.
- *
- * <p> This method otherwise behaves exactly as specified by the {@link
- * Channel} interface.
- *
- * @throws IOException
- * If an I/O error occurs
- */
- @Override void close() throws IOException;
-
- /**
- * Joins a multicast group to begin receiving all datagrams sent to the group,
- * returning a membership key.
- *
- * <p> If this channel is currently a member of the group on the given
- * interface to receive all datagrams then the membership key, representing
- * that membership, is returned. Otherwise this channel joins the group and
- * the resulting new membership key is returned. The resulting membership key
- * is not {@link MembershipKey#sourceAddress source-specific}.
- *
- * <p> A multicast channel may join several multicast groups, including
- * the same group on more than one interface. An implementation may impose a
- * limit on the number of groups that may be joined at the same time.
- *
- * @param group
- * The multicast address to join
- * @param interf
- * The network interface on which to join the group
- *
- * @return The membership key
- *
- * @throws IllegalArgumentException
- * If the group parameter is not a {@link InetAddress#isMulticastAddress
- * multicast} address, or the group parameter is an address type
- * that is not supported by this channel
- * @throws IllegalStateException
- * If the channel already has source-specific membership of the
- * group on the interface
- * @throws UnsupportedOperationException
- * If the channel's socket is not an Internet Protocol socket
- * @throws ClosedChannelException
- * If this channel is closed
- * @throws IOException
- * If an I/O error occurs
- * @throws SecurityException
- * If a security manager is set, and its
- * {@link SecurityManager#checkMulticast(InetAddress) checkMulticast}
- * method denies access to the multiast group
- */
- MembershipKey join(InetAddress group, NetworkInterface interf)
- throws IOException;
-
- /**
- * Joins a multicast group to begin receiving datagrams sent to the group
- * from a given source address.
- *
- * <p> If this channel is currently a member of the group on the given
- * interface to receive datagrams from the given source address then the
- * membership key, representing that membership, is returned. Otherwise this
- * channel joins the group and the resulting new membership key is returned.
- * The resulting membership key is {@link MembershipKey#sourceAddress
- * source-specific}.
- *
- * <p> Membership is <em>cumulative</em> and this method may be invoked
- * again with the same group and interface to allow receiving datagrams sent
- * by other source addresses to the group.
- *
- * @param group
- * The multicast address to join
- * @param interf
- * The network interface on which to join the group
- * @param source
- * The source address
- *
- * @return The membership key
- *
- * @throws IllegalArgumentException
- * If the group parameter is not a {@link
- * InetAddress#isMulticastAddress multicast} address, the
- * source parameter is not a unicast address, the group
- * parameter is an address type that is not supported by this channel,
- * or the source parameter is not the same address type as the group
- * @throws IllegalStateException
- * If the channel is currently a member of the group on the given
- * interface to receive all datagrams
- * @throws UnsupportedOperationException
- * If the channel's socket is not an Internet Protocol socket or
- * source filtering is not supported
- * @throws ClosedChannelException
- * If this channel is closed
- * @throws IOException
- * If an I/O error occurs
- * @throws SecurityException
- * If a security manager is set, and its
- * {@link SecurityManager#checkMulticast(InetAddress) checkMulticast}
- * method denies access to the multiast group
- */
- MembershipKey join(InetAddress group, NetworkInterface interf, InetAddress source)
- throws IOException;
-}
diff --git a/ojluni/src/main/java/java/nio/channels/ReadPendingException.java b/ojluni/src/main/java/java/nio/channels/ReadPendingException.java
deleted file mode 100644
index 770c9de..0000000
--- a/ojluni/src/main/java/java/nio/channels/ReadPendingException.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
- *
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-// -- This file was mechanically generated: Do not edit! -- //
-
-package java.nio.channels;
-
-
-/**
- * Unchecked exception thrown when an attempt is made to read from an
- * asynchronous socket channel and a previous read has not completed.
- *
- * @since 1.7
- */
-
-public class ReadPendingException
- extends IllegalStateException
-{
-
- private static final long serialVersionUID = 1986315242191227217L;
-
- /**
- * Constructs an instance of this class.
- */
- public ReadPendingException() { }
-
-}
diff --git a/ojluni/src/main/java/java/nio/channels/ShutdownChannelGroupException.java b/ojluni/src/main/java/java/nio/channels/ShutdownChannelGroupException.java
deleted file mode 100644
index b4e4b7d..0000000
--- a/ojluni/src/main/java/java/nio/channels/ShutdownChannelGroupException.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
- *
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-// -- This file was mechanically generated: Do not edit! -- //
-
-package java.nio.channels;
-
-
-/**
- * Unchecked exception thrown when an attempt is made to construct a channel in
- * a group that is shutdown or the completion handler for an I/O operation
- * cannot be invoked because the channel group has terminated.
- *
- * @since 1.7
- */
-
-public class ShutdownChannelGroupException
- extends IllegalStateException
-{
-
- private static final long serialVersionUID = -3903801676350154157L;
-
- /**
- * Constructs an instance of this class.
- */
- public ShutdownChannelGroupException() { }
-
-}
diff --git a/ojluni/src/main/java/java/nio/channels/WritePendingException.java b/ojluni/src/main/java/java/nio/channels/WritePendingException.java
deleted file mode 100644
index 8957702..0000000
--- a/ojluni/src/main/java/java/nio/channels/WritePendingException.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
- *
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-// -- This file was mechanically generated: Do not edit! -- //
-
-package java.nio.channels;
-
-
-/**
- * Unchecked exception thrown when an attempt is made to write to an
- * asynchronous socket channel and a previous write has not completed.
- *
- * @since 1.7
- */
-
-public class WritePendingException
- extends IllegalStateException
-{
-
- private static final long serialVersionUID = 7031871839266032276L;
-
- /**
- * Constructs an instance of this class.
- */
- public WritePendingException() { }
-
-}
diff --git a/ojluni/src/main/java/java/nio/channels/spi/AsynchronousChannelProvider.java b/ojluni/src/main/java/java/nio/channels/spi/AsynchronousChannelProvider.java
deleted file mode 100755
index 827a2c5..0000000
--- a/ojluni/src/main/java/java/nio/channels/spi/AsynchronousChannelProvider.java
+++ /dev/null
@@ -1,241 +0,0 @@
-/*
- * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package java.nio.channels.spi;
-
-import java.nio.channels.*;
-import java.io.IOException;
-import java.util.Iterator;
-import java.util.ServiceLoader;
-import java.util.ServiceConfigurationError;
-import java.util.concurrent.*;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-
-/**
- * Service-provider class for asynchronous channels.
- *
- * <p> An asynchronous channel provider is a concrete subclass of this class that
- * has a zero-argument constructor and implements the abstract methods specified
- * below. A given invocation of the Java virtual machine maintains a single
- * system-wide default provider instance, which is returned by the {@link
- * #provider() provider} method. The first invocation of that method will locate
- * the default provider as specified below.
- *
- * <p> All of the methods in this class are safe for use by multiple concurrent
- * threads. </p>
- *
- * @since 1.7
- */
-
-public abstract class AsynchronousChannelProvider {
- private static Void checkPermission() {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null)
- sm.checkPermission(new RuntimePermission("asynchronousChannelProvider"));
- return null;
- }
- private AsynchronousChannelProvider(Void ignore) { }
-
- /**
- * Initializes a new instance of this class.
- *
- * @throws SecurityException
- * If a security manager has been installed and it denies
- * {@link RuntimePermission}<tt>("asynchronousChannelProvider")</tt>
- */
- protected AsynchronousChannelProvider() {
- this(checkPermission());
- }
-
- // lazy initialization of default provider
- private static class ProviderHolder {
- static final AsynchronousChannelProvider provider = load();
-
- private static AsynchronousChannelProvider load() {
- return AccessController
- .doPrivileged(new PrivilegedAction<AsynchronousChannelProvider>() {
- public AsynchronousChannelProvider run() {
- AsynchronousChannelProvider p;
- p = loadProviderFromProperty();
- if (p != null)
- return p;
- p = loadProviderAsService();
- if (p != null)
- return p;
- return sun.nio.ch.DefaultAsynchronousChannelProvider.create();
- }});
- }
-
- private static AsynchronousChannelProvider loadProviderFromProperty() {
- String cn = System.getProperty("java.nio.channels.spi.AsynchronousChannelProvider");
- if (cn == null)
- return null;
- try {
- Class<?> c = Class.forName(cn, true,
- ClassLoader.getSystemClassLoader());
- return (AsynchronousChannelProvider)c.newInstance();
- } catch (ClassNotFoundException x) {
- throw new ServiceConfigurationError(null, x);
- } catch (IllegalAccessException x) {
- throw new ServiceConfigurationError(null, x);
- } catch (InstantiationException x) {
- throw new ServiceConfigurationError(null, x);
- } catch (SecurityException x) {
- throw new ServiceConfigurationError(null, x);
- }
- }
-
- private static AsynchronousChannelProvider loadProviderAsService() {
- ServiceLoader<AsynchronousChannelProvider> sl =
- ServiceLoader.load(AsynchronousChannelProvider.class,
- ClassLoader.getSystemClassLoader());
- Iterator<AsynchronousChannelProvider> i = sl.iterator();
- for (;;) {
- try {
- return (i.hasNext()) ? i.next() : null;
- } catch (ServiceConfigurationError sce) {
- if (sce.getCause() instanceof SecurityException) {
- // Ignore the security exception, try the next provider
- continue;
- }
- throw sce;
- }
- }
- }
- }
-
- /**
- * Returns the system-wide default asynchronous channel provider for this
- * invocation of the Java virtual machine.
- *
- * <p> The first invocation of this method locates the default provider
- * object as follows: </p>
- *
- * <ol>
- *
- * <li><p> If the system property
- * <tt>java.nio.channels.spi.AsynchronousChannelProvider</tt> is defined
- * then it is taken to be the fully-qualified name of a concrete provider class.
- * The class is loaded and instantiated; if this process fails then an
- * unspecified error is thrown. </p></li>
- *
- * <li><p> If a provider class has been installed in a jar file that is
- * visible to the system class loader, and that jar file contains a
- * provider-configuration file named
- * <tt>java.nio.channels.spi.AsynchronousChannelProvider</tt> in the resource
- * directory <tt>META-INF/services</tt>, then the first class name
- * specified in that file is taken. The class is loaded and
- * instantiated; if this process fails then an unspecified error is
- * thrown. </p></li>
- *
- * <li><p> Finally, if no provider has been specified by any of the above
- * means then the system-default provider class is instantiated and the
- * result is returned. </p></li>
- *
- * </ol>
- *
- * <p> Subsequent invocations of this method return the provider that was
- * returned by the first invocation. </p>
- *
- * @return The system-wide default AsynchronousChannel provider
- */
- public static AsynchronousChannelProvider provider() {
- return ProviderHolder.provider;
- }
-
- /**
- * Constructs a new asynchronous channel group with a fixed thread pool.
- *
- * @param nThreads
- * The number of threads in the pool
- * @param threadFactory
- * The factory to use when creating new threads
- *
- * @throws IllegalArgumentException
- * If {@code nThreads <= 0}
- * @throws IOException
- * If an I/O error occurs
- *
- * @see AsynchronousChannelGroup#withFixedThreadPool
- */
- public abstract AsynchronousChannelGroup
- openAsynchronousChannelGroup(int nThreads, ThreadFactory threadFactory) throws IOException;
-
- /**
- * Constructs a new asynchronous channel group with the given thread pool.
- *
- * @param executor
- * The thread pool
- * @param initialSize
- * A value {@code >=0} or a negative value for implementation
- * specific default
- *
- * @throws IOException
- * If an I/O error occurs
- *
- * @see AsynchronousChannelGroup#withCachedThreadPool
- */
- public abstract AsynchronousChannelGroup
- openAsynchronousChannelGroup(ExecutorService executor, int initialSize) throws IOException;
-
- /**
- * Opens an asynchronous server-socket channel.
- *
- * @param group
- * The group to which the channel is bound, or {@code null} to
- * bind to the default group
- *
- * @return The new channel
- *
- * @throws IllegalChannelGroupException
- * If the provider that created the group differs from this provider
- * @throws ShutdownChannelGroupException
- * The group is shutdown
- * @throws IOException
- * If an I/O error occurs
- */
- public abstract AsynchronousServerSocketChannel openAsynchronousServerSocketChannel
- (AsynchronousChannelGroup group) throws IOException;
-
- /**
- * Opens an asynchronous socket channel.
- *
- * @param group
- * The group to which the channel is bound, or {@code null} to
- * bind to the default group
- *
- * @return The new channel
- *
- * @throws IllegalChannelGroupException
- * If the provider that created the group differs from this provider
- * @throws ShutdownChannelGroupException
- * The group is shutdown
- * @throws IOException
- * If an I/O error occurs
- */
- public abstract AsynchronousSocketChannel openAsynchronousSocketChannel
- (AsynchronousChannelGroup group) throws IOException;
-}
diff --git a/ojluni/src/main/java/sun/nio/ch/AsynchronousChannelGroupImpl.java b/ojluni/src/main/java/sun/nio/ch/AsynchronousChannelGroupImpl.java
deleted file mode 100755
index a584ce9..0000000
--- a/ojluni/src/main/java/sun/nio/ch/AsynchronousChannelGroupImpl.java
+++ /dev/null
@@ -1,338 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.nio.ch;
-
-import java.nio.channels.Channel;
-import java.nio.channels.AsynchronousChannelGroup;
-import java.nio.channels.spi.AsynchronousChannelProvider;
-import java.io.IOException;
-import java.io.FileDescriptor;
-import java.util.Queue;
-import java.util.concurrent.*;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.security.PrivilegedAction;
-import java.security.AccessController;
-import java.security.AccessControlContext;
-import sun.security.action.GetIntegerAction;
-
-/**
- * Base implementation of AsynchronousChannelGroup
- */
-
-abstract class AsynchronousChannelGroupImpl
- extends AsynchronousChannelGroup implements Executor
-{
- // number of internal threads handling I/O events when using an unbounded
- // thread pool. Internal threads do not dispatch to completion handlers.
- private static final int internalThreadCount = AccessController.doPrivileged(
- new GetIntegerAction("sun.nio.ch.internalThreadPoolSize", 1));
-
- // associated thread pool
- private final ThreadPool pool;
-
- // number of tasks running (including internal)
- private final AtomicInteger threadCount = new AtomicInteger();
-
- // associated Executor for timeouts
- private ScheduledThreadPoolExecutor timeoutExecutor;
-
- // task queue for when using a fixed thread pool. In that case, thread
- // waiting on I/O events must be awokon to poll tasks from this queue.
- private final Queue<Runnable> taskQueue;
-
- // group shutdown
- private final AtomicBoolean shutdown = new AtomicBoolean();
- private final Object shutdownNowLock = new Object();
- private volatile boolean terminateInitiated;
-
- AsynchronousChannelGroupImpl(AsynchronousChannelProvider provider,
- ThreadPool pool)
- {
- super(provider);
- this.pool = pool;
-
- if (pool.isFixedThreadPool()) {
- taskQueue = new ConcurrentLinkedQueue<Runnable>();
- } else {
- taskQueue = null; // not used
- }
-
- // use default thread factory as thread should not be visible to
- // application (it doesn't execute completion handlers).
- this.timeoutExecutor = (ScheduledThreadPoolExecutor)
- Executors.newScheduledThreadPool(1, ThreadPool.defaultThreadFactory());
- this.timeoutExecutor.setRemoveOnCancelPolicy(true);
- }
-
- final ExecutorService executor() {
- return pool.executor();
- }
-
- final boolean isFixedThreadPool() {
- return pool.isFixedThreadPool();
- }
-
- final int fixedThreadCount() {
- if (isFixedThreadPool()) {
- return pool.poolSize();
- } else {
- return pool.poolSize() + internalThreadCount;
- }
- }
-
- private Runnable bindToGroup(final Runnable task) {
- final AsynchronousChannelGroupImpl thisGroup = this;
- return new Runnable() {
- public void run() {
- Invoker.bindToGroup(thisGroup);
- task.run();
- }
- };
- }
-
- private void startInternalThread(final Runnable task) {
- AccessController.doPrivileged(new PrivilegedAction<Void>() {
- @Override
- public Void run() {
- // internal threads should not be visible to application so
- // cannot use user-supplied thread factory
- ThreadPool.defaultThreadFactory().newThread(task).start();
- return null;
- }
- });
- }
-
- protected final void startThreads(Runnable task) {
- if (!isFixedThreadPool()) {
- for (int i=0; i<internalThreadCount; i++) {
- startInternalThread(task);
- threadCount.incrementAndGet();
- }
- }
- if (pool.poolSize() > 0) {
- task = bindToGroup(task);
- try {
- for (int i=0; i<pool.poolSize(); i++) {
- pool.executor().execute(task);
- threadCount.incrementAndGet();
- }
- } catch (RejectedExecutionException x) {
- // nothing we can do
- }
- }
- }
-
- final int threadCount() {
- return threadCount.get();
- }
-
- /**
- * Invoked by tasks as they terminate
- */
- final int threadExit(Runnable task, boolean replaceMe) {
- if (replaceMe) {
- try {
- if (Invoker.isBoundToAnyGroup()) {
- // submit new task to replace this thread
- pool.executor().execute(bindToGroup(task));
- } else {
- // replace internal thread
- startInternalThread(task);
- }
- return threadCount.get();
- } catch (RejectedExecutionException x) {
- // unable to replace
- }
- }
- return threadCount.decrementAndGet();
- }
-
- /**
- * Wakes up a thread waiting for I/O events to execute the given task.
- */
- abstract void executeOnHandlerTask(Runnable task);
-
- /**
- * For a fixed thread pool the task is queued to a thread waiting on I/O
- * events. For other thread pools we simply submit the task to the thread
- * pool.
- */
- final void executeOnPooledThread(Runnable task) {
- if (isFixedThreadPool()) {
- executeOnHandlerTask(task);
- } else {
- pool.executor().execute(bindToGroup(task));
- }
- }
-
- final void offerTask(Runnable task) {
- taskQueue.offer(task);
- }
-
- final Runnable pollTask() {
- return (taskQueue == null) ? null : taskQueue.poll();
- }
-
- final Future<?> schedule(Runnable task, long timeout, TimeUnit unit) {
- try {
- return timeoutExecutor.schedule(task, timeout, unit);
- } catch (RejectedExecutionException rej) {
- if (terminateInitiated) {
- // no timeout scheduled as group is terminating
- return null;
- }
- throw new AssertionError(rej);
- }
- }
-
- @Override
- public final boolean isShutdown() {
- return shutdown.get();
- }
-
- @Override
- public final boolean isTerminated() {
- return pool.executor().isTerminated();
- }
-
- /**
- * Returns true if there are no channels in the group
- */
- abstract boolean isEmpty();
-
- /**
- * Attaches a foreign channel to this group.
- */
- abstract Object attachForeignChannel(Channel channel, FileDescriptor fdo)
- throws IOException;
-
- /**
- * Detaches a foreign channel from this group.
- */
- abstract void detachForeignChannel(Object key);
-
- /**
- * Closes all channels in the group
- */
- abstract void closeAllChannels() throws IOException;
-
- /**
- * Shutdown all tasks waiting for I/O events.
- */
- abstract void shutdownHandlerTasks();
-
- private void shutdownExecutors() {
- AccessController.doPrivileged(new PrivilegedAction<Void>() {
- public Void run() {
- pool.executor().shutdown();
- timeoutExecutor.shutdown();
- return null;
- }
- });
- }
-
- @Override
- public final void shutdown() {
- if (shutdown.getAndSet(true)) {
- // already shutdown
- return;
- }
- // if there are channels in the group then shutdown will continue
- // when the last channel is closed
- if (!isEmpty()) {
- return;
- }
- // initiate termination (acquire shutdownNowLock to ensure that other
- // threads invoking shutdownNow will block).
- synchronized (shutdownNowLock) {
- if (!terminateInitiated) {
- terminateInitiated = true;
- shutdownHandlerTasks();
- shutdownExecutors();
- }
- }
- }
-
- @Override
- public final void shutdownNow() throws IOException {
- shutdown.set(true);
- synchronized (shutdownNowLock) {
- if (!terminateInitiated) {
- terminateInitiated = true;
- closeAllChannels();
- shutdownHandlerTasks();
- shutdownExecutors();
- }
- }
- }
-
- /**
- * For use by AsynchronousFileChannel to release resources without shutting
- * down the thread pool.
- */
- final void detachFromThreadPool() {
- if (shutdown.getAndSet(true))
- throw new AssertionError("Already shutdown");
- if (!isEmpty())
- throw new AssertionError("Group not empty");
- shutdownHandlerTasks();
- }
-
- @Override
- public final boolean awaitTermination(long timeout, TimeUnit unit)
- throws InterruptedException
- {
- return pool.executor().awaitTermination(timeout, unit);
- }
-
- /**
- * Executes the given command on one of the channel group's pooled threads.
- */
- @Override
- public final void execute(Runnable task) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- // when a security manager is installed then the user's task
- // must be run with the current calling context
- final AccessControlContext acc = AccessController.getContext();
- final Runnable delegate = task;
- task = new Runnable() {
- @Override
- public void run() {
- AccessController.doPrivileged(new PrivilegedAction<Void>() {
- @Override
- public Void run() {
- delegate.run();
- return null;
- }
- }, acc);
- }
- };
- }
- executeOnPooledThread(task);
- }
-}
diff --git a/ojluni/src/main/java/sun/nio/ch/AsynchronousServerSocketChannelImpl.java b/ojluni/src/main/java/sun/nio/ch/AsynchronousServerSocketChannelImpl.java
deleted file mode 100755
index d852b36..0000000
--- a/ojluni/src/main/java/sun/nio/ch/AsynchronousServerSocketChannelImpl.java
+++ /dev/null
@@ -1,260 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.nio.ch;
-
-import java.nio.channels.*;
-import java.net.SocketAddress;
-import java.net.SocketOption;
-import java.net.StandardSocketOptions;
-import java.net.InetSocketAddress;
-import java.io.FileDescriptor;
-import java.io.IOException;
-import java.util.Set;
-import java.util.HashSet;
-import java.util.Collections;
-import java.util.concurrent.Future;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-import sun.net.NetHooks;
-
-/**
- * Base implementation of AsynchronousServerSocketChannel.
- */
-
-abstract class AsynchronousServerSocketChannelImpl
- extends AsynchronousServerSocketChannel
- implements Cancellable, Groupable
-{
- protected final FileDescriptor fd;
-
- // the local address to which the channel's socket is bound
- protected volatile InetSocketAddress localAddress = null;
-
- // need this lock to set local address
- private final Object stateLock = new Object();
-
- // close support
- private ReadWriteLock closeLock = new ReentrantReadWriteLock();
- private volatile boolean open = true;
-
- // set true when accept operation is cancelled
- private volatile boolean acceptKilled;
-
- // set true when exclusive binding is on and SO_REUSEADDR is emulated
- private boolean isReuseAddress;
-
- AsynchronousServerSocketChannelImpl(AsynchronousChannelGroupImpl group) {
- super(group.provider());
- this.fd = Net.serverSocket(true);
- }
-
- @Override
- public final boolean isOpen() {
- return open;
- }
-
- /**
- * Marks beginning of access to file descriptor/handle
- */
- final void begin() throws IOException {
- closeLock.readLock().lock();
- if (!isOpen())
- throw new ClosedChannelException();
- }
-
- /**
- * Marks end of access to file descriptor/handle
- */
- final void end() {
- closeLock.readLock().unlock();
- }
-
- /**
- * Invoked to close file descriptor/handle.
- */
- abstract void implClose() throws IOException;
-
- @Override
- public final void close() throws IOException {
- // synchronize with any threads using file descriptor/handle
- closeLock.writeLock().lock();
- try {
- if (!open)
- return; // already closed
- open = false;
- } finally {
- closeLock.writeLock().unlock();
- }
- implClose();
- }
-
- /**
- * Invoked by accept to accept connection
- */
- abstract Future<AsynchronousSocketChannel>
- implAccept(Object attachment,
- CompletionHandler<AsynchronousSocketChannel,Object> handler);
-
-
- @Override
- public final Future<AsynchronousSocketChannel> accept() {
- return implAccept(null, null);
- }
-
- @Override
- @SuppressWarnings("unchecked")
- public final <A> void accept(A attachment,
- CompletionHandler<AsynchronousSocketChannel,? super A> handler)
- {
- if (handler == null)
- throw new NullPointerException("'handler' is null");
- implAccept(attachment, (CompletionHandler<AsynchronousSocketChannel,Object>)handler);
- }
-
- final boolean isAcceptKilled() {
- return acceptKilled;
- }
-
- @Override
- public final void onCancel(PendingFuture<?,?> task) {
- acceptKilled = true;
- }
-
- @Override
- public final AsynchronousServerSocketChannel bind(SocketAddress local, int backlog)
- throws IOException
- {
- InetSocketAddress isa = (local == null) ? new InetSocketAddress(0) :
- Net.checkAddress(local);
- SecurityManager sm = System.getSecurityManager();
- if (sm != null)
- sm.checkListen(isa.getPort());
-
- try {
- begin();
- synchronized (stateLock) {
- if (localAddress != null)
- throw new AlreadyBoundException();
- NetHooks.beforeTcpBind(fd, isa.getAddress(), isa.getPort());
- Net.bind(fd, isa.getAddress(), isa.getPort());
- Net.listen(fd, backlog < 1 ? 50 : backlog);
- localAddress = Net.localAddress(fd);
- }
- } finally {
- end();
- }
- return this;
- }
-
- @Override
- public final SocketAddress getLocalAddress() throws IOException {
- if (!isOpen())
- throw new ClosedChannelException();
- return Net.getRevealedLocalAddress(localAddress);
- }
-
- @Override
- public final <T> AsynchronousServerSocketChannel setOption(SocketOption<T> name,
- T value)
- throws IOException
- {
- if (name == null)
- throw new NullPointerException();
- if (!supportedOptions().contains(name))
- throw new UnsupportedOperationException("'" + name + "' not supported");
-
- try {
- begin();
- if (name == StandardSocketOptions.SO_REUSEADDR &&
- Net.useExclusiveBind())
- {
- // SO_REUSEADDR emulated when using exclusive bind
- isReuseAddress = (Boolean)value;
- } else {
- Net.setSocketOption(fd, Net.UNSPEC, name, value);
- }
- return this;
- } finally {
- end();
- }
- }
-
- @Override
- @SuppressWarnings("unchecked")
- public final <T> T getOption(SocketOption<T> name) throws IOException {
- if (name == null)
- throw new NullPointerException();
- if (!supportedOptions().contains(name))
- throw new UnsupportedOperationException("'" + name + "' not supported");
-
- try {
- begin();
- if (name == StandardSocketOptions.SO_REUSEADDR &&
- Net.useExclusiveBind())
- {
- // SO_REUSEADDR emulated when using exclusive bind
- return (T)Boolean.valueOf(isReuseAddress);
- }
- return (T) Net.getSocketOption(fd, Net.UNSPEC, name);
- } finally {
- end();
- }
- }
-
- private static class DefaultOptionsHolder {
- static final Set<SocketOption<?>> defaultOptions = defaultOptions();
-
- private static Set<SocketOption<?>> defaultOptions() {
- HashSet<SocketOption<?>> set = new HashSet<SocketOption<?>>(2);
- set.add(StandardSocketOptions.SO_RCVBUF);
- set.add(StandardSocketOptions.SO_REUSEADDR);
- return Collections.unmodifiableSet(set);
- }
- }
-
- @Override
- public final Set<SocketOption<?>> supportedOptions() {
- return DefaultOptionsHolder.defaultOptions;
- }
-
- @Override
- public final String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append(this.getClass().getName());
- sb.append('[');
- if (!isOpen())
- sb.append("closed");
- else {
- if (localAddress == null) {
- sb.append("unbound");
- } else {
- sb.append(Net.getRevealedLocalAddressAsString(localAddress));
- }
- }
- sb.append(']');
- return sb.toString();
- }
-}
diff --git a/ojluni/src/main/java/sun/nio/ch/AsynchronousSocketChannelImpl.java b/ojluni/src/main/java/sun/nio/ch/AsynchronousSocketChannelImpl.java
deleted file mode 100755
index af20709..0000000
--- a/ojluni/src/main/java/sun/nio/ch/AsynchronousSocketChannelImpl.java
+++ /dev/null
@@ -1,597 +0,0 @@
-/*
- * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.nio.ch;
-
-import java.nio.ByteBuffer;
-import java.nio.channels.*;
-import java.net.SocketOption;
-import java.net.StandardSocketOptions;
-import java.net.SocketAddress;
-import java.net.InetSocketAddress;
-import java.io.IOException;
-import java.io.FileDescriptor;
-import java.util.Set;
-import java.util.HashSet;
-import java.util.Collections;
-import java.util.concurrent.*;
-import java.util.concurrent.locks.*;
-import sun.net.NetHooks;
-
-/**
- * Base implementation of AsynchronousSocketChannel
- */
-
-abstract class AsynchronousSocketChannelImpl
- extends AsynchronousSocketChannel
- implements Cancellable, Groupable
-{
- protected final FileDescriptor fd;
-
- // protects state, localAddress, and remoteAddress
- protected final Object stateLock = new Object();
-
- protected volatile InetSocketAddress localAddress = null;
- protected volatile InetSocketAddress remoteAddress = null;
-
- // State, increases monotonically
- static final int ST_UNINITIALIZED = -1;
- static final int ST_UNCONNECTED = 0;
- static final int ST_PENDING = 1;
- static final int ST_CONNECTED = 2;
- protected volatile int state = ST_UNINITIALIZED;
-
- // reading state
- private final Object readLock = new Object();
- private boolean reading;
- private boolean readShutdown;
- private boolean readKilled; // further reading disallowed due to timeout
-
- // writing state
- private final Object writeLock = new Object();
- private boolean writing;
- private boolean writeShutdown;
- private boolean writeKilled; // further writing disallowed due to timeout
-
- // close support
- private final ReadWriteLock closeLock = new ReentrantReadWriteLock();
- private volatile boolean open = true;
-
- // set true when exclusive binding is on and SO_REUSEADDR is emulated
- private boolean isReuseAddress;
-
- AsynchronousSocketChannelImpl(AsynchronousChannelGroupImpl group)
- throws IOException
- {
- super(group.provider());
- this.fd = Net.socket(true);
- this.state = ST_UNCONNECTED;
- }
-
- // Constructor for sockets obtained from AsynchronousServerSocketChannelImpl
- AsynchronousSocketChannelImpl(AsynchronousChannelGroupImpl group,
- FileDescriptor fd,
- InetSocketAddress remote)
- throws IOException
- {
- super(group.provider());
- this.fd = fd;
- this.state = ST_CONNECTED;
- this.localAddress = Net.localAddress(fd);
- this.remoteAddress = remote;
- }
-
- @Override
- public final boolean isOpen() {
- return open;
- }
-
- /**
- * Marks beginning of access to file descriptor/handle
- */
- final void begin() throws IOException {
- closeLock.readLock().lock();
- if (!isOpen())
- throw new ClosedChannelException();
- }
-
- /**
- * Marks end of access to file descriptor/handle
- */
- final void end() {
- closeLock.readLock().unlock();
- }
-
- /**
- * Invoked to close socket and release other resources.
- */
- abstract void implClose() throws IOException;
-
- @Override
- public final void close() throws IOException {
- // synchronize with any threads initiating asynchronous operations
- closeLock.writeLock().lock();
- try {
- if (!open)
- return; // already closed
- open = false;
- } finally {
- closeLock.writeLock().unlock();
- }
- implClose();
- }
-
- final void enableReading(boolean killed) {
- synchronized (readLock) {
- reading = false;
- if (killed)
- readKilled = true;
- }
- }
-
- final void enableReading() {
- enableReading(false);
- }
-
- final void enableWriting(boolean killed) {
- synchronized (writeLock) {
- writing = false;
- if (killed)
- writeKilled = true;
- }
- }
-
- final void enableWriting() {
- enableWriting(false);
- }
-
- final void killReading() {
- synchronized (readLock) {
- readKilled = true;
- }
- }
-
- final void killWriting() {
- synchronized (writeLock) {
- writeKilled = true;
- }
- }
-
- final void killConnect() {
- // when a connect is cancelled then the connection may have been
- // established so prevent reading or writing.
- killReading();
- killWriting();
- }
-
- /**
- * Invoked by connect to initiate the connect operation.
- */
- abstract <A> Future<Void> implConnect(SocketAddress remote,
- A attachment,
- CompletionHandler<Void,? super A> handler);
-
- @Override
- public final Future<Void> connect(SocketAddress remote) {
- return implConnect(remote, null, null);
- }
-
- @Override
- public final <A> void connect(SocketAddress remote,
- A attachment,
- CompletionHandler<Void,? super A> handler)
- {
- if (handler == null)
- throw new NullPointerException("'handler' is null");
- implConnect(remote, attachment, handler);
- }
-
- /**
- * Invoked by read to initiate the I/O operation.
- */
- abstract <V extends Number,A> Future<V> implRead(boolean isScatteringRead,
- ByteBuffer dst,
- ByteBuffer[] dsts,
- long timeout,
- TimeUnit unit,
- A attachment,
- CompletionHandler<V,? super A> handler);
-
- @SuppressWarnings("unchecked")
- private <V extends Number,A> Future<V> read(boolean isScatteringRead,
- ByteBuffer dst,
- ByteBuffer[] dsts,
- long timeout,
- TimeUnit unit,
- A att,
- CompletionHandler<V,? super A> handler)
- {
- if (!isOpen()) {
- Throwable e = new ClosedChannelException();
- if (handler == null)
- return CompletedFuture.withFailure(e);
- Invoker.invoke(this, handler, att, null, e);
- return null;
- }
-
- if (remoteAddress == null)
- throw new NotYetConnectedException();
-
- boolean hasSpaceToRead = isScatteringRead || dst.hasRemaining();
- boolean shutdown = false;
-
- // check and update state
- synchronized (readLock) {
- if (readKilled)
- throw new IllegalStateException("Reading not allowed due to timeout or cancellation");
- if (reading)
- throw new ReadPendingException();
- if (readShutdown) {
- shutdown = true;
- } else {
- if (hasSpaceToRead) {
- reading = true;
- }
- }
- }
-
- // immediately complete with -1 if shutdown for read
- // immediately complete with 0 if no space remaining
- if (shutdown || !hasSpaceToRead) {
- Number result;
- if (isScatteringRead) {
- result = (shutdown) ? Long.valueOf(-1L) : Long.valueOf(0L);
- } else {
- result = (shutdown) ? -1 : 0;
- }
- if (handler == null)
- return CompletedFuture.withResult((V)result);
- Invoker.invoke(this, handler, att, (V)result, null);
- return null;
- }
-
- return implRead(isScatteringRead, dst, dsts, timeout, unit, att, handler);
- }
-
- @Override
- public final Future<Integer> read(ByteBuffer dst) {
- if (dst.isReadOnly())
- throw new IllegalArgumentException("Read-only buffer");
- return read(false, dst, null, 0L, TimeUnit.MILLISECONDS, null, null);
- }
-
- @Override
- public final <A> void read(ByteBuffer dst,
- long timeout,
- TimeUnit unit,
- A attachment,
- CompletionHandler<Integer,? super A> handler)
- {
- if (handler == null)
- throw new NullPointerException("'handler' is null");
- if (dst.isReadOnly())
- throw new IllegalArgumentException("Read-only buffer");
- read(false, dst, null, timeout, unit, attachment, handler);
- }
-
- @Override
- public final <A> void read(ByteBuffer[] dsts,
- int offset,
- int length,
- long timeout,
- TimeUnit unit,
- A attachment,
- CompletionHandler<Long,? super A> handler)
- {
- if (handler == null)
- throw new NullPointerException("'handler' is null");
- if ((offset < 0) || (length < 0) || (offset > dsts.length - length))
- throw new IndexOutOfBoundsException();
- ByteBuffer[] bufs = Util.subsequence(dsts, offset, length);
- for (int i=0; i<bufs.length; i++) {
- if (bufs[i].isReadOnly())
- throw new IllegalArgumentException("Read-only buffer");
- }
- read(true, null, bufs, timeout, unit, attachment, handler);
- }
-
- /**
- * Invoked by write to initiate the I/O operation.
- */
- abstract <V extends Number,A> Future<V> implWrite(boolean isGatheringWrite,
- ByteBuffer src,
- ByteBuffer[] srcs,
- long timeout,
- TimeUnit unit,
- A attachment,
- CompletionHandler<V,? super A> handler);
-
- @SuppressWarnings("unchecked")
- private <V extends Number,A> Future<V> write(boolean isGatheringWrite,
- ByteBuffer src,
- ByteBuffer[] srcs,
- long timeout,
- TimeUnit unit,
- A att,
- CompletionHandler<V,? super A> handler)
- {
- boolean hasDataToWrite = isGatheringWrite || src.hasRemaining();
-
- boolean closed = false;
- if (isOpen()) {
- if (remoteAddress == null)
- throw new NotYetConnectedException();
- // check and update state
- synchronized (writeLock) {
- if (writeKilled)
- throw new IllegalStateException("Writing not allowed due to timeout or cancellation");
- if (writing)
- throw new WritePendingException();
- if (writeShutdown) {
- closed = true;
- } else {
- if (hasDataToWrite)
- writing = true;
- }
- }
- } else {
- closed = true;
- }
-
- // channel is closed or shutdown for write
- if (closed) {
- Throwable e = new ClosedChannelException();
- if (handler == null)
- return CompletedFuture.withFailure(e);
- Invoker.invoke(this, handler, att, null, e);
- return null;
- }
-
- // nothing to write so complete immediately
- if (!hasDataToWrite) {
- Number result = (isGatheringWrite) ? (Number)0L : (Number)0;
- if (handler == null)
- return CompletedFuture.withResult((V)result);
- Invoker.invoke(this, handler, att, (V)result, null);
- return null;
- }
-
- return implWrite(isGatheringWrite, src, srcs, timeout, unit, att, handler);
- }
-
- @Override
- public final Future<Integer> write(ByteBuffer src) {
- return write(false, src, null, 0L, TimeUnit.MILLISECONDS, null, null);
- }
-
- @Override
- public final <A> void write(ByteBuffer src,
- long timeout,
- TimeUnit unit,
- A attachment,
- CompletionHandler<Integer,? super A> handler)
- {
- if (handler == null)
- throw new NullPointerException("'handler' is null");
- write(false, src, null, timeout, unit, attachment, handler);
- }
-
- @Override
- public final <A> void write(ByteBuffer[] srcs,
- int offset,
- int length,
- long timeout,
- TimeUnit unit,
- A attachment,
- CompletionHandler<Long,? super A> handler)
- {
- if (handler == null)
- throw new NullPointerException("'handler' is null");
- if ((offset < 0) || (length < 0) || (offset > srcs.length - length))
- throw new IndexOutOfBoundsException();
- srcs = Util.subsequence(srcs, offset, length);
- write(true, null, srcs, timeout, unit, attachment, handler);
- }
-
- @Override
- public final AsynchronousSocketChannel bind(SocketAddress local)
- throws IOException
- {
- try {
- begin();
- synchronized (stateLock) {
- if (state == ST_PENDING)
- throw new ConnectionPendingException();
- if (localAddress != null)
- throw new AlreadyBoundException();
- InetSocketAddress isa = (local == null) ?
- new InetSocketAddress(0) : Net.checkAddress(local);
- NetHooks.beforeTcpBind(fd, isa.getAddress(), isa.getPort());
- Net.bind(fd, isa.getAddress(), isa.getPort());
- localAddress = Net.localAddress(fd);
- }
- } finally {
- end();
- }
- return this;
- }
-
- @Override
- public final SocketAddress getLocalAddress() throws IOException {
- if (!isOpen())
- throw new ClosedChannelException();
- return Net.getRevealedLocalAddress(localAddress);
- }
-
- @Override
- public final <T> AsynchronousSocketChannel setOption(SocketOption<T> name, T value)
- throws IOException
- {
- if (name == null)
- throw new NullPointerException();
- if (!supportedOptions().contains(name))
- throw new UnsupportedOperationException("'" + name + "' not supported");
-
- try {
- begin();
- if (writeShutdown)
- throw new IOException("Connection has been shutdown for writing");
- if (name == StandardSocketOptions.SO_REUSEADDR &&
- Net.useExclusiveBind())
- {
- // SO_REUSEADDR emulated when using exclusive bind
- isReuseAddress = (Boolean)value;
- } else {
- Net.setSocketOption(fd, Net.UNSPEC, name, value);
- }
- return this;
- } finally {
- end();
- }
- }
-
- @Override
- @SuppressWarnings("unchecked")
- public final <T> T getOption(SocketOption<T> name) throws IOException {
- if (name == null)
- throw new NullPointerException();
- if (!supportedOptions().contains(name))
- throw new UnsupportedOperationException("'" + name + "' not supported");
-
- try {
- begin();
- if (name == StandardSocketOptions.SO_REUSEADDR &&
- Net.useExclusiveBind())
- {
- // SO_REUSEADDR emulated when using exclusive bind
- return (T)Boolean.valueOf(isReuseAddress);
- }
- return (T) Net.getSocketOption(fd, Net.UNSPEC, name);
- } finally {
- end();
- }
- }
-
- private static class DefaultOptionsHolder {
- static final Set<SocketOption<?>> defaultOptions = defaultOptions();
-
- private static Set<SocketOption<?>> defaultOptions() {
- HashSet<SocketOption<?>> set = new HashSet<SocketOption<?>>(5);
- set.add(StandardSocketOptions.SO_SNDBUF);
- set.add(StandardSocketOptions.SO_RCVBUF);
- set.add(StandardSocketOptions.SO_KEEPALIVE);
- set.add(StandardSocketOptions.SO_REUSEADDR);
- set.add(StandardSocketOptions.TCP_NODELAY);
- return Collections.unmodifiableSet(set);
- }
- }
-
- @Override
- public final Set<SocketOption<?>> supportedOptions() {
- return DefaultOptionsHolder.defaultOptions;
- }
-
- @Override
- public final SocketAddress getRemoteAddress() throws IOException {
- if (!isOpen())
- throw new ClosedChannelException();
- return remoteAddress;
- }
-
- @Override
- public final AsynchronousSocketChannel shutdownInput() throws IOException {
- try {
- begin();
- if (remoteAddress == null)
- throw new NotYetConnectedException();
- synchronized (readLock) {
- if (!readShutdown) {
- Net.shutdown(fd, Net.SHUT_RD);
- readShutdown = true;
- }
- }
- } finally {
- end();
- }
- return this;
- }
-
- @Override
- public final AsynchronousSocketChannel shutdownOutput() throws IOException {
- try {
- begin();
- if (remoteAddress == null)
- throw new NotYetConnectedException();
- synchronized (writeLock) {
- if (!writeShutdown) {
- Net.shutdown(fd, Net.SHUT_WR);
- writeShutdown = true;
- }
- }
- } finally {
- end();
- }
- return this;
- }
-
- @Override
- public final String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append(this.getClass().getName());
- sb.append('[');
- synchronized (stateLock) {
- if (!isOpen()) {
- sb.append("closed");
- } else {
- switch (state) {
- case ST_UNCONNECTED:
- sb.append("unconnected");
- break;
- case ST_PENDING:
- sb.append("connection-pending");
- break;
- case ST_CONNECTED:
- sb.append("connected");
- if (readShutdown)
- sb.append(" ishut");
- if (writeShutdown)
- sb.append(" oshut");
- break;
- }
- if (localAddress != null) {
- sb.append(" local=");
- sb.append(
- Net.getRevealedLocalAddressAsString(localAddress));
- }
- if (remoteAddress != null) {
- sb.append(" remote=");
- sb.append(remoteAddress.toString());
- }
- }
- }
- sb.append(']');
- return sb.toString();
- }
-}
diff --git a/ojluni/src/main/java/sun/nio/ch/BsdAsynchronousChannelProvider.java b/ojluni/src/main/java/sun/nio/ch/BsdAsynchronousChannelProvider.java
deleted file mode 100755
index a732c11..0000000
--- a/ojluni/src/main/java/sun/nio/ch/BsdAsynchronousChannelProvider.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.nio.ch;
-
-import java.nio.channels.*;
-import java.nio.channels.spi.AsynchronousChannelProvider;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.ThreadFactory;
-import java.io.IOException;
-
-public class BsdAsynchronousChannelProvider
- extends AsynchronousChannelProvider
-{
- private static volatile KQueuePort defaultPort;
-
- private KQueuePort defaultEventPort() throws IOException {
- if (defaultPort == null) {
- synchronized (BsdAsynchronousChannelProvider.class) {
- if (defaultPort == null) {
- defaultPort = new KQueuePort(this, ThreadPool.getDefault()).start();
- }
- }
- }
- return defaultPort;
- }
-
- public BsdAsynchronousChannelProvider() {
- }
-
- @Override
- public AsynchronousChannelGroup openAsynchronousChannelGroup(int nThreads, ThreadFactory factory)
- throws IOException
- {
- return new KQueuePort(this, ThreadPool.create(nThreads, factory)).start();
- }
-
- @Override
- public AsynchronousChannelGroup openAsynchronousChannelGroup(ExecutorService executor, int initialSize)
- throws IOException
- {
- return new KQueuePort(this, ThreadPool.wrap(executor, initialSize)).start();
- }
-
- private Port toPort(AsynchronousChannelGroup group) throws IOException {
- if (group == null) {
- return defaultEventPort();
- } else {
- if (!(group instanceof KQueuePort))
- throw new IllegalChannelGroupException();
- return (Port)group;
- }
- }
-
- @Override
- public AsynchronousServerSocketChannel openAsynchronousServerSocketChannel(AsynchronousChannelGroup group)
- throws IOException
- {
- return new UnixAsynchronousServerSocketChannelImpl(toPort(group));
- }
-
- @Override
- public AsynchronousSocketChannel openAsynchronousSocketChannel(AsynchronousChannelGroup group)
- throws IOException
- {
- return new UnixAsynchronousSocketChannelImpl(toPort(group));
- }
-}
diff --git a/ojluni/src/main/java/sun/nio/ch/Cancellable.java b/ojluni/src/main/java/sun/nio/ch/Cancellable.java
deleted file mode 100755
index 9a84a63..0000000
--- a/ojluni/src/main/java/sun/nio/ch/Cancellable.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.nio.ch;
-
-/**
- * Implemented by asynchronous channels that require notification when an I/O
- * operation is cancelled.
- */
-
-interface Cancellable {
- /**
- * Invoked to notify channel that cancel has been invoked while holding
- * the Future's lock.
- */
- void onCancel(PendingFuture<?,?> task);
-}
diff --git a/ojluni/src/main/java/sun/nio/ch/DatagramChannelImpl.java b/ojluni/src/main/java/sun/nio/ch/DatagramChannelImpl.java
index e4d24a5..7da4bc86 100755
--- a/ojluni/src/main/java/sun/nio/ch/DatagramChannelImpl.java
+++ b/ojluni/src/main/java/sun/nio/ch/DatagramChannelImpl.java
@@ -96,9 +96,6 @@
// Our socket adaptor, if any
private DatagramSocket socket;
- // Multicast support
- private MembershipRegistry registry;
-
// set true when socket is bound and SO_REUSEADDRESS is emulated
private boolean reuseAddressEmulated;
@@ -168,7 +165,6 @@
}
}
- @Override
public SocketAddress getLocalAddress() throws IOException {
synchronized (stateLock) {
if (!isOpen())
@@ -246,7 +242,6 @@
}
}
- @Override
@SuppressWarnings("unchecked")
public <T> T getOption(SocketOption<T> name)
throws IOException
@@ -325,7 +320,6 @@
}
}
- @Override
public final Set<SocketOption<?>> supportedOptions() {
return DefaultOptionsHolder.defaultOptions;
}
@@ -793,228 +787,12 @@
return this;
}
- /**
- * Joins channel's socket to the given group/interface and
- * optional source address.
- */
- private MembershipKey innerJoin(InetAddress group,
- NetworkInterface interf,
- InetAddress source)
- throws IOException
- {
- if (!group.isMulticastAddress())
- throw new IllegalArgumentException("Group not a multicast address");
-
- // check multicast address is compatible with this socket
- if (group instanceof Inet4Address) {
- if (family == StandardProtocolFamily.INET6 && !Net.canIPv6SocketJoinIPv4Group())
- throw new IllegalArgumentException("IPv6 socket cannot join IPv4 multicast group");
- } else if (group instanceof Inet6Address) {
- if (family != StandardProtocolFamily.INET6)
- throw new IllegalArgumentException("Only IPv6 sockets can join IPv6 multicast group");
- } else {
- throw new IllegalArgumentException("Address type not supported");
- }
-
- // check source address
- if (source != null) {
- if (source.isAnyLocalAddress())
- throw new IllegalArgumentException("Source address is a wildcard address");
- if (source.isMulticastAddress())
- throw new IllegalArgumentException("Source address is multicast address");
- if (source.getClass() != group.getClass())
- throw new IllegalArgumentException("Source address is different type to group");
- }
-
- SecurityManager sm = System.getSecurityManager();
- if (sm != null)
- sm.checkMulticast(group);
-
- synchronized (stateLock) {
- if (!isOpen())
- throw new ClosedChannelException();
-
- // check the registry to see if we are already a member of the group
- if (registry == null) {
- registry = new MembershipRegistry();
- } else {
- // return existing membership key
- MembershipKey key = registry.checkMembership(group, interf, source);
- if (key != null)
- return key;
- }
-
- MembershipKeyImpl key;
- if ((family == StandardProtocolFamily.INET6) &&
- ((group instanceof Inet6Address) || Net.canJoin6WithIPv4Group()))
- {
- int index = interf.getIndex();
- if (index == -1)
- throw new IOException("Network interface cannot be identified");
-
- // need multicast and source address as byte arrays
- byte[] groupAddress = Net.inet6AsByteArray(group);
- byte[] sourceAddress = (source == null) ? null :
- Net.inet6AsByteArray(source);
-
- // join the group
- int n = Net.join6(fd, groupAddress, index, sourceAddress);
- if (n == IOStatus.UNAVAILABLE)
- throw new UnsupportedOperationException();
-
- key = new MembershipKeyImpl.Type6(this, group, interf, source,
- groupAddress, index, sourceAddress);
-
- } else {
- // need IPv4 address to identify interface
- Inet4Address target = Net.anyInet4Address(interf);
- if (target == null)
- throw new IOException("Network interface not configured for IPv4");
-
- int groupAddress = Net.inet4AsInt(group);
- int targetAddress = Net.inet4AsInt(target);
- int sourceAddress = (source == null) ? 0 : Net.inet4AsInt(source);
-
- // join the group
- int n = Net.join4(fd, groupAddress, targetAddress, sourceAddress);
- if (n == IOStatus.UNAVAILABLE)
- throw new UnsupportedOperationException();
-
- key = new MembershipKeyImpl.Type4(this, group, interf, source,
- groupAddress, targetAddress, sourceAddress);
- }
-
- registry.add(key);
- return key;
- }
- }
-
- @Override
- public MembershipKey join(InetAddress group,
- NetworkInterface interf)
- throws IOException
- {
- return innerJoin(group, interf, null);
- }
-
- @Override
- public MembershipKey join(InetAddress group,
- NetworkInterface interf,
- InetAddress source)
- throws IOException
- {
- if (source == null)
- throw new NullPointerException("source address is null");
- return innerJoin(group, interf, source);
- }
-
- // package-private
- void drop(MembershipKeyImpl key) {
- assert key.channel() == this;
-
- synchronized (stateLock) {
- if (!key.isValid())
- return;
-
- try {
- if (key instanceof MembershipKeyImpl.Type6) {
- MembershipKeyImpl.Type6 key6 =
- (MembershipKeyImpl.Type6)key;
- Net.drop6(fd, key6.groupAddress(), key6.index(), key6.source());
- } else {
- MembershipKeyImpl.Type4 key4 = (MembershipKeyImpl.Type4)key;
- Net.drop4(fd, key4.groupAddress(), key4.interfaceAddress(),
- key4.source());
- }
- } catch (IOException ioe) {
- // should not happen
- throw new AssertionError(ioe);
- }
-
- key.invalidate();
- registry.remove(key);
- }
- }
-
- /**
- * Block datagrams from given source if a memory to receive all
- * datagrams.
- */
- void block(MembershipKeyImpl key, InetAddress source)
- throws IOException
- {
- assert key.channel() == this;
- assert key.sourceAddress() == null;
-
- synchronized (stateLock) {
- if (!key.isValid())
- throw new IllegalStateException("key is no longer valid");
- if (source.isAnyLocalAddress())
- throw new IllegalArgumentException("Source address is a wildcard address");
- if (source.isMulticastAddress())
- throw new IllegalArgumentException("Source address is multicast address");
- if (source.getClass() != key.group().getClass())
- throw new IllegalArgumentException("Source address is different type to group");
-
- int n;
- if (key instanceof MembershipKeyImpl.Type6) {
- MembershipKeyImpl.Type6 key6 =
- (MembershipKeyImpl.Type6)key;
- n = Net.block6(fd, key6.groupAddress(), key6.index(),
- Net.inet6AsByteArray(source));
- } else {
- MembershipKeyImpl.Type4 key4 =
- (MembershipKeyImpl.Type4)key;
- n = Net.block4(fd, key4.groupAddress(), key4.interfaceAddress(),
- Net.inet4AsInt(source));
- }
- if (n == IOStatus.UNAVAILABLE) {
- // ancient kernel
- throw new UnsupportedOperationException();
- }
- }
- }
-
- /**
- * Unblock given source.
- */
- void unblock(MembershipKeyImpl key, InetAddress source) {
- assert key.channel() == this;
- assert key.sourceAddress() == null;
-
- synchronized (stateLock) {
- if (!key.isValid())
- throw new IllegalStateException("key is no longer valid");
-
- try {
- if (key instanceof MembershipKeyImpl.Type6) {
- MembershipKeyImpl.Type6 key6 =
- (MembershipKeyImpl.Type6)key;
- Net.unblock6(fd, key6.groupAddress(), key6.index(),
- Net.inet6AsByteArray(source));
- } else {
- MembershipKeyImpl.Type4 key4 =
- (MembershipKeyImpl.Type4)key;
- Net.unblock4(fd, key4.groupAddress(), key4.interfaceAddress(),
- Net.inet4AsInt(source));
- }
- } catch (IOException ioe) {
- // should not happen
- throw new AssertionError(ioe);
- }
- }
- }
-
protected void implCloseSelectableChannel() throws IOException {
synchronized (stateLock) {
if (state != ST_KILLED)
nd.preClose(fd);
ResourceManager.afterUdpClose();
- // if member of mulitcast group then invalidate all keys
- if (registry != null)
- registry.invalidateAll();
-
long th;
if ((th = readerThread) != 0)
NativeThread.signal(th);
diff --git a/ojluni/src/main/java/sun/nio/ch/DefaultAsynchronousChannelProvider.java b/ojluni/src/main/java/sun/nio/ch/DefaultAsynchronousChannelProvider.java
deleted file mode 100755
index 38dd74f..0000000
--- a/ojluni/src/main/java/sun/nio/ch/DefaultAsynchronousChannelProvider.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.nio.ch;
-
-import java.nio.channels.spi.AsynchronousChannelProvider;
-import java.security.AccessController;
-import sun.security.action.GetPropertyAction;
-
-/**
- * Creates this platform's default asynchronous channel provider
- */
-
-public class DefaultAsynchronousChannelProvider {
-
- /**
- * Prevent instantiation.
- */
- private DefaultAsynchronousChannelProvider() { }
-
- /**
- * Returns the default AsynchronousChannelProvider.
- */
- public static AsynchronousChannelProvider create() {
- String osname = AccessController
- .doPrivileged(new GetPropertyAction("os.name"));
- // Android-changed: We don't compile SolarisAsynchronousChannelProvider.
- //
- // if (osname.equals("SunOS"))
- // return new SolarisAsynchronousChannelProvider();
- if (osname.equals("Linux"))
- return new LinuxAsynchronousChannelProvider();
- if (osname.contains("OS X"))
- return new BsdAsynchronousChannelProvider();
- throw new InternalError("platform not recognized");
- }
-
-}
diff --git a/ojluni/src/main/java/sun/nio/ch/EPollPort.java b/ojluni/src/main/java/sun/nio/ch/EPollPort.java
deleted file mode 100755
index 6b496ca..0000000
--- a/ojluni/src/main/java/sun/nio/ch/EPollPort.java
+++ /dev/null
@@ -1,323 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.nio.ch;
-
-import java.nio.channels.spi.AsynchronousChannelProvider;
-import java.io.IOException;
-import java.util.concurrent.ArrayBlockingQueue;
-import java.util.concurrent.RejectedExecutionException;
-import java.util.concurrent.atomic.AtomicInteger;
-import static sun.nio.ch.EPoll.*;
-
-/**
- * AsynchronousChannelGroup implementation based on the Linux epoll facility.
- */
-
-final class EPollPort
- extends Port
-{
- // maximum number of events to poll at a time
- private static final int MAX_EPOLL_EVENTS = 512;
-
- // errors
- private static final int ENOENT = 2;
-
- // epoll file descriptor
- private final int epfd;
-
- // true if epoll closed
- private boolean closed;
-
- // socket pair used for wakeup
- private final int sp[];
-
- // number of wakeups pending
- private final AtomicInteger wakeupCount = new AtomicInteger();
-
- // address of the poll array passed to epoll_wait
- private final long address;
-
- // encapsulates an event for a channel
- static class Event {
- final PollableChannel channel;
- final int events;
-
- Event(PollableChannel channel, int events) {
- this.channel = channel;
- this.events = events;
- }
-
- PollableChannel channel() { return channel; }
- int events() { return events; }
- }
-
- // queue of events for cases that a polling thread dequeues more than one
- // event
- private final ArrayBlockingQueue<Event> queue;
- private final Event NEED_TO_POLL = new Event(null, 0);
- private final Event EXECUTE_TASK_OR_SHUTDOWN = new Event(null, 0);
-
- EPollPort(AsynchronousChannelProvider provider, ThreadPool pool)
- throws IOException
- {
- super(provider, pool);
-
- // open epoll
- this.epfd = epollCreate();
-
- // create socket pair for wakeup mechanism
- int[] sv = new int[2];
- try {
- socketpair(sv);
- // register one end with epoll
- epollCtl(epfd, EPOLL_CTL_ADD, sv[0], POLLIN);
- } catch (IOException x) {
- close0(epfd);
- throw x;
- }
- this.sp = sv;
-
- // allocate the poll array
- this.address = allocatePollArray(MAX_EPOLL_EVENTS);
-
- // create the queue and offer the special event to ensure that the first
- // threads polls
- this.queue = new ArrayBlockingQueue<Event>(MAX_EPOLL_EVENTS);
- this.queue.offer(NEED_TO_POLL);
- }
-
- EPollPort start() {
- startThreads(new EventHandlerTask());
- return this;
- }
-
- /**
- * Release all resources
- */
- private void implClose() {
- synchronized (this) {
- if (closed)
- return;
- closed = true;
- }
- freePollArray(address);
- close0(sp[0]);
- close0(sp[1]);
- close0(epfd);
- }
-
- private void wakeup() {
- if (wakeupCount.incrementAndGet() == 1) {
- // write byte to socketpair to force wakeup
- try {
- interrupt(sp[1]);
- } catch (IOException x) {
- throw new AssertionError(x);
- }
- }
- }
-
- @Override
- void executeOnHandlerTask(Runnable task) {
- synchronized (this) {
- if (closed)
- throw new RejectedExecutionException();
- offerTask(task);
- wakeup();
- }
- }
-
- @Override
- void shutdownHandlerTasks() {
- /*
- * If no tasks are running then just release resources; otherwise
- * write to the one end of the socketpair to wakeup any polling threads.
- */
- int nThreads = threadCount();
- if (nThreads == 0) {
- implClose();
- } else {
- // send interrupt to each thread
- while (nThreads-- > 0) {
- wakeup();
- }
- }
- }
-
- // invoke by clients to register a file descriptor
- @Override
- void startPoll(int fd, int events) {
- // update events (or add to epoll on first usage)
- int err = epollCtl(epfd, EPOLL_CTL_MOD, fd, (events | EPOLLONESHOT));
- if (err == ENOENT)
- err = epollCtl(epfd, EPOLL_CTL_ADD, fd, (events | EPOLLONESHOT));
- if (err != 0)
- throw new AssertionError(); // should not happen
- }
-
- /*
- * Task to process events from epoll and dispatch to the channel's
- * onEvent handler.
- *
- * Events are retreived from epoll in batch and offered to a BlockingQueue
- * where they are consumed by handler threads. A special "NEED_TO_POLL"
- * event is used to signal one consumer to re-poll when all events have
- * been consumed.
- */
- private class EventHandlerTask implements Runnable {
- private Event poll() throws IOException {
- try {
- for (;;) {
- int n = epollWait(epfd, address, MAX_EPOLL_EVENTS);
- /*
- * 'n' events have been read. Here we map them to their
- * corresponding channel in batch and queue n-1 so that
- * they can be handled by other handler threads. The last
- * event is handled by this thread (and so is not queued).
- */
- fdToChannelLock.readLock().lock();
- try {
- while (n-- > 0) {
- long eventAddress = getEvent(address, n);
- int fd = getDescriptor(eventAddress);
-
- // wakeup
- if (fd == sp[0]) {
- if (wakeupCount.decrementAndGet() == 0) {
- // no more wakeups so drain pipe
- drain1(sp[0]);
- }
-
- // queue special event if there are more events
- // to handle.
- if (n > 0) {
- queue.offer(EXECUTE_TASK_OR_SHUTDOWN);
- continue;
- }
- return EXECUTE_TASK_OR_SHUTDOWN;
- }
-
- PollableChannel channel = fdToChannel.get(fd);
- if (channel != null) {
- int events = getEvents(eventAddress);
- Event ev = new Event(channel, events);
-
- // n-1 events are queued; This thread handles
- // the last one except for the wakeup
- if (n > 0) {
- queue.offer(ev);
- } else {
- return ev;
- }
- }
- }
- } finally {
- fdToChannelLock.readLock().unlock();
- }
- }
- } finally {
- // to ensure that some thread will poll when all events have
- // been consumed
- queue.offer(NEED_TO_POLL);
- }
- }
-
- public void run() {
- Invoker.GroupAndInvokeCount myGroupAndInvokeCount =
- Invoker.getGroupAndInvokeCount();
- final boolean isPooledThread = (myGroupAndInvokeCount != null);
- boolean replaceMe = false;
- Event ev;
- try {
- for (;;) {
- // reset invoke count
- if (isPooledThread)
- myGroupAndInvokeCount.resetInvokeCount();
-
- try {
- replaceMe = false;
- ev = queue.take();
-
- // no events and this thread has been "selected" to
- // poll for more.
- if (ev == NEED_TO_POLL) {
- try {
- ev = poll();
- } catch (IOException x) {
- x.printStackTrace();
- return;
- }
- }
- } catch (InterruptedException x) {
- continue;
- }
-
- // handle wakeup to execute task or shutdown
- if (ev == EXECUTE_TASK_OR_SHUTDOWN) {
- Runnable task = pollTask();
- if (task == null) {
- // shutdown request
- return;
- }
- // run task (may throw error/exception)
- replaceMe = true;
- task.run();
- continue;
- }
-
- // process event
- try {
- ev.channel().onEvent(ev.events(), isPooledThread);
- } catch (Error x) {
- replaceMe = true; throw x;
- } catch (RuntimeException x) {
- replaceMe = true; throw x;
- }
- }
- } finally {
- // last handler to exit when shutdown releases resources
- int remaining = threadExit(this, replaceMe);
- if (remaining == 0 && isShutdown()) {
- implClose();
- }
- }
- }
- }
-
- // -- Native methods --
-
- private static native void socketpair(int[] sv) throws IOException;
-
- private static native void interrupt(int fd) throws IOException;
-
- private static native void drain1(int fd) throws IOException;
-
- private static native void close0(int fd);
-
- static {
- Util.load();
- }
-}
diff --git a/ojluni/src/main/java/sun/nio/ch/Groupable.java b/ojluni/src/main/java/sun/nio/ch/Groupable.java
deleted file mode 100755
index 64d8958..0000000
--- a/ojluni/src/main/java/sun/nio/ch/Groupable.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.nio.ch;
-
-/**
- * Implemented by asynchronous channels that can be associated with an
- * asynchronous channel group.
- */
-
-interface Groupable {
- AsynchronousChannelGroupImpl group();
-}
diff --git a/ojluni/src/main/java/sun/nio/ch/Invoker.java b/ojluni/src/main/java/sun/nio/ch/Invoker.java
deleted file mode 100755
index e55db54..0000000
--- a/ojluni/src/main/java/sun/nio/ch/Invoker.java
+++ /dev/null
@@ -1,308 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.nio.ch;
-
-import java.nio.channels.*;
-import java.util.concurrent.*;
-import java.security.AccessController;
-import sun.security.action.GetIntegerAction;
-
-/**
- * Defines static methods to invoke a completion handler or arbitrary task.
- */
-
-class Invoker {
- private Invoker() { }
-
- // maximum number of completion handlers that may be invoked on the current
- // thread before it re-directs invocations to the thread pool. This helps
- // avoid stack overflow and lessens the risk of starvation.
- private static final int maxHandlerInvokeCount = AccessController.doPrivileged(
- new GetIntegerAction("sun.nio.ch.maxCompletionHandlersOnStack", 16));
-
- // Per-thread object with reference to channel group and a counter for
- // the number of completion handlers invoked. This should be reset to 0
- // when all completion handlers have completed.
- static class GroupAndInvokeCount {
- private final AsynchronousChannelGroupImpl group;
- private int handlerInvokeCount;
- GroupAndInvokeCount(AsynchronousChannelGroupImpl group) {
- this.group = group;
- }
- AsynchronousChannelGroupImpl group() {
- return group;
- }
- int invokeCount() {
- return handlerInvokeCount;
- }
- void setInvokeCount(int value) {
- handlerInvokeCount = value;
- }
- void resetInvokeCount() {
- handlerInvokeCount = 0;
- }
- void incrementInvokeCount() {
- handlerInvokeCount++;
- }
- }
- private static final ThreadLocal<GroupAndInvokeCount> myGroupAndInvokeCount =
- new ThreadLocal<GroupAndInvokeCount>() {
- @Override protected GroupAndInvokeCount initialValue() {
- return null;
- }
- };
-
- /**
- * Binds this thread to the given group
- */
- static void bindToGroup(AsynchronousChannelGroupImpl group) {
- myGroupAndInvokeCount.set(new GroupAndInvokeCount(group));
- }
-
- /**
- * Returns the GroupAndInvokeCount object for this thread.
- */
- static GroupAndInvokeCount getGroupAndInvokeCount() {
- return myGroupAndInvokeCount.get();
- }
-
- /**
- * Returns true if the current thread is in a channel group's thread pool
- */
- static boolean isBoundToAnyGroup() {
- return myGroupAndInvokeCount.get() != null;
- }
-
- /**
- * Returns true if the current thread is in the given channel's thread
- * pool and we haven't exceeded the maximum number of handler frames on
- * the stack.
- */
- static boolean mayInvokeDirect(GroupAndInvokeCount myGroupAndInvokeCount,
- AsynchronousChannelGroupImpl group)
- {
- if ((myGroupAndInvokeCount != null) &&
- (myGroupAndInvokeCount.group() == group) &&
- (myGroupAndInvokeCount.invokeCount() < maxHandlerInvokeCount))
- {
- return true;
- }
- return false;
- }
-
- /**
- * Invoke handler without checking the thread identity or number of handlers
- * on the thread stack.
- */
- static <V,A> void invokeUnchecked(CompletionHandler<V,? super A> handler,
- A attachment,
- V value,
- Throwable exc)
- {
- if (exc == null) {
- handler.completed(value, attachment);
- } else {
- handler.failed(exc, attachment);
- }
-
- // clear interrupt
- Thread.interrupted();
- }
-
- /**
- * Invoke handler assuming thread identity already checked
- */
- static <V,A> void invokeDirect(GroupAndInvokeCount myGroupAndInvokeCount,
- CompletionHandler<V,? super A> handler,
- A attachment,
- V result,
- Throwable exc)
- {
- myGroupAndInvokeCount.incrementInvokeCount();
- Invoker.invokeUnchecked(handler, attachment, result, exc);
- }
-
- /**
- * Invokes the handler. If the current thread is in the channel group's
- * thread pool then the handler is invoked directly, otherwise it is
- * invoked indirectly.
- */
- static <V,A> void invoke(AsynchronousChannel channel,
- CompletionHandler<V,? super A> handler,
- A attachment,
- V result,
- Throwable exc)
- {
- boolean invokeDirect = false;
- boolean identityOkay = false;
- GroupAndInvokeCount thisGroupAndInvokeCount = myGroupAndInvokeCount.get();
- if (thisGroupAndInvokeCount != null) {
- if ((thisGroupAndInvokeCount.group() == ((Groupable)channel).group()))
- identityOkay = true;
- if (identityOkay &&
- (thisGroupAndInvokeCount.invokeCount() < maxHandlerInvokeCount))
- {
- // group match
- invokeDirect = true;
- }
- }
- if (invokeDirect) {
- invokeDirect(thisGroupAndInvokeCount, handler, attachment, result, exc);
- } else {
- try {
- invokeIndirectly(channel, handler, attachment, result, exc);
- } catch (RejectedExecutionException ree) {
- // channel group shutdown; fallback to invoking directly
- // if the current thread has the right identity.
- if (identityOkay) {
- invokeDirect(thisGroupAndInvokeCount,
- handler, attachment, result, exc);
- } else {
- throw new ShutdownChannelGroupException();
- }
- }
- }
- }
-
- /**
- * Invokes the handler indirectly via the channel group's thread pool.
- */
- static <V,A> void invokeIndirectly(AsynchronousChannel channel,
- final CompletionHandler<V,? super A> handler,
- final A attachment,
- final V result,
- final Throwable exc)
- {
- try {
- ((Groupable)channel).group().executeOnPooledThread(new Runnable() {
- public void run() {
- GroupAndInvokeCount thisGroupAndInvokeCount =
- myGroupAndInvokeCount.get();
- if (thisGroupAndInvokeCount != null)
- thisGroupAndInvokeCount.setInvokeCount(1);
- invokeUnchecked(handler, attachment, result, exc);
- }
- });
- } catch (RejectedExecutionException ree) {
- throw new ShutdownChannelGroupException();
- }
- }
-
- /**
- * Invokes the handler "indirectly" in the given Executor
- */
- static <V,A> void invokeIndirectly(final CompletionHandler<V,? super A> handler,
- final A attachment,
- final V value,
- final Throwable exc,
- Executor executor)
- {
- try {
- executor.execute(new Runnable() {
- public void run() {
- invokeUnchecked(handler, attachment, value, exc);
- }
- });
- } catch (RejectedExecutionException ree) {
- throw new ShutdownChannelGroupException();
- }
- }
-
- /**
- * Invokes the given task on the thread pool associated with the given
- * channel. If the current thread is in the thread pool then the task is
- * invoked directly.
- */
- static void invokeOnThreadInThreadPool(Groupable channel,
- Runnable task)
- {
- boolean invokeDirect;
- GroupAndInvokeCount thisGroupAndInvokeCount = myGroupAndInvokeCount.get();
- AsynchronousChannelGroupImpl targetGroup = channel.group();
- if (thisGroupAndInvokeCount == null) {
- invokeDirect = false;
- } else {
- invokeDirect = (thisGroupAndInvokeCount.group == targetGroup);
- }
- try {
- if (invokeDirect) {
- task.run();
- } else {
- targetGroup.executeOnPooledThread(task);
- }
- } catch (RejectedExecutionException ree) {
- throw new ShutdownChannelGroupException();
- }
- }
-
- /**
- * Invoke handler with completed result. This method does not check the
- * thread identity or the number of handlers on the thread stack.
- */
- static <V,A> void invokeUnchecked(PendingFuture<V,A> future) {
- assert future.isDone();
- CompletionHandler<V,? super A> handler = future.handler();
- if (handler != null) {
- invokeUnchecked(handler,
- future.attachment(),
- future.value(),
- future.exception());
- }
- }
-
- /**
- * Invoke handler with completed result. If the current thread is in the
- * channel group's thread pool then the handler is invoked directly,
- * otherwise it is invoked indirectly.
- */
- static <V,A> void invoke(PendingFuture<V,A> future) {
- assert future.isDone();
- CompletionHandler<V,? super A> handler = future.handler();
- if (handler != null) {
- invoke(future.channel(),
- handler,
- future.attachment(),
- future.value(),
- future.exception());
- }
- }
-
- /**
- * Invoke handler with completed result. The handler is invoked indirectly,
- * via the channel group's thread pool.
- */
- static <V,A> void invokeIndirectly(PendingFuture<V,A> future) {
- assert future.isDone();
- CompletionHandler<V,? super A> handler = future.handler();
- if (handler != null) {
- invokeIndirectly(future.channel(),
- handler,
- future.attachment(),
- future.value(),
- future.exception());
- }
- }
-}
diff --git a/ojluni/src/main/java/sun/nio/ch/KQueue.java b/ojluni/src/main/java/sun/nio/ch/KQueue.java
deleted file mode 100755
index e3466e3..0000000
--- a/ojluni/src/main/java/sun/nio/ch/KQueue.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.nio.ch;
-
-import java.io.IOException;
-import sun.misc.Unsafe;
-
-/**
- * Provides access to the BSD kqueue facility.
- */
-
-class KQueue {
- private KQueue() { }
-
- private static final Unsafe unsafe = Unsafe.getUnsafe();
-
- /**
- * struct kevent {
- * uintptr_t ident; // identifier for this event, usually the fd
- * int16_t filter; // filter for event
- * uint16_t flags; // general flags
- * uint32_t fflags; // filter-specific flags
- * intptr_t data; // filter-specific data
- * void *udata; // opaque user data identifier
- * };
- */
- private static final int SIZEOF_KQUEUEEVENT = keventSize();
- private static final int OFFSET_IDENT = identOffset();
- private static final int OFFSET_FILTER = filterOffset();
- private static final int OFFSET_FLAGS = flagsOffset();
-
- // filters
- static final int EVFILT_READ = -1;
- static final int EVFILT_WRITE = -2;
-
- // flags
- static final int EV_ADD = 0x0001;
- static final int EV_ONESHOT = 0x0010;
- static final int EV_CLEAR = 0x0020;
-
- /**
- * Allocates a poll array to handle up to {@code count} events.
- */
- static long allocatePollArray(int count) {
- return unsafe.allocateMemory(count * SIZEOF_KQUEUEEVENT);
- }
-
- /**
- * Free a poll array
- */
- static void freePollArray(long address) {
- unsafe.freeMemory(address);
- }
-
- /**
- * Returns kevent[i].
- */
- static long getEvent(long address, int i) {
- return address + (SIZEOF_KQUEUEEVENT*i);
- }
-
- /**
- * Returns the file descriptor from a kevent (assuming to be in ident field)
- */
- static int getDescriptor(long address) {
- return unsafe.getInt(address + OFFSET_IDENT);
- }
-
- static int getFilter(long address) {
- return unsafe.getShort(address + OFFSET_FILTER);
- }
-
- static int getFlags(long address) {
- return unsafe.getShort(address + OFFSET_FLAGS);
- }
-
- // -- Native methods --
-
- private static native int keventSize();
-
- private static native int identOffset();
-
- private static native int filterOffset();
-
- private static native int flagsOffset();
-
- static native int kqueue() throws IOException;
-
- static native int keventRegister(int kqpfd, int fd, int filter, int flags);
-
- static native int keventPoll(int kqpfd, long pollAddress, int nevents)
- throws IOException;
-
- static {
- Util.load();
- }
-}
diff --git a/ojluni/src/main/java/sun/nio/ch/KQueuePort.java b/ojluni/src/main/java/sun/nio/ch/KQueuePort.java
deleted file mode 100755
index cd16e2e..0000000
--- a/ojluni/src/main/java/sun/nio/ch/KQueuePort.java
+++ /dev/null
@@ -1,331 +0,0 @@
-/*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.nio.ch;
-
-import java.nio.channels.spi.AsynchronousChannelProvider;
-import java.io.IOException;
-import java.util.concurrent.ArrayBlockingQueue;
-import java.util.concurrent.RejectedExecutionException;
-import java.util.concurrent.atomic.AtomicInteger;
-import static sun.nio.ch.KQueue.*;
-
-/**
- * AsynchronousChannelGroup implementation based on the BSD kqueue facility.
- */
-
-final class KQueuePort
- extends Port
-{
- // maximum number of events to poll at a time
- private static final int MAX_KEVENTS_TO_POLL = 512;
-
- // kqueue file descriptor
- private final int kqfd;
-
- // true if kqueue closed
- private boolean closed;
-
- // socket pair used for wakeup
- private final int sp[];
-
- // number of wakeups pending
- private final AtomicInteger wakeupCount = new AtomicInteger();
-
- // address of the poll array passed to kqueue_wait
- private final long address;
-
- // encapsulates an event for a channel
- static class Event {
- final PollableChannel channel;
- final int events;
-
- Event(PollableChannel channel, int events) {
- this.channel = channel;
- this.events = events;
- }
-
- PollableChannel channel() { return channel; }
- int events() { return events; }
- }
-
- // queue of events for cases that a polling thread dequeues more than one
- // event
- private final ArrayBlockingQueue<Event> queue;
- private final Event NEED_TO_POLL = new Event(null, 0);
- private final Event EXECUTE_TASK_OR_SHUTDOWN = new Event(null, 0);
-
- KQueuePort(AsynchronousChannelProvider provider, ThreadPool pool)
- throws IOException
- {
- super(provider, pool);
-
- // open kqueue
- this.kqfd = kqueue();
-
- // create socket pair for wakeup mechanism
- int[] sv = new int[2];
- try {
- socketpair(sv);
-
- // register one end with kqueue
- keventRegister(kqfd, sv[0], EVFILT_READ, EV_ADD);
- } catch (IOException x) {
- close0(kqfd);
- throw x;
- }
- this.sp = sv;
-
- // allocate the poll array
- this.address = allocatePollArray(MAX_KEVENTS_TO_POLL);
-
- // create the queue and offer the special event to ensure that the first
- // threads polls
- this.queue = new ArrayBlockingQueue<Event>(MAX_KEVENTS_TO_POLL);
- this.queue.offer(NEED_TO_POLL);
- }
-
- KQueuePort start() {
- startThreads(new EventHandlerTask());
- return this;
- }
-
- /**
- * Release all resources
- */
- private void implClose() {
- synchronized (this) {
- if (closed)
- return;
- closed = true;
- }
- freePollArray(address);
- close0(sp[0]);
- close0(sp[1]);
- close0(kqfd);
- }
-
- private void wakeup() {
- if (wakeupCount.incrementAndGet() == 1) {
- // write byte to socketpair to force wakeup
- try {
- interrupt(sp[1]);
- } catch (IOException x) {
- throw new AssertionError(x);
- }
- }
- }
-
- @Override
- void executeOnHandlerTask(Runnable task) {
- synchronized (this) {
- if (closed)
- throw new RejectedExecutionException();
- offerTask(task);
- wakeup();
- }
- }
-
- @Override
- void shutdownHandlerTasks() {
- /*
- * If no tasks are running then just release resources; otherwise
- * write to the one end of the socketpair to wakeup any polling threads.
- */
- int nThreads = threadCount();
- if (nThreads == 0) {
- implClose();
- } else {
- // send interrupt to each thread
- while (nThreads-- > 0) {
- wakeup();
- }
- }
- }
-
- // invoked by clients to register a file descriptor
- @Override
- void startPoll(int fd, int events) {
- // We use a separate filter for read and write events.
- // TBD: Measure cost of EV_ONESHOT vs. EV_CLEAR, either will do here.
- int err = 0;
- int flags = (EV_ADD|EV_ONESHOT);
- if ((events & Port.POLLIN) > 0)
- err = keventRegister(kqfd, fd, EVFILT_READ, flags);
- if (err == 0 && (events & Port.POLLOUT) > 0)
- err = keventRegister(kqfd, fd, EVFILT_WRITE, flags);
- if (err != 0)
- throw new InternalError("kevent failed: " + err); // should not happen
- }
-
- /*
- * Task to process events from kqueue and dispatch to the channel's
- * onEvent handler.
- *
- * Events are retreived from kqueue in batch and offered to a BlockingQueue
- * where they are consumed by handler threads. A special "NEED_TO_POLL"
- * event is used to signal one consumer to re-poll when all events have
- * been consumed.
- */
- private class EventHandlerTask implements Runnable {
- private Event poll() throws IOException {
- try {
- for (;;) {
- int n = keventPoll(kqfd, address, MAX_KEVENTS_TO_POLL);
- /*
- * 'n' events have been read. Here we map them to their
- * corresponding channel in batch and queue n-1 so that
- * they can be handled by other handler threads. The last
- * event is handled by this thread (and so is not queued).
- */
- fdToChannelLock.readLock().lock();
- try {
- while (n-- > 0) {
- long keventAddress = getEvent(address, n);
- int fd = getDescriptor(keventAddress);
-
- // wakeup
- if (fd == sp[0]) {
- if (wakeupCount.decrementAndGet() == 0) {
- // no more wakeups so drain pipe
- drain1(sp[0]);
- }
-
- // queue special event if there are more events
- // to handle.
- if (n > 0) {
- queue.offer(EXECUTE_TASK_OR_SHUTDOWN);
- continue;
- }
- return EXECUTE_TASK_OR_SHUTDOWN;
- }
-
- PollableChannel channel = fdToChannel.get(fd);
- if (channel != null) {
- int filter = getFilter(keventAddress);
- int events = 0;
- if (filter == EVFILT_READ)
- events = Port.POLLIN;
- else if (filter == EVFILT_WRITE)
- events = Port.POLLOUT;
-
- Event ev = new Event(channel, events);
-
- // n-1 events are queued; This thread handles
- // the last one except for the wakeup
- if (n > 0) {
- queue.offer(ev);
- } else {
- return ev;
- }
- }
- }
- } finally {
- fdToChannelLock.readLock().unlock();
- }
- }
- } finally {
- // to ensure that some thread will poll when all events have
- // been consumed
- queue.offer(NEED_TO_POLL);
- }
- }
-
- public void run() {
- Invoker.GroupAndInvokeCount myGroupAndInvokeCount =
- Invoker.getGroupAndInvokeCount();
- final boolean isPooledThread = (myGroupAndInvokeCount != null);
- boolean replaceMe = false;
- Event ev;
- try {
- for (;;) {
- // reset invoke count
- if (isPooledThread)
- myGroupAndInvokeCount.resetInvokeCount();
-
- try {
- replaceMe = false;
- ev = queue.take();
-
- // no events and this thread has been "selected" to
- // poll for more.
- if (ev == NEED_TO_POLL) {
- try {
- ev = poll();
- } catch (IOException x) {
- x.printStackTrace();
- return;
- }
- }
- } catch (InterruptedException x) {
- continue;
- }
-
- // handle wakeup to execute task or shutdown
- if (ev == EXECUTE_TASK_OR_SHUTDOWN) {
- Runnable task = pollTask();
- if (task == null) {
- // shutdown request
- return;
- }
- // run task (may throw error/exception)
- replaceMe = true;
- task.run();
- continue;
- }
-
- // process event
- try {
- ev.channel().onEvent(ev.events(), isPooledThread);
- } catch (Error x) {
- replaceMe = true; throw x;
- } catch (RuntimeException x) {
- replaceMe = true; throw x;
- }
- }
- } finally {
- // last handler to exit when shutdown releases resources
- int remaining = threadExit(this, replaceMe);
- if (remaining == 0 && isShutdown()) {
- implClose();
- }
- }
- }
- }
-
- // -- Native methods --
-
- private static native void socketpair(int[] sv) throws IOException;
-
- private static native void interrupt(int fd) throws IOException;
-
- private static native void drain1(int fd) throws IOException;
-
- private static native void close0(int fd);
-
- static {
- Util.load();
- }
-}
diff --git a/ojluni/src/main/java/sun/nio/ch/LinuxAsynchronousChannelProvider.java b/ojluni/src/main/java/sun/nio/ch/LinuxAsynchronousChannelProvider.java
deleted file mode 100755
index 2fbe896..0000000
--- a/ojluni/src/main/java/sun/nio/ch/LinuxAsynchronousChannelProvider.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.nio.ch;
-
-import java.nio.channels.*;
-import java.nio.channels.spi.AsynchronousChannelProvider;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.ThreadFactory;
-import java.io.IOException;
-
-public class LinuxAsynchronousChannelProvider
- extends AsynchronousChannelProvider
-{
- private static volatile EPollPort defaultPort;
-
- private EPollPort defaultEventPort() throws IOException {
- if (defaultPort == null) {
- synchronized (LinuxAsynchronousChannelProvider.class) {
- if (defaultPort == null) {
- defaultPort = new EPollPort(this, ThreadPool.getDefault()).start();
- }
- }
- }
- return defaultPort;
- }
-
- public LinuxAsynchronousChannelProvider() {
- }
-
- @Override
- public AsynchronousChannelGroup openAsynchronousChannelGroup(int nThreads, ThreadFactory factory)
- throws IOException
- {
- return new EPollPort(this, ThreadPool.create(nThreads, factory)).start();
- }
-
- @Override
- public AsynchronousChannelGroup openAsynchronousChannelGroup(ExecutorService executor, int initialSize)
- throws IOException
- {
- return new EPollPort(this, ThreadPool.wrap(executor, initialSize)).start();
- }
-
- private Port toPort(AsynchronousChannelGroup group) throws IOException {
- if (group == null) {
- return defaultEventPort();
- } else {
- if (!(group instanceof EPollPort))
- throw new IllegalChannelGroupException();
- return (Port)group;
- }
- }
-
- @Override
- public AsynchronousServerSocketChannel openAsynchronousServerSocketChannel(AsynchronousChannelGroup group)
- throws IOException
- {
- return new UnixAsynchronousServerSocketChannelImpl(toPort(group));
- }
-
- @Override
- public AsynchronousSocketChannel openAsynchronousSocketChannel(AsynchronousChannelGroup group)
- throws IOException
- {
- return new UnixAsynchronousSocketChannelImpl(toPort(group));
- }
-}
diff --git a/ojluni/src/main/java/sun/nio/ch/MembershipKeyImpl.java b/ojluni/src/main/java/sun/nio/ch/MembershipKeyImpl.java
deleted file mode 100755
index 5ecc396..0000000
--- a/ojluni/src/main/java/sun/nio/ch/MembershipKeyImpl.java
+++ /dev/null
@@ -1,220 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.nio.ch;
-
-import java.nio.channels.*;
-import java.net.InetAddress;
-import java.net.NetworkInterface;
-import java.io.IOException;
-import java.util.HashSet;
-
-/**
- * MembershipKey implementation.
- */
-
-class MembershipKeyImpl
- extends MembershipKey
-{
- private final MulticastChannel ch;
- private final InetAddress group;
- private final NetworkInterface interf;
- private final InetAddress source;
-
- // true when key is valid
- private volatile boolean valid = true;
-
- // lock used when creating or accessing blockedSet
- private Object stateLock = new Object();
-
- // set of source addresses that are blocked
- private HashSet<InetAddress> blockedSet;
-
- private MembershipKeyImpl(MulticastChannel ch,
- InetAddress group,
- NetworkInterface interf,
- InetAddress source)
- {
- this.ch = ch;
- this.group = group;
- this.interf = interf;
- this.source = source;
- }
-
- /**
- * MembershipKey will additional context for IPv4 membership
- */
- static class Type4 extends MembershipKeyImpl {
- private final int groupAddress;
- private final int interfAddress;
- private final int sourceAddress;
-
- Type4(MulticastChannel ch,
- InetAddress group,
- NetworkInterface interf,
- InetAddress source,
- int groupAddress,
- int interfAddress,
- int sourceAddress)
- {
- super(ch, group, interf, source);
- this.groupAddress = groupAddress;
- this.interfAddress = interfAddress;
- this.sourceAddress = sourceAddress;
- }
-
- int groupAddress() {
- return groupAddress;
- }
-
- int interfaceAddress() {
- return interfAddress;
- }
-
- int source() {
- return sourceAddress;
- }
- }
-
- /**
- * MembershipKey will additional context for IPv6 membership
- */
- static class Type6 extends MembershipKeyImpl {
- private final byte[] groupAddress;
- private final int index;
- private final byte[] sourceAddress;
-
- Type6(MulticastChannel ch,
- InetAddress group,
- NetworkInterface interf,
- InetAddress source,
- byte[] groupAddress,
- int index,
- byte[] sourceAddress)
- {
- super(ch, group, interf, source);
- this.groupAddress = groupAddress;
- this.index = index;
- this.sourceAddress = sourceAddress;
- }
-
- byte[] groupAddress() {
- return groupAddress;
- }
-
- int index() {
- return index;
- }
-
- byte[] source() {
- return sourceAddress;
- }
- }
-
- public boolean isValid() {
- return valid;
- }
-
- // package-private
- void invalidate() {
- valid = false;
- }
-
- public void drop() {
- // delegate to channel
- ((DatagramChannelImpl)ch).drop(this);
- }
-
- @Override
- public MulticastChannel channel() {
- return ch;
- }
-
- @Override
- public InetAddress group() {
- return group;
- }
-
- @Override
- public NetworkInterface networkInterface() {
- return interf;
- }
-
- @Override
- public InetAddress sourceAddress() {
- return source;
- }
-
- @Override
- public MembershipKey block(InetAddress toBlock)
- throws IOException
- {
- if (source != null)
- throw new IllegalStateException("key is source-specific");
-
- synchronized (stateLock) {
- if ((blockedSet != null) && blockedSet.contains(toBlock)) {
- // already blocked, nothing to do
- return this;
- }
-
- ((DatagramChannelImpl)ch).block(this, toBlock);
-
- // created blocked set if required and add source address
- if (blockedSet == null)
- blockedSet = new HashSet<InetAddress>();
- blockedSet.add(toBlock);
- }
- return this;
- }
-
- @Override
- public MembershipKey unblock(InetAddress toUnblock) {
- synchronized (stateLock) {
- if ((blockedSet == null) || !blockedSet.contains(toUnblock))
- throw new IllegalStateException("not blocked");
-
- ((DatagramChannelImpl)ch).unblock(this, toUnblock);
-
- blockedSet.remove(toUnblock);
- }
- return this;
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder(64);
- sb.append('<');
- sb.append(group.getHostAddress());
- sb.append(',');
- sb.append(interf.getName());
- if (source != null) {
- sb.append(',');
- sb.append(source.getHostAddress());
- }
- sb.append('>');
- return sb.toString();
- }
-}
diff --git a/ojluni/src/main/java/sun/nio/ch/MembershipRegistry.java b/ojluni/src/main/java/sun/nio/ch/MembershipRegistry.java
deleted file mode 100755
index 6607fc8..0000000
--- a/ojluni/src/main/java/sun/nio/ch/MembershipRegistry.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.nio.ch;
-
-import java.nio.channels.*;
-import java.net.InetAddress;
-import java.net.NetworkInterface;
-import java.util.*;
-
-/**
- * Simple registry of membership keys for a MulticastChannel.
- *
- * Instances of this object are not safe by multiple concurrent threads.
- */
-
-class MembershipRegistry {
-
- // map multicast group to keys
- private Map<InetAddress,List<MembershipKeyImpl>> groups = null;
-
- MembershipRegistry() {
- }
-
- /**
- * Checks registry for membership of the group on the given
- * network interface.
- */
- MembershipKey checkMembership(InetAddress group, NetworkInterface interf,
- InetAddress source)
- {
- if (groups != null) {
- List<MembershipKeyImpl> keys = groups.get(group);
- if (keys != null) {
- for (MembershipKeyImpl key: keys) {
- if (key.networkInterface().equals(interf)) {
- // already a member to receive all packets so return
- // existing key or detect conflict
- if (source == null) {
- if (key.sourceAddress() == null)
- return key;
- throw new IllegalStateException("Already a member to receive all packets");
- }
-
- // already have source-specific membership so return key
- // or detect conflict
- if (key.sourceAddress() == null)
- throw new IllegalStateException("Already have source-specific membership");
- if (source.equals(key.sourceAddress()))
- return key;
- }
- }
- }
- }
- return null;
- }
-
- /**
- * Add membership to the registry, returning a new membership key.
- */
- void add(MembershipKeyImpl key) {
- InetAddress group = key.group();
- List<MembershipKeyImpl> keys;
- if (groups == null) {
- groups = new HashMap<InetAddress,List<MembershipKeyImpl>>();
- keys = null;
- } else {
- keys = groups.get(group);
- }
- if (keys == null) {
- keys = new LinkedList<MembershipKeyImpl>();
- groups.put(group, keys);
- }
- keys.add(key);
- }
-
- /**
- * Remove a key from the registry
- */
- void remove(MembershipKeyImpl key) {
- InetAddress group = key.group();
- List<MembershipKeyImpl> keys = groups.get(group);
- if (keys != null) {
- Iterator<MembershipKeyImpl> i = keys.iterator();
- while (i.hasNext()) {
- if (i.next() == key) {
- i.remove();
- break;
- }
- }
- if (keys.isEmpty()) {
- groups.remove(group);
- }
- }
- }
-
- /**
- * Invalidate all keys in the registry
- */
- void invalidateAll() {
- if (groups != null) {
- for (InetAddress group: groups.keySet()) {
- for (MembershipKeyImpl key: groups.get(group)) {
- key.invalidate();
- }
- }
- }
- }
-}
diff --git a/ojluni/src/main/java/sun/nio/ch/PendingFuture.java b/ojluni/src/main/java/sun/nio/ch/PendingFuture.java
deleted file mode 100755
index 863b0f0..0000000
--- a/ojluni/src/main/java/sun/nio/ch/PendingFuture.java
+++ /dev/null
@@ -1,254 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.nio.ch;
-
-import java.nio.channels.*;
-import java.util.concurrent.*;
-import java.io.IOException;
-
-/**
- * A Future for a pending I/O operation. A PendingFuture allows for the
- * attachment of an additional arbitrary context object and a timer task.
- */
-
-final class PendingFuture<V,A> implements Future<V> {
- private static final CancellationException CANCELLED =
- new CancellationException();
-
- private final AsynchronousChannel channel;
- private final CompletionHandler<V,? super A> handler;
- private final A attachment;
-
- // true if result (or exception) is available
- private volatile boolean haveResult;
- private volatile V result;
- private volatile Throwable exc;
-
- // latch for waiting (created lazily if needed)
- private CountDownLatch latch;
-
- // optional timer task that is cancelled when result becomes available
- private Future<?> timeoutTask;
-
- // optional context object
- private volatile Object context;
-
- PendingFuture(AsynchronousChannel channel,
- CompletionHandler<V,? super A> handler,
- A attachment,
- Object context)
- {
- this.channel = channel;
- this.handler = handler;
- this.attachment = attachment;
- this.context = context;
- }
-
- PendingFuture(AsynchronousChannel channel,
- CompletionHandler<V,? super A> handler,
- A attachment)
- {
- this.channel = channel;
- this.handler = handler;
- this.attachment = attachment;
- }
-
- PendingFuture(AsynchronousChannel channel) {
- this(channel, null, null);
- }
-
- PendingFuture(AsynchronousChannel channel, Object context) {
- this(channel, null, null, context);
- }
-
- AsynchronousChannel channel() {
- return channel;
- }
-
- CompletionHandler<V,? super A> handler() {
- return handler;
- }
-
- A attachment() {
- return attachment;
- }
-
- void setContext(Object context) {
- this.context = context;
- }
-
- Object getContext() {
- return context;
- }
-
- void setTimeoutTask(Future<?> task) {
- synchronized (this) {
- if (haveResult) {
- task.cancel(false);
- } else {
- this.timeoutTask = task;
- }
- }
- }
-
- // creates latch if required; return true if caller needs to wait
- private boolean prepareForWait() {
- synchronized (this) {
- if (haveResult) {
- return false;
- } else {
- if (latch == null)
- latch = new CountDownLatch(1);
- return true;
- }
- }
- }
-
- /**
- * Sets the result, or a no-op if the result or exception is already set.
- */
- void setResult(V res) {
- synchronized (this) {
- if (haveResult)
- return;
- result = res;
- haveResult = true;
- if (timeoutTask != null)
- timeoutTask.cancel(false);
- if (latch != null)
- latch.countDown();
- }
- }
-
- /**
- * Sets the result, or a no-op if the result or exception is already set.
- */
- void setFailure(Throwable x) {
- if (!(x instanceof IOException) && !(x instanceof SecurityException))
- x = new IOException(x);
- synchronized (this) {
- if (haveResult)
- return;
- exc = x;
- haveResult = true;
- if (timeoutTask != null)
- timeoutTask.cancel(false);
- if (latch != null)
- latch.countDown();
- }
- }
-
- /**
- * Sets the result
- */
- void setResult(V res, Throwable x) {
- if (x == null) {
- setResult(res);
- } else {
- setFailure(x);
- }
- }
-
- @Override
- public V get() throws ExecutionException, InterruptedException {
- if (!haveResult) {
- boolean needToWait = prepareForWait();
- if (needToWait)
- latch.await();
- }
- if (exc != null) {
- if (exc == CANCELLED)
- throw new CancellationException();
- throw new ExecutionException(exc);
- }
- return result;
- }
-
- @Override
- public V get(long timeout, TimeUnit unit)
- throws ExecutionException, InterruptedException, TimeoutException
- {
- if (!haveResult) {
- boolean needToWait = prepareForWait();
- if (needToWait)
- if (!latch.await(timeout, unit)) throw new TimeoutException();
- }
- if (exc != null) {
- if (exc == CANCELLED)
- throw new CancellationException();
- throw new ExecutionException(exc);
- }
- return result;
- }
-
- Throwable exception() {
- return (exc != CANCELLED) ? exc : null;
- }
-
- V value() {
- return result;
- }
-
- @Override
- public boolean isCancelled() {
- return (exc == CANCELLED);
- }
-
- @Override
- public boolean isDone() {
- return haveResult;
- }
-
- @Override
- public boolean cancel(boolean mayInterruptIfRunning) {
- synchronized (this) {
- if (haveResult)
- return false; // already completed
-
- // notify channel
- if (channel() instanceof Cancellable)
- ((Cancellable)channel()).onCancel(this);
-
- // set result and cancel timer
- exc = CANCELLED;
- haveResult = true;
- if (timeoutTask != null)
- timeoutTask.cancel(false);
- }
-
- // close channel if forceful cancel
- if (mayInterruptIfRunning) {
- try {
- channel().close();
- } catch (IOException ignore) { }
- }
-
- // release waiters
- if (latch != null)
- latch.countDown();
- return true;
- }
-}
diff --git a/ojluni/src/main/java/sun/nio/ch/Port.java b/ojluni/src/main/java/sun/nio/ch/Port.java
deleted file mode 100755
index 9402508..0000000
--- a/ojluni/src/main/java/sun/nio/ch/Port.java
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.nio.ch;
-
-import java.nio.channels.spi.AsynchronousChannelProvider;
-import java.nio.channels.*;
-import java.io.IOException;
-import java.io.Closeable;
-import java.io.FileDescriptor;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-
-/**
- * Base implementation of AsynchronousChannelGroupImpl for Unix systems.
- */
-
-abstract class Port extends AsynchronousChannelGroupImpl {
- static final short POLLIN = 0x0001;
- static final short POLLOUT = 0x0004;
- static final short POLLERR = 0x0008;
- static final short POLLHUP = 0x0010;
-
- /**
- * Implemented by clients registered with this port.
- */
- interface PollableChannel extends Closeable {
- void onEvent(int events, boolean mayInvokeDirect);
- }
-
- // maps fd to "pollable" channel
- protected final ReadWriteLock fdToChannelLock = new ReentrantReadWriteLock();
- protected final Map<Integer,PollableChannel> fdToChannel =
- new HashMap<Integer,PollableChannel>();
-
-
- Port(AsynchronousChannelProvider provider, ThreadPool pool) {
- super(provider, pool);
- }
-
- /**
- * Register channel identified by its file descriptor
- */
- final void register(int fd, PollableChannel ch) {
- fdToChannelLock.writeLock().lock();
- try {
- if (isShutdown())
- throw new ShutdownChannelGroupException();
- fdToChannel.put(Integer.valueOf(fd), ch);
- } finally {
- fdToChannelLock.writeLock().unlock();
- }
- }
-
- /**
- * Unregister channel identified by its file descriptor
- */
- final void unregister(int fd) {
- boolean checkForShutdown = false;
-
- fdToChannelLock.writeLock().lock();
- try {
- fdToChannel.remove(Integer.valueOf(fd));
-
- // last key to be removed so check if group is shutdown
- if (fdToChannel.isEmpty())
- checkForShutdown = true;
-
- } finally {
- fdToChannelLock.writeLock().unlock();
- }
-
- // continue shutdown
- if (checkForShutdown && isShutdown()) {
- try {
- shutdownNow();
- } catch (IOException ignore) { }
- }
- }
- /**
- * Register file descriptor with polling mechanism for given events.
- * The implementation should translate the events as required.
- */
- abstract void startPoll(int fd, int events);
-
- @Override
- final boolean isEmpty() {
- fdToChannelLock.writeLock().lock();
- try {
- return fdToChannel.isEmpty();
- } finally {
- fdToChannelLock.writeLock().unlock();
- }
- }
-
- @Override
- final Object attachForeignChannel(final Channel channel, FileDescriptor fd) {
- int fdVal = IOUtil.fdVal(fd);
- register(fdVal, new PollableChannel() {
- public void onEvent(int events, boolean mayInvokeDirect) { }
- public void close() throws IOException {
- channel.close();
- }
- });
- return Integer.valueOf(fdVal);
- }
-
- @Override
- final void detachForeignChannel(Object key) {
- unregister((Integer)key);
- }
-
- @Override
- final void closeAllChannels() {
- /**
- * Close channels in batches of up to 128 channels. This allows close
- * to remove the channel from the map without interference.
- */
- final int MAX_BATCH_SIZE = 128;
- PollableChannel channels[] = new PollableChannel[MAX_BATCH_SIZE];
- int count;
- do {
- // grab a batch of up to 128 channels
- fdToChannelLock.writeLock().lock();
- count = 0;
- try {
- for (Integer fd: fdToChannel.keySet()) {
- channels[count++] = fdToChannel.get(fd);
- if (count >= MAX_BATCH_SIZE)
- break;
- }
- } finally {
- fdToChannelLock.writeLock().unlock();
- }
-
- // close them
- for (int i=0; i<count; i++) {
- try {
- channels[i].close();
- } catch (IOException ignore) { }
- }
- } while (count > 0);
- }
-}
diff --git a/ojluni/src/main/java/sun/nio/ch/UnixAsynchronousServerSocketChannelImpl.java b/ojluni/src/main/java/sun/nio/ch/UnixAsynchronousServerSocketChannelImpl.java
deleted file mode 100755
index 3b431e7..0000000
--- a/ojluni/src/main/java/sun/nio/ch/UnixAsynchronousServerSocketChannelImpl.java
+++ /dev/null
@@ -1,351 +0,0 @@
-/*
- * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.nio.ch;
-
-import java.nio.channels.*;
-import java.util.concurrent.*;
-import java.io.IOException;
-import java.io.FileDescriptor;
-import java.net.InetSocketAddress;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.security.AccessControlContext;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-
-/**
- * Unix implementation of AsynchronousServerSocketChannel
- */
-
-class UnixAsynchronousServerSocketChannelImpl
- extends AsynchronousServerSocketChannelImpl
- implements Port.PollableChannel
-{
- private final static NativeDispatcher nd = new SocketDispatcher();
-
- private final Port port;
- private final int fdVal;
-
- // flag to indicate an accept is outstanding
- private final AtomicBoolean accepting = new AtomicBoolean();
- private void enableAccept() {
- accepting.set(false);
- }
-
- // used to ensure that the context for an asynchronous accept is visible
- // the pooled thread that handles the I/O event
- private final Object updateLock = new Object();
-
- // pending accept
- private boolean acceptPending;
- private CompletionHandler<AsynchronousSocketChannel,Object> acceptHandler;
- private Object acceptAttachment;
- private PendingFuture<AsynchronousSocketChannel,Object> acceptFuture;
-
- // context for permission check when security manager set
- private AccessControlContext acceptAcc;
-
-
- UnixAsynchronousServerSocketChannelImpl(Port port)
- throws IOException
- {
- super(port);
-
- try {
- IOUtil.configureBlocking(fd, false);
- } catch (IOException x) {
- nd.close(fd); // prevent leak
- throw x;
- }
- this.port = port;
- this.fdVal = IOUtil.fdVal(fd);
-
- // add mapping from file descriptor to this channel
- port.register(fdVal, this);
- }
-
- @Override
- void implClose() throws IOException {
- // remove the mapping
- port.unregister(fdVal);
-
- // close file descriptor
- nd.close(fd);
-
- // if there is a pending accept then complete it
- CompletionHandler<AsynchronousSocketChannel,Object> handler;
- Object att;
- PendingFuture<AsynchronousSocketChannel,Object> future;
- synchronized (updateLock) {
- if (!acceptPending)
- return; // no pending accept
- acceptPending = false;
- handler = acceptHandler;
- att = acceptAttachment;
- future = acceptFuture;
- }
-
- // discard the stack trace as otherwise it may appear that implClose
- // has thrown the exception.
- AsynchronousCloseException x = new AsynchronousCloseException();
- x.setStackTrace(new StackTraceElement[0]);
- if (handler == null) {
- future.setFailure(x);
- } else {
- // invoke by submitting task rather than directly
- Invoker.invokeIndirectly(this, handler, att, null, x);
- }
- }
-
- @Override
- public AsynchronousChannelGroupImpl group() {
- return port;
- }
-
- /**
- * Invoked by event handling thread when listener socket is polled
- */
- @Override
- public void onEvent(int events, boolean mayInvokeDirect) {
- synchronized (updateLock) {
- if (!acceptPending)
- return; // may have been grabbed by asynchronous close
- acceptPending = false;
- }
-
- // attempt to accept connection
- FileDescriptor newfd = new FileDescriptor();
- InetSocketAddress[] isaa = new InetSocketAddress[1];
- Throwable exc = null;
- try {
- begin();
- int n = accept0(this.fd, newfd, isaa);
-
- // spurious wakeup, is this possible?
- if (n == IOStatus.UNAVAILABLE) {
- synchronized (updateLock) {
- acceptPending = true;
- }
- port.startPoll(fdVal, Port.POLLIN);
- return;
- }
-
- } catch (Throwable x) {
- if (x instanceof ClosedChannelException)
- x = new AsynchronousCloseException();
- exc = x;
- } finally {
- end();
- }
-
- // Connection accepted so finish it when not holding locks.
- AsynchronousSocketChannel child = null;
- if (exc == null) {
- try {
- child = finishAccept(newfd, isaa[0], acceptAcc);
- } catch (Throwable x) {
- if (!(x instanceof IOException) && !(x instanceof SecurityException))
- x = new IOException(x);
- exc = x;
- }
- }
-
- // copy field befores accept is re-renabled
- CompletionHandler<AsynchronousSocketChannel,Object> handler = acceptHandler;
- Object att = acceptAttachment;
- PendingFuture<AsynchronousSocketChannel,Object> future = acceptFuture;
-
- // re-enable accepting and invoke handler
- enableAccept();
-
- if (handler == null) {
- future.setResult(child, exc);
- // if an async cancel has already cancelled the operation then
- // close the new channel so as to free resources
- if (child != null && future.isCancelled()) {
- try {
- child.close();
- } catch (IOException ignore) { }
- }
- } else {
- Invoker.invoke(this, handler, att, child, exc);
- }
- }
-
- /**
- * Completes the accept by creating the AsynchronousSocketChannel for
- * the given file descriptor and remote address. If this method completes
- * with an IOException or SecurityException then the channel/file descriptor
- * will be closed.
- */
- private AsynchronousSocketChannel finishAccept(FileDescriptor newfd,
- final InetSocketAddress remote,
- AccessControlContext acc)
- throws IOException, SecurityException
- {
- AsynchronousSocketChannel ch = null;
- try {
- ch = new UnixAsynchronousSocketChannelImpl(port, newfd, remote);
- } catch (IOException x) {
- nd.close(newfd);
- throw x;
- }
-
- // permission check must always be in initiator's context
- try {
- if (acc != null) {
- AccessController.doPrivileged(new PrivilegedAction<Void>() {
- public Void run() {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkAccept(remote.getAddress().getHostAddress(),
- remote.getPort());
- }
- return null;
- }
- }, acc);
- } else {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkAccept(remote.getAddress().getHostAddress(),
- remote.getPort());
- }
- }
- } catch (SecurityException x) {
- try {
- ch.close();
- } catch (Throwable suppressed) {
- x.addSuppressed(suppressed);
- }
- throw x;
- }
- return ch;
- }
-
- @Override
- Future<AsynchronousSocketChannel> implAccept(Object att,
- CompletionHandler<AsynchronousSocketChannel,Object> handler)
- {
- // complete immediately if channel is closed
- if (!isOpen()) {
- Throwable e = new ClosedChannelException();
- if (handler == null) {
- return CompletedFuture.withFailure(e);
- } else {
- Invoker.invoke(this, handler, att, null, e);
- return null;
- }
- }
- if (localAddress == null)
- throw new NotYetBoundException();
-
- // cancel was invoked with pending accept so connection may have been
- // dropped.
- if (isAcceptKilled())
- throw new RuntimeException("Accept not allowed due cancellation");
-
- // check and set flag to prevent concurrent accepting
- if (!accepting.compareAndSet(false, true))
- throw new AcceptPendingException();
-
- // attempt accept
- FileDescriptor newfd = new FileDescriptor();
- InetSocketAddress[] isaa = new InetSocketAddress[1];
- Throwable exc = null;
- try {
- begin();
-
- int n = accept0(this.fd, newfd, isaa);
- if (n == IOStatus.UNAVAILABLE) {
-
- // need calling context when there is security manager as
- // permission check may be done in a different thread without
- // any application call frames on the stack
- PendingFuture<AsynchronousSocketChannel,Object> result = null;
- synchronized (updateLock) {
- if (handler == null) {
- this.acceptHandler = null;
- result = new PendingFuture<AsynchronousSocketChannel,Object>(this);
- this.acceptFuture = result;
- } else {
- this.acceptHandler = handler;
- this.acceptAttachment = att;
- }
- this.acceptAcc = (System.getSecurityManager() == null) ?
- null : AccessController.getContext();
- this.acceptPending = true;
- }
-
- // register for connections
- port.startPoll(fdVal, Port.POLLIN);
- return result;
- }
- } catch (Throwable x) {
- // accept failed
- if (x instanceof ClosedChannelException)
- x = new AsynchronousCloseException();
- exc = x;
- } finally {
- end();
- }
-
- AsynchronousSocketChannel child = null;
- if (exc == null) {
- // connection accepted immediately
- try {
- child = finishAccept(newfd, isaa[0], null);
- } catch (Throwable x) {
- exc = x;
- }
- }
-
- // re-enable accepting before invoking handler
- enableAccept();
-
- if (handler == null) {
- return CompletedFuture.withResult(child, exc);
- } else {
- Invoker.invokeIndirectly(this, handler, att, child, exc);
- return null;
- }
- }
-
- // -- Native methods --
-
- private static native void initIDs();
-
- // Accepts a new connection, setting the given file descriptor to refer to
- // the new socket and setting isaa[0] to the socket's remote address.
- // Returns 1 on success, or IOStatus.UNAVAILABLE.
- //
- private native int accept0(FileDescriptor ssfd, FileDescriptor newfd,
- InetSocketAddress[] isaa)
- throws IOException;
-
- static {
- Util.load();
- initIDs();
- }
-}
diff --git a/ojluni/src/main/java/sun/nio/ch/UnixAsynchronousSocketChannelImpl.java b/ojluni/src/main/java/sun/nio/ch/UnixAsynchronousSocketChannelImpl.java
deleted file mode 100755
index 8b74488..0000000
--- a/ojluni/src/main/java/sun/nio/ch/UnixAsynchronousSocketChannelImpl.java
+++ /dev/null
@@ -1,753 +0,0 @@
-/*
- * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.nio.ch;
-
-import java.nio.channels.*;
-import java.nio.ByteBuffer;
-import java.net.*;
-import java.util.concurrent.*;
-import java.io.IOException;
-import java.io.FileDescriptor;
-import java.security.AccessController;
-import sun.net.NetHooks;
-import sun.security.action.GetPropertyAction;
-
-/**
- * Unix implementation of AsynchronousSocketChannel
- */
-
-class UnixAsynchronousSocketChannelImpl
- extends AsynchronousSocketChannelImpl implements Port.PollableChannel
-{
- private final static NativeDispatcher nd = new SocketDispatcher();
- private static enum OpType { CONNECT, READ, WRITE };
-
- private static final boolean disableSynchronousRead;
- static {
- String propValue = AccessController.doPrivileged(
- new GetPropertyAction("sun.nio.ch.disableSynchronousRead", "false"));
- disableSynchronousRead = (propValue.length() == 0) ?
- true : Boolean.valueOf(propValue);
- }
-
- private final Port port;
- private final int fdVal;
-
- // used to ensure that the context for I/O operations that complete
- // ascynrhonously is visible to the pooled threads handling I/O events.
- private final Object updateLock = new Object();
-
- // pending connect (updateLock)
- private boolean connectPending;
- private CompletionHandler<Void,Object> connectHandler;
- private Object connectAttachment;
- private PendingFuture<Void,Object> connectFuture;
-
- // pending remote address (stateLock)
- private SocketAddress pendingRemote;
-
- // pending read (updateLock)
- private boolean readPending;
- private boolean isScatteringRead;
- private ByteBuffer readBuffer;
- private ByteBuffer[] readBuffers;
- private CompletionHandler<Number,Object> readHandler;
- private Object readAttachment;
- private PendingFuture<Number,Object> readFuture;
- private Future<?> readTimer;
-
- // pending write (updateLock)
- private boolean writePending;
- private boolean isGatheringWrite;
- private ByteBuffer writeBuffer;
- private ByteBuffer[] writeBuffers;
- private CompletionHandler<Number,Object> writeHandler;
- private Object writeAttachment;
- private PendingFuture<Number,Object> writeFuture;
- private Future<?> writeTimer;
-
-
- UnixAsynchronousSocketChannelImpl(Port port)
- throws IOException
- {
- super(port);
-
- // set non-blocking
- try {
- IOUtil.configureBlocking(fd, false);
- } catch (IOException x) {
- nd.close(fd);
- throw x;
- }
-
- this.port = port;
- this.fdVal = IOUtil.fdVal(fd);
-
- // add mapping from file descriptor to this channel
- port.register(fdVal, this);
- }
-
- // Constructor for sockets created by UnixAsynchronousServerSocketChannelImpl
- UnixAsynchronousSocketChannelImpl(Port port,
- FileDescriptor fd,
- InetSocketAddress remote)
- throws IOException
- {
- super(port, fd, remote);
-
- this.fdVal = IOUtil.fdVal(fd);
- IOUtil.configureBlocking(fd, false);
-
- try {
- port.register(fdVal, this);
- } catch (ShutdownChannelGroupException x) {
- // ShutdownChannelGroupException thrown if we attempt to register a
- // new channel after the group is shutdown
- throw new IOException(x);
- }
-
- this.port = port;
- }
-
- @Override
- public AsynchronousChannelGroupImpl group() {
- return port;
- }
-
- // register events for outstanding I/O operations, caller already owns updateLock
- private void updateEvents() {
- assert Thread.holdsLock(updateLock);
- int events = 0;
- if (readPending)
- events |= Port.POLLIN;
- if (connectPending || writePending)
- events |= Port.POLLOUT;
- if (events != 0)
- port.startPoll(fdVal, events);
- }
-
- // register events for outstanding I/O operations
- private void lockAndUpdateEvents() {
- synchronized (updateLock) {
- updateEvents();
- }
- }
-
- // invoke to finish read and/or write operations
- private void finish(boolean mayInvokeDirect,
- boolean readable,
- boolean writable)
- {
- boolean finishRead = false;
- boolean finishWrite = false;
- boolean finishConnect = false;
-
- // map event to pending result
- synchronized (updateLock) {
- if (readable && this.readPending) {
- this.readPending = false;
- finishRead = true;
- }
- if (writable) {
- if (this.writePending) {
- this.writePending = false;
- finishWrite = true;
- } else if (this.connectPending) {
- this.connectPending = false;
- finishConnect = true;
- }
- }
- }
-
- // complete the I/O operation. Special case for when channel is
- // ready for both reading and writing. In that case, submit task to
- // complete write if write operation has a completion handler.
- if (finishRead) {
- if (finishWrite)
- finishWrite(false);
- finishRead(mayInvokeDirect);
- return;
- }
- if (finishWrite) {
- finishWrite(mayInvokeDirect);
- }
- if (finishConnect) {
- finishConnect(mayInvokeDirect);
- }
- }
-
- /**
- * Invoked by event handler thread when file descriptor is polled
- */
- @Override
- public void onEvent(int events, boolean mayInvokeDirect) {
- boolean readable = (events & Port.POLLIN) > 0;
- boolean writable = (events & Port.POLLOUT) > 0;
- if ((events & (Port.POLLERR | Port.POLLHUP)) > 0) {
- readable = true;
- writable = true;
- }
- finish(mayInvokeDirect, readable, writable);
- }
-
- @Override
- void implClose() throws IOException {
- // remove the mapping
- port.unregister(fdVal);
-
- // close file descriptor
- nd.close(fd);
-
- // All outstanding I/O operations are required to fail
- finish(false, true, true);
- }
-
- @Override
- public void onCancel(PendingFuture<?,?> task) {
- if (task.getContext() == OpType.CONNECT)
- killConnect();
- if (task.getContext() == OpType.READ)
- killReading();
- if (task.getContext() == OpType.WRITE)
- killWriting();
- }
-
- // -- connect --
-
- private void setConnected() throws IOException {
- synchronized (stateLock) {
- state = ST_CONNECTED;
- localAddress = Net.localAddress(fd);
- remoteAddress = (InetSocketAddress)pendingRemote;
- }
- }
-
- private void finishConnect(boolean mayInvokeDirect) {
- Throwable e = null;
- try {
- begin();
- checkConnect(fdVal);
- setConnected();
- } catch (Throwable x) {
- if (x instanceof ClosedChannelException)
- x = new AsynchronousCloseException();
- e = x;
- } finally {
- end();
- }
- if (e != null) {
- // close channel if connection cannot be established
- try {
- close();
- } catch (Throwable suppressed) {
- e.addSuppressed(suppressed);
- }
- }
-
- // invoke handler and set result
- CompletionHandler<Void,Object> handler = connectHandler;
- Object att = connectAttachment;
- PendingFuture<Void,Object> future = connectFuture;
- if (handler == null) {
- future.setResult(null, e);
- } else {
- if (mayInvokeDirect) {
- Invoker.invokeUnchecked(handler, att, null, e);
- } else {
- Invoker.invokeIndirectly(this, handler, att, null, e);
- }
- }
- }
-
- @Override
- @SuppressWarnings("unchecked")
- <A> Future<Void> implConnect(SocketAddress remote,
- A attachment,
- CompletionHandler<Void,? super A> handler)
- {
- if (!isOpen()) {
- Throwable e = new ClosedChannelException();
- if (handler == null) {
- return CompletedFuture.withFailure(e);
- } else {
- Invoker.invoke(this, handler, attachment, null, e);
- return null;
- }
- }
-
- InetSocketAddress isa = Net.checkAddress(remote);
-
- // permission check
- SecurityManager sm = System.getSecurityManager();
- if (sm != null)
- sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort());
-
- // check and set state
- boolean notifyBeforeTcpConnect;
- synchronized (stateLock) {
- if (state == ST_CONNECTED)
- throw new AlreadyConnectedException();
- if (state == ST_PENDING)
- throw new ConnectionPendingException();
- state = ST_PENDING;
- pendingRemote = remote;
- notifyBeforeTcpConnect = (localAddress == null);
- }
-
- Throwable e = null;
- try {
- begin();
- // notify hook if unbound
- if (notifyBeforeTcpConnect)
- NetHooks.beforeTcpConnect(fd, isa.getAddress(), isa.getPort());
- int n = Net.connect(fd, isa.getAddress(), isa.getPort());
- if (n == IOStatus.UNAVAILABLE) {
- // connection could not be established immediately
- PendingFuture<Void,A> result = null;
- synchronized (updateLock) {
- if (handler == null) {
- result = new PendingFuture<Void,A>(this, OpType.CONNECT);
- this.connectFuture = (PendingFuture<Void,Object>)result;
- } else {
- this.connectHandler = (CompletionHandler<Void,Object>)handler;
- this.connectAttachment = attachment;
- }
- this.connectPending = true;
- updateEvents();
- }
- return result;
- }
- setConnected();
- } catch (Throwable x) {
- if (x instanceof ClosedChannelException)
- x = new AsynchronousCloseException();
- e = x;
- } finally {
- end();
- }
-
- // close channel if connect fails
- if (e != null) {
- try {
- close();
- } catch (Throwable suppressed) {
- e.addSuppressed(suppressed);
- }
- }
- if (handler == null) {
- return CompletedFuture.withResult(null, e);
- } else {
- Invoker.invoke(this, handler, attachment, null, e);
- return null;
- }
- }
-
- // -- read --
-
- private void finishRead(boolean mayInvokeDirect) {
- int n = -1;
- Throwable exc = null;
-
- // copy fields as we can't access them after reading is re-enabled.
- boolean scattering = isScatteringRead;
- CompletionHandler<Number,Object> handler = readHandler;
- Object att = readAttachment;
- PendingFuture<Number,Object> future = readFuture;
- Future<?> timeout = readTimer;
-
- try {
- begin();
-
- if (scattering) {
- n = (int)IOUtil.read(fd, readBuffers, nd);
- } else {
- n = IOUtil.read(fd, readBuffer, -1, nd);
- }
- if (n == IOStatus.UNAVAILABLE) {
- // spurious wakeup, is this possible?
- synchronized (updateLock) {
- readPending = true;
- }
- return;
- }
-
- // allow objects to be GC'ed.
- this.readBuffer = null;
- this.readBuffers = null;
- this.readAttachment = null;
-
- // allow another read to be initiated
- enableReading();
-
- } catch (Throwable x) {
- enableReading();
- if (x instanceof ClosedChannelException)
- x = new AsynchronousCloseException();
- exc = x;
- } finally {
- // restart poll in case of concurrent write
- if (!(exc instanceof AsynchronousCloseException))
- lockAndUpdateEvents();
- end();
- }
-
- // cancel the associated timer
- if (timeout != null)
- timeout.cancel(false);
-
- // create result
- Number result = (exc != null) ? null : (scattering) ?
- (Number)Long.valueOf(n) : (Number)Integer.valueOf(n);
-
- // invoke handler or set result
- if (handler == null) {
- future.setResult(result, exc);
- } else {
- if (mayInvokeDirect) {
- Invoker.invokeUnchecked(handler, att, result, exc);
- } else {
- Invoker.invokeIndirectly(this, handler, att, result, exc);
- }
- }
- }
-
- private Runnable readTimeoutTask = new Runnable() {
- public void run() {
- CompletionHandler<Number,Object> handler = null;
- Object att = null;
- PendingFuture<Number,Object> future = null;
-
- synchronized (updateLock) {
- if (!readPending)
- return;
- readPending = false;
- handler = readHandler;
- att = readAttachment;
- future = readFuture;
- }
-
- // kill further reading before releasing waiters
- enableReading(true);
-
- // invoke handler or set result
- Exception exc = new InterruptedByTimeoutException();
- if (handler == null) {
- future.setFailure(exc);
- } else {
- AsynchronousChannel ch = UnixAsynchronousSocketChannelImpl.this;
- Invoker.invokeIndirectly(ch, handler, att, null, exc);
- }
- }
- };
-
- /**
- * Initiates a read or scattering read operation
- */
- @Override
- @SuppressWarnings("unchecked")
- <V extends Number,A> Future<V> implRead(boolean isScatteringRead,
- ByteBuffer dst,
- ByteBuffer[] dsts,
- long timeout,
- TimeUnit unit,
- A attachment,
- CompletionHandler<V,? super A> handler)
- {
- // A synchronous read is not attempted if disallowed by system property
- // or, we are using a fixed thread pool and the completion handler may
- // not be invoked directly (because the thread is not a pooled thread or
- // there are too many handlers on the stack).
- Invoker.GroupAndInvokeCount myGroupAndInvokeCount = null;
- boolean invokeDirect = false;
- boolean attemptRead = false;
- if (!disableSynchronousRead) {
- if (handler == null) {
- attemptRead = true;
- } else {
- myGroupAndInvokeCount = Invoker.getGroupAndInvokeCount();
- invokeDirect = Invoker.mayInvokeDirect(myGroupAndInvokeCount, port);
- // okay to attempt read with user thread pool
- attemptRead = invokeDirect || !port.isFixedThreadPool();
- }
- }
-
- int n = IOStatus.UNAVAILABLE;
- Throwable exc = null;
- boolean pending = false;
-
- try {
- begin();
-
- if (attemptRead) {
- if (isScatteringRead) {
- n = (int)IOUtil.read(fd, dsts, nd);
- } else {
- n = IOUtil.read(fd, dst, -1, nd);
- }
- }
-
- if (n == IOStatus.UNAVAILABLE) {
- PendingFuture<V,A> result = null;
- synchronized (updateLock) {
- this.isScatteringRead = isScatteringRead;
- this.readBuffer = dst;
- this.readBuffers = dsts;
- if (handler == null) {
- this.readHandler = null;
- result = new PendingFuture<V,A>(this, OpType.READ);
- this.readFuture = (PendingFuture<Number,Object>)result;
- this.readAttachment = null;
- } else {
- this.readHandler = (CompletionHandler<Number,Object>)handler;
- this.readAttachment = attachment;
- this.readFuture = null;
- }
- if (timeout > 0L) {
- this.readTimer = port.schedule(readTimeoutTask, timeout, unit);
- }
- this.readPending = true;
- updateEvents();
- }
- pending = true;
- return result;
- }
- } catch (Throwable x) {
- if (x instanceof ClosedChannelException)
- x = new AsynchronousCloseException();
- exc = x;
- } finally {
- if (!pending)
- enableReading();
- end();
- }
-
- Number result = (exc != null) ? null : (isScatteringRead) ?
- (Number)Long.valueOf(n) : (Number)Integer.valueOf(n);
-
- // read completed immediately
- if (handler != null) {
- if (invokeDirect) {
- Invoker.invokeDirect(myGroupAndInvokeCount, handler, attachment, (V)result, exc);
- } else {
- Invoker.invokeIndirectly(this, handler, attachment, (V)result, exc);
- }
- return null;
- } else {
- return CompletedFuture.withResult((V)result, exc);
- }
- }
-
- // -- write --
-
- private void finishWrite(boolean mayInvokeDirect) {
- int n = -1;
- Throwable exc = null;
-
- // copy fields as we can't access them after reading is re-enabled.
- boolean gathering = this.isGatheringWrite;
- CompletionHandler<Number,Object> handler = this.writeHandler;
- Object att = this.writeAttachment;
- PendingFuture<Number,Object> future = this.writeFuture;
- Future<?> timer = this.writeTimer;
-
- try {
- begin();
-
- if (gathering) {
- n = (int)IOUtil.write(fd, writeBuffers, nd);
- } else {
- n = IOUtil.write(fd, writeBuffer, -1, nd);
- }
- if (n == IOStatus.UNAVAILABLE) {
- // spurious wakeup, is this possible?
- synchronized (updateLock) {
- writePending = true;
- }
- return;
- }
-
- // allow objects to be GC'ed.
- this.writeBuffer = null;
- this.writeBuffers = null;
- this.writeAttachment = null;
-
- // allow another write to be initiated
- enableWriting();
-
- } catch (Throwable x) {
- enableWriting();
- if (x instanceof ClosedChannelException)
- x = new AsynchronousCloseException();
- exc = x;
- } finally {
- // restart poll in case of concurrent write
- if (!(exc instanceof AsynchronousCloseException))
- lockAndUpdateEvents();
- end();
- }
-
- // cancel the associated timer
- if (timer != null)
- timer.cancel(false);
-
- // create result
- Number result = (exc != null) ? null : (gathering) ?
- (Number)Long.valueOf(n) : (Number)Integer.valueOf(n);
-
- // invoke handler or set result
- if (handler == null) {
- future.setResult(result, exc);
- } else {
- if (mayInvokeDirect) {
- Invoker.invokeUnchecked(handler, att, result, exc);
- } else {
- Invoker.invokeIndirectly(this, handler, att, result, exc);
- }
- }
- }
-
- private Runnable writeTimeoutTask = new Runnable() {
- public void run() {
- CompletionHandler<Number,Object> handler = null;
- Object att = null;
- PendingFuture<Number,Object> future = null;
-
- synchronized (updateLock) {
- if (!writePending)
- return;
- writePending = false;
- handler = writeHandler;
- att = writeAttachment;
- future = writeFuture;
- }
-
- // kill further writing before releasing waiters
- enableWriting(true);
-
- // invoke handler or set result
- Exception exc = new InterruptedByTimeoutException();
- if (handler != null) {
- Invoker.invokeIndirectly(UnixAsynchronousSocketChannelImpl.this,
- handler, att, null, exc);
- } else {
- future.setFailure(exc);
- }
- }
- };
-
- /**
- * Initiates a read or scattering read operation
- */
- @Override
- @SuppressWarnings("unchecked")
- <V extends Number,A> Future<V> implWrite(boolean isGatheringWrite,
- ByteBuffer src,
- ByteBuffer[] srcs,
- long timeout,
- TimeUnit unit,
- A attachment,
- CompletionHandler<V,? super A> handler)
- {
- Invoker.GroupAndInvokeCount myGroupAndInvokeCount =
- Invoker.getGroupAndInvokeCount();
- boolean invokeDirect = Invoker.mayInvokeDirect(myGroupAndInvokeCount, port);
- boolean attemptWrite = (handler == null) || invokeDirect ||
- !port.isFixedThreadPool(); // okay to attempt write with user thread pool
-
- int n = IOStatus.UNAVAILABLE;
- Throwable exc = null;
- boolean pending = false;
-
- try {
- begin();
-
- if (attemptWrite) {
- if (isGatheringWrite) {
- n = (int)IOUtil.write(fd, srcs, nd);
- } else {
- n = IOUtil.write(fd, src, -1, nd);
- }
- }
-
- if (n == IOStatus.UNAVAILABLE) {
- PendingFuture<V,A> result = null;
- synchronized (updateLock) {
- this.isGatheringWrite = isGatheringWrite;
- this.writeBuffer = src;
- this.writeBuffers = srcs;
- if (handler == null) {
- this.writeHandler = null;
- result = new PendingFuture<V,A>(this, OpType.WRITE);
- this.writeFuture = (PendingFuture<Number,Object>)result;
- this.writeAttachment = null;
- } else {
- this.writeHandler = (CompletionHandler<Number,Object>)handler;
- this.writeAttachment = attachment;
- this.writeFuture = null;
- }
- if (timeout > 0L) {
- this.writeTimer = port.schedule(writeTimeoutTask, timeout, unit);
- }
- this.writePending = true;
- updateEvents();
- }
- pending = true;
- return result;
- }
- } catch (Throwable x) {
- if (x instanceof ClosedChannelException)
- x = new AsynchronousCloseException();
- exc = x;
- } finally {
- if (!pending)
- enableWriting();
- end();
- }
-
- Number result = (exc != null) ? null : (isGatheringWrite) ?
- (Number)Long.valueOf(n) : (Number)Integer.valueOf(n);
-
- // write completed immediately
- if (handler != null) {
- if (invokeDirect) {
- Invoker.invokeDirect(myGroupAndInvokeCount, handler, attachment, (V)result, exc);
- } else {
- Invoker.invokeIndirectly(this, handler, attachment, (V)result, exc);
- }
- return null;
- } else {
- return CompletedFuture.withResult((V)result, exc);
- }
- }
-
- // -- Native methods --
-
- private static native void checkConnect(int fdVal) throws IOException;
-
- static {
- Util.load();
- }
-}
diff --git a/ojluni/src/main/native/NetworkInterface.c b/ojluni/src/main/native/NetworkInterface.c
index 83ab1b8..0c98458 100755
--- a/ojluni/src/main/native/NetworkInterface.c
+++ b/ojluni/src/main/native/NetworkInterface.c
@@ -37,37 +37,13 @@
#include <arpa/inet.h>
#include <net/if.h>
#include <net/if_arp.h>
+#include <linux/if_packet.h>
-#ifdef __solaris__
-#include <sys/dlpi.h>
-#include <fcntl.h>
-#include <stropts.h>
-#include <sys/sockio.h>
-#endif
-
-#ifdef __linux__
#include <sys/ioctl.h>
//#include <bits/ioctls.h>
#include <sys/utsname.h>
#include <stdio.h>
-#endif
-
-#ifdef __linux__
-#define _PATH_PROCNET_IFINET6 "/proc/net/if_inet6"
-#endif
-
-#if defined(_ALLBSD_SOURCE)
-#include <sys/param.h>
-#include <sys/ioctl.h>
-#include <sys/sockio.h>
-#if defined(__APPLE__)
-#include <net/ethernet.h>
-#include <net/if_var.h>
-#include <net/if_dl.h>
-#include <netinet/in_var.h>
#include <ifaddrs.h>
-#endif
-#endif
#include "jvm.h"
#include "jni_util.h"
@@ -89,6 +65,9 @@
char *name;
int index;
char virtual;
+
+ uint8_t hwAddrLen;
+ uint8_t *hwAddr;
netaddr *addr;
struct _netif *childs;
struct _netif *next;
@@ -112,6 +91,7 @@
jfieldID ni_childsID;
jfieldID ni_parentID;
jfieldID ni_defaultIndexID;
+jfieldID ni_hardwareAddrID;
jmethodID ni_ctrID;
static jclass ni_iacls;
@@ -131,39 +111,18 @@
static int getFlags0(JNIEnv *env, jstring ifname);
static netif *enumInterfaces(JNIEnv *env);
-static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs);
-#ifdef AF_INET6
-static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs);
-#endif
-
-static netif *addif(JNIEnv *env, int sock, const char * if_name, netif *ifs, struct sockaddr* ifr_addrP, int family, short prefix);
+static netif *addif(JNIEnv *env, int sock, struct ifaddrs *ifa, netif *ifs);
static void freeif(netif *ifs);
static int openSocket(JNIEnv *env, int proto);
static int openSocketWithFallback(JNIEnv *env, const char *ifname);
-
-static struct sockaddr *getBroadcast(JNIEnv *env, int sock, const char *name, struct sockaddr *brdcast_store);
-static short getSubnet(JNIEnv *env, int sock, const char *ifname);
static int getIndex(int sock, const char *ifname);
static int getFlags(int sock, const char *ifname, int *flags);
-static int getMacAddress(JNIEnv *env, int sock, const char* ifname, const struct in_addr* addr, unsigned char *buf);
static int getMTU(JNIEnv *env, int sock, const char *ifname);
-
-
-#ifdef __solaris__
-static netif *enumIPvXInterfaces(JNIEnv *env, int sock, netif *ifs, int family);
-static int getMacFromDevice(JNIEnv *env, const char* ifname, unsigned char* retbuf);
-
-#ifndef SIOCGLIFHWADDR
-#define SIOCGLIFHWADDR _IOWR('i', 192, struct lifreq)
-#endif
-
-#endif
-
/******************* Java entry points *****************************/
/*
@@ -183,6 +142,7 @@
ni_virutalID = (*env)->GetFieldID(env, ni_class, "virtual", "Z");
ni_childsID = (*env)->GetFieldID(env, ni_class, "childs", "[Ljava/net/NetworkInterface;");
ni_parentID = (*env)->GetFieldID(env, ni_class, "parent", "Ljava/net/NetworkInterface;");
+ ni_hardwareAddrID = (*env)->GetFieldID(env, ni_class, "hardwareAddr", "[B");
ni_ctrID = (*env)->GetMethodID(env, ni_class, "<init>", "()V");
ni_iacls = (*env)->FindClass(env, "java/net/InetAddress");
@@ -298,11 +258,7 @@
netif *ifs, *curr;
-#ifdef AF_INET6
int family = (getInetAddress_family(env, iaObj) == IPv4) ? AF_INET : AF_INET6;
-#else
- int family = AF_INET;
-#endif
jobject obj = NULL;
jboolean match = JNI_FALSE;
@@ -332,7 +288,6 @@
}
}
-#ifdef AF_INET6
if (family == AF_INET6) {
jbyte *bytes = (jbyte *)&(((struct sockaddr_in6*)addrP->addr)->sin6_addr);
jbyteArray ipaddress = (*env)->GetObjectField(env, iaObj, ni_ia6ipaddressID);
@@ -352,8 +307,6 @@
break;
}
}
-#endif
-
}
if (match) {
@@ -477,57 +430,6 @@
}
/*
- * Class: java_net_NetworkInterface
- * Method: getMacAddr0
- * Signature: ([bLjava/lang/String;I)[b
- */
-JNIEXPORT jbyteArray JNICALL NetworkInterface_getMacAddr0(JNIEnv *env, jclass class, jbyteArray addrArray, jstring name, jint index) {
- jint addr;
- jbyte caddr[4];
- struct in_addr iaddr;
- jbyteArray ret = NULL;
- unsigned char mac[16];
- int len;
- int sock;
- jboolean isCopy;
- const char* name_utf;
-
- name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
-
- if ((sock =openSocketWithFallback(env, name_utf)) < 0) {
- (*env)->ReleaseStringUTFChars(env, name, name_utf);
- return JNI_FALSE;
- }
-
-
- if (!IS_NULL(addrArray)) {
- (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
- addr = ((caddr[0]<<24) & 0xff000000);
- addr |= ((caddr[1] <<16) & 0xff0000);
- addr |= ((caddr[2] <<8) & 0xff00);
- addr |= (caddr[3] & 0xff);
- iaddr.s_addr = htonl(addr);
- len = getMacAddress(env, sock, name_utf, &iaddr, mac);
- } else {
- len = getMacAddress(env, sock, name_utf,NULL, mac);
- }
- if (len > 0) {
- ret = (*env)->NewByteArray(env, len);
- if (IS_NULL(ret)) {
- /* we may have memory to free at the end of this */
- goto fexit;
- }
- (*env)->SetByteArrayRegion(env, ret, 0, len, (jbyte *) (mac));
- }
-fexit:
- /* release the UTF string and interface list */
- (*env)->ReleaseStringUTFChars(env, name, name_utf);
-
- close(sock);
- return ret;
-}
-
-/*
* Class: java_net_NetworkInterface
* Method: getMTU0
* Signature: ([bLjava/lang/String;I)I
@@ -619,6 +521,18 @@
(*env)->SetBooleanField(env, netifObj, ni_virutalID, ifs->virtual ? JNI_TRUE : JNI_FALSE);
/*
+ * Set the hardware address
+ */
+ if (ifs->hwAddrLen > 0 && ifs->hwAddr != NULL) {
+ jbyteArray hardwareAddr = (*env)->NewByteArray(env, ifs->hwAddrLen);
+ if (hardwareAddr == NULL) {
+ return NULL;
+ }
+ (*env)->SetByteArrayRegion(env, hardwareAddr, 0, ifs->hwAddrLen, (jbyte *)ifs->hwAddr);
+ (*env)->SetObjectField(env, netifObj, ni_hardwareAddrID, hardwareAddr);
+ }
+
+ /*
* Count the number of address on this interface
*/
addr_count = 0;
@@ -661,14 +575,13 @@
if (ia2Obj) {
setInetAddress_addr(env, ia2Obj, htonl(((struct sockaddr_in*)addrP->brdcast)->sin_addr.s_addr));
(*env)->SetObjectField(env, ibObj, ni_ib4broadcastID, ia2Obj);
- (*env)->SetShortField(env, ibObj, ni_ib4maskID, addrP->mask);
}
}
+ (*env)->SetShortField(env, ibObj, ni_ib4maskID, addrP->mask);
(*env)->SetObjectArrayElement(env, bindArr, bind_index++, ibObj);
}
}
-#ifdef AF_INET6
if (addrP->family == AF_INET6) {
int scope=0;
iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
@@ -696,7 +609,6 @@
(*env)->SetObjectArrayElement(env, bindArr, bind_index++, ibObj);
}
}
-#endif
if (iaObj == NULL) {
return NULL;
@@ -745,56 +657,54 @@
}
/*
+ * Determines the mask length for IPV4/v6 addresses.
+ */
+static
+int mask_address_to_mask_length(uint8_t *val, int size) {
+ int byte, bit, plen = 0;
+
+ for (byte = 0; byte < size && val[byte] == 0xff; byte++) {
+ plen += 8;
+ }
+ if (byte < size) {
+ for (bit = 7; bit > 0; bit--) {
+ if (val[byte] & (1 << bit)) plen++;
+ }
+ }
+ return plen;
+}
+
+/*
* Enumerates all interfaces
*/
static netif *enumInterfaces(JNIEnv *env) {
- netif *ifs;
- int sock;
+ netif *ifs = NULL;
+ struct ifaddrs *ifa, *origifa;
- /*
- * Enumerate IPv4 addresses
- */
-
- sock = openSocket(env, AF_INET);
+ int sock = openSocket(env, AF_INET);
if (sock < 0 && (*env)->ExceptionOccurred(env)) {
return NULL;
}
- ifs = enumIPv4Interfaces(env, sock, NULL);
- close(sock);
-
- if (ifs == NULL && (*env)->ExceptionOccurred(env)) {
+ if (getifaddrs(&origifa) != 0) {
+ NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException",
+ "getifaddrs() function failed");
return NULL;
}
- /* return partial list if exception occure in the middle of process ???*/
-
- /*
- * If IPv6 is available then enumerate IPv6 addresses.
- */
-#ifdef AF_INET6
-
- /* User can disable ipv6 expicitly by -Djava.net.preferIPv4Stack=true,
- * so we have to call ipv6_available()
- */
- if (ipv6_available()) {
-
- sock = openSocket(env, AF_INET6);
- if (sock < 0 && (*env)->ExceptionOccurred(env)) {
- freeif(ifs);
- return NULL;
+ for (ifa = origifa; ifa != NULL; ifa = ifa->ifa_next) {
+ if (ifa->ifa_addr != NULL) {
+ switch (ifa->ifa_addr->sa_family) {
+ case AF_PACKET:
+ case AF_INET:
+ case AF_INET6:
+ ifs = addif(env, sock, ifa, ifs);
+ break;
+ }
}
-
- ifs = enumIPv6Interfaces(env, sock, ifs);
- close(sock);
-
- if ((*env)->ExceptionOccurred(env)) {
- freeif(ifs);
- return NULL;
- }
-
}
-#endif
+
+ close(sock);
return ifs;
}
@@ -831,26 +741,25 @@
freeif(currif->childs);
}
+ /*
+ * Remove mac address
+ */
+ if (currif->hwAddr != NULL) {
+ free(currif->hwAddr);
+ }
+
ifs = currif->next;
free(currif);
currif = ifs;
}
}
-netif *addif(JNIEnv *env, int sock, const char * if_name,
- netif *ifs, struct sockaddr* ifr_addrP, int family,
- short prefix)
+netif *addif(JNIEnv *env, int sock, struct ifaddrs *ifa, netif *ifs)
{
netif *currif = ifs, *parent;
- netaddr *addrP;
+ netaddr *addrP = NULL;
-#ifdef LIFNAMSIZ
- int ifnam_size = LIFNAMSIZ;
- char name[LIFNAMSIZ], vname[LIFNAMSIZ];
-#else
- int ifnam_size = IFNAMSIZ;
char name[IFNAMSIZ], vname[IFNAMSIZ];
-#endif
char *name_colonP;
int mask;
@@ -865,39 +774,58 @@
* currently doesn't have any concept of physical vs.
* logical interfaces.
*/
- strncpy(name, if_name, ifnam_size);
- name[ifnam_size - 1] = '\0';
+ strncpy(name, ifa->ifa_name, sizeof(name));
+ name[sizeof(name) - 1] = '\0';
*vname = 0;
/*
* Create and populate the netaddr node. If allocation fails
* return an un-updated list.
*/
- /*Allocate for addr and brdcast at once*/
+ switch(ifa->ifa_addr->sa_family) {
+ case AF_INET:
+ addr_size = sizeof(struct sockaddr_in);
+ break;
+ case AF_INET6:
+ addr_size = sizeof(struct sockaddr_in6);
+ break;
+ case AF_PACKET:
+ // Don't add an address entry, will extract data to netif struct
+ addr_size = 0;
+ break;
+ default:
+ return NULL;
+ }
-#ifdef AF_INET6
- addr_size = (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6);
-#else
- addr_size = sizeof(struct sockaddr_in);
-#endif
+ if (addr_size > 0) {
+ /*Allocate for addr and brdcast at once*/
+ CHECKED_MALLOC3(addrP, netaddr *, sizeof(netaddr)+2*addr_size);
+ addrP->addr = (struct sockaddr *)( (char *) addrP+sizeof(netaddr) );
+ memcpy(addrP->addr, ifa->ifa_addr, addr_size);
- CHECKED_MALLOC3(addrP, netaddr *, sizeof(netaddr)+2*addr_size);
- addrP->addr = (struct sockaddr *)( (char *) addrP+sizeof(netaddr) );
- memcpy(addrP->addr, ifr_addrP, addr_size);
+ addrP->family = ifa->ifa_addr->sa_family;
+ addrP->next = 0;
- addrP->family = family;
- addrP->brdcast = NULL;
- addrP->mask = prefix;
- addrP->next = 0;
- if (family == AF_INET) {
- /*
- * Deal with brodcast addr & subnet mask
- */
- struct sockaddr * brdcast_to = (struct sockaddr *) ((char *) addrP + sizeof(netaddr) + addr_size);
- addrP->brdcast = getBroadcast(env, sock, name, brdcast_to );
+ if (ifa->ifa_broadaddr && (ifa->ifa_flags & IFF_BROADCAST)) {
+ struct sockaddr * brdcast_to = (struct sockaddr *) ((char *) addrP + sizeof(netaddr) + addr_size);
+ addrP->brdcast = brdcast_to;
+ memcpy(brdcast_to, ifa->ifa_broadaddr, sizeof(struct sockaddr));
+ } else {
+ addrP->brdcast = NULL;
+ }
- if (addrP->brdcast && (mask = getSubnet(env, sock, name)) != -1) {
- addrP->mask = mask;
+ if (ifa->ifa_netmask) {
+ if (ifa->ifa_netmask->sa_family == AF_INET) {
+ addrP->mask = mask_address_to_mask_length(
+ (uint8_t*)&(((struct sockaddr_in*)ifa->ifa_netmask)->sin_addr),
+ sizeof(struct in_addr));
+ } else if (ifa->ifa_netmask->sa_family == AF_INET6) {
+ addrP->mask = mask_address_to_mask_length(
+ (uint8_t*)&((struct sockaddr_in6*)ifa->ifa_netmask)->sin6_addr,
+ sizeof(struct in6_addr));
+ }
+ } else {
+ addrP->mask = 0;
}
}
@@ -943,23 +871,51 @@
* insert it onto the list.
*/
if (currif == NULL) {
- CHECKED_MALLOC3(currif, netif *, sizeof(netif) + ifnam_size);
+ CHECKED_MALLOC3(currif, netif *, sizeof(netif) + sizeof(name));
currif->name = (char *) currif+sizeof(netif);
- strncpy(currif->name, name, ifnam_size);
- currif->name[ifnam_size - 1] = '\0';
+ strncpy(currif->name, name, sizeof(name));
+ currif->name[sizeof(name) - 1] = '\0';
currif->index = getIndex(sock, name);
currif->addr = NULL;
currif->childs = NULL;
currif->virtual = isVirtual;
+ currif->hwAddrLen = 0;
+ currif->hwAddr = NULL;
currif->next = ifs;
ifs = currif;
}
/*
+ * Insert the mac address on the interface
+ */
+ if (ifa->ifa_addr->sa_family == AF_PACKET) {
+ struct sockaddr_ll *s = (struct sockaddr_ll*)ifa->ifa_addr;
+
+ if (s->sll_halen > 0) {
+ /*
+ * All bytes to 0 means no hardware address.
+ */
+ int i;
+ for (i = 0;i < s->sll_halen; ++i) {
+ if (s->sll_addr[i] != 0) {
+ break;
+ }
+ }
+ if (i != s->sll_halen && currif->hwAddr == NULL) {
+ CHECKED_MALLOC3(currif->hwAddr, uint8_t *, s->sll_halen);
+ memcpy(currif->hwAddr, s->sll_addr, s->sll_halen);
+ currif->hwAddrLen = s->sll_halen;
+ }
+ }
+ }
+
+ /*
* Finally insert the address on the interface
*/
- addrP->next = currif->addr;
- currif->addr = addrP;
+ if (addrP != NULL) {
+ addrP->next = currif->addr;
+ currif->addr = addrP;
+ }
parent = currif;
@@ -979,10 +935,10 @@
}
if (currif == NULL) {
- CHECKED_MALLOC3(currif, netif *, sizeof(netif) + ifnam_size);
+ CHECKED_MALLOC3(currif, netif *, sizeof(netif) + sizeof(name));
currif->name = (char *) currif + sizeof(netif);
- strncpy(currif->name, vname, ifnam_size);
- currif->name[ifnam_size - 1] = '\0';
+ strncpy(currif->name, vname, sizeof(name));
+ currif->name[sizeof(name) - 1] = '\0';
currif->index = getIndex(sock, vname);
currif->addr = NULL;
/* Need to duplicate the addr entry? */
@@ -1033,12 +989,11 @@
/** Linux **/
-#ifdef __linux__
+
/* Open socket for further ioct calls, try v4 socket first and
* if it falls return v6 socket
*/
-#ifdef AF_INET6
static int openSocketWithFallback(JNIEnv *env, const char *ifname){
int sock;
struct ifreq if2;
@@ -1062,114 +1017,6 @@
return sock;
}
-#else
-static int openSocketWithFallback(JNIEnv *env, const char *ifname){
- return openSocket(env,AF_INET);
-}
-#endif
-
-static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
- struct ifconf ifc;
- struct ifreq *ifreqP;
- char *buf;
- int numifs;
- unsigned i;
-
-
- /* need to do a dummy SIOCGIFCONF to determine the buffer size.
- * SIOCGIFCOUNT doesn't work
- */
- ifc.ifc_buf = NULL;
- if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
- NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "ioctl SIOCGIFCONF failed");
- return ifs;
- }
-
- CHECKED_MALLOC3(buf,char *, ifc.ifc_len);
-
- ifc.ifc_buf = buf;
- if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
- NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "ioctl SIOCGIFCONF failed");
- (void) free(buf);
- return ifs;
- }
-
- /*
- * Iterate through each interface
- */
- ifreqP = ifc.ifc_req;
- for (i=0; i<ifc.ifc_len/sizeof (struct ifreq); i++, ifreqP++) {
- /*
- * Add to the list
- */
- ifs = addif(env, sock, ifreqP->ifr_name, ifs, (struct sockaddr *) & (ifreqP->ifr_addr), AF_INET, 0);
-
- /*
- * If an exception occurred then free the list
- */
- if ((*env)->ExceptionOccurred(env)) {
- free(buf);
- freeif(ifs);
- return NULL;
- }
- }
-
- /*
- * Free socket and buffer
- */
- free(buf);
- return ifs;
-}
-
-
-/*
- * Enumerates and returns all IPv6 interfaces on Linux
- */
-
-#ifdef AF_INET6
-static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
- FILE *f;
- char addr6[40], devname[21];
- char addr6p[8][5];
- int plen, scope, dad_status, if_idx;
- uint8_t ipv6addr[16];
-
- if ((f = fopen(_PATH_PROCNET_IFINET6, "r")) != NULL) {
- while (fscanf(f, "%4s%4s%4s%4s%4s%4s%4s%4s %08x %02x %02x %02x %20s\n",
- addr6p[0], addr6p[1], addr6p[2], addr6p[3], addr6p[4], addr6p[5], addr6p[6], addr6p[7],
- &if_idx, &plen, &scope, &dad_status, devname) != EOF) {
-
- struct netif *ifs_ptr = NULL;
- struct netif *last_ptr = NULL;
- struct sockaddr_in6 addr;
-
- sprintf(addr6, "%s:%s:%s:%s:%s:%s:%s:%s",
- addr6p[0], addr6p[1], addr6p[2], addr6p[3], addr6p[4], addr6p[5], addr6p[6], addr6p[7]);
- inet_pton(AF_INET6, addr6, ipv6addr);
-
- memset(&addr, 0, sizeof(struct sockaddr_in6));
- memcpy((void*)addr.sin6_addr.s6_addr, (const void*)ipv6addr, 16);
-
- addr.sin6_scope_id = if_idx;
-
- ifs = addif(env, sock, devname, ifs, (struct sockaddr *)&addr, AF_INET6, plen);
-
-
- /*
- * If an exception occurred then return the list as is.
- */
- if ((*env)->ExceptionOccurred(env)) {
- fclose(f);
- return ifs;
- }
- }
- fclose(f);
- }
- return ifs;
-}
-#endif
-
-
static int getIndex(int sock, const char *name){
/*
* Try to get the interface index
@@ -1185,93 +1032,6 @@
return if2.ifr_ifindex;
}
-/**
- * Returns the IPv4 broadcast address of a named interface, if it exists.
- * Returns 0 if it doesn't have one.
- */
-static struct sockaddr *getBroadcast(JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store) {
- struct sockaddr *ret = NULL;
- struct ifreq if2;
-
- memset((char *) &if2, 0, sizeof(if2));
- strcpy(if2.ifr_name, ifname);
-
- /* Let's make sure the interface does have a broadcast address */
- if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
- NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFFLAGS failed");
- return ret;
- }
-
- if (if2.ifr_flags & IFF_BROADCAST) {
- /* It does, let's retrieve it*/
- if (ioctl(sock, SIOCGIFBRDADDR, (char *)&if2) < 0) {
- NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFBRDADDR failed");
- return ret;
- }
-
- ret = brdcast_store;
- memcpy(ret, &if2.ifr_broadaddr, sizeof(struct sockaddr));
- }
-
- return ret;
-}
-
-/**
- * Returns the IPv4 subnet prefix length (aka subnet mask) for the named
- * interface, if it has one, otherwise return -1.
- */
-static short getSubnet(JNIEnv *env, int sock, const char *ifname) {
- unsigned int mask;
- short ret;
- struct ifreq if2;
-
- memset((char *) &if2, 0, sizeof(if2));
- strcpy(if2.ifr_name, ifname);
-
- if (ioctl(sock, SIOCGIFNETMASK, (char *)&if2) < 0) {
- NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFNETMASK failed");
- return -1;
- }
-
- mask = ntohl(((struct sockaddr_in*)&(if2.ifr_addr))->sin_addr.s_addr);
- ret = 0;
- while (mask) {
- mask <<= 1;
- ret++;
- }
-
- return ret;
-}
-
-/**
- * Get the Hardware address (usually MAC address) for the named interface.
- * return puts the data in buf, and returns the length, in byte, of the
- * MAC address. Returns -1 if there is no hardware address on that interface.
- */
-static int getMacAddress(JNIEnv *env, int sock, const char* ifname, const struct in_addr* addr, unsigned char *buf) {
- static struct ifreq ifr;
- int i;
-
- strcpy(ifr.ifr_name, ifname);
- if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0) {
- NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFHWADDR failed");
- return -1;
- }
-
- memcpy(buf, &ifr.ifr_hwaddr.sa_data, IFHWADDRLEN);
-
- /*
- * All bytes to 0 means no hardware address.
- */
-
- for (i = 0; i < IFHWADDRLEN; i++) {
- if (buf[i] != 0)
- return IFHWADDRLEN;
- }
-
- return -1;
-}
-
static int getMTU(JNIEnv *env, int sock, const char *ifname) {
struct ifreq if2;
@@ -1304,707 +1064,8 @@
return 0;
}
-#endif
-
-/** Solaris **/
-#ifdef __solaris__
-/* Open socket for further ioct calls, try v4 socket first and
- * if it falls return v6 socket
- */
-
-#ifdef AF_INET6
-static int openSocketWithFallback(JNIEnv *env, const char *ifname){
- int sock, alreadyV6 = 0;
- struct lifreq if2;
-
- if ((sock = JVM_Socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
- if (errno == EPROTONOSUPPORT){
- if ( (sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0 ){
- NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
- return -1;
- }
-
- alreadyV6=1;
- }
- else{ // errno is not NOSUPPORT
- NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
- return -1;
- }
- }
-
- /**
- * Solaris requires that we have IPv6 socket to query an
- * interface without IPv4 address - check it here
- * POSIX 1 require the kernell to return ENOTTY if the call is
- * unappropriate for device e.g. NETMASK for device having IPv6
- * only address but not all devices follows the standart so
- * fallback on any error. It's not an ecology friendly but more
- * reliable.
- */
-
- if (! alreadyV6 ){
- memset((char *) &if2, 0, sizeof(if2));
- strcpy(if2.lifr_name, ifname);
- if (ioctl(sock, SIOCGLIFNETMASK, (char *)&if2) < 0) {
- close(sock);
- if ( (sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0 ){
- NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
- return -1;
- }
- }
- }
-
- return sock;
-}
-
-#else
-static int openSocketWithFallback(JNIEnv *env, const char *ifname){
- return openSocket(env,AF_INET);
-}
-#endif
-
-/*
- * Enumerates and returns all IPv4 interfaces
- * (linux verison)
- */
-
-static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
- return enumIPvXInterfaces(env,sock, ifs, AF_INET);
-}
-
-#ifdef AF_INET6
-static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
- return enumIPvXInterfaces(env,sock, ifs, AF_INET6);
-}
-#endif
-
-/*
- Enumerates and returns all interfaces on Solaris
- use the same code for IPv4 and IPv6
- */
-static netif *enumIPvXInterfaces(JNIEnv *env, int sock, netif *ifs, int family) {
- struct lifconf ifc;
- struct lifreq *ifr;
- int n;
- char *buf;
- struct lifnum numifs;
- unsigned bufsize;
-
- /*
- * Get the interface count
- */
- numifs.lifn_family = family;
- numifs.lifn_flags = 0;
- if (ioctl(sock, SIOCGLIFNUM, (char *)&numifs) < 0) {
- NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "ioctl SIOCGLIFNUM failed");
- return ifs;
- }
-
- /*
- * Enumerate the interface configurations
- */
- bufsize = numifs.lifn_count * sizeof (struct lifreq);
- CHECKED_MALLOC3(buf, char *, bufsize);
-
- ifc.lifc_family = family;
- ifc.lifc_flags = 0;
- ifc.lifc_len = bufsize;
- ifc.lifc_buf = buf;
- if (ioctl(sock, SIOCGLIFCONF, (char *)&ifc) < 0) {
- NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "ioctl SIOCGLIFCONF failed");
- free(buf);
- return ifs;
- }
-
- /*
- * Iterate through each interface
- */
- ifr = ifc.lifc_req;
- for (n=0; n<numifs.lifn_count; n++, ifr++) {
- int index = -1;
- struct lifreq if2;
-
- /*
- * Ignore either IPv4 or IPv6 addresses
- */
- if (ifr->lifr_addr.ss_family != family) {
- continue;
- }
-
-#ifdef AF_INET6
- if (ifr->lifr_addr.ss_family == AF_INET6) {
- struct sockaddr_in6 *s6= (struct sockaddr_in6 *)&(ifr->lifr_addr);
- s6->sin6_scope_id = getIndex(sock, ifr->lifr_name);
- }
-#endif
-
- /* add to the list */
- ifs = addif(env, sock,ifr->lifr_name, ifs, (struct sockaddr *)&(ifr->lifr_addr),family, (short) ifr->lifr_addrlen);
-
- /*
- * If an exception occurred we return immediately
- */
- if ((*env)->ExceptionOccurred(env)) {
- free(buf);
- return ifs;
- }
-
- }
-
- free(buf);
- return ifs;
-}
-
-static int getIndex(int sock, const char *name){
- /*
- * Try to get the interface index
- * (Not supported on Solaris 2.6 or 7)
- */
- struct lifreq if2;
- strcpy(if2.lifr_name, name);
-
- if (ioctl(sock, SIOCGLIFINDEX, (char *)&if2) < 0) {
- return -1;
- }
-
- return if2.lifr_index;
-}
-
-/**
- * Returns the IPv4 broadcast address of a named interface, if it exists.
- * Returns 0 if it doesn't have one.
- */
-static struct sockaddr *getBroadcast(JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store) {
- struct sockaddr *ret = NULL;
- struct lifreq if2;
-
- memset((char *) &if2, 0, sizeof(if2));
- strcpy(if2.lifr_name, ifname);
-
- /* Let's make sure the interface does have a broadcast address */
- if (ioctl(sock, SIOCGLIFFLAGS, (char *)&if2) < 0) {
- NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGLIFFLAGS failed");
- return ret;
- }
-
- if (if2.lifr_flags & IFF_BROADCAST) {
- /* It does, let's retrieve it*/
- if (ioctl(sock, SIOCGLIFBRDADDR, (char *)&if2) < 0) {
- NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGLIFBRDADDR failed");
- return ret;
- }
-
- ret = brdcast_store;
- memcpy(ret, &if2.lifr_broadaddr, sizeof(struct sockaddr));
- }
-
- return ret;
-}
-
-/**
- * Returns the IPv4 subnet prefix length (aka subnet mask) for the named
- * interface, if it has one, otherwise return -1.
- */
-static short getSubnet(JNIEnv *env, int sock, const char *ifname) {
- unsigned int mask;
- short ret;
- struct lifreq if2;
-
- memset((char *) &if2, 0, sizeof(if2));
- strcpy(if2.lifr_name, ifname);
-
- if (ioctl(sock, SIOCGLIFNETMASK, (char *)&if2) < 0) {
- NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGLIFNETMASK failed");
- return -1;
- }
-
- mask = ntohl(((struct sockaddr_in*)&(if2.lifr_addr))->sin_addr.s_addr);
- ret = 0;
-
- while (mask) {
- mask <<= 1;
- ret++;
- }
-
- return ret;
-}
-
-
-
-#define DEV_PREFIX "/dev/"
-
-/**
- * Solaris specific DLPI code to get hardware address from a device.
- * Unfortunately, at least up to Solaris X, you have to have special
- * privileges (i.e. be root).
- */
-static int getMacFromDevice(JNIEnv *env, const char* ifname, unsigned char* retbuf) {
- char style1dev[MAXPATHLEN];
- int fd;
- dl_phys_addr_req_t dlpareq;
- dl_phys_addr_ack_t *dlpaack;
- struct strbuf msg;
- char buf[128];
- int flags = 0;
-
- /**
- * Device is in /dev
- * e.g.: /dev/bge0
- */
- strcpy(style1dev, DEV_PREFIX);
- strcat(style1dev, ifname);
- if ((fd = open(style1dev, O_RDWR)) < 0) {
- /*
- * Can't open it. We probably are missing the privilege.
- * We'll have to try something else
- */
- return 0;
- }
-
- dlpareq.dl_primitive = DL_PHYS_ADDR_REQ;
- dlpareq.dl_addr_type = DL_CURR_PHYS_ADDR;
-
- msg.buf = (char *)&dlpareq;
- msg.len = DL_PHYS_ADDR_REQ_SIZE;
-
- if (putmsg(fd, &msg, NULL, 0) < 0) {
- NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "putmsg failed");
- return -1;
- }
-
- dlpaack = (dl_phys_addr_ack_t *)buf;
-
- msg.buf = (char *)buf;
- msg.len = 0;
- msg.maxlen = sizeof (buf);
- if (getmsg(fd, &msg, NULL, &flags) < 0) {
- NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "getmsg failed");
- return -1;
- }
-
- if (msg.len < DL_PHYS_ADDR_ACK_SIZE || dlpaack->dl_primitive != DL_PHYS_ADDR_ACK) {
- JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Couldn't obtain phys addr\n");
- return -1;
- }
-
- memcpy(retbuf, &buf[dlpaack->dl_addr_offset], dlpaack->dl_addr_length);
- return dlpaack->dl_addr_length;
-}
-
-/**
- * Get the Hardware address (usually MAC address) for the named interface.
- * return puts the data in buf, and returns the length, in byte, of the
- * MAC address. Returns -1 if there is no hardware address on that interface.
- */
-static int getMacAddress(JNIEnv *env, int sock, const char *ifname, const struct in_addr* addr, unsigned char *buf) {
- struct arpreq arpreq;
- struct sockaddr_in* sin;
- struct sockaddr_in ipAddr;
- int len, i;
- struct lifreq lif;
-
- /* First, try the new (S11) SIOCGLIFHWADDR ioctl(). If that fails
- * try the old way.
- */
- memset(&lif, 0, sizeof(lif));
- strlcpy(lif.lifr_name, ifname, sizeof(lif.lifr_name));
-
- if (ioctl(sock, SIOCGLIFHWADDR, &lif) != -1) {
- struct sockaddr_dl *sp;
- sp = (struct sockaddr_dl *)&lif.lifr_addr;
- memcpy(buf, &sp->sdl_data[0], sp->sdl_alen);
- return sp->sdl_alen;
- }
-
- /**
- * On Solaris we have to use DLPI, but it will only work if we have
- * privileged access (i.e. root). If that fails, we try a lookup
- * in the ARP table, which requires an IPv4 address.
- */
- if ((len = getMacFromDevice(env, ifname, buf)) == 0) {
- /*DLPI failed - trying to do arp lookup*/
-
- if (addr == NULL) {
- /**
- * No IPv4 address for that interface, so can't do an ARP lookup.
- */
- return -1;
- }
-
- len = 6; //???
-
- sin = (struct sockaddr_in *) &arpreq.arp_pa;
- memset((char *) &arpreq, 0, sizeof(struct arpreq));
- ipAddr.sin_port = 0;
- ipAddr.sin_family = AF_INET;
- memcpy(&ipAddr.sin_addr, addr, sizeof(struct in_addr));
- memcpy(&arpreq.arp_pa, &ipAddr, sizeof(struct sockaddr_in));
- arpreq.arp_flags= ATF_PUBL;
-
- if (ioctl(sock, SIOCGARP, &arpreq) < 0) {
- return -1;
- }
-
- memcpy(buf, &arpreq.arp_ha.sa_data[0], len );
- }
-
- /*
- * All bytes to 0 means no hardware address.
- */
-
- for (i = 0; i < len; i++) {
- if (buf[i] != 0)
- return len;
- }
-
- return -1;
-}
-
-static int getMTU(JNIEnv *env, int sock, const char *ifname) {
- struct lifreq if2;
-
- memset((char *) &if2, 0, sizeof(if2));
- strcpy(if2.lifr_name, ifname);
-
- if (ioctl(sock, SIOCGLIFMTU, (char *)&if2) < 0) {
- NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGLIFMTU failed");
- return -1;
- }
-
- return if2.lifr_mtu;
-}
-
-
-static int getFlags(int sock, const char *ifname, int *flags) {
- struct lifreq lifr;
- memset((caddr_t)&lifr, 0, sizeof(lifr));
- strcpy((caddr_t)&(lifr.lifr_name), ifname);
-
- if (ioctl(sock, SIOCGLIFFLAGS, (char *)&lifr) < 0) {
- return -1;
- }
-
- *flags = lifr.lifr_flags;
- return 0;
-}
-
-
-#endif
-
-
-/** BSD **/
-#ifdef _ALLBSD_SOURCE
-/* Open socket for further ioct calls, try v4 socket first and
- * if it falls return v6 socket
- */
-
-#ifdef AF_INET6
-static int openSocketWithFallback(JNIEnv *env, const char *ifname){
- int sock;
- struct ifreq if2;
-
- if ((sock = JVM_Socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
- if (errno == EPROTONOSUPPORT){
- if ( (sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0 ){
- NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
- return -1;
- }
- }
- else{ // errno is not NOSUPPORT
- NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
- return -1;
- }
- }
-
- return sock;
-}
-
-#else
-static int openSocketWithFallback(JNIEnv *env, const char *ifname){
- return openSocket(env,AF_INET);
-}
-#endif
-
-/*
- * Enumerates and returns all IPv4 interfaces
- */
-static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
- struct ifaddrs *ifa, *origifa;
-
- if (getifaddrs(&origifa) != 0) {
- NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException",
- "getifaddrs() function failed");
- return ifs;
- }
-
- for (ifa = origifa; ifa != NULL; ifa = ifa->ifa_next) {
-
- /*
- * Skip non-AF_INET entries.
- */
- if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET)
- continue;
-
- /*
- * Add to the list.
- */
- ifs = addif(env, sock, ifa->ifa_name, ifs, ifa->ifa_addr, AF_INET, 0);
-
- /*
- * If an exception occurred then free the list.
- */
- if ((*env)->ExceptionOccurred(env)) {
- freeifaddrs(origifa);
- freeif(ifs);
- return NULL;
- }
- }
-
- /*
- * Free socket and buffer
- */
- freeifaddrs(origifa);
- return ifs;
-}
-
-
-/*
- * Enumerates and returns all IPv6 interfaces on Linux
- */
-
-#ifdef AF_INET6
-/*
- * Determines the prefix on BSD for IPv6 interfaces.
- */
-static
-int prefix(void *val, int size) {
- u_char *name = (u_char *)val;
- int byte, bit, plen = 0;
-
- for (byte = 0; byte < size; byte++, plen += 8)
- if (name[byte] != 0xff)
- break;
- if (byte == size)
- return (plen);
- for (bit = 7; bit != 0; bit--, plen++)
- if (!(name[byte] & (1 << bit)))
- break;
- for (; bit != 0; bit--)
- if (name[byte] & (1 << bit))
- return (0);
- byte++;
- for (; byte < size; byte++)
- if (name[byte])
- return (0);
- return (plen);
-}
-
-/*
- * Enumerates and returns all IPv6 interfaces on BSD
- */
-static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
- struct ifaddrs *ifa, *origifa;
- struct sockaddr_in6 *sin6;
- struct in6_ifreq ifr6;
-
- if (getifaddrs(&origifa) != 0) {
- NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException",
- "getifaddrs() function failed");
- return ifs;
- }
-
- for (ifa = origifa; ifa != NULL; ifa = ifa->ifa_next) {
-
- /*
- * Skip non-AF_INET6 entries.
- */
- if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET6)
- continue;
-
- memset(&ifr6, 0, sizeof(ifr6));
- strlcpy(ifr6.ifr_name, ifa->ifa_name, sizeof(ifr6.ifr_name));
- memcpy(&ifr6.ifr_addr, ifa->ifa_addr, MIN(sizeof(ifr6.ifr_addr), ifa->ifa_addr->sa_len));
-
- if (ioctl(sock, SIOCGIFNETMASK_IN6, (caddr_t)&ifr6) < 0) {
- NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException",
- "ioctl SIOCGIFNETMASK_IN6 failed");
- freeifaddrs(origifa);
- freeif(ifs);
- return NULL;
- }
-
- /* Add to the list. */
- sin6 = (struct sockaddr_in6 *)&ifr6.ifr_addr;
- ifs = addif(env, sock, ifa->ifa_name, ifs, ifa->ifa_addr, AF_INET6,
- prefix(&sin6->sin6_addr, sizeof(struct in6_addr)));
-
- /* If an exception occurred then free the list. */
- if ((*env)->ExceptionOccurred(env)) {
- freeifaddrs(origifa);
- freeif(ifs);
- return NULL;
- }
- }
-
- /*
- * Free socket and ifaddrs buffer
- */
- freeifaddrs(origifa);
- return ifs;
-}
-#endif
-
-static int getIndex(int sock, const char *name){
-#ifdef __FreeBSD__
- /*
- * Try to get the interface index
- * (Not supported on Solaris 2.6 or 7)
- */
- struct ifreq if2;
- strcpy(if2.ifr_name, name);
-
- if (ioctl(sock, SIOCGIFINDEX, (char *)&if2) < 0) {
- return -1;
- }
-
- return if2.ifr_index;
-#else
- /*
- * Try to get the interface index using BSD specific if_nametoindex
- */
- int index = if_nametoindex(name);
- return (index == 0) ? -1 : index;
-#endif
-}
-
-/**
- * Returns the IPv4 broadcast address of a named interface, if it exists.
- * Returns 0 if it doesn't have one.
- */
-static struct sockaddr *getBroadcast(JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store) {
- struct sockaddr *ret = NULL;
- struct ifreq if2;
-
- memset((char *) &if2, 0, sizeof(if2));
- strcpy(if2.ifr_name, ifname);
-
- /* Let's make sure the interface does have a broadcast address */
- if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
- NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFFLAGS failed");
- return ret;
- }
-
- if (if2.ifr_flags & IFF_BROADCAST) {
- /* It does, let's retrieve it*/
- if (ioctl(sock, SIOCGIFBRDADDR, (char *)&if2) < 0) {
- NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFBRDADDR failed");
- return ret;
- }
-
- ret = brdcast_store;
- memcpy(ret, &if2.ifr_broadaddr, sizeof(struct sockaddr));
- }
-
- return ret;
-}
-
-/**
- * Returns the IPv4 subnet prefix length (aka subnet mask) for the named
- * interface, if it has one, otherwise return -1.
- */
-static short getSubnet(JNIEnv *env, int sock, const char *ifname) {
- unsigned int mask;
- short ret;
- struct ifreq if2;
-
- memset((char *) &if2, 0, sizeof(if2));
- strcpy(if2.ifr_name, ifname);
-
- if (ioctl(sock, SIOCGIFNETMASK, (char *)&if2) < 0) {
- NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFNETMASK failed");
- return -1;
- }
-
- mask = ntohl(((struct sockaddr_in*)&(if2.ifr_addr))->sin_addr.s_addr);
- ret = 0;
- while (mask) {
- mask <<= 1;
- ret++;
- }
-
- return ret;
-}
-
-/**
- * Get the Hardware address (usually MAC address) for the named interface.
- * return puts the data in buf, and returns the length, in byte, of the
- * MAC address. Returns -1 if there is no hardware address on that interface.
- */
-static int getMacAddress(JNIEnv *env, int sock, const char* ifname, const struct in_addr* addr, unsigned char *buf) {
- struct ifaddrs *ifa0, *ifa;
- struct sockaddr *saddr;
- int i;
-
- /* Grab the interface list */
- if (!getifaddrs(&ifa0)) {
- /* Cycle through the interfaces */
- for (i = 0, ifa = ifa0; ifa != NULL; ifa = ifa->ifa_next, i++) {
- saddr = ifa->ifa_addr;
- /* Link layer contains the MAC address */
- if (saddr->sa_family == AF_LINK && !strcmp(ifname, ifa->ifa_name)) {
- struct sockaddr_dl *sadl = (struct sockaddr_dl *) saddr;
- /* Check the address is the correct length */
- if (sadl->sdl_alen == ETHER_ADDR_LEN) {
- memcpy(buf, (sadl->sdl_data + sadl->sdl_nlen), ETHER_ADDR_LEN);
- freeifaddrs(ifa0);
- return ETHER_ADDR_LEN;
- }
- }
- }
- freeifaddrs(ifa0);
- }
-
- return -1;
-}
-
-static int getMTU(JNIEnv *env, int sock, const char *ifname) {
- struct ifreq if2;
-
- memset((char *) &if2, 0, sizeof(if2));
- strcpy(if2.ifr_name, ifname);
-
- if (ioctl(sock, SIOCGIFMTU, (char *)&if2) < 0) {
- NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFMTU failed");
- return -1;
- }
-
- return if2.ifr_mtu;
-}
-
-static int getFlags(int sock, const char *ifname, int *flags) {
- struct ifreq if2;
- int ret = -1;
-
- memset((char *) &if2, 0, sizeof(if2));
- strcpy(if2.ifr_name, ifname);
-
- if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0){
- return -1;
- }
-
- if (sizeof(if2.ifr_flags) == sizeof(short)) {
- *flags = (if2.ifr_flags & 0xffff);
- } else {
- *flags = if2.ifr_flags;
- }
- return 0;
-}
-
-#endif
-
static JNINativeMethod gMethods[] = {
NATIVE_METHOD(NetworkInterface, getMTU0, "(Ljava/lang/String;I)I"),
- NATIVE_METHOD(NetworkInterface, getMacAddr0, "([BLjava/lang/String;I)[B"),
NATIVE_METHOD(NetworkInterface, supportsMulticast0, "(Ljava/lang/String;I)Z"),
NATIVE_METHOD(NetworkInterface, isLoopback0, "(Ljava/lang/String;I)Z"),
NATIVE_METHOD(NetworkInterface, isP2P0, "(Ljava/lang/String;I)Z"),
diff --git a/ojluni/src/main/native/PlainDatagramSocketImpl.c b/ojluni/src/main/native/PlainDatagramSocketImpl.c
index f64d269..f4857df 100755
--- a/ojluni/src/main/native/PlainDatagramSocketImpl.c
+++ b/ojluni/src/main/native/PlainDatagramSocketImpl.c
@@ -58,7 +58,6 @@
#include "java_net_SocketOptions.h"
#include "java_net_PlainDatagramSocketImpl.h"
-#include "java_net_NetworkInterface.h"
#include "JNIHelp.h"
#define NATIVE_METHOD(className, functionName, signature) \
@@ -1065,55 +1064,19 @@
/*
- * Set outgoing multicast interface designated by a NetworkInterface.
+ * Set outgoing multicast interface designated by a NetworkInterface index.
* Throw exception if failed.
*
* Android changed: return 0 on success, negative on failure.
+ * Android changed: Interface index (not NetworkInterface) as the parameter
*/
-static int mcast_set_if_by_if_v4(JNIEnv *env, jobject this, int fd, jobject value) {
- static jfieldID ni_addrsID;
- struct in_addr in;
- jobjectArray addrArray;
- jsize len;
- jobject addr;
- int i;
-
- if (ni_addrsID == NULL ) {
- jclass c = (*env)->FindClass(env, "java/net/NetworkInterface");
- // Android-changed: return -1 if null.
- CHECK_NULL_RETURN(c, -1);
- ni_addrsID = (*env)->GetFieldID(env, c, "addrs",
- "[Ljava/net/InetAddress;");
- // Android-changed: return -1 if null.
- CHECK_NULL_RETURN(ni_addrsID, -1);
- }
-
- addrArray = (*env)->GetObjectField(env, value, ni_addrsID);
- len = (*env)->GetArrayLength(env, addrArray);
-
- /*
- * Check that there is at least one address bound to this
- * interface.
- */
- if (len < 1) {
- JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
- "bad argument for IP_MULTICAST_IF2: No IP addresses bound to interface");
- return -1;
- }
-
- /*
- * We need an ipv4 address here
- */
- for (i = 0; i < len; i++) {
- addr = (*env)->GetObjectArrayElement(env, addrArray, i);
- if (getInetAddress_family(env, addr) == IPv4) {
- in.s_addr = htonl(getInetAddress_addr(env, addr));
- break;
- }
- }
+static int mcast_set_if_by_if_v4(JNIEnv *env, jobject this, int fd, jint ifindex) {
+ struct ip_mreqn req;
+ memset(&req, 0, sizeof(req));
+ req.imr_ifindex = ifindex;
if (JVM_SetSockOpt(fd, IPPROTO_IP, IP_MULTICAST_IF,
- (const char*)&in, sizeof(in)) < 0) {
+ (const char*)&req, sizeof(req)) < 0) {
NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
"Error setting socket option");
return -1;
@@ -1125,23 +1088,12 @@
/*
* Set outgoing multicast interface designated by a NetworkInterface.
* Throw exception if failed.
+ * Android changed: Interface index (not NetworkInterface) as the parameter
*/
-#ifdef AF_INET6
-static void mcast_set_if_by_if_v6(JNIEnv *env, jobject this, int fd, jobject value) {
- static jfieldID ni_indexID;
- int index;
-
- if (ni_indexID == NULL) {
- jclass c = (*env)->FindClass(env, "java/net/NetworkInterface");
- CHECK_NULL(c);
- ni_indexID = (*env)->GetFieldID(env, c, "index", "I");
- CHECK_NULL(ni_indexID);
- }
- index = (*env)->GetIntField(env, value, ni_indexID);
-
+static void mcast_set_if_by_if_v6(JNIEnv *env, jobject this, int fd, jint ifindex) {
if (JVM_SetSockOpt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
- (const char*)&index, sizeof(index)) < 0) {
- if (errno == EINVAL && index > 0) {
+ (const char*)&ifindex, sizeof(ifindex)) < 0) {
+ if (errno == EINVAL && ifindex > 0) {
JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
"IPV6_MULTICAST_IF failed (interface has IPv4 "
"address only?)");
@@ -1151,9 +1103,7 @@
}
return;
}
-
}
-#endif /* AF_INET6 */
/*
* Set outgoing multicast interface designated by an InetAddress.
@@ -1180,18 +1130,29 @@
* Set outgoing multicast interface designated by an InetAddress.
* Throw exception if failed.
*/
-#ifdef AF_INET6
static void mcast_set_if_by_addr_v6(JNIEnv *env, jobject this, int fd, jobject value) {
static jclass ni_class;
+ static jmethodID ni_getByInetAddress;
+ static jmethodID ni_getIndex;
if (ni_class == NULL) {
jclass c = (*env)->FindClass(env, "java/net/NetworkInterface");
CHECK_NULL(c);
ni_class = (*env)->NewGlobalRef(env, c);
CHECK_NULL(ni_class);
+ ni_getByInetAddress = (*env)->GetStaticMethodID(
+ env, ni_class, "getByInetAddress", "(Ljava/net/InetAddress;)Ljava/net/NetworkInterface;");
+ CHECK_NULL(ni_getByInetAddress);
+ ni_getIndex = (*env)->GetMethodID(
+ env, ni_class, "getIndex", "()I");
+ CHECK_NULL(ni_getIndex);
}
- value = NetworkInterface_getByInetAddress0(env, ni_class, value);
- if (value == NULL) {
+ /*
+ * Get the NetworkInterface by inetAddress
+ */
+ jobject ni_value = (*env)->CallStaticObjectMethod(
+ env, ni_class, ni_getByInetAddress, value);
+ if (ni_value == NULL) {
if (!(*env)->ExceptionOccurred(env)) {
JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
"bad argument for IP_MULTICAST_IF"
@@ -1200,9 +1161,16 @@
return;
}
- mcast_set_if_by_if_v6(env, this, fd, value);
+ /*
+ * Get the NetworkInterface index
+ */
+ jint ifindex = (*env)->CallIntMethod(env, ni_value, ni_getIndex);
+ if ((*env)->ExceptionOccurred(env)) {
+ return;
+ }
+
+ mcast_set_if_by_if_v6(env, this, fd, ifindex);
}
-#endif
/*
* Sets the multicast interface.
@@ -1238,8 +1206,6 @@
/*
* value is an InetAddress.
*/
-#ifdef AF_INET6
-#ifdef __linux__
// Android-changed: Return early if mcast_set_if_by_addr_v4 threw.
// We don't want to call into the IPV6 code with a pending exception.
if (mcast_set_if_by_addr_v4(env, this, fd, value)) {
@@ -1248,42 +1214,29 @@
if (ipv6_available()) {
mcast_set_if_by_addr_v6(env, this, fd, value);
}
-#else /* __linux__ not defined */
- if (ipv6_available()) {
- mcast_set_if_by_addr_v6(env, this, fd, value);
- } else {
- mcast_set_if_by_addr_v4(env, this, fd, value);
- }
-#endif /* __linux__ */
-#else
- mcast_set_if_by_addr_v4(env, this, fd, value);
-#endif /* AF_INET6 */
}
if (opt == java_net_SocketOptions_IP_MULTICAST_IF2) {
- /*
- * value is a NetworkInterface.
+ /*
+ * value is a Integer (Android-changed, openJdk uses NetworkInterface)
*/
-#ifdef AF_INET6
-#ifdef __linux__
+ static jfieldID integer_valueID;
+ if (integer_valueID == NULL) {
+ jclass c = (*env)->FindClass(env, "java/lang/Integer");
+ CHECK_NULL(c);
+ integer_valueID = (*env)->GetFieldID(env, c, "value", "I");
+ CHECK_NULL(integer_valueID);
+ }
+ int index = (*env)->GetIntField(env, value, integer_valueID);
+
// Android-changed: Return early if mcast_set_if_by_addr_v4 threw.
// We don't want to call into the IPV6 code with a pending exception.
- if (mcast_set_if_by_if_v4(env, this, fd, value)) {
+ if (mcast_set_if_by_if_v4(env, this, fd, index)) {
return;
}
if (ipv6_available()) {
- mcast_set_if_by_if_v6(env, this, fd, value);
+ mcast_set_if_by_if_v6(env, this, fd, index);
}
-#else /* __linux__ not defined */
- if (ipv6_available()) {
- mcast_set_if_by_if_v6(env, this, fd, value);
- } else {
- mcast_set_if_by_if_v4(env, this, fd, value);
- }
-#endif /* __linux__ */
-#else
- mcast_set_if_by_if_v4(env, this, fd, value);
-#endif /* AF_INET6 */
}
}
@@ -1500,128 +1453,11 @@
* return NetworkInterface.
*/
jobject getMulticastInterface(JNIEnv *env, jobject this, int fd, jint opt) {
- jboolean isIPV4 = JNI_TRUE;
-
-#ifdef AF_INET6
- if (ipv6_available()) {
- isIPV4 = JNI_FALSE;
- }
-#endif
-
- /*
- * IPv4 implementation
- */
- if (isIPV4) {
- static jclass inet4_class;
- static jmethodID inet4_ctrID;
-
- static jclass ni_class;
- static jmethodID ni_ctrID;
- static jfieldID ni_indexID;
- static jfieldID ni_addrsID;
-
- jobjectArray addrArray;
- jobject addr;
- jobject ni;
-
- struct in_addr in;
- struct in_addr *inP = ∈
- int len = sizeof(struct in_addr);
-
-#ifdef __linux__
- struct ip_mreqn mreqn;
-#endif
-
- if (JVM_GetSockOpt(fd, IPPROTO_IP, IP_MULTICAST_IF,
- (char *)inP, &len) < 0) {
- NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
- "Error getting socket option");
- return NULL;
- }
-
- /*
- * Construct and populate an Inet4Address
- */
- if (inet4_class == NULL) {
- jclass c = (*env)->FindClass(env, "java/net/Inet4Address");
- CHECK_NULL_RETURN(c, NULL);
- inet4_ctrID = (*env)->GetMethodID(env, c, "<init>", "()V");
- CHECK_NULL_RETURN(inet4_ctrID, NULL);
- inet4_class = (*env)->NewGlobalRef(env, c);
- CHECK_NULL_RETURN(inet4_class, NULL);
- }
- addr = (*env)->NewObject(env, inet4_class, inet4_ctrID, 0);
- CHECK_NULL_RETURN(addr, NULL);
-
- setInetAddress_addr(env, addr, ntohl(in.s_addr));
-
- /*
- * For IP_MULTICAST_IF return InetAddress
- */
- if (opt == java_net_SocketOptions_IP_MULTICAST_IF) {
- return addr;
- }
-
- /*
- * For IP_MULTICAST_IF2 we get the NetworkInterface for
- * this address and return it
- */
- if (ni_class == NULL) {
- jclass c = (*env)->FindClass(env, "java/net/NetworkInterface");
- CHECK_NULL_RETURN(c, NULL);
- ni_ctrID = (*env)->GetMethodID(env, c, "<init>", "()V");
- CHECK_NULL_RETURN(ni_ctrID, NULL);
- ni_indexID = (*env)->GetFieldID(env, c, "index", "I");
- CHECK_NULL_RETURN(ni_indexID, NULL);
- ni_addrsID = (*env)->GetFieldID(env, c, "addrs",
- "[Ljava/net/InetAddress;");
- CHECK_NULL_RETURN(ni_addrsID, NULL);
- ni_class = (*env)->NewGlobalRef(env, c);
- CHECK_NULL_RETURN(ni_class, NULL);
- }
- ni = NetworkInterface_getByInetAddress0(env, ni_class, addr);
- if (ni) {
- return ni;
- }
-
- /*
- * The address doesn't appear to be bound at any known
- * NetworkInterface. Therefore we construct a NetworkInterface
- * with this address.
- */
- ni = (*env)->NewObject(env, ni_class, ni_ctrID, 0);
- CHECK_NULL_RETURN(ni, NULL);
-
- (*env)->SetIntField(env, ni, ni_indexID, -1);
- addrArray = (*env)->NewObjectArray(env, 1, inet4_class, NULL);
- CHECK_NULL_RETURN(addrArray, NULL);
- (*env)->SetObjectArrayElement(env, addrArray, 0, addr);
- (*env)->SetObjectField(env, ni, ni_addrsID, addrArray);
- return ni;
- }
-
-
-#ifdef AF_INET6
- /*
- * IPv6 implementation
- */
- if ((opt == java_net_SocketOptions_IP_MULTICAST_IF) ||
- (opt == java_net_SocketOptions_IP_MULTICAST_IF2)) {
-
- static jclass ni_class;
- static jmethodID ni_ctrID;
- static jfieldID ni_indexID;
- static jfieldID ni_addrsID;
- static jclass ia_class;
- static jmethodID ia_anyLocalAddressID;
-
+ if ((opt == java_net_SocketOptions_IP_MULTICAST_IF2) ||
+ (opt == java_net_SocketOptions_IP_MULTICAST_IF)) {
int index;
int len = sizeof(index);
- jobjectArray addrArray;
- jobject addr;
- jobject ni;
-
{
if (JVM_GetSockOpt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
(char*)&index, &len) < 0) {
@@ -1631,89 +1467,10 @@
}
}
- if (ni_class == NULL) {
- jclass c = (*env)->FindClass(env, "java/net/NetworkInterface");
- CHECK_NULL_RETURN(c, NULL);
- ni_ctrID = (*env)->GetMethodID(env, c, "<init>", "()V");
- CHECK_NULL_RETURN(ni_ctrID, NULL);
- ni_indexID = (*env)->GetFieldID(env, c, "index", "I");
- CHECK_NULL_RETURN(ni_indexID, NULL);
- ni_addrsID = (*env)->GetFieldID(env, c, "addrs",
- "[Ljava/net/InetAddress;");
- CHECK_NULL_RETURN(ni_addrsID, NULL);
-
- ia_class = (*env)->FindClass(env, "java/net/InetAddress");
- CHECK_NULL_RETURN(ia_class, NULL);
- ia_class = (*env)->NewGlobalRef(env, ia_class);
- CHECK_NULL_RETURN(ia_class, NULL);
- ia_anyLocalAddressID = (*env)->GetStaticMethodID(env,
- ia_class,
- "anyLocalAddress",
- "()Ljava/net/InetAddress;");
- CHECK_NULL_RETURN(ia_anyLocalAddressID, NULL);
- ni_class = (*env)->NewGlobalRef(env, c);
- CHECK_NULL_RETURN(ni_class, NULL);
- }
-
- /*
- * If multicast to a specific interface then return the
- * interface (for IF2) or the any address on that interface
- * (for IF).
- */
- if (index > 0) {
- ni = NetworkInterface_getByIndex0(env, ni_class,
- index);
- if (ni == NULL) {
- char errmsg[255];
- sprintf(errmsg,
- "IPV6_MULTICAST_IF returned index to unrecognized interface: %d",
- index);
- JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", errmsg);
- return NULL;
- }
-
- /*
- * For IP_MULTICAST_IF2 return the NetworkInterface
- */
- if (opt == java_net_SocketOptions_IP_MULTICAST_IF2) {
- return ni;
- }
-
- /*
- * For IP_MULTICAST_IF return addrs[0]
- */
- addrArray = (*env)->GetObjectField(env, ni, ni_addrsID);
- if ((*env)->GetArrayLength(env, addrArray) < 1) {
- JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
- "IPV6_MULTICAST_IF returned interface without IP bindings");
- return NULL;
- }
-
- addr = (*env)->GetObjectArrayElement(env, addrArray, 0);
- return addr;
- }
-
- /*
- * Multicast to any address - return anyLocalAddress
- * or a NetworkInterface with addrs[0] set to anyLocalAddress
- */
-
- addr = (*env)->CallStaticObjectMethod(env, ia_class, ia_anyLocalAddressID,
- NULL);
- if (opt == java_net_SocketOptions_IP_MULTICAST_IF) {
- return addr;
- }
-
- ni = (*env)->NewObject(env, ni_class, ni_ctrID, 0);
- CHECK_NULL_RETURN(ni, NULL);
- (*env)->SetIntField(env, ni, ni_indexID, -1);
- addrArray = (*env)->NewObjectArray(env, 1, ia_class, NULL);
- CHECK_NULL_RETURN(addrArray, NULL);
- (*env)->SetObjectArrayElement(env, addrArray, 0, addr);
- (*env)->SetObjectField(env, ni, ni_addrsID, addrArray);
- return ni;
+ jobject ifindex = createInteger(env, index);
+ CHECK_NULL_RETURN(ifindex, NULL);
+ return ifindex;
}
-#endif
return NULL;
}
diff --git a/openjdk_java_files.mk b/openjdk_java_files.mk
index 29f53aa..6676a9e 100644
--- a/openjdk_java_files.mk
+++ b/openjdk_java_files.mk
@@ -309,86 +309,15 @@
ojluni/src/main/java/java/nio/Buffer.java \
ojluni/src/main/java/java/nio/BufferOverflowException.java \
ojluni/src/main/java/java/nio/BufferUnderflowException.java \
+ ojluni/src/main/java/java/nio/ByteBuffer.java \
ojluni/src/main/java/java/nio/ByteBufferAsCharBuffer.java \
ojluni/src/main/java/java/nio/ByteBufferAsDoubleBuffer.java \
ojluni/src/main/java/java/nio/ByteBufferAsFloatBuffer.java \
ojluni/src/main/java/java/nio/ByteBufferAsIntBuffer.java \
ojluni/src/main/java/java/nio/ByteBufferAsLongBuffer.java \
ojluni/src/main/java/java/nio/ByteBufferAsShortBuffer.java \
- ojluni/src/main/java/java/nio/ByteBuffer.java \
ojluni/src/main/java/java/nio/ByteOrder.java \
- ojluni/src/main/java/java/nio/channels/AcceptPendingException.java \
- ojluni/src/main/java/java/nio/channels/AlreadyBoundException.java \
- ojluni/src/main/java/java/nio/channels/AlreadyConnectedException.java \
- ojluni/src/main/java/java/nio/channels/AsynchronousByteChannel.java \
- ojluni/src/main/java/java/nio/channels/AsynchronousChannelGroup.java \
- ojluni/src/main/java/java/nio/channels/AsynchronousChannel.java \
- ojluni/src/main/java/java/nio/channels/AsynchronousCloseException.java \
- ojluni/src/main/java/java/nio/channels/AsynchronousServerSocketChannel.java \
- ojluni/src/main/java/java/nio/channels/AsynchronousSocketChannel.java \
- ojluni/src/main/java/java/nio/channels/ByteChannel.java \
- ojluni/src/main/java/java/nio/channels/CancelledKeyException.java \
- ojluni/src/main/java/java/nio/channels/Channel.java \
- ojluni/src/main/java/java/nio/channels/Channels.java \
- ojluni/src/main/java/java/nio/channels/ClosedByInterruptException.java \
- ojluni/src/main/java/java/nio/channels/ClosedChannelException.java \
- ojluni/src/main/java/java/nio/channels/ClosedSelectorException.java \
- ojluni/src/main/java/java/nio/channels/CompletionHandler.java \
- ojluni/src/main/java/java/nio/channels/ConnectionPendingException.java \
- ojluni/src/main/java/java/nio/channels/DatagramChannel.java \
- ojluni/src/main/java/java/nio/channels/FileChannel.java \
- ojluni/src/main/java/java/nio/channels/FileLockInterruptionException.java \
- ojluni/src/main/java/java/nio/channels/FileLock.java \
- ojluni/src/main/java/java/nio/channels/GatheringByteChannel.java \
- ojluni/src/main/java/java/nio/channels/IllegalBlockingModeException.java \
- ojluni/src/main/java/java/nio/channels/IllegalChannelGroupException.java \
- ojluni/src/main/java/java/nio/channels/IllegalSelectorException.java \
- ojluni/src/main/java/java/nio/channels/InterruptedByTimeoutException.java \
- ojluni/src/main/java/java/nio/channels/InterruptibleChannel.java \
- ojluni/src/main/java/java/nio/channels/MembershipKey.java \
- ojluni/src/main/java/java/nio/channels/MulticastChannel.java \
- ojluni/src/main/java/java/nio/channels/NetworkChannel.java \
- ojluni/src/main/java/java/nio/channels/NoConnectionPendingException.java \
- ojluni/src/main/java/java/nio/channels/NonReadableChannelException.java \
- ojluni/src/main/java/java/nio/channels/NonWritableChannelException.java \
- ojluni/src/main/java/java/nio/channels/NotYetBoundException.java \
- ojluni/src/main/java/java/nio/channels/NotYetConnectedException.java \
- ojluni/src/main/java/java/nio/channels/OverlappingFileLockException.java \
- ojluni/src/main/java/java/nio/channels/Pipe.java \
- ojluni/src/main/java/java/nio/channels/ReadableByteChannel.java \
- ojluni/src/main/java/java/nio/channels/ReadPendingException.java \
- ojluni/src/main/java/java/nio/channels/ScatteringByteChannel.java \
- ojluni/src/main/java/java/nio/channels/SeekableByteChannel.java \
- ojluni/src/main/java/java/nio/channels/SelectableChannel.java \
- ojluni/src/main/java/java/nio/channels/SelectionKey.java \
- ojluni/src/main/java/java/nio/channels/Selector.java \
- ojluni/src/main/java/java/nio/channels/ServerSocketChannel.java \
- ojluni/src/main/java/java/nio/channels/ShutdownChannelGroupException.java \
- ojluni/src/main/java/java/nio/channels/SocketChannel.java \
- ojluni/src/main/java/java/nio/channels/spi/AbstractInterruptibleChannel.java \
- ojluni/src/main/java/java/nio/channels/spi/AbstractSelectableChannel.java \
- ojluni/src/main/java/java/nio/channels/spi/AbstractSelectionKey.java \
- ojluni/src/main/java/java/nio/channels/spi/AbstractSelector.java \
- ojluni/src/main/java/java/nio/channels/spi/AsynchronousChannelProvider.java \
- ojluni/src/main/java/java/nio/channels/spi/SelectorProvider.java \
- ojluni/src/main/java/java/nio/channels/UnresolvedAddressException.java \
- ojluni/src/main/java/java/nio/channels/UnsupportedAddressTypeException.java \
- ojluni/src/main/java/java/nio/channels/WritableByteChannel.java \
- ojluni/src/main/java/java/nio/channels/WritePendingException.java \
ojluni/src/main/java/java/nio/CharBuffer.java \
- ojluni/src/main/java/java/nio/charset/CharacterCodingException.java \
- ojluni/src/main/java/java/nio/charset/CharsetDecoder.java \
- ojluni/src/main/java/java/nio/charset/CharsetEncoder.java \
- ojluni/src/main/java/java/nio/charset/Charset.java \
- ojluni/src/main/java/java/nio/charset/CoderMalfunctionError.java \
- ojluni/src/main/java/java/nio/charset/CoderResult.java \
- ojluni/src/main/java/java/nio/charset/CodingErrorAction.java \
- ojluni/src/main/java/java/nio/charset/IllegalCharsetNameException.java \
- ojluni/src/main/java/java/nio/charset/MalformedInputException.java \
- ojluni/src/main/java/java/nio/charset/spi/CharsetProvider.java \
- ojluni/src/main/java/java/nio/charset/StandardCharsets.java \
- ojluni/src/main/java/java/nio/charset/UnmappableCharacterException.java \
- ojluni/src/main/java/java/nio/charset/UnsupportedCharsetException.java \
ojluni/src/main/java/java/nio/DirectByteBuffer.java \
ojluni/src/main/java/java/nio/DoubleBuffer.java \
ojluni/src/main/java/java/nio/FloatBuffer.java \
@@ -406,6 +335,62 @@
ojluni/src/main/java/java/nio/ReadOnlyBufferException.java \
ojluni/src/main/java/java/nio/ShortBuffer.java \
ojluni/src/main/java/java/nio/StringCharBuffer.java \
+ ojluni/src/main/java/java/nio/channels/AlreadyBoundException.java \
+ ojluni/src/main/java/java/nio/channels/AlreadyConnectedException.java \
+ ojluni/src/main/java/java/nio/channels/AsynchronousCloseException.java \
+ ojluni/src/main/java/java/nio/channels/ByteChannel.java \
+ ojluni/src/main/java/java/nio/channels/CancelledKeyException.java \
+ ojluni/src/main/java/java/nio/channels/Channel.java \
+ ojluni/src/main/java/java/nio/channels/Channels.java \
+ ojluni/src/main/java/java/nio/channels/ClosedByInterruptException.java \
+ ojluni/src/main/java/java/nio/channels/ClosedChannelException.java \
+ ojluni/src/main/java/java/nio/channels/ClosedSelectorException.java \
+ ojluni/src/main/java/java/nio/channels/ConnectionPendingException.java \
+ ojluni/src/main/java/java/nio/channels/DatagramChannel.java \
+ ojluni/src/main/java/java/nio/channels/FileChannel.java \
+ ojluni/src/main/java/java/nio/channels/FileLock.java \
+ ojluni/src/main/java/java/nio/channels/FileLockInterruptionException.java \
+ ojluni/src/main/java/java/nio/channels/GatheringByteChannel.java \
+ ojluni/src/main/java/java/nio/channels/IllegalBlockingModeException.java \
+ ojluni/src/main/java/java/nio/channels/IllegalSelectorException.java \
+ ojluni/src/main/java/java/nio/channels/InterruptibleChannel.java \
+ ojluni/src/main/java/java/nio/channels/NetworkChannel.java \
+ ojluni/src/main/java/java/nio/channels/NoConnectionPendingException.java \
+ ojluni/src/main/java/java/nio/channels/NonReadableChannelException.java \
+ ojluni/src/main/java/java/nio/channels/NonWritableChannelException.java \
+ ojluni/src/main/java/java/nio/channels/NotYetBoundException.java \
+ ojluni/src/main/java/java/nio/channels/NotYetConnectedException.java \
+ ojluni/src/main/java/java/nio/channels/OverlappingFileLockException.java \
+ ojluni/src/main/java/java/nio/channels/Pipe.java \
+ ojluni/src/main/java/java/nio/channels/ReadableByteChannel.java \
+ ojluni/src/main/java/java/nio/channels/ScatteringByteChannel.java \
+ ojluni/src/main/java/java/nio/channels/SeekableByteChannel.java \
+ ojluni/src/main/java/java/nio/channels/SelectableChannel.java \
+ ojluni/src/main/java/java/nio/channels/SelectionKey.java \
+ ojluni/src/main/java/java/nio/channels/Selector.java \
+ ojluni/src/main/java/java/nio/channels/ServerSocketChannel.java \
+ ojluni/src/main/java/java/nio/channels/SocketChannel.java \
+ ojluni/src/main/java/java/nio/channels/UnresolvedAddressException.java \
+ ojluni/src/main/java/java/nio/channels/UnsupportedAddressTypeException.java \
+ ojluni/src/main/java/java/nio/channels/WritableByteChannel.java \
+ ojluni/src/main/java/java/nio/channels/spi/AbstractInterruptibleChannel.java \
+ ojluni/src/main/java/java/nio/channels/spi/AbstractSelectableChannel.java \
+ ojluni/src/main/java/java/nio/channels/spi/AbstractSelectionKey.java \
+ ojluni/src/main/java/java/nio/channels/spi/AbstractSelector.java \
+ ojluni/src/main/java/java/nio/channels/spi/SelectorProvider.java \
+ ojluni/src/main/java/java/nio/charset/CharacterCodingException.java \
+ ojluni/src/main/java/java/nio/charset/Charset.java \
+ ojluni/src/main/java/java/nio/charset/CharsetDecoder.java \
+ ojluni/src/main/java/java/nio/charset/CharsetEncoder.java \
+ ojluni/src/main/java/java/nio/charset/CoderMalfunctionError.java \
+ ojluni/src/main/java/java/nio/charset/CoderResult.java \
+ ojluni/src/main/java/java/nio/charset/CodingErrorAction.java \
+ ojluni/src/main/java/java/nio/charset/IllegalCharsetNameException.java \
+ ojluni/src/main/java/java/nio/charset/MalformedInputException.java \
+ ojluni/src/main/java/java/nio/charset/StandardCharsets.java \
+ ojluni/src/main/java/java/nio/charset/UnmappableCharacterException.java \
+ ojluni/src/main/java/java/nio/charset/UnsupportedCharsetException.java \
+ ojluni/src/main/java/java/nio/charset/spi/CharsetProvider.java \
ojluni/src/main/java/java/security/AccessControlContext.java \
ojluni/src/main/java/java/security/AccessControlException.java \
ojluni/src/main/java/java/security/AccessController.java \
@@ -1101,17 +1086,11 @@
ojluni/src/main/java/sun/nio/ch/AbstractPollArrayWrapper.java \
ojluni/src/main/java/sun/nio/ch/AbstractPollSelectorImpl.java \
ojluni/src/main/java/sun/nio/ch/AllocatedNativeObject.java \
- ojluni/src/main/java/sun/nio/ch/AsynchronousChannelGroupImpl.java \
- ojluni/src/main/java/sun/nio/ch/AsynchronousServerSocketChannelImpl.java \
- ojluni/src/main/java/sun/nio/ch/AsynchronousSocketChannelImpl.java \
- ojluni/src/main/java/sun/nio/ch/BsdAsynchronousChannelProvider.java \
- ojluni/src/main/java/sun/nio/ch/Cancellable.java \
ojluni/src/main/java/sun/nio/ch/ChannelInputStream.java \
ojluni/src/main/java/sun/nio/ch/CompletedFuture.java \
ojluni/src/main/java/sun/nio/ch/DatagramChannelImpl.java \
ojluni/src/main/java/sun/nio/ch/DatagramDispatcher.java \
ojluni/src/main/java/sun/nio/ch/DatagramSocketAdaptor.java \
- ojluni/src/main/java/sun/nio/ch/DefaultAsynchronousChannelProvider.java \
ojluni/src/main/java/sun/nio/ch/DefaultSelectorProvider.java \
ojluni/src/main/java/sun/nio/ch/DevPollArrayWrapper.java \
ojluni/src/main/java/sun/nio/ch/DevPollSelectorImpl.java \
@@ -1119,7 +1098,6 @@
ojluni/src/main/java/sun/nio/ch/DirectBuffer.java \
ojluni/src/main/java/sun/nio/ch/EPollArrayWrapper.java \
ojluni/src/main/java/sun/nio/ch/EPoll.java \
- ojluni/src/main/java/sun/nio/ch/EPollPort.java \
ojluni/src/main/java/sun/nio/ch/EPollSelectorImpl.java \
ojluni/src/main/java/sun/nio/ch/EPollSelectorProvider.java \
ojluni/src/main/java/sun/nio/ch/ExtendedSocketOption.java \
@@ -1130,30 +1108,21 @@
ojluni/src/main/java/sun/nio/ch/FileKey.java \
ojluni/src/main/java/sun/nio/ch/FileLockImpl.java \
ojluni/src/main/java/sun/nio/ch/FileLockTable.java \
- ojluni/src/main/java/sun/nio/ch/Groupable.java \
ojluni/src/main/java/sun/nio/ch/InheritedChannel.java \
ojluni/src/main/java/sun/nio/ch/Interruptible.java \
- ojluni/src/main/java/sun/nio/ch/Invoker.java \
ojluni/src/main/java/sun/nio/ch/IOStatus.java \
ojluni/src/main/java/sun/nio/ch/IOUtil.java \
ojluni/src/main/java/sun/nio/ch/IOVecWrapper.java \
- ojluni/src/main/java/sun/nio/ch/KQueue.java \
- ojluni/src/main/java/sun/nio/ch/KQueuePort.java \
- ojluni/src/main/java/sun/nio/ch/LinuxAsynchronousChannelProvider.java \
- ojluni/src/main/java/sun/nio/ch/MembershipKeyImpl.java \
- ojluni/src/main/java/sun/nio/ch/MembershipRegistry.java \
ojluni/src/main/java/sun/nio/ch/NativeDispatcher.java \
ojluni/src/main/java/sun/nio/ch/NativeObject.java \
ojluni/src/main/java/sun/nio/ch/NativeThread.java \
ojluni/src/main/java/sun/nio/ch/NativeThreadSet.java \
ojluni/src/main/java/sun/nio/ch/Net.java \
ojluni/src/main/java/sun/nio/ch/OptionKey.java \
- ojluni/src/main/java/sun/nio/ch/PendingFuture.java \
ojluni/src/main/java/sun/nio/ch/PipeImpl.java \
ojluni/src/main/java/sun/nio/ch/PollArrayWrapper.java \
ojluni/src/main/java/sun/nio/ch/PollSelectorImpl.java \
ojluni/src/main/java/sun/nio/ch/PollSelectorProvider.java \
- ojluni/src/main/java/sun/nio/ch/Port.java \
ojluni/src/main/java/sun/nio/ch/Reflect.java \
ojluni/src/main/java/sun/nio/ch/SelChImpl.java \
ojluni/src/main/java/sun/nio/ch/SelectionKeyImpl.java \
@@ -1168,8 +1137,6 @@
ojluni/src/main/java/sun/nio/ch/SocketOptionRegistry.java \
ojluni/src/main/java/sun/nio/ch/SourceChannelImpl.java \
ojluni/src/main/java/sun/nio/ch/ThreadPool.java \
- ojluni/src/main/java/sun/nio/ch/UnixAsynchronousServerSocketChannelImpl.java \
- ojluni/src/main/java/sun/nio/ch/UnixAsynchronousSocketChannelImpl.java \
ojluni/src/main/java/sun/nio/ch/Util.java \
ojluni/src/main/java/sun/nio/cs/ArrayDecoder.java \
ojluni/src/main/java/sun/nio/cs/ArrayEncoder.java \