Example usage for org.apache.thrift.transport TTransportException TTransportException

List of usage examples for org.apache.thrift.transport TTransportException TTransportException

Introduction

In this page you can find the example usage for org.apache.thrift.transport TTransportException TTransportException.

Prototype

public TTransportException(String message, Throwable cause) 

Source Link

Usage

From source file:com.baidu.oped.apm.thrift.io.ByteArrayOutputStreamTransport.java

License:Apache License

@Override
public int read(byte[] buf, int off, int len) throws TTransportException {
    throw new TTransportException(TTransportException.NOT_OPEN, "unsupported inputStream");
}

From source file:com.baidu.oped.apm.thrift.io.ByteArrayOutputStreamTransport.java

License:Apache License

@Override
public void write(byte[] buf, int off, int len) throws TTransportException {
    if (out == null) {
        throw new TTransportException(TTransportException.NOT_OPEN, "cannot write to null outputStream");
    }/* w w  w.  j a  v a2s  .com*/

    out.write(buf, off, len);
}

From source file:com.facebook.hive.metastore.client.RetryingHiveMetastore.java

License:Apache License

@VisibleForTesting
@SuppressWarnings("PMD.PreserveStackTrace")
HiveMetastore connect() throws TException {
    if (closed.get()) {
        throw new TTransportException(TTransportException.NOT_OPEN, "Client is already closed");
    }//from   w  w w. j  a va 2 s  .c  o m

    HiveMetastore client = clientHolder.get();

    while (client == null) {
        try {
            final HostAndPort hostAndPort = getNextHostAndPort();
            final NiftyClientConnector<? extends NiftyClientChannel> clientConnector = config.isFramed()
                    ? new FramedClientConnector(hostAndPort)
                    : new UnframedClientConnector(hostAndPort);

            client = thriftClient.open(clientConnector).get();
            if (!clientHolder.compareAndSet(null, client)) {
                client.close();
                client = clientHolder.get();
            }
        } catch (final ExecutionException e) {
            final Throwable t = e.getCause();
            Throwables.propagateIfInstanceOf(t, TTransportException.class);
            throw Throwables.propagate(t);
        } catch (final InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new TTransportException(TTransportException.NOT_OPEN, "Interrupted while connecting");
        }
    }

    return client;
}

From source file:com.facebook.hive.metastore.client.RetryingHiveMetastore.java

License:Apache License

@SuppressWarnings("PMD.PreserveStackTrace")
private <T> T withRetries(final String apiName, final CallableWithMetastore<T> callable) throws TException {
    checkNotNull(apiName, "apiName is null");
    checkNotNull(callable, "callable is null");

    final long startTime = System.nanoTime();

    int attempt = 0;

    try {/*from w w w.  ja  v  a  2s. c  o m*/
        for (;;) {
            attempt++;
            try {
                final HiveMetastore client = connect();
                log.debug("Executing %s (connected to %s, attempt %s)", apiName, currentHostAndPort.get(),
                        attempt);
                return callable.call(client);
            } catch (final Throwable t) {
                TTransportException te = null;

                if (t instanceof TTransportException) {
                    te = (TTransportException) t;
                } else if (t.getCause() instanceof TTransportException) {
                    te = (TTransportException) t.getCause();
                    log.debug("Found a TTransportException (%s) wrapped in a %s", te.getMessage(),
                            t.getClass().getSimpleName());
                }

                if (te != null) {
                    final Duration now = Duration.nanosSince(startTime);
                    if (attempt > config.getMaxRetries() || now.compareTo(config.getRetryTimeout()) >= 0) {
                        log.warn(
                                "Failed executing %s (last host %s, attempt %s, elapsed time %s), Exception: %s (%s)",
                                apiName, currentHostAndPort.get(), attempt, now.toString(TimeUnit.MILLISECONDS),
                                te.getClass().getSimpleName(), te.getMessage());

                        Throwables.propagateIfInstanceOf(t, TException.class);
                        throw Throwables.propagate(t);
                    }
                    log.debug(
                            "Retry executing %s (last host: %s, attempt %s, elapsed time %s), Exception: %s (%s)",
                            apiName, currentHostAndPort.get(), attempt, now.toString(TimeUnit.MILLISECONDS),
                            te.getClass().getSimpleName(), te.getMessage());

                    internalClose();

                    TimeUnit.MILLISECONDS.sleep(config.getRetrySleep().toMillis());
                } else {
                    log.warn("Failed executing %s, Exception: %s (%s)", apiName, t.getClass().getSimpleName(),
                            t.getMessage());
                    Throwables.propagateIfInstanceOf(t, TException.class);
                    throw Throwables.propagate(t);
                }
            }
        }
    } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
        throw new TTransportException(TTransportException.NOT_OPEN, "Interrupted while connecting");
    }
}

