Java Code Examples for org.apache.thrift.protocol.TJSONProtocol#Factory

The following examples show how to use org.apache.thrift.protocol.TJSONProtocol#Factory . 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: ThriftProtocolFactories.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the {@link SerializationFormat} for the specified {@link TProtocolFactory}.
 *
 * @throws IllegalArgumentException if the specified {@link TProtocolFactory} is not known by this class
 */
public static SerializationFormat toSerializationFormat(TProtocolFactory protoFactory) {
    requireNonNull(protoFactory, "protoFactory");

    if (protoFactory instanceof TBinaryProtocol.Factory) {
        return ThriftSerializationFormats.BINARY;
    } else if (protoFactory instanceof TCompactProtocol.Factory) {
        return ThriftSerializationFormats.COMPACT;
    } else if (protoFactory instanceof TJSONProtocol.Factory) {
        return ThriftSerializationFormats.JSON;
    } else if (protoFactory instanceof TTextProtocolFactory) {
        final TTextProtocolFactory factory = (TTextProtocolFactory) protoFactory;
        return factory.usesNamedEnums() ? ThriftSerializationFormats.TEXT_NAMED_ENUM
                                        : ThriftSerializationFormats.TEXT;
    } else {
        throw new IllegalArgumentException(
                "unsupported TProtocolFactory: " + protoFactory.getClass().getName());
    }
}
 
Example 2
Source File: ThriftUtil.java    From buck with Apache License 2.0 6 votes vote down vote up
public static TProtocolFactory getProtocolFactory(ThriftProtocol protocol) {
  // TODO(ruibm): Check whether the Factories are thread safe so we can static initialize
  // them just once.
  switch (protocol) {
    case JSON:
      return new TJSONProtocol.Factory();

    case COMPACT:
      return new TCompactProtocol.Factory();

    case BINARY:
      return new TBinaryProtocol.Factory();

    default:
      throw new IllegalArgumentException(
          String.format("Unknown ThriftProtocol [%s].", protocol.toString()));
  }
}
 
Example 3
Source File: CrossflowServlet.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
public CrossflowServlet() {
   super();
   
this.protocolFactory = new TJSONProtocol.Factory();
   this.processor = new Crossflow.Processor<>(new CrossflowHandler(this));
   this.customHeaders = new ArrayList<Map.Entry<String, String>>();
 }
 
Example 4
Source File: ThriftJobDaoImpl.java    From plow with Apache License 2.0 5 votes vote down vote up
@Override
public JobSpecT getJobSpec(UUID jobId) {

    final String json = jdbc.queryForObject("SELECT str_thrift_spec FROM job_history WHERE pk_job=?",
            String.class, jobId);

    final TDeserializer deserializer = new TDeserializer(new TJSONProtocol.Factory());
    final JobSpecT spec = new JobSpecT();
    try {
        deserializer.deserialize(spec, json.getBytes());
        return spec;
    } catch (TException e) {
        throw new JobSpecException("Failed to parse job spec " + e, e);
    }
}
 
Example 5
Source File: DemoClientTraditionalTEST.java    From nettythrift with Apache License 2.0 4 votes vote down vote up
@Test
public void test_AsyncClient() throws Throwable {
	Random rnd = new Random(System.nanoTime());

	TProtocolFactory[] protfacs = new TProtocolFactory[] { new TCompactProtocol.Factory(),
			new TBinaryProtocol.Factory(), new TJSONProtocol.Factory(),
			new TSimpleJSONProtocol.Factory(TCalculator.Iface.class, false) };

	TProtocolFactory protocolFactory = protfacs[rnd.nextInt(protfacs.length)];

	System.out.println("protocolFactory: " + protocolFactory);

	TAsyncClientManager clientManager = new TAsyncClientManager();
	TNonblockingTransport transport = new TNonblockingSocket(HOST, PORT);
	TCalculator.AsyncClient client = new TCalculator.AsyncClient(protocolFactory, clientManager, transport);
	final int num1 = rnd.nextInt(Integer.MAX_VALUE / 2 - 1);
	final int num2 = rnd.nextInt(Integer.MAX_VALUE / 2 - 1);

	final CountDownLatch latch = new CountDownLatch(1);
	final Throwable[] exceptions = new Throwable[1];
	AsyncMethodCallback<TCalculator.AsyncClient.add_call> resultHandler = new AsyncMethodCallback<TCalculator.AsyncClient.add_call>() {
		@Override
		public void onComplete(TCalculator.AsyncClient.add_call response) {
			System.out.println("onComplete!");
			try {
				int result = response.getResult();
				Assert.assertEquals(num1 + num2, result);
			} catch (Throwable e) {
				exceptions[0] = e;
			} finally {
				latch.countDown();
			}
		}

		@Override
		public void onError(Exception exception) {
			System.err.println("onError!");
			exception.printStackTrace();
			latch.countDown();
		}

	};
	client.add(num1, num2, resultHandler);
	latch.await();
	transport.close();
	if (exceptions[0] != null) {
		throw exceptions[0];
	}
}
 
