private void connect(String portName) throws Exception { CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName); if (portIdentifier.isCurrentlyOwned()) throw new PortInUseException(); CommPort commPort = portIdentifier.open(this.getClass().getName(), COMPORT_PORT); if (commPort instanceof SerialPort) { SerialPort serialPort = (SerialPort) commPort; serialPort.setSerialPortParams(BAUD_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); InputStream in = serialPort.getInputStream(); OutputStream out = serialPort.getOutputStream(); new Thread(new SerialReader(in)).start(); new Thread(new SerialWriter(out)).start(); } else { throw new PortUnreachableException("ERROR - Only serial ports are handled by this class"); } }
private static int maybeThrowAfterRecvfrom(boolean isRead, boolean isConnected, ErrnoException errnoException) throws SocketException, SocketTimeoutException { if (isRead) { if (errnoException.errno == EAGAIN) { return 0; } else { throw errnoException.rethrowAsSocketException(); } } else { if (isConnected && errnoException.errno == ECONNREFUSED) { throw new PortUnreachableException("", errnoException); } else if (errnoException.errno == EAGAIN) { throw new SocketTimeoutException(errnoException); } else { throw errnoException.rethrowAsSocketException(); } } }
void throwAsIoOrRuntimeException(Throwable t) throws IOException { if (t instanceof PortUnreachableException && transport == Transport.UDP) { //This is an exception that may or may not happen, see the javadoc for DatagramSocket.send(). //We don't want something this unreliable polluting the failure count. //With UDP syslogging set up against a non-existent syslog server: //On OS X this exception never happens. //On Linux this seems to happens every other send, so we end up with a loop // odd send works; failure count = 0 // even send fails; failure count = 1 // odd send works; failure count reset to 0 // //Also, we don't want the full stack trace for this which would get printed by StandardFailureCountHandler.StandardFailureCountHandler.failure(), //which also handles the failure count, so we swallow the exception and print a warning. ControllerLogger.MGMT_OP_LOGGER.udpSyslogServerUnavailable(getName(), t.getLocalizedMessage()); return; } if (t instanceof IOException) { throw (IOException)t; } if (t instanceof RuntimeException) { throw (RuntimeException)t; } throw new RuntimeException(t); }
public void run() { this.func_72609_b("Query running on " + this.field_72642_r + ":" + this.field_72636_h); this.field_72629_g = MinecraftServer.func_130071_aq(); this.field_72631_o = new DatagramPacket(this.field_72630_n, this.field_72630_n.length); try { while(this.field_72619_a) { try { this.field_72633_m.receive(this.field_72631_o); this.func_72628_f(); this.func_72621_a(this.field_72631_o); } catch (SocketTimeoutException var7) { this.func_72628_f(); } catch (PortUnreachableException var8) { ; } catch (IOException var9) { this.func_72623_a(var9); } } } finally { this.func_72611_e(); } }
public void run() { this.b("Query running on " + this.s + ":" + this.i); this.h = MinecraftServer.av(); this.p = new DatagramPacket(this.o, this.o.length); try { while (this.a) { try { this.n.receive(this.p); this.f(); this.a(this.p); } catch (SocketTimeoutException sockettimeoutexception) { this.f(); } catch (PortUnreachableException portunreachableexception) { ; } catch (IOException ioexception) { this.a((Exception) ioexception); } } } finally { this.e(); } }
public void run() { this.logInfo("Query running on " + this.serverHostname + ":" + this.queryPort); this.lastAuthCheckTime = MinecraftServer.getCurrentTimeMillis(); this.incomingPacket = new DatagramPacket(this.buffer, this.buffer.length); try { while (this.running) { try { this.querySocket.receive(this.incomingPacket); this.cleanQueryClientsMap(); this.parseIncomingPacket(this.incomingPacket); } catch (SocketTimeoutException var7) { this.cleanQueryClientsMap(); } catch (PortUnreachableException var8) { ; } catch (IOException ioexception) { this.stopWithException(ioexception); } } } finally { this.closeAllSockets(); } }
public static boolean isServerUnavailableException(Throwable cause) { return isHttpException(cause, 503) || (isException(cause, ConnectException.class) || isException(cause, NoRouteToHostException.class) || isException(cause, PortUnreachableException.class) || isException(cause, SocketTimeoutException.class)); }
@Test public void connectPortUnreachable() throws Exception { Mockito.doThrow(new PortUnreachableException()).when(mockSocket).connect(Mockito.any()); final TcpCollector.ConnectDatum result; try (TcpCollector tcpCollector = new TcpCollector(dstAddress, GROUP)) { result = tcpCollector.tryConnect(mockSocket); } assertThat(result.getResult(), equalTo(TcpCollector.ConnectResult.PORT_UNREACHABLE)); Mockito.verify(mockSocket, times(1)).connect(Mockito.eq(dstAddress)); Mockito.verifyNoMoreInteractions(mockSocket); }
private boolean shouldHandleException(IOException ex) { // enumerate handled exceptions if (ex instanceof ConnectException || ex instanceof NoRouteToHostException || ex instanceof PortUnreachableException || ex instanceof EOFException || ex instanceof ConnectionClosedException) { return true; } if (ex instanceof RemoteException && ((RemoteException) ex).unwrapRemoteException() instanceof SafeModeException) { return true; } return false; // we rethrow all other exceptions (including remote exceptions }
/** * Take an IOException and the address we were trying to connect to * and return an IOException with the input exception as the cause. * The new exception provides the stack trace of the place where * the exception is thrown and some extra diagnostics information. * If the exception is ConnectException or SocketTimeoutException, * return a new one of the same type; Otherwise return an IOException. * * @param addr target address * @param exception the relevant exception * @return an exception to throw */ private IOException wrapException(InetSocketAddress addr, IOException exception) { if (exception instanceof ConnectException) { //connection refused; include the host:port in the error return (ConnectException)new ConnectException( "Call to " + addr + " failed on connection exception: " + exception) .initCause(exception); } else if (exception instanceof SocketTimeoutException) { return (SocketTimeoutException)new SocketTimeoutException( "Call to " + addr + " failed on socket timeout exception: " + exception).initCause(exception); } else if (exception instanceof NoRouteToHostException) { return (NoRouteToHostException)new NoRouteToHostException( "Call to " + addr + " failed on NoRouteToHostException exception: " + exception).initCause(exception); } else if (exception instanceof PortUnreachableException) { return (PortUnreachableException)new PortUnreachableException( "Call to " + addr + " failed on PortUnreachableException exception: " + exception).initCause(exception); } else if (exception instanceof EOFException) { return (EOFException)new EOFException( "Call to " + addr + " failed on EOFException exception: " + exception).initCause(exception); } else { return (IOException)new IOException( "Call to " + addr + " failed on local exception: " + exception) .initCause(exception); } }
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { final boolean logDebug = !fastProtocol && LOG.isDebugEnabled(); long startTime = 0; if (logDebug) { startTime = System.currentTimeMillis(); } ObjectWritable value = null; try { String name = null; if (fastProtocol) { // try to obtain registered name for the method name = FastProtocolRegister.tryGetId(method); } value = (ObjectWritable) client.call(new Invocation(method, name, args), getAddress(), protocol, ticket, rpcTimeout, fastProtocol); } catch (RemoteException re) { throw re; } catch (ConnectException ce) { needCheckDnsUpdate = true; throw ce; } catch (NoRouteToHostException nrhe) { needCheckDnsUpdate = true; throw nrhe; } catch (PortUnreachableException pue) { needCheckDnsUpdate = true; throw pue; } catch (UnknownHostException uhe) { needCheckDnsUpdate = true; throw uhe; } if (logDebug) { long callTime = System.currentTimeMillis() - startTime; LOG.debug("Call: " + method.getName() + " " + callTime); } return value.get(); }
/** * iOS devices are in a deep sleep mode, where they only listen to UDP traffic on port 5353 (Bonjour service * discovery). A packet on port 5353 will wake up the network stack to respond to ARP pings at least. * * @throws IOException */ public void wakeUpIOS(InetAddress address) throws IOException { try (DatagramSocket s = new DatagramSocket()) { byte[] buffer = new byte[0]; s.send(new DatagramPacket(buffer, buffer.length, address, 5353)); } catch (PortUnreachableException ignored) { // We ignore the port unreachable error } }
/** * Send contents of a {@link ByteBuffer} to connected address. * This is used on the sender side for performance over send(ByteBuffer, SocketAddress). * * @param buffer to send * @return number of bytes sent */ public int send(final ByteBuffer buffer) { int bytesSent = 0; if (null != sendDatagramChannel) { final int bytesToSend = buffer.remaining(); if (null == multiDestination) { try { presend(buffer, connectAddress); bytesSent = sendDatagramChannel.write(buffer); } catch (final PortUnreachableException | ClosedChannelException | NotYetConnectedException ignore) { } catch (final IOException ex) { throw new RuntimeException("Failed to send packet of length: " + bytesToSend, ex); } } else { bytesSent = multiDestination.send(sendDatagramChannel, buffer, this, bytesToSend); } } return bytesSent; }
int send( final DatagramChannel datagramChannel, final ByteBuffer buffer, final SendChannelEndpoint channelEndpoint, final int bytesToSend) { final int position = buffer.position(); int minBytesSent = bytesToSend; for (final InetSocketAddress destination : destinations) { int bytesSent = 0; try { channelEndpoint.presend(buffer, destination); buffer.position(position); bytesSent = datagramChannel.send(buffer, destination); } catch (final PortUnreachableException | ClosedChannelException ignore) { } catch (final IOException ex) { throw new RuntimeException("Failed to send: " + bytesToSend, ex); } minBytesSent = Math.min(minBytesSent, bytesSent); } return minBytesSent; }
public void run() { this.logInfo("Query running on " + this.serverHostname + ":" + this.queryPort); this.lastAuthCheckTime = MinecraftServer.getSystemTimeMillis(); this.incomingPacket = new DatagramPacket(this.buffer, this.buffer.length); try { while (this.running) { try { this.querySocket.receive(this.incomingPacket); this.cleanQueryClientsMap(); this.parseIncomingPacket(this.incomingPacket); } catch (SocketTimeoutException sockettimeoutexception) { this.cleanQueryClientsMap(); } catch (PortUnreachableException portunreachableexception) { ; } catch (IOException ioexception) { this.stopWithException(ioexception); } } } finally { this.closeAllSockets(); } }
/** * Take an IOException and the address we were trying to connect to * and return an IOException with the input exception as the cause. * The new exception provides the stack trace of the place where * the exception is thrown and some extra diagnostics information. * If the exception is ConnectException or SocketTimeoutException, * return a new one of the same type; Otherwise return an IOException. * * @param addr target address * @param exception the relevant exception * @return an exception to throw */ private IOException wrapException(InetSocketAddress addr, IOException exception) { if (exception instanceof ConnectException) { //connection refused; include the host:port in the error return (ConnectException)new ConnectException( "Call to " + addr + " failed on connection exception: " + exception) .initCause(exception); } else if (exception instanceof SocketTimeoutException) { return (SocketTimeoutException)new SocketTimeoutException( "Call to " + addr + " failed on socket timeout exception: " + exception).initCause(exception); } else if (exception instanceof NoRouteToHostException) { return (NoRouteToHostException)new NoRouteToHostException( "Call to " + addr + " failed on NoRouteToHostException exception: " + exception).initCause(exception); } else if (exception instanceof PortUnreachableException) { return (PortUnreachableException)new PortUnreachableException( "Call to " + addr + " failed on PortUnreachableException exception: " + exception).initCause(exception); } else { return (IOException)new IOException( "Call to " + addr + " failed on local exception: " + exception) .initCause(exception); } }
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { final boolean logDebug = LOG.isDebugEnabled(); long startTime = 0; if (logDebug) { startTime = System.currentTimeMillis(); } ObjectWritable value = null; try { value = (ObjectWritable) client.call(new Invocation(method, args), getAddress(), protocol, ticket, rpcTimeout); } catch (RemoteException re) { throw re; } catch (ConnectException ce) { needCheckDnsUpdate = true; throw ce; } catch (NoRouteToHostException nrhe) { needCheckDnsUpdate = true; throw nrhe; } catch (PortUnreachableException pue) { needCheckDnsUpdate = true; throw pue; } if (logDebug) { long callTime = System.currentTimeMillis() - startTime; LOG.debug("Call: " + method.getName() + " " + callTime); } return value.get(); }
public void run() { this.logInfo("Query running on " + this.serverHostname + ":" + this.queryPort); this.lastAuthCheckTime = MinecraftServer.func_130071_aq(); this.incomingPacket = new DatagramPacket(this.buffer, this.buffer.length); try { while (this.running) { try { this.querySocket.receive(this.incomingPacket); this.cleanQueryClientsMap(); this.parseIncomingPacket(this.incomingPacket); } catch (SocketTimeoutException var7) { this.cleanQueryClientsMap(); } catch (PortUnreachableException var8) { ; } catch (IOException var9) { this.stopWithException(var9); } } } finally { this.closeAllSockets(); } }
/** * Write to ccnd using methods based on the protocol type * @param src - ByteBuffer to write * @return - number of bytes written * @throws IOException */ public int write(ByteBuffer src) throws IOException { if (! isConnected()) return -1; // XXX - is this documented? if (Log.isLoggable(Log.FAC_NETMANAGER, Level.FINEST)) Log.finest(Log.FAC_NETMANAGER, "NetworkChannel {0}: write() on port {1}", _channelId, _ncLocalPort); try { if (_ncDGrmChannel != null) { return (_ncDGrmChannel.write(src)); } else { // XXX -this depends on synchronization in caller, which is less than ideal. // Need to handle partial writes int written = 0; while (src.hasRemaining()) { if (! isConnected()) return -1; int b = _ncSockChannel.write(src); if (b > 0) { written += b; } else { _ncWriteSelector.selectedKeys().clear(); _ncWriteSelector.select(); } } return written; } } catch (PortUnreachableException pue) {} catch (ClosedChannelException cce) {} Log.info(Log.FAC_NETMANAGER, "NetworkChannel {0}: closing due to error on write", _channelId); close(true); return -1; }
public static boolean hasServerConnectivity(Throwable cause) { return !(isException(cause, ConnectException.class) || isException(cause, NoRouteToHostException.class) || isException(cause, PortUnreachableException.class) || isException(cause, SocketTimeoutException.class)); }
private <T> RestResult<T> execute( String httpMethod, String url, Object body, Class<T> clazz, boolean encrypt ) { log.info( "{} {}", httpMethod, url ); WebClient webClient = null; Response response = null; RestResult<T> restResult = new RestResult<>( HttpStatus.SC_INTERNAL_SERVER_ERROR ); try { webClient = configManager.getTrustedWebClientWithAuth( url, configManager.getHubIp() ); Object requestBody = encrypt ? encryptBody( body ) : body; response = webClient.invoke( httpMethod, requestBody ); // retry on 503 http code >>> int attemptNo = 1; while ( response.getStatus() == HttpStatus.SC_SERVICE_UNAVAILABLE && attemptNo < MAX_ATTEMPTS ) { attemptNo++; response = webClient.invoke( httpMethod, requestBody ); TaskUtil.sleep( 500 ); } // <<< retry on 503 http code log.info( "response.status: {} - {}", response.getStatus(), response.getStatusInfo().getReasonPhrase() ); restResult = handleResponse( response, clazz, encrypt ); } catch ( Exception e ) { if ( response != null ) { restResult.setReasonPhrase( response.getStatusInfo().getReasonPhrase() ); } Throwable rootCause = ExceptionUtil.getRootCauze( e ); if ( rootCause instanceof ConnectException || rootCause instanceof UnknownHostException || rootCause instanceof BindException || rootCause instanceof NoRouteToHostException || rootCause instanceof PortUnreachableException || rootCause instanceof SocketTimeoutException ) { restResult.setError( CONNECTION_EXCEPTION_MARKER ); } else { restResult.setError( ERROR + e.getMessage() ); } log.error( ERROR + e.getMessage() ); } finally { close( webClient, response ); } return restResult; }
public static boolean isConnectionFailure(Throwable thr){ return thr instanceof UnresolvedAddressException || thr instanceof ConnectException || thr instanceof PortUnreachableException; }
int send( final DatagramChannel datagramChannel, final ByteBuffer buffer, final SendChannelEndpoint channelEndpoint, final int bytesToSend) { final long nowNs = nanoClock.nanoTime(); final ArrayList<Destination> destinations = this.destinations; final int position = buffer.position(); int minBytesSent = bytesToSend; for (int lastIndex = destinations.size() - 1, i = lastIndex; i >= 0; i--) { final Destination destination = destinations.get(i); if (nowNs > (destination.timeOfLastActivityNs + destinationTimeoutNs)) { ArrayListUtil.fastUnorderedRemove(destinations, i, lastIndex); lastIndex--; } else { int bytesSent = 0; try { channelEndpoint.presend(buffer, destination.address); buffer.position(position); bytesSent = datagramChannel.send(buffer, destination.address); } catch (final PortUnreachableException | ClosedChannelException ignore) { } catch (final IOException ex) { throw new RuntimeException("Failed to send packet of length: " + bytesToSend, ex); } minBytesSent = Math.min(minBytesSent, bytesSent); } } return minBytesSent; }