org.apache.thrift.protocol.TMultiplexedProtocol Java Examples

The following examples show how to use org.apache.thrift.protocol.TMultiplexedProtocol. 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: MultiServiceClient.java    From ThriftBook with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws TException {
    TTransport trans = new TFramedTransport(new TSocket("localhost", 9090));
    TProtocol proto = new TJSONProtocol(trans);

    TMultiplexedProtocol proto_msg = new TMultiplexedProtocol(proto, "Message");
    Message.Client client_msg = new Message.Client(proto_msg);
    TMultiplexedProtocol proto_time = new TMultiplexedProtocol(proto, "ServerTime");
    ServerTime.Client client_time = new ServerTime.Client(proto_time);

    trans.open();
    String line;
    do {
        System.out.println("Message from server: " + client_msg.motd());
        System.out.println("Time at server: " + client_time.time_at_server((short)-1));
        System.out.println("Enter to continue, 'q' to quit: ");
        line = System.console().readLine();
    } while (0 != line.compareToIgnoreCase("q"));   
}
 
Example #2
Source File: Bmv2PreControllerImpl.java    From onos with Apache License 2.0 6 votes vote down vote up
private boolean doCreateClient(DeviceId deviceId, String thriftServerIp, Integer thriftServerPort) {
    SafeThriftClient.Options options = new SafeThriftClient.Options(numConnectionRetries, timeBetweenRetries);

    try {
        // Make the expensive call
        TTransport transport = new TSocket(thriftServerIp, thriftServerPort);

        TProtocol protocol = new TBinaryProtocol(transport);
        // Create a client for simple_pre service.
        SimplePreLAG.Client simplePreClient = new SimplePreLAG.Client(
                new TMultiplexedProtocol(protocol, THRIFT_SERVICE_NAME));

        SimplePreLAG.Iface safeSimplePreClient = SafeThriftClient.wrap(simplePreClient,
                                                                       SimplePreLAG.Iface.class,
                                                                       options);

        Bmv2DeviceThriftClient client = new Bmv2DeviceThriftClient(deviceId, safeSimplePreClient);
        clients.put(deviceId, Pair.of(transport, client));
        return true;

    } catch (RuntimeException e) {
        log.warn("Failed to create Thrift client for BMv2 device. deviceId={}, cause={}", deviceId, e);
        return false;
    }
}
 
Example #3
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 #4
Source File: AsyncMultiplexedProtocolFactory.java    From ikasoa with MIT License 4 votes vote down vote up
@Override
public TProtocol getProtocol(TTransport trans) {
	return Optional.ofNullable(serviceName)
			.map(n -> (TProtocol) new TMultiplexedProtocol(super.getProtocol(trans), n))
			.orElse(super.getProtocol(trans));
}
 
Example #5
Source File: AbstractThriftClientImpl.java    From ikasoa with MIT License 4 votes vote down vote up
@Override
public TProtocol getProtocol(TTransport transport, String serviceName) {
	return Optional.ofNullable(serviceName)
			.map(sName -> (TProtocol) new TMultiplexedProtocol(getProtocol(transport), sName))
			.orElseGet(() -> getProtocol(transport));
}
 
Example #6
Source File: ThriftMultiplexedBinaryProtocolFactory.java    From thrift-client-pool-java with Artistic License 2.0 4 votes vote down vote up
@Override
public TProtocol makeProtocol(TTransport transport) {
    return new TMultiplexedProtocol(new TBinaryProtocol(new TFramedTransport(transport)), serviceName);
}
 
Example #7
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 #8
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");
}
 
Example #9
Source File: ThriftClientImpl.java    From thrift-pool-client with Artistic License 2.0 3 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * <p>
 * mpiface.
 * </p>
 */
@Override
public <X extends TServiceClient> X mpiface(Class<X> ifaceClass, String serviceName,
    Function<TTransport, TProtocol> protocolProvider, int hash) {
    return iface(ifaceClass,
        protocolProvider.andThen((p) -> new TMultiplexedProtocol(p, serviceName)), hash);
}