Search in sources :

Example 26 with UnresolvedAddressException

use of java.nio.channels.UnresolvedAddressException in project grpc-java by grpc.

the class Utils method statusFromThrowable.

public static Status statusFromThrowable(Throwable t) {
    Status s = Status.fromThrowable(t);
    if (s.getCode() != Status.Code.UNKNOWN) {
        return s;
    }
    if (t instanceof ClosedChannelException) {
        // ClosedChannelException is used any time the Netty channel is closed. Proper error
        // processing requires remembering the error that occurred before this one and using it
        // instead.
        // 
        // Netty uses an exception that has no stack trace, while we would never hope to show this to
        // users, if it happens having the extra information may provide a small hint of where to
        // look.
        ClosedChannelException extraT = new ClosedChannelException();
        extraT.initCause(t);
        return Status.UNKNOWN.withDescription("channel closed").withCause(extraT);
    }
    if (t instanceof DecoderException && t.getCause() instanceof SSLException) {
        return Status.UNAVAILABLE.withDescription("ssl exception").withCause(t);
    }
    if (t instanceof IOException) {
        return Status.UNAVAILABLE.withDescription("io exception").withCause(t);
    }
    if (t instanceof UnresolvedAddressException) {
        return Status.UNAVAILABLE.withDescription("unresolved address").withCause(t);
    }
    if (t instanceof Http2Exception) {
        return Status.INTERNAL.withDescription("http2 exception").withCause(t);
    }
    return s;
}
Also used : Status(io.grpc.Status) ClosedChannelException(java.nio.channels.ClosedChannelException) DecoderException(io.netty.handler.codec.DecoderException) Http2Exception(io.netty.handler.codec.http2.Http2Exception) IOException(java.io.IOException) UnresolvedAddressException(java.nio.channels.UnresolvedAddressException) SSLException(javax.net.ssl.SSLException)

Example 27 with UnresolvedAddressException

use of java.nio.channels.UnresolvedAddressException in project ToyShark by LipiLee.

the class SocketNIODataService method processTCPSelectionKey.

private void processTCPSelectionKey(SelectionKey key) throws IOException {
    if (!key.isValid()) {
        Log.d(TAG, "Invalid SelectionKey for TCP");
        return;
    }
    SocketChannel channel = (SocketChannel) key.channel();
    Session session = SessionManager.INSTANCE.getSessionByChannel(channel);
    if (session == null) {
        return;
    }
    if (!session.isConnected() && key.isConnectable()) {
        String ips = PacketUtil.intToIPAddress(session.getDestIp());
        int port = session.getDestPort();
        SocketAddress address = new InetSocketAddress(ips, port);
        Log.d(TAG, "connecting to remote tcp server: " + ips + ":" + port);
        boolean connected = false;
        if (!channel.isConnected() && !channel.isConnectionPending()) {
            try {
                connected = channel.connect(address);
            } catch (ClosedChannelException | UnresolvedAddressException | UnsupportedAddressTypeException | SecurityException e) {
                Log.e(TAG, e.toString());
                session.setAbortingConnection(true);
            } catch (IOException e) {
                Log.e(TAG, e.toString());
                session.setAbortingConnection(true);
            }
        }
        if (connected) {
            session.setConnected(connected);
            Log.d(TAG, "connected immediately to remote tcp server: " + ips + ":" + port);
        } else {
            if (channel.isConnectionPending()) {
                connected = channel.finishConnect();
                session.setConnected(connected);
                Log.d(TAG, "connected to remote tcp server: " + ips + ":" + port);
            }
        }
    }
    if (channel.isConnected()) {
        processSelector(key, session);
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ClosedChannelException(java.nio.channels.ClosedChannelException) UnsupportedAddressTypeException(java.nio.channels.UnsupportedAddressTypeException) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) UnresolvedAddressException(java.nio.channels.UnresolvedAddressException) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) Session(com.lipisoft.toyshark.Session)

Example 28 with UnresolvedAddressException

