Java Code Examples for org.apache.thrift.transport.TTransportException

The following examples show how to use org.apache.thrift.transport.TTransportException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: presto   Source File: Transport.java    License: Apache License 2.0 6 votes vote down vote up
public static TTransport create(
        HostAndPort address,
        Optional<SSLContext> sslContext,
        Optional<HostAndPort> socksProxy,
        int timeoutMillis,
        HiveMetastoreAuthentication authentication,
        Optional<String> delegationToken)
        throws TTransportException
{
    requireNonNull(address, "address is null");
    try {
        TTransport rawTransport = createRaw(address, sslContext, socksProxy, timeoutMillis);
        TTransport authenticatedTransport = authentication.authenticate(rawTransport, address.getHost(), delegationToken);
        if (!authenticatedTransport.isOpen()) {
            authenticatedTransport.open();
        }
        return new TTransportWrapper(authenticatedTransport, address);
    }
    catch (TTransportException e) {
        throw rewriteException(e, address);
    }
}
 
Example 2
Source Project: RDFS   Source File: CoronaTaskTracker.java    License: Apache License 2.0 6 votes vote down vote up
private synchronized void initializeClusterManagerClient()
    throws IOException {
  // Connect to cluster manager thrift service
  String target = CoronaConf.getClusterManagerAddress(fConf);
  LOG.info("Connecting to Cluster Manager at " + target);
  InetSocketAddress address = NetUtils.createSocketAddr(target);
  transport = new TFramedTransport(
    new TSocket(address.getHostName(), address.getPort()));
  TProtocol protocol = new TBinaryProtocol(transport);
  client = new ClusterManagerService.Client(protocol);
  try {
    transport.open();
  } catch (TTransportException e) {
    throw new IOException(e);
  }
}
 
Example 3
Source Project: ikasoa   Source File: AbstractThriftServerImpl.java    License: MIT License 6 votes vote down vote up
/**
 * 启动Thrift服务
 * 
 * @exception IkasoaException
 *                异常
 */
public void start() throws IkasoaException {
	if (ObjectUtil.isNull(server)) {
		log.debug("Server configuration : {}", configuration);
		// 不允许使用1024以内的端口.
		if (!ServerUtil.isSocketPort(serverPort))
			throw new IkasoaException(String.format(
					"Server initialize failed ! Port range must is 1025 ~ 65535 . Your port is : %d .",
					serverPort));
		try {
			initServer(getTransport());
		} catch (TTransportException e) {
			throw new IkasoaException("Server initialize failed !", e);
		}
	}
	// 如果服务没有启动,则自动启动服务.
	if (ObjectUtil.isNotNull(server)) {
		if (server.isServing()) {
			log.info("Server already run .");
			return;
		}
		server.serve();
		log.info("Startup server ... (name : {} , port : {})", getServerName(), getServerPort());
	} else
		log.warn("Startup server failed !");
}
 
Example 4
Source Project: hbase   Source File: ThriftConnection.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Pair<THBaseService.Client, TTransport> getClient() throws IOException {
  Preconditions.checkArgument(connection.getHost().startsWith("http"),
      "http client host must start with http or https");
  String url = connection.getHost() + ":" + connection.getPort();
  try {
    THttpClient httpClient = new THttpClient(url, connection.getHttpClient());
    for (Map.Entry<String, String> header : customHeader.entrySet()) {
      httpClient.setCustomHeader(header.getKey(), header.getValue());
    }
    httpClient.open();
    TProtocol prot = new TBinaryProtocol(httpClient);
    THBaseService.Client client = new THBaseService.Client(prot);
    return new Pair<>(client, httpClient);
  } catch (TTransportException e) {
    throw new IOException(e);
  }

}
 
Example 5
Source Project: DDMQ   Source File: CarreraConsumerExample.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws TTransportException, InterruptedException {
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            LogManager.shutdown(); //shutdown log4j2.
        }
    }));

    LOGGER.info("start simpleExample...");
    simpleExample(60 * 1000);

    LOGGER.info("start exampleWithExtraThreadsForSomeTopic...");
    exampleWithExtraThreadsForSomeTopic(60 * 1000);

    exampleConsumeStatsFetch();
}
 
