Source Code Cross Referenced for SocketTest.java in  » Apache-Harmony-Java-SE » org-package » org » apache » harmony » luni » tests » java » net » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Apache Harmony Java SE » org package » org.apache.harmony.luni.tests.java.net 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        /*
0002:         *  Licensed to the Apache Software Foundation (ASF) under one or more
0003:         *  contributor license agreements.  See the NOTICE file distributed with
0004:         *  this work for additional information regarding copyright ownership.
0005:         *  The ASF licenses this file to You under the Apache License, Version 2.0
0006:         *  (the "License"); you may not use this file except in compliance with
0007:         *  the License.  You may obtain a copy of the License at
0008:         *
0009:         *     http://www.apache.org/licenses/LICENSE-2.0
0010:         *
0011:         *  Unless required by applicable law or agreed to in writing, software
0012:         *  distributed under the License is distributed on an "AS IS" BASIS,
0013:         *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0014:         *  See the License for the specific language governing permissions and
0015:         *  limitations under the License.
0016:         */
0017:
0018:        package org.apache.harmony.luni.tests.java.net;
0019:
0020:        import java.io.IOException;
0021:        import java.io.InputStream;
0022:        import java.io.OutputStream;
0023:        import java.net.ConnectException;
0024:        import java.net.Inet4Address;
0025:        import java.net.Inet6Address;
0026:        import java.net.InetAddress;
0027:        import java.net.InetSocketAddress;
0028:        import java.net.Proxy;
0029:        import java.net.ServerSocket;
0030:        import java.net.Socket;
0031:        import java.net.SocketAddress;
0032:        import java.net.SocketException;
0033:        import java.net.SocketImpl;
0034:        import java.net.SocketTimeoutException;
0035:        import java.net.UnknownHostException;
0036:        import java.security.Permission;
0037:
0038:        import tests.support.Support_Configuration;
0039:
0040:        public class SocketTest extends SocketTestCase {
0041:            private class ClientThread implements  Runnable {
0042:
0043:                public void run() {
0044:                    try {
0045:                        Socket socket = new Socket();
0046:                        InetSocketAddress addr = new InetSocketAddress(host,
0047:                                port);
0048:                        socket.connect(addr);
0049:
0050:                        socket.close();
0051:                    } catch (IOException e) {
0052:                        throw new RuntimeException(e);
0053:                    }
0054:                }
0055:            }
0056:
0057:            private class ServerThread implements  Runnable {
0058:                private static final int FIRST_TIME = 1;
0059:
0060:                private static final int SECOND_TIME = 2;
0061:
0062:                private int backlog = 10;
0063:
0064:                public boolean ready = false;
0065:
0066:                private int serverSocketConstructor = 0;
0067:
0068:                public void run() {
0069:                    try {
0070:
0071:                        ServerSocket socket = null;
0072:                        switch (serverSocketConstructor) {
0073:                        case FIRST_TIME:
0074:                            socket = new ServerSocket(port, backlog,
0075:                                    new InetSocketAddress(host, port)
0076:                                            .getAddress());
0077:                            port = socket.getLocalPort();
0078:                            break;
0079:                        case SECOND_TIME:
0080:                            socket = new ServerSocket(port, backlog);
0081:                            host = socket.getInetAddress().getHostName();
0082:                            port = socket.getLocalPort();
0083:                            break;
0084:                        default:
0085:                            socket = new ServerSocket();
0086:                            break;
0087:                        }
0088:
0089:                        synchronized (this ) {
0090:                            ready = true;
0091:                            this .notifyAll();
0092:                        }
0093:
0094:                        socket.setSoTimeout(5000);
0095:                        socket.accept();
0096:
0097:                        socket.close();
0098:                    } catch (IOException e) {
0099:                        e.printStackTrace();
0100:                    } catch (Throwable e) {
0101:                        e.printStackTrace();
0102:                    }
0103:                }
0104:
0105:                public synchronized void waitCreated() throws Exception {
0106:                    while (!ready) {
0107:                        this .wait();
0108:                    }
0109:                }
0110:            }
0111:
0112:            boolean interrupted;
0113:
0114:            String host = "localhost";
0115:            int port;
0116:
0117:            Thread t;
0118:
0119:            private void connectTestImpl(int ssConsType) throws Exception {
0120:                ServerThread server = new ServerThread();
0121:                server.serverSocketConstructor = ssConsType;
0122:                Thread serverThread = new Thread(server);
0123:                serverThread.start();
0124:                server.waitCreated();
0125:
0126:                ClientThread client = new ClientThread();
0127:                Thread clientThread = new Thread(client);
0128:                clientThread.start();
0129:                try {
0130:                    serverThread.join();
0131:                    clientThread.join();
0132:                } catch (InterruptedException e) {
0133:                    e.printStackTrace();
0134:                }
0135:            }
0136:
0137:            protected void tearDown() {
0138:                try {
0139:                    if (t != null) {
0140:                        t.interrupt();
0141:                    }
0142:                } catch (Exception e) {
0143:                }
0144:                this .t = null;
0145:                this .interrupted = false;
0146:            }
0147:
0148:            /**
0149:             * @tests java.net.Socket#bind(java.net.SocketAddress)
0150:             */
0151:            public void test_bindLjava_net_SocketAddress() throws IOException {
0152:
0153:                @SuppressWarnings("serial")
0154:                class UnsupportedSocketAddress extends SocketAddress {
0155:                    public UnsupportedSocketAddress() {
0156:                    }
0157:                }
0158:
0159:                // Address we cannot bind to
0160:                Socket theSocket = new Socket();
0161:                InetSocketAddress bogusAddress = new InetSocketAddress(
0162:                        InetAddress
0163:                                .getByAddress(Support_Configuration.nonLocalAddressBytes),
0164:                        42);
0165:                try {
0166:                    theSocket.bind(bogusAddress);
0167:                    fail("No exception when binding to bad address");
0168:                } catch (IOException ex) {
0169:                    // Expected
0170:                }
0171:                theSocket.close();
0172:
0173:                // Now create a socket that is not bound and then bind it
0174:                theSocket = new Socket();
0175:                theSocket.bind(new InetSocketAddress(
0176:                        InetAddress.getLocalHost(), 0));
0177:                int portNumber = theSocket.getLocalPort();
0178:
0179:                // Validate that the localSocketAddress reflects the address we
0180:                // bound to
0181:                assertEquals("Local address not correct after bind",
0182:                        new InetSocketAddress(InetAddress.getLocalHost(),
0183:                                portNumber), theSocket.getLocalSocketAddress());
0184:
0185:                // Make sure we can now connect and that connections appear to come
0186:                // from the address we bound to.
0187:                InetSocketAddress theAddress = new InetSocketAddress(
0188:                        InetAddress.getLocalHost(), 0);
0189:                ServerSocket server = new ServerSocket();
0190:                server.bind(theAddress);
0191:                int sport = server.getLocalPort();
0192:                InetSocketAddress boundAddress = new InetSocketAddress(
0193:                        InetAddress.getLocalHost(), sport);
0194:
0195:                theSocket.connect(boundAddress);
0196:                Socket worker = server.accept();
0197:                assertEquals(
0198:                        "Returned Remote address from server connected to does not match expected local address",
0199:                        new InetSocketAddress(InetAddress.getLocalHost(),
0200:                                portNumber), worker.getRemoteSocketAddress());
0201:                theSocket.close();
0202:                worker.close();
0203:                server.close();
0204:
0205:                // Validate if we pass in null that it picks an address for us and
0206:                // all is ok
0207:                theSocket = new Socket();
0208:                theSocket.bind(null);
0209:                assertNotNull("Bind with null did not work", theSocket
0210:                        .getLocalSocketAddress());
0211:                theSocket.close();
0212:
0213:                // now check the error conditions
0214:
0215:                // Address that we have already bound to
0216:                theSocket = new Socket();
0217:                theAddress = new InetSocketAddress(InetAddress.getLocalHost(),
0218:                        0);
0219:                theSocket.bind(theAddress);
0220:
0221:                Socket theSocket2 = new Socket();
0222:                try {
0223:                    theSocket2.bind(theSocket.getLocalSocketAddress());
0224:                    fail("No exception binding to address that is not available");
0225:                } catch (IOException ex) {
0226:                    // Expected
0227:                }
0228:                theSocket.close();
0229:                theSocket2.close();
0230:
0231:                // Unsupported SocketAddress subclass
0232:                theSocket = new Socket();
0233:                try {
0234:                    theSocket.bind(new UnsupportedSocketAddress());
0235:                    fail("No exception when binding using unsupported SocketAddress subclass");
0236:                } catch (IllegalArgumentException ex) {
0237:                    // Expected
0238:                }
0239:                theSocket.close();
0240:            }
0241:
0242:            /**
0243:             * @tests java.net.Socket#bind(java.net.SocketAddress)
0244:             */
0245:            public void test_bindLjava_net_SocketAddress_Proxy()
0246:                    throws IOException {
0247:                // The Proxy will not impact on the bind operation. It can be assigned
0248:                // with any address.
0249:                Proxy proxy = new Proxy(Proxy.Type.SOCKS,
0250:                        new InetSocketAddress("127.0.0.1", 0));
0251:                Socket socket = new Socket(proxy);
0252:
0253:                InetAddress address = InetAddress.getByName("localhost");
0254:                socket.bind(new InetSocketAddress(address, 0));
0255:
0256:                assertEquals(address, socket.getLocalAddress());
0257:                assertTrue(0 != socket.getLocalPort());
0258:
0259:                socket.close();
0260:            }
0261:
0262:            /**
0263:             * @tests java.net.Socket#close()
0264:             */
0265:            public void test_close() throws IOException {
0266:                ServerSocket server = new ServerSocket(0);
0267:                Socket client = new Socket(InetAddress.getLocalHost(), server
0268:                        .getLocalPort());
0269:
0270:                try {
0271:                    client.setSoLinger(false, 100);
0272:                } catch (IOException e) {
0273:                    handleException(e, SO_LINGER);
0274:                }
0275:
0276:                client.close();
0277:                try {
0278:                    client.getOutputStream();
0279:                    fail("Failed to close socket");
0280:                } catch (IOException e) { // Caught Exception after close.
0281:                    // Expected
0282:                }
0283:
0284:                server.close();
0285:            }
0286:
0287:            /**
0288:             * @tests Socket#connect(SocketAddress) try an unknownhost
0289:             */
0290:            public void test_connect_unknownhost() throws Exception {
0291:                Socket socket = new Socket();
0292:                try {
0293:                    socket.connect(new InetSocketAddress("unknownhost.invalid",
0294:                            12345));
0295:                    fail("Should throw UnknownHostException");
0296:                } catch (UnknownHostException e) {
0297:                    // expected
0298:                }
0299:            }
0300:
0301:            /**
0302:             * @tests Socket#connect(SocketAddress)
0303:             */
0304:            public void test_connect_unresolved() throws IOException {
0305:                Socket socket = new Socket();
0306:
0307:                // Try a known host created by createUnresolved()
0308:                try {
0309:                    socket.connect(InetSocketAddress.createUnresolved(
0310:                            "www.apache.org", 80));
0311:                    fail("Should throw UnknownHostException");
0312:                } catch (UnknownHostException e) {
0313:                    // expected
0314:                }
0315:
0316:                // Try an unknown host created by createUnresolved()
0317:                try {
0318:                    socket.connect(InetSocketAddress.createUnresolved(
0319:                            "unknownhost.invalid", 12345));
0320:                    fail("Should throw UnknownHostException");
0321:                } catch (UnknownHostException e) {
0322:                    // expected
0323:                }
0324:            }
0325:
0326:            /**
0327:             * @tests java.net.Socket#connect(java.net.SocketAddress)
0328:             */
0329:            public void test_connectLjava_net_SocketAddress() throws Exception {
0330:
0331:                @SuppressWarnings("serial")
0332:                class UnsupportedSocketAddress extends SocketAddress {
0333:                    public UnsupportedSocketAddress() {
0334:                    }
0335:                }
0336:
0337:                Socket theSocket = new Socket();
0338:                try {
0339:                    theSocket.connect(null);
0340:                    fail("No exception for null arg");
0341:                } catch (IllegalArgumentException e) {
0342:                    // Expected
0343:                }
0344:
0345:                try {
0346:                    theSocket.connect(new UnsupportedSocketAddress());
0347:                    fail("No exception for invalid socket address");
0348:                } catch (IllegalArgumentException e) {
0349:                    // Expected
0350:                }
0351:
0352:                try {
0353:                    theSocket.connect(new InetSocketAddress(InetAddress
0354:                            .getByAddress(new byte[] { 0, 0, 0, 0 }), 42));
0355:                    fail("No exception with non-connectable address");
0356:                } catch (ConnectException e) {
0357:                    // Expected
0358:                }
0359:
0360:                // now validate that we get a connect exception if we try to connect to
0361:                // an address on which nobody is listening
0362:                theSocket = new Socket();
0363:                try {
0364:                    theSocket.connect(new InetSocketAddress(InetAddress
0365:                            .getLocalHost(), 0));
0366:                    fail("No exception when connecting to address nobody listening on");
0367:                } catch (ConnectException e) {
0368:                    // Expected
0369:                }
0370:
0371:                // Now validate that we can actually connect when somebody is listening
0372:                ServerSocket server = new ServerSocket(0);
0373:                InetSocketAddress boundAddress = new InetSocketAddress(
0374:                        InetAddress.getLocalHost(), server.getLocalPort());
0375:                Socket client = new Socket();
0376:                client.connect(boundAddress);
0377:
0378:                // validate that when a socket is connected that it answers
0379:                // correctly to related queries
0380:                assertTrue("Wrong connected status", client.isConnected());
0381:                assertFalse("Wrong closed status", client.isClosed());
0382:                assertTrue("Wrong bound status", client.isBound());
0383:                assertFalse("Wrong input shutdown status", client
0384:                        .isInputShutdown());
0385:                assertFalse("Wrong output shutdown status", client
0386:                        .isOutputShutdown());
0387:                assertTrue("Local port was 0", client.getLocalPort() != 0);
0388:
0389:                client.close();
0390:                server.close();
0391:
0392:                // Now validate that we get the right exception if we connect when we
0393:                // are already connected
0394:                server = new ServerSocket(0);
0395:                boundAddress = new InetSocketAddress(
0396:                        InetAddress.getLocalHost(), server.getLocalPort());
0397:                client = new Socket();
0398:                client.connect(boundAddress);
0399:
0400:                try {
0401:                    client.connect(boundAddress);
0402:                    fail("No exception when we try to connect on a connected socket: ");
0403:                } catch (SocketException e) {
0404:                    // Expected
0405:                }
0406:                client.close();
0407:                server.close();
0408:            }
0409:
0410:            /**
0411:             * Regression for Harmony-2503
0412:             */
0413:            public void test_connectLjava_net_SocketAddress_AnyAddress()
0414:                    throws Exception {
0415:                connectTestImpl(ServerThread.FIRST_TIME);
0416:                connectTestImpl(ServerThread.SECOND_TIME);
0417:            }
0418:
0419:            /**
0420:             * @tests java.net.Socket#connect(java.net.SocketAddress, int)
0421:             */
0422:            public void test_connectLjava_net_SocketAddressI() throws Exception {
0423:
0424:                @SuppressWarnings("serial")
0425:                class UnsupportedSocketAddress extends SocketAddress {
0426:                    public UnsupportedSocketAddress() {
0427:                    }
0428:                }
0429:
0430:                // Start by validating the error checks
0431:                Socket theSocket = new Socket();
0432:                try {
0433:                    theSocket.connect(new InetSocketAddress(0), -100);
0434:                    fail("No exception for negative timeout");
0435:                } catch (IllegalArgumentException e) {
0436:                    // Expected
0437:                }
0438:
0439:                try {
0440:                    theSocket.connect(null, 0);
0441:                    fail("No exception for null address");
0442:                } catch (IllegalArgumentException e) {
0443:                    // Expected
0444:                }
0445:
0446:                try {
0447:                    theSocket.connect(new UnsupportedSocketAddress(), 1000);
0448:                    fail("No exception for invalid socket address type");
0449:                } catch (IllegalArgumentException e) {
0450:                    // Expected
0451:                }
0452:
0453:                SocketAddress nonConnectableAddress = new InetSocketAddress(
0454:                        InetAddress.getByAddress(new byte[] { 0, 0, 0, 0 }), 0);
0455:                try {
0456:                    theSocket.connect(nonConnectableAddress, 1000);
0457:                    fail("No exception when non Connectable Address passed in: ");
0458:                } catch (SocketException e) {
0459:                    // Expected
0460:                }
0461:
0462:                // Now validate that we get a connect exception if we try to connect to
0463:                // an address on which nobody is listening
0464:                theSocket = new Socket();
0465:                try {
0466:                    theSocket.connect(new InetSocketAddress(InetAddress
0467:                            .getLocalHost(), 0), 0);
0468:                    fail("No exception when connecting to address nobody listening on");
0469:                } catch (ConnectException e) {
0470:                    // Expected
0471:                }
0472:                theSocket.close();
0473:
0474:                // Now validate that we can actually connect when somebody is listening
0475:                ServerSocket server = new ServerSocket(0);
0476:                InetSocketAddress boundAddress = new InetSocketAddress(
0477:                        InetAddress.getLocalHost(), server.getLocalPort());
0478:                Socket client = new Socket();
0479:                client.connect(boundAddress, 0);
0480:
0481:                // Validate that when a socket is connected that it answers
0482:                // correctly to related queries
0483:                assertTrue("Wrong connected status", client.isConnected());
0484:                assertFalse("Wrong closed status", client.isClosed());
0485:                assertTrue("Wrong bound status", client.isBound());
0486:                assertFalse("Wrong input shutdown status", client
0487:                        .isInputShutdown());
0488:                assertFalse("Wrong output shutdown status", client
0489:                        .isOutputShutdown());
0490:                assertTrue("Local port was 0", client.getLocalPort() != 0);
0491:
0492:                client.close();
0493:                server.close();
0494:
0495:                // Now validate that we get a connect exception if we try to connect to
0496:                // an address on which nobody is listening
0497:                theSocket = new Socket();
0498:                SocketAddress nonListeningAddress = new InetSocketAddress(
0499:                        InetAddress.getLocalHost(), 42);
0500:                try {
0501:                    theSocket.connect(nonListeningAddress, 1000);
0502:                    fail("No exception when connecting to address nobody listening on");
0503:                } catch (ConnectException e) {
0504:                    // Expected
0505:                } catch (SocketTimeoutException e) {
0506:                    // The other possibility is that the system timed us out.
0507:                }
0508:                theSocket.close();
0509:
0510:                // Now validate that we get a interrupted exception if we try to connect
0511:                // to an address on which nobody is accepting connections and the
0512:                // timeout expired
0513:                theSocket = new Socket();
0514:                try {
0515:                    theSocket.connect(new InetSocketAddress(InetAddress
0516:                            .getLocalHost(), 1), 200);
0517:                    fail("No interrupted exception when connecting to address nobody listening on with short timeout 200");
0518:                } catch (SocketTimeoutException e) {
0519:                    // Expected
0520:                }
0521:                theSocket.close();
0522:
0523:                // Now validate that we get the right exception if we connect when we
0524:                // are already connected
0525:                server = new ServerSocket(0);
0526:                boundAddress = new InetSocketAddress(
0527:                        InetAddress.getLocalHost(), server.getLocalPort());
0528:                client = new Socket();
0529:                client.connect(boundAddress, 10000);
0530:
0531:                try {
0532:                    client.connect(boundAddress, 10000);
0533:                    fail("No exception when we try to connect on a connected socket: ");
0534:                } catch (SocketException e) {
0535:                    // Expected
0536:                }
0537:                client.close();
0538:                server.close();
0539:            }
0540:
0541:            /**
0542:             * @tests java.net.Socket#Socket()
0543:             */
0544:            public void test_Constructor() {
0545:                // create the socket and then validate some basic state
0546:                Socket s = new Socket();
0547:                assertFalse("new socket should not be connected", s
0548:                        .isConnected());
0549:                assertFalse("new socket should not be bound", s.isBound());
0550:                assertFalse("new socket should not be closed", s.isClosed());
0551:                assertFalse("new socket should not be in InputShutdown", s
0552:                        .isInputShutdown());
0553:                assertFalse("new socket should not be in OutputShutdown", s
0554:                        .isOutputShutdown());
0555:            }
0556:
0557:            /**
0558:             * @tests java.net.Socket#Socket(java.lang.String, int)
0559:             */
0560:            public void test_ConstructorLjava_lang_StringI() throws IOException {
0561:                ServerSocket server = new ServerSocket(0);
0562:                Socket client = new Socket(InetAddress.getLocalHost(), server
0563:                        .getLocalPort());
0564:
0565:                assertEquals("Failed to create socket", server.getLocalPort(),
0566:                        client.getPort());
0567:
0568:                // Regression for HARMONY-946
0569:                ServerSocket ss = new ServerSocket(0);
0570:                Socket s = new Socket("0.0.0.0 ", ss.getLocalPort());
0571:                ss.close();
0572:                s.close();
0573:            }
0574:
0575:            /**
0576:             * @tests java.net.Socket#Socket(java.lang.String, int,
0577:             *        java.net.InetAddress, int)
0578:             */
0579:            public void test_ConstructorLjava_lang_StringILjava_net_InetAddressI()
0580:                    throws IOException {
0581:
0582:                ServerSocket server = new ServerSocket(0);
0583:                int serverPort = server.getLocalPort();
0584:                Socket client = new Socket(InetAddress.getLocalHost()
0585:                        .getHostName(), serverPort, InetAddress.getLocalHost(),
0586:                        0);
0587:                assertTrue("Failed to create socket",
0588:                        client.getPort() == serverPort);
0589:                client.close();
0590:
0591:                Socket theSocket = null;
0592:                try {
0593:                    theSocket = new Socket("127.0.0.1", serverPort, InetAddress
0594:                            .getLocalHost(), 0);
0595:                } catch (IOException e) {
0596:                    // check here if InetAddress.getLocalHost() is returning the
0597:                    // loopback address, if so that is likely the cause of the failure
0598:                    assertFalse(
0599:                            "Misconfiguration - local host is the loopback address",
0600:                            InetAddress.getLocalHost().isLoopbackAddress());
0601:                    throw e;
0602:                }
0603:
0604:                assertTrue(theSocket.isConnected());
0605:
0606:                try {
0607:                    new Socket("127.0.0.1", serverPort, theSocket
0608:                            .getLocalAddress(), theSocket.getLocalPort());
0609:                    fail("Was able to create two sockets on same port");
0610:                } catch (IOException e) {
0611:                    // Expected
0612:                }
0613:
0614:                theSocket.close();
0615:                server.close();
0616:            }
0617:
0618:            /**
0619:             * @tests java.net.Socket#Socket(java.lang.String, int,
0620:             *        java.net.InetAddress, int)
0621:             */
0622:            public void test_ConstructorLjava_lang_StringILjava_net_InetAddressI_ipv6()
0623:                    throws IOException {
0624:
0625:                boolean preferIPv6 = "true".equals(System
0626:                        .getProperty("java.net.preferIPv6Addresses"));
0627:                boolean preferIPv4 = "true".equals(System
0628:                        .getProperty("java.net.preferIPv4Stack"));
0629:                boolean runIPv6 = "true".equals(System
0630:                        .getProperty("run.ipv6tests"));
0631:
0632:                if (!runIPv6 || !preferIPv6 || preferIPv4) {
0633:                    // This test is not for me
0634:                    return;
0635:                }
0636:
0637:                ServerSocket server = new ServerSocket(0);
0638:                int serverPort = server.getLocalPort();
0639:                Socket client = new Socket(InetAddress.getLocalHost()
0640:                        .getHostName(), serverPort, InetAddress.getLocalHost(),
0641:                        0);
0642:                assertTrue("Failed to create socket",
0643:                        client.getPort() == serverPort);
0644:                client.close();
0645:
0646:                Socket theSocket = null;
0647:                try {
0648:                    theSocket = new Socket(
0649:                            Support_Configuration.IPv6GlobalAddressJcl4,
0650:                            serverPort, InetAddress.getLocalHost(), 0);
0651:                } catch (IOException e) {
0652:                    // check here if InetAddress.getLocalHost() is returning the
0653:                    // loopback address, if so that is likely the cause of the failure
0654:                    assertFalse(
0655:                            "Misconfiguration - local host is the loopback address",
0656:                            InetAddress.getLocalHost().isLoopbackAddress());
0657:                    throw e;
0658:                }
0659:
0660:                assertTrue(theSocket.isConnected());
0661:
0662:                try {
0663:                    new Socket(Support_Configuration.IPv6GlobalAddressJcl4,
0664:                            serverPort, theSocket.getLocalAddress(), theSocket
0665:                                    .getLocalPort());
0666:                    fail("Was able to create two sockets on same port");
0667:                } catch (IOException e) {
0668:                    // Expected
0669:                }
0670:
0671:                theSocket.close();
0672:                server.close();
0673:            }
0674:
0675:            /**
0676:             * @tests java.net.Socket#Socket(java.lang.String, int, boolean)
0677:             */
0678:            @SuppressWarnings("deprecation")
0679:            public void test_ConstructorLjava_lang_StringIZ()
0680:                    throws IOException {
0681:                ServerSocket server = new ServerSocket(0);
0682:                int serverPort = server.getLocalPort();
0683:                Socket client = new Socket(InetAddress.getLocalHost()
0684:                        .getHostAddress(), serverPort, true);
0685:
0686:                assertEquals("Failed to create socket", serverPort, client
0687:                        .getPort());
0688:                client.close();
0689:
0690:                client = new Socket(InetAddress.getLocalHost().getHostName(),
0691:                        serverPort, false);
0692:                client.close();
0693:                server.close();
0694:            }
0695:
0696:            /**
0697:             * @tests java.net.Socket#Socket(java.net.InetAddress, int)
0698:             */
0699:            public void test_ConstructorLjava_net_InetAddressI()
0700:                    throws IOException {
0701:                ServerSocket server = new ServerSocket(0);
0702:                Socket client = new Socket(InetAddress.getLocalHost(), server
0703:                        .getLocalPort());
0704:
0705:                assertEquals("Failed to create socket", server.getLocalPort(),
0706:                        client.getPort());
0707:
0708:                client.close();
0709:                server.close();
0710:            }
0711:
0712:            /**
0713:             * @tests java.net.Socket#Socket(java.net.InetAddress, int,
0714:             *        java.net.InetAddress, int)
0715:             */
0716:            public void test_ConstructorLjava_net_InetAddressILjava_net_InetAddressI()
0717:                    throws IOException {
0718:                ServerSocket server = new ServerSocket(0);
0719:                Socket client = new Socket(InetAddress.getLocalHost(), server
0720:                        .getLocalPort(), InetAddress.getLocalHost(), 0);
0721:                assertNotSame("Failed to create socket", 0, client
0722:                        .getLocalPort());
0723:            }
0724:
0725:            /**
0726:             * @tests java.net.Socket#Socket(java.net.InetAddress, int, boolean)
0727:             */
0728:            @SuppressWarnings("deprecation")
0729:            public void test_ConstructorLjava_net_InetAddressIZ()
0730:                    throws IOException {
0731:                ServerSocket server = new ServerSocket(0);
0732:                int serverPort = server.getLocalPort();
0733:
0734:                Socket client = new Socket(InetAddress.getLocalHost(),
0735:                        serverPort, true);
0736:                assertEquals("Failed to create socket", serverPort, client
0737:                        .getPort());
0738:
0739:                client = new Socket(InetAddress.getLocalHost(), serverPort,
0740:                        false);
0741:                client.close();
0742:            }
0743:
0744:            /**
0745:             * @tests java.net.Socket#Socket(Proxy)
0746:             */
0747:            public void test_ConstructorLjava_net_Proxy_Exception() {
0748:
0749:                class MockSecurityManager extends SecurityManager {
0750:
0751:                    public void checkConnect(String host, int port) {
0752:                        if ("127.0.0.1".equals(host)) {
0753:                            throw new SecurityException(
0754:                                    "permission is not allowed");
0755:                        }
0756:                    }
0757:
0758:                    public void checkPermission(Permission permission) {
0759:                        return;
0760:                    }
0761:                }
0762:
0763:                SocketAddress addr1 = InetSocketAddress.createUnresolved(
0764:                        "127.0.0.1", 80);
0765:                SocketAddress addr2 = new InetSocketAddress("localhost", 80);
0766:
0767:                Proxy proxy1 = new Proxy(Proxy.Type.HTTP, addr1);
0768:                // IllegalArgumentException test
0769:                try {
0770:                    new Socket(proxy1);
0771:                    fail("should throw IllegalArgumentException");
0772:                } catch (IllegalArgumentException e) {
0773:                    // expected
0774:                }
0775:
0776:                Proxy proxy2 = new Proxy(Proxy.Type.SOCKS, addr1);
0777:                // should not throw any exception
0778:                new Socket(proxy2);
0779:                new Socket(Proxy.NO_PROXY);
0780:
0781:                // SecurityException test
0782:                SecurityManager originalSecurityManager = System
0783:                        .getSecurityManager();
0784:                try {
0785:                    System.setSecurityManager(new MockSecurityManager());
0786:                } catch (SecurityException e) {
0787:                    System.err
0788:                            .println("No permission to setSecurityManager, security related test in test_ConstructorLjava_net_Proxy_Security is ignored");
0789:                    return;
0790:                }
0791:
0792:                Proxy proxy3 = new Proxy(Proxy.Type.SOCKS, addr1);
0793:                Proxy proxy4 = new Proxy(Proxy.Type.SOCKS, addr2);
0794:                try {
0795:                    try {
0796:                        new Socket(proxy3);
0797:                        fail("should throw SecurityException");
0798:                    } catch (SecurityException e) {
0799:                        // expected
0800:                    }
0801:                    try {
0802:                        new Socket(proxy4);
0803:                        fail("should throw SecurityException");
0804:                    } catch (SecurityException e) {
0805:                        // expected
0806:                    }
0807:                } finally {
0808:                    System.setSecurityManager(originalSecurityManager);
0809:                }
0810:
0811:            }
0812:
0813:            /**
0814:             * @tests java.net.Socket#getChannel()
0815:             */
0816:            public void test_getChannel() {
0817:                assertNull(new Socket().getChannel());
0818:            }
0819:
0820:            /**
0821:             * @tests java.net.Socket#getInetAddress()
0822:             */
0823:            public void test_getInetAddress() throws IOException {
0824:                ServerSocket server = new ServerSocket(0);
0825:                Socket client = new Socket(InetAddress.getLocalHost(), server
0826:                        .getLocalPort());
0827:
0828:                assertTrue("Returned incorrect InetAdrees", client
0829:                        .getInetAddress().equals(InetAddress.getLocalHost()));
0830:
0831:                client.close();
0832:                server.close();
0833:            }
0834:
0835:            /**
0836:             * @tests java.net.Socket#getInputStream()
0837:             */
0838:            public void test_getInputStream() throws IOException {
0839:                // Simple fetch test
0840:                ServerSocket server = new ServerSocket(0);
0841:                Socket client = new Socket(InetAddress.getLocalHost(), server
0842:                        .getLocalPort());
0843:                InputStream is = client.getInputStream();
0844:                assertNotNull("Failed to get stream", is);
0845:                is.close();
0846:                client.close();
0847:                server.close();
0848:
0849:                // Simple read/write test over the IO streams
0850:                final ServerSocket pingServer = new ServerSocket(0);
0851:                Runnable runnable = new Runnable() {
0852:                    public void run() {
0853:                        try {
0854:                            Socket worker = pingServer.accept();
0855:                            pingServer.close();
0856:                            InputStream in = worker.getInputStream();
0857:                            in.read();
0858:                            OutputStream out = worker.getOutputStream();
0859:                            out.write(new byte[42]);
0860:                            worker.close();
0861:                        } catch (IOException e) {
0862:                            fail(e.getMessage());
0863:                        }
0864:                    }
0865:                };
0866:                Thread thread = new Thread(runnable, "Socket.getInputStream");
0867:                thread.start();
0868:
0869:                Socket pingClient = new Socket(InetAddress.getLocalHost(),
0870:                        pingServer.getLocalPort());
0871:
0872:                // Busy wait until the client is connected.
0873:                int c = 0;
0874:                while (!pingClient.isConnected()) {
0875:                    try {
0876:                        Thread.sleep(200);
0877:                    } catch (InterruptedException e) {
0878:                    }
0879:                    if (++c > 4) {
0880:                        fail("thread is not alive");
0881:                    }
0882:                }
0883:
0884:                // Write some data to the server to provoke it
0885:                OutputStream out = pingClient.getOutputStream();
0886:                out.write(new byte[256]);
0887:
0888:                InputStream in = pingClient.getInputStream();
0889:                in.read(new byte[42]);
0890:
0891:                // Check EOF
0892:                assertEquals(-1, in.read());
0893:
0894:                in.close();
0895:
0896:                // No exception when reading a closed stream
0897:                assertEquals(-1, in.read());
0898:
0899:                pingClient.close();
0900:                pingServer.close();
0901:            }
0902:
0903:            /**
0904:             * @tests java.net.Socket#getKeepAlive()
0905:             */
0906:            public void test_getKeepAlive() {
0907:                try {
0908:                    ServerSocket server = new ServerSocket(0);
0909:                    Socket client = new Socket(InetAddress.getLocalHost(),
0910:                            server.getLocalPort(), null, 0);
0911:
0912:                    client.setKeepAlive(true);
0913:                    assertTrue("getKeepAlive false when it should be true",
0914:                            client.getKeepAlive());
0915:
0916:                    client.setKeepAlive(false);
0917:                    assertFalse("getKeepAlive true when it should be False",
0918:                            client.getKeepAlive());
0919:                    ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_KEEPALIVE);
0920:                } catch (Exception e) {
0921:                    handleException(e, SO_KEEPALIVE);
0922:                }
0923:            }
0924:
0925:            /**
0926:             * @tests java.net.Socket#getLocalAddress()
0927:             */
0928:            public void test_getLocalAddress() throws IOException {
0929:                ServerSocket server = new ServerSocket(0);
0930:                Socket client = new Socket(InetAddress.getLocalHost(), server
0931:                        .getLocalPort());
0932:
0933:                assertTrue("Returned incorrect InetAddress", client
0934:                        .getLocalAddress().equals(InetAddress.getLocalHost()));
0935:
0936:                // now validate that behaviour when the any address is returned
0937:                String preferIPv4StackValue = System
0938:                        .getProperty("java.net.preferIPv4Stack");
0939:                String preferIPv6AddressesValue = System
0940:                        .getProperty("java.net.preferIPv6Addresses");
0941:
0942:                client = new Socket();
0943:                client.bind(new InetSocketAddress(InetAddress
0944:                        .getByName("0.0.0.0"), 0));
0945:
0946:                if (((preferIPv4StackValue == null) || preferIPv4StackValue
0947:                        .equalsIgnoreCase("false"))
0948:                        && (preferIPv6AddressesValue != null)
0949:                        && (preferIPv6AddressesValue.equals("true"))) {
0950:                    assertTrue(
0951:                            "ANY address not returned correctly (getLocalAddress) with preferIPv6Addresses=true, preferIPv4Stack=false "
0952:                                    + client.getLocalSocketAddress(), client
0953:                                    .getLocalAddress() instanceof  Inet6Address);
0954:                } else {
0955:                    assertTrue(
0956:                            "ANY address not returned correctly (getLocalAddress) with preferIPv6Addresses=true, preferIPv4Stack=true "
0957:                                    + client.getLocalSocketAddress(), client
0958:                                    .getLocalAddress() instanceof  Inet4Address);
0959:                }
0960:                client.close();
0961:                server.close();
0962:            }
0963:
0964:            /**
0965:             * @tests java.net.Socket#getLocalPort()
0966:             */
0967:            public void test_getLocalPort() throws IOException {
0968:                ServerSocket server = new ServerSocket(0);
0969:                Socket client = new Socket(InetAddress.getLocalHost(), server
0970:                        .getLocalPort());
0971:
0972:                assertNotSame("Returned incorrect port", 0, client
0973:                        .getLocalPort());
0974:
0975:                client.close();
0976:                server.close();
0977:            }
0978:
0979:            /**
0980:             * @tests java.net.Socket#getLocalSocketAddress()
0981:             */
0982:            public void test_getLocalSocketAddress() throws IOException {
0983:                // set up server connect and then validate that we get the right
0984:                // response for the local address
0985:                ServerSocket server = new ServerSocket(0);
0986:                Socket client = new Socket(InetAddress.getLocalHost(), server
0987:                        .getLocalPort());
0988:                int clientPort = client.getLocalPort();
0989:
0990:                assertEquals("Returned incorrect InetSocketAddress(1):",
0991:                        new InetSocketAddress(InetAddress.getLocalHost(),
0992:                                clientPort), client.getLocalSocketAddress());
0993:                client.close();
0994:                server.close();
0995:
0996:                // now create a socket that is not bound and validate we get the
0997:                // right answer
0998:                client = new Socket();
0999:                assertNull(
1000:                        "Returned incorrect InetSocketAddress -unbound socket- Expected null",
1001:                        client.getLocalSocketAddress());
1002:
1003:                // now bind the socket and make sure we get the right answer
1004:                client
1005:                        .bind(new InetSocketAddress(InetAddress.getLocalHost(),
1006:                                0));
1007:                clientPort = client.getLocalPort();
1008:                assertEquals("Returned incorrect InetSocketAddress(2):",
1009:                        new InetSocketAddress(InetAddress.getLocalHost(),
1010:                                clientPort), client.getLocalSocketAddress());
1011:                client.close();
1012:
1013:                // now validate the behaviour when the any address is returned
1014:                client = new Socket();
1015:                client.bind(new InetSocketAddress(InetAddress
1016:                        .getByName("0.0.0.0"), 0));
1017:
1018:                String preferIPv4StackValue = System
1019:                        .getProperty("java.net.preferIPv4Stack");
1020:                String preferIPv6AddressesValue = System
1021:                        .getProperty("java.net.preferIPv6Addresses");
1022:                if (((preferIPv4StackValue == null) || preferIPv4StackValue
1023:                        .equalsIgnoreCase("false"))
1024:                        && (preferIPv6AddressesValue != null)
1025:                        && (preferIPv6AddressesValue.equals("true"))) {
1026:                    assertTrue(
1027:                            "ANY address not returned correctly with preferIPv6Addresses=true, preferIPv4Stack=false "
1028:                                    + client.getLocalSocketAddress(),
1029:                            ((InetSocketAddress) client.getLocalSocketAddress())
1030:                                    .getAddress() instanceof  Inet6Address);
1031:                } else {
1032:                    assertTrue(
1033:                            "ANY address not returned correctly with preferIPv6Addresses=true, preferIPv4Stack=true "
1034:                                    + client.getLocalSocketAddress(),
1035:                            ((InetSocketAddress) client.getLocalSocketAddress())
1036:                                    .getAddress() instanceof  Inet4Address);
1037:                }
1038:                client.close();
1039:
1040:                // now validate the same for getLocalAddress
1041:                client = new Socket();
1042:                client.bind(new InetSocketAddress(InetAddress
1043:                        .getByName("0.0.0.0"), 0));
1044:                if (((preferIPv4StackValue == null) || preferIPv4StackValue
1045:                        .equalsIgnoreCase("false"))
1046:                        && (preferIPv6AddressesValue != null)
1047:                        && (preferIPv6AddressesValue.equals("true"))) {
1048:                    assertTrue(
1049:                            "ANY address not returned correctly with preferIPv6Addresses=true, preferIPv4Stack=false "
1050:                                    + client.getLocalSocketAddress(),
1051:                            ((InetSocketAddress) client.getLocalSocketAddress())
1052:                                    .getAddress() instanceof  Inet6Address);
1053:                } else {
1054:                    assertTrue(
1055:                            "ANY address not returned correctly with preferIPv6Addresses=true, preferIPv4Stack=true "
1056:                                    + client.getLocalSocketAddress(),
1057:                            ((InetSocketAddress) client.getLocalSocketAddress())
1058:                                    .getAddress() instanceof  Inet4Address);
1059:                }
1060:                client.close();
1061:            }
1062:
1063:            /**
1064:             * @tests java.net.Socket#getOOBInline()
1065:             */
1066:            public void test_getOOBInline() {
1067:                try {
1068:                    Socket theSocket = new Socket();
1069:
1070:                    theSocket.setOOBInline(true);
1071:                    assertTrue("expected OOBIline to be true", theSocket
1072:                            .getOOBInline());
1073:
1074:                    theSocket.setOOBInline(false);
1075:                    assertFalse("expected OOBIline to be false", theSocket
1076:                            .getOOBInline());
1077:
1078:                    theSocket.setOOBInline(false);
1079:                    assertFalse("expected OOBIline to be false", theSocket
1080:                            .getOOBInline());
1081:
1082:                    ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_OOBINLINE);
1083:                } catch (Exception e) {
1084:                    handleException(e, SO_OOBINLINE);
1085:                }
1086:            }
1087:
1088:            /**
1089:             * @tests java.net.Socket#getOutputStream()
1090:             */
1091:            @SuppressWarnings("deprecation")
1092:            public void test_getOutputStream() throws IOException {
1093:                // Simple fetch test
1094:                ServerSocket server = new ServerSocket(0);
1095:                Socket client = new Socket(InetAddress.getLocalHost(), server
1096:                        .getLocalPort());
1097:                OutputStream os = client.getOutputStream();
1098:                assertNotNull("Failed to get stream", os);
1099:                os.close();
1100:                client.close();
1101:                server.close();
1102:
1103:                // Simple read/write test over the IO streams
1104:                final ServerSocket sinkServer = new ServerSocket(0);
1105:                Runnable runnable = new Runnable() {
1106:                    public void run() {
1107:                        try {
1108:                            Socket worker = sinkServer.accept();
1109:                            sinkServer.close();
1110:                            InputStream in = worker.getInputStream();
1111:                            in.read();
1112:                            in.close();
1113:                            worker.close();
1114:                        } catch (IOException e) {
1115:                            fail();
1116:                        }
1117:                    }
1118:                };
1119:                Thread thread = new Thread(runnable, "Socket.getOutputStream");
1120:                thread.start();
1121:
1122:                Socket pingClient = new Socket(InetAddress.getLocalHost(),
1123:                        sinkServer.getLocalPort());
1124:
1125:                // Busy wait until the client is connected.
1126:                int c = 0;
1127:                while (!pingClient.isConnected()) {
1128:                    try {
1129:                        Thread.sleep(200);
1130:                    } catch (InterruptedException e) {
1131:                    }
1132:                    if (++c > 4) {
1133:                        fail("thread is not alive");
1134:                    }
1135:                }
1136:
1137:                // Write some data to the server
1138:                OutputStream out = pingClient.getOutputStream();
1139:                out.write(new byte[256]);
1140:
1141:                // Wait for the server to finish
1142:                Thread.yield();
1143:                c = 0;
1144:                while (thread.isAlive()) {
1145:                    try {
1146:                        Thread.sleep(200);
1147:                    } catch (InterruptedException e) {
1148:                    }
1149:                    if (++c > 4) {
1150:                        fail("read call did not exit");
1151:                    }
1152:                }
1153:
1154:                // Subsequent writes should throw an exception
1155:                try {
1156:                    // The output buffer may remain valid until the close completes
1157:                    for (int i = 0; i < 400; i++) {
1158:                        out.write(new byte[256]);
1159:                    }
1160:                    fail("write to closed socket did not cause exception");
1161:                } catch (IOException e) {
1162:                    // Expected
1163:                }
1164:
1165:                out.close();
1166:                pingClient.close();
1167:                sinkServer.close();
1168:
1169:                // Regression test for HARMONY-2934
1170:                Socket socket = new Socket("127.0.0.1", 0, false);
1171:                OutputStream o = socket.getOutputStream();
1172:                o.write(1);
1173:                socket.close();
1174:
1175:                // Regression test for HARMONY-873
1176:                ServerSocket ss2 = new ServerSocket(0);
1177:                Socket s = new Socket("127.0.0.1", ss2.getLocalPort());
1178:                ss2.accept();
1179:                s.shutdownOutput();
1180:                try {
1181:                    s.getOutputStream();
1182:                    fail("should throw SocketException");
1183:                } catch (SocketException e) {
1184:                    // expected
1185:                }
1186:            }
1187:
1188:            /**
1189:             * @tests java.net.Socket#getPort()
1190:             */
1191:            public void test_getPort() throws IOException {
1192:                ServerSocket server = new ServerSocket(0);
1193:                int serverPort = server.getLocalPort();
1194:                Socket client = new Socket(InetAddress.getLocalHost(),
1195:                        serverPort);
1196:
1197:                assertEquals("Returned incorrect port", serverPort, client
1198:                        .getPort());
1199:
1200:                client.close();
1201:                server.close();
1202:            }
1203:
1204:            /**
1205:             * @tests java.net.Socket#getReceiveBufferSize()
1206:             */
1207:            public void test_getReceiveBufferSize() throws IOException {
1208:                ServerSocket server = new ServerSocket(0);
1209:                Socket client = new Socket(InetAddress.getLocalHost(), server
1210:                        .getLocalPort());
1211:
1212:                try {
1213:                    client.setReceiveBufferSize(130);
1214:                    assertTrue("Incorrect buffer size", client
1215:                            .getReceiveBufferSize() >= 130);
1216:
1217:                    ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_RCVBUF);
1218:                } catch (Exception e) {
1219:                    handleException(e, SO_RCVBUF);
1220:                } finally {
1221:                    client.close();
1222:                    server.close();
1223:                }
1224:            }
1225:
1226:            /**
1227:             * @tests java.net.Socket#getRemoteSocketAddress()
1228:             */
1229:            public void test_getRemoteSocketAddress() throws IOException {
1230:                // set up server connect and then validate that we get the right
1231:                // response for the remote address
1232:                ServerSocket server = new ServerSocket(0);
1233:                int serverPort = server.getLocalPort();
1234:                Socket client = new Socket(InetAddress.getLocalHost(),
1235:                        serverPort);
1236:
1237:                assertEquals("Returned incorrect InetSocketAddress(1):",
1238:                        new InetSocketAddress(InetAddress.getLocalHost(),
1239:                                serverPort), client.getRemoteSocketAddress());
1240:                client.close();
1241:
1242:                // now create one that is not connected and validate that we get the
1243:                // right answer
1244:                Socket theSocket = new Socket();
1245:                theSocket.bind(new InetSocketAddress(
1246:                        InetAddress.getLocalHost(), 0));
1247:                assertNull(
1248:                        "Returned incorrect InetSocketAddress -unconnected socket:",
1249:                        theSocket.getRemoteSocketAddress());
1250:
1251:                // now connect and validate we get the right answer
1252:                theSocket.connect(new InetSocketAddress(InetAddress
1253:                        .getLocalHost(), serverPort));
1254:                assertEquals("Returned incorrect InetSocketAddress(2):",
1255:                        new InetSocketAddress(InetAddress.getLocalHost(),
1256:                                serverPort), theSocket.getRemoteSocketAddress());
1257:                theSocket.close();
1258:
1259:                server.close();
1260:            }
1261:
1262:            /**
1263:             * @tests java.net.Socket#getReuseAddress()
1264:             */
1265:            public void test_getReuseAddress() {
1266:                try {
1267:                    Socket theSocket = new Socket();
1268:                    theSocket.setReuseAddress(true);
1269:                    assertTrue("getReuseAddress false when it should be true",
1270:                            theSocket.getReuseAddress());
1271:                    theSocket.setReuseAddress(false);
1272:                    assertFalse("getReuseAddress true when it should be False",
1273:                            theSocket.getReuseAddress());
1274:
1275:                    ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
1276:                } catch (Exception e) {
1277:                    handleException(e, SO_REUSEADDR);
1278:                }
1279:            }
1280:
1281:            /**
1282:             * @tests java.net.Socket#getSendBufferSize()
1283:             */
1284:            public void test_getSendBufferSize() throws IOException {
1285:                ServerSocket server = new ServerSocket(0);
1286:                Socket client = new Socket(InetAddress.getLocalHost(), server
1287:                        .getLocalPort());
1288:
1289:                try {
1290:                    client.setSendBufferSize(134);
1291:                    assertTrue("Incorrect buffer size", client
1292:                            .getSendBufferSize() >= 134);
1293:
1294:                    ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_SNDBUF);
1295:                } catch (Exception e) {
1296:                    handleException(e, SO_SNDBUF);
1297:                } finally {
1298:                    client.close();
1299:                    server.close();
1300:                }
1301:            }
1302:
1303:            /**
1304:             * @tests java.net.Socket#getSoLinger()
1305:             */
1306:            public void test_getSoLinger() throws IOException {
1307:                ServerSocket server = new ServerSocket(0);
1308:                Socket client = new Socket(InetAddress.getLocalHost(), server
1309:                        .getLocalPort());
1310:
1311:                try {
1312:                    client.setSoLinger(true, 200);
1313:                    assertEquals("Returned incorrect linger", 200, client
1314:                            .getSoLinger());
1315:                    client.setSoLinger(false, 0);
1316:
1317:                    ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_LINGER);
1318:                } catch (Exception e) {
1319:                    handleException(e, SO_LINGER);
1320:                } finally {
1321:                    client.close();
1322:                    server.close();
1323:                }
1324:            }
1325:
1326:            /**
1327:             * @tests java.net.Socket#getSoTimeout()
1328:             */
1329:            public void test_getSoTimeout() throws IOException {
1330:                ServerSocket server = new ServerSocket(0);
1331:                Socket client = new Socket(InetAddress.getLocalHost(), server
1332:                        .getLocalPort());
1333:
1334:                try {
1335:                    client.setSoTimeout(100);
1336:                    assertEquals("Returned incorrect sotimeout", 100, client
1337:                            .getSoTimeout());
1338:
1339:                    ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_TIMEOUT);
1340:                } catch (Exception e) {
1341:                    handleException(e, SO_TIMEOUT);
1342:                } finally {
1343:                    client.close();
1344:                    server.close();
1345:                }
1346:            }
1347:
1348:            /**
1349:             * @tests java.net.Socket#getTcpNoDelay()
1350:             */
1351:            public void test_getTcpNoDelay() throws IOException {
1352:                ServerSocket server = new ServerSocket(0);
1353:                Socket client = new Socket(InetAddress.getLocalHost(), server
1354:                        .getLocalPort());
1355:
1356:                try {
1357:                    boolean bool = !client.getTcpNoDelay();
1358:                    client.setTcpNoDelay(bool);
1359:                    assertTrue("Failed to get no delay setting: "
1360:                            + client.getTcpNoDelay(),
1361:                            client.getTcpNoDelay() == bool);
1362:
1363:                    ensureExceptionThrownIfOptionIsUnsupportedOnOS(TCP_NODELAY);
1364:                } catch (Exception e) {
1365:                    handleException(e, TCP_NODELAY);
1366:                } finally {
1367:                    client.close();
1368:                    server.close();
1369:                }
1370:            }
1371:
1372:            /**
1373:             * @tests java.net.Socket#getTrafficClass()
1374:             */
1375:            public void test_getTrafficClass() {
1376:                try {
1377:                    /*
1378:                     * We cannot actually check that the values are set as if a platform
1379:                     * does not support the option then it may come back unset even
1380:                     * though we set it so just get the value to make sure we can get it
1381:                     */
1382:                    int trafficClass = new Socket().getTrafficClass();
1383:                    assertTrue(0 <= trafficClass);
1384:                    assertTrue(trafficClass <= 255);
1385:
1386:                    ensureExceptionThrownIfOptionIsUnsupportedOnOS(IP_TOS);
1387:                } catch (Exception e) {
1388:                    handleException(e, IP_TOS);
1389:                }
1390:            }
1391:
1392:            /**
1393:             * @tests java.net.Socket#isBound()
1394:             */
1395:            public void test_isBound() throws IOException {
1396:                ServerSocket server = new ServerSocket(0);
1397:                Socket client = new Socket(InetAddress.getLocalHost(), server
1398:                        .getLocalPort());
1399:                Socket worker = server.accept();
1400:
1401:                assertTrue("Socket indicated  not bound when it should be (1)",
1402:                        client.isBound());
1403:                worker.close();
1404:                client.close();
1405:                server.close();
1406:
1407:                client = new Socket();
1408:                assertFalse("Socket indicated bound when it was not (2)",
1409:                        client.isBound());
1410:
1411:                server = new ServerSocket();
1412:                server
1413:                        .bind(new InetSocketAddress(InetAddress.getLocalHost(),
1414:                                0));
1415:                InetSocketAddress boundAddress = new InetSocketAddress(server
1416:                        .getInetAddress(), server.getLocalPort());
1417:                client.connect(boundAddress);
1418:                worker = server.accept();
1419:                assertTrue("Socket indicated not bound when it should be (2)",
1420:                        client.isBound());
1421:                worker.close();
1422:                client.close();
1423:                server.close();
1424:
1425:                // now test when we bind explicitly
1426:                InetSocketAddress theLocalAddress = new InetSocketAddress(
1427:                        InetAddress.getLocalHost(), 0);
1428:                client = new Socket();
1429:                assertFalse("Socket indicated bound when it was not (3)",
1430:                        client.isBound());
1431:                client.bind(theLocalAddress);
1432:                assertTrue("Socket indicated not bound when it should be (3a)",
1433:                        client.isBound());
1434:                client.close();
1435:                assertTrue("Socket indicated not bound when it should be (3b)",
1436:                        client.isBound());
1437:            }
1438:
1439:            /**
1440:             * @tests java.net.Socket#isClosed()
1441:             */
1442:            public void test_isClosed() throws IOException {
1443:                ServerSocket server = new ServerSocket(0);
1444:                Socket client = new Socket(InetAddress.getLocalHost(), server
1445:                        .getLocalPort());
1446:                Socket worker = server.accept();
1447:
1448:                // validate isClosed returns expected values
1449:                assertFalse("Socket should indicate it is not closed(1):",
1450:                        client.isClosed());
1451:                client.close();
1452:                assertTrue("Socket should indicate it is closed(1):", client
1453:                        .isClosed());
1454:
1455:                // validate that isClosed works ok for sockets returned from
1456:                // ServerSocket.accept()
1457:                assertFalse(
1458:                        "Accepted Socket should indicate it is not closed:",
1459:                        worker.isClosed());
1460:                worker.close();
1461:                assertTrue("Accepted Socket should indicate it is closed:",
1462:                        worker.isClosed());
1463:
1464:                // and finally for the server socket
1465:                assertFalse("Server Socket should indicate it is not closed:",
1466:                        server.isClosed());
1467:                server.close();
1468:                assertTrue("Server Socket should indicate it is closed:",
1469:                        server.isClosed());
1470:            }
1471:
1472:            /**
1473:             * @tests java.net.Socket#isConnected()
1474:             */
1475:            public void test_isConnected() throws IOException {
1476:                ServerSocket server = new ServerSocket(0);
1477:                Socket client = new Socket(InetAddress.getLocalHost(), server
1478:                        .getLocalPort());
1479:                Socket worker = server.accept();
1480:
1481:                assertTrue("Socket indicated  not connected when it should be",
1482:                        client.isConnected());
1483:                client.close();
1484:                worker.close();
1485:                server.close();
1486:
1487:                // now do it with the new constructors and revalidate
1488:                InetSocketAddress theAddress = new InetSocketAddress(
1489:                        InetAddress.getLocalHost(), 0);
1490:                client = new Socket();
1491:                assertFalse("Socket indicated connected when it was not",
1492:                        client.isConnected());
1493:
1494:                server = new ServerSocket();
1495:                server.bind(theAddress);
1496:                InetSocketAddress boundAddress = new InetSocketAddress(server
1497:                        .getInetAddress(), server.getLocalPort());
1498:                client.connect(boundAddress);
1499:                worker = server.accept();
1500:                assertTrue("Socket indicated  not connected when it should be",
1501:                        client.isConnected());
1502:                client.close();
1503:                worker.close();
1504:                server.close();
1505:            }
1506:
1507:            /**
1508:             * @tests java.net.Socket#isInputShutdown()
1509:             */
1510:            public void test_isInputShutdown() throws IOException {
1511:                ServerSocket server = new ServerSocket(0);
1512:                Socket client = new Socket(InetAddress.getLocalHost(), server
1513:                        .getLocalPort());
1514:
1515:                Socket worker = server.accept();
1516:                InputStream theInput = client.getInputStream();
1517:                OutputStream theOutput = worker.getOutputStream();
1518:
1519:                // make sure we get the right answer with newly connected socket
1520:                assertFalse(
1521:                        "Socket indicated input shutdown when it should not have",
1522:                        client.isInputShutdown());
1523:
1524:                // shutdown the output
1525:                client.shutdownInput();
1526:
1527:                // make sure we get the right answer once it is shut down
1528:                assertTrue(
1529:                        "Socket indicated input was NOT shutdown when it should have been",
1530:                        client.isInputShutdown());
1531:
1532:                client.close();
1533:                worker.close();
1534:                server.close();
1535:
1536:                // make sure we get the right answer for closed sockets
1537:                assertFalse(
1538:                        "Socket indicated input was shutdown when socket was closed",
1539:                        worker.isInputShutdown());
1540:
1541:                theInput.close();
1542:                theOutput.close();
1543:            }
1544:
1545:            /**
1546:             * @tests java.net.Socket#isOutputShutdown()
1547:             */
1548:            public void test_isOutputShutdown() throws IOException {
1549:                ServerSocket server = new ServerSocket(0);
1550:                Socket client = new Socket(InetAddress.getLocalHost(), server
1551:                        .getLocalPort());
1552:
1553:                Socket worker = server.accept();
1554:                InputStream theInput = client.getInputStream();
1555:                OutputStream theOutput = worker.getOutputStream();
1556:
1557:                // make sure we get the right answer with newly connected socket
1558:                assertFalse(
1559:                        "Socket indicated output shutdown when it should not have",
1560:                        worker.isOutputShutdown());
1561:
1562:                // shutdown the output
1563:                worker.shutdownOutput();
1564:
1565:                // make sure we get the right answer once it is shut down
1566:                assertTrue(
1567:                        "Socket indicated output was NOT shutdown when it should have been",
1568:                        worker.isOutputShutdown());
1569:
1570:                client.close();
1571:                worker.close();
1572:                server.close();
1573:
1574:                // make sure we get the right answer for closed sockets
1575:                assertFalse(
1576:                        "Socket indicated output was output shutdown when the socket was closed",
1577:                        client.isOutputShutdown());
1578:
1579:                theInput.close();
1580:                theOutput.close();
1581:            }
1582:
1583:            /**
1584:             * @tests java.net.Socket#sendUrgentData(int)
1585:             */
1586:            public void test_sendUrgentDataI() throws Exception {
1587:                /*
1588:                 * Some platforms may not support urgent data in this case we will not
1589:                 * run these tests. For now run on all platforms until we find those
1590:                 * that do not support urgent data
1591:                 */
1592:                String platform = System.getProperty("os.name");
1593:                if (platform.equals("Dummy")) {
1594:                    return;
1595:                }
1596:
1597:                /*
1598:                 * Test 1: Validate that when OOBInline is false that any urgent data is
1599:                 * silently ignored
1600:                 */
1601:                InetAddress localHost = InetAddress.getLocalHost();
1602:                ServerSocket server = new ServerSocket(0, 5, localHost);
1603:                SocketAddress serverAddress = new InetSocketAddress(localHost,
1604:                        server.getLocalPort());
1605:
1606:                Socket client = new Socket();
1607:                client.setOOBInline(false);
1608:
1609:                client.connect(serverAddress);
1610:                Socket worker = server.accept();
1611:                worker.setTcpNoDelay(true);
1612:                OutputStream theOutput = worker.getOutputStream();
1613:
1614:                // Send the regular data
1615:                String sendString = new String("Test");
1616:                theOutput.write(sendString.getBytes());
1617:                theOutput.flush();
1618:
1619:                // Send the urgent data byte which should not be received
1620:                worker.sendUrgentData("UrgentData".getBytes()[0]);
1621:                theOutput.write(sendString.getBytes());
1622:                worker.shutdownOutput();
1623:                worker.close();
1624:
1625:                // Try to read the bytes back
1626:                int totalBytesRead = 0;
1627:                byte[] myBytes = new byte[100];
1628:                InputStream theInput = client.getInputStream();
1629:                while (true) {
1630:                    int bytesRead = theInput.read(myBytes, totalBytesRead,
1631:                            myBytes.length - totalBytesRead);
1632:                    if (bytesRead == -1) {
1633:                        break;
1634:                    }
1635:                    totalBytesRead = totalBytesRead + bytesRead;
1636:                }
1637:
1638:                client.close();
1639:                server.close();
1640:
1641:                String receivedString = new String(myBytes, 0, totalBytesRead);
1642:                assertEquals("Urgent data was received", sendString
1643:                        + sendString, receivedString);
1644:
1645:                /*
1646:                 * Test 2: Now validate that urgent data is received as expected. Expect
1647:                 * that it should be between the two writes.
1648:                 */
1649:                server = new ServerSocket(0, 5, localHost);
1650:                serverAddress = new InetSocketAddress(localHost, server
1651:                        .getLocalPort());
1652:
1653:                client = new Socket();
1654:                client.setOOBInline(true);
1655:
1656:                client.connect(serverAddress);
1657:                worker = server.accept();
1658:                worker.setTcpNoDelay(true);
1659:                theOutput = worker.getOutputStream();
1660:
1661:                // Send the regular data
1662:                sendString = new String("Test - Urgent Data");
1663:                theOutput.write(sendString.getBytes());
1664:
1665:                // Send the urgent data (one byte) which should be received
1666:                client.setOOBInline(true);
1667:                byte urgentByte = "UrgentData".getBytes()[0];
1668:                worker.sendUrgentData(urgentByte);
1669:
1670:                // Send more data, the urgent byte must stay in position
1671:                theOutput.write(sendString.getBytes());
1672:                worker.shutdownOutput();
1673:                worker.close();
1674:
1675:                // Try to read the bytes back
1676:                totalBytesRead = 0;
1677:                myBytes = new byte[100];
1678:                theInput = client.getInputStream();
1679:                while (true) {
1680:                    int bytesRead = theInput.read(myBytes, totalBytesRead,
1681:                            myBytes.length - totalBytesRead);
1682:                    if (bytesRead == -1) {
1683:                        break;
1684:                    }
1685:                    totalBytesRead = totalBytesRead + bytesRead;
1686:                }
1687:
1688:                client.close();
1689:                server.close();
1690:
1691:                receivedString = new String(myBytes, 0, totalBytesRead);
1692:                assertEquals(
1693:                        "Urgent data was not received with one urgent byte",
1694:                        sendString + (char) urgentByte + sendString,
1695:                        receivedString);
1696:
1697:                /*
1698:                 * Test 3: Now validate that urgent data is received as expected. Expect
1699:                 * that it should be between the two writes.
1700:                 */
1701:                server = new ServerSocket(0, 5, localHost);
1702:                serverAddress = new InetSocketAddress(localHost, server
1703:                        .getLocalPort());
1704:
1705:                client = new Socket();
1706:                client.setOOBInline(true);
1707:
1708:                client.connect(serverAddress);
1709:                worker = server.accept();
1710:                worker.setTcpNoDelay(true);
1711:                theOutput = worker.getOutputStream();
1712:
1713:                // Send the regular data
1714:                sendString = new String("Test - Urgent Data");
1715:                theOutput.write(sendString.getBytes());
1716:
1717:                // Send the urgent data (one byte) which should be received
1718:                client.setOOBInline(true);
1719:                byte urgentByte1 = "UrgentData".getBytes()[0];
1720:                byte urgentByte2 = "UrgentData".getBytes()[1];
1721:                worker.sendUrgentData(urgentByte1);
1722:                worker.sendUrgentData(urgentByte2);
1723:
1724:                // Send more data, the urgent byte must stay in position
1725:                theOutput.write(sendString.getBytes());
1726:                worker.shutdownOutput();
1727:                worker.close();
1728:
1729:                // Try to read the bytes back
1730:                totalBytesRead = 0;
1731:                myBytes = new byte[100];
1732:                theInput = client.getInputStream();
1733:                while (true) {
1734:                    int bytesRead = theInput.read(myBytes, totalBytesRead,
1735:                            myBytes.length - totalBytesRead);
1736:                    if (bytesRead == -1) {
1737:                        break;
1738:                    }
1739:                    totalBytesRead = totalBytesRead + bytesRead;
1740:                }
1741:
1742:                client.close();
1743:                server.close();
1744:
1745:                receivedString = new String(myBytes, 0, totalBytesRead);
1746:                assertEquals(
1747:                        "Urgent data was not received with two urgent bytes",
1748:                        sendString + (char) urgentByte1 + (char) urgentByte2
1749:                                + sendString, receivedString);
1750:
1751:                /*
1752:                 * Test 4: Now test the case where there is only urgent data.
1753:                 */
1754:                server = new ServerSocket(0, 5, localHost);
1755:                serverAddress = new InetSocketAddress(localHost, server
1756:                        .getLocalPort());
1757:
1758:                client = new Socket();
1759:                client.setOOBInline(true);
1760:
1761:                client.connect(serverAddress);
1762:                worker = server.accept();
1763:                worker.setTcpNoDelay(true);
1764:
1765:                // Send the urgent data (one byte) which should be received
1766:                client.setOOBInline(true);
1767:                urgentByte = "UrgentData".getBytes()[0];
1768:                worker.sendUrgentData(urgentByte);
1769:                worker.close();
1770:
1771:                // Try to read the bytes back
1772:                theInput = client.getInputStream();
1773:                int byteRead = theInput.read();
1774:
1775:                client.close();
1776:                server.close();
1777:
1778:                assertEquals("Sole urgent data was not received",
1779:                        (int) urgentByte, byteRead);
1780:            }
1781:
1782:            /**
1783:             * @tests java.net.Socket#setKeepAlive(boolean)
1784:             */
1785:            public void test_setKeepAliveZ() throws IOException {
1786:
1787:                class TestSocket extends Socket {
1788:                    public TestSocket(SocketImpl impl) throws SocketException {
1789:                        super (impl);
1790:                    }
1791:                }
1792:
1793:                // There is not really a good test for this as it is there to detect
1794:                // crashed machines. Just make sure we can set it
1795:                ServerSocket server = new ServerSocket(0);
1796:                Socket client = new Socket(InetAddress.getLocalHost(), server
1797:                        .getLocalPort());
1798:
1799:                try {
1800:                    client.setKeepAlive(true);
1801:                    client.setKeepAlive(false);
1802:                    ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_KEEPALIVE);
1803:                } catch (Exception e) {
1804:                    handleException(e, SO_KEEPALIVE);
1805:                } finally {
1806:                    client.close();
1807:                    server.close();
1808:                }
1809:
1810:                // Regression test for HARMONY-1136
1811:                new TestSocket((SocketImpl) null).setKeepAlive(true);
1812:            }
1813:
1814:            /**
1815:             * @tests java.net.Socket#setOOBInline(boolean)
1816:             */
1817:            public void test_setOOBInlineZ() {
1818:                try {
1819:                    Socket theSocket = new Socket();
1820:                    theSocket.setOOBInline(true);
1821:                    assertTrue("expected OOBIline to be true", theSocket
1822:                            .getOOBInline());
1823:
1824:                    ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_OOBINLINE);
1825:                } catch (Exception e) {
1826:                    handleException(e, SO_OOBINLINE);
1827:                }
1828:            }
1829:
1830:            /**
1831:             * @tests java.net.Socket#setPerformancePreference()
1832:             */
1833:            public void test_setPerformancePreference_Int_Int_Int()
1834:                    throws IOException {
1835:                Socket theSocket = new Socket();
1836:                theSocket.setPerformancePreferences(1, 1, 1);
1837:            }
1838:
1839:            /**
1840:             * @tests java.net.Socket#setReceiveBufferSize(int)
1841:             */
1842:            public void test_setReceiveBufferSizeI() throws IOException {
1843:                ServerSocket server = new ServerSocket(0);
1844:                Socket client = new Socket(InetAddress.getLocalHost(), server
1845:                        .getLocalPort());
1846:
1847:                try {
1848:                    client.setReceiveBufferSize(130);
1849:                    assertTrue("Incorrect buffer size", client
1850:                            .getReceiveBufferSize() >= 130);
1851:
1852:                    ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_RCVBUF);
1853:                } catch (Exception e) {
1854:                    handleException(e, SO_RCVBUF);
1855:                } finally {
1856:                    client.close();
1857:                    server.close();
1858:                }
1859:            }
1860:
1861:            /**
1862:             * @tests java.net.Socket#setReuseAddress(boolean)
1863:             */
1864:            public void test_setReuseAddressZ() throws UnknownHostException {
1865:
1866:                try {
1867:                    Socket theSocket = new Socket();
1868:                    theSocket.setReuseAddress(false);
1869:                    // Bind to any available port on the given address
1870:                    theSocket.bind(new InetSocketAddress(InetAddress
1871:                            .getLocalHost(), 0));
1872:                    InetSocketAddress localAddress1 = new InetSocketAddress(
1873:                            theSocket.getLocalAddress(), theSocket
1874:                                    .getLocalPort());
1875:
1876:                    Socket theSocket2 = new Socket();
1877:                    theSocket2.setReuseAddress(false);
1878:
1879:                    /*
1880:                     * Try to invoke a bind while the port is busy (TIME_WAIT). Note
1881:                     * that we may not succeed, which will cause the test to pass
1882:                     * without testing the reuseaddr behavior.
1883:                     */
1884:                    theSocket.close();
1885:                    theSocket2.bind(localAddress1);
1886:
1887:                    theSocket2.close();
1888:
1889:                    ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
1890:                } catch (Exception e) {
1891:                    handleException(e, SO_REUSEADDR);
1892:                }
1893:            }
1894:
1895:            /**
1896:             * @tests java.net.Socket#setSendBufferSize(int)
1897:             */
1898:            public void test_setSendBufferSizeI() throws IOException {
1899:                ServerSocket server = new ServerSocket(0);
1900:                Socket client = new Socket(InetAddress.getLocalHost(), server
1901:                        .getLocalPort());
1902:
1903:                try {
1904:                    client.setSendBufferSize(134);
1905:                    assertTrue("Incorrect buffer size", client
1906:                            .getSendBufferSize() >= 134);
1907:                    ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_SNDBUF);
1908:                } catch (Exception e) {
1909:                    handleException(e, SO_SNDBUF);
1910:                } finally {
1911:                    client.close();
1912:                    server.close();
1913:                }
1914:            }
1915:
1916:            /**
1917:             * @tests java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory)
1918:             */
1919:            public void test_setSocketImplFactoryLjava_net_SocketImplFactory() {
1920:                // Cannot test as setting will cause the factory to be changed for
1921:                // all subsequent sockets
1922:            }
1923:
1924:            /**
1925:             * @tests java.net.Socket#setSoLinger(boolean, int)
1926:             */
1927:            public void test_setSoLingerZI() throws IOException {
1928:                ServerSocket server = new ServerSocket(0);
1929:                Socket client = new Socket(InetAddress.getLocalHost(), server
1930:                        .getLocalPort());
1931:
1932:                try {
1933:                    client.setSoLinger(true, 500);
1934:                    assertEquals("Set incorrect linger", 500, client
1935:                            .getSoLinger());
1936:                    ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_LINGER);
1937:                    client.setSoLinger(false, 0);
1938:                } catch (Exception e) {
1939:                    handleException(e, SO_LINGER);
1940:                } finally {
1941:                    client.close();
1942:                    server.close();
1943:                }
1944:            }
1945:
1946:            /**
1947:             * @tests java.net.Socket#setSoTimeout(int)
1948:             */
1949:            public void test_setSoTimeoutI() throws IOException {
1950:                ServerSocket server = new ServerSocket(0);
1951:                Socket client = new Socket(InetAddress.getLocalHost(), server
1952:                        .getLocalPort());
1953:
1954:                try {
1955:                    client.setSoTimeout(100);
1956:                    assertEquals("Set incorrect sotimeout", 100, client
1957:                            .getSoTimeout());
1958:                    ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_TIMEOUT);
1959:                } catch (Exception e) {
1960:                    handleException(e, SO_TIMEOUT);
1961:                } finally {
1962:                    client.close();
1963:                    server.close();
1964:                }
1965:            }
1966:
1967:            /**
1968:             * @tests java.net.Socket#setTcpNoDelay(boolean)
1969:             */
1970:            public void test_setTcpNoDelayZ() throws IOException {
1971:                ServerSocket server = new ServerSocket(0);
1972:                Socket client = new Socket(InetAddress.getLocalHost(), server
1973:                        .getLocalPort());
1974:
1975:                try {
1976:                    boolean bool;
1977:                    client.setTcpNoDelay(bool = !client.getTcpNoDelay());
1978:                    assertTrue("Failed to set no delay setting: "
1979:                            + client.getTcpNoDelay(),
1980:                            client.getTcpNoDelay() == bool);
1981:
1982:                    ensureExceptionThrownIfOptionIsUnsupportedOnOS(TCP_NODELAY);
1983:                } catch (Exception e) {
1984:                    handleException(e, TCP_NODELAY);
1985:                } finally {
1986:                    client.close();
1987:                    server.close();
1988:                }
1989:            }
1990:
1991:            /**
1992:             * @tests java.net.Socket#setTrafficClass(int)
1993:             */
1994:            public void test_setTrafficClassI() {
1995:                try {
1996:                    int IPTOS_LOWCOST = 0x2;
1997:                    int IPTOS_RELIABILTY = 0x4;
1998:                    int IPTOS_THROUGHPUT = 0x8;
1999:                    int IPTOS_LOWDELAY = 0x10;
2000:
2001:                    Socket theSocket = new Socket();
2002:
2003:                    // validate that value set must be between 0 and 255
2004:                    try {
2005:                        theSocket.setTrafficClass(256);
2006:                        fail("No exception was thrown when traffic class set to 256");
2007:                    } catch (IllegalArgumentException e) {
2008:                        // Expected
2009:                    }
2010:
2011:                    try {
2012:                        theSocket.setTrafficClass(-1);
2013:                        fail("No exception was thrown when traffic class set to -1");
2014:                    } catch (IllegalArgumentException e) {
2015:                        // Expected
2016:                    }
2017:
2018:                    // now validate that we can set it to some good values
2019:                    theSocket.setTrafficClass(IPTOS_LOWCOST);
2020:                    theSocket.setTrafficClass(IPTOS_RELIABILTY);
2021:                    theSocket.setTrafficClass(IPTOS_THROUGHPUT);
2022:                    theSocket.setTrafficClass(IPTOS_LOWDELAY);
2023:
2024:                    ensureExceptionThrownIfOptionIsUnsupportedOnOS(IP_TOS);
2025:                } catch (Exception e) {
2026:                    handleException(e, IP_TOS);
2027:                }
2028:            }
2029:
2030:            /**
2031:             * @tests java.net.Socket#shutdownInput()
2032:             */
2033:            @SuppressWarnings("deprecation")
2034:            public void test_shutdownInput() throws IOException {
2035:                ServerSocket server = new ServerSocket(0);
2036:                Socket client = new Socket(InetAddress.getLocalHost(), server
2037:                        .getLocalPort());
2038:
2039:                Socket worker = server.accept();
2040:                worker.setTcpNoDelay(true);
2041:
2042:                InputStream theInput = client.getInputStream();
2043:                OutputStream theOutput = worker.getOutputStream();
2044:
2045:                // shutdown the input
2046:                client.shutdownInput();
2047:
2048:                // send the regular data
2049:                String sendString = new String("Test");
2050:                theOutput.write(sendString.getBytes());
2051:                theOutput.flush();
2052:
2053:                // RI fails here. It is a RI bug not to return 0 to indicate EOF
2054:                assertEquals(0, theInput.available());
2055:
2056:                client.close();
2057:                server.close();
2058:
2059:                // Regression test for HARMONY-2944
2060:                Socket s = new Socket("0.0.0.0", 0, false);
2061:                s.shutdownInput();
2062:                try {
2063:                    s.shutdownInput();
2064:                    fail("should throw SocketException");
2065:                } catch (SocketException se) {
2066:                    // Expected
2067:                }
2068:                s.close();
2069:            }
2070:
2071:            /**
2072:             * @tests java.net.Socket#shutdownOutput()
2073:             */
2074:            @SuppressWarnings("deprecation")
2075:            public void test_shutdownOutput() throws IOException {
2076:                ServerSocket server = new ServerSocket(0);
2077:                Socket client = new Socket(InetAddress.getLocalHost(), server
2078:                        .getLocalPort());
2079:
2080:                Socket worker = server.accept();
2081:                OutputStream theOutput = worker.getOutputStream();
2082:
2083:                // shutdown the output
2084:                worker.shutdownOutput();
2085:
2086:                // send the regular data
2087:                String sendString = new String("Test");
2088:                try {
2089:                    theOutput.write(sendString.getBytes());
2090:                    theOutput.flush();
2091:                    fail("No exception when writing on socket with output shutdown");
2092:                } catch (IOException e) {
2093:                    // Expected
2094:                }
2095:
2096:                client.close();
2097:                server.close();
2098:
2099:                // Regression test for HARMONY-2944
2100:                Socket s = new Socket("0.0.0.0", 0, false);
2101:                s.shutdownOutput();
2102:                try {
2103:                    s.shutdownOutput();
2104:                    fail("should throw SocketException");
2105:                } catch (SocketException se) {
2106:                    // Expected
2107:                }
2108:                s.close();
2109:            }
2110:
2111:            /**
2112:             * @tests java.net.Socket#toString()
2113:             */
2114:            public void test_toString() throws IOException {
2115:                ServerSocket server = new ServerSocket(0);
2116:                Socket client = new Socket(InetAddress.getLocalHost(), server
2117:                        .getLocalPort());
2118:
2119:                String expected = "Socket[addr=" + InetAddress.getLocalHost()
2120:                        + ",port=" + client.getPort() + ",localport="
2121:                        + client.getLocalPort() + "]";
2122:                assertEquals("Returned incorrect string", expected, client
2123:                        .toString());
2124:                client.close();
2125:                server.close();
2126:            }
2127:        }
ww__w__._j_a_v__a__2___s___.__c___o_m | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.