Example usage for org.apache.thrift TBaseHelper byteBufferToByteArray

List of usage examples for org.apache.thrift TBaseHelper byteBufferToByteArray

Introduction

In this page you can find the example usage for org.apache.thrift TBaseHelper byteBufferToByteArray.

Prototype

public static byte[] byteBufferToByteArray(ByteBuffer byteBuffer) 

Source Link

Usage

From source file:co.cask.cdap.common.logging.FlumeLogAdapter.java

License:Apache License

@Override
public Status append(AvroFlumeEvent event) throws AvroRemoteException {
    Map<String, String> headers = toStringMap(event.getHeaders());
    if (!headers.containsKey(LogEvent.FIELD_NAME_LOGTAG)
            || !headers.containsKey(LogEvent.FIELD_NAME_LOGLEVEL)) {
        return Status.UNKNOWN;
    }/*from   w  ww  . j  a  v  a  2s .c o m*/

    String logtag = headers.get(LogEvent.FIELD_NAME_LOGTAG);
    String level = headers.get(LogEvent.FIELD_NAME_LOGLEVEL);

    if (logtag == null || logtag.isEmpty() || level == null || level.isEmpty()) {
        LOG.warn("Logtag or level is null. Please check the send events.");
        return Status.UNKNOWN;
    }

    String body = new String(TBaseHelper.byteBufferToByteArray(event.getBody()));
    LogEvent logEvent = new LogEvent(logtag, level, body);
    this.collector.log(logEvent);
    return Status.OK;
}

From source file:com.perpetumobile.bit.orm.cassandra.CliMain.java

License:Apache License

/**
 * Converts column name into byte[] according to comparator type
 * @param column - column name from parser
 * @param columnFamily - column family name from parser
 * @return bytes[] - into which column name was converted according to comparator type
 *///  w  ww  .j ava  2s  .  c om
private byte[] columnNameAsByteArray(String column, String columnFamily) {
    return TBaseHelper.byteBufferToByteArray(columnNameAsBytes(column, columnFamily));
}

From source file:com.perpetumobile.bit.orm.cassandra.CliMain.java

License:Apache License

/**
 * Converts column name into byte[] according to comparator type
 * @param column - column name from parser
 * @param cfDef  - column family from parser
 * @return bytes[] - into which column name was converted according to comparator type
 *//*from w w  w  . j  a  v  a 2 s .  c  o  m*/
private byte[] columnNameAsByteArray(String column, CfDef cfDef) {
    return TBaseHelper.byteBufferToByteArray(columnNameAsBytes(column, cfDef));
}

From source file:com.perpetumobile.bit.orm.cassandra.CliMain.java

License:Apache License

/**
 * Converts sub-column name into byte[] according to comparator type
 * @param superColumn - sub-column name from parser
 * @param cfDef - column family from parser
 * @return bytes[] - into which column name was converted according to comparator type
 *//*from   w w  w . ja v a  2 s.c o  m*/
private byte[] subColumnNameAsByteArray(String superColumn, CfDef cfDef) {
    return TBaseHelper.byteBufferToByteArray(subColumnNameAsBytes(superColumn, cfDef));
}

From source file:org.apache.cassandra.cli.CliClient.java

License:Apache License

