Example usage for org.apache.thrift.transport TSocket open

List of usage examples for org.apache.thrift.transport TSocket open

Introduction

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

Prototype

public void open() throws TTransportException 

Source Link

Document

Connects the socket, creating a new socket object if necessary.

Usage

From source file:client.controller.ThriftClient.java

public static void ProcessClientRequest(String host, int port, String request, String path, int version,
        byte[] data) {
    try {/*from ww w.j  a  v a  2s  .  co  m*/
        TSocket transport = new TSocket(host, port);
        transport.open();
        TProtocol protocol = new TBinaryProtocol(transport);

        ByteBuffer newData = ByteBuffer.wrap(data);
        //            List<String> partiotionedPath = new ArrayList<>(Arrays.asList(path.split("/")));
        //            if (partiotionedPath.isEmpty()) {
        //                partiotionedPath.add("/");
        //            } else {
        //                partiotionedPath.set(0, "/");
        //            }

        FileSystem.Client client = new FileSystem.Client(protocol);
        String result = "";
        switch (request) {
        case "ADD":
            result = client.addFile(path, newData);
            break;
        case "GET":
            result = client.getFile(path);
            break;
        case "LIST":
            result = client.listChildren(path);
            break;
        case "UPDATE":
            result = client.updateFile(path, newData, false, version);
            break;
        case "DELETE":
            result = client.deleteFile(path, false, version);
            if (result == null) {
                result = "The file " + path + " does not exist!";
            }
            break;
        case "DELETE+VERSION":
            result = client.deleteFile(path, true, version);
            if (result == null) {
                result = "The file " + path + " does not exist or it has a different version!";
            }
            break;
        case "UPDATE+VERSION":
            result = client.updateFile(path, newData, true, version);
            if (result == null) {
                result = "The file " + path + " does not exist or it has a different version!";
            }
            break;
        default:
            result = "Error!";
            break;
        }

        //result = client.hi();
        String[] a = null;
        new ClientResultsView("").show(result);
        //System.out.println("Return from server: " + result);

        transport.close();
    } catch (TException e) {
        e.printStackTrace();
    }
}

From source file:cloud.thrift.client.config.ZooKeeperConfig.java

License:Open Source License

private UserService.Client createUserService(String serviceInstanceName) {
    String ip = serviceInstanceName.split("-")[1];
    TSocket transport = new TSocket(ip, 7911);
    try {/*from   w  w  w.j ava  2 s  .  c  o m*/
        transport.open();
    } catch (TTransportException e) {
        e.printStackTrace();
    }
    return new UserService.Client(new TBinaryProtocol(transport));
}

From source file:cn.lhfei.spark.hive.HiveThriftClient.java

License:Apache License

public static void main(String[] args) {
    try {/*w w  w.jav  a  2  s .c om*/
        TSocket transport = new TSocket("10.58.62.142", 10003);
        transport.setTimeout(999999999);
        TBinaryProtocol protocol = new TBinaryProtocol(transport);

        Client client = new ThriftHive.Client(protocol);

        transport.open();

        String hql = "select c.dt,sum(c.num),count(distinct c.imei) from (select count(1) as num,imei,dt from data_sum.sum_sdk_phone_event_day where dt='20151022' and app_name='Wallpaper' and widget_id='YL' and event_id='expose' group by dt,imei union all select count(1) as num,props['imei'] as imei,dt from data_sum.sum_sdk_phone_event_day where dt=20151022  and app_name='Wallpaper' and widget_id='YL' and event_id='expose' and imei='-' group by dt,props['imei']) c join (select a.dt,a.imei from (select dt,imei,cast(from_unixtime(cast(substr(activation_halfhour_time,0,10) as bigint),'yyyyMMdd') as string) time from data_sum.sum_phone_source_day where dt='20151022') a where a.time<=a.dt group by a.dt,a.imei) d on c.imei=d.imei where c.dt=d.dt group by c.dt";
        client.execute(hql);

        List<String> result = client.fetchAll();

        for (String row : result) {
            log.info(row);
        }

        /*client.execute("select count(*) from data_sum.sum_sdk_phone_app_day where dt='20151022'");
        String length = client.fetchOne();
                
        log.info("Count: [{}]", length);*/

        transport.close();

    } catch (TTransportException e) {
        e.printStackTrace();
    } catch (HiveServerException e) {
        e.printStackTrace();
    } catch (TException e) {
        e.printStackTrace();
    }

}

