Example usage for org.apache.thrift.protocol TCompactProtocol TCompactProtocol

List of usage examples for org.apache.thrift.protocol TCompactProtocol TCompactProtocol

Introduction

In this page you can find the example usage for org.apache.thrift.protocol TCompactProtocol TCompactProtocol.

Prototype

public TCompactProtocol(TTransport transport) 

Source Link

Document

Create a TCompactProtocol.

Usage

From source file:org.eclipse.sw360.rest.resourceserver.vendor.Sw360VendorService.java

License:Open Source License

private VendorService.Iface getThriftVendorClient() throws TTransportException {
    THttpClient thriftClient = new THttpClient(thriftServerUrl + "/vendors/thrift");
    TProtocol protocol = new TCompactProtocol(thriftClient);
    return new VendorService.Client(protocol);
}

From source file:org.eclipse.sw360.rest.resourceserver.vulnerability.Sw360VulnerabilityService.java

License:Open Source License

private VulnerabilityService.Iface getThriftVulnerabilityClient() throws TTransportException {
    THttpClient thriftClient = new THttpClient(thriftServerUrl + "/vulnerabilities/thrift");
    TProtocol protocol = new TCompactProtocol(thriftClient);
    return new VulnerabilityService.Client(protocol);
}

From source file:org.glassfish.grizzly.thrift.client.GrizzlyThriftClient.java

License:Open Source License

private GrizzlyThriftClient(Builder<T> builder) {
    this.thriftClientName = builder.thriftClientName;
    this.transport = builder.transport;
    this.clientFactory = builder.clientFactory;
    this.thriftProtocol = builder.thriftProtocol;
    this.connectTimeoutInMillis = builder.connectTimeoutInMillis;
    this.writeTimeoutInMillis = builder.writeTimeoutInMillis;
    this.responseTimeoutInMillis = builder.responseTimeoutInMillis;
    this.healthMonitorIntervalInSecs = builder.healthMonitorIntervalInSecs;
    this.validationCheckMethodName = builder.validationCheckMethodName;
    this.retainLastServer = builder.retainLastServer;

    this.maxThriftFrameLength = builder.maxThriftFrameLength;
    this.transferProtocol = builder.transferProtocol;
    this.httpUriPath = builder.httpUriPath;
    final FilterChainBuilder clientFilterChainBuilder = FilterChainBuilder.stateless();
    switch (transferProtocol) {
    case HTTP://from  w  ww. j a  v a 2 s . c o m
        clientFilterChainBuilder.add(new TransportFilter()).add(new HttpClientFilter())
                .add(new ThriftHttpClientFilter(httpUriPath)).add(new ThriftClientFilter());
        break;
    case BASIC:
    default:
        clientFilterChainBuilder.add(new TransportFilter()).add(new ThriftFrameFilter(maxThriftFrameLength))
                .add(new ThriftClientFilter());
        break;
    }
    this.processor = clientFilterChainBuilder.build();

    @SuppressWarnings("unchecked")
    final BaseObjectPool.Builder<SocketAddress, T> connectionPoolBuilder = new BaseObjectPool.Builder<SocketAddress, T>(
            new PoolableObjectFactory<SocketAddress, T>() {
                @Override
                public T createObject(final SocketAddress key) throws Exception {
                    final ConnectorHandler<SocketAddress> connectorHandler = TCPNIOConnectorHandler
                            .builder(transport).processor(processor).setReuseAddress(true).build();
                    final Future<Connection> future = connectorHandler.connect(key);
                    final Connection<SocketAddress> connection;
                    try {
                        if (connectTimeoutInMillis < 0) {
                            connection = future.get();
                        } else {
                            connection = future.get(connectTimeoutInMillis, TimeUnit.MILLISECONDS);
                        }
                    } catch (InterruptedException ie) {
                        if (!future.cancel(false) && future.isDone()) {
                            final Connection c = future.get();
                            if (c != null && c.isOpen()) {
                                c.closeSilently();
                            }
                        }
                        if (logger.isLoggable(Level.FINER)) {
                            logger.log(Level.FINER, "failed to get the connection. address=" + key, ie);
                        }
                        throw ie;
                    } catch (ExecutionException ee) {
                        if (!future.cancel(false) && future.isDone()) {
                            final Connection c = future.get();
                            if (c != null && c.isOpen()) {
                                c.closeSilently();
                            }
                        }
                        if (logger.isLoggable(Level.FINER)) {
                            logger.log(Level.FINER, "failed to get the connection. address=" + key, ee);
                        }
                        throw ee;
                    } catch (TimeoutException te) {
                        if (!future.cancel(false) && future.isDone()) {
                            final Connection c = future.get();
                            if (c != null && c.isOpen()) {
                                c.closeSilently();
                            }
                        }
                        if (logger.isLoggable(Level.FINER)) {
                            logger.log(Level.FINER, "failed to get the connection. address=" + key, te);
                        }
                        throw te;
                    }
                    if (connection != null) {
                        connectionPoolAttribute.set(connection, connectionPool);
                        final TGrizzlyClientTransport ttransport = TGrizzlyClientTransport.create(connection,
                                responseTimeoutInMillis, writeTimeoutInMillis);
                        final TProtocol protocol;
                        if (thriftProtocol == ThriftProtocols.BINARY) {
                            protocol = new TBinaryProtocol(ttransport);
                        } else if (thriftProtocol == ThriftProtocols.COMPACT) {
                            protocol = new TCompactProtocol(ttransport);
                        } else {
                            protocol = new TBinaryProtocol(ttransport);
                        }
                        final T result = clientFactory.getClient(protocol);
                        clientAttribute.set(connection, result);
                        return result;
                    } else {
                        throw new IllegalStateException("connection must not be null");
                    }
                }

                @Override
                public void destroyObject(final SocketAddress key, final T value) throws Exception {
                    if (value != null) {
                        final TProtocol inputTProtocol = value.getInputProtocol();
                        if (inputTProtocol != null) {
                            final TTransport inputTTransport = inputTProtocol.getTransport();
                            closeTTransport(inputTTransport);
                        }
                        final TProtocol outputTProtocol = value.getOutputProtocol();
                        if (outputTProtocol != null) {
                            final TTransport outputTTransport = outputTProtocol.getTransport();
                            closeTTransport(outputTTransport);
                        }
                    }
                }

                private void closeTTransport(final TTransport tTransport) {
                    if (tTransport == null) {
                        return;
                    }
                    if (tTransport instanceof TGrizzlyClientTransport) {
                        final TGrizzlyClientTransport tGrizzlyClientTransport = (TGrizzlyClientTransport) tTransport;
                        final Connection connection = tGrizzlyClientTransport.getGrizzlyConnection();
                        if (connection != null) {
                            connectionPoolAttribute.remove(connection);
                            clientAttribute.remove(connection);
                        }
                    }
                    tTransport.close();
                }

                @Override
                public boolean validateObject(final SocketAddress key, final T value) throws Exception {
                    return GrizzlyThriftClient.this.validateClient(value);
                }
            });
    connectionPoolBuilder.min(builder.minConnectionPerServer);
    connectionPoolBuilder.max(builder.maxConnectionPerServer);
    connectionPoolBuilder.keepAliveTimeoutInSecs(builder.keepAliveTimeoutInSecs);
    connectionPoolBuilder.disposable(builder.allowDisposableConnection);
    connectionPoolBuilder.borrowValidation(builder.borrowValidation);
    connectionPoolBuilder.returnValidation(builder.returnValidation);
    connectionPool = connectionPoolBuilder.build();

    this.failover = builder.failover;
    this.retryCount = builder.retryCount;

    this.initialServers = builder.servers;

    if (failover && healthMonitorIntervalInSecs > 0) {
        healthMonitorTask = new HealthMonitorTask();
        scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
        scheduledFuture = scheduledExecutor.scheduleWithFixedDelay(healthMonitorTask,
                healthMonitorIntervalInSecs, healthMonitorIntervalInSecs, TimeUnit.SECONDS);
    } else {
        healthMonitorTask = null;
        scheduledExecutor = null;
        scheduledFuture = null;
    }

    this.zkClient = builder.zkClient;
    this.zkListener = new ServerListBarrierListener(this, initialServers);
}

