Example usage for org.apache.thrift TSerializer toString

List of usage examples for org.apache.thrift TSerializer toString

Introduction

In this page you can find the example usage for org.apache.thrift TSerializer toString.

Prototype

public String toString(TBase base) throws TException 

Source Link

Document

Serialize the Thrift object into a Java string, using the default JVM charset encoding.

Usage

From source file:com.xiaomi.linden.common.util.CommonUtils.java

License:Apache License

public static <T extends TBase> String ThriftToJSON(T thrift) {
    TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
    try {//from w  w w  . j  av a 2s . c o  m
        return serializer.toString(thrift);
    } catch (TException e) {
    }
    throw new IllegalStateException("Convert to json failed : " + thrift);
}

From source file:ezbake.frack.common.utils.SSRJSONTest.java

License:Apache License

@Test
public void test() throws TException {
    SSR ssr = new SSR();
    SSR jsonThrift = new SSR();

    ssr.setUri("the uri");
    ssr.setVisibility(new Visibility().setFormalVisibility("U"));
    jsonThrift.setUri("the JSON thrift object");
    jsonThrift.setVisibility(new Visibility().setFormalVisibility("U"));
    SSRJSON s = SSRJSONUtil.fromThriftAndSSR(ssr, jsonThrift);
    TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
    String json = serializer.toString(jsonThrift);

    assertEquals("The ssr string check for equality ", s.ssr.toString(), ssr.toString());
    assertEquals("The jsonString check for equality ", s.jsonString, json);
}

From source file:ezbake.frack.common.utils.SSRJSONUtil.java

License:Apache License

/**
 * //from  w  w w . j  av a2s . c  o  m
 * @param ssr
 * The ssr parameter is the SSR object that contains data about the object to which it refers:
 *     the Warehouse URI (e.g. CATAGORY://gtdb/x/date),
 *     security (a document classification object ... which contains the visibility string),
 *     title (the name of the object)
 *     snippet (short description of the object)
 *     resultDate (date within the referenced object)
 *     coordinate (geographic location coordinate)
 *     preview (a thumbnail if the object is a mime type)
 * 
 * @param thriftObject
 * The thrift Object to translate to JSON.
 *    
 * @return
 *    The SSRJSON result.
 * 
 * @throws TException
 */
static public SSRJSON fromThriftAndSSR(SSR ssr, TBase thriftObject) throws TException {
    TSerializer ser = new TSerializer(new TSimpleJSONProtocol.Factory());
    return new SSRJSON(ssr, ser.toString(thriftObject));
}

From source file:ezbake.ins.thrift.impl.InternalNameServiceHandler.java

License:Apache License

private String getThriftJson(TBase thriftObject) throws TException {
    TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
    return serializer.toString(thriftObject);
}

From source file:ezbake.training.ElasticDatasetClient.java

License:Apache License

public void insertText(String text, String inputVisibility, String group) throws TException {
    EzElastic.Client elasticClient = null;
    EzGroups.Client groupClient = null;/* ww  w .ja  v a  2s  .co m*/

    try {
        EzSecurityToken token = securityClient.fetchTokenForProxiedUser();
        elasticClient = getThriftClient();

        Tweet tweet = new Tweet();
        tweet.setTimestamp(System.currentTimeMillis());
        tweet.setId(0);
        tweet.setText(text);
        tweet.setUserId(1);
        tweet.setUserName("test");
        tweet.setIsFavorite(new Random().nextBoolean());
        tweet.setIsRetweet(new Random().nextBoolean());

        TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
        String jsonContent = serializer.toString(tweet);

        final Document doc = new Document();
        doc.set_id(UUID.randomUUID().toString());
        doc.set_type("TEST");
        doc.set_jsonObject(jsonContent);

        Visibility visibility = new Visibility();
        visibility.setFormalVisibility(inputVisibility);

        System.out.println(group);

        if (!group.equals("none")) {
            groupClient = pool.getClient(EzGroupsConstants.SERVICE_NAME, EzGroups.Client.class);
            try {
                Group ezgroup;
                try {
                    EzSecurityToken groupsToken = securityClient
                            .fetchTokenForProxiedUser(pool.getSecurityId(EzGroupsConstants.SERVICE_NAME));
                    ezgroup = groupClient.getGroup(groupsToken, group);
                } catch (org.apache.thrift.transport.TTransportException e) {
                    throw new TException("User is not part of : " + group);
                }
                PlatformObjectVisibilities platformObjectVisibilities = new PlatformObjectVisibilities();
                platformObjectVisibilities.addToPlatformObjectWriteVisibility(ezgroup.getId());
                platformObjectVisibilities.addToPlatformObjectReadVisibility(ezgroup.getId());
                AdvancedMarkings advancedMarkings = new AdvancedMarkings();
                advancedMarkings.setPlatformObjectVisibility(platformObjectVisibilities);
                visibility.setAdvancedMarkings(advancedMarkings);
                visibility.setAdvancedMarkingsIsSet(true);
            } catch (TException ex) {
                ex.printStackTrace();
                throw ex;
            }
        }

        doc.setVisibility(visibility);
        elasticClient.put(doc, token);

        logger.info("Successful elastic client insert");
    } finally {
        if (elasticClient != null) {
            pool.returnToPool(elasticClient);
        }
        if (groupClient != null) {
            pool.returnToPool(groupClient);
        }
    }
}