Example 6
Source Project: gemfirexd-oss   Source File: GfxdTSSLServerSocketFactory.java    License: Apache License 2.0 6 votes vote down vote up
private static GfxdTSSLServerSocket createServer(
    SSLServerSocketFactory factory, InetSocketAddress bindAddress,
    SocketParameters params) throws TTransportException {
  try {
    SSLServerSocket serverSocket = (SSLServerSocket)factory
        .createServerSocket(bindAddress.getPort(), 100,
            bindAddress.getAddress());
    if (params != null) {
      if (params.getSSLEnabledProtocols() != null) {
        serverSocket.setEnabledProtocols(params.getSSLEnabledProtocols());
      }
      if (params.getSSLCipherSuites() != null) {
        serverSocket.setEnabledCipherSuites(params.getSSLCipherSuites());
      }
      serverSocket.setNeedClientAuth(params.getSSLClientAuth());
    }
    return new GfxdTSSLServerSocket(serverSocket, bindAddress, params);
  } catch (Exception e) {
    throw new TTransportException(TTransportException.NOT_OPEN,
        "Could not bind to host:port " + bindAddress.toString(), e);
  }
}
 
Example 7
Source Project: garmadon   Source File: HiveClient.java    License: Apache License 2.0 6 votes vote down vote up
protected void execute(String query) throws SQLException {
    LOGGER.debug("Execute hql: {}", query);
    int maxAttempts = 5;
    for (int retry = 1; retry <= maxAttempts; ++retry) {
        try {
            stmt.execute(query);
        } catch (SQLException sqlException) {
            if (ExceptionUtils.indexOfThrowable(sqlException, TTransportException.class) != -1) {
                String exMsg = String.format("Retry connecting to hive (%d/%d)", retry, maxAttempts);
                if (retry <= maxAttempts) {
                    LOGGER.warn(exMsg, sqlException);
                    try {
                        Thread.sleep(1000 * retry);
                        connect();
                    } catch (Exception ignored) {
                    }
                } else {
                    LOGGER.error(exMsg, sqlException);
                    throw sqlException;
                }
            } else {
                throw sqlException;
            }
        }
    }
}
 
Example 8
Source Project: spring-thrift-starter   Source File: TLoadBalancerClient.java    License: MIT License 6 votes vote down vote up
public void flush() throws TTransportException {
    byte[] data = this.requestBuffer_.toByteArray();
    this.requestBuffer_.reset();
    int retryCount = 0;
    while (true) {
        try {
            retryCount++;
            doFlush(data);
            return;
        } catch (IOException ioe) {
            if (retryCount >= maxRetries_) {
                throw new TTransportException(ioe);
            }
        } catch (Exception e) {
            if (retryCount >= maxRetries_) {
                throw e;
            }
        }
    }
}
 
Example 9
Source Project: gemfirexd-oss   Source File: GfxdTSSLSocket.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sets the socket properties like timeout, keepalive, buffer sizes.
 * 
 * @param timeout
 *          Milliseconds timeout
 * @param params
 *          Socket parameters including buffer sizes and keep-alive settings
 * @param props
 *          the system properties instance to use and initialize global socket
 *          options like keepalive and buffer sizes that are not set in params
 */
protected void setProperties(Socket socket, int timeout,
    SocketParameters params, SystemProperties props)
    throws TTransportException {
  this.inputBufferSize = params.getInputBufferSize(props
      .getSocketInputBufferSize());
  this.outputBufferSize = params.getOutputBufferSize(props
      .getSocketOutputBufferSize());
  try {
    socket.setSoLinger(false, 0);
    socket.setTcpNoDelay(true);
    this.timeout = GfxdTSocket.setTimeout(socket, timeout, params, props);
  } catch (SocketException se) {
    LOGGER.warn("Could not set socket timeout.", se);
    throw new TTransportException(TTransportException.NOT_OPEN,
        "Could not set socket timeout.", se);
  }
}
 
Example 10
Source Project: warp10-platform   Source File: TFramedTransport.java    License: Apache License 2.0 6 votes vote down vote up
private void readFrame() throws TTransportException {
  transport_.readAll(i32buf, 0, 4);
  int size = decodeFrameSize(i32buf);

  if (size < 0) {
    throw new TTransportException("Read a negative frame size (" + size + ")!");
  }

  if (size > maxLength_) {
    throw new TTransportException("Frame size (" + size + ") larger than max length (" + maxLength_ + ")!");
  }

  byte[] buff = new byte[size];
  transport_.readAll(buff, 0, size);
  readBuffer_.reset(buff);
}
 
