Java Code Examples for org.apache.thrift.transport.TTransport#close()

The following examples show how to use org.apache.thrift.transport.TTransport#close() . 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: ThriftITest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
  final CountDownLatch latch = TestUtil.initExpectedSpanLatch(2);
  final TServerTransport serverTransport = new TServerSocket(port);
  final TServer server = startNewThreadPoolServer(serverTransport);

  final TTransport transport = new TSocket("localhost", port);
  transport.open();

  final TProtocol protocol = new TBinaryProtocol(transport);

  final CustomService.Client client = new CustomService.Client(protocol);
  final String res = client.say("one", "two");
  if (!"Say one two".equals(res))
    throw new AssertionError("ERROR: wrong result");

  TestUtil.checkSpan(latch, new ComponentSpanCount("java-thrift", 2, true));

  server.stop();
  transport.close();
}
 
Example 2
Source File: ServerTrans.java    From ThriftBook with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) 
       throws TTransportException, UnsupportedEncodingException {
    final String msg = "Hello Thrift!\n";
    final String stop_cmd = "STOP";
    final int buf_size = 1024*8;
    byte[] buf = new byte[buf_size];
    final int port = 9090;

    TServerTransport acceptor = new TServerSocket(9090);
    acceptor.listen();
    System.out.println("[Server] listening on port: " + port);
    
    String input;
    do {
        TTransport trans = acceptor.accept();
        int len = trans.read(buf, 0, buf_size);
        input = new String(buf, 0, len,"UTF-8");
        System.out.println("[Server] handling request: " + input);
        trans.write(msg.getBytes());
        trans.flush();
        trans.close();
    } while (! stop_cmd.regionMatches(0, input, 0, 4)); 

    System.out.println("[Server] exiting");
    acceptor.close();
}
 
Example 3
Source File: ThriftBinaryCodec.java    From attic-aurora with Apache License 2.0 6 votes vote down vote up
/**
 * Encodes a thrift object into a DEFLATE-compressed binary array.
 *
 * @param tBase Object to encode.
 * @return Deflated, encoded object.
 * @throws CodingException If the object could not be encoded.
 */
public static byte[] deflateNonNull(TBase<?, ?> tBase) throws CodingException {
  requireNonNull(tBase);

  // NOTE: Buffering is needed here for performance.
  // There are actually 2 buffers in play here - the BufferedOutputStream prevents thrift from
  // causing a call to deflate() on every encoded primitive. The DeflaterOutputStream buffer
  // allows the underlying Deflater to operate on a larger chunk at a time without stopping to
  // copy the intermediate compressed output to outBytes.
  // See http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4986239
  ByteArrayOutputStream outBytes = new ByteArrayOutputStream();
  TTransport transport = new TIOStreamTransport(
      new BufferedOutputStream(
          new DeflaterOutputStream(outBytes, new Deflater(DEFLATE_LEVEL), DEFLATER_BUFFER_SIZE),
          DEFLATER_BUFFER_SIZE));
  try {
    TProtocol protocol = PROTOCOL_FACTORY.getProtocol(transport);
    tBase.write(protocol);
    transport.close(); // calls finish() on the underlying stream, completing the compression
    return outBytes.toByteArray();
  } catch (TException e) {
    throw new CodingException("Failed to serialize: " + tBase, e);
  } finally {
    transport.close();
  }
}
 
Example 4
Source File: AbstractMultiRequestTest.java    From disruptor_thrift_server with Apache License 2.0 6 votes vote down vote up
@Test
public void multiRequestTest() throws Exception
{
    TTransport transport = getNewTransport();

    try
    {
        TestService.Client client = getNewClient(transport);

        for (int i = 0; i < REQUESTS; i += 4)
            invokeRequests(client, i, getRandomArgument(), getRandomArgument());
    }
    finally
    {
        transport.close();
    }
}
 