From source file:com.facebook.nifty.client.AbstractClientChannel.java

License:Apache License

private void messageSent(ChannelFuture future, Request request, boolean oneway) {
    try {/* w w  w .  j  a v  a2  s . co  m*/
        if (future.isSuccess()) {
            cancelRequestTimeouts(request);
            fireRequestSentCallback(request.getListener());
            if (oneway) {
                retireRequest(request);
            } else {
                queueReceiveAndReadTimeout(request);
            }
        } else {
            TTransportException transportException = new TTransportException("Sending request failed",
                    future.getCause());
            onError(transportException);
        }
    } catch (Throwable t) {
        onError(t);
    }
}

From source file:com.facebook.nifty.client.NiftyClient.java

License:Apache License

public TNiftyClientTransport connectSync(InetSocketAddress addr, @Nullable Duration connectTimeout,
        @Nullable Duration receiveTimeout, @Nullable Duration sendTimeout, int maxFrameSize,
        @Nullable InetSocketAddress socksProxyAddress) throws TTransportException, InterruptedException {
    // TODO: implement send timeout for sync client
    ClientBootstrap bootstrap = createClientBootstrap(socksProxyAddress);
    bootstrap.setOptions(nettyClientConfig.getBootstrapOptions());

    if (connectTimeout != null) {
        bootstrap.setOption("connectTimeoutMillis", connectTimeout.toMillis());
    }//from  w  ww.  j av a  2 s.  com

    bootstrap.setPipelineFactory(new NiftyClientChannelPipelineFactory(maxFrameSize));
    ChannelFuture f = bootstrap.connect(addr);
    f.await();
    Channel channel = f.getChannel();
    if (f.getCause() != null) {
        String message = String.format("unable to connect to %s:%d %s", addr.getHostName(), addr.getPort(),
                socksProxyAddress == null ? "" : "via socks proxy at " + socksProxyAddress);
        throw new TTransportException(message, f.getCause());
    }

    if (f.isSuccess() && channel != null) {
        if (channel.isOpen()) {
            allChannels.add(channel);
        }

        TNiftyClientTransport transport = new TNiftyClientTransport(channel, receiveTimeout);
        channel.getPipeline().addLast("thrift", transport);
        return transport;
    }

    throw new TTransportException(String.format("unknown error connecting to %s:%d %s", addr.getHostName(),
            addr.getPort(), socksProxyAddress == null ? "" : "via socks proxy at " + socksProxyAddress));
}

From source file:com.linecorp.armeria.server.thrift.THttp2Client.java

License:Apache License

THttp2Client(String uriStr) throws TTransportException {
    uri = URI.create(uriStr);/* w ww .  j a  v  a  2  s.  c om*/

    int port;
    switch (uri.getScheme()) {
    case "http":
        port = uri.getPort();
        if (port < 0) {
            port = 80;
        }
        sslCtx = null;
        break;
    case "https":
        port = uri.getPort();
        if (port < 0) {
            port = 443;
        }

        try {
            sslCtx = SslContextBuilder.forClient()
                    .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                    .trustManager(InsecureTrustManagerFactory.INSTANCE)
                    .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                            // NO_ADVERTISE is currently the only mode supported by both OpenSsl and
                            // JDK providers.
                            SelectorFailureBehavior.NO_ADVERTISE,
                            // ACCEPT is currently the only mode supported by both OpenSsl and
                            // JDK providers.
                            SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2))
                    .build();
        } catch (SSLException e) {
            throw new TTransportException(TTransportException.UNKNOWN, e);
        }
        break;
    default:
        throw new IllegalArgumentException("unknown scheme: " + uri.getScheme());
    }

    String host = uri.getHost();
    if (host == null) {
        throw new IllegalArgumentException("host not specified: " + uriStr);
    }

    String path = uri.getPath();
    if (path == null) {
        throw new IllegalArgumentException("path not specified: " + uriStr);
    }

    this.host = host;
    this.port = port;
    this.path = path;
}

