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:gridool.marshaller.ThriftMarshaller.java

License:Apache License

public <T extends TBase> T unmarshall(final byte[] ary, final ClassLoader cl) throws GridException {
    FastByteArrayInputStream bais = new FastByteArrayInputStream(ary);
    TIOStreamTransport trans = new TIOStreamTransport(bais);
    final TCompactProtocol prot = new TCompactProtocol(trans);
    final T obj = createObject();
    try {//from   w  w  w.j  a  v  a2s. c o  m
        obj.read(prot);
    } catch (TException e) {
        throw new GridException(e);
    }
    return obj;
}

From source file:io.airlift.drift.integration.LegacyApacheThriftTesterUtil.java

License:Apache License

private static int logThrift(HostAndPort address, List<LogEntry> messages, List<MethodInvocationFilter> filters,
        Transport transportType, Protocol protocolType, boolean secure) {
    if (!filters.isEmpty()) {
        return 0;
    }// w  w w. j a  v a  2 s.  c o m

    TTransportFactory transportFactory;
    switch (transportType) {
    case UNFRAMED:
        transportFactory = new TTransportFactory();
        break;
    case FRAMED:
        transportFactory = new TFramedTransport.Factory();
        break;
    case HEADER:
        return 0;
    default:
        throw new IllegalArgumentException("Unsupported transport " + transportType);
    }

    try (TSocket socket = createClientSocket(secure, address)) {
        if (!socket.isOpen()) {
            socket.open();
        }
        TTransport transport = transportFactory.getTransport(socket);
        TProtocol protocol;
        switch (protocolType) {
        case BINARY:
            protocol = new TBinaryProtocol(transport);
            break;
        case COMPACT:
            protocol = new TCompactProtocol(transport);
            break;
        case FB_COMPACT:
            return 0;
        default:
            throw new IllegalArgumentException("Unsupported protocol " + protocolType);
        }

        assertEquals(new scribe.Client(protocol).Log(messages), ResultCode.OK);
    } catch (TException e) {
        throw new RuntimeException(e);
    }
    return 1;
}

From source file:io.cslinmiso.line.api.impl.LineApiImpl.java

License:Open Source License

/**
 * Ready.//  ww w .  jav a 2s . co m
 * 
 * @return the talk service. client
 * @throws TTransportException
 */
public Client ready() throws TTransportException {

    THttpClient transport = new THttpClient(LINE_HTTP_IN_URL);
    transport.setCustomHeaders(headers);
    transport.open();

    TProtocol protocol = new TCompactProtocol(transport);

    return new TalkService.Client(protocol);
}

From source file:io.cslinmiso.line.api.impl.LineApiImpl.java

License:Open Source License