Example 6
Source File: ThriftServer.java    From ThriftBook with Apache License 2.0 4 votes vote down vote up
public ThriftServer() {
    super(new TradeHistory.Processor(new TradeHistoryHandler()),
          new TJSONProtocol.Factory());
}
 
Example 7
Source File: JobDaoImpl.java    From plow with Apache License 2.0 4 votes vote down vote up
@Override
public FilterableJob create(final Project project, final JobSpecT spec, final boolean isPostJob) {

    final UUID jobId = UUID.randomUUID();
    final String name = createJobName(spec, isPostJob);

    jdbc.update(new PreparedStatementCreator() {
        @Override
        public PreparedStatement createPreparedStatement(final Connection conn) throws SQLException {
            final PreparedStatement ret = conn.prepareStatement(INSERT[0]);


            boolean paused = spec.isPaused();
            if (isPostJob) {
                paused = false;
            }

            ret.setObject(1, jobId);
            ret.setObject(2, project.getProjectId());
            ret.setString(3, name);
            ret.setString(4, name);
            ret.setString(5, spec.username);
            ret.setInt(6, spec.getUid());
            ret.setInt(7, JobState.INITIALIZE.ordinal());
            ret.setBoolean(8, paused);
            ret.setString(9, spec.logPath);
            ret.setObject(10, spec.attrs);
            ret.setObject(11, spec.env);
            ret.setBoolean(12, isPostJob);
            return ret;
        }
    });

    jdbc.update("INSERT INTO plow.job_count (pk_job) VALUES (?)", jobId);
    jdbc.update("INSERT INTO plow.job_dsp (pk_job) VALUES (?)", jobId);
    jdbc.update("INSERT INTO plow.job_stat (pk_job) VALUES (?)", jobId);

    // Serialize the spec into json.  Don't let a failure here stop
    // the job from launching.  This keeps the job spec around mainly
    // for troubleshooting.
    try {
        final TSerializer serializer = new TSerializer(new TJSONProtocol.Factory());
        final String json = serializer.toString(spec);

        jdbc.update("UPDATE plow.job_history SET str_thrift_spec=? WHERE pk_job=?",
                json, jobId);
    } catch (Exception e) {
        logger.warn("Failed to serialize thrift job spec to json: " + e, e);
    }


    final FilterableJob job = new FilterableJob();
    job.setJobId(jobId);
    job.setProjectId(project.getProjectId());
    job.setFolderId(null); // Don't know folder yet
    job.setName(name);
    job.username = spec.username;
    job.attrs = spec.attrs;
    return job;
}
 
Example 8
Source File: ThriftServlet.java    From plow with Apache License 2.0 4 votes vote down vote up
@Autowired
public ThriftServlet(RpcService.Iface service) {
	super(new RpcService.Processor<RpcService.Iface>(service), new TJSONProtocol.Factory());
}
 
Example 9
Source File: ApiModule.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
@Provides
@Singleton
TContentAwareServlet provideApiThriftServlet(AnnotatedAuroraAdmin schedulerThriftInterface) {
  /*
   * For backwards compatibility the servlet is configured to assume `application/x-thrift` and
   * `application/json` have TJSON bodies.
   *
   * Requests that have the registered MIME type for apache thrift are mapped to their respective
   * protocols. See
   * http://www.iana.org/assignments/media-types/application/vnd.apache.thrift.binary and
   * http://www.iana.org/assignments/media-types/application/vnd.apache.thrift.json for details.
   *
   * Responses have the registered MIME type so the client can decode appropriately.
   *
   * The Accept header is used to determine the response type. By default JSON is sent for any
   * value except for the binary thrift header.
   */

  ContentFactoryPair jsonFactory = new ContentFactoryPair(
      new TJSONProtocol.Factory(),
      THRIFT_JSON);
  ContentFactoryPair binFactory = new ContentFactoryPair(
      new TBinaryProtocol.Factory(),
      THRIFT_BINARY);

  // Which factory to use based on the Content-Type header of the request for reading the request.
  InputConfig inputConfig = new InputConfig(GENERIC_THRIFT, ImmutableMap.of(
      GENERIC_JSON, jsonFactory,
      GENERIC_THRIFT, jsonFactory,
      THRIFT_JSON, jsonFactory,
      THRIFT_JSON_UTF_8, jsonFactory,
      THRIFT_BINARY, binFactory
  ));

  // Which factory to use based on the Accept header of the request for the response.
  OutputConfig outputConfig = new OutputConfig(GENERIC_JSON, ImmutableMap.of(
      GENERIC_JSON, jsonFactory,
      GENERIC_THRIFT, jsonFactory,
      THRIFT_JSON, jsonFactory,
      THRIFT_JSON_UTF_8, jsonFactory,
      THRIFT_BINARY, binFactory
      ));

  // A request without a Content-Type (like from curl) should be treated as GENERIC_THRIFT
  return new TContentAwareServlet(
      new AuroraAdmin.Processor<>(schedulerThriftInterface),
      inputConfig,
      outputConfig);
}