org.apache.thrift.protocol.TSimpleJSONProtocol Java Examples

The following examples show how to use org.apache.thrift.protocol.TSimpleJSONProtocol. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LindenController.java    From linden with Apache License 2.0 5 votes vote down vote up
public static <T extends TBase> String ThriftToJSON(T thrift) {
  TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
  try {
    return serializer.toString(thrift);
  } catch (TException e) {
  }
  throw new IllegalStateException("Convert to json failed : " + thrift);
}
 
Example #2
Source File: SlaManagerTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
private AbstractHandler mockCoordinatorResponse(
    IScheduledTask task,
    String pollResponse,
    Map<String, String> params) {

  return new AbstractHandler() {
    @Override
    public void handle(
        String target,
        Request baseRequest,
        HttpServletRequest request,
        HttpServletResponse response) throws IOException {
      try {
        String taskKey = slaManager.getTaskKey(task);
        String query = Joiner
            .on("=")
            .join(SlaManager.TASK_PARAM, URLEncoder.encode(taskKey, "UTF-8"));

        String taskConfig = new TSerializer(new TSimpleJSONProtocol.Factory())
            .toString(task.newBuilder());
        JsonObject jsonBody = new JsonObject();
        jsonBody.add("taskConfig", new JsonParser().parse(taskConfig));
        jsonBody.addProperty(SlaManager.TASK_PARAM, taskKey);
        params.forEach(jsonBody::addProperty);
        String body = new Gson().toJson(jsonBody);

        if (request.getQueryString().equals(query)
            && request.getReader().lines().collect(Collectors.joining()).equals(body)) {
          createResponse(baseRequest, response, pollResponse);
        }
        coordinatorResponded.countDown();
      } catch (TException e) {
        fail();
      }
    }
  };
}
 
Example #3
Source File: ThriftUtil.java    From buck with Apache License 2.0 5 votes vote down vote up
public static String thriftToDebugJson(TBase<?, ?> thriftObject) {
  TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
  try {
    return new String(serializer.serialize(thriftObject));
  } catch (TException e) {
    LOGGER.error(
        e,
        String.format(
            "Failed trying to serialize type [%s] to debug JSON.",
            thriftObject.getClass().getName()));
    return "FAILED_TO_DESERIALIZE";
  }
}
 
Example #4
Source File: TestLogMessageProducer.java    From secor with Apache License 2.0 4 votes vote down vote up
public void run() {
    Properties properties = new Properties();
    if (mMetadataBrokerList == null || mMetadataBrokerList.isEmpty()) {
        properties.put("bootstrap.servers", "localhost:9092");
    } else {
        properties.put("bootstrap.severs", mMetadataBrokerList);
    }
    properties.put("value.serializer", ByteArraySerializer.class);
    properties.put("key.serializer", StringSerializer.class);
    properties.put("acks", "1");

    Producer<String, byte[]> producer = new KafkaProducer<>(properties);

    TProtocolFactory protocol = null;
    if(mType.equals("json")) {
        protocol = new TSimpleJSONProtocol.Factory();
    } else if (mType.equals("binary")) {
        protocol = new TBinaryProtocol.Factory();
    } else {
        throw new RuntimeException("Undefined message encoding type: " + mType);
    }

    TSerializer serializer = new TSerializer(protocol);
    for (int i = 0; i < mNumMessages; ++i) {
        long time = (System.currentTimeMillis() - mTimeshift * 1000L) * 1000000L + i;
        TestMessage testMessage = new TestMessage(time,
                                                  "some_value_" + i);
        if (i % 2 == 0) {
            testMessage.setEnumField(TestEnum.SOME_VALUE);
        } else {
            testMessage.setEnumField(TestEnum.SOME_OTHER_VALUE);
        }
        byte[] bytes;
        try {
            bytes = serializer.serialize(testMessage);
        } catch(TException e) {
            throw new RuntimeException("Failed to serialize message " + testMessage, e);
        }
        ProducerRecord<String, byte[]> data = new ProducerRecord<>(mTopic, Integer.toString(i), bytes);
        producer.send(data);
    }
    producer.close();
}
 
Example #5
Source File: SlaManager.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
private boolean coordinatorAllows(
    IScheduledTask task,
    String taskKey,
    ICoordinatorSlaPolicy slaPolicy,
    Map<String, String> params)
    throws InterruptedException, ExecutionException, TException {

  LOG.info("Checking coordinator: {} for task: {}", slaPolicy.getCoordinatorUrl(), taskKey);

  String taskConfig = new TSerializer(new TSimpleJSONProtocol.Factory())
      .toString(task.newBuilder());
  JsonObject jsonBody = new JsonObject();
  jsonBody.add("taskConfig", new JsonParser().parse(taskConfig));
  jsonBody.addProperty(TASK_PARAM, taskKey);
  params.forEach(jsonBody::addProperty);

  Response response = httpClient.preparePost(slaPolicy.getCoordinatorUrl())
      .setQueryParams(ImmutableList.of(new Param(TASK_PARAM, taskKey)))
      .setBody(new Gson().toJson(jsonBody))
      .execute()
      .get();

  if (response.getStatusCode() != HttpConstants.ResponseStatusCodes.OK_200) {
    LOG.error("Request failed to coordinator: {} for task: {}. Response: {}",
        slaPolicy.getCoordinatorUrl(),
        taskKey,
        response.getStatusCode());
    incrementErrorCount(USER_ERRORS_STAT_NAME, taskKey);
    return false;
  }

  successCounter.incrementAndGet();
  String json = response.getResponseBody();
  LOG.info("Got response: {} from {} for task: {}",
      json,
      slaPolicy.getCoordinatorUrl(),
      taskKey);

  Map<String, Boolean> result = new Gson().fromJson(
      json,
      new TypeReference<Map<String, Boolean>>() { }.getType());

  return result.get(slaPolicy.isSetStatusKey() ? slaPolicy.getStatusKey() : "drain");
}
 
Example #6
Source File: ThriftIO.java    From beam with Apache License 2.0 3 votes vote down vote up
/**
 * Specifies the {@link TProtocolFactory} to be used to decode Thrift objects.
 *
 * @param protocol {@link TProtocolFactory} used to decode Thrift objects.
 * @return ReadFiles object with protocol set.
 * @throws IllegalArgumentException if {@link TSimpleJSONProtocol} is passed as it is
 *     write-only.
 */
public ReadFiles<T> withProtocol(TProtocolFactory protocol) {
  checkArgument(
      !(protocol instanceof TSimpleJSONProtocol.Factory),
      "TSimpleJSONProtocol is a write only protocol");
  return toBuilder().setTProtocolFactory(protocol).build();
}