use of java.nio.channels.UnresolvedAddressException in project ambry by linkedin.

the class Selector method connect.

/**
 * Begin connecting to the given address and add the connection to this selector and returns an id that identifies
 * the connection
 * <p>
 * Note that this call only initiates the connection, which will be completed on a future {@link #poll(long)}
 * call. Check {@link #connected()} to see which (if any) connections have completed after a given poll call.
 * @param address The address to connect to
 * @param sendBufferSize The networkSend buffer size for the new connection
 * @param receiveBufferSize The receive buffer size for the new connection
 * @param portType {@link PortType} which represents the type of connection to establish
 * @return The id for the connection that was created
 * @throws IllegalStateException if there is already a connection for that id
 * @throws IOException if DNS resolution fails on the hostname or if the server is down
 */
@Override
public String connect(InetSocketAddress address, int sendBufferSize, int receiveBufferSize, PortType portType) throws IOException {
    SocketChannel channel = SocketChannel.open();
    channel.configureBlocking(false);
    Socket socket = channel.socket();
    socket.setKeepAlive(true);
    socket.setSendBufferSize(sendBufferSize);
    socket.setReceiveBufferSize(receiveBufferSize);
    socket.setTcpNoDelay(true);
    try {
        channel.connect(address);
    } catch (UnresolvedAddressException e) {
        channel.close();
        throw new IOException("Can't resolve address: " + address, e);
    } catch (IOException e) {
        channel.close();
        throw e;
    }
    String connectionId = generateConnectionId(channel);
    SelectionKey key = channel.register(this.nioSelector, SelectionKey.OP_CONNECT);
    Transmission transmission;
    try {
        transmission = createTransmission(connectionId, key, address.getHostName(), address.getPort(), portType, SSLFactory.Mode.CLIENT);
    } catch (IOException e) {
        logger.error("IOException on transmission creation {}", e);
        channel.socket().close();
        channel.close();
        throw e;
    }
    key.attach(transmission);
    this.keyMap.put(connectionId, key);
    numActiveConnections.set(this.keyMap.size());
    return connectionId;
}
Also used : SocketChannel(java.nio.channels.SocketChannel) SelectionKey(java.nio.channels.SelectionKey) UnresolvedAddressException(java.nio.channels.UnresolvedAddressException) IOException(java.io.IOException) Socket(java.net.Socket)

Example 29 with UnresolvedAddressException

use of java.nio.channels.UnresolvedAddressException in project sakuli by ConSol.

the class GearmanResultServiceImplTest method testSaveAllResultsWrongConnectionCacheResults.

@Test
public void testSaveAllResultsWrongConnectionCacheResults() throws Exception {
    final String host = "not-resolveable-host.de";
    when(properties.getServerHost()).thenReturn(host);
    when(properties.isCacheEnabled()).thenReturn(true);
    TestSuite testSuite = new TestSuiteExampleBuilder().buildExample();
    when(checkResultBuilder.build(testSuite)).thenReturn(new NagiosCheckResult(queueName, "sakuli_demo22__2015_03_07_12_59_00_00", testResult));
    doReturn(connection).when(testling).getGearmanConnection(host, port);
    when(gearmanClient.addJobServer(connection)).thenThrow(new UnresolvedAddressException());
    when(gearmanCacheService.getCachedResults()).thenReturn(Collections.emptyList());
    doAnswer(invocationOnMock -> {
        assertEquals(((List) invocationOnMock.getArguments()[0]).size(), 1L);
        return null;
    }).when(gearmanCacheService).cacheResults(anyList());
    doAnswer(invocationOnMock -> {
        Exception exception = (Exception) invocationOnMock.getArguments()[0];
        assertRegExMatch(exception.getMessage(), "Could not transfer Sakuli results to the Gearman server.*");
        assertEquals(exception.getSuppressed()[0].getClass(), UnresolvedAddressException.class);
        return null;
    }).when(exceptionHandler).handleException(any(Exception.class), anyBoolean());
    testling.tearDown(Optional.of(testSuite));
    // checks
    verify(gearmanCacheService).cacheResults(anyList());
    verify(gearmanCacheService).getCachedResults();
    verify(exceptionHandler).handleException(any(SakuliForwarderRuntimeException.class));
    verify(testling).getGearmanClient();
    verify(testling).getGearmanConnection(host, port);
    verify(gearmanClient).addJobServer(connection);
    verify(gearmanClient).shutdown();
}
Also used : SakuliForwarderRuntimeException(org.sakuli.exceptions.SakuliForwarderRuntimeException) TestSuite(org.sakuli.datamodel.TestSuite) NagiosCheckResult(org.sakuli.services.forwarder.gearman.model.NagiosCheckResult) UnresolvedAddressException(java.nio.channels.UnresolvedAddressException) TestSuiteExampleBuilder(org.sakuli.builder.TestSuiteExampleBuilder) SakuliRuntimeException(org.sakuli.exceptions.SakuliRuntimeException) SakuliForwarderRuntimeException(org.sakuli.exceptions.SakuliForwarderRuntimeException) UnresolvedAddressException(java.nio.channels.UnresolvedAddressException) BaseTest(org.sakuli.BaseTest) Test(org.testng.annotations.Test)