public LoginResult login(String id, String password, String certificate) throws Exception {

    IdentityProvider provider = null;/*from  ww  w.  jav a  2s .  co m*/
    Map<String, String> json = null;
    String sessionKey = null;
    boolean keepLoggedIn = true;
    String accessLocation = this.ip;

    // Login to LINE server.
    if (id.matches(EMAIL_REGEX)) {
        provider = IdentityProvider.LINE; // LINE
        json = getCertResult(LINE_SESSION_LINE_URL);
    } else {
        provider = IdentityProvider.NAVER_KR; // NAVER
        json = getCertResult(LINE_SESSION_NAVER_URL);
    }

    if (id != null) {
        this.id = id;
    }

    if (password != null) {
        this.password = password;
    }

    if (StringUtils.isNotEmpty(certificate)) {
        setCertificate(certificate);
    } else {
        // read the certificate file if it exists
        try {
            List<String> readFile = Utility.readFile(LineApiImpl.CERT_FILE);
            String tmpCert = readFile != null ? readFile.get(0) : "";
            if (tmpCert != null) {
                setCertificate(tmpCert);
            }
        } catch (Exception ex) {
            setCertificate("");
        }
    }

    sessionKey = json.get("session_key");
    String tmpMsg = (char) (sessionKey.length()) + sessionKey + (char) (id.length()) + id
            + (char) (password.length()) + password;
    String message = new String(tmpMsg.getBytes(), java.nio.charset.StandardCharsets.UTF_8);
    String[] keyArr = json.get("rsa_key").split(",");
    String keyName = keyArr[0];
    String n = keyArr[1];
    String e = keyArr[2];

    BigInteger modulus = new BigInteger(n, 16);
    BigInteger pubExp = new BigInteger(e, 16);

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, pubExp);
    RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec);
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] enBytes = cipher.doFinal(message.getBytes());
    String encryptString = Hex.encodeHexString(enBytes);

    THttpClient transport = new THttpClient(LINE_HTTP_URL);
    transport.setCustomHeaders(headers);
    transport.open();

    TProtocol protocol = new TCompactProtocol(transport);
    this.client = new TalkService.Client(protocol);

    LoginResult result = this.client.loginWithIdentityCredentialForCertificate(provider, keyName, encryptString,
            keepLoggedIn, accessLocation, this.systemName, this.certificate);

    if (result.getType() == LoginResultType.REQUIRE_DEVICE_CONFIRM) {

        headers.put("X-Line-Access", result.getVerifier());
        String pinCode = result.getPinCode();

        System.out.printf("Enter PinCode '%s' to your mobile phone in 2 minutes.\n", pinCode);
        // await for pinCode to be certified, it will return a verifier afterward.
        loginWithVerifierForCertificate();
    } else if (result.getType() == LoginResultType.SUCCESS) {
        // if param certificate has passed certification
        setAuthToken(result.getAuthToken());
    }

    // Once the client passed the verification, switch connection to HTTP_IN_URL
    this.client = ready();
    return result;
}

From source file:io.cslinmiso.line.api.impl.LineApiImpl.java

License:Open Source License

public void loginWithAuthToken(String authToken) throws Exception {
    if (StringUtils.isNotEmpty(authToken)) {
        setAuthToken(authToken);/*from  w w w .  j  a v  a  2 s.c  o m*/
    }
    THttpClient transport = new THttpClient(LINE_HTTP_URL);
    transport.setCustomHeaders(headers);
    transport.open();

    TProtocol protocol = new TCompactProtocol(transport);
    setClient(new TalkService.Client(protocol));
}

From source file:io.cslinmiso.line.api.impl.LineApiImpl.java

License:Open Source License

public AuthQrcode loginWithQrCode() throws Exception {
    // Request QrCode from LINE server.

    // Map<String, String> json = null;
    boolean keepLoggedIn = false;

    THttpClient transport = new THttpClient(LINE_HTTP_URL);
    transport.setCustomHeaders(headers);
    transport.open();/*from   www .j  a v  a  2  s. c o  m*/

    TProtocol protocol = new TCompactProtocol(transport);

    this.client = new TalkService.Client(protocol);

    AuthQrcode result = this.client.getAuthQrcode(keepLoggedIn, systemName);

    headers.put("X-Line-Access", result.getVerifier());

    System.out.println("Retrieved QR Code.");

    return result;
    // await for QR code to be certified, it will return a verifier afterward.
    // loginWithVerifier();
}

From source file:io.fluo.core.oracle.OracleServer.java

License:Apache License

