org.apache.thrift.transport.TSocket Java Examples

The following examples show how to use org.apache.thrift.transport.TSocket. 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: CoronaAdmin.java    From RDFS with Apache License 2.0 6 votes vote down vote up
/**
 * Persists the state of the ClusterManager
 * @return 0 if successful.
 * @throws IOException
 */
private int persistState() throws IOException {
  // Get the current configuration
  CoronaConf conf = new CoronaConf(getConf());

  InetSocketAddress address = NetUtils.createSocketAddr(conf
    .getClusterManagerAddress());
  TFramedTransport transport = new TFramedTransport(
    new TSocket(address.getHostName(), address.getPort()));
  ClusterManagerService.Client client = new ClusterManagerService.Client(
    new TBinaryProtocol(transport));

  try {
    transport.open();
    if (!client.persistState())  {
      System.err.println("Persisting Cluster Manager state failed. ");
    }
  } catch (TException e) {
    throw new IOException(e);
  }

  return 0;
}
 
Example #2
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 #3
Source File: ThriftTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Test
public void test(final MockTracer tracer) throws Exception {
  startNewThreadPoolServer();

  final TTransport transport = new TSocket("localhost", port);
  transport.open();

  final TProtocol protocol = new TBinaryProtocol(transport);

  final CustomService.Client client = new CustomService.Client(protocol);
  assertEquals("Say Good bye World", client.say("Good bye", "World"));

  await().atMost(5, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(2));

  final List<MockSpan> mockSpans = tracer.finishedSpans();
  assertEquals(2, mockSpans.size());

  assertTrue(mockSpans.get(0).parentId() != 0 || mockSpans.get(1).parentId() != 0);
  assertNull(tracer.activeSpan());
}
 
Example #4
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 #5
Source File: ThriftITest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
  final CountDownLatch latch = TestUtil.initExpectedSpanLatch(2);
  final TServerTransport serverTransport = new TServerSocket(port);
  final TServer server = startNewThreadPoolServer(serverTransport);

  final TTransport transport = new TSocket("localhost", port);
  transport.open();

  final TProtocol protocol = new TBinaryProtocol(transport);

  final CustomService.Client client = new CustomService.Client(protocol);
  final String res = client.say("one", "two");
  if (!"Say one two".equals(res))
    throw new AssertionError("ERROR: wrong result");

  TestUtil.checkSpan(latch, new ComponentSpanCount("java-thrift", 2, true));

  server.stop();
  transport.close();
}
 
Example #6
Source File: AbstractTransportPool.java    From jigsaw-payment with Apache License 2.0 6 votes vote down vote up
/**
 * 根据rc的设置来确定创建什么类型的transport;
 *
 * @param instance
 * @return
 */
protected TTransport createNativeTransport(
        ServiceInstance<RpcPayload> instance) {
    TSocket socket = new TSocket(instance.getAddress(), instance.getPort());
    socket.setTimeout(socketTimeout);

    RpcPayload server = instance.getPayload();
    if ((server == null) || (server.getTransport() == null)
            || (server.getTransport().equals("socket"))) {
        return socket;
    } else if ("framed-transport".equals(server.getTransport())) {
        return new TFramedTransport(socket);
    }

    // for default, use TSocket;
    return socket;
}
 
Example #7
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 #8
Source File: ClusterManagerAvailabilityChecker.java    From RDFS with Apache License 2.0 6 votes vote down vote up
/**
 * Used for getting a client to the CoronaProxyJobTracker
 * @param conf
 * @return Returns a client to the CPJT
 * @throws IOException
 */
public static CoronaProxyJobTrackerService.Client
  getPJTClient(CoronaConf conf) throws IOException {
  InetSocketAddress address =
    NetUtils.createSocketAddr(conf.getProxyJobTrackerThriftAddress());
  TFramedTransport transport = new TFramedTransport(
    new TSocket(address.getHostName(), address.getPort()));
  CoronaProxyJobTrackerService.Client client =
    new CoronaProxyJobTrackerService.Client(new TBinaryProtocol(transport));
  try {
    transport.open();
  } catch (TException e) {
    LOG.info("Transport Exception: ", e);
  }
  return client;
}
 
