org.apache.thrift.protocol.TJSONProtocol Java Examples

The following examples show how to use org.apache.thrift.protocol.TJSONProtocol. 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: 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 #2
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 #3
Source File: MultiServiceServer.java    From ThriftBook with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws TTransportException, IOException, InterruptedException {
    TNonblockingServerSocket trans_svr = new TNonblockingServerSocket(9090);
    TMultiplexedProcessor proc = new TMultiplexedProcessor();
    proc.registerProcessor("Message", new Message.Processor<>(new MessageHandler()));
    proc.registerProcessor("ServerTime", new ServerTime.Processor<>(new ServerTimeHandler()));

    TServer server = new TThreadedSelectorServer(
            new TThreadedSelectorServer.Args(trans_svr)
            .processor(proc)
            .protocolFactory(new TJSONProtocol.Factory())
            .workerThreads(6)
            .selectorThreads(3));
    Thread server_thread = new Thread(new RunnableServer(server), "server_thread");
    server_thread.start();

    System.out.println("[Server] press enter to shutdown> ");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    br.readLine();
    System.out.println("[Server] shutting down...");
    server.stop();
    server_thread.join();
    System.out.println("[Server] down, exiting");
}
 
Example #4
Source File: ServerLoad.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
public static ServerLoad deserialize(byte[] data) throws IOException {
    org.apache.distributedlog.service.placement.thrift.ServerLoad tServerLoad =
        new org.apache.distributedlog.service.placement.thrift.ServerLoad();
    TMemoryInputTransport transport = new TMemoryInputTransport(data);
    TJSONProtocol protocol = new TJSONProtocol(transport);
    try {
        tServerLoad.read(protocol);
        ServerLoad serverLoad = new ServerLoad(tServerLoad.getServer());
        if (tServerLoad.isSetStreams()) {
            for (org.apache.distributedlog.service.placement.thrift.StreamLoad tStreamLoad :
                tServerLoad.getStreams()) {
                serverLoad.addStream(new StreamLoad(tStreamLoad.getStream(), tStreamLoad.getLoad()));
            }
        }
        return serverLoad;
    } catch (TException e) {
        throw new IOException("Failed to deserialize server load : ", e);
    }
}
 
Example #5
Source File: MultiServiceClient.java    From ThriftBook with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws TException {
    TTransport trans = new TFramedTransport(new TSocket("localhost", 9090));
    TProtocol proto = new TJSONProtocol(trans);

    TMultiplexedProtocol proto_msg = new TMultiplexedProtocol(proto, "Message");
    Message.Client client_msg = new Message.Client(proto_msg);
    TMultiplexedProtocol proto_time = new TMultiplexedProtocol(proto, "ServerTime");
    ServerTime.Client client_time = new ServerTime.Client(proto_time);

    trans.open();
    String line;
    do {
        System.out.println("Message from server: " + client_msg.motd());
        System.out.println("Time at server: " + client_time.time_at_server((short)-1));
        System.out.println("Enter to continue, 'q' to quit: ");
        line = System.console().readLine();
    } while (0 != line.compareToIgnoreCase("q"));   
}
 
Example #6
Source File: ZKAccessControl.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
static byte[] serialize(AccessControlEntry ace) throws IOException {
    TMemoryBuffer transport = new TMemoryBuffer(BUFFER_SIZE);
    TJSONProtocol protocol = new TJSONProtocol(transport);
    try {
        ace.write(protocol);
        transport.flush();
        return transport.toString(UTF_8.name()).getBytes(UTF_8);
    } catch (TException e) {
        throw new IOException("Failed to serialize access control entry : ", e);
    } catch (UnsupportedEncodingException uee) {
        throw new IOException("Failed to serialize acesss control entry : ", uee);
    }
}
 
Example #7
Source File: DefaultThriftConnection.java    From Thrift-Connection-Pool with Apache License 2.0 5 votes vote down vote up
/**
 * 根据配置创建thrift管道的方法
 * 
 */
private TProtocol createTProtocol(TTransport transport) {
	if (tProtocolType == TProtocolType.BINARY) {
		return new TBinaryProtocol(transport);
	} else if (tProtocolType == TProtocolType.JSON) {
		return new TJSONProtocol(transport);
	}
	throw new IllegalStateException("暂不支持的管道类型:" + tProtocolType);
}
 
