Java Code Examples for org.apache.thrift.transport.TSocket#open()

The following examples show how to use org.apache.thrift.transport.TSocket#open() . 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 File: TestApacheThriftMethodInvoker.java    From drift with Apache License 2.0 6 votes vote down vote up
private static int logThrift(HostAndPort address, List<LogEntry> messages)
{
    try {
        TSocket socket = new TSocket(address.getHost(), address.getPort());
        socket.open();
        try {
            TBinaryProtocol tp = new TBinaryProtocol(new TFramedTransport(socket));
            assertEquals(new scribe.Client(tp).Log(messages), ResultCode.OK);
        }
        finally {
            socket.close();
        }
    }
    catch (TException e) {
        throw new RuntimeException(e);
    }
    return 1;
}
 
Example 2
Source File: DefaultThriftConnection.java    From Thrift-Connection-Pool with Apache License 2.0 6 votes vote down vote up
/**
 * 创建原始连接的方法
 * 
 * @throws ThriftConnectionPoolException
 *             创建连接出现问题时抛出该异常
 */
@SuppressWarnings("unchecked")
private void createConnection() throws ThriftConnectionPoolException {
	try {
		transport = new TSocket(host, port, connectionTimeOut);
		transport.open();
		TProtocol protocol = createTProtocol(transport);
		// 反射实例化客户端对象
		Constructor<? extends TServiceClient> clientConstructor = clientClass.getConstructor(TProtocol.class);
		client = (T) clientConstructor.newInstance(protocol);
		if (logger.isDebugEnabled()) {
			logger.debug("创建新连接成功:" + host + " 端口:" + port);
		}
	} catch (Exception e) {
		throw new ThriftConnectionPoolException("无法连接服务器:" + host + " 端口:" + port);
	}
}
 
Example 3
Source File: TestRingCache.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
private void setup(String server, int port) throws Exception
{
    /* Establish a thrift connection to the cassandra instance */
    TSocket socket = new TSocket(server, port);
    System.out.println(" connected to " + server + ":" + port + ".");
    TBinaryProtocol binaryProtocol = new TBinaryProtocol(new TFramedTransport(socket));
    Cassandra.Client cassandraClient = new Cassandra.Client(binaryProtocol);
    socket.open();
    thriftClient = cassandraClient;
    String seed = DatabaseDescriptor.getSeeds().iterator().next().getHostAddress();
    conf = new Configuration();
    ConfigHelper.setOutputPartitioner(conf, DatabaseDescriptor.getPartitioner().getClass().getName());
    ConfigHelper.setOutputInitialAddress(conf, seed);
    ConfigHelper.setOutputRpcPort(conf, Integer.toString(DatabaseDescriptor.getRpcPort()));

}
 
Example 4
Source File: ServerSelector.java    From das with 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 5
Source File: SyncClient.java    From incubator-iotdb with Apache License 2.0 5 votes vote down vote up
@Override
public void establishConnection(String serverIp, int serverPort) throws SyncConnectionException {
  transport = new TSocket(serverIp, serverPort, TIMEOUT_MS);
  TProtocol protocol = new TBinaryProtocol(transport);
  serviceClient = new SyncService.Client(protocol);
  try {
    if (!transport.isOpen()) {
      transport.open();
    }
  } catch (TTransportException e) {
    logger.error("Cannot connect to the receiver.");
    throw new SyncConnectionException(e);
  }
}
 
Example 6
Source File: MulitServiceThriftConnecion.java    From Thrift-Connection-Pool with Apache License 2.0 5 votes vote down vote up
/**
 * 创建原始连接的方法
 * 
 * @throws ThriftConnectionPoolException
 *             创建连接出现问题时抛出该异常
 */
@SuppressWarnings("unchecked")
private void createConnection() throws ThriftConnectionPoolException {
	try {
		transport = new TSocket(host, port, connectionTimeOut);
		transport.open();
		TProtocol protocol = createTProtocol(transport);

		Iterator<Entry<String, Class<? extends TServiceClient>>> iterator = thriftClientClasses.entrySet()
				.iterator();
		while (iterator.hasNext()) {
			Entry<String, Class<? extends TServiceClient>> entry = iterator.next();
			String serviceName = entry.getKey();
			Class<? extends TServiceClient> clientClass = entry.getValue();
			TMultiplexedProtocol multiProtocol = new TMultiplexedProtocol(protocol, serviceName);
			// 反射实例化客户端对象
			Constructor<? extends TServiceClient> clientConstructor = clientClass.getConstructor(TProtocol.class);
			T client = (T) clientConstructor.newInstance(multiProtocol);
			clients.put(serviceName, client);
			if (logger.isDebugEnabled()) {
				logger.debug("创建新连接成功:" + host + " 端口:" + port);
			}
		}

	} catch (Exception e) {
		e.printStackTrace();
		throw new ThriftConnectionPoolException("无法连接服务器:" + host + " 端口:" + port, e);
	}
}
 