From source file:com.linecorp.armeria.server.thrift.THttp2Client.java

License:Apache License

@Override
public void flush() throws TTransportException {
    THttp2ClientInitializer initHandler = new THttp2ClientInitializer();

    Bootstrap b = new Bootstrap();
    b.group(group);/* w  w w  .j  av a2s .c  o  m*/
    b.channel(NioSocketChannel.class);
    b.handler(initHandler);

    Channel ch = null;
    try {
        ch = b.connect(host, port).syncUninterruptibly().channel();
        THttp2ClientHandler handler = initHandler.clientHandler;

        // Wait until HTTP/2 upgrade is finished.
        assertTrue(handler.settingsPromise.await(5, TimeUnit.SECONDS));
        handler.settingsPromise.get();

        // Send a Thrift request.
        FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, path,
                Unpooled.wrappedBuffer(out.getArray(), 0, out.length()));
        request.headers().add(HttpHeaderNames.HOST, host);
        request.headers().set(ExtensionHeaderNames.SCHEME.text(), uri.getScheme());
        ch.writeAndFlush(request).sync();

        // Wait until the Thrift response is received.
        assertTrue(handler.responsePromise.await(5, TimeUnit.SECONDS));
        ByteBuf response = handler.responsePromise.get();

        // Pass the received Thrift response to the Thrift client.
        final byte[] array = new byte[response.readableBytes()];
        response.readBytes(array);
        in = new TMemoryInputTransport(array);
        response.release();
    } catch (Exception e) {
        throw new TTransportException(TTransportException.UNKNOWN, e);
    } finally {
        if (ch != null) {
            ch.close();
        }
    }
}

From source file:com.netflix.suro.input.thrift.CustomServerSocket.java

License:Apache License

protected TNonblockingSocket acceptImpl() throws TTransportException {
    if (serverSocket_ == null) {
        throw new TTransportException(TTransportException.NOT_OPEN, "No underlying server socket.");
    }//from   w w  w  . j  a  v  a2  s . c  om
    try {
        SocketChannel socketChannel = serverSocketChannel.accept();
        if (socketChannel == null) {
            return null;
        }

        TNonblockingSocket tsocket = new TNonblockingSocket(socketChannel);
        tsocket.setTimeout(0); // disabling client timeout
        tsocket.getSocketChannel().socket().setKeepAlive(true);
        tsocket.getSocketChannel().socket().setSendBufferSize(config.getSocketSendBufferBytes());
        tsocket.getSocketChannel().socket().setReceiveBufferSize(config.getSocketRecvBufferBytes());
        return tsocket;
    } catch (IOException iox) {
        throw new TTransportException(iox);
    }
}

From source file:com.pinterest.quasar.thrift.TFiberServerSocket.java

License:Apache License

/**
 * Binds the server socket to the requested port. This must be called before the server socket
 * can be used to accept incoming requests.
 *
 * The server socket enables SO_REUSEADDR to make it faster to restart a server on the same port.
 *
 * @throws TTransportException if the bind operation fails.
 *//*from ww  w.  j av a2  s .  co  m*/
@Override
@Suspendable
public void listen() throws TTransportException {
    try {
        serverSocketChannel = FiberServerSocketChannel.open()
                .setOption(StandardSocketOptions.SO_REUSEADDR, true).bind(addr);
    } catch (SuspendExecution se) {
        throw new AssertionError(se);
    } catch (IOException ioex) {
        throw new TTransportException(TTransportException.UNKNOWN, ioex);
    }
}