Example 5
Source File: DiskSerZ.java    From ThriftBook with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    TTransport trans = null;
    try {
        System.out.println("Radio Observation Disk Serializer " + radio_observationConstants.Version);
        trans = new TSimpleFileTransport("data.z", true, true);
        trans = new TZlibTransport(trans);
        trans.open();
        TProtocol proto = new TBinaryProtocol(trans);
        if (args.length > 0 && 0 == args[0].compareTo("write")) {
            WriteRadioObservation(proto, args.length > 1);
        } else if (args.length>0 && 0==args[0].compareToIgnoreCase("read")) {
            ReadRadioObservation(proto);
        } else {
            System.out.println("Usage: DiskSer (read | write [bmp])");
        }
    } catch (TException | IOException ex) {
        System.out.println("Error: " + ex.getMessage());
    }
    if (null != trans) {
        trans.close();
    }
}
 
Example 6
Source File: Schema.java    From janusgraph_tutorial with Apache License 2.0 5 votes vote down vote up
private void dropOldKeyspace() throws InvalidRequestException, SchemaDisagreementException, TException {
  TTransport tr = new TFramedTransport(new TSocket("localhost", 9160));
  TProtocol proto = new TBinaryProtocol(tr);
  Cassandra.Client client = new Cassandra.Client(proto);
  tr.open();

  client.system_drop_keyspace(JANUSGRAPH);
  LOGGER.info("DROPPED keyspace janusgraph");
  tr.close();
}
 
Example 7
Source File: ServerFrame.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) 
         throws TTransportException, UnsupportedEncodingException, SocketException {
     final String msg = "Hello Thrift!\n";
     final String stop_cmd = "STOP";
     final int buf_size = 1024*8;
     byte[] buf = new byte[buf_size];
     final int port = 9090;

     TServerTransport acceptor = new TServerSocket(port);
     acceptor.listen();
     System.out.println("[Server] listening on port " + port);

     while (true) {
         TTransport trans_ep = acceptor.accept();
TTransport trans = new TFramedTransport(trans_ep);
         int len = trans.read(buf, 0, buf_size);
         String input = new String(buf, 0, len, "UTF-8");
         System.out.println("[Server] handling request: " + input);
         trans.write(msg.getBytes());
         trans.flush();
         trans.close();
         if (stop_cmd.regionMatches(0, input, 0, 4)) {
            break;
         }
     }
     System.out.println("[Server] exiting");
     acceptor.close();
 }
 
Example 8
Source File: SimpleClient.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 TSocket("localhost", 9090);
    TProtocol proto = new TBinaryProtocol(trans);
    SocialLookup.Iface client = new SocialLookup.Client(proto);

    trans.open();
    System.out.println("Number 1 site: " + client.GetSiteByRank(1));
    System.out.println("Twitter rank : " + client.GetSiteRankByName("Twitter"));
    trans.close();
}
 
Example 9
Source File: TFactoryBasedThreadPoolServer.java    From RDFS with Apache License 2.0 5 votes vote down vote up
/**
 * Loops on processing a client forever
 */
public void run() {
  TProcessor processor = null;
  TTransport inputTransport = null;
  TTransport outputTransport = null;
  TProtocol inputProtocol = null;
  TProtocol outputProtocol = null;
  try {
    processor = processorFactory_.getProcessor(client_);
    inputTransport = inputTransportFactory_.getTransport(client_);
    outputTransport = outputTransportFactory_.getTransport(client_);
    inputProtocol = inputProtocolFactory_.getProtocol(inputTransport);
    outputProtocol = outputProtocolFactory_.getProtocol(outputTransport);
    // we check stopped_ first to make sure we're not supposed to be shutting
    // down. this is necessary for graceful shutdown.
    while (!stopped_ && processor.process(inputProtocol, outputProtocol)) {}
  } catch (TTransportException ttx) {
    // Assume the client died and continue silently
  } catch (TException tx) {
    LOG.error("Thrift error occurred during processing of message.", tx);
  } catch (Exception x) {
    LOG.error("Error occurred during processing of message.", x);
  }

  if (inputTransport != null) {
    inputTransport.close();
  }

  if (outputTransport != null) {
    outputTransport.close();
  }
}
 