private OracleService.Client getOracleClient(String host, int port) {
    try {//  w ww . j  av a  2  s . c  o m
        TTransport transport = new TFastFramedTransport(new TSocket(host, port));
        transport.open();
        TProtocol protocol = new TCompactProtocol(transport);
        log.info("Former leader was reachable at " + host + ":" + port);
        return new OracleService.Client(protocol);
    } catch (TTransportException e) {
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return null;
}

From source file:io.jaegertracing.thrift.internal.reporters.protocols.ThriftSenderBaseTest.java

License:Apache License

private int calculateBatchOverheadDifference(int numberOfSpans) throws Exception {
    AutoExpandingBufferWriteTransport memoryTransport = new AutoExpandingBufferWriteTransport(maxPacketSize, 2);
    Agent.Client memoryClient = new Agent.Client(new TCompactProtocol((memoryTransport)));
    Span span = new Span();
    span.setOperationName("raza");
    //0, 0, 0, 0, "raza", 0, 0, 0);
    List<Span> spans = new ArrayList<>();
    for (int i = 0; i < numberOfSpans; i++) {
        spans.add(span);/*from   w  w w .j  av a  2  s.  co  m*/
    }

    memoryClient.emitBatch(new Batch(new io.jaegertracing.thriftjava.Process(SERVICE_NAME), spans));
    int emitBatchOverheadMultipleSpans = memoryTransport.getPos();

    memoryTransport.reset();
    for (int j = 0; j < numberOfSpans; j++) {
        span.write(new TCompactProtocol(memoryTransport));
    }
    int writeBatchOverheadMultipleSpans = memoryTransport.getPos();

    return emitBatchOverheadMultipleSpans - writeBatchOverheadMultipleSpans;
}

From source file:io.warp10.continuum.egress.ThriftDirectoryClient.java

License:Apache License

@Override
public void cacheChanged() {

    Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_DIRECTORY_CLIENT_CACHE_CHANGED,
            Sensision.EMPTY_LABELS, 1);/*  w w w  . j ava  2s .  c o m*/

    synchronized (clientCacheMutex) {
        //
        // Clear transportException
        //

        transportException.set(false);

        //System.out.println("in cacheChanged");

        //
        // Rebuild the Client cache
        //

        List<ServiceInstance<Map>> instances = serviceCache.getInstances();

        //
        // Allocate new clients
        //

        Map<String, Client> newClients = new ConcurrentHashMap<String, DirectoryService.Client>();
        Map<String, Integer> newModulus = new ConcurrentHashMap<String, Integer>();
        Map<String, Integer> newRemainder = new ConcurrentHashMap<String, Integer>();
        Map<String, String> newHosts = new ConcurrentHashMap<String, String>();
        Map<String, Integer> newStreamingPorts = new ConcurrentHashMap<String, Integer>();

        //
        // Determine which instances we should retain.
        // Only the instances which cover the full range of remainders for a given
        // modulus should be retained
        //

        // Set of available remainders per modulus
        Map<Integer, Set<Integer>> remaindersPerModulus = new HashMap<Integer, Set<Integer>>();

        for (ServiceInstance<Map> instance : instances) {
            int modulus = Integer.parseInt(instance.getPayload().get(Directory.PAYLOAD_MODULUS_KEY).toString());
            int remainder = Integer
                    .parseInt(instance.getPayload().get(Directory.PAYLOAD_REMAINDER_KEY).toString());

            // Skip invalid modulus/remainder
            if (modulus <= 0 || remainder >= modulus) {
                continue;
            }

            if (!remaindersPerModulus.containsKey(modulus)) {
                remaindersPerModulus.put(modulus, new HashSet<Integer>());
            }

            remaindersPerModulus.get(modulus).add(remainder);
        }

        //
        // Only retain the moduli which have a full set of remainders
        //

        Set<Integer> validModuli = new HashSet<Integer>();

        for (Entry<Integer, Set<Integer>> entry : remaindersPerModulus.entrySet()) {
            if (entry.getValue().size() == entry.getKey()) {
                validModuli.add(entry.getKey());
            }
        }

        for (ServiceInstance<Map> instance : instances) {

            int modulus = Integer.parseInt(instance.getPayload().get(Directory.PAYLOAD_MODULUS_KEY).toString());

            //
            // Skip instance if it is not associated with a valid modulus
            //

            if (!validModuli.contains(modulus)) {
                continue;
            }

            String id = instance.getId();

            String host = instance.getAddress();
            int port = instance.getPort();
            TTransport transport = new TSocket(host, port);
            try {
                transport.open();
            } catch (TTransportException tte) {
                // FIXME(hbs): log
                continue;
            }

            if (instance.getPayload().containsKey(Directory.PAYLOAD_THRIFT_MAXFRAMELEN_KEY)) {
                transport = new TFramedTransport(transport, Integer.parseInt(
                        instance.getPayload().get(Directory.PAYLOAD_THRIFT_MAXFRAMELEN_KEY).toString()));
            } else {
                transport = new TFramedTransport(transport);
            }

            if (instance.getPayload().containsKey(Directory.PAYLOAD_STREAMING_PORT_KEY)) {
                newHosts.put(id, instance.getAddress());
                newStreamingPorts.put(id, Integer
                        .parseInt(instance.getPayload().get(Directory.PAYLOAD_STREAMING_PORT_KEY).toString()));
            }

            DirectoryService.Client client = new DirectoryService.Client(new TCompactProtocol(transport));
            newClients.put(id, client);
            newModulus.put(id, modulus);
            newRemainder.put(id,
                    Integer.parseInt(instance.getPayload().get(Directory.PAYLOAD_REMAINDER_KEY).toString()));
        }

        //
        // Close current clients and allocate new ones
        //

        synchronized (clientCacheMutex) {

            for (Entry<String, DirectoryService.Client> entry : clientCache.entrySet()) {
                synchronized (entry.getValue()) {
                    try {
                        entry.getValue().getInputProtocol().getTransport().close();
                    } catch (Exception e) {
                    }
                }
            }

            clientCache = newClients;
            modulus = newModulus;
            remainder = newRemainder;

            hosts = newHosts;
            streamingPorts = newStreamingPorts;

            //
            // Shut down the current executor
            //

            if (null != executor) {
                ExecutorService oldexecutor = executor;

                synchronized (executorMutex) {
                    //
                    // Allocate a new executor with 4x as many threads as there are clients
                    //

                    executor = Executors.newCachedThreadPool();
                }

                oldexecutor.shutdown();
            } else {
                synchronized (executorMutex) {
                    executor = Executors.newCachedThreadPool();
                }
            }
        }
    }
}