Example #8
Source File: ZKAccessControl.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
static AccessControlEntry deserialize(String zkPath, byte[] data) throws IOException {
    if (data.length == 0) {
        return DEFAULT_ACCESS_CONTROL_ENTRY;
    }

    AccessControlEntry ace = new AccessControlEntry();
    TMemoryInputTransport transport = new TMemoryInputTransport(data);
    TJSONProtocol protocol = new TJSONProtocol(transport);
    try {
        ace.read(protocol);
    } catch (TException e) {
        throw new CorruptedAccessControlException(zkPath, e);
    }
    return ace;
}
 
Example #9
Source File: ThriftCodec.java    From singer with Apache License 2.0 5 votes vote down vote up
/**
 * Serialize a thrift object as JSON.
 *
 * @param obj A thrift object.
 */
public static <T extends TBase> String serializeJson(T obj) throws TException {
  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  obj.write(new TJSONProtocol(new TIOStreamTransport(byteArrayOutputStream)));
  try {
    return byteArrayOutputStream.toString("UTF-8");
  } catch (UnsupportedEncodingException e) {
    throw new TException(e);
  }
}
 
Example #10
Source File: MulitServiceThriftConnecion.java    From Thrift-Connection-Pool with Apache License 2.0 5 votes vote down vote up
/**
 * 根据配置创建thrift管道的方法
 * 
 */
private TProtocol createTProtocol(TTransport transport) {
	if (tProtocolType == TProtocolType.BINARY) {
		return new TBinaryProtocol(transport);
	} else if (tProtocolType == TProtocolType.JSON) {
		return new TJSONProtocol(transport);
	}
	throw new IllegalStateException("暂不支持的管道类型:" + tProtocolType);
}
 
Example #11
Source File: FactoryServer.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws TTransportException {
  TServerSocket trans_svr = new TServerSocket(9090);
  TProcessor proc = new Message.Processor<>(new MessageHandler());
  
  TServer server = new TThreadPoolServer(
          new TThreadPoolServer.Args(trans_svr)
            .processor(proc)
            .protocolFactory(new TJSONProtocol.Factory())
            .inputTransportFactory(new TFramedTransport.Factory())
            .outputTransportFactory(new TWritelogTransportFactory(100)));
  server.serve();
}
 
Example #12
Source File: FactoryClient.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws TException {
    TTransport trans = new TFramedTransport(new TSocket("localhost", 9090));
    TProtocol proto = new TJSONProtocol(trans);
    Message.Iface client = new Message.Client(proto);
    trans.open();
    String line;
    do {
        System.out.println("Message from server: " + client.motd());
        System.out.println("Enter to continue, 'q' to quit: ");
        line = System.console().readLine();
    } while (0 != line.compareToIgnoreCase("q"));
}
 
Example #13
Source File: ThriftClient.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) 
        throws IOException, TException {
    THttpClient trans = new THttpClient("http://localhost:8080/thrift-servlet");
    TJSONProtocol proto = new TJSONProtocol(trans);
    TradeHistory.Client client = new TradeHistory.Client(proto);

    for (int i = 0; i < 1000000; i++) {
        trans.open();
        TradeReport tr = client.get_last_sale("AAPL");
        trans.close();
    }
}
 
Example #14
Source File: ThriftServer.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args)
        throws TTransportException, IOException {
    TradeHistory.Processor proc = 
        new TradeHistory.Processor(new TradeHistoryHandler());
    TServerSocket trans_svr = 
        new TServerSocket(9090);
    TThreadPoolServer server = 
        new TThreadPoolServer(new TThreadPoolServer.Args(trans_svr)
                .protocolFactory(new TJSONProtocol.Factory())
                .processor(proc));
    System.out.println("[Server] listening of port 9090");
    server.serve();
}
 
Example #15
Source File: ThriftClient.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) 
        throws IOException, TException {
    TSocket trans = new TSocket("localhost", 9090);
    TJSONProtocol proto = new TJSONProtocol(trans);
    TradeHistory.Client client = new TradeHistory.Client(proto);

    trans.open();
    for (int i = 0; i < 1000000; i++) {
        TradeReport tr = client.get_last_sale("APPL");
    }
    trans.close();
}
 