Example 10
Source File: TransExcep.java    From ThriftBook with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
     try {
         TTransport trans = new TSimpleFileTransport("data", false, true);
         Trade trade = new Trade();
         trade.symbol = "F";
         trade.price = 13.10;
         trade.size = 2500;
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(baos);
         oos.writeObject(trade);
         trans.write(baos.toByteArray());
trans.close();

         trans = new TSimpleFileTransport("data",
                                      ((args.length==0) ? true : false), 
                                      true);			
         byte[] buf = new byte[128];
         int iBytesRead = trans.read(buf, 0, buf.length);
         ByteArrayInputStream bais = new ByteArrayInputStream(buf);
         ObjectInputStream ois = new ObjectInputStream(bais);
         trade = (Trade) ois.readObject();
         System.out.println("Trade(" + iBytesRead + "): " + trade.symbol + " " + 
                            trade.size + " @ " + trade.price);
     } catch (TTransportException tte) {				
         System.out.println("TTransportException(" + tte.getType() + 
                            "): " + tte);
     } catch (TException te) {						
         System.out.println("TException: " + te);
     } catch (Exception e) {						
         System.out.println("Exception: " + e);
     } catch (Throwable t) {						
         System.out.println("Throwable: " + t);			
     }
 }
 
Example 11
Source File: TBoundedThreadPoolServer.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Loops on processing a client forever
 */
@Override
public void run() {
  TProcessor processor = null;
  TTransport inputTransport = null;
  TTransport outputTransport = null;
  TProtocol inputProtocol = null;
  TProtocol outputProtocol = null;
  try {
    processor = processorFactory_.getProcessor(client);
    inputTransport = inputTransportFactory_.getTransport(client);
    outputTransport = outputTransportFactory_.getTransport(client);
    inputProtocol = inputProtocolFactory_.getProtocol(inputTransport);
    outputProtocol = outputProtocolFactory_.getProtocol(outputTransport);
    // we check stopped_ first to make sure we're not supposed to be shutting
    // down. this is necessary for graceful shutdown.
    while (true) {
      if (stopped) {
        break;
      }
      processor.process(inputProtocol, outputProtocol);
    }
  } catch (TTransportException ttx) {
    // Assume the client died and continue silently
  } catch (TException tx) {
    LOG.error("Thrift error occurred during processing of message.", tx);
  } catch (Exception x) {
    LOG.error("Error occurred during processing of message.", x);
  }

  if (inputTransport != null) {
    inputTransport.close();
  }

  if (outputTransport != null) {
    outputTransport.close();
  }
}
 
Example 12
Source File: DefaultThriftConnectionPoolImpl.java    From thrift-pool-client with Artistic License 2.0 5 votes vote down vote up
@Override
public void destroyObject(ThriftServerInfo info, PooledObject<TTransport> p) {
    TTransport transport = p.getObject();
    if (transport != null && transport.isOpen()) {
        transport.close();
        logger.trace("close thrift connection:{}", info);
    }
}
 
Example 13
Source File: ConsumerPoolFactory.java    From ourea with Apache License 2.0 5 votes vote down vote up
@Override
public void destroyObject(PooledObject<TTransport> p) throws Exception {

    try {
        TTransport transport = p.getObject();
        if (transport.isOpen()) {
            transport.close();
        }
    } catch (Exception e) {
        LOGGER.error("destroy transport object fail.maybe exist memory leek.e:", e);
        throw new OureaException("destroy transport object fail" + e.getMessage());
    }

}
 
Example 14
Source File: AbstractColumnFamilyRecordWriter.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
protected void closeInternal()
{
    if (client != null)
    {
        TTransport transport = client.getOutputProtocol().getTransport();
        if (transport.isOpen())
            transport.close();
    }
}
 