From source file:cn.lhfei.spark.hive.ThriftSocketClient.java

License:Apache License

public static void main(String[] args) {
    try {//from   ww  w .  j  a  va 2  s .  co  m
        TSocket transport = new TSocket("10.154.29.150", 10002);
        transport.setTimeout(999999999);
        TBinaryProtocol protocol = new TBinaryProtocol(transport);
        TCLIService.Client client = new TCLIService.Client(protocol);

        transport.open();

        TOpenSessionReq openReq = new TOpenSessionReq();
        TOpenSessionResp openResp = client.OpenSession(openReq);
        TSessionHandle sessHandle = openResp.getSessionHandle();
        TExecuteStatementReq execReq = new TExecuteStatementReq(sessHandle,
                "SELECT * FROM temp.uuid_count limit 10;");
        TExecuteStatementResp execResp = client.ExecuteStatement(execReq);
        TOperationHandle stmtHandle = execResp.getOperationHandle();
        TFetchResultsReq fetchReq = new TFetchResultsReq(stmtHandle, TFetchOrientation.FETCH_FIRST, 1);
        TFetchResultsResp resultsResp = client.FetchResults(fetchReq);

        TRowSet resultsSet = resultsResp.getResults();
        List<TRow> resultRows = resultsSet.getRows();
        for (TRow resultRow : resultRows) {
            resultRow.toString();
        }

        TCloseOperationReq closeReq = new TCloseOperationReq();
        closeReq.setOperationHandle(stmtHandle);
        client.CloseOperation(closeReq);
        TCloseSessionReq closeConnectionReq = new TCloseSessionReq(sessHandle);
        client.CloseSession(closeConnectionReq);

        transport.close();
    } catch (TException e) {
        e.printStackTrace();
    }
}

From source file:com.bfd.harpc.pool.TServiceClientPoolFactory.java

License:Apache License

/**
 * ?//  ww  w . j a v a  2  s.co m
 */
@SuppressWarnings("unchecked")
@Override
public T makeObject(ServerNode key) throws Exception {
    // ?client
    if (key != null) {
        TSocket tsocket = new TSocket(key.getIp(), key.getPort(), timeout);
        TProtocol protocol = new TBinaryProtocol(tsocket);
        TServiceClient client = clientFactory.getClient(protocol);
        tsocket.open();
        return (T) client;
    }
    LOGGER.error("Not find a vilid server!");
    throw new RpcException("Not find a vilid server!");
}

From source file:com.bfd.harpc.test.thrift.ThriftMain.java

License:Apache License

public static void main(String[] args) {
    TSocket transport = new TSocket("127.0.0.1", 19091);
    TProtocol protocol = new TBinaryProtocol(transport);
    Client client = new Client(protocol);

    try {/*from w  w w .  ja  v a2  s  .  c  o m*/
        transport.open();
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            client.echo("hello world!");
        }
        System.out.println(System.currentTimeMillis() - startTime);
    } catch (TException e) {
        System.err.println(e.getMessage());
    }
}

From source file:com.bigdata.dastor.client.RingCache.java

License:Apache License

public void refreshEndPointMap() {
    for (String seed : seeds_) {
        try {// ww  w.  j ava  2s .c o  m
            TSocket socket = new TSocket(seed, port_);
            TBinaryProtocol binaryProtocol = new TBinaryProtocol(socket, false, false);
            Dastor.Client client = new Dastor.Client(binaryProtocol);
            socket.open();

            Map<String, String> tokenToHostMap = (Map<String, String>) JSONValue
                    .parse(client.get_string_property(DastorThriftServer.TOKEN_MAP));

            BiMap<Token, InetAddress> tokenEndpointMap = HashBiMap.create();
            for (Map.Entry<String, String> entry : tokenToHostMap.entrySet()) {
                Token token = StorageService.getPartitioner().getTokenFactory().fromString(entry.getKey());
                String host = entry.getValue();
                try {
                    tokenEndpointMap.put(token, InetAddress.getByName(host));
                } catch (UnknownHostException e) {
                    throw new AssertionError(e); // host strings are IPs
                }
            }

            tokenMetadata = new TokenMetadata(tokenEndpointMap);

            break;
        } catch (TException e) {
            /* let the Exception go and try another seed. log this though */
            logger_.debug("Error contacting seed " + seed + " " + e.getMessage());
        }
    }
}