From source file:ezbake.training.PostgresDatasetClient.java

License:Apache License

public void insertText(String text, String inputVisibility, String group) throws TException, SQLException {

    EzGroups.Client groupClient = null;/*from   ww w  . j a v  a2  s  .  com*/
    try {
        EzSecurityToken token = securityClient.fetchTokenForProxiedUser();

        Tweet tweet = new Tweet();
        tweet.setTimestamp(System.currentTimeMillis());
        tweet.setId(0);
        tweet.setText(text);
        tweet.setUserId(1);
        tweet.setUserName("test");
        tweet.setIsFavorite(new Random().nextBoolean());
        tweet.setIsRetweet(new Random().nextBoolean());

        TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
        String jsonContent = serializer.toString(tweet);

        PostgresConfigurationHelper helper = new PostgresConfigurationHelper(this.properties);
        Visibility visibility = new Visibility();
        visibility.setFormalVisibility(inputVisibility);

        if (!group.equals("none")) {
            groupClient = pool.getClient(EzGroupsConstants.SERVICE_NAME, EzGroups.Client.class);

            try {
                Group ezgroup;
                try {
                    EzSecurityToken groupsToken = securityClient
                            .fetchTokenForProxiedUser(pool.getSecurityId(EzGroupsConstants.SERVICE_NAME));
                    ezgroup = groupClient.getGroup(groupsToken, group);
                } catch (org.apache.thrift.transport.TTransportException e) {
                    throw new TException("User is not part of : " + group);
                }
                PlatformObjectVisibilities platformObjectVisibilities = new PlatformObjectVisibilities();
                platformObjectVisibilities.addToPlatformObjectWriteVisibility(ezgroup.getId());
                platformObjectVisibilities.addToPlatformObjectReadVisibility(ezgroup.getId());
                AdvancedMarkings advancedMarkings = new AdvancedMarkings();
                advancedMarkings.setPlatformObjectVisibility(platformObjectVisibilities);
                visibility.setAdvancedMarkings(advancedMarkings);
                visibility.setAdvancedMarkingsIsSet(true);
            } catch (Exception ex) {
                ex.printStackTrace();
                throw ex;
            }
        }
        try (Connection connection = helper.getEzPostgresConnection(token)) {
            try (PreparedStatement ps = connection
                    .prepareStatement("insert into tweets(tweet, visibility) values(?,?)")) {
                ps.setString(1, jsonContent);
                ps.setString(2, ThriftUtils.serializeToBase64(visibility));
                ps.execute();
            }
        }
        logger.info("Successful postgres client insert");
    } finally {
        if (groupClient != null) {
            pool.returnToPool(groupClient);
        }
        assert true;
    }
}

From source file:ezbake.training.TweetMongoStoreWorker.java

License:Apache License

private void insertTweet(Visibility visibility, Tweet tweet) throws TException {
    EzMongo.Client mongoClient = null;/*from  w  w  w. j  av  a2 s.com*/
    try {
        mongoClient = pool.getClient(EZMONGO, EzMongo.Client.class);

        TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
        String jsonContent = serializer.toString(tweet);

        final EzSecurityToken token;
        try {
            token = securityClient.fetchAppToken();
        } catch (TException e) {
            logger.error("An error occurred while obtaining the security token: {}\nProperties Dump: {}",
                    e.getMessage(), this.properties);
            logger.error("", e);
            throw new RuntimeException(e);
        }

        String result = mongoClient.insert("tweets", new MongoEzbakeDocument(jsonContent, visibility), token);
        logger.info("Successful mongo client insert {} with visibility {}", result, visibility);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new TException(e);
    } finally {
        pool.returnToPool(mongoClient);
    }
}

From source file:net.modelbased.proasense.storage.reader.StorageReaderMongoService.java

License:Apache License