Example 15
Source File: ThriftConnectionFactory.java    From ThriftJ with Apache License 2.0 5 votes vote down vote up
@Override
public void destroyObject(ThriftServer thriftServer, PooledObject<TTransport> pooledObject) throws Exception {
	TTransport transport = pooledObject.getObject();
	if (transport != null) {
		transport.close();
		logger.trace("Close thrift connection: {}:{}", thriftServer.getHost(), thriftServer.getPort());
	}
}
 
Example 16
Source File: ColumnFamilyRecordReader.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public void close()
{
    if (client != null)
    {
        TTransport transport = client.getOutputProtocol().getTransport();
        if (transport.isOpen())
            transport.close();
    }
}
 
Example 17
Source File: GfxdThriftServerThreadPool.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Loops on processing a client forever
 */
@Override
public void run() {
  TProcessor processor = null;
  TTransport inputTransport = null;
  TTransport outputTransport = null;
  TProtocol inputProtocol = null;
  TProtocol outputProtocol = null;

  final TServerEventHandler eventHandler = getEventHandler();
  ServerContext connectionContext = null;

  final ConnectionListener listener = connListener;
  final TTransport client = this.client;
  Socket clientSocket = null;

  try {
    processor = processorFactory_.getProcessor(client);
    inputTransport = inputTransportFactory_.getTransport(client);
    outputTransport = outputTransportFactory_.getTransport(client);
    inputProtocol = inputProtocolFactory_.getProtocol(inputTransport);
    outputProtocol = outputProtocolFactory_.getProtocol(outputTransport);

    if (eventHandler != null) {
      connectionContext = eventHandler.createContext(inputProtocol,
          outputProtocol);
    }
    // register with ConnectionListener
    if (listener != null) {
      if (client instanceof GfxdTSocket) {
        clientSocket = ((GfxdTSocket)client).getSocket();
      }
      else if (client instanceof TSocket) {
        clientSocket = ((TSocket)client).getSocket();
      }
      listener.connectionOpened(clientSocket, this.connectionNumber);
    }
    // we check stopped_ first to make sure we're not supposed to be
    // shutting down. this is necessary for graceful shutdown.
    while (true) {

      if (eventHandler != null) {
        eventHandler.processContext(connectionContext, inputTransport,
            outputTransport);
      }

      if (stopped || !processor.process(inputProtocol, outputProtocol)) {
        break;
      }
    }
  } catch (TTransportException tte) {
    // Assume the client died and continue silently
  } catch (TException te) {
    LOGGER.error("Thrift error occurred during processing of message.", te);
  } catch (Exception e) {
    LOGGER.error("Error occurred during processing of message.", e);
  }

  if (eventHandler != null) {
    eventHandler.deleteContext(connectionContext, inputProtocol,
        outputProtocol);
  }

  if (inputTransport != null) {
    inputTransport.close();
  }

  if (outputTransport != null) {
    outputTransport.close();
  }

  // deregister with ConnectionListener
  if (listener != null) {
    listener.connectionClosed(clientSocket, this.connectionNumber);
  }
}
 