private void executeGet(Tree statement)
        throws TException, NotFoundException, InvalidRequestException, UnavailableException, TimedOutException,
        IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchFieldException {
    if (!CliMain.isConnected() || !hasKeySpace())
        return;/*w  w w  . ja v a 2 s  .  c o  m*/

    Tree columnFamilySpec = statement.getChild(0);
    String columnFamily = CliCompiler.getColumnFamily(columnFamilySpec, keyspacesMap.get(keySpace).cf_defs);
    ByteBuffer key = getKeyAsBytes(columnFamily, columnFamilySpec.getChild(1));
    int columnSpecCnt = CliCompiler.numColumnSpecifiers(columnFamilySpec);
    CfDef cfDef = getCfDef(columnFamily);
    boolean isSuper = cfDef.column_type.equals("Super");

    byte[] superColumnName = null;
    ByteBuffer columnName;

    // table.cf['key'] -- row slice
    if (columnSpecCnt == 0) {
        doSlice(keySpace, key, columnFamily, superColumnName);
        return;
    }
    // table.cf['key']['column'] -- slice of a super, or get of a standard
    else if (columnSpecCnt == 1) {
        columnName = getColumnName(columnFamily, columnFamilySpec.getChild(2));

        if (isSuper) {
            superColumnName = columnName.array();
            doSlice(keySpace, key, columnFamily, superColumnName);
            return;
        }
    }
    // table.cf['key']['column']['column'] -- get of a sub-column
    else if (columnSpecCnt == 2) {
        superColumnName = getColumnName(columnFamily, columnFamilySpec.getChild(2)).array();
        columnName = getSubColumnName(columnFamily, columnFamilySpec.getChild(3));
    }
    // The parser groks an arbitrary number of these so it is possible to get here.
    else {
        sessionState.out.println("Invalid row, super column, or column specification.");
        return;
    }

    AbstractType validator = getValidatorForValue(cfDef, TBaseHelper.byteBufferToByteArray(columnName));

    // Perform a get()
    ColumnPath path = new ColumnPath(columnFamily);
    if (superColumnName != null)
        path.setSuper_column(superColumnName);
    path.setColumn(columnName);
    Column column;
    try {
        column = thriftClient.get(key, path, ConsistencyLevel.ONE).column;
    } catch (NotFoundException e) {
        sessionState.out.println("Value was not found");
        return;
    }

    byte[] columnValue = column.getValue();
    String valueAsString;

    // we have ^(CONVERT_TO_TYPE <type>) inside of GET statement
    // which means that we should try to represent byte[] value according
    // to specified type
    if (statement.getChildCount() == 2) {
        // getting ^(CONVERT_TO_TYPE <type>) tree 
        Tree typeTree = statement.getChild(1).getChild(0);
        // .getText() will give us <type>
        String typeName = CliUtils.unescapeSQLString(typeTree.getText());
        // building AbstractType from <type>
        AbstractType valueValidator = getFormatTypeForColumn(typeName);

        // setting value for output
        valueAsString = valueValidator.getString(ByteBuffer.wrap(columnValue));
        // updating column value validator class
        updateColumnMetaData(cfDef, columnName, valueValidator.getClass().getName());
    } else {
        valueAsString = (validator == null) ? new String(columnValue, Charsets.UTF_8)
                : validator.getString(ByteBuffer.wrap(columnValue));
    }

    String formattedColumnName = isSuper ? formatSubcolumnName(keySpace, columnFamily, column)
            : formatColumnName(keySpace, columnFamily, column);

    // print results
    sessionState.out.printf("=> (column=%s, value=%s, timestamp=%d%s)%n", formattedColumnName, valueAsString,
            column.timestamp, column.isSetTtl() ? String.format(", ttl=%d", column.getTtl()) : "");
}

From source file:org.apache.cassandra.cli.CliClient.java

License:Apache License

/**
 * Converts column name into byte[] according to comparator type
 * @param superColumn - sub-column name from parser
 * @param columnFamily - column family name from parser
 * @return bytes[] - into which column name was converted according to comparator type
 *//* w  w w.  j  a  va 2  s. c  o m*/
private byte[] subColumnNameAsByteArray(String superColumn, String columnFamily) {
    return TBaseHelper.byteBufferToByteArray(subColumnNameAsBytes(superColumn, columnFamily));
}

From source file:org.apache.cassandra.db.marshal.IntegerType.java

License:Apache License

public String getString(ByteBuffer bytes) {
    if (bytes == null)
        return "null";
    if (bytes.remaining() == 0)
        return "empty";

    return new java.math.BigInteger(TBaseHelper.byteBufferToByteArray(bytes)).toString(10);
}

From source file:org.kie.server.thrift.client.RSClient.java

License:Apache License