Example 11
Source Project: drift   Source File: LegacyApacheThriftTesterUtil.java    License: Apache License 2.0 6 votes vote down vote up
private static TSocket createClientSocket(boolean secure, HostAndPort address)
        throws TTransportException
{
    if (!secure) {
        return new TSocket(address.getHost(), address.getPort());
    }

    try {
        SSLContext serverSslContext = ClientTestUtils.getClientSslContext();
        SSLSocket clientSocket = (SSLSocket) serverSslContext.getSocketFactory().createSocket(address.getHost(), address.getPort());
        //            clientSocket.setSoTimeout(timeout);
        return new TSocket(clientSocket);
    }
    catch (Exception e) {
        throw new TTransportException("Error initializing secure socket", e);
    }
}
 
Example 12
Source Project: waggle-dance   Source File: MetaStoreProxyServer.java    License: Apache License 2.0 6 votes vote down vote up
private TServerSocket createServerSocket(boolean useSSL, int port) throws IOException, TTransportException {
  TServerSocket serverSocket = null;
  // enable SSL support for HMS
  List<String> sslVersionBlacklist = new ArrayList<>(Arrays.asList(hiveConf.getVar(ConfVars.HIVE_SSL_PROTOCOL_BLACKLIST).split(",")));
  if (!useSSL) {
    serverSocket = HiveAuthUtils.getServerSocket(null, port);
  } else {
    String keyStorePath = hiveConf.getVar(ConfVars.HIVE_METASTORE_SSL_KEYSTORE_PATH).trim();
    if (keyStorePath.isEmpty()) {
      throw new IllegalArgumentException(
          ConfVars.HIVE_METASTORE_SSL_KEYSTORE_PASSWORD.varname + " Not configured for SSL connection");
    }
    String keyStorePassword = ShimLoader
        .getHadoopShims()
        .getPassword(hiveConf, HiveConf.ConfVars.HIVE_METASTORE_SSL_KEYSTORE_PASSWORD.varname);
    serverSocket = HiveAuthUtils.getServerSSLSocket(null, port, keyStorePath, keyStorePassword, sslVersionBlacklist);
  }
  return serverSocket;
}
 
Example 13
Source Project: plow   Source File: ThriftServer.java    License: Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void start() {
    logger.info("Starting thift server " + name + " on port " + port);

    try {
        transport = new TNonblockingServerSocket(port);
        server = new TThreadedSelectorServer(
                new TThreadedSelectorServer.Args(transport)
            .processor(processor)
            .workerThreads(threads)
            .selectorThreads((threads / 16) + 1)
            .protocolFactory(protocolFactory)
            .transportFactory(new TFramedTransport.Factory()));
        thread.start();

    } catch (TTransportException e) {
        throw new RuntimeException("Unable to start thrift server " + e, e);
    }
}
 
Example 14
Source Project: rubix   Source File: BookKeeperFactory.java    License: Apache License 2.0 6 votes vote down vote up
public RetryingPooledBookkeeperClient createBookKeeperClient(String host, Configuration conf) throws TTransportException
{
  if (!initFlag.get()) {
    synchronized (initFlag) {
      if (!initFlag.get()) {
        pool = createSocketObjectPool(conf, host, CacheConfig.getBookKeeperServerPort(conf));
        initFlag.set(true);
      }
    }
  }

  if (bookKeeper != null) {
    return new LocalBookKeeperClient(bookKeeper);
  }
  else {
    Poolable<TTransport> obj;
    obj = pool.borrowObject(host, conf);
    RetryingPooledBookkeeperClient retryingBookkeeperClient = new RetryingPooledBookkeeperClient(obj, host, conf);
    return retryingBookkeeperClient;
  }
}
 
Example 15
Source Project: ThriftBook   Source File: FileTrans.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) 
        throws IOException, TTransportException, ClassNotFoundException {
    Trade trade = new Trade();
    trade.symbol = "F";
    trade.price = 13.10;
    trade.size = 2500;

    TSimpleFileTransport trans_out = new TSimpleFileTransport("data",false,true);	
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(trade);
    trans_out.write(baos.toByteArray());				
    trans_out.close();				

    TSimpleFileTransport trans_in = new TSimpleFileTransport("data",true,false);
    byte[] buf = new byte[128];
    int iBytesRead = trans_in.read(buf, 0, buf.length);		
    ByteArrayInputStream bais = new ByteArrayInputStream(buf);
    ObjectInputStream ois = new ObjectInputStream(bais);
    trade = (Trade) ois.readObject();

    System.out.println("Trade(" + iBytesRead + "): " + trade.symbol
            + " " + trade.size + " @ " + trade.price);
}
 