Example 18
Source File: HttpDoAsClient.java    From hbase with Apache License 2.0 4 votes vote down vote up
private void run() throws Exception {
  TTransport transport = new TSocket(host, port);

  transport.open();
  String url = "http://" + host + ":" + port;
  THttpClient httpClient = new THttpClient(url);
  httpClient.open();
  TProtocol protocol = new TBinaryProtocol(httpClient);
  Hbase.Client client = new Hbase.Client(protocol);

  byte[] t = bytes("demo_table");

  //
  // Scan all tables, look for the demo table and delete it.
  //
  System.out.println("scanning tables...");
  for (ByteBuffer name : refresh(client, httpClient).getTableNames()) {
    System.out.println("  found: " + ClientUtils.utf8(name.array()));
    if (ClientUtils.utf8(name.array()).equals(ClientUtils.utf8(t))) {
      if (refresh(client, httpClient).isTableEnabled(name)) {
        System.out.println("    disabling table: " + ClientUtils.utf8(name.array()));
        refresh(client, httpClient).disableTable(name);
      }
      System.out.println("    deleting table: " + ClientUtils.utf8(name.array()));
      refresh(client, httpClient).deleteTable(name);
    }
  }

  //
  // Create the demo table with two column families, entry: and unused:
  //
  ArrayList<ColumnDescriptor> columns = new ArrayList<>(2);
  ColumnDescriptor col;
  col = new ColumnDescriptor();
  col.name = ByteBuffer.wrap(bytes("entry:"));
  col.timeToLive = Integer.MAX_VALUE;
  col.maxVersions = 10;
  columns.add(col);
  col = new ColumnDescriptor();
  col.name = ByteBuffer.wrap(bytes("unused:"));
  col.timeToLive = Integer.MAX_VALUE;
  columns.add(col);

  System.out.println("creating table: " + ClientUtils.utf8(t));
  try {

    refresh(client, httpClient).createTable(ByteBuffer.wrap(t), columns);
  } catch (AlreadyExists ae) {
    System.out.println("WARN: " + ae.message);
  }

  System.out.println("column families in " + ClientUtils.utf8(t) + ": ");
  Map<ByteBuffer, ColumnDescriptor> columnMap = refresh(client, httpClient)
      .getColumnDescriptors(ByteBuffer.wrap(t));
  for (ColumnDescriptor col2 : columnMap.values()) {
    System.out.println("  column: " + ClientUtils.utf8(col2.name.array()) + ", maxVer: "
        + col2.maxVersions);
  }

  transport.close();
  httpClient.close();
}
 
Example 19
Source File: GfxdThriftServerThreadPool.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Loops on processing a client forever
 */
@Override
public void run() {
  TProcessor processor = null;
  TTransport inputTransport = null;
  TTransport outputTransport = null;
  TProtocol inputProtocol = null;
  TProtocol outputProtocol = null;

  final TServerEventHandler eventHandler = getEventHandler();
  ServerContext connectionContext = null;

  final ConnectionListener listener = connListener;
  final TTransport client = this.client;
  Socket clientSocket = null;

  try {
    processor = processorFactory_.getProcessor(client);
    inputTransport = inputTransportFactory_.getTransport(client);
    outputTransport = outputTransportFactory_.getTransport(client);
    inputProtocol = inputProtocolFactory_.getProtocol(inputTransport);
    outputProtocol = outputProtocolFactory_.getProtocol(outputTransport);

    if (eventHandler != null) {
      connectionContext = eventHandler.createContext(inputProtocol,
          outputProtocol);
    }
    // register with ConnectionListener
    if (listener != null) {
      if (client instanceof GfxdTSocket) {
        clientSocket = ((GfxdTSocket)client).getSocket();
      }
      else if (client instanceof TSocket) {
        clientSocket = ((TSocket)client).getSocket();
      }
      listener.connectionOpened(clientSocket, this.connectionNumber);
    }
    // we check stopped_ first to make sure we're not supposed to be
    // shutting down. this is necessary for graceful shutdown.
    while (true) {

      if (eventHandler != null) {
        eventHandler.processContext(connectionContext, inputTransport,
            outputTransport);
      }

      if (stopped || !processor.process(inputProtocol, outputProtocol)) {
        break;
      }
    }
  } catch (TTransportException tte) {
    // Assume the client died and continue silently
  } catch (TException te) {
    LOGGER.error("Thrift error occurred during processing of message.", te);
  } catch (Exception e) {
    LOGGER.error("Error occurred during processing of message.", e);
  }

  if (eventHandler != null) {
    eventHandler.deleteContext(connectionContext, inputProtocol,
        outputProtocol);
  }

  if (inputTransport != null) {
    inputTransport.close();
  }

  if (outputTransport != null) {
    outputTransport.close();
  }

  // deregister with ConnectionListener
  if (listener != null) {
    listener.connectionClosed(clientSocket, this.connectionNumber);
  }
}
 
Example 20
Source File: SuroPing.java    From suro with Apache License 2.0 4 votes vote down vote up
private void close(@Nullable TTransport transport) {
    if (transport == null) {
        return;
    }
    transport.close();
}