Example 7
Source File: ExcepClient.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws TException {
    TSocket trans = new TSocket("localhost", 9090);
    TBinaryProtocol proto = new TBinaryProtocol(trans);
    TradeHistory.Client client = new TradeHistory.Client(proto);

    try {
        trans.open();
        double price = client.GetLastSale(args[0]);
        System.out.println("[Client] received: " + price);
    } catch (BadFish bf) {
        System.out.println("[Client] GetLastSale() call failed for fish: " + 
                           bf.fish + ", error " + bf.error_code);
    }
    trans.close();
}
 
Example 8
Source File: HelloClient.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws TException {
    TSocket trans = new TSocket("localhost", 9090);
    TBinaryProtocol proto = new TBinaryProtocol(trans);
    HelloSvc.Client client = new HelloSvc.Client(proto);

    trans.open();
    String str = client.hello_func();
    System.out.println("[Client] received: " + str);
    trans.close();
}
 
Example 9
Source File: HelloClient.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    TSocket trans = new TSocket("localhost", 9090);
    TBinaryProtocol proto = new TBinaryProtocol(trans);
    helloSvc.Client client = new helloSvc.Client(proto);

    try {
        trans.open();
        String str = client.getMessage("world");
        System.out.println("[Client] received: " + str);
    } catch (TException ex) {
        System.out.println("Error: " + ex.toString());
    }
    trans.close();
}
 
Example 10
Source File: HelloClient.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    TSocket trans = new TSocket("localhost", 9090);
    TBinaryProtocol proto = new TBinaryProtocol(trans);
    helloSvc.Client client = new helloSvc.Client(proto);

    try {
        trans.open();
        String str = client.getMessage("world");
        System.out.println("[Client] received: " + str);
    } catch (TException ex) {
        System.out.println("Error: " + ex.toString());
    }
    trans.close();
}
 
Example 11
Source File: ThriftClient.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) 
        throws IOException, TException {
    TSocket trans = new TSocket("localhost", 9090);
    TJSONProtocol proto = new TJSONProtocol(trans);
    TradeHistory.Client client = new TradeHistory.Client(proto);

    trans.open();
    for (int i = 0; i < 1000000; i++) {
        TradeReport tr = client.get_last_sale("APPL");
    }
    trans.close();
}
 
Example 12
Source File: ThriftClient.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) 
        throws IOException, TException {
    TSocket trans = new TSocket("localhost", 9090);
    TBinaryProtocol proto = new TBinaryProtocol(trans);
    TradeHistory.Client client = new TradeHistory.Client(proto);

    trans.open();
    for (int i = 0; i < 1000000; i++) {
        TradeReport tr = client.get_last_sale("APPL");
    }
    trans.close();
}
 
Example 13
Source File: DemoClientTraditionalTEST.java    From nettythrift with Apache License 2.0 4 votes vote down vote up
TSocket socket() throws Exception {
	TSocket sc = new TSocket(HOST, PORT);
	sc.open();
	return sc;
}
 
Example 14
Source File: SentryGenericServiceClientDefaultImpl.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
public SentryGenericServiceClientDefaultImpl(Configuration conf) throws IOException {
  // copy the configuration because we may make modifications to it.
  this.conf = new Configuration(conf);
  Preconditions.checkNotNull(this.conf, "Configuration object cannot be null");
  this.serverAddress = NetUtils.createSocketAddr(Preconditions.checkNotNull(
                         conf.get(ClientConfig.SERVER_RPC_ADDRESS), "Config key "
                         + ClientConfig.SERVER_RPC_ADDRESS + " is required"), conf.getInt(
                         ClientConfig.SERVER_RPC_PORT, ClientConfig.SERVER_RPC_PORT_DEFAULT));
  this.connectionTimeout = conf.getInt(ClientConfig.SERVER_RPC_CONN_TIMEOUT,
                                       ClientConfig.SERVER_RPC_CONN_TIMEOUT_DEFAULT);
  kerberos = ServerConfig.SECURITY_MODE_KERBEROS.equalsIgnoreCase(
      conf.get(ServerConfig.SECURITY_MODE, ServerConfig.SECURITY_MODE_KERBEROS).trim());
  transport = new TSocket(serverAddress.getHostName(),
      serverAddress.getPort(), connectionTimeout);
  if (kerberos) {
    String serverPrincipal = Preconditions.checkNotNull(conf.get(ServerConfig.PRINCIPAL), ServerConfig.PRINCIPAL + " is required");
    // since the client uses hadoop-auth, we need to set kerberos in
    // hadoop-auth if we plan to use kerberos
    conf.set(HADOOP_SECURITY_AUTHENTICATION, ServerConfig.SECURITY_MODE_KERBEROS);

    // Resolve server host in the same way as we are doing on server side
    serverPrincipal = SecurityUtil.getServerPrincipal(serverPrincipal, serverAddress.getAddress());
    LOGGER.debug("Using server kerberos principal: " + serverPrincipal);

    serverPrincipalParts = SaslRpcServer.splitKerberosName(serverPrincipal);
    Preconditions.checkArgument(serverPrincipalParts.length == 3,
         "Kerberos principal should have 3 parts: " + serverPrincipal);
    boolean wrapUgi = "true".equalsIgnoreCase(conf
        .get(ServerConfig.SECURITY_USE_UGI_TRANSPORT, "true"));
    transport = new UgiSaslClientTransport(AuthMethod.KERBEROS.getMechanismName(),
        null, serverPrincipalParts[0], serverPrincipalParts[1],
        ClientConfig.SASL_PROPERTIES, null, transport, wrapUgi, conf);
  } else {
    serverPrincipalParts = null;
  }
  try {
    transport.open();
  } catch (TTransportException e) {
    throw new IOException("Transport exception while opening transport: " + e.getMessage(), e);
  }
  LOGGER.debug("Successfully opened transport: " + transport + " to " + serverAddress);
  long maxMessageSize = conf.getLong(ServiceConstants.ClientConfig.SENTRY_POLICY_CLIENT_THRIFT_MAX_MESSAGE_SIZE,
      ServiceConstants.ClientConfig.SENTRY_POLICY_CLIENT_THRIFT_MAX_MESSAGE_SIZE_DEFAULT);
  TMultiplexedProtocol protocol = new TMultiplexedProtocol(
      new TBinaryProtocol(transport, maxMessageSize, maxMessageSize, true, true),
      SentryGenericPolicyProcessor.SENTRY_GENERIC_SERVICE_NAME);
  client = new SentryGenericPolicyService.Client(protocol);
  LOGGER.debug("Successfully created client");
}
 