Example 16
Source Project: suro   Source File: CustomServerSocket.java    License: Apache License 2.0 6 votes vote down vote up
public CustomServerSocket(ServerConfig config) throws TTransportException {
    this.config = config;
    InetSocketAddress bindAddr = new InetSocketAddress(config.getPort());
    try {
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);

        // Make server socket
        serverSocket_ = serverSocketChannel.socket();
        // Prevent 2MSL delay problem on server restarts
        serverSocket_.setReuseAddress(true);
        // Bind to listening port
        serverSocket_.bind(new InetSocketAddress(config.getPort()));
    } catch (IOException ioe) {
        serverSocket_ = null;
        throw new TTransportException("Could not create ServerSocket on address " + bindAddr.toString() + ".");
    }
}
 
Example 17
Source Project: stratio-cassandra   Source File: TCustomSocket.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Connects the socket, creating a new socket object if necessary.
 */
public void open() throws TTransportException {
  if (isOpen()) {
    throw new TTransportException(TTransportException.ALREADY_OPEN, "Socket already connected.");
  }

  if (host.length() == 0) {
    throw new TTransportException(TTransportException.NOT_OPEN, "Cannot open null host.");
  }
  if (port <= 0) {
    throw new TTransportException(TTransportException.NOT_OPEN, "Cannot open without port.");
  }

  if (socket == null) {
    initSocket();
  }

  try {
    socket.connect(new InetSocketAddress(host, port), timeout);
    inputStream_ = new BufferedInputStream(socket.getInputStream(), 1024);
    outputStream_ = new BufferedOutputStream(socket.getOutputStream(), 1024);
  } catch (IOException iox) {
    close();
    throw new TTransportException(TTransportException.NOT_OPEN, iox);
  }
}
 
Example 18
Source Project: das   Source File: ServerSelector.java    License: Apache License 2.0 5 votes vote down vote up
public void stickServerMode() {
    DasServerInstanceWithStatus chosen = rule.chooseServer();
    if (chosen == null) {
        throw new RuntimeException("No available server from: " + serverInstances);
    } else {
           try{
                currentClient.set(getClientObject(chosen.getAddress(), chosen.getPort()));
            } catch (TTransportException e) {
               throw new RuntimeException(e);
            }
        }
}
 
Example 19
Source Project: das   Source File: ServerSelector.java    License: Apache License 2.0 5 votes vote down vote up
static ClientObject getClientObject(String host, int port) throws TTransportException {
    TSocket transport = new TSocket(host, port);
    TFramedTransport ft = new TFramedTransport(transport);
    TBinaryProtocol protocol = new TBinaryProtocol(ft);
    transport.open();
    return new ClientObject(new DasService.Client(protocol), transport);
}
 
Example 20
Source Project: attic-aurora   Source File: HttpSecurityIT.java    License: Apache License 2.0 5 votes vote down vote up
private AuroraAdmin.Client getAuthenticatedClient(Credentials credentials)
    throws TTransportException {

  DefaultHttpClient defaultHttpClient = new DefaultHttpClient();

  CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(AuthScope.ANY, credentials);
  defaultHttpClient.setCredentialsProvider(credentialsProvider);

  return getClient(defaultHttpClient);
}
 
Example 21
Source Project: stratio-cassandra   Source File: TFramedTransportFactory.java    License: Apache License 2.0 5 votes vote down vote up
public TTransport openTransport(String host, int port) throws TTransportException
{
    TSocket socket = new TSocket(host, port);
    TTransport transport = new TFramedTransport(socket, thriftFramedTransportSizeMb * 1024 * 1024);
    transport.open();
    return transport;
}
 
Example 22
Source Project: presto   Source File: Transport.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void open()
        throws TTransportException
{
    try {
        transport.open();
    }
    catch (TTransportException e) {
        throw rewriteException(e, address);
    }
}
 
Example 23
Source Project: presto   Source File: Transport.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int read(byte[] bytes, int off, int len)
        throws TTransportException
{
    try {
        return transport.read(bytes, off, len);
    }
    catch (TTransportException e) {
        throw rewriteException(e, address);
    }
}
 