Example #16
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 #17
Source File: DataCompatibilityTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
private static String serialize(Op op) {
  try {
    String unformattedJson =
        new String(new TSerializer(new TJSONProtocol.Factory()).serialize(op), UTF_8);

    // Pretty print the json for easier review of diffs.
    return new GsonBuilder().setPrettyPrinting().create()
        .toJson(new JsonParser().parse(unformattedJson)) + "\n";
  } catch (TException e) {
    throw new RuntimeException(e);
  }
}
 
Example #18
Source File: DataCompatibilityTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
private static Op deserialize(String serializedOp) {
  try {
    Op op = new Op();

    String nonPrettyJson = new GsonBuilder().create()
        .toJson(new JsonParser().parse(serializedOp));

    new TDeserializer(new TJSONProtocol.Factory())
        .deserialize(op, nonPrettyJson.getBytes(UTF_8));
    return op;
  } catch (TException e) {
    throw new RuntimeException(e);
  }
}
 
Example #19
Source File: ThriftCodec.java    From singer with Apache License 2.0 5 votes vote down vote up
/**
 * Deserialize a thrift object encoded using the TJSONProtocol
 */
public static <T extends TBase> T deserializeJson(String jsonValue, Class<T> thriftClass)
    throws TException {
  ByteArrayInputStream byteArrayInputStream =
      new ByteArrayInputStream(jsonValue.getBytes(Charsets.UTF_8));
  try {
    T obj = thriftClass.newInstance();
    obj.read(new TJSONProtocol(new TIOStreamTransport(byteArrayInputStream)));
    return obj;
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example #20
Source File: ZKAccessControl.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
static AccessControlEntry deserialize(String zkPath, byte[] data) throws IOException {
    if (data.length == 0) {
        return DEFAULT_ACCESS_CONTROL_ENTRY;
    }

    AccessControlEntry ace = new AccessControlEntry();
    TMemoryInputTransport transport = new TMemoryInputTransport(data);
    TJSONProtocol protocol = new TJSONProtocol(transport);
    try {
        ace.read(protocol);
    } catch (TException e) {
        throw new CorruptedAccessControlException(zkPath, e);
    }
    return ace;
}
 
Example #21
Source File: ZKAccessControl.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
static byte[] serialize(AccessControlEntry ace) throws IOException {
    TMemoryBuffer transport = new TMemoryBuffer(BUFFER_SIZE);
    TJSONProtocol protocol = new TJSONProtocol(transport);
    try {
        ace.write(protocol);
        transport.flush();
        return transport.toString(UTF_8.name()).getBytes(UTF_8);
    } catch (TException e) {
        throw new IOException("Failed to serialize access control entry : ", e);
    } catch (UnsupportedEncodingException uee) {
        throw new IOException("Failed to serialize acesss control entry : ", uee);
    }
}
 
Example #22
Source File: StreamLoad.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
public static StreamLoad deserialize(byte[] data) throws IOException {
    org.apache.distributedlog.service.placement.thrift.StreamLoad tStreamLoad =
        new org.apache.distributedlog.service.placement.thrift.StreamLoad();
    TMemoryInputTransport transport = new TMemoryInputTransport(data);
    TJSONProtocol protocol = new TJSONProtocol(transport);
    try {
        tStreamLoad.read(protocol);
        return new StreamLoad(tStreamLoad.getStream(), tStreamLoad.getLoad());
    } catch (TException e) {
        throw new IOException("Failed to deserialize stream load : ", e);
    }
}
 
Example #23
Source File: StreamLoad.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
public byte[] serialize() throws IOException {
    TMemoryBuffer transport = new TMemoryBuffer(BUFFER_SIZE);
    TJSONProtocol protocol = new TJSONProtocol(transport);
    try {
        toThrift().write(protocol);
        transport.flush();
        return transport.toString(UTF_8.name()).getBytes(UTF_8);
    } catch (TException e) {
        throw new IOException("Failed to serialize stream load : ", e);
    } catch (UnsupportedEncodingException uee) {
        throw new IOException("Failed to serialize stream load : ", uee);
    }
}
 
Example #24
Source File: ServerLoad.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
public byte[] serialize() throws IOException {
    TMemoryBuffer transport = new TMemoryBuffer(BUFFER_SIZE);
    TJSONProtocol protocol = new TJSONProtocol(transport);
    try {
        toThrift().write(protocol);
        transport.flush();
        return transport.toString(UTF_8.name()).getBytes(UTF_8);
    } catch (TException e) {
        throw new IOException("Failed to serialize server load : ", e);
    } catch (UnsupportedEncodingException uee) {
        throw new IOException("Failed to serialize server load : ", uee);
    }
}
 
Example #25
Source File: IkasoaFactoryFactory.java    From ikasoa with MIT License 5 votes vote down vote up
public IkasoaFactory getIkasoaServletFactory() {
	ThriftServerConfiguration config = Optional.ofNullable(configurator).map(c -> c.getThriftServerConfiguration())
			.orElse(new ThriftServerConfiguration());
	config.setProtocolFactory(new TJSONProtocol.Factory()); // Servlet需要使用Json协议
	configurator.setThriftServerConfiguration(config);
	return new ServletServerIkasoaFactory(configurator);
}
 
Example #26
Source File: ProtocolFactorySelector.java    From nettythrift with Apache License 2.0 5 votes vote down vote up
public ProtocolFactorySelector(@SuppressWarnings("rawtypes") Class interfaceClass) {
	protocolFactoryMap.put((short) -32767, new TBinaryProtocol.Factory());
	protocolFactoryMap.put((short) -32223, new TCompactProtocol.Factory());
	protocolFactoryMap.put((short) 23345, new TJSONProtocol.Factory());
	if (interfaceClass != null) {
		protocolFactoryMap.put((short) 23330, new TSimpleJSONProtocol.Factory(interfaceClass));
	}
}
 
Example #27
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 #28
Source File: CrossflowWebTests.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
	transport = new THttpClient("http://localhost:8080/org.eclipse.scava.crossflow.web/thrift");
	transport.open();
	TProtocol protocol = new TJSONProtocol(transport); // JSON transport forma
	client = new Crossflow.Client(protocol);
}
 
Example #29
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 #30
Source File: FuzzerServer.java    From graphicsfuzz with Apache License 2.0 4 votes vote down vote up
public void start() throws Exception {

    FuzzerServiceImpl fuzzerService = new FuzzerServiceImpl(
        Paths.get(workingDir, processingDir).toString(),
        executorService);

    FuzzerService.Processor processor =
        new FuzzerService.Processor<FuzzerService.Iface>(fuzzerService);

    FuzzerServiceManagerImpl fuzzerServiceManager = new FuzzerServiceManagerImpl(fuzzerService,
          new PublicServerCommandDispatcher());
    FuzzerServiceManager.Processor managerProcessor =
        new FuzzerServiceManager.Processor<FuzzerServiceManager.Iface>(fuzzerServiceManager);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");

    {
      ServletHolder sh = new ServletHolder();
      sh.setServlet(new TServlet(processor, new TBinaryProtocol.Factory()));
      context.addServlet(sh, "/request");
    }
    {
      ServletHolder serveltHolderJson = new ServletHolder();
      serveltHolderJson.setServlet(new TServlet(processor, new TJSONProtocol.Factory()));
      context.addServlet(serveltHolderJson, "/requestJSON");
    }

    {
      ServletHolder shManager = new ServletHolder();
      shManager.setServlet(new TServlet(managerProcessor, new TBinaryProtocol.Factory()));
      context.addServlet(shManager, "/manageAPI");
    }

    final String staticDir = ToolPaths.getStaticDir();
    context.addServlet(
          new ServletHolder(
                new FileDownloadServlet(
                    (pathInfo, worker) -> Paths.get(staticDir, pathInfo).toFile(), staticDir)),
          "/static/*");

    HandlerList handlerList = new HandlerList();
    handlerList.addHandler(context);

    GzipHandler gzipHandler = new GzipHandler();
    gzipHandler.setHandler(handlerList);

    Server server = new Server(port);

    server.setHandler(gzipHandler);
    server.start();
    server.join();
  }