Example usage for org.apache.thrift.transport TServerSocket getServerSocket

List of usage examples for org.apache.thrift.transport TServerSocket getServerSocket

Introduction

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

Prototype

public ServerSocket getServerSocket() 

Source Link

Usage

From source file:com.facebook.swift.service.unframed.UnframedTest.java

License:Apache License

public TestServerInfo startServer() throws Exception {
    final TestServerInfo info = new TestServerInfo();
    TServerSocket serverSocket = new TServerSocket(0);
    com.facebook.swift.service.scribe.scribe.Iface handler = new PlainScribeHandler();
    TProcessor processor = new com.facebook.swift.service.scribe.scribe.Processor<>(handler);

    TThreadPoolServer.Args args = new TThreadPoolServer.Args(serverSocket).processor(processor);
    final TServer thriftServer = info.server = new TThreadPoolServer(args);

    LOG.info("Server running on port %s", serverSocket.getServerSocket().getLocalPort());

    new Thread() {
        @Override//w  ww .  j  a v a 2  s.c  o  m
        public void run() {
            thriftServer.serve();
        }
    }.start();

    while (!info.server.isServing()) {
        Thread.sleep(10);
    }
    info.port = serverSocket.getServerSocket().getLocalPort();

    return info;
}

From source file:com.facebook.swift.service.unframed.UnframedTestSuite.java

License:Apache License

public TestServerInfo startServer() throws Exception {
    final TestServerInfo info = new TestServerInfo();
    TServerSocket serverSocket = new TServerSocket(0);
    com.facebook.swift.service.scribe.scribe.Iface handler = new PlainScribeHandler();
    TProcessor processor = new com.facebook.swift.service.scribe.scribe.Processor<>(handler);

    TThreadPoolServer.Args args = new TThreadPoolServer.Args(serverSocket).processor(processor);
    final TServer thriftServer = info.server = new TThreadPoolServer(args);

    new Thread() {
        @Override//w  ww  .j ava  2  s  . com
        public void run() {
            thriftServer.serve();
        }
    }.start();

    while (!info.server.isServing()) {
        Thread.sleep(10);
    }
    info.port = serverSocket.getServerSocket().getLocalPort();

    return info;
}

From source file:com.vmware.photon.controller.chairman.ChairmanServer.java

License:Open Source License

public void serve() throws TTransportException, IOException {
    InetAddress registrationIpAddress = InetAddress.getByName(registrationAddress);
    if (registrationIpAddress.isAnyLocalAddress()) {
        logger.error("Using a wildcard registration address will not work with service registry: {}",
                registrationAddress);/*  w  w  w . j  av  a  2  s  .  c  o m*/
        throw new IllegalArgumentException("Wildcard registration address");
    }

    InetAddress bindIpAddress = InetAddress.getByName(bind);
    InetSocketAddress bindSocketAddress = new InetSocketAddress(bindIpAddress, port);
    TServerSocket transport = new TServerSocket(bindSocketAddress);

    Chairman.Processor<ChairmanService> chairmanProcessor = new Chairman.Processor<>(chairmanService);
    TMultiplexedProcessor processor = new TMultiplexedProcessor();
    processor.registerProcessor("Chairman", chairmanProcessor);

    // TODO(vspivak): add configurable executor
    server = new TThreadPoolServer(new TThreadPoolServer.Args(transport).processor(processor)
            .protocolFactory(protocolFactory).transportFactory(transportFactory));

    // Need to re-fetch local port in case it was 0
    InetSocketAddress registrationSocketAddress = new InetSocketAddress(registrationIpAddress,
            transport.getServerSocket().getLocalPort());
    serviceNode = serviceNodeFactory.createLeader("chairman", registrationSocketAddress);

    ServiceNodeUtils.joinService(serviceNode, retryIntervalMsec, manager);

    logger.info("Starting chairman ({})", buildInfo);
    logger.info("Listening on: {}", bindSocketAddress);
    logger.info("Registering address: {}", registrationSocketAddress);
    server.serve();
}

From source file:com.vmware.photon.controller.common.thrift.EndToEndTest.java

License:Open Source License

