List of usage examples for java.net Socket isClosed
public boolean isClosed()
From source file:com.mirth.connect.connectors.mllp.MllpMessageDispatcher.java
public void doDispose() { for (Socket connectedSocket : connectedSockets.values()) { if (null != connectedSocket && !connectedSocket.isClosed()) { try { connectedSocket.close(); connectedSockets.values().remove(connectedSocket); connectedSocket = null;/* w ww . j a v a 2s. c om*/ } catch (IOException e) { logger.debug("ConnectedSocked close raised exception. Reason: " + e.getMessage()); } } } }
From source file:edu.umass.cs.msocket.common.policies.GeoLoadProxyPolicy.java
/** * @throws Exception if a GNS error occurs * @see edu.umass.cs.msocket.common.policies.ProxySelectionPolicy#getNewProxy() *///from ww w . j a va 2s . com @Override public List<InetSocketAddress> getNewProxy() throws Exception { // Lookup for active location service GUIDs final UniversalGnsClient gnsClient = gnsCredentials.getGnsClient(); final GuidEntry guidEntry = gnsCredentials.getGuidEntry(); JSONArray guids; try { guids = gnsClient.fieldRead(proxyGroupName, GnsConstants.ACTIVE_LOCATION_FIELD, guidEntry); } catch (Exception e) { throw new GnsException("Could not find active location services (" + e + ")"); } // Try every location proxy in the list until one works for (int i = 0; i < guids.length(); i++) { // Retrieve the location service IP and connect to it String locationGuid = guids.getString(i); String locationIP = gnsClient.fieldRead(locationGuid, GnsConstants.LOCATION_SERVICE_IP, guidEntry) .getString(0); logger.fine("Contacting location service " + locationIP + " to request " + numProxies + " proxies"); // Location IP is stored as host:port StringTokenizer st = new StringTokenizer(locationIP, ":"); try { // Protocol is send the number of desired proxies and receive strings // containing proxy IP:port Socket s = new Socket(st.nextToken(), Integer.parseInt(st.nextToken())); ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); ObjectInputStream ois = new ObjectInputStream(s.getInputStream()); oos.writeInt(numProxies); oos.flush(); List<InetSocketAddress> result = new LinkedList<InetSocketAddress>(); while (!s.isClosed() && result.size() < numProxies) { String proxyIP = ois.readUTF(); StringTokenizer stp = new StringTokenizer(proxyIP, ":"); result.add(new InetSocketAddress(stp.nextToken(), Integer.parseInt(stp.nextToken()))); } if (!s.isClosed()) // We receive all the proxies we need, just close the // socket s.close(); return result; } catch (Exception e) { logger.info("Failed to obtain proxy from location service" + locationIP + " (" + e + ")"); } } throw new GnsException("Could not find any location service to provide a geolocated proxy"); }
From source file:com.mirth.connect.connectors.mllp.MllpMessageDispatcher.java
public void doDispose(Socket socket) { monitoringController.updateStatus(connector, connectorType, Event.DISCONNECTED, socket); if (null != socket && !socket.isClosed()) { try {/* w w w . ja v a 2 s .com*/ socket.close(); connectedSockets.values().remove(socket); socket = null; } catch (IOException e) { logger.debug("ConnectedSocked close raised exception. Reason: " + e.getMessage()); } } }
From source file:com.groupon.odo.bmp.http.SimulatedSocketFactory.java
/** * Checks whether a socket connection is secure. This factory creates plain socket connections which are not * considered secure./* w w w .j a v a 2 s .com*/ * * @param sock the connected socket * @return <code>false</code> * @throws IllegalArgumentException if the argument is invalid */ @Override public final boolean isSecure(Socket sock) throws IllegalArgumentException { if (sock == null) { throw new IllegalArgumentException("Socket may not be null."); } // This check is performed last since it calls a method implemented // by the argument object. getClass() is final in java.lang.Object. if (sock.isClosed()) { throw new IllegalArgumentException("Socket is closed."); } return false; }
From source file:com.shonshampain.streamrecorder.util.StreamProxy.java
private void startOver(InputStream data, Socket client, FailType type, Exception e) throws IOException { if (data != null) { Logger.e(TAG, "Closing data connection"); data.close();//from ww w. j a v a 2 s .c o m } if (client != null && !client.isClosed()) { Logger.e(TAG, "Closing client connection"); client.close(); } ++retryCount; switch (type) { case Stall: Logger.e(TAG, "Stream has stalled, rethrottling(" + retryCount + ") the data connection"); break; case Unexpected: Logger.e(TAG, "Unexpected exception: " + e.getLocalizedMessage() + " retrying(" + retryCount + ")"); break; case CantDownload: Logger.e(TAG, "Cannot download, retrying(" + retryCount + ")"); break; case SocketAccept: Logger.e(TAG, "Cannot accept on the socket, retrying(" + retryCount + ")"); break; } if (retryCount == MAX_RETRIES) { Logger.e(TAG, "Retry count exceeded, stopping stream service"); StreamManager.getInstance().stop(StreamRecorderApplication.getContext()); } else { EventBus.getDefault().post(new ThrottleStreamRequest()); } }
From source file:org.springframework.integration.ip.tcp.TcpOutboundGatewayTests.java
@Test public void testCachingFailover() throws Exception { final int port = SocketUtils.findAvailableServerSocket(); final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean done = new AtomicBoolean(); final CountDownLatch serverLatch = new CountDownLatch(1); Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port); latch.countDown();//from w w w.j a va 2 s . c om while (!done.get()) { Socket socket = server.accept(); while (!socket.isClosed()) { try { ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); String request = (String) ois.readObject(); logger.debug("Read " + request); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); oos.writeObject("bar"); logger.debug("Replied to " + request); serverLatch.countDown(); } catch (IOException e) { logger.debug("error on write " + e.getClass().getSimpleName()); socket.close(); } } } } catch (Exception e) { if (!done.get()) { e.printStackTrace(); } } } }); assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); // Failover AbstractClientConnectionFactory factory1 = mock(AbstractClientConnectionFactory.class); TcpConnectionSupport mockConn1 = makeMockConnection(); when(factory1.getConnection()).thenReturn(mockConn1); doThrow(new IOException("fail")).when(mockConn1).send(Mockito.any(Message.class)); AbstractClientConnectionFactory factory2 = new TcpNetClientConnectionFactory("localhost", port); factory2.setSerializer(new DefaultSerializer()); factory2.setDeserializer(new DefaultDeserializer()); factory2.setSoTimeout(10000); factory2.setSingleUse(false); List<AbstractClientConnectionFactory> factories = new ArrayList<AbstractClientConnectionFactory>(); factories.add(factory1); factories.add(factory2); FailoverClientConnectionFactory failoverFactory = new FailoverClientConnectionFactory(factories); failoverFactory.start(); // Cache CachingClientConnectionFactory cachingFactory = new CachingClientConnectionFactory(failoverFactory, 2); cachingFactory.start(); TcpOutboundGateway gateway = new TcpOutboundGateway(); gateway.setConnectionFactory(cachingFactory); PollableChannel outputChannel = new QueueChannel(); gateway.setOutputChannel(outputChannel); gateway.afterPropertiesSet(); gateway.start(); GenericMessage<String> message = new GenericMessage<String>("foo"); gateway.handleMessage(message); Message<?> reply = outputChannel.receive(0); assertNotNull(reply); assertEquals("bar", reply.getPayload()); done.set(true); gateway.stop(); verify(mockConn1).send(Mockito.any(Message.class)); }
From source file:org.springframework.integration.ip.tcp.TcpOutboundGatewayTests.java
@Test public void testFailoverCached() throws Exception { final int port = SocketUtils.findAvailableServerSocket(); final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean done = new AtomicBoolean(); final CountDownLatch serverLatch = new CountDownLatch(1); Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port); latch.countDown();/*from w w w . java 2s . c om*/ while (!done.get()) { Socket socket = server.accept(); while (!socket.isClosed()) { try { ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); String request = (String) ois.readObject(); logger.debug("Read " + request); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); oos.writeObject("bar"); logger.debug("Replied to " + request); serverLatch.countDown(); } catch (IOException e) { logger.debug("error on write " + e.getClass().getSimpleName()); socket.close(); } } } } catch (Exception e) { if (!done.get()) { e.printStackTrace(); } } } }); assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); // Cache AbstractClientConnectionFactory factory1 = mock(AbstractClientConnectionFactory.class); TcpConnectionSupport mockConn1 = makeMockConnection(); when(factory1.getConnection()).thenReturn(mockConn1); doThrow(new IOException("fail")).when(mockConn1).send(Mockito.any(Message.class)); CachingClientConnectionFactory cachingFactory1 = new CachingClientConnectionFactory(factory1, 1); AbstractClientConnectionFactory factory2 = new TcpNetClientConnectionFactory("localhost", port); factory2.setSerializer(new DefaultSerializer()); factory2.setDeserializer(new DefaultDeserializer()); factory2.setSoTimeout(10000); factory2.setSingleUse(false); CachingClientConnectionFactory cachingFactory2 = new CachingClientConnectionFactory(factory2, 1); // Failover List<AbstractClientConnectionFactory> factories = new ArrayList<AbstractClientConnectionFactory>(); factories.add(cachingFactory1); factories.add(cachingFactory2); FailoverClientConnectionFactory failoverFactory = new FailoverClientConnectionFactory(factories); failoverFactory.start(); TcpOutboundGateway gateway = new TcpOutboundGateway(); gateway.setConnectionFactory(failoverFactory); PollableChannel outputChannel = new QueueChannel(); gateway.setOutputChannel(outputChannel); gateway.afterPropertiesSet(); gateway.start(); GenericMessage<String> message = new GenericMessage<String>("foo"); gateway.handleMessage(message); Message<?> reply = outputChannel.receive(0); assertNotNull(reply); assertEquals("bar", reply.getPayload()); done.set(true); gateway.stop(); verify(mockConn1).send(Mockito.any(Message.class)); }
From source file:org.springframework.integration.ip.tcp.TcpOutboundGatewayTests.java
private void testGWPropagatesSocketCloseGuts(final int port, AbstractClientConnectionFactory ccf) throws Exception { final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean done = new AtomicBoolean(); final AtomicReference<String> lastReceived = new AtomicReference<String>(); final CountDownLatch serverLatch = new CountDownLatch(1); Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port); latch.countDown();/* ww w . j a v a2 s . co m*/ int i = 0; while (!done.get()) { Socket socket = server.accept(); i++; while (!socket.isClosed()) { try { ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); String request = (String) ois.readObject(); logger.debug("Read " + request + " closing socket"); socket.close(); lastReceived.set(request); serverLatch.countDown(); } catch (IOException e) { socket.close(); } } } } catch (Exception e) { if (!done.get()) { e.printStackTrace(); } } } }); assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); final TcpOutboundGateway gateway = new TcpOutboundGateway(); gateway.setConnectionFactory(ccf); gateway.setRequestTimeout(Integer.MAX_VALUE); QueueChannel replyChannel = new QueueChannel(); gateway.setRequiresReply(true); gateway.setOutputChannel(replyChannel); gateway.setRemoteTimeout(5000); gateway.afterPropertiesSet(); gateway.start(); try { gateway.handleMessage(MessageBuilder.withPayload("Test").build()); fail("expected failure"); } catch (Exception e) { assertTrue(e.getCause() instanceof EOFException); } assertEquals(0, TestUtils.getPropertyValue(gateway, "pendingReplies", Map.class).size()); Message<?> reply = replyChannel.receive(0); assertNull(reply); done.set(true); ccf.getConnection(); }
From source file:com.budrotech.jukebox.service.ssl.SSLSocketFactory.java
/** * Checks whether a socket connection is secure. * This factory creates TLS/SSL socket connections * which, by default, are considered secure. * <br/>/*from www .ja v a2 s . c o m*/ * Derived classes may override this method to perform * runtime checks, for example based on the cypher suite. * * @param sock the connected socket * @return <code>true</code> * @throws IllegalArgumentException if the argument is invalid */ public boolean isSecure(final Socket sock) throws IllegalArgumentException { if (sock == null) { throw new IllegalArgumentException("Socket may not be null"); } // This instanceof check is in line with createSocket() above. if (!(sock instanceof SSLSocket)) { throw new IllegalArgumentException("Socket not created by this factory"); } // This check is performed last since it calls the argument object. if (sock.isClosed()) { throw new IllegalArgumentException("Socket is closed"); } return true; }
From source file:com.android.beyondemail.SSLSocketFactory.java
/** * Checks whether a socket connection is secure. * This factory creates TLS/SSL socket connections * which, by default, are considered secure. * <br/>//w w w . j av a 2s. com * Derived classes may override this method to perform * runtime checks, for example based on the cypher suite. * * @param sock the connected socket * * @return <code>true</code> * * @throws IllegalArgumentException if the argument is invalid */ public boolean isSecure(Socket sock) throws IllegalArgumentException { if (sock == null) { throw new IllegalArgumentException("Socket may not be null."); } // This instanceof check is in line with createSocket() above. if (!(sock instanceof SSLSocket)) { throw new IllegalArgumentException("Socket not created by this factory."); } // This check is performed last since it calls the argument object. if (sock.isClosed()) { throw new IllegalArgumentException("Socket is closed."); } return true; }