Example 24
Source Project: presto   Source File: Transport.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void flush()
        throws TTransportException
{
    try {
        transport.flush();
    }
    catch (TTransportException e) {
        throw rewriteException(e, address);
    }
}
 
Example 25
Source Project: hudi   Source File: HiveTestService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected TSocket acceptImpl() throws TTransportException {
  TSocket ts = super.acceptImpl();
  try {
    ts.getSocket().setKeepAlive(true);
  } catch (SocketException e) {
    throw new TTransportException(e);
  }
  return ts;
}
 
Example 26
Source Project: presto   Source File: MockThriftMetastoreClientFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ThriftMetastoreClient create(HostAndPort address, Optional<String> delegationToken)
        throws TTransportException
{
    checkArgument(delegationToken.isEmpty(), "delegation token is not supported");
    Optional<ThriftMetastoreClient> client = clients.getOrDefault(address, Optional.empty());
    if (client.isEmpty()) {
        throw new TTransportException(TTransportException.TIMED_OUT);
    }
    return client.get();
}
 
Example 27
Source Project: ThriftBook   Source File: TradeReader.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] argv)
    throws java.io.IOException,
           java.lang.InterruptedException,
           java.util.concurrent.TimeoutException,
           TException,
           TTransportException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(QUEUE_NAME, true, consumer);

    System.out.println("Waiting for trade reports...");
    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        byte[] data = delivery.getBody();
        TMemoryBuffer trans = new TMemoryBuffer(data.length);
        trans.write(data, 0, data.length);
        TCompactProtocol proto = new TCompactProtocol(trans);
        TradeReport tr = new TradeReport();
        tr.read(proto);
        System.out.println("[" + tr.seq_num + "] " + tr.symbol + 
                           " @ " + tr.price + " x " + tr.size);
    }
}
 
Example 28
Source Project: incubator-retired-htrace   Source File: ScribeTransport.java    License: Apache License 2.0 5 votes vote down vote up
private Scribe.Iface newScribe(String collectorHostname,
                               int collectorPort)
    throws IOException {

  TTransport transport = new TFramedTransport(
      new TSocket(collectorHostname, collectorPort));
  try {
    transport.open();
  } catch (TTransportException e) {
    throw new IOException(e);
  }
  TBinaryProtocol.Factory factory = new TBinaryProtocol.Factory();
  TProtocol protocol = factory.getProtocol(transport);
  return new Scribe.Client(protocol);
}
 
Example 29
Source Project: ThriftBook   Source File: TransExcep.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
     try {
         TTransport trans = new TSimpleFileTransport("data", false, true);
         Trade trade = new Trade();
         trade.symbol = "F";
         trade.price = 13.10;
         trade.size = 2500;
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(baos);
         oos.writeObject(trade);
         trans.write(baos.toByteArray());
trans.close();

         trans = new TSimpleFileTransport("data",
                                      ((args.length==0) ? true : false), 
                                      true);			
         byte[] buf = new byte[128];
         int iBytesRead = trans.read(buf, 0, buf.length);
         ByteArrayInputStream bais = new ByteArrayInputStream(buf);
         ObjectInputStream ois = new ObjectInputStream(bais);
         trade = (Trade) ois.readObject();
         System.out.println("Trade(" + iBytesRead + "): " + trade.symbol + " " + 
                            trade.size + " @ " + trade.price);
     } catch (TTransportException tte) {				
         System.out.println("TTransportException(" + tte.getType() + 
                            "): " + tte);
     } catch (TException te) {						
         System.out.println("TException: " + te);
     } catch (Exception e) {						
         System.out.println("Exception: " + e);
     } catch (Throwable t) {						
         System.out.println("Throwable: " + t);			
     }
 }
 
Example 30
Source Project: Doradus   Source File: DBConn.java    License: Apache License 2.0 5 votes vote down vote up
private TSocket createTLSSocket(String host) throws TTransportException {
    TSSLTransportParameters sslParams = new TSSLTransportParameters("SSL", m_dbtls_cipher_suites);
    if (!Utils.isEmpty(m_keystore)) {
        sslParams.setKeyStore(m_keystore, m_keystorepassword);
    }
    if (!Utils.isEmpty(m_truststore)) {
        sslParams.setTrustStore(m_truststore, m_truststorepassword);
    }
    return TSSLTransportFactory.getClientSocket(host, m_dbport, m_db_timeout_millis, sslParams);
}