@Test
public void testEndToEnd() throws TException, InterruptedException {
    TServerSocket transport = new TServerSocket(0);
    Echoer.Processor<EchoServer> processor = new Echoer.Processor<>(new EchoServer());
    server = new TThreadPoolServer(new TThreadPoolServer.Args(transport).transportFactory(transportFactory)
            .protocolFactory(protocolFactory).processor(processor));

    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(new Runnable() {
        @Override//from   ww w .j a v  a 2  s . co  m
        public void run() {
            server.serve();
        }
    });

    InetSocketAddress localPort = new InetSocketAddress(transport.getServerSocket().getLocalPort());
    ClientPool<Echoer.AsyncClient> pool = poolFactory.create(new StaticServerSet(localPort),
            new ClientPoolOptions().setMaxClients(10).setMaxWaiters(10));
    ClientProxy<Echoer.AsyncClient> clientProxy = proxyFactory.create(pool);

    final CountDownLatch latch = new CountDownLatch(1);
    final Echoer.AsyncClient.echo_call[] result = { null };
    final Exception[] error = { null };

    Echoer.AsyncIface echoer = clientProxy.get();
    echoer.echo("Hello", new AsyncMethodCallback<Echoer.AsyncClient.echo_call>() {
        @Override
        public void onComplete(Echoer.AsyncClient.echo_call response) {
            result[0] = response;
            latch.countDown();
        }

        @Override
        public void onError(Exception exception) {
            error[0] = exception;
            latch.countDown();
        }
    });

    latch.await(AWAIT_TIMEOUT, TimeUnit.SECONDS);

    assertThat(error[0], is(nullValue()));
    assertThat(result[0].getResult(), is("Echoed: Hello"));
}

From source file:com.vmware.photon.controller.common.thrift.EndToEndTest.java

License:Open Source License

@Test
public void testEndToEndRpcTimeout() throws Exception {
    TServerSocket transport = new TServerSocket(0);
    Echoer.Processor<SleepyEchoServer> processor = new Echoer.Processor<>(new SleepyEchoServer());
    server = new TThreadPoolServer(new TThreadPoolServer.Args(transport).transportFactory(transportFactory)
            .protocolFactory(protocolFactory).processor(processor));

    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(new Runnable() {
        @Override//from ww  w .j ava 2  s .  c  o  m
        public void run() {
            server.serve();
        }
    });

    InetSocketAddress localPort = new InetSocketAddress(transport.getServerSocket().getLocalPort());
    ClientPool<Echoer.AsyncClient> pool = poolFactory.create(new StaticServerSet(localPort),
            new ClientPoolOptions().setMaxClients(10).setMaxWaiters(10));
    ClientProxy<Echoer.AsyncClient> clientProxy = proxyFactory.create(pool);

    final CountDownLatch latch = new CountDownLatch(1);
    final Echoer.AsyncClient.echo_call[] result = { null };
    final Exception[] error = { null };

    Echoer.AsyncClient echoer = clientProxy.get();
    echoer.setTimeout(5);
    echoer.echo("Hello", new AsyncMethodCallback<Echoer.AsyncClient.echo_call>() {
        @Override
        public void onComplete(Echoer.AsyncClient.echo_call response) {
            result[0] = response;
            latch.countDown();
        }

        @Override
        public void onError(Exception exception) {
            error[0] = exception;
            latch.countDown();
        }
    });

    latch.await(AWAIT_TIMEOUT, TimeUnit.SECONDS);

    assertThat(error[0], is(instanceOf(TimeoutException.class)));
    assertTrue(error[0].getMessage().contains("timed out"), "Expecting 'timed out' in error message");
    assertThat(result[0], is(nullValue()));
}

From source file:com.vmware.photon.controller.deployer.DeployerServer.java

License:Open Source License

