List of usage examples for java.net Socket isConnected
public boolean isConnected()
From source file:org.eclipse.mylyn.commons.tests.net.SslProtocolSocketFactoryTest.java
public void testTrustAllSslProtocolSocketFactory() throws Exception { SecureProtocolSocketFactory factory = new PollingSslProtocolSocketFactory(); Socket s; s = factory.createSocket(proxyAddress.getHostName(), proxyAddress.getPort()); assertNotNull(s);/* w ww . j a va2s .co m*/ assertTrue(s.isConnected()); s.close(); InetAddress anyHost = new Socket().getLocalAddress(); s = factory.createSocket(proxyAddress.getHostName(), proxyAddress.getPort(), anyHost, 0); assertNotNull(s); assertTrue(s.isConnected()); s.close(); HttpConnectionParams params = new HttpConnectionParams(); s = factory.createSocket(proxyAddress.getHostName(), proxyAddress.getPort(), anyHost, 0, params); assertNotNull(s); assertTrue(s.isConnected()); s.close(); params.setConnectionTimeout(1000); s = factory.createSocket(proxyAddress.getHostName(), proxyAddress.getPort(), anyHost, 0, params); assertNotNull(s); assertTrue(s.isConnected()); s.close(); }
From source file:com.bmwcarit.barefoot.tracker.TrackerServerTest.java
public void sendSample(InetAddress host, int port, JSONObject sample) throws InterruptedException, IOException { int trials = 120; int timeout = 500; Socket client = null; while (client == null || !client.isConnected()) { try {/*from ww w . j av a 2 s.c o m*/ client = new Socket(host, port); } catch (IOException e) { Thread.sleep(timeout); if (trials == 0) { logger.error(e.getMessage()); client.close(); throw new IOException(); } else { trials -= 1; } } } PrintWriter writer = new PrintWriter(client.getOutputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream())); writer.println(sample.toString()); writer.flush(); String code = reader.readLine(); assertEquals("SUCCESS", code); }
From source file:at.bitfire.davdroid.webdav.TlsSniSocketFactoryTest.java
public void testCreateLayeredSocket() { try {//from w ww. j a v a 2 s . c o m // connect plain socket first @Cleanup Socket plain = new Socket(); plain.connect(sampleTlsEndpoint); assertTrue(plain.isConnected()); // then create TLS socket on top of it and establish TLS Connection @Cleanup Socket socket = factory.createLayeredSocket(plain, sampleTlsEndpoint.getHostName(), sampleTlsEndpoint.getPort(), null); assertTrue(socket.isConnected()); } catch (IOException e) { Log.e(TAG, "I/O exception", e); fail(); } }
From source file:org.transdroid.daemon.util.TlsSniSocketFactory.java
@Override public boolean isSecure(Socket s) throws IllegalArgumentException { if (s instanceof SSLSocket) { return s.isConnected(); }/*www . ja va 2 s.co m*/ return false; }
From source file:org.apache.stratos.kubernetes.client.live.KubernetesApiClientLiveTest.java
@Test public void testServiceCreation() throws Exception { log.info("Testing service creation..."); String serviceId = "tomcat-domain-1"; String serviceName = "stratos-test-pod"; String containerPortName = "http-1"; String serviceType = "NodePort"; Map<String, String> serviceLabels1 = new HashMap<>(); serviceLabels1.put("applicationId", "my-application-1"); Map<String, String> annotationMap = new HashMap<>(); annotationMap.put("test", "test"); createService(serviceId, serviceName, serviceLabels1, annotationMap, SERVICE_PORT, serviceType, containerPortName, containerPort, minionPublicIPs); Map<String, String> podLabels3 = new HashMap<>(); podLabels3.put("applicationId", "my-application-3"); Map<String, String> podAnnocations3 = new HashMap<>(); podAnnocations3.put("test", "test"); createPod("stratos-test-pod-3", serviceName, podLabels3, podAnnocations3, containerPortName, "1", "512", null, null);/*from w w w . java2s . c o m*/ Map<String, String> podLabels4 = new HashMap<>(); podLabels4.put("applicationId", "my-application-4"); Map<String, String> podAnnocations4 = new HashMap<>(); podAnnocations4.put("test", "test"); createPod("stratos-test-pod-4", serviceName, podLabels4, podAnnocations4, containerPortName, "2", "512", null, null); if (testServiceSocket) { // test service accessibility log.info(String.format("Connecting to service: [portal] %s:%d", minionPublicIPs.get(0), SERVICE_PORT)); sleep(4000); Socket socket = new Socket(minionPublicIPs.get(0), SERVICE_PORT); assertTrue(socket.isConnected()); log.info(String.format("Connecting to service successful: [portal] %s:%d", minionPublicIPs.get(0), SERVICE_PORT)); } deleteService(serviceId); deletePod("stratos-test-pod-3"); deletePod("stratos-test-pod-4"); }
From source file:com.bmwcarit.barefoot.tracker.TrackerServerTest.java
public MatcherKState requestState(InetAddress host, int port, String id) throws JSONException, InterruptedException, IOException { int trials = 120; int timeout = 500; Socket client = null; while (client == null || !client.isConnected()) { try {//from w w w .ja v a2 s . c o m client = new Socket(host, port); } catch (IOException e) { Thread.sleep(timeout); if (trials == 0) { logger.error(e.getMessage()); client.close(); throw new IOException(); } else { trials -= 1; } } } JSONObject json = new JSONObject(); json.put("id", id); PrintWriter writer = new PrintWriter(client.getOutputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream())); writer.println(json.toString()); writer.flush(); String code = reader.readLine(); assertEquals("SUCCESS", code); String response = reader.readLine(); client.close(); return new MatcherKState(new JSONObject(response), new MatcherFactory(TrackerControl.getServer().getMap())); }
From source file:org.pircbotx.CAPTest.java
public void runTest(String cap, final OutputParser callback) throws Exception { final MutableObject<Exception> connectionException = new MutableObject<Exception>(); botInWrite = new PipedOutputStream(); botIn = new BufferedInputStream(new PipedInputStream(botInWrite)); botOut = new ByteArrayOutputStream() { @Override/*from w ww.j av a 2 s.co m*/ public synchronized void write(byte[] bytes, int i, int i1) { super.write(bytes, i, i1); String outputText = new String(bytes, i, i1).trim(); try { try { String callbackText = callback.handleOutput(outputText); if (callbackText == null) //Will close bots input loop botInWrite.close(); else if (!callbackText.equals("")) { botInWrite.write((callbackText + "\r\n").getBytes()); botInWrite.flush(); } } catch (Exception ex) { log.error("Recieved error, closing bot and escelating", ex); connectionException.setValue(ex); botInWrite.close(); } } catch (IOException ex) { log.error("Recieved IO error, closing bot and escelating", ex); connectionException.setValue(ex); try { botInWrite.close(); } catch (Exception e) { throw new RuntimeException("Can't close botInWrite", e); } } } }; Socket socket = mock(Socket.class); when(socket.isConnected()).thenReturn(true); when(socket.getInputStream()).thenReturn(botIn); when(socket.getOutputStream()).thenReturn(botOut); Configuration.Builder configurationBuilder = TestUtils.generateConfigurationBuilder(); SocketFactory socketFactory = mock(SocketFactory.class); when(socketFactory.createSocket( InetAddress.getByName(configurationBuilder.getServers().get(0).getHostname()), 6667, null, 0)) .thenReturn(socket); configurationBuilder.getCapHandlers().clear(); configurationBuilder.getCapHandlers().addAll(capHandlers); bot = new PircBotX( configurationBuilder.setSocketFactory(socketFactory).setAutoReconnect(false).buildConfiguration()); botInWrite.write((":ircd.test CAP * LS :" + cap + "\r\n").getBytes()); bot.connect(); if (connectionException.getValue() != null) throw connectionException.getValue(); }
From source file:org.darkphoenixs.pool.socket.SocketConnectionFactory.java
@Override public boolean validateObject(PooledObject<Socket> p) { Socket socket = p.getObject(); if (socket != null) return (socket.isConnected()) && (!socket.isClosed()); return false; }
From source file:it.evilsocket.dsploit.core.System.java
public static boolean isPortAvailable(int port) { boolean available = true; int available_code = mOpenPorts.get(port); if (available_code != 0) return available_code == 1 ? false : true; try {/* ww w .j av a 2s .c om*/ // attempt 3 times since proxy and server could be still releasing // their ports for (int i = 0; i < 3; i++) { Socket channel = new Socket(); InetSocketAddress address = new InetSocketAddress( InetAddress.getByName(mNetwork.getLocalAddressAsString()), port); channel.connect(address, 200); available = !channel.isConnected(); channel.close(); if (available) break; Thread.sleep(200); } } catch (Exception e) { available = true; } mOpenPorts.put(port, available ? 2 : 1); return available; }
From source file:nacho.tfg.blepresencetracker.MyFirebaseInstanceIDService.java
/** * Persist token to third-party servers. * * Modify this method to associate the user's FCM InstanceID token with any server-side account * maintained by your application./*from w w w .ja v a 2s . co m*/ * * @param token The new token. */ private void sendRegistrationToServer(String token) { // Add custom implementation, as needed. Intent intent = new Intent(ACTION_SHOW_TOKEN); intent.putExtra("token", token); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Boolean doInBackground(String... params) { String data = params[0]; String ip = "192.168.4.1"; int port = 7777; try { Socket socket = new Socket(ip, port); while (!socket.isConnected()) { } OutputStream out = socket.getOutputStream(); PrintWriter output = new PrintWriter(out); output.println(data); output.flush(); out.close(); output.close(); socket.close(); } catch (SocketException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } return true; } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); if (result) { SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(MyFirebaseInstanceIDService.this); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(getString(R.string.registration_id_sent), true); editor.commit(); } else { SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(MyFirebaseInstanceIDService.this); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(getString(R.string.registration_id_sent), false); editor.commit(); } } }; // Change wifi network to "NodeMCU WiFi" String ssid = ""; WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if (WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState()) == NetworkInfo.DetailedState.CONNECTED) { ssid = wifiInfo.getSSID(); } if (!ssid.equals("NodeMCU WiFi")) { Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), getString(R.string.toast_connect_NodeMCU), Toast.LENGTH_LONG).show(); } }); } }