List of usage examples for java.net Socket connect
public void connect(SocketAddress endpoint) throws IOException
From source file:us.pserver.revok.HttpConnector.java
/** * Create a bounded network <code>Socket</code> * with this HttpConnector informations. * @return <code>Socket</code>. * @throws IOException In case of creation error. *///from w ww .jav a 2 s.co m public Socket connectSocket() throws IOException { Socket sc = new Socket(); String addr = (address == null ? "127.0.0.1" : address); int prt = port; if (proxyAddr != null && proxyPort > 0) { addr = proxyAddr; prt = proxyPort; } sc.connect(new InetSocketAddress(addr, prt)); return sc; }
From source file:org.sonatype.nexus.bundle.launcher.support.DefaultNexusBundle.java
/** * Stops Nexus.// w w w.j a v a 2 s .c om * <p/> * {@inheritDoc} * * @since 2.0 */ @Override protected void stopApplication() { // application may be in suspended state waiting for debugger to attach, if we can reasonably guess this is // the case, then we should resume the vm so that we can ask command monitor to immediately halt try { if (getConfiguration().isSuspendOnStart()) { boolean isSuspended = new TimedCondition() { @Override protected boolean isSatisfied() throws Exception { Socket socket = new Socket(); socket.setSoTimeout(5000); socket.connect(new InetSocketAddress(getConfiguration().getHostName(), getConfiguration().getDebugPort())); return true; } }.await(Time.seconds(1), Time.seconds(10), Time.seconds(1)); if (isSuspended) { // FIXME avoiding the compile time dependency for now on jdi classes (DebuggerUtils) throw new RuntimeException(format("%s (%s) looks suspended at {}:{}, CANNOT STOP THIS BUNDLE!", getName(), getConfiguration().getId(), getConfiguration().getHostName(), getConfiguration().getDebugPort())); } } terminateRemoteNexus(commandMonitorPort); try { // clear transient cache to avoid filesystem bloat when running ITs FileUtils.deleteDirectory(new File(getNexusDirectory(), "data/cache")); } catch (IOException e) { // couldn't delete directory, too bad } } finally { // Stop the launcher-controller-side monitor thread if there is one if (keepAliveThread != null) { sendStopToKeepAlive(keepAlivePort); keepAliveThread = null; } } }
From source file:org.sonatype.nexus.bundle.launcher.support.DefaultNexusBundle.java
/** * Starts Nexus.//from w w w . ja v a 2 s. co m * <p/> * {@inheritDoc} * * @since 2.0 */ @Override protected void startApplication() { try { keepAliveThread = new CommandMonitorThread(keepAlivePort, new PingCommand(), new StopMonitorCommand(), new ExitCommand(), new HaltCommand()); keepAliveThread.start(); } catch (IOException e) { throw new RuntimeException("Could not start keep alive thread", e); } installStopShutdownHook(commandMonitorPort); final File nexusDir = getNexusDirectory(); makeExecutable(nexusDir, "bin/*"); // log whenever ports are configured to aid solving test port conflicts log.info("{} ({}) spawned env [{}={},{}={}]", getName(), getConfiguration().getId(), strategy.commandMonitorProperty(), commandMonitorPort, strategy.keepAliveProperty(), keepAlivePort); onDirectory(nexusDir).apply(fileTaskBuilder.exec().spawn() .script(path("bin/nexus" + (Os.isFamily(Os.FAMILY_WINDOWS) ? ".bat" : ""))).withArgument("start") .withEnv(strategy.commandMonitorProperty(), String.valueOf(commandMonitorPort)) .withEnv(strategy.keepAliveProperty(), String.valueOf(keepAlivePort))); if (getConfiguration().isSuspendOnStart()) { // verify the debugger socket has been opened and is waiting for a debugger to connect // command monitor thread is not started while suspended so this is the best we can do final boolean jvmSuspended = new TimedCondition() { @Override protected boolean isSatisfied() throws Exception { Socket socket = new Socket(); socket.setSoTimeout(5000); socket.connect(new InetSocketAddress(getConfiguration().getHostName(), getConfiguration().getDebugPort())); return true; } }.await(Time.seconds(10), Time.seconds(100), Time.seconds(1)); if (jvmSuspended) { log.info("{} ({}) suspended for debugging at {}:{}", getName(), getConfiguration().getId(), getConfiguration().getHostName(), getConfiguration().getDebugPort()); } else { throw new RuntimeException(format("%s (%s) no open socket for debugging at %s:%s within 10 seconds", getName(), getConfiguration().getId(), getConfiguration().getHostName(), getConfiguration().getDebugPort())); } } else { // when not suspending, we expect the internal command monitor thread to start well before bundle is ready // so we only give it 10 seconds to be available log.info("{} ({}) pinging command monitor at {}:{}", getName(), getConfiguration().getId(), getConfiguration().getHostName(), commandMonitorPort); final boolean monitorInstalled = new TimedCondition() { @Override protected boolean isSatisfied() throws Exception { // FIXME replace LOCALHOST with getHostName() after making default hostname be 127.0.0.1 new CommandMonitorTalker(LOCALHOST, commandMonitorPort).send(PingCommand.NAME); return true; } }.await(Time.seconds(10), Time.seconds(100), Time.seconds(1)); if (monitorInstalled) { log.debug("{} ({}) command monitor detected at {}:{}", getName(), getConfiguration().getId(), getConfiguration().getHostName(), commandMonitorPort); } else { throw new RuntimeException( format("%s (%s) no command monitor detected at %s:%s within 10 seconds", getName(), getConfiguration().getId(), getConfiguration().getHostName(), commandMonitorPort)); } } }
From source file:org.wso2.carbon.analytics.common.jmx.agent.JmxAgentWebInterface.java
/** * Test the availability of the DataPublisher by * trying to connect to it (credentials are not checked) * * @return : whether the test was successful or not */// w w w .j a va2 s. c om public boolean testDataPublisherAvailability(String connectionType, String url, int port) { //check for tcp and ssl port availability if (connectionType.equalsIgnoreCase("tcp://") || connectionType.equalsIgnoreCase("ssl://")) { DatagramSocket ds = null; try { ds = new DatagramSocket(port); ds.setReuseAddress(true); return true; } catch (IOException e) { log.error(e); } finally { if (ds != null) { ds.close(); } } } //check for http and https port availability if (connectionType.equalsIgnoreCase("http://") || connectionType.equalsIgnoreCase("https://")) { Socket socket = null; try { socket = new Socket(); socket.setReuseAddress(true); SocketAddress sa = new InetSocketAddress(url, port); socket.connect(sa); return true; } catch (IOException e) { log.error(e); } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { //do nothing } } } } return false; }
From source file:org.kde.kdeconnect.LanLinkTest.java
public void testSendPayload() throws Exception { class Downloader extends Thread { NetworkPackage np;/*from w w w . j a va2 s.co m*/ ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); public void setNetworkPackage(NetworkPackage networkPackage) { this.np = networkPackage; } public ByteArrayOutputStream getOutputStream() { return outputStream; } @Override public void run() { try { Socket socket = null; try { socket = new Socket(); int tcpPort = np.getPayloadTransferInfo().getInt("port"); InetSocketAddress address = (InetSocketAddress) session.getRemoteAddress(); socket.connect(new InetSocketAddress(address.getAddress(), tcpPort)); np.setPayload(socket.getInputStream(), np.getPayloadSize()); } catch (Exception e) { try { socket.close(); } catch (Exception ignored) { throw ignored; } e.printStackTrace(); Log.e("KDE/LanLinkTest", "Exception connecting to remote socket"); throw e; } final InputStream input = np.getPayload(); final long fileLength = np.getPayloadSize(); byte data[] = new byte[1024]; long progress = 0, prevProgressPercentage = 0; int count; while ((count = input.read(data)) >= 0) { progress += count; outputStream.write(data, 0, count); if (fileLength > 0) { if (progress >= fileLength) break; long progressPercentage = (progress * 100 / fileLength); if (progressPercentage != prevProgressPercentage) { prevProgressPercentage = progressPercentage; } } } outputStream.close(); input.close(); } catch (Exception e) { Log.e("Downloader Test", "Exception"); e.printStackTrace(); } } } final Downloader downloader = new Downloader(); // Using byte array for payload, try to use input stream as used in real device String dataString = "Lorem ipsum dolor sit amet, consectetur adipiscing elit." + " Cras vel erat et ante fringilla tristique. Sed consequat ligula at interdum " + "rhoncus. Integer semper enim felis, id sodales tellus aliquet eget." + " Sed fringilla ac metus eget dictum. Aliquam euismod non sem sit" + " amet dapibus. Interdum et malesuada fames ac ante ipsum primis " + "in faucibus. Nam et ligula placerat, varius justo eu, convallis " + "lorem. Nam consequat consequat tortor et gravida. Praesent " + "ultricies tortor eget ex elementum gravida. Suspendisse aliquet " + "erat a orci feugiat dignissim."; // reallyLongString contains dataString 16 times String reallyLongString = dataString + dataString; reallyLongString = reallyLongString + reallyLongString; reallyLongString = reallyLongString + reallyLongString; reallyLongString = reallyLongString + reallyLongString; final byte[] data = reallyLongString.getBytes(); final JSONObject sharePackageJson = new JSONObject( "{\"id\":123,\"body\":{\"filename\":\"data.txt\"},\"payloadTransferInfo\":{},\"payloadSize\":8720,\"type\":\"kdeconnect.share\"}"); // Mocking share package final NetworkPackage sharePackage = Mockito.mock(NetworkPackage.class); Mockito.when(sharePackage.getType()).thenReturn("kdeconnect.share"); Mockito.when(sharePackage.hasPayload()).thenReturn(true); Mockito.when(sharePackage.hasPayloadTransferInfo()).thenReturn(true); Mockito.doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { return sharePackageJson.toString(); } }).when(sharePackage).serialize(); Mockito.when(sharePackage.getPayload()).thenReturn(new ByteArrayInputStream(data)); Mockito.when(sharePackage.getPayloadSize()).thenReturn((long) data.length); Mockito.doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { return sharePackageJson.getJSONObject("payloadTransferInfo"); } }).when(sharePackage).getPayloadTransferInfo(); Mockito.doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { JSONObject object = (JSONObject) invocationOnMock.getArguments()[0]; sharePackageJson.put("payloadTransferInfo", object); return null; } }).when(sharePackage).setPayloadTransferInfo(Mockito.any(JSONObject.class)); Mockito.doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { String stringNetworkPackage = (String) invocationOnMock.getArguments()[0]; final NetworkPackage np = NetworkPackage.unserialize(stringNetworkPackage); downloader.setNetworkPackage(np); downloader.start(); return writeFutureSuccess; } }).when(session).write(Mockito.anyString()); lanLink.sendPackage(sharePackage, callback); try { // Wait 1 secs for downloader to finish (if some error, it will continue and assert will fail) downloader.join(1 * 1000); } catch (Exception e) { e.printStackTrace(); throw e; } assertEquals(new String(data), new String(downloader.getOutputStream().toByteArray())); }
From source file:org.apache.pig.shock.SSHSocketImplFactory.java
public Socket createSocket(String host, int port) throws IOException, UnknownHostException { String socksHost = System.getProperty("socksProxyHost"); Socket s; InetSocketAddress addr = new InetSocketAddress(host, port); if (socksHost != null) { Proxy proxy = new Proxy(Type.SOCKS, new InetSocketAddress(socksHost, 1080)); s = new Socket(proxy); s.connect(addr); } else {// ww w . j a v a 2 s.c om log.error(addr); SocketChannel sc = SocketChannel.open(addr); s = sc.socket(); } s.setTcpNoDelay(true); return s; }
From source file:gov.hhs.fha.nhinc.lift.proxy.properties.imp.ProducerProxyPropertiesService.java
@Override public Socket getSocketToServerForRequest(LiftConnectionRequestToken request) throws IOException { Socket socket = new Socket(); try {/*from w ww. j a v a2 s .co m*/ String fileServerIP = PropertyAccessor.getProperty(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.LIFT_FILESERVER_IP); String fileServerPort = PropertyAccessor.getProperty(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.LIFT_FILESERVER_PORT); int portNum = Integer.parseInt(fileServerPort); SocketAddress socketAddr = new InetSocketAddress(fileServerIP, portNum); socket.connect(socketAddr); } catch (PropertyAccessException ex) { log.error(ex.getMessage()); } log.debug("Creating socket " + socket.getInetAddress() + ": " + socket.getPort()); return socket; }
From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java
private void runSimultaneousDataExchange(boolean useTunnel, int nclients) throws IOException, InterruptedException, NoSuchAlgorithmException { long t0 = System.currentTimeMillis(); final int nMsgs = 50; final Map<String, MessageDigest> digestMsgsRecvdAtServer = new HashMap<String, MessageDigest>(); final Map<String, MessageDigest> digestMsgsSentByClients = new HashMap<String, MessageDigest>(); final Map<String, MessageDigest> digestMsgsRecvdAtClients = new HashMap<String, MessageDigest>(); for (int c = 0; c < nclients; c++) { digestMsgsRecvdAtServer.put(Integer.toString(c), MessageDigest.getInstance("MD5")); digestMsgsSentByClients.put(Integer.toString(c), MessageDigest.getInstance("MD5")); digestMsgsRecvdAtClients.put(Integer.toString(c), MessageDigest.getInstance("MD5")); }// w w w .ja v a 2 s . c o m final MessageDigest digestMsgsSentByServer = MessageDigest.getInstance("MD5"); for (int i = 0; i < nMsgs; i++) { digestMsgsSentByServer.update(TalkPastServer.generateMsgFromServer(i).getBytes()); } String hashOfMsgsSentByServer = Hex.encodeHexString(digestMsgsSentByServer.digest()); MockServer talkPastServer = startTalkPastServer(nMsgs, digestMsgsRecvdAtServer); int targetPort = talkPastServer.getServerSocketPort(); Tunnel tunnel = null; MockServer proxyServer = null; if (useTunnel) { proxyServer = startConnectProxyServer(); tunnel = Tunnel.build("localhost", talkPastServer.getServerSocketPort(), "localhost", proxyServer.getServerSocketPort()); targetPort = tunnel.getPort(); } try { List<EasyThread> clientThreads = new ArrayList<EasyThread>(); final int portToUse = targetPort; for (int c = 0; c < nclients; c++) { final int clientId = c; clientThreads.add(new EasyThread() { @Override void runQuietly() throws Exception { long t = System.currentTimeMillis(); LOG.info("\t" + clientId + ": Client starting"); final MessageDigest digestMsgsRecvdAtClient = digestMsgsRecvdAtClients .get(Integer.toString(clientId)); //final SocketChannel client = SocketChannel.open(); // tunnel test hangs for some reason with SocketChannel final Socket client = new Socket(); client.connect(new InetSocketAddress("localhost", portToUse)); EasyThread serverReaderThread = new EasyThread() { @Override public void runQuietly() { try { BufferedReader clientIn = new BufferedReader( new InputStreamReader(client.getInputStream())); String line = clientIn.readLine(); while (line != null && !line.equals("Goodbye")) { //LOG.info("\t" + clientId + ": Server said [" + line.substring(0, 32) + "... ]"); digestMsgsRecvdAtClient.update(line.getBytes()); digestMsgsRecvdAtClient.update("\n".getBytes()); line = clientIn.readLine(); } } catch (IOException e) { e.printStackTrace(); } LOG.info("\t" + clientId + ": Client done reading"); } }.startThread(); MessageDigest hashMsgsFromClient = digestMsgsSentByClients.get(Integer.toString(clientId)); BufferedOutputStream clientOut = new BufferedOutputStream(client.getOutputStream()); for (int i = 0; i < nMsgs; i++) { String msg = clientId + ":" + i + " " + StringUtils.repeat("Blahhh Blahhh ", 10000) + "\n"; //LOG.info(clientId + " sending " + msg.length() + " bytes"); byte[] bytes = msg.getBytes(); hashMsgsFromClient.update(bytes); clientOut.write(bytes); MockServer.sleepQuietly(2); } clientOut.write(("Goodbye\n".getBytes())); clientOut.flush(); LOG.info("\t" + clientId + ": Client done writing in " + (System.currentTimeMillis() - t) + " ms"); serverReaderThread.join(); LOG.info("\t" + clientId + ": Client done in " + (System.currentTimeMillis() - t) + " ms"); client.close(); } }.startThread()); } for (Thread clientThread : clientThreads) { clientThread.join(); } LOG.info("All data transfer done in " + (System.currentTimeMillis() - t0) + " ms"); } finally { talkPastServer.stopServer(); if (tunnel != null) { proxyServer.stopServer(); tunnel.close(); assertFalse(tunnel.isTunnelThreadAlive()); assertEquals(proxyServer.getNumConnects(), nclients); } Map<String, String> hashOfMsgsRecvdAtServer = new HashMap<String, String>(); Map<String, String> hashOfMsgsSentByClients = new HashMap<String, String>(); Map<String, String> hashOfMsgsRecvdAtClients = new HashMap<String, String>(); for (int c = 0; c < nclients; c++) { String client = Integer.toString(c); hashOfMsgsRecvdAtServer.put(client, Hex.encodeHexString(digestMsgsRecvdAtServer.get(client).digest())); hashOfMsgsSentByClients.put(client, Hex.encodeHexString(digestMsgsSentByClients.get(client).digest())); hashOfMsgsRecvdAtClients.put(client, Hex.encodeHexString(digestMsgsRecvdAtClients.get(client).digest())); } LOG.info("\tComparing client sent to server received"); assertEquals(hashOfMsgsSentByClients, hashOfMsgsRecvdAtServer); LOG.info("\tComparing server sent to client received"); for (String hashOfMsgsRecvdAtClient : hashOfMsgsRecvdAtClients.values()) { assertEquals(hashOfMsgsSentByServer, hashOfMsgsRecvdAtClient); } LOG.info("\tDone"); } }
From source file:org.rifidi.emulator.io.comm.ip.tcpserver.TCPServerCommunicationTest.java
License:asdf
/** * Tests turning on the TCPServerCommunication while it is off. * /* ww w . ja v a2s .c o m*/ * */ public void testTurnOnWhenOff() { /* Turn on */ this.tcpComm.turnOn(); /* Make a client to connect to the server. */ Socket clientSocket = new Socket(); InetSocketAddress clientAddress = new InetSocketAddress("127.0.0.1", 0); /* Allow server socket to fully start */ synchronized (this) { try { this.wait(1000); } catch (InterruptedException e2) { /* Do nothing */ } this.notifyAll(); } /* Create a client to connect to the server */ try { /* Bind */ clientSocket.bind(clientAddress); try { /* Connect to the TCPServerCommunication. */ InetSocketAddress serverAddress = new InetSocketAddress(SERVER_HOSTNAME, SERVER_PORT); clientSocket.connect(serverAddress); } catch (IOException e) { /* Failed */ fail("Test client could not connect to Communication: " + e.getMessage()); } /* Allow server socket to fully start client services */ synchronized (this) { try { this.wait(1000); } catch (InterruptedException e2) { /* Do nothing */ } this.notifyAll(); } /* Close the socket. */ try { clientSocket.close(); } catch (IOException ioe) { /* Do nothing */ } } catch (IOException e) { fail("Cannot create client to test properly: " + e.getMessage()); } }
From source file:android.core.SSLSocketTest.java
/** * Regression test for problem where close() resulted in a hand if * a different thread was sitting in a blocking read or write. *///from www . j a v a2 s . co m public void testMultithreadedClose() throws Exception { InetSocketAddress address = new InetSocketAddress("www.fortify.net", 443); final Socket socket = clientFactory.createSocket(); socket.connect(address); Thread reader = new Thread() { @Override public void run() { try { byte[] buffer = new byte[512]; InputStream stream = socket.getInputStream(); socket.getInputStream().read(buffer); } catch (Exception ex) { android.util.Log.d("SSLSocketTest", "testMultithreadedClose() reader got " + ex.toString()); } } }; Thread closer = new Thread() { @Override public void run() { try { Thread.sleep(5000); socket.close(); } catch (Exception ex) { android.util.Log.d("SSLSocketTest", "testMultithreadedClose() closer got " + ex.toString()); } } }; android.util.Log.d("SSLSocketTest", "testMultithreadedClose() starting reader..."); reader.start(); android.util.Log.d("SSLSocketTest", "testMultithreadedClose() starting closer..."); closer.start(); long t1 = System.currentTimeMillis(); android.util.Log.d("SSLSocketTest", "testMultithreadedClose() joining reader..."); reader.join(30000); android.util.Log.d("SSLSocketTest", "testMultithreadedClose() joining closer..."); closer.join(30000); long t2 = System.currentTimeMillis(); assertTrue("Concurrent close() hangs", t2 - t1 < 30000); }