Example usage for org.apache.thrift.transport TNonblockingSocket TNonblockingSocket

List of usage examples for org.apache.thrift.transport TNonblockingSocket TNonblockingSocket

Introduction

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

Prototype

public TNonblockingSocket(String host, int port) throws IOException 

Source Link

Usage

From source file:ParallelClient.java

License:Apache License

public static void main(String[] args) {

    if (args.length != 1 || !args[0].contains("simple")) {
        System.out.println("Please enter 'simple' ");
        System.exit(0);/*from   w w w .  ja  v  a  2s .co  m*/
    }

    try {

        for (int i = 0; i < 5; ++i) {
            System.out.println("Send request i = " + i);
            new Thread() {
                public void run() {
                    try {
                        TProtocolFactory protocolFactory = new TBinaryProtocol.Factory();
                        TAsyncClientManager clientManager = new TAsyncClientManager();
                        TNonblockingTransport transport = new TNonblockingSocket("localhost", 9090);
                        Myservice.AsyncClient client = new Myservice.AsyncClient(protocolFactory, clientManager,
                                transport);
                        client.DelayAdd(100, 200, 3, new AddCallBack(latch, transport));
                    } catch (TException x) {
                        x.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
            System.out.println("After Send request i = " + i);
        }
        boolean wait = latch.await(30, TimeUnit.SECONDS);
        System.out.println("latch.await =:" + wait);

        System.out.println("Exiting client.");

    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:com.baidu.oped.apm.plugin.thrift.common.client.AsyncEchoTestClient.java

License:Apache License

private AsyncEchoTestClient(TestEnvironment environment) throws IOException {
    this.environment = environment;
    this.transport = new TNonblockingSocket(this.environment.getServerIp(), this.environment.getPort());
    this.asyncClient = new EchoService.AsyncClient(this.environment.getProtocolFactory(),
            this.asyncClientManager, this.transport);
}

From source file:com.kurento.kmf.thrift.pool.MediaServerAsyncClientFactory.java

License:Open Source License

private AsyncClient createAsyncClient() {
    TNonblockingTransport transport;/*from  ww w.jav a2  s.  c  om*/

    try {
        transport = new TNonblockingSocket(apiConfig.getServerAddress(), apiConfig.getServerPort());
    } catch (IOException e) {
        throw new KurentoMediaFrameworkException("Error creating non blocking transport", e, 30000);
    }

    TAsyncClientManager clientManager;
    try {
        clientManager = new TAsyncClientManager();
    } catch (IOException e) {
        throw new KurentoMediaFrameworkException("Error creating client manager", e, 30000);
    }

    TProtocolFactory protocolFactory = new TBinaryProtocol.Factory();

    return new AsyncClientWithValidation(protocolFactory, clientManager, transport);
}

From source file:com.kurento.kmf.thrift.pool.ThriftAsyncClientFactory.java

License:Open Source License

private AsyncClient createAsyncClient() {
    TNonblockingTransport transport;//  w w w. j a  v a  2 s.c o m

    try {
        transport = new TNonblockingSocket(apiConfig.getServerAddress(), apiConfig.getServerPort());
    } catch (IOException e) {
        throw new ClientPoolException("Error creating non blocking transport for asynchronous client with \"\n"
                + this.apiConfig.getServerAddress() + ":" + this.apiConfig.getServerPort(), e);
    }

    TProtocolFactory protocolFactory = new TBinaryProtocol.Factory();

    return new AsyncClientWithValidation(protocolFactory, clientManager, transport);
}

From source file:com.nearinfinity.blur.thrift.AsyncClientPool.java

License:Apache License

private TNonblockingSocket newTransport(Connection connection) throws IOException {
    return new TNonblockingSocket(connection.getHost(), connection.getPort());
}

From source file:com.twitter.common.thrift.ThriftConnectionFactory.java

License:Apache License

@VisibleForTesting
TTransport createTransport(int timeoutMillis) throws TTransportException, IOException {
    TSocket socket = null;//from  ww w.ja  v  a 2 s  .c  om
    if (transportType != TransportType.NONBLOCKING) {
        // can't do a nonblocking create on a blocking transport
        if (timeoutMillis <= 0) {
            return null;
        }

        if (sslTransport) {
            SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            SSLSocket ssl_socket = (SSLSocket) factory.createSocket(endpoint.getHostName(), endpoint.getPort());
            ssl_socket.setSoTimeout(timeoutMillis);
            return new TSocket(ssl_socket);
        } else {
            socket = new TSocket(endpoint.getHostName(), endpoint.getPort(), timeoutMillis);
        }
    }

    try {
        switch (transportType) {
        case BLOCKING:
            socket.open();
            setSocketTimeout(socket);
            return socket;
        case FRAMED:
            TFramedTransport transport = new TFramedTransport(socket);
            transport.open();
            setSocketTimeout(socket);
            return transport;
        case NONBLOCKING:
            try {
                return new TNonblockingSocket(endpoint.getHostName(), endpoint.getPort());
            } catch (IOException e) {
                throw new IOException("Failed to create non-blocking transport to " + endpoint, e);
            }
        }
    } catch (TTransportException e) {
        throw new TTransportException("Failed to create transport to " + endpoint, e);
    }

    throw new IllegalArgumentException("unknown transport type " + transportType);
}

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

License:Open Source License

public static <C extends TAsyncClient> C createNewClient(InetSocketAddress address,
        TProtocolFactory protocolFactory, ClientPoolOptions options, ThriftFactory thriftFactory,
        TAsyncClientFactory<C> clientFactory, Map<C, TTransport> clientTransportMap)
        throws IOException, TTransportException {
    TTransport socket = null;//from w w w  .  j  a  va  2  s .  c  om

    if (!isKeyStoreUsed(options.getKeyStorePath())) {
        // Auth is not enabled
        socket = new TNonblockingSocket(address.getHostString(), address.getPort());
    } else {
        TSSLTransportFactory.TSSLTransportParameters params = new TSSLTransportFactory.TSSLTransportParameters();
        params.setTrustStore(options.getKeyStorePath(), options.getKeyStorePassword());

        socket = TSSLTransportFactory.getClientSocket(address.getHostString(), address.getPort(),
                (options.getTimeoutMs() == 0L) ? 10000 : (int) options.getTimeoutMs(), params);
    }
    if (StringUtils.isNotBlank(options.getServiceName())) {
        protocolFactory = thriftFactory.create(options.getServiceName());
    }

    C client = clientFactory.create(protocolFactory, socket);
    clientTransportMap.put(client, socket);
    logger.debug("created new client {} for {}", client, address);
    return client;
}

From source file:com.vmware.photon.controller.deployer.healthcheck.ThriftBasedHealthChecker.java

License:Open Source License

private <X, C extends TAsyncClient> X getThriftClient(Class<X> clientClass, final Class<C> asyncClass,
        final String serviceName) {

    logger.debug("Constructing Thrift client for: {} [{}:{}]", clientClass.getCanonicalName(), ipAddress, port);

    try {/* w  ww  .ja v a  2 s.  c om*/
        Constructor asyncClassCtor = asyncClass.getConstructor(
                new Class[] { TProtocolFactory.class, TAsyncClientManager.class, TNonblockingTransport.class });

        final C asyncClient = (C) asyncClassCtor.newInstance(
                new Object[] { new MultiplexedProtocolFactory(new TCompactProtocol.Factory(), serviceName),
                        new TAsyncClientManager(), new TNonblockingSocket(ipAddress, port) });

        final ClientProxy<C> clientProxy = new ClientProxy<C>() {
            @Override
            public C get() {
                return asyncClient;
            }
        };

        Constructor clientClassCtor = clientClass.getConstructor(new Class[] { ClientProxy.class });
        return (X) clientClassCtor.newInstance(new Object[] { clientProxy });
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.weibo.dip.flume.extension.sink.scribe.AsyncScribeSink.java

License:Apache License

@Override
public void configure(Context context) {
    String name = context.getString(ScribeSinkConfigurationConstants.CONFIG_SINK_NAME, "sink-" + hashCode());
    setName(name);/* w ww.j  a  va2  s .  c o  m*/
    sinkCounter = new SinkCounter(name);
    batchSize = context.getLong(ScribeSinkConfigurationConstants.CONFIG_BATCHSIZE, 1L);
    String clazz = context.getString(ScribeSinkConfigurationConstants.CONFIG_SERIALIZER,
            EventToLogEntrySerializer.class.getName());

    try {
        serializer = (FlumeEventSerializer) Class.forName(clazz).newInstance();
    } catch (Exception ex) {
        logger.warn("Defaulting to EventToLogEntrySerializer", ex);
        serializer = new EventToLogEntrySerializer();
    } finally {
        serializer.configure(context);
    }

    String host = context.getString(ScribeSinkConfigurationConstants.CONFIG_SCRIBE_HOST);
    int port = context.getInteger(ScribeSinkConfigurationConstants.CONFIG_SCRIBE_PORT);
    timeout = context.getInteger(ScribeSinkConfigurationConstants.CONFIG_SCRIBE_TIMEOUT, 1000);

    try {
        transport = new TNonblockingSocket(host, port);
        clientManager = new TAsyncClientManager();
    } catch (Exception ex) {
        logger.error("Unable to create Thrift Transport", ex);
        throw new RuntimeException(ex);
    }
}

From source file:edu.berkeley.sparrow.examples.ProtoFrontendAsync.java

License:Apache License

public static void main(String[] args) {
    try {/*from w  ww .  j  a  va 2s.  c  o m*/
        OptionParser parser = new OptionParser();
        parser.accepts("c", "configuration file").withRequiredArg().ofType(String.class);
        parser.accepts("help", "print help statement");
        OptionSet options = parser.parse(args);

        if (options.has("help")) {
            parser.printHelpOn(System.out);
            System.exit(-1);
        }

        // Logger configuration: log to the console
        BasicConfigurator.configure();
        LOG.setLevel(Level.DEBUG);

        Configuration conf = new PropertiesConfiguration();

        if (options.has("c")) {
            String configFile = (String) options.valueOf("c");
            conf = new PropertiesConfiguration(configFile);
        }

        Random r = new Random();
        double lambda = conf.getDouble("job_arrival_rate_s", DEFAULT_JOB_ARRIVAL_RATE_S);
        int tasksPerJob = conf.getInt("tasks_per_job", DEFAULT_TASKS_PER_JOB);
        int benchmarkIterations = conf.getInt("benchmark.iterations", DEFAULT_BENCHMARK_ITERATIONS);
        int benchmarkId = conf.getInt("benchmark.id", DEFAULT_TASK_BENCHMARK);

        int schedulerPort = conf.getInt("scheduler_port", SchedulerThrift.DEFAULT_SCHEDULER_THRIFT_PORT);

        TProtocolFactory factory = new TBinaryProtocol.Factory();
        TAsyncClientManager manager = new TAsyncClientManager();

        long lastLaunch = System.currentTimeMillis();
        // Loop and generate tasks launches
        while (true) {
            // Lambda is the arrival rate in S, so we need to multiply the result here by
            // 1000 to convert to ms.
            long delay = (long) (generateInterarrivalDelay(r, lambda) * 1000);
            long curLaunch = lastLaunch + delay;
            long toWait = Math.max(0, curLaunch - System.currentTimeMillis());
            lastLaunch = curLaunch;
            if (toWait == 0) {
                LOG.warn("Generated workload not keeping up with real time.");
            }
            List<TTaskSpec> tasks = generateJob(tasksPerJob, benchmarkId, benchmarkIterations);
            TUserGroupInfo user = new TUserGroupInfo();
            user.setUser("*");
            user.setGroup("*");
            TSchedulingRequest req = new TSchedulingRequest();
            req.setApp("testApp");
            req.setTasks(tasks);
            req.setUser(user);

            TNonblockingTransport tr = new TNonblockingSocket("localhost", schedulerPort);
            SchedulerService.AsyncClient client = new SchedulerService.AsyncClient(factory, manager, tr);
            //client.registerFrontend("testApp", new RegisterCallback());
            client.submitJob(req, new SubmitCallback(req, tr));
        }
    } catch (Exception e) {
        LOG.error("Fatal exception", e);
    }
}