From source file:org.glassfish.grizzly.thrift.client.GrizzlyThriftClient.java

License:Open Source License

private boolean validateConnection(final Connection connection) {
    if (connection == null) {
        return false;
    }/*from  w  w w .j  a v a2 s  . c o m*/
    final TGrizzlyClientTransport ttransport = TGrizzlyClientTransport.create(connection,
            responseTimeoutInMillis, writeTimeoutInMillis);
    final TProtocol protocol;
    if (thriftProtocol == ThriftProtocols.BINARY) {
        protocol = new TBinaryProtocol(ttransport);
    } else if (thriftProtocol == ThriftProtocols.COMPACT) {
        protocol = new TCompactProtocol(ttransport);
    } else {
        protocol = new TBinaryProtocol(ttransport);
    }
    final T client = clientFactory.getClient(protocol);
    final boolean result = validateClient(client);
    ttransport.close();
    return result;
}

From source file:org.ponder.serviceframework.ServiceInvoker.Thrift.ThriftClient.java

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    WrapService instance = pickone();/*from w w w  .  j  a  v a 2s.  c  o  m*/
    if (null == instance) {
        throw new NoServiceInstanceException(
                this.protocol + "@" + this.servicename + "@" + this.version + "??");
    }
    try {
        poolkey = instance.getUri();
        tsocket = pool.borrowObject(poolkey);
        if (null != tsocket) {
            if (null != tsocket && !tsocket.isOpen()) {
                tsocket.open();
            }
        }

        //            System.out.println("Cp3:"+System.nanoTime());
        TProtocol protocol = new TMultiplexedProtocol(new TCompactProtocol(tsocket),
                instance.getServicename() + "@" + instance.getVersion());
        //System.out.println("Cp4:"+System.nanoTime());
        Object client = cons.newInstance(protocol);
        //System.out.println("Cp5:"+System.nanoTime());
        if (client == null) {
            throw new NoServiceInstanceException(this.protocol + "@" + this.servicename + "@" + this.version
                    + "??");
        }
        return method.invoke(client, args);
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException ex) {
        throw ex;
    } catch (TTransportException | InvocationTargetException ex) {
        try {
            pool.invalidateObject(poolkey, tsocket);
        } catch (Exception e1) {
        } finally {
            tsocket = null;
            poolkey = null;
        }
        if (ex.getCause() != null) {
            // (?)
            throw ex.getCause();
        } else {
            throw ex;
        }
    } catch (Exception ex) {
        log.warn("ThriftClient invoke Exception");
        throw ex;
    } finally {
        if (tsocket != null && poolkey != null) {
            if (null != tsocket) {
                tsocket.flush();
            }
            try {
                pool.returnObject(poolkey, tsocket);
            } catch (IllegalStateException ex) {
                log.debug("??", ex);
            }
        }
        //System.out.println("Cp6:"+System.nanoTime());
    }
}