Example #9
Source File: SaslTransportPlugin.java    From jstorm with Apache License 2.0 6 votes vote down vote up
public boolean process(final TProtocol inProt, final TProtocol outProt) throws TException {
    // populating request context
    ReqContext req_context = ReqContext.context();

    TTransport trans = inProt.getTransport();
    // Sasl transport
    TSaslServerTransport saslTrans = (TSaslServerTransport) trans;
    // remote address
    TSocket tsocket = (TSocket) saslTrans.getUnderlyingTransport();
    Socket socket = tsocket.getSocket();
    req_context.setRemoteAddress(socket.getInetAddress());

    // remote subject
    SaslServer saslServer = saslTrans.getSaslServer();
    String authId = saslServer.getAuthorizationID();
    Subject remoteUser = new Subject();
    remoteUser.getPrincipals().add(new User(authId));
    req_context.setSubject(remoteUser);

    // invoke service handler
    return wrapped.process(inProt, outProt);
}
 
Example #10
Source File: CoronaAdmin.java    From RDFS with Apache License 2.0 6 votes vote down vote up
/**
 * Turns on the Safe Mode if safeMode is true. Turns off the Safe Mode if
 * safeMode is false.
 * @param safeMode Is true if we want the Safe Mode to be on. false
 *                 otherwise.
 * @return 0 if successful.
 * @throws IOException
 */
private int setSafeMode(boolean safeMode) throws IOException {
  // Get the current configuration
  CoronaConf conf = new CoronaConf(getConf());

  InetSocketAddress address = NetUtils.createSocketAddr(conf
    .getClusterManagerAddress());
  TFramedTransport transport = new TFramedTransport(
    new TSocket(address.getHostName(), address.getPort()));
  ClusterManagerService.Client client = new ClusterManagerService.Client(
    new TBinaryProtocol(transport));

  try {
    transport.open();
    if (client.setSafeMode(safeMode)) {
      System.out.println("The safeMode is: " +
                          (safeMode ? "ON" : "OFF"));
    } else {
      System.err.println("Could not set the safeMode flag");
    }
  } catch (TException e) {
    throw new IOException(e);
  }

  return 0;
}
 
Example #11
Source File: AppClient.java    From rpcx-benchmark with Apache License 2.0 6 votes vote down vote up
public static Greeter.Client[] createClients(String host, int n, BenchmarkMessage msg) throws TException {
    TTransport[] transport = new TTransport[n];
    Greeter.Client[] clients = new Greeter.Client[n];

    //warmup
    for (int i = 0; i < n; i++) {
        transport[i] = new TFramedTransport(new TSocket(host, 8972));
        transport[i].open();

        TProtocol protocol = new TBinaryProtocol(transport[i]);
        clients[i] =  new Greeter.Client(protocol);
        clients[i].say(msg);
    }

    return clients;
}
 
Example #12
Source File: ConnectionPool.java    From suro with Apache License 2.0 6 votes vote down vote up
public void connect() throws Exception {
    TSocket socket = new TSocket(server.getHost(), server.getPort(), config.getConnectionTimeout());
    socket.getSocket().setTcpNoDelay(true);
    socket.getSocket().setKeepAlive(true);
    socket.getSocket().setSoLinger(true, 0);
    transport = new TFramedTransport(socket);
    transport.open();

    TProtocol protocol = new TBinaryProtocol(transport);

    client = new SuroServer.Client(protocol);
    ServiceStatus status = client.getStatus();
    if (status != ServiceStatus.ALIVE) {
        transport.close();
        throw new RuntimeException(server + " IS NOT ALIVE!!!");
    }
}
 
Example #13
Source File: TSetIpAddressProcessorFactory.java    From waggle-dance with Apache License 2.0 6 votes vote down vote up
@Override
public TProcessor getProcessor(TTransport transport) {
  try {
    if (transport instanceof TSocket) {
      Socket socket = ((TSocket) transport).getSocket();
      log.debug("Received a connection from ip: {}", socket.getInetAddress().getHostAddress());
    }
    CloseableIHMSHandler baseHandler = federatedHMSHandlerFactory.create();
    IHMSHandler handler = newRetryingHMSHandler(ExceptionWrappingHMSHandler.newProxyInstance(baseHandler), hiveConf,
        false);
    transportMonitor.monitor(transport, baseHandler);
    return new TSetIpAddressProcessor<>(handler);
  } catch (MetaException | ReflectiveOperationException | RuntimeException e) {
    throw new RuntimeException("Error creating TProcessor", e);
  }
}
 
