类java.net.PortUnreachableException源码实例Demo

下面列出了怎么用java.net.PortUnreachableException的API类实例代码及写法,或者点击链接到github查看源代码。

public void testConnectNotExists(Bootstrap cb) throws Throwable {
    final Promise<Throwable> promise = ImmediateEventExecutor.INSTANCE.newPromise();
    cb.handler(new ChannelInboundHandlerAdapter() {
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            promise.trySuccess(cause);
        }
    });
    ChannelFuture future = cb.connect(NetUtil.LOCALHOST, SocketTestPermutation.BAD_PORT);
    try {
        Channel datagramChannel = future.syncUninterruptibly().channel();
        Assert.assertTrue(datagramChannel.isActive());
        datagramChannel.writeAndFlush(
                Unpooled.copiedBuffer("test", CharsetUtil.US_ASCII)).syncUninterruptibly();
        if (!(datagramChannel instanceof OioDatagramChannel)) {
            Assert.assertTrue(promise.syncUninterruptibly().getNow() instanceof PortUnreachableException);
        }
    } finally {
        future.channel().close();
    }
}
 
源代码2 项目: netty-4.1.22   文件: Socket.java
public final int sendTo(ByteBuffer buf, int pos, int limit, InetAddress addr, int port) throws IOException {
    // just duplicate the toNativeInetAddress code here to minimize object creation as this method is expected
    // to be called frequently
    byte[] address;
    int scopeId;
    if (addr instanceof Inet6Address) {
        address = addr.getAddress();
        scopeId = ((Inet6Address) addr).getScopeId();
    } else {
        // convert to ipv4 mapped ipv6 address;
        scopeId = 0;
        address = ipv4MappedIpv6Address(addr.getAddress());
    }
    int res = sendTo(fd, buf, pos, limit, address, scopeId, port);
    if (res >= 0) {
        return res;
    }
    if (res == ERROR_ECONNREFUSED_NEGATIVE) {
        throw new PortUnreachableException("sendTo failed");
    }
    return ioResult("sendTo", res, SEND_TO_CONNECTION_RESET_EXCEPTION, SEND_TO_CLOSED_CHANNEL_EXCEPTION);
}
 
源代码3 项目: netty-4.1.22   文件: Socket.java
public final int sendToAddress(long memoryAddress, int pos, int limit, InetAddress addr, int port)
        throws IOException {
    // just duplicate the toNativeInetAddress code here to minimize object creation as this method is expected
    // to be called frequently
    byte[] address;
    int scopeId;
    if (addr instanceof Inet6Address) {
        address = addr.getAddress();
        scopeId = ((Inet6Address) addr).getScopeId();
    } else {
        // convert to ipv4 mapped ipv6 address;
        scopeId = 0;
        address = ipv4MappedIpv6Address(addr.getAddress());
    }
    int res = sendToAddress(fd, memoryAddress, pos, limit, address, scopeId, port);
    if (res >= 0) {
        return res;
    }
    if (res == ERROR_ECONNREFUSED_NEGATIVE) {
        throw new PortUnreachableException("sendToAddress failed");
    }
    return ioResult("sendToAddress", res,
            SEND_TO_ADDRESS_CONNECTION_RESET_EXCEPTION, SEND_TO_ADDRESS_CLOSED_CHANNEL_EXCEPTION);
}
 
源代码4 项目: netty-4.1.22   文件: Socket.java
public final int sendToAddresses(long memoryAddress, int length, InetAddress addr, int port) throws IOException {
    // just duplicate the toNativeInetAddress code here to minimize object creation as this method is expected
    // to be called frequently
    byte[] address;
    int scopeId;
    if (addr instanceof Inet6Address) {
        address = addr.getAddress();
        scopeId = ((Inet6Address) addr).getScopeId();
    } else {
        // convert to ipv4 mapped ipv6 address;
        scopeId = 0;
        address = ipv4MappedIpv6Address(addr.getAddress());
    }
    int res = sendToAddresses(fd, memoryAddress, length, address, scopeId, port);
    if (res >= 0) {
        return res;
    }

    if (res == ERROR_ECONNREFUSED_NEGATIVE) {
        throw new PortUnreachableException("sendToAddresses failed");
    }
    return ioResult("sendToAddresses", res,
            CONNECTION_RESET_EXCEPTION_SENDMSG, SEND_TO_ADDRESSES_CLOSED_CHANNEL_EXCEPTION);
}
 