Example 30 with UnresolvedAddressException

use of java.nio.channels.UnresolvedAddressException in project Mindroid.java by Himmele.

the class AbstractClient method start.

public void start(String uri, SocketAddress localAddress) throws IOException {
    LOG_TAG = "Client [" + uri + "]";
    try {
        URI url = new URI(uri);
        if (!"tcp".equals(url.getScheme())) {
            throw new IllegalArgumentException("Invalid URI scheme: " + url.getScheme());
        }
        mHost = url.getHost();
        mPort = url.getPort();
        try {
            if (localAddress != null) {
                mSocket.bind(localAddress);
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
            shutdown(e);
            throw e;
        }
        mSocket.connect(new InetSocketAddress(mHost, mPort)).whenComplete((value, exception) -> {
            if (exception != null) {
                if (DEBUG) {
                    Log.e(LOG_TAG, exception.getMessage(), exception);
                }
                shutdown(exception);
            } else {
                onConnected();
            }
        });
        mExecutorGroup.register(mSocket);
    } catch (URISyntaxException e) {
        shutdown(e);
        throw new IOException("Invalid URI: " + uri);
    } catch (UnresolvedAddressException e) {
        shutdown(e);
        throw new IOException("Address cannot be resolved", e);
    } catch (RuntimeException e) {
        shutdown(e);
        throw e;
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) UnresolvedAddressException(java.nio.channels.UnresolvedAddressException) URI(java.net.URI)

Aggregations

UnresolvedAddressException (java.nio.channels.UnresolvedAddressException)30 IOException (java.io.IOException)15 InetSocketAddress (java.net.InetSocketAddress)15 SocketChannel (java.nio.channels.SocketChannel)8 ConnectException (java.net.ConnectException)5 SocketAddress (java.net.SocketAddress)4 UnsupportedAddressTypeException (java.nio.channels.UnsupportedAddressTypeException)4 Socket (java.net.Socket)3 SocketTimeoutException (java.net.SocketTimeoutException)3 ClosedChannelException (java.nio.channels.ClosedChannelException)3 SelectionKey (java.nio.channels.SelectionKey)3 ServerSocketChannel (java.nio.channels.ServerSocketChannel)3 FetchRequest (kafka.api.FetchRequest)3 FetchRequestBuilder (kafka.api.FetchRequestBuilder)3 FetchResponse (kafka.javaapi.FetchResponse)3 ByteBufferMessageSet (kafka.javaapi.message.ByteBufferMessageSet)3 Status (io.grpc.Status)2 Http2Exception (io.netty.handler.codec.http2.Http2Exception)2 ServerSocket (java.net.ServerSocket)2 AsynchronousSocketChannel (java.nio.channels.AsynchronousSocketChannel)2