List of usage examples for org.apache.thrift TProcessor process
public boolean process(TProtocol in, TProtocol out) throws TException;
From source file:com.alibaba.dubbo.rpc.protocol.thrift.ext.MultiServiceProcessor.java
License:Open Source License
public boolean process(TProtocol in, TProtocol out) throws TException { short magic = in.readI16(); if (magic != ThriftCodec.MAGIC) { logger.error(new StringBuilder(24).append("Unsupported magic ").append(magic).toString()); return false; }// w w w . j a v a2s. c om in.readI32(); in.readI16(); byte version = in.readByte(); String serviceName = in.readString(); long id = in.readI64(); ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); TIOStreamTransport transport = new TIOStreamTransport(bos); TProtocol protocol = protocolFactory.getProtocol(transport); TProcessor processor = processorMap.get(serviceName); if (processor == null) { logger.error(new StringBuilder(32).append("Could not find processor for service ").append(serviceName) .toString()); return false; } // todo if exception boolean result = processor.process(in, protocol); ByteArrayOutputStream header = new ByteArrayOutputStream(512); TIOStreamTransport headerTransport = new TIOStreamTransport(header); TProtocol headerProtocol = protocolFactory.getProtocol(headerTransport); headerProtocol.writeI16(magic); headerProtocol.writeI32(Integer.MAX_VALUE); headerProtocol.writeI16(Short.MAX_VALUE); headerProtocol.writeByte(version); headerProtocol.writeString(serviceName); headerProtocol.writeI64(id); headerProtocol.getTransport().flush(); out.writeI16(magic); out.writeI32(bos.size() + header.size()); out.writeI16((short) (0xffff & header.size())); out.writeByte(version); out.writeString(serviceName); out.writeI64(id); out.getTransport().write(bos.toByteArray()); out.getTransport().flush(); return result; }
From source file:com.cloudera.llama.server.TestClientPrincipalTProcessor.java
License:Apache License
@Test public void testSetGetPrincipal() throws Exception { invoked = false;//w w w . j a v a 2 s. c o m user = "foo"; SaslServer saslServer = Mockito.mock(SaslServer.class); Mockito.when(saslServer.getAuthorizationID()).thenReturn("foo"); MyTSaslServerTransport tst = Mockito.mock(MyTSaslServerTransport.class); Mockito.when(tst.getSaslServer()).thenReturn(saslServer); Mockito.when(tst.getSaslServer()).thenReturn(saslServer); TProtocol p = Mockito.mock(TProtocol.class); Mockito.when(p.getTransport()).thenReturn(tst); TProcessor cpTp = new ClientPrincipalTProcessor(this); Assert.assertNull(ClientPrincipalTProcessor.getPrincipal()); cpTp.process(p, p); Assert.assertTrue(invoked); Assert.assertNull(ClientPrincipalTProcessor.getPrincipal()); }
From source file:com.facebook.nifty.processor.NiftyProcessorAdapters.java
License:Apache License
/** * Adapt a {@link TProcessor} to a standard Thrift {@link NiftyProcessor}. Nifty uses this * internally to adapt the processors generated by the standard Thrift code generator into * instances of {@link NiftyProcessor} usable by {@link com.facebook.nifty.core.NiftyDispatcher} *///from w w w . jav a 2 s. c o m public static NiftyProcessor processorFromTProcessor(final TProcessor standardThriftProcessor) { checkProcessMethodSignature(); return new NiftyProcessor() { @Override public ListenableFuture<Boolean> process(TProtocol in, TProtocol out, RequestContext requestContext) throws TException { return Futures.immediateFuture(standardThriftProcessor.process(in, out)); } }; }
From source file:com.funtl.framework.rpc.thrift.spring.ThriftServiceExporter.java
License:Apache License
@Override public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!"POST".equals(request.getMethod())) { throw new HttpRequestMethodNotSupportedException(request.getMethod(), new String[] { "POST" }, "ThriftServiceExporter only supports POST requests"); }//from www . j av a2s . c o m InputStream in = request.getInputStream(); OutputStream out = response.getOutputStream(); try { ThriftContextHolder.init(); response.setContentType("application/x-thrift"); TTransport transport = new TIOStreamTransport(in, out); TProtocol protocol = getProtocolFactory().getProtocol(transport); TProcessor processor = ThriftUtil.buildProcessor(getServiceInterface(), getProxyForService()); processor.process(protocol, protocol); } catch (Throwable e) { response.setContentType("text/plain; charset=UTF-8"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); e.printStackTrace(new PrintWriter(out, true)); if (LOGGER.isErrorEnabled()) { LOGGER.error("Thrift server direct error", e); } } finally { ThriftContextHolder.reset(); } }
From source file:com.si.jupiter.smart.processor.SmartProcessorAdapters.java
License:Apache License
/** * ?,?TProcessor?/*from www .j a v a 2 s .c o m*/ * @param standardThriftProcessor * @return */ public static SmartProcessor processorFromTProcessor(final TProcessor standardThriftProcessor) { checkProcessMethodSignature(); return new SmartProcessor() { public ListenableFuture<Boolean> process(TProtocol in, TProtocol out, RequestContext requestContext) throws TException { return Futures.immediateFuture(standardThriftProcessor.process(in, out)); } }; }
From source file:org.apache.dubbo.rpc.protocol.thrift.ext.MultiServiceProcessor.java
License:Apache License
@Override public boolean process(TProtocol in, TProtocol out) throws TException { short magic = in.readI16(); if (magic != ThriftCodec.MAGIC) { logger.error("Unsupported magic " + magic); return false; }/* w w w .j a v a 2s . co m*/ in.readI32(); in.readI16(); byte version = in.readByte(); String serviceName = in.readString(); long id = in.readI64(); ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); TIOStreamTransport transport = new TIOStreamTransport(bos); TProtocol protocol = protocolFactory.getProtocol(transport); TProcessor processor = processorMap.get(serviceName); if (processor == null) { logger.error("Could not find processor for service " + serviceName); return false; } // todo if exception boolean result = processor.process(in, protocol); ByteArrayOutputStream header = new ByteArrayOutputStream(512); TIOStreamTransport headerTransport = new TIOStreamTransport(header); TProtocol headerProtocol = protocolFactory.getProtocol(headerTransport); headerProtocol.writeI16(magic); headerProtocol.writeI32(Integer.MAX_VALUE); headerProtocol.writeI16(Short.MAX_VALUE); headerProtocol.writeByte(version); headerProtocol.writeString(serviceName); headerProtocol.writeI64(id); headerProtocol.getTransport().flush(); out.writeI16(magic); out.writeI32(bos.size() + header.size()); out.writeI16((short) (0xffff & header.size())); out.writeByte(version); out.writeString(serviceName); out.writeI64(id); out.getTransport().write(bos.toByteArray()); out.getTransport().flush(); return result; }
From source file:org.apache.hadoop.hbase.thrift.ThriftServerRunner.java
License:Apache License
/** * Setting up the thrift TServer// w ww . jav a 2 s . c o m */ private void setupServer() throws Exception { // Construct correct ProtocolFactory TProtocolFactory protocolFactory; if (conf.getBoolean(COMPACT_CONF_KEY, false)) { LOG.debug("Using compact protocol"); protocolFactory = new TCompactProtocol.Factory(); } else { LOG.debug("Using binary protocol"); protocolFactory = new TBinaryProtocol.Factory(); } final TProcessor p = new Hbase.Processor<Hbase.Iface>(handler); ImplType implType = ImplType.getServerImpl(conf); TProcessor processor = p; // Construct correct TransportFactory TTransportFactory transportFactory; if (conf.getBoolean(FRAMED_CONF_KEY, false) || implType.isAlwaysFramed) { if (qop != null) { throw new RuntimeException( "Thrift server authentication" + " doesn't work with framed transport yet"); } transportFactory = new TFramedTransport.Factory(conf.getInt(MAX_FRAME_SIZE_CONF_KEY, 2) * 1024 * 1024); LOG.debug("Using framed transport"); } else if (qop == null) { transportFactory = new TTransportFactory(); } else { // Extract the name from the principal String name = SecurityUtil.getUserFromPrincipal(conf.get("hbase.thrift.kerberos.principal")); Map<String, String> saslProperties = new HashMap<String, String>(); saslProperties.put(Sasl.QOP, qop); TSaslServerTransport.Factory saslFactory = new TSaslServerTransport.Factory(); saslFactory.addServerDefinition("GSSAPI", name, host, saslProperties, new SaslGssCallbackHandler() { @Override public void handle(Callback[] callbacks) throws UnsupportedCallbackException { AuthorizeCallback ac = null; for (Callback callback : callbacks) { if (callback instanceof AuthorizeCallback) { ac = (AuthorizeCallback) callback; } else { throw new UnsupportedCallbackException(callback, "Unrecognized SASL GSSAPI Callback"); } } if (ac != null) { String authid = ac.getAuthenticationID(); String authzid = ac.getAuthorizationID(); if (!authid.equals(authzid)) { ac.setAuthorized(false); } else { ac.setAuthorized(true); String userName = SecurityUtil.getUserFromPrincipal(authzid); LOG.info("Effective user: " + userName); ac.setAuthorizedID(userName); } } } }); transportFactory = saslFactory; // Create a processor wrapper, to get the caller processor = new TProcessor() { @Override public boolean process(TProtocol inProt, TProtocol outProt) throws TException { TSaslServerTransport saslServerTransport = (TSaslServerTransport) inProt.getTransport(); SaslServer saslServer = saslServerTransport.getSaslServer(); String principal = saslServer.getAuthorizationID(); hbaseHandler.setEffectiveUser(principal); return p.process(inProt, outProt); } }; } if (conf.get(BIND_CONF_KEY) != null && !implType.canSpecifyBindIP) { LOG.error("Server types " + Joiner.on(", ").join(ImplType.serversThatCannotSpecifyBindIP()) + " don't support IP " + "address binding at the moment. See " + "https://issues.apache.org/jira/browse/HBASE-2155 for details."); throw new RuntimeException("-" + BIND_CONF_KEY + " not supported with " + implType); } if (implType == ImplType.HS_HA || implType == ImplType.NONBLOCKING || implType == ImplType.THREADED_SELECTOR) { InetAddress listenAddress = getBindAddress(conf); TNonblockingServerTransport serverTransport = new TNonblockingServerSocket( new InetSocketAddress(listenAddress, listenPort)); if (implType == ImplType.NONBLOCKING) { TNonblockingServer.Args serverArgs = new TNonblockingServer.Args(serverTransport); serverArgs.processor(processor).transportFactory(transportFactory).protocolFactory(protocolFactory); tserver = new TNonblockingServer(serverArgs); } else if (implType == ImplType.HS_HA) { THsHaServer.Args serverArgs = new THsHaServer.Args(serverTransport); CallQueue callQueue = new CallQueue(new LinkedBlockingQueue<Call>(), metrics); ExecutorService executorService = createExecutor(callQueue, serverArgs.getWorkerThreads()); serverArgs.executorService(executorService).processor(processor).transportFactory(transportFactory) .protocolFactory(protocolFactory); tserver = new THsHaServer(serverArgs); } else { // THREADED_SELECTOR TThreadedSelectorServer.Args serverArgs = new HThreadedSelectorServerArgs(serverTransport, conf); CallQueue callQueue = new CallQueue(new LinkedBlockingQueue<Call>(), metrics); ExecutorService executorService = createExecutor(callQueue, serverArgs.getWorkerThreads()); serverArgs.executorService(executorService).processor(processor).transportFactory(transportFactory) .protocolFactory(protocolFactory); tserver = new TThreadedSelectorServer(serverArgs); } LOG.info("starting HBase " + implType.simpleClassName() + " server on " + Integer.toString(listenPort)); } else if (implType == ImplType.THREAD_POOL) { // Thread pool server. Get the IP address to bind to. InetAddress listenAddress = getBindAddress(conf); TServerTransport serverTransport = new TServerSocket(new InetSocketAddress(listenAddress, listenPort)); TBoundedThreadPoolServer.Args serverArgs = new TBoundedThreadPoolServer.Args(serverTransport, conf); serverArgs.processor(processor).transportFactory(transportFactory).protocolFactory(protocolFactory); LOG.info("starting " + ImplType.THREAD_POOL.simpleClassName() + " on " + listenAddress + ":" + Integer.toString(listenPort) + "; " + serverArgs); TBoundedThreadPoolServer tserver = new TBoundedThreadPoolServer(serverArgs, metrics); this.tserver = tserver; } else { throw new AssertionError("Unsupported Thrift server implementation: " + implType.simpleClassName()); } // A sanity check that we instantiated the right type of server. if (tserver.getClass() != implType.serverClass) { throw new AssertionError("Expected to create Thrift server class " + implType.serverClass.getName() + " but got " + tserver.getClass().getName()); } registerFilters(conf); }
From source file:org.hawk.service.servlet.servlets.RequestAwareThriftServlet.java
License:Open Source License
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)// w ww . j a va2s . co m */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { TTransport inTransport = null; TTransport outTransport = null; try { response.setContentType("application/x-thrift"); if (null != this.customHeaders) { for (Map.Entry<String, String> header : this.customHeaders) { response.addHeader(header.getKey(), header.getValue()); } } InputStream in = request.getInputStream(); OutputStream out = response.getOutputStream(); TTransport transport = new TIOStreamTransport(in, out); inTransport = transport; outTransport = transport; TProtocol inProtocol = inProtocolFactory.getProtocol(inTransport); TProtocol outProtocol = outProtocolFactory.getProtocol(outTransport); final TProcessor processor = processorFactory.create(request); processor.process(inProtocol, outProtocol); out.flush(); } catch (TException te) { throw new ServletException(te); } }
From source file:org.ponder.serviceframework.ServiceRegister.CustomizedThriftMultipleProcessor.java
@Override public boolean process(TProtocol in, TProtocol out) throws TException { TMessage message = in.readMessageBegin(); if (message.type != TMessageType.CALL && message.type != TMessageType.ONEWAY) { // TODO Apache Guys - Can the server ever get an EXCEPTION or REPLY? // TODO Should we check for this here? throw new TException("This should not have happened!?"); }//from w w w .ja v a 2 s.co m String[] headers = message.name.split(SEPARATOR); String subject; String serviceName; String method; // Extract the service name if (headers.length < 2) { throw new TException("Service name not found in message name [" + message.name + "] Did you forget to use a TMultiplexProtocol in your client?"); } else if (headers.length == 3) { subject = headers[0]; serviceName = headers[1]; method = headers[2]; } else { subject = DEFAULT_SUBJECT; serviceName = headers[0]; method = headers[1]; } // Create a new TMessage, something that can be consumed by any // TProtocol TProcessor actualProcessor = SVRPROCESSORMAP.get(serviceName); if (actualProcessor == null) { throw new TException( "Service name not found: " + serviceName + ". Did you forget to call registerProcessor()?"); } // Create a new TMessage, removing the service name TMessage standardMessage = new TMessage(method, message.type, message.seqid); // Dispatch processing to the stored processor boolean result = false; boolean successed = true; try { result = actualProcessor.process(new StoredMessageProtocol(in, standardMessage), out); } catch (TException e) { successed = false; throw e; } finally { // } return result; }
From source file:org.thriftzmq.ServerWorker.java
License:Apache License
@Override protected void run() throws Exception { ZMQ.Context context = socketFactory.getContext(); ZMQ.Poller poller = context.poller(2); poller.register(transportSocket.getSocket(), ZMQ.Poller.POLLIN); poller.register(commandSocket.getSocket(), ZMQ.Poller.POLLIN); while (true) { poller.poll(POLL_TIMEOUT_MS); if (poller.pollin(0)) { TProtocol inputProtocol = inputProtocolFactory.getProtocol(transportSocket); TProtocol outputProtocol = outputProtocolFactory.getProtocol(transportSocket); TProcessor processor = processorFactory.getProcessor(transportSocket); try { processor.process(inputProtocol, outputProtocol); } catch (TException ex) { logger.error("Exception in request processor:", ex); throw ex; }/*from w ww . ja va 2 s . c om*/ } if (poller.pollin(1)) { byte cmd = commandSocket.recvCommand(); if (cmd == CommandSocket.STOP) { break; } } } }