From source file:org.smartloli.kafka.eagle.core.ipc.RpcClient.java

License:Apache License

/** Get consumer offset from Rpc server. */
public static String getOffset(String clusterAlias) {
    TTransport transport = new TFramedTransport(new TSocket(ADDR, PORT, TIMEOUT));
    TProtocol protocol = new TCompactProtocol(transport);
    OffsetMetadataServer.Client client = new OffsetMetadataServer.Client(protocol);
    String target = "";
    try {//from  w  w  w . j a  v a2 s .  co  m
        transport.open();
        target = client.getOffset(clusterAlias);
    } catch (Exception e) {
        LOG.error("Rpc Client getOffset has error,msg is " + e.getMessage());
    } finally {
        transport.close();
    }
    return target;
}

From source file:org.smartloli.kafka.eagle.core.ipc.RpcClient.java

License:Apache License

/** Get consumer system topic from Rpc server. */
public static void system(String bootstrapServers) {
    TTransport transport = new TFramedTransport(new TSocket(ADDR, PORT, TIMEOUT));
    TProtocol protocol = new TCompactProtocol(transport);
    OffsetMetadataServer.Client client = new OffsetMetadataServer.Client(protocol);
    try {//from  www  .j a  v  a2s . co  m
        transport.open();
        client.system(bootstrapServers);
    } catch (Exception e) {
        LOG.error("Rpc Client system topic has error,msg is " + e.getMessage());
    } finally {
        transport.close();
    }
}

From source file:org.thriftzmq.TZMQMultiThreadServerTest.java

License:Apache License

/**
 * Test of serve method, of class TZMQSimpleServer.
 *///w  w w .  jav  a  2  s. c o m
@Test
public void testEcho() throws TException, InterruptedException {
    logger.info("echo");
    TZMQMultiThreadServer server = createServer(TCP_ENDPOINT);
    server.startAndWait();
    TTransport clientTransport = TZMQClientFactory.create(context, TCP_ENDPOINT);
    Service1.Client client = new Service1.Client(new TCompactProtocol(clientTransport));
    clientTransport.open();
    String s = "abcdABCD";
    String r = client.echo(s);
    assertEquals(s, r);
    clientTransport.close();
    server.stopAndWait();
}

From source file:org.thriftzmq.TZMQMultiThreadServerTest.java

License:Apache License

/**
 * Test of echo method with long argument
 *//*from  w w  w.j av  a 2 s.  com*/
@Test
public void testEchoLong() throws Throwable {
    try {
        logger.info("echoLong");
        TZMQMultiThreadServer server = createServer(TCP_ENDPOINT);
        server.startAndWait();
        TTransport clientTransport = TZMQClientFactory.create(context, TCP_ENDPOINT);
        Service1.Client client = new Service1.Client(new TCompactProtocol(clientTransport));
        clientTransport.open();
        //String s = "abcdABCD";
        int l = 1024 * 1024;
        char c[] = new char[l];
        Random rand = new Random(12345);
        for (int i = 0; i < l; i++) {
            c[i] = (char) (rand.nextInt(0x80 - 0x20) + 0x20);
        }
        String s = new String(c);
        String r = client.echo(s);
        assertEquals(s, r);
        clientTransport.close();
        server.stopAndWait();
    } catch (Throwable ex) {
        logger.error("Error in test", ex);
        throw ex;
    }
}

From source file:org.thriftzmq.TZMQMultiThreadServerTest.java

License:Apache License

/**
 * Test of voidMethod method//w  ww  .  jav a  2  s  .c  o m
 */
@Test
public void testVoidMethod() throws TException, InterruptedException {
    logger.info("voidMethod");
    TZMQMultiThreadServer server = createServer(TCP_ENDPOINT);
    server.startAndWait();
    TTransport clientTransport = TZMQClientFactory.create(context, TCP_ENDPOINT);
    Service1.Client client = new Service1.Client(new TCompactProtocol(clientTransport));
    clientTransport.open();
    String s = "abcdABCD";
    client.voidMethod(s);
    clientTransport.close();
    server.stopAndWait();
}