public void serve() throws UnknownHostException, TTransportException {
    InetAddress registrationIpAddress = InetAddress.getByName(registrationAddress);
    if (registrationIpAddress.isAnyLocalAddress()) {
        logger.error("Using a wildcard registration address will not work with service registry: {}",
                registrationAddress);/*from  w  w w  .j  av a2  s.c o m*/
        throw new IllegalArgumentException("Wildcard registration address");
    }

    InetAddress bindIpAddress = InetAddress.getByName(bind);
    InetSocketAddress bindSocketAddress = new InetSocketAddress(bindIpAddress, port);
    TServerSocket transport = new TServerSocket(bindSocketAddress);

    Deployer.Processor<DeployerService> deployerProcessor = new Deployer.Processor<>(deployerService);
    TMultiplexedProcessor processor = new TMultiplexedProcessor();
    processor.registerProcessor(SERVICE_NAME, deployerProcessor);

    server = new TThreadPoolServer(new TThreadPoolServer.Args(transport).processor(processor)
            .protocolFactory(protocolFactory).transportFactory(transportFactory));

    // Need to re-fetch local port in case it was 0
    InetSocketAddress registrationSocketAddress = new InetSocketAddress(registrationIpAddress,
            transport.getServerSocket().getLocalPort());
    serviceNode = serviceNodeFactory.createSimple("deployer", registrationSocketAddress);

    server.setServerEventHandler(getThriftEventHandler());

    logger.info("Starting deployer ({})", buildInfo);
    logger.info("Listening on: {}", bindSocketAddress);
    logger.info("Registering address: {}", registrationSocketAddress);
    logger.info("HttpClient is: {}", httpClient);
    server.serve();
}

From source file:com.vmware.photon.controller.housekeeper.HousekeeperServer.java

License:Open Source License

public void serve() throws UnknownHostException, TTransportException {
    InetAddress registrationIpAddress = InetAddress.getByName(registrationAddress);
    if (registrationIpAddress.isAnyLocalAddress()) {
        logger.error("Using a wildcard registration address will not work with service registry: {}",
                registrationAddress);//from   www  .  j a va  2 s  .c  o m
        throw new IllegalArgumentException("Wildcard registration address");
    }

    InetAddress bindIpAddress = InetAddress.getByName(bind);
    InetSocketAddress bindSocketAddress = new InetSocketAddress(bindIpAddress, port);
    TServerSocket transport = new TServerSocket(bindSocketAddress);

    Housekeeper.Processor<HousekeeperService> housekeeperProcessor = new Housekeeper.Processor<>(
            housekeeperService);
    TMultiplexedProcessor processor = new TMultiplexedProcessor();
    processor.registerProcessor(SERVICE_NAME, housekeeperProcessor);

    server = new TThreadPoolServer(new TThreadPoolServer.Args(transport).processor(processor)
            .protocolFactory(protocolFactory).transportFactory(transportFactory));

    // Need to re-fetch local port in case it was 0
    InetSocketAddress registrationSocketAddress = new InetSocketAddress(registrationIpAddress,
            transport.getServerSocket().getLocalPort());
    serviceNode = serviceNodeFactory.createSimple("housekeeper", registrationSocketAddress);

    server.setServerEventHandler(getThriftEventHandler());

    logger.info("Starting housekeeper ({})", buildInfo);
    logger.info("Listening on: {}", bindSocketAddress);
    logger.info("Registering address: {}", registrationSocketAddress);
    server.serve();
}

From source file:com.vmware.photon.controller.rootscheduler.RootSchedulerServer.java

License:Open Source License

public void serve() throws TTransportException, UnknownHostException {
    InetAddress registrationIpAddress = InetAddress.getByName(registrationAddress);
    if (registrationIpAddress.isAnyLocalAddress()) {
        logger.error("Using a wildcard registration address will not work with service registry: {}",
                registrationAddress);/*from  w  ww  .  j a  v a 2  s  . c  o m*/
        throw new IllegalArgumentException("Wildcard registration address");
    }

    InetAddress bindIpAddress = InetAddress.getByName(bind);
    InetSocketAddress bindSocketAddress = new InetSocketAddress(bindIpAddress, port);
    TServerSocket transport = new TServerSocket(bindSocketAddress);

    RootScheduler.Processor<RootScheduler.Iface> rootSchedulerProcessor = new RootScheduler.Processor<>(
            rootSchedulerService);
    TMultiplexedProcessor processor = new TMultiplexedProcessor();
    processor.registerProcessor("RootScheduler", rootSchedulerProcessor);

    server = new TThreadPoolServer(new TThreadPoolServer.Args(transport).processor(processor)
            .protocolFactory(protocolFactory).transportFactory(transportFactory));

    // Need to re-fetch local port in case it was 0
    InetSocketAddress registrationSocketAddress = new InetSocketAddress(registrationIpAddress,
            transport.getServerSocket().getLocalPort());
    serviceNode = serviceNodeFactory.createSimple("root-scheduler", registrationSocketAddress);
    if (rootSchedulerService instanceof ServiceNodeEventHandler) {
        server.setServerEventHandler(
                thriftFactory.create((ServiceNodeEventHandler) rootSchedulerService, serviceNode));
    }
    logger.info("Starting root scheduler ({})", buildInfo);
    logger.info("Listening on: {}", bindSocketAddress);
    logger.info("Registering address: {}", registrationSocketAddress);
    server.serve();
}