From source file:io.warp10.continuum.geo.GeoDirectoryThriftClient.java

License:Apache License

@Override
public void cacheChanged() {

    //// www . j ava 2s.  com
    // Rebuild the Client cache
    //

    List<ServiceInstance<Map>> instances = serviceCache.getInstances();

    //
    // Allocate new clients
    //

    Map<String, Client> newClients = new ConcurrentHashMap<String, GeoDirectoryService.Client>();
    Map<String, Integer> newModulus = new ConcurrentHashMap<String, Integer>();
    Map<String, Integer> newRemainder = new ConcurrentHashMap<String, Integer>();
    Map<String, String> newGeoDirectory = new ConcurrentHashMap<String, String>();

    for (ServiceInstance<Map> instance : instances) {
        String id = instance.getId();

        String host = instance.getAddress();
        int port = instance.getPort();
        TTransport transport = new TSocket(host, port);
        try {
            transport.open();
        } catch (TTransportException tte) {
            // FIXME(hbs): log
            continue;
        }

        if (instance.getPayload().containsKey(GeoDirectory.INSTANCE_PAYLOAD_THRIFT_MAXFRAMELEN)) {
            transport = new TFramedTransport(transport, Integer.parseInt(
                    instance.getPayload().get(GeoDirectory.INSTANCE_PAYLOAD_THRIFT_MAXFRAMELEN).toString()));
        } else {
            transport = new TFramedTransport(transport);
        }

        GeoDirectoryService.Client client = new GeoDirectoryService.Client(new TCompactProtocol(transport));
        newClients.put(id, client);
        newModulus.put(id,
                Integer.parseInt(instance.getPayload().get(GeoDirectory.INSTANCE_PAYLOAD_MODULUS).toString()));
        newRemainder.put(id, Integer
                .parseInt(instance.getPayload().get(GeoDirectory.INSTANCE_PAYLOAD_REMAINDER).toString()));
        newGeoDirectory.put(id, instance.getPayload().get(GeoDirectory.INSTANCE_PAYLOAD_GEODIR).toString());
    }

    //
    // Close current clients and allocate new ones
    //

    synchronized (clientCache) {

        for (Entry<String, GeoDirectoryService.Client> entry : clientCache.entrySet()) {
            synchronized (entry.getValue()) {
                entry.getValue().getInputProtocol().getTransport().close();
            }
        }

        clientCache = newClients;
        modulus = newModulus;
        remainder = newRemainder;
        names = newGeoDirectory;

        //
        // Shut down the current executor
        //

        if (null != executor) {
            executor.shutdown();
        }

        //
        // Allocate a new executor with 4x as many threads as there are clients
        //

        executor = Executors.newCachedThreadPool();
    }
}