Example #14
Source File: CassandraConnection.java    From learning-hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Construct an CassandaraConnection with optional authentication.
 * 
 * @param host the host to connect to
 * @param port the port to use
 * @param username the username to authenticate with (may be null
 * for no authentication)
 * @param password the password to authenticate with (may be null
 * for no authentication)
 * @throws Exception if the connection fails
 */
public CassandraConnection(String host, int port,
    String username, String password, int timeout) throws Exception {
  TSocket socket = new TSocket(host, port);
  if (timeout > 0) {
    socket.setTimeout(timeout);
  }
  
  m_transport = new TFramedTransport(socket);
  TProtocol protocol = new TBinaryProtocol(m_transport);
  m_client = new Cassandra.Client(protocol);      
  m_transport.open();
  
  if (!Const.isEmpty(username) && !Const.isEmpty(password)) {
    Map<String, String> creds = new HashMap<String, String>();
    creds.put("username", username);
    creds.put("password", password);
    m_client.login(new AuthenticationRequest(creds));
  }
}
 
Example #15
Source File: RemoteInterpreterProcess.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
public RemoteInterpreterProcess(int connectTimeout,
                                String intpEventServerHost,
                                int intpEventServerPort) {
  this.connectTimeout = connectTimeout;
  this.intpEventServerHost = intpEventServerHost;
  this.intpEventServerPort = intpEventServerPort;
  this.remoteClient = new PooledRemoteClient<Client>(() -> {
    TSocket transport = new TSocket(getHost(), getPort());
    try {
      transport.open();
    } catch (TTransportException e) {
      throw new IOException(e);
    }
    TProtocol protocol = new  TBinaryProtocol(transport);
    return new Client(protocol);
  });
}
 
Example #16
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 #17
Source File: TestThriftHBaseServiceHandler.java    From hbase with Apache License 2.0 6 votes vote down vote up
/**
 * Verify that thrift2 client calling thrift server can get the thrift server type correctly.
 */
@Test
public void testGetThriftServerOneType() throws Exception {

  // start a thrift server
  HBaseThriftTestingUtility THRIFT_TEST_UTIL = new HBaseThriftTestingUtility();

  LOG.info("Starting HBase Thrift server One");
  THRIFT_TEST_UTIL.startThriftServer(UTIL.getConfiguration(), ThriftServerType.ONE);
  try (TTransport transport = new TSocket(InetAddress.getLocalHost().getHostName(),
      THRIFT_TEST_UTIL.getServerPort())){
    TProtocol protocol = new TBinaryProtocol(transport);
    // This is our thrift2 client.
    THBaseService.Iface client = new THBaseService.Client(protocol);
    // open the transport
    transport.open();
    assertEquals(TThriftServerType.ONE.name(), client.getThriftServerType().name());
  } finally {
    THRIFT_TEST_UTIL.stopThriftServer();
  }
}
 
Example #18
Source File: TestThriftServer.java    From hbase with Apache License 2.0 6 votes vote down vote up
/**
 * Verify that thrift client calling thrift2 server can get the thrift2 server type correctly.
 */
@Test
public void testGetThriftServerOneType() throws Exception {
  // start a thrift2 server
  HBaseThriftTestingUtility THRIFT_TEST_UTIL = new HBaseThriftTestingUtility();

  LOG.info("Starting HBase Thrift Server Two");
  THRIFT_TEST_UTIL.startThriftServer(UTIL.getConfiguration(), ThriftServerType.TWO);
  try (TTransport transport = new TSocket(InetAddress.getLocalHost().getHostName(),
      THRIFT_TEST_UTIL.getServerPort())){
    TProtocol protocol = new TBinaryProtocol(transport);
    // This is our thrift client.
    Hbase.Client client = new Hbase.Client(protocol);
    // open the transport
    transport.open();
    assertEquals(TThriftServerType.TWO.name(), client.getThriftServerType().name());
  } finally {
    THRIFT_TEST_UTIL.stopThriftServer();
  }
}
 