From source file:ezbake.security.service.EzSecurityLauncher.java

License:Apache License

/**
 * Parse command line arguments and start the server
 *
 * @throws Exception/*from w  w  w.  java  2 s  .  c  o  m*/
 */
public void run() throws Exception {
    checkEzConfig();
    // get the port
    if (this.port == 0) {
        this.port = findFreePort();
    }

    // Setup the EzConfiguration
    Properties config = new EzConfiguration().getProperties();
    if (!config.containsKey(EzBakePropertyConstants.EZBAKE_SECURITY_ID)) {
        config.setProperty(EzBakePropertyConstants.EZBAKE_SECURITY_ID, this.id);
    }
    if (!config.containsKey(EzBakePropertyConstants.EZBAKE_CERTIFICATES_DIRECTORY)) {
        config.setProperty(EzBakePropertyConstants.EZBAKE_CERTIFICATES_DIRECTORY,
                new File(this.config, "ssl").getPath());
    }

    if (!config.containsKey(EzBakePropertyConstants.EZBAKE_SECURITY_SERVICE_MOCK_SERVER)) {
        config.setProperty(EzBakePropertyConstants.EZBAKE_SECURITY_SERVICE_MOCK_SERVER,
                String.valueOf(this.mock));
    }

    EzBakeBaseThriftService runner = new EzSecurityHandler();
    runner.setConfigurationProperties(config);

    TProcessor processor = runner.getThriftProcessor();
    TServerSocket socket = ThriftUtils.getSslServerSocket(this.port, config);
    server = new TThreadPoolServer(
            new TThreadPoolServer.Args(socket).processor(processor).minWorkerThreads(1000));

    // Make the service discoverable
    if (new ZookeeperConfigurationHelper(config).getZookeeperConnectionString() == null) {
        throw new RuntimeException("No zookeeper is available for service discovery!");
    }

    // register with zookeeper
    client = new ServiceDiscoveryClient(
            new ZookeeperConfigurationHelper(config).getZookeeperConnectionString());
    client.registerEndpoint(ezsecurityConstants.SERVICE_NAME, getHostName());

    // Add shutdown hook to unregister
    unregisterOnShutdown();

    log.info("Starting EzBakeSecurity server: port({})", socket.getServerSocket().getLocalPort());
    server.serve();
}

From source file:org.apache.accumulo.core.client.TestThrift1474.java

License:Apache License

@Test
public void test() throws IOException, TException, InterruptedException {
    TServerSocket serverTransport = new TServerSocket(0);
    serverTransport.listen();/*ww  w. j  a  v  a2  s .c om*/
    int port = serverTransport.getServerSocket().getLocalPort();
    TestServer handler = new TestServer();
    ThriftTest.Processor<ThriftTest.Iface> processor = new ThriftTest.Processor<ThriftTest.Iface>(handler);

    TThreadPoolServer.Args args = new TThreadPoolServer.Args(serverTransport);
    args.stopTimeoutVal = 10;
    args.stopTimeoutUnit = TimeUnit.MILLISECONDS;
    final TServer server = new TThreadPoolServer(args.processor(processor));
    Thread thread = new Thread() {
        @Override
        public void run() {
            server.serve();
        }
    };
    thread.start();
    while (!server.isServing()) {
        UtilWaitThread.sleep(10);
    }

    TTransport transport = new TSocket("localhost", port);
    transport.open();
    TProtocol protocol = new TBinaryProtocol(transport);
    ThriftTest.Client client = new ThriftTest.Client(protocol);
    assertTrue(client.success());
    assertFalse(client.fails());
    try {
        client.throwsError();
        fail("no exception thrown");
    } catch (ThriftSecurityException ex) {
        // expected
    }
    server.stop();
    thread.join();
}