源代码5 项目: Bytecoder   文件: DatagramChannelImpl.java
private int sendFromNativeBuffer(FileDescriptor fd, ByteBuffer bb,
                                 InetSocketAddress target)
    throws IOException
{
    int pos = bb.position();
    int lim = bb.limit();
    assert (pos <= lim);
    int rem = (pos <= lim ? lim - pos : 0);

    int written;
    try {
        int addressLen = targetSocketAddress(target);
        written = send0(fd, ((DirectBuffer)bb).address() + pos, rem,
                        targetSockAddr.address(), addressLen);
    } catch (PortUnreachableException pue) {
        if (isConnected())
            throw pue;
        written = rem;
    }
    if (written > 0)
        bb.position(pos + written);
    return written;
}
 
源代码6 项目: j2objc   文件: NetworkBridge.java
private static int maybeThrowAfterRecvfrom(boolean isRead, boolean isConnected, ErrnoException errnoException) throws SocketException, SocketTimeoutException {
    if (isRead) {
        if (errnoException.errno == EAGAIN) {
            return 0;
        } else {
            throw new SocketException(errnoException.getMessage(), errnoException);
        }
    } else {
        if (isConnected && errnoException.errno == ECONNREFUSED) {
            throw new PortUnreachableException("", errnoException);
        } else if (errnoException.errno == EAGAIN) {
            throw new SocketTimeoutException(errnoException);
        } else {
            throw new SocketException(errnoException.getMessage(), errnoException);
        }
    }
}
 
源代码7 项目: wildfly-core   文件: SyslogAuditLogHandler.java
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);
}
 
源代码8 项目: netty-4.1.22   文件: AbstractNioMessageChannel.java
protected boolean closeOnReadError(Throwable cause) {
    // ServerChannel should not be closed even on IOException because it can often continue
    // accepting incoming connections. (e.g. too many open files)
    return cause instanceof IOException &&
            !(cause instanceof PortUnreachableException) &&
            !(this instanceof ServerChannel);
}
 
源代码9 项目: micrometer   文件: StatsdMeterRegistry.java
private void prepareUdpClient(Publisher<String> publisher) {
    AtomicReference<UdpClient> udpClientReference = new AtomicReference<>();
    UdpClient udpClient = UdpClient.create()
            .host(statsdConfig.host())
            .port(statsdConfig.port())
            .handle((in, out) -> out
                    .sendString(publisher)
                    .neverComplete()
                    .retryWhen(Retry.indefinitely().filter(throwable -> throwable instanceof PortUnreachableException))
            )
            .doOnDisconnected(connection -> connectAndSubscribe(udpClientReference.get()));
    udpClientReference.set(udpClient);
    connectAndSubscribe(udpClient);
}
 
源代码10 项目: monsoon   文件: TcpCollectorTest.java
@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);
}
 
源代码11 项目: aeron   文件: SendChannelEndpoint.java
/**
 * 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 == multiSndDestination)
        {
            try
            {
                sendHook(buffer, connectAddress);
                if (sendDatagramChannel.isConnected())
                {
                    bytesSent = sendDatagramChannel.write(buffer);
                }
            }
            catch (final PortUnreachableException ignore)
            {
            }
            catch (final IOException ex)
            {
                sendError(bytesToSend, ex, connectAddress);
            }
        }
        else
        {
            bytesSent = multiSndDestination.send(sendDatagramChannel, buffer, this, bytesToSend);
        }
    }

    return bytesSent;
}
 
源代码12 项目: aeron   文件: MultiSndDestination.java
static int send(
    final DatagramChannel datagramChannel,
    final ByteBuffer buffer,
    final SendChannelEndpoint channelEndpoint,
    final int bytesToSend,
    final int position,
    final InetSocketAddress destination)
{
    int bytesSent = 0;
    try
    {
        if (datagramChannel.isOpen())
        {
            buffer.position(position);
            channelEndpoint.sendHook(buffer, destination);
            bytesSent = datagramChannel.send(buffer, destination);
        }
    }
    catch (final PortUnreachableException ignore)
    {
    }
    catch (final IOException ex)
    {
        sendError(bytesToSend, ex, destination);
    }

    return bytesSent;
}
 
源代码13 项目: pinpoint   文件: UdpDataSender.java
private void sendPacket(Object message) {

        final InetSocketAddress inetSocketAddress = socketAddressProvider.resolve();
        if (inetSocketAddress.getAddress() == null) {
            logger.info("dns lookup fail host:{}", inetSocketAddress);
            return;
        }

        final ByteMessage byteMessage = messageSerializer.serializer(message);
        if (byteMessage == null) {
            logger.warn("sendPacket fail. message:{}", message != null ? message.getClass() : null);
            if (logger.isDebugEnabled()) {
                logger.debug("unknown message:{}", message);
            }
            return;
        }
        final DatagramPacket packet = preparePacket(inetSocketAddress, byteMessage);

        try {
            udpSocket.send(packet);
            if (isDebug) {
                logger.debug("Data sent. size:{}, {}", byteMessage.getLength(), message);
            }
        } catch (PortUnreachableException pe) {
            this.socketAddressProvider.handlePortUnreachable();
            logger.info("packet send error. size:{}, {}", byteMessage.getLength(), message, pe);
        } catch (IOException e) {
            logger.info("packet send error. size:{}, {}", byteMessage.getLength(), message, e);
        }

    }
 
源代码14 项目: RDFS   文件: Client.java
/**
 * 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);

  }
}
 
源代码15 项目: RDFS   文件: RPC.java
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();
}
 
源代码16 项目: uima-uimaj   文件: LocalVNS.java
/**
 * Initialize local VNS instance with a range of ports, and the port for the VNS itself. A given
 * port is tested first for availability. If it is not available the next port is tested, until
 * one is found to be available.
 * 
 * @param aStartPort -
 *          starting port number used
 * @param aEndPort -
 *          end port number. Together with StartPort defines the range of ports (port pool)
 * @param aVNSPort -
 *          port on which this VNS will listen for requests
 * 
 * @throws PortUnreachableException unreachable port after retries
 */