Example #19
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 #20
Source File: CatalogThriftEventHandler.java    From metacat with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public ServerContext createContext(final TProtocol input, final TProtocol output) {
    final String userName = "metacat-thrift-interface";
    String clientHost = null; //requestContext.getHeaderString("X-Forwarded-For");
    final long requestThreadId = Thread.currentThread().getId();

    final TTransport transport = input.getTransport();
    if (transport instanceof TSocket) {
        final TSocket thriftSocket = (TSocket) transport;
        clientHost = thriftSocket.getSocket().getInetAddress().getHostAddress();
    }

    final CatalogServerRequestContext context = new CatalogServerRequestContext(
        userName,
        null,
        clientHost,
        null,
        "hive",
        requestThreadId
    );
    MetacatContextManager.setContext(context);
    return context;
}
 
Example #21
Source File: rpcClient.java    From leaf-snowflake with Apache License 2.0 6 votes vote down vote up
public static void startClient(String ip ,int port ,int timeout) throws Exception
{
	TTransport transport = new TSocket(ip,port,timeout);
	TProtocol protocol = new TBinaryProtocol(transport);
	leafrpc.Client client = new leafrpc.Client(protocol);
	transport.open();

	int i = 0;
	while(i < 2000000)
	{
		 client.getID("");
		 ++i;
	}

	transport.close();
}
 
Example #22
Source File: AbstractCassandraInputAdapter.java    From OpenRate with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to connect to Cassandra.
 *
 * @throws OpenRate.exception.ProcessingException
 */
public void openCassandraConnection() throws ProcessingException {
  tr = new TFramedTransport(new TSocket(cassandraIPAddr, 9160));
  TProtocol proto = new TBinaryProtocol(tr);
  client = new Cassandra.Client(proto);

  try {
    tr.open();
  } catch (TTransportException ex) {
    message = "Transport exception opening Cassandra transport";
    throw new ProcessingException(message, ex, getSymbolicName());
  }
}
 
Example #23
Source File: SimpleClient.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws TException {
    TTransport trans = new TSocket("localhost", 9090);
    TProtocol proto = new TBinaryProtocol(trans);
    SocialLookup.Iface client = new SocialLookup.Client(proto);

    trans.open();
    System.out.println("Number 1 site: " + client.GetSiteByRank(1));
    System.out.println("Twitter rank : " + client.GetSiteRankByName("Twitter"));
    trans.close();
}
 
Example #24
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 #25
Source File: PigTestBase.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
protected static Cassandra.Client getClient() throws TTransportException
{
    TTransport tr = new TFramedTransport(new TSocket("localhost", 9170));
    TProtocol proto = new TBinaryProtocol(tr);
    Cassandra.Client client = new Cassandra.Client(proto);
    tr.open();
    return client;
}
 
Example #26
Source File: TSocketConstructInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
    if (isDebug) {
        logger.afterInterceptor(target, args, result, throwable);
    }
    if (validate(target)) {
        Socket socket = ((TSocket)target).getSocket();
        ((SocketFieldAccessor)target)._$PINPOINT$_setSocket(socket);
    }
}
 
Example #27
Source File: TSocketConstructInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private boolean validate(Object target) {
    if (!(target instanceof TSocket)) {
        return false;
    }
    if (!(target instanceof SocketFieldAccessor)) {
        if (isDebug) {
            logger.debug("Invalid target object. Need field accessor({}).", SocketFieldAccessor.class.getName());
        }
        return false;
    }
    return true;
}
 
Example #28
Source File: AbstractCassandraInputAdapter.java    From OpenRate with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to connect to Cassandra.
 *
 * @throws OpenRate.exception.InitializationException
 */
public void initCassandraConnection() throws InitializationException {
  tr = new TFramedTransport(new TSocket(cassandraIPAddr, cassandraPort));
  TProtocol proto = new TBinaryProtocol(tr);
  client = new Cassandra.Client(proto);

  try {
    tr.open();
  } catch (TTransportException ex) {
    message = "Transport exception opening Cassandra transport";
    throw new InitializationException(message, ex, getSymbolicName());
  }
}
 
Example #29
Source File: ThriftUtil.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the underlying TSocket from the transport, or null of the transport type is unknown.
 */
private static TSocket getUnderlyingSocketFromTransport(TTransport transport) {
  Preconditions.checkNotNull(transport);
  if (transport instanceof TSaslServerTransport) {
    return (TSocket) ((TSaslServerTransport) transport).getUnderlyingTransport();
  } else if (transport instanceof TSaslClientTransport) {
    return (TSocket) ((TSaslClientTransport) transport).getUnderlyingTransport();
  } else if (transport instanceof TSocket) {
    return (TSocket) transport;
  }
  return null;
}
 
Example #30
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();
}