From source file:com.buzzinate.dm.cassandra.ColumnFamilyOutputFormat.java

License:Apache License

/**
 * Return a client based on the given socket that points to the configured
 * keyspace, and is logged in with the configured credentials.
 *
 * @param socket  a socket pointing to a particular node, seed or otherwise
 * @param conf a job configuration//from   ww w . j a  v  a 2s  .co  m
 * @return a cassandra client
 * @throws InvalidRequestException
 * @throws TException
 * @throws AuthenticationException
 * @throws AuthorizationException
 */
public static Cassandra.Client createAuthenticatedClient(TSocket socket, Configuration conf)
        throws InvalidRequestException, TException, AuthenticationException, AuthorizationException {
    TBinaryProtocol binaryProtocol = new TBinaryProtocol(new TFramedTransport(socket));
    Cassandra.Client client = new Cassandra.Client(binaryProtocol);
    socket.open();
    client.set_keyspace(ConfigHelper.getOutputKeyspace(conf));
    if (ConfigHelper.getOutputKeyspaceUserName(conf) != null) {
        Map<String, String> creds = new HashMap<String, String>();
        creds.put(IAuthenticator.USERNAME_KEY, ConfigHelper.getOutputKeyspaceUserName(conf));
        creds.put(IAuthenticator.PASSWORD_KEY, ConfigHelper.getOutputKeyspacePassword(conf));
        AuthenticationRequest authRequest = new AuthenticationRequest(creds);
        client.login(authRequest);
    }
    return client;
}

From source file:com.cloudera.branchreduce.impl.thrift.Client.java

License:Open Source License

@Override
public int handle(YarnClientService clientService) throws Exception {
    clientService.startAndWait();/* w  w  w  . j  av  a2  s  . c o  m*/
    if (!clientService.isRunning()) {
        LOG.error("BranchReduce job did not start, exiting...");
        return 1;
    }

    Lord.Client client = null;
    while (clientService.isRunning()) {
        ApplicationReport report = clientService.getApplicationReport();
        if (report.getYarnApplicationState() == YarnApplicationState.RUNNING) {
            String originalTrackingUrl = report.getOriginalTrackingUrl();
            if (originalTrackingUrl != null && originalTrackingUrl.contains(":")) {
                System.out.println("Original Tracking URL = " + originalTrackingUrl);
                String[] pieces = originalTrackingUrl.split(":");
                TSocket socket = new TSocket(pieces[0], Integer.valueOf(pieces[1]));
                TProtocol protocol = new TBinaryProtocol(socket);
                client = new Lord.Client(protocol);
                socket.open();
                break;
            }
        }
    }

    if (client == null) {
        LOG.error("Could not connect to thrift service to get status");
        return 1;
    }

    Configuration conf = clientService.getParameters().getConfiguration();
    Class<GlobalState> globalStatusClass = (Class<GlobalState>) conf
            .getClass(BranchReduceConfig.GLOBAL_STATE_CLASS, GlobalState.class);

    boolean finished = false;
    while (!clientService.isApplicationFinished()) {
        if (!finished) {
            GlobalStatusResponse resp = client.getGlobalStatus(new GlobalStatusRequest());
            this.value = Writables.fromByteBuffer(resp.bufferForGlobalState(), globalStatusClass);
            if (resp.isFinished()) {
                LOG.info("Job finished running.");
                finished = true;
            }
            LOG.info(value);
        }
        Thread.sleep(1000);
    }

    clientService.stopAndWait();
    ApplicationReport report = clientService.getFinalReport();
    if (report.getFinalApplicationStatus() == FinalApplicationStatus.SUCCEEDED) {
        System.out.println("Job complete.");
        System.out.println(value);
        return 0;
    } else {
        System.out.println("Final app state: " + report.getFinalApplicationStatus());
        System.out.println("Last global state:");
        System.out.println(value);
        return 1;
    }
}

From source file:com.cloudera.branchreduce.impl.thrift.LordProxy.java

License:Open Source License

public LordProxy(String hostname, int port, Class<T> taskClass) throws TTransportException {
    TSocket socket = new TSocket(hostname, port);
    TProtocol protocol = new TBinaryProtocol(socket);
    this.client = new Lord.Client(protocol);
    socket.open();
    this.taskClass = taskClass;
}