public LocalVNS(int aStartPort, int aEndPort, int aVNSPort) throws PortUnreachableException {
  startport = aStartPort;
  maxport = aEndPort;
  vnsPort = aVNSPort;
  boolean vnsPortAvailable = false;
  int currentRetryCount = 0;
  // Loop until we find a valid port or hard limit of 100 tries is reached
  while (!vnsPortAvailable) {
    if (UIMAFramework.getLogger().isLoggable(Level.INFO)) {
      UIMAFramework.getLogger(this.getClass()).logrb(Level.INFO, this.getClass().getName(),
              "initialize", CPMUtils.CPM_LOG_RESOURCE_BUNDLE, "UIMA_CPM_test_vns_port__INFO",
              new Object[] { Thread.currentThread().getName(), String.valueOf(vnsPort) });
    }
    vnsPortAvailable = isAvailable(vnsPort);

    if (currentRetryCount > 100) {
      UIMAFramework.getLogger(this.getClass()).logrb(Level.SEVERE, this.getClass().getName(),
              "initialize", CPMUtils.CPM_LOG_RESOURCE_BUNDLE,
              "UIMA_CPM_vns_port_not_available__SEVERE",
              new Object[] { Thread.currentThread().getName(), String.valueOf(vnsPort) });

      throw new PortUnreachableException("Unable to aquire a port for VNS Service");
    }
    if (!vnsPortAvailable) {
      vnsPort++;
    }
    currentRetryCount++;
  }
  if (UIMAFramework.getLogger().isLoggable(Level.INFO)) {
    UIMAFramework.getLogger(this.getClass()).logrb(Level.INFO, this.getClass().getName(),
            "initialize", CPMUtils.CPM_LOG_RESOURCE_BUNDLE, "UIMA_CPM_activating_vns_port__INFO",
            new Object[] { Thread.currentThread().getName(), String.valueOf(vnsPort) });
  }
  onport = startport;
}
 
源代码17 项目: uima-uimaj   文件: LocalVNS.java
/**
 * Returns the next available port. The port is allocated from a cache of ports given to the VNS
 * service on startup.
 * 
 * @return - free port
 * 
 * @throws PortUnreachableException can't get port in configured range
 */
public synchronized int getPort() throws PortUnreachableException {
  boolean portAvailable = false;
  int retryCount = 0;
  while (!portAvailable) {
    onport++;
    if (onport > maxport) {
      onport = startport;
      retryCount++; // increment total number of times we cycled through available ports
    }
    if (UIMAFramework.getLogger().isLoggable(Level.INFO)) {
      UIMAFramework.getLogger(this.getClass()).logrb(Level.INFO, this.getClass().getName(),
              "initialize", CPMUtils.CPM_LOG_RESOURCE_BUNDLE, "UIMA_CPM_test_local_port__INFO",
              new Object[] { Thread.currentThread().getName(), String.valueOf(onport) });
    }
    // Check port availability
    portAvailable = isAvailable(onport);
    // In case ports are not available break out of the loop having tried 4 times
    // to acquire any of the ports in configured range
    if (retryCount > 3) {
      throw new PortUnreachableException(
              "Unable to aquire any of the ports in configured range:[" + startport + ".."
                      + maxport + "]");
    }
  }
  return onport;
}
 
源代码18 项目: peer-os   文件: BazaarRestClient.java
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.getBazaarIp() );

        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;
}
 
源代码19 项目: jlibs   文件: NIOUtil.java
public static boolean isConnectionFailure(Throwable thr){
    return thr instanceof UnresolvedAddressException
            || thr instanceof ConnectException
            || thr instanceof PortUnreachableException;
}
 
 类所在包
 同包方法