public static void main(String[] args) throws Exception {

    ResteasyClientBuilder resteasyClientBuilder = new ResteasyClientBuilder();
    ResteasyClient resteasyClient = resteasyClientBuilder.build();
    JaxRsAuthenticator jaxRsAuthenticator = new JaxRsAuthenticator("ks-user", "ks-user");
    KieServicesClient kieServicesClient = new KieServicesClient();
    kieServicesClient.setClient("Test RSClient");
    KieServicesRequest kieServicesRequest;
    KieServicesResponse response;// w w w  . java 2  s  .  co  m

    // ServerInfoTest

    String host = "http://localhost:8080";
    ResteasyWebTarget webTarget = resteasyClient.target(host).path("/kie-server/services/rest/server/thrift");
    webTarget.register(ThriftMessageReader.class);
    webTarget.register(ThriftMessageWriter.class);
    webTarget.register(jaxRsAuthenticator);
    kieServicesRequest = new KieServicesRequest();
    kieServicesRequest.setKieServicesClient(kieServicesClient);
    response = webTarget.request().accept(APPLICATION_XTHRIFT).header("Content-Type", APPLICATION_XTHRIFT)
            .get(KieServicesResponse.class);

    // ListContainersTest

    webTarget = resteasyClient.target(host).path("/kie-server/services/rest/server/thrift/containers");
    webTarget.register(ThriftMessageReader.class);
    webTarget.register(ThriftMessageWriter.class);
    webTarget.register(jaxRsAuthenticator);
    response = webTarget.request().accept(APPLICATION_XTHRIFT).header("Content-Type", APPLICATION_XTHRIFT)
            .get(KieServicesResponse.class);
    System.out.println(response);

    // ContainerInfoTest

    webTarget = resteasyClient.target(host).path("/kie-server/services/rest/server/thrift/containers/test");
    webTarget.register(ThriftMessageReader.class);
    webTarget.register(ThriftMessageWriter.class);
    webTarget.register(jaxRsAuthenticator);
    response = webTarget.request().accept(APPLICATION_XTHRIFT).header("Content-Type", APPLICATION_XTHRIFT)
            .get(KieServicesResponse.class);
    System.out.println(response);

    // ContainerExecuteTest

    webTarget = resteasyClient.target(host)
            .path("/kie-server/services/rest/server/thrift/containers/instances/test/testStatelessKieSession");
    webTarget.register(ThriftMessageReader.class);
    webTarget.register(ThriftMessageWriter.class);
    webTarget.register(jaxRsAuthenticator);
    kieServicesRequest = new KieServicesRequest();
    kieServicesRequest.setKieServicesClient(kieServicesClient);

    TSerializer tSerializer = ThriftMessageWriter.pollTSerializer();
    TDeserializer tDeserializer = ThriftMessageReader.pollTDeserializer();

    SetGlobalCommand setGlobalCommand = new SetGlobalCommand();
    Global global = new Global();
    setGlobalCommand.setObject(tSerializer.serialize(global));
    setGlobalCommand.setClassCanonicalName(Global.class.getCanonicalName());
    setGlobalCommand.setIdentifier("globalList");
    setGlobalCommand.setOutIdentifier("GlobalList");

    SetGlobalCommand setGlobalCommand2 = new SetGlobalCommand();
    BigDecimal bigDecimal = new BigDecimal("45645.5678483633");
    setGlobalCommand2.setObject(tSerializer.serialize(bigDecimal));
    setGlobalCommand2.setClassCanonicalName(BigDecimal.class.getCanonicalName());
    setGlobalCommand2.setIdentifier("bigDecimal");
    setGlobalCommand2.setOutIdentifier("BigDecimalGlobal");

    SetGlobalCommand setGlobalCommand3 = new SetGlobalCommand();
    Date date = new Date(4325643464356L);
    setGlobalCommand3.setObject(tSerializer.serialize(date));
    setGlobalCommand3.setClassCanonicalName(Date.class.getCanonicalName());
    setGlobalCommand3.setIdentifier("executionDate");
    setGlobalCommand3.setOutIdentifier("ExecutionDate");

    InsertObjectCommand insertObjectCommand = new InsertObjectCommand();
    BigDecimal bigDecimal2 = new BigDecimal();
    bigDecimal2.setValue("1000");
    insertObjectCommand.setObject(tSerializer.serialize(bigDecimal2));
    insertObjectCommand.setClassCanonicalName(BigDecimal.class.getCanonicalName());
    insertObjectCommand.setOutIdentifier("BigDecimal2");

    InsertObjectCommand insertObjectCommand2 = new InsertObjectCommand();
    Message message = new Message();
    message.setMessageString("WORLD");
    message.setStatus(HELLO);
    EmbeddedMessage embeddedMessage = new EmbeddedMessage();
    embeddedMessage.setEmbeddedMessageString("Embedded message string");
    embeddedMessage.setBigdecimal(new BigDecimal("1234.5678"));
    message.setEmbeddedMessage(embeddedMessage);
    insertObjectCommand2.setObject(tSerializer.serialize(message));
    insertObjectCommand2.setClassCanonicalName(Message.class.getCanonicalName());
    insertObjectCommand2.setOutIdentifier("Message");

    InsertElementsCommand insertElementsCommand = new InsertElementsCommand();
    Element element = new Element("Element1");
    Element element1 = new Element("Element2");
    Element element2 = new Element("Element3");
    insertElementsCommand.setClassCanonicalName(Element.class.getCanonicalName());
    insertElementsCommand.addToObjects(ByteBuffer.wrap(tSerializer.serialize(element)));
    insertElementsCommand.addToObjects(ByteBuffer.wrap(tSerializer.serialize(element1)));
    insertElementsCommand.addToObjects(ByteBuffer.wrap(tSerializer.serialize(element2)));
    insertElementsCommand.setOutIdentifier("Elements");

    FireAllRulesCommand fireAllRulesCommand = new FireAllRulesCommand();
    AgendaFilter agendaFilter = new AgendaFilter();
    agendaFilter.setAgendaFilterType(AgendaFilterType.RULE_NAME_STARTS_WITH);
    agendaFilter.setExpression("Elem");
    //fireAllRulesCommand.setAgendaFilter(agendaFilter);

    BatchExecutionCommand batchExecutionCommand = new BatchExecutionCommand();
    batchExecutionCommand.addToSetGlobalCommands(setGlobalCommand);
    batchExecutionCommand.addToSetGlobalCommands(setGlobalCommand2);
    batchExecutionCommand.addToSetGlobalCommands(setGlobalCommand3);
    batchExecutionCommand.addToInsertObjectCommands(insertObjectCommand);
    batchExecutionCommand.addToInsertObjectCommands(insertObjectCommand2);
    batchExecutionCommand.addToInsertElementsCommands(insertElementsCommand);
    batchExecutionCommand.setFireAllRulesCommand(fireAllRulesCommand);

    kieServicesRequest.setBatchExecutionCommand(batchExecutionCommand);

    Entity<KieServicesRequest> entity = Entity.entity(kieServicesRequest, APPLICATION_XTHRIFT);
    response = webTarget.request(APPLICATION_XTHRIFT).post(entity, KieServicesResponse.class);
    System.out.println(response);
    if (response.getResponse().isSetKieServicesException()) {
        KieServicesException kieServicesException = response.getResponse().getKieServicesException();
        System.out.println(kieServicesException);
    } else {
        ExecutionResults executionResults = response.getResponse().getResults().getExecutionResults();
        System.out.println(executionResults);
        Message messageResult = new Message();
        ThriftMessageReader.pollTDeserializer().deserialize(messageResult,
                TBaseHelper.byteBufferToByteArray(executionResults.getObjects().get("Message")));
        System.out.println(messageResult);
        Global global1 = new Global();
        ThriftMessageReader.pollTDeserializer().deserialize(global1,
                TBaseHelper.byteBufferToByteArray(executionResults.getObjects().get("GlobalList")));
        System.out.println(global1);
        BigDecimal bigDecimalResult = new BigDecimal();
        ThriftMessageReader.pollTDeserializer().deserialize(bigDecimalResult,
                TBaseHelper.byteBufferToByteArray(executionResults.getObjects().get("BigDecimalGlobal")));
        System.out.println(bigDecimalResult);
        Date dateResult = new Date();
        ThriftMessageReader.pollTDeserializer().deserialize(dateResult,
                TBaseHelper.byteBufferToByteArray(executionResults.getObjects().get("ExecutionDate")));
        System.out.println(dateResult);
        System.out.println(new java.util.Date(dateResult.getValue()));
        Collection collection = new Collection();
        ThriftMessageReader.pollTDeserializer().deserialize(collection,
                TBaseHelper.byteBufferToByteArray(executionResults.getObjects().get("Elements")));
        for (ByteBuffer byteBuffer : collection.getObjects()) {
            Element elementResult = new Element();
            tDeserializer.deserialize(elementResult, TBaseHelper.byteBufferToByteArray(byteBuffer));
            System.out.println(elementResult);
        }
    }
}

From source file:org.kie.server.thrift.Converter.java

License:Apache License

public static ArrayList<Object> convertCommandPayLoad(InsertElementsCommand insertElementsCommand,
        ClassLoader kieContainerClassLoader)
        throws ClassNotFoundException, TException, InstantiationException, IllegalAccessException {
    ArrayList<Object> instances = new ArrayList<>(insertElementsCommand.getObjects().size());
    if (insertElementsCommand.getClassCanonicalName().startsWith(JAVA_MODEL_NAMESPACE)) {
        for (ByteBuffer byteBuffer : insertElementsCommand.getObjects()) {
            instances.add(deserializeToJava(TBaseHelper.byteBufferToByteArray(byteBuffer),
                    insertElementsCommand.getClassCanonicalName(), kieContainerClassLoader));
        }//from  w  w  w.  ja  v a  2  s  .  c  o  m
        return instances;
    } else {
        for (ByteBuffer byteBuffer : insertElementsCommand.getObjects()) {
            instances.add(deserializeToTBase(TBaseHelper.byteBufferToByteArray(byteBuffer),
                    insertElementsCommand.getClassCanonicalName(), kieContainerClassLoader));
        }
        return instances;
    }
}