Example 15
Source File: SentryPolicyServiceClientDefaultImpl.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
public SentryPolicyServiceClientDefaultImpl(Configuration conf) throws IOException {
  this.conf = conf;
  Preconditions.checkNotNull(this.conf, "Configuration object cannot be null");
  this.serverAddress = NetUtils.createSocketAddr(Preconditions.checkNotNull(
                         conf.get(ClientConfig.SERVER_RPC_ADDRESS), "Config key "
                         + ClientConfig.SERVER_RPC_ADDRESS + " is required"), conf.getInt(
                         ClientConfig.SERVER_RPC_PORT, ClientConfig.SERVER_RPC_PORT_DEFAULT));
  this.connectionTimeout = conf.getInt(ClientConfig.SERVER_RPC_CONN_TIMEOUT,
                                       ClientConfig.SERVER_RPC_CONN_TIMEOUT_DEFAULT);
  kerberos = ServerConfig.SECURITY_MODE_KERBEROS.equalsIgnoreCase(
      conf.get(ServerConfig.SECURITY_MODE, ServerConfig.SECURITY_MODE_KERBEROS).trim());
  transport = new TSocket(serverAddress.getHostName(),
      serverAddress.getPort(), connectionTimeout);
  if (kerberos) {
    String serverPrincipal = Preconditions.checkNotNull(conf.get(ServerConfig.PRINCIPAL), ServerConfig.PRINCIPAL + " is required");

    // Resolve server host in the same way as we are doing on server side
    serverPrincipal = SecurityUtil.getServerPrincipal(serverPrincipal, serverAddress.getAddress());
    LOGGER.debug("Using server kerberos principal: " + serverPrincipal);

    serverPrincipalParts = SaslRpcServer.splitKerberosName(serverPrincipal);
    Preconditions.checkArgument(serverPrincipalParts.length == 3,
         "Kerberos principal should have 3 parts: " + serverPrincipal);
    boolean wrapUgi = "true".equalsIgnoreCase(conf
        .get(ServerConfig.SECURITY_USE_UGI_TRANSPORT, "true"));
    transport = new UgiSaslClientTransport(AuthMethod.KERBEROS.getMechanismName(),
        null, serverPrincipalParts[0], serverPrincipalParts[1],
        ClientConfig.SASL_PROPERTIES, null, transport, wrapUgi);
  } else {
    serverPrincipalParts = null;
  }
  try {
    transport.open();
  } catch (TTransportException e) {
    throw new IOException("Transport exception while opening transport: " + e.getMessage(), e);
  }
  LOGGER.debug("Successfully opened transport: " + transport + " to " + serverAddress);
  long maxMessageSize = conf.getLong(ServiceConstants.ClientConfig.SENTRY_POLICY_CLIENT_THRIFT_MAX_MESSAGE_SIZE,
      ServiceConstants.ClientConfig.SENTRY_POLICY_CLIENT_THRIFT_MAX_MESSAGE_SIZE_DEFAULT);
  TMultiplexedProtocol protocol = new TMultiplexedProtocol(
      new TBinaryProtocol(transport, maxMessageSize, maxMessageSize, true, true),
      SentryPolicyStoreProcessor.SENTRY_POLICY_SERVICE_NAME);
  client = new SentryPolicyService.Client(protocol);
  LOGGER.debug("Successfully created client");
}