@GET
@Path("/query/simple/default")
@Produces(MediaType.APPLICATION_JSON)//from ww  w  . j  ava 2  s. co m
public Response queryDefaultSimpleEvents(@QueryParam("sensorId") String sensorId,
        @QueryParam("startTime") long startTime, @QueryParam("endTime") long endTime) {
    String collectionId = "simple." + sensorId;

    ExecutorService executor = Executors.newFixedThreadPool(1);
    Callable<List<Document>> query = new EventReaderMongoSync(MONGODB_URL, MONGODB_DATABASE,
            EventQueryType.SIMPLE, collectionId, startTime, endTime, null, EventQueryOperation.DEFAULT, null);
    executor.submit(query);

    List<Document> queryResult = null;
    StringBuilder responseResult = new StringBuilder("[");
    try {
        queryResult = query.call();

        for (Document doc : queryResult) {
            SimpleEvent event = new EventConverter<SimpleEvent>(SimpleEvent.class, doc).getEvent();

            // Serialize event as JSON
            TSerializer serializer = new TSerializer(new TJSONProtocol.Factory());
            String jsonEvent = serializer.toString(event);

            responseResult.append(jsonEvent);
            responseResult.append(",");
        }
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Convert to string and remove trailing ","
    int responseLength = responseResult.length();
    if (responseLength > 1)
        responseResult.deleteCharAt(responseLength - 1);
    responseResult.append("]");
    String result = responseResult.toString();

    // Return HTTP response 200 in case of success
    return Response.status(200).entity(result).build();
}

From source file:net.modelbased.proasense.storage.reader.StorageReaderMongoService.java

License:Apache License

@GET
@Path("/query/derived/default")
@Produces(MediaType.APPLICATION_JSON)/*from  w w  w. j  a  v  a2 s.  c om*/
public Response queryDefaultDerivedEvents(@QueryParam("componentId") String componentId,
        @QueryParam("startTime") long startTime, @QueryParam("endTime") long endTime) {
    String collectionId = "derived." + componentId;

    ExecutorService executor = Executors.newFixedThreadPool(1);
    Callable<List<Document>> query = new EventReaderMongoSync(MONGODB_URL, MONGODB_DATABASE,
            EventQueryType.DERIVED, collectionId, startTime, endTime, null, EventQueryOperation.DEFAULT, null);
    executor.submit(query);

    List<Document> queryResult = null;
    StringBuilder responseResult = new StringBuilder("[");
    try {
        queryResult = query.call();

        for (Document doc : queryResult) {
            DerivedEvent event = new EventConverter<DerivedEvent>(DerivedEvent.class, doc).getEvent();

            // Serialize event as JSON
            TSerializer serializer = new TSerializer(new TJSONProtocol.Factory());
            String jsonEvent = serializer.toString(event);

            responseResult.append(jsonEvent);
            responseResult.append(",");
        }
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Convert to string and remove trailing ","
    int responseLength = responseResult.length();
    if (responseLength > 1)
        responseResult.deleteCharAt(responseLength - 1);
    responseResult.append("]");
    String result = responseResult.toString();

    // Return HTTP response 200 in case of success
    return Response.status(200).entity(result).build();
}

From source file:net.modelbased.proasense.storage.reader.StorageReaderMongoService.java

License:Apache License

@GET
@Path("/query/kpi/default")
@Produces(MediaType.APPLICATION_JSON)//from w  w w.  j  a v a 2 s . com
public Response queryDefaultKPIEvents(
        //            @QueryParam("componentId") String componentId,
        @QueryParam("kpiId") String kpiId, @QueryParam("startTime") long startTime,
        @QueryParam("endTime") long endTime) {
    String collectionId = "derived." + "KPI";

    ExecutorService executor = Executors.newFixedThreadPool(1);
    Callable<List<Document>> query = new EventReaderMongoSync(MONGODB_URL, MONGODB_DATABASE, EventQueryType.KPI,
            collectionId, startTime, endTime, kpiId, EventQueryOperation.DEFAULT, null);
    executor.submit(query);

    List<Document> queryResult = null;
    StringBuilder responseResult = new StringBuilder("[");
    try {
        queryResult = query.call();

        for (Document doc : queryResult) {
            DerivedEvent event = new EventConverter<DerivedEvent>(DerivedEvent.class, doc).getEvent();

            // Serialize event as JSON
            TSerializer serializer = new TSerializer(new TJSONProtocol.Factory());
            String jsonEvent = serializer.toString(event);

            responseResult.append(jsonEvent);
            responseResult.append(",");
        }
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Convert to string and remove trailing ","
    int responseLength = responseResult.length();
    if (responseLength > 1)
        responseResult.deleteCharAt(responseLength - 1);
    responseResult.append("]");
    String result = responseResult.toString();

    // Return HTTP response 200 in case of success
    return Response.status(200).entity(result).build();
}