Java Examples for org.apache.thrift.transport.TTransportException
The following java examples will help you to understand the usage of org.apache.thrift.transport.TTransportException. These source code samples are taken from different open source projects.
Example 1
Project: dedupeer-master File: ThriftClient.java View source code |
public Map<Long, Chunk> deduplicate(Map<Integer, Map<String, ChunkIDs>> chunksInfo, String pathOfFile, int chunkSizeInBytes, int bytesToLoadByTime, HashingAlgorithm hashingAlgorithm) {
TTransport transport;
Map<Long, Chunk> chunks = null;
try {
transport = new TSocket("localhost", 7911);
TProtocol protocol = new TBinaryProtocol(transport);
DeduplicationService.Client client = new DeduplicationService.Client(protocol);
transport.open();
chunks = client.deduplicate(chunksInfo, pathOfFile, chunkSizeInBytes, bytesToLoadByTime, hashingAlgorithm);
transport.close();
} catch (TTransportException e) {
e.printStackTrace();
} catch (TException e) {
e.printStackTrace();
}
return chunks;
}
Example 2
Project: ThriftBook-master File: AsyncServer.java View source code |
public static void main(String[] args) throws TTransportException, IOException, InterruptedException {
FloorBroker floor = new FloorBroker();
(new Thread(floor)).start();
TProcessor proc = new TradeReporting.TradeHistory.AsyncProcessor(new AsyncTradeHistoryHandler(floor.getQ()));
TNonblockingServerSocket trans_svr = new TNonblockingServerSocket(9090);
TServer server = new THsHaServer(new THsHaServer.Args(trans_svr).processor(proc).protocolFactory(new TBinaryProtocol.Factory()).minWorkerThreads(4).maxWorkerThreads(4));
System.out.println("[Server] listening of port 9090");
server.serve();
}
Example 3
Project: deepnighttwo-master File: SocketServer.java View source code |
public static void main(String[] args) throws TTransportException {
TNonblockingServerSocket socket = new TNonblockingServerSocket(56789);
TProcessor processor = new ProcessDataService.Processor<ProcessDataService.Iface>(new ProcessDataService.Iface() {
@Override
public ProcessResult processData(DataPackage dataPackage) throws TException {
ProcessResult result = new ProcessResult();
result.setId(1);
result.setMessage("aaaa");
result.setSuccess(true);
return result;
}
});
TThreadedSelectorServer server = new TThreadedSelectorServer(new TThreadedSelectorServer.Args(socket).processor(processor));
server.serve();
}
Example 4
Project: hat-vldb2014-code-master File: TwoPLSlaveReplicationService.java View source code |
public void connectSlaves() {
slaveReplicas = Lists.newArrayList();
try {
Thread.sleep(5000);
} catch (Exception e) {
}
logger.debug("Bootstrapping slave replication service...");
for (ServerAddress slave : Config.getSiblingServers()) {
while (true) {
try {
slaveReplicas.add(TwoPLThriftUtil.getSlaveReplicaServiceClient(slave.getIP(), slave.getPort()));
break;
} catch (TTransportException e) {
System.err.println("Exception while bootstrapping connection with slave: " + slave);
e.printStackTrace();
}
}
}
logger.debug("...slave replication service bootstrapped");
}
Example 5
Project: phantom-master File: Server.java View source code |
@SuppressWarnings({ "unchecked", "rawtypes" })
private void start(int port) {
try {
TServerSocket serverTransport = new TServerSocket(port);
ArithmeticService.Processor processor = new ArithmeticService.Processor(new ArithmeticServiceImpl());
TServer server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport).processor(processor));
System.out.println("Starting server on port " + port);
server.serve();
} catch (TTransportException e) {
e.printStackTrace();
}
}
Example 6
Project: IronCount-master File: BaseEmbededServerSetupTest.java View source code |
/** * Set embedded cassandra up and spawn it in a new thread. * * @throws org.apache.thrift.transport.TTransportException * @throws java.io.IOException * @throws InterruptedException */ @BeforeClass public static void setup() throws TTransportException, IOException, InterruptedException, ConfigurationException { if (embedded == null) { embedded = new EmbeddedServerHelper(); embedded.setup(); } cassandraHostConfigurator = new CassandraHostConfigurator("localhost:9157"); cluster = HFactory.getOrCreateCluster(clusterName, cassandraHostConfigurator); buildTestSchema(); }
Example 7
Project: JCommon-master File: ThriftService.java View source code |
private T openService(HostAndPort host, ThriftClient<T> client, Transport transport) throws TTransportException { try { NiftyClientConnector<? extends NiftyClientChannel> connector; if (Transport.FRAMED.equals(transport)) { connector = new FramedClientConnector(host); } else if (Transport.BUFFERED.equals(transport)) { connector = new UnframedClientConnector(host); } else { throw new ErrorMessage("Unexpected thrift transport type: %s", transport); } return client.open(connector).get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new TTransportException(TIMED_OUT, "Interrupted opening connection to " + host, e); } catch (ExecutionException e) { Throwable cause = e.getCause(); Throwables.propagateIfInstanceOf(cause, TTransportException.class); throw new TTransportException(UNKNOWN, "Exception opening connection to " + host, cause); } }
Example 8
Project: bolton-sigmod2013-code-master File: SimpleServer.java View source code |
private void start(int socket) {
try {
TServerSocket serverTransport = new TServerSocket(socket);
SimpleServerService.Processor processor = new SimpleServerService.Processor(new SimpleServerServiceImpl());
TServer server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport).processor(processor));
server.serve();
} catch (TTransportException e) {
e.printStackTrace();
}
}
Example 9
Project: feedly-cassandra-master File: CassandraServiceTestBase.java View source code |
/** * Set embedded cassandra up and spawn it in a new thread. * * @throws TTransportException * @throws IOException * @throws InterruptedException */ @BeforeClass public static void beforeClass() throws TTransportException, IOException, InterruptedException { try { cassandra = new EmbeddedCassandraService(); boolean started = cassandra.cleanStart(KEYSPACE, snapshotFile); if (started) { int retries = 5; boolean bootstrapped = false; while (!bootstrapped) { try { cluster = HFactory.getOrCreateCluster("test-cluster", "localhost:8160"); KeyspaceDefinition keyspaceDefn = HFactory.createKeyspaceDefinition(KEYSPACE, ThriftKsDef.DEF_STRATEGY_CLASS, 1, Collections.<ColumnFamilyDefinition>emptyList()); cluster.addKeyspace(keyspaceDefn, true); keyspace = HFactory.createKeyspace(KEYSPACE, cluster); bootstrapped = true; } catch (HectorException ex) { if (retries == 0) throw ex; retries--; Thread.sleep(1000); } } } } catch (RuntimeException re) { re.printStackTrace(); throw re; } }
Example 10
Project: flipper-reverse-image-search-master File: AbstractCassandraTest.java View source code |
@BeforeClass
public static void startServer() throws InterruptedException, TTransportException, ConfigurationException, IOException {
EmbeddedCassandraServerHelper.startEmbeddedCassandra();
Cluster cluster = new Cluster.Builder().addContactPoints("127.0.0.1").withPort(9142).build();
Session session = cluster.connect();
CQLDataLoader dataLoader = new CQLDataLoader(session);
dataLoader.load(new ClassPathCQLDataSet("config/cql/create-tables.cql", true, "cassandra_unit_keyspace"));
}
Example 11
Project: id-server-master File: QndBenchmarkThriftClientSnowflake.java View source code |
private static void runTest(final int numRuns, final int numThreads, final int numNamespaces, final String engine) throws TTransportException {
final ThriftClientPool<TIdService.Client, TIdService.Iface> pool = clientPool("localhost", 9090);
BenchmarkResult result = new Benchmark(new Operation() {
@Override
public void run(int runId) {
String namespace = String.valueOf(runId % numNamespaces);
try {
TIdService.Iface client = pool.borrowObject();
try {
TIdResponse id = client.nextId(namespace, engine);
if (id.status != 200) {
System.out.println(id);
}
} finally {
pool.returnObject(client);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, numRuns, numThreads).run();
System.out.println("[" + engine + "]:\t" + result.summarize());
pool.destroy();
}
Example 12
Project: MSearch-master File: DefaultTServerFactory.java View source code |
@Override
public TServer createTServer() {
TMultiplexedProcessor tMultiplexedProcessor = new TMultiplexedProcessor();
for (Map.Entry<String, TProcessor> entry : this.map.entrySet()) {
tMultiplexedProcessor.registerProcessor(entry.getKey(), entry.getValue());
}
TNonblockingServerSocket socket = null;
try {
socket = new TNonblockingServerSocket(5000);
} catch (TTransportException e) {
throw new ThriftInitException(e.getMessage(), e);
}
TThreadedSelectorServer.Args args = new TThreadedSelectorServer.Args(socket);
args.executorService(Executors.newFixedThreadPool(20));
args.protocolFactory(new TCompactProtocol.Factory());
args.processor(tMultiplexedProcessor);
args.transportFactory(new TFramedTransport.Factory());
TThreadedSelectorServer server = new TThreadedSelectorServer(args);
return server;
}
Example 13
Project: qi4j-sandbox-master File: CassandraEntityStoreTest.java View source code |
@BeforeClass
public static void setup() throws TTransportException, IOException, InterruptedException {
// Tell cassandra where the configuration files are.
// Use the test configuration file.
System.setProperty("storage-config", "src/test/resources");
new CassandraServiceDataCleaner().prepare();
cassandra = new EmbeddedCassandraService();
cassandra.init();
t = new Thread(cassandra);
t.setDaemon(true);
t.start();
}
Example 14
Project: springside-engine-master File: StandardNIOServer.java View source code |
public static void main(String[] args) {
try {
handler = new CalculatorHandler();
processor = new Calculator.Processor(handler);
try {
TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(9090);
TServer server = new TThreadedSelectorServer(new TThreadedSelectorServer.Args(serverTransport).processor(processor));
System.out.println("Starting the server...");
server.serve();
} catch (TTransportException e) {
e.printStackTrace();
}
} catch (Exception x) {
x.printStackTrace();
}
}
Example 15
Project: thrift-rpc-master File: DefaultTServerFactory.java View source code |
@Override
public TServer createTServer() {
TMultiplexedProcessor tMultiplexedProcessor = new TMultiplexedProcessor();
for (Map.Entry<String, TProcessor> entry : this.map.entrySet()) {
tMultiplexedProcessor.registerProcessor(entry.getKey(), entry.getValue());
}
TNonblockingServerSocket socket = null;
try {
socket = new TNonblockingServerSocket(address);
} catch (TTransportException e) {
throw new ThriftInitException(e.getMessage(), e);
}
TThreadedSelectorServer.Args args = new TThreadedSelectorServer.Args(socket);
args.executorService(Executors.newFixedThreadPool(20));
args.protocolFactory(new TCompactProtocol.Factory());
args.processor(tMultiplexedProcessor);
args.transportFactory(new TFramedTransport.Factory());
TThreadedSelectorServer server = new TThreadedSelectorServer(args);
return server;
}
Example 16
Project: hive-master File: TUGIAssumingTransport.java View source code |
@Override public void open() throws TTransportException { try { ugi.doAs(new PrivilegedExceptionAction<Void>() { public Void run() { try { wrapped.open(); } catch (TTransportException tte) { throw new RuntimeException(tte); } return null; } }); } catch (IOException ioe) { throw new RuntimeException("Received an ioe we never threw!", ioe); } catch (InterruptedException ie) { throw new RuntimeException("Received an ie we never threw!", ie); } catch (RuntimeException rte) { if (rte.getCause() instanceof TTransportException) { throw (TTransportException) rte.getCause(); } else { throw rte; } } }
Example 17
Project: Jacass-master File: EmbeddedServerHelper.java View source code |
/** * Set embedded cassandra up and spawn it in a new thread. * * @throws org.apache.thrift.transport.TTransportException * * @throws java.io.IOException * @throws InterruptedException */ public void setup() throws TTransportException, IOException, InterruptedException { // delete tmp dir first rmdir(TMP); // make a tmp dir and copy storag-conf.xml and log4j.properties to it copy("/storage-conf.xml", TMP); copy("/log4j.properties", TMP); System.setProperty("storage-config", TMP); CassandraServiceDataCleaner cleaner = new CassandraServiceDataCleaner(); cleaner.prepare(); cassandra = new EmbeddedCassandraService(); cassandra.init(); Thread t = new Thread(cassandra); t.setDaemon(true); t.start(); }
Example 18
Project: ACaZoo-master File: THsHaDisruptorServer.java View source code |
public TServer buildTServer(Args args) {
if (DatabaseDescriptor.getClientEncryptionOptions().enabled)
throw new RuntimeException("Client SSL is not supported for non-blocking sockets (hsha). Please remove client ssl from the configuration.");
final InetSocketAddress addr = args.addr;
TNonblockingServerTransport serverTransport;
try {
serverTransport = new TCustomNonblockingServerSocket(addr, args.keepAlive, args.sendBufferSize, args.recvBufferSize);
} catch (TTransportException e) {
throw new RuntimeException(String.format("Unable to create thrift socket to %s:%s", addr.getAddress(), addr.getPort()), e);
}
com.thinkaurelius.thrift.util.TBinaryProtocol.Factory protocolFactory = new com.thinkaurelius.thrift.util.TBinaryProtocol.Factory(true, true);
TDisruptorServer.Args serverArgs = new TDisruptorServer.Args(serverTransport).inputTransportFactory(args.inTransportFactory).outputTransportFactory(args.outTransportFactory).inputProtocolFactory(protocolFactory).outputProtocolFactory(protocolFactory).processor(args.processor).maxFrameSizeInBytes(DatabaseDescriptor.getThriftFramedTransportSize());
return new THsHaDisruptorServer(serverArgs);
}
Example 19
Project: airavata-master File: GfacServer.java View source code |
public void StartGfacServer(GfacService.Processor<GfacServerHandler> gfacServerHandlerProcessor) throws Exception {
final int serverPort = Integer.parseInt(ServerSettings.getGFacServerPort());
try {
final String serverHost = ServerSettings.getGfacServerHost();
InetSocketAddress inetSocketAddress = new InetSocketAddress(serverHost, serverPort);
TServerTransport serverTransport = new TServerSocket(inetSocketAddress);
server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport).processor(gfacServerHandlerProcessor));
new Thread() {
public void run() {
server.serve();
setStatus(ServerStatus.STARTING);
logger.info("Starting Gfac Server ...");
}
}.start();
new Thread() {
public void run() {
while (!server.isServing()) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
break;
}
}
if (server.isServing()) {
setStatus(IServer.ServerStatus.STARTED);
logger.info("Started Gfac Server on Port " + serverPort + " ...");
}
}
}.start();
} catch (TTransportException e) {
logger.error(e.getMessage());
setStatus(IServer.ServerStatus.FAILED);
logger.error("Failed to start Gfac server on port " + serverPort + " ...");
}
}
Example 20
Project: androGister-master File: ApplicationConfiguration.java View source code |
@PostConstruct
public void initTatami() throws IOException, TTransportException {
if (env.getActiveProfiles().length == 0) {
log.debug("No Spring profile configured, running with default configuration");
} else {
for (String profile : env.getActiveProfiles()) {
log.debug("Detected Spring profile : " + profile);
}
}
Constants.VERSION = env.getRequiredProperty("app.version");
log.info("AndroGister version " + Constants.VERSION + " started!");
}
Example 21
Project: BidiThrift-master File: ConnectionStatusMonitor.java View source code |
/**
* Attempts to reconnect to the server.
*/
public void tryOpen() {
if (connected.get())
return;
// Make sure it's closed
transport.close();
try {
transport.open();
connected.set(true);
for (ConnectionStatusListener listener : listeners) {
listener.connectionEstablished();
}
return;
} catch (TTransportException e) {
}
timer.schedule(new RetryTask(), 5 * 1000);
}
Example 22
Project: brave-master File: ScribeSpanCollectorTest.java View source code |
@Test
public void testCollect() throws TTransportException {
final ScribeSpanCollector scribeSpanCollector = new ScribeSpanCollector("localhost", PORT);
try {
scribeSpanCollector.collect(span);
} finally {
scribeSpanCollector.close();
}
final List<Span> serverCollectedSpans = scribeServer.getReceivedSpans();
assertEquals(1, serverCollectedSpans.size());
assertEquals(span.getId(), serverCollectedSpans.get(0).getId());
assertEquals(span.getTrace_id(), serverCollectedSpans.get(0).getTrace_id());
}
Example 23
Project: cassandra-cqlMod-master File: THsHaDisruptorServer.java View source code |
public TServer buildTServer(Args args) {
if (DatabaseDescriptor.getClientEncryptionOptions().enabled)
throw new RuntimeException("Client SSL is not supported for non-blocking sockets (hsha). Please remove client ssl from the configuration.");
final InetSocketAddress addr = args.addr;
TNonblockingServerTransport serverTransport;
try {
serverTransport = new TCustomNonblockingServerSocket(addr, args.keepAlive, args.sendBufferSize, args.recvBufferSize);
} catch (TTransportException e) {
throw new RuntimeException(String.format("Unable to create thrift socket to %s:%s", addr.getAddress(), addr.getPort()), e);
}
com.thinkaurelius.thrift.util.TBinaryProtocol.Factory protocolFactory = new com.thinkaurelius.thrift.util.TBinaryProtocol.Factory(true, true);
TDisruptorServer.Args serverArgs = new TDisruptorServer.Args(serverTransport).inputTransportFactory(args.inTransportFactory).outputTransportFactory(args.outTransportFactory).inputProtocolFactory(protocolFactory).outputProtocolFactory(protocolFactory).processor(args.processor).maxFrameSizeInBytes(DatabaseDescriptor.getThriftFramedTransportSize());
return new THsHaDisruptorServer(serverArgs);
}
Example 24
Project: ColumnStoreUnifier-master File: HypertableHandler.java View source code |
public void connectToDatabase(String host, String port) {
try {
CLIENT = ThriftClient.create(host, Integer.parseInt(port));
NAMESPACE = CLIENT.namespace_open("test");
} catch (TTransportException e) {
e.printStackTrace();
} catch (TException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
}
Example 25
Project: commons-master File: TMonitoredServerSocket.java View source code |
@Override
protected TSocket acceptImpl() throws TTransportException {
final TSocket socket = super.acceptImpl();
final InetSocketAddress remoteAddress = (InetSocketAddress) socket.getSocket().getRemoteSocketAddress();
TSocket monitoredSocket = new TSocket(socket.getSocket()) {
boolean closed = false;
@Override
public void close() {
try {
super.close();
} finally {
if (!closed) {
monitor.released(remoteAddress);
addressMap.remove(this);
}
closed = true;
}
}
};
addressMap.put(monitoredSocket, remoteAddress);
monitor.connected(remoteAddress);
return monitoredSocket;
}
Example 26
Project: distributed-processor-master File: DigestSaslTransportPlugin.java View source code |
public TTransport connect(TTransport transport, String serverHost) throws TTransportException, IOException {
ClientCallbackHandler client_callback_handler = new ClientCallbackHandler(login_conf);
TSaslClientTransport wrapper_transport = new TSaslClientTransport(DIGEST, null, AuthUtils.SERVICE, serverHost, null, client_callback_handler, transport);
wrapper_transport.open();
LOG.debug("SASL DIGEST-MD5 client transport has been established");
return wrapper_transport;
}
Example 27
Project: donut-master File: ServerModule.java View source code |
@Override
protected void configure() {
binder().install(donutModule);
try {
binder().bind(TServerTransport.class).toInstance(new TServerSocket(donutModule.getPort()));
} catch (TTransportException e) {
System.err.println("Unable to listen on port " + donutModule.getPort() + ".");
System.exit(1);
}
binder().bind(TProcessor.class).toProvider(Providers.TKeyLocatorProcessorProvider.class);
binder().bind(TServer.class).toProvider(Providers.TServerProvider.class);
}
Example 28
Project: indextank-engine-master File: SuggestorServer.java View source code |
public void run() {
try {
TServerSocket serverTransport = new TServerSocket(SuggestorServer.this.port);
Suggestor.Processor processor = new Suggestor.Processor(new SuggestorImpl(SuggestorServer.this.suggestor));
Factory protFactory = new TBinaryProtocol.Factory(true, true);
TServer server = new TThreadPoolServer(processor, serverTransport, protFactory);
System.out.println("Starting suggestor server on port " + SuggestorServer.this.port + " ...");
server.serve();
} catch (TTransportException tte) {
tte.printStackTrace();
}
}
Example 29
Project: iotcloud2-master File: RabbitMQSensor.java View source code |
public static void main(String[] args) throws TTransportException {
// read the configuration file
Map conf = Utils.readConfig();
SensorClient client;
client = new SensorClient(conf);
List<String> sites = new ArrayList<String>();
sites.add("local");
SensorDeployDescriptor deployDescriptor = new SensorDeployDescriptor("iotcloud-examples-1.0-SNAPSHOT.jar", "cgl.iotcloud.examples.chat.RabbitMQSensor");
deployDescriptor.addDeploySites(sites);
client.deploySensor(deployDescriptor);
}
Example 30
Project: libcassandra-master File: Test.java View source code |
public static void main(String... args) throws TTransportException {
TTransport tr = new TSocket("localhost", 9160);
TProtocol proto = new TBinaryProtocol(tr);
Cassandra.Client client = new Cassandra.Client(proto);
tr.open();
Map<UUID, String> playerSessions = new ColumnFamilyMap<UUID, String>(UUID.class, String.class, client, "gamelink", "Sessions", "Players", ConsistencyLevel.ONE);
long start, took;
// System.out.println("took " + took + "ms");
for (int i = 0; i < 100; i++) {
start = System.currentTimeMillis();
System.out.println(playerSessions.size());
took = System.currentTimeMillis() - start;
System.out.println("took " + took + "ms");
}
// List<UUID> uuids = new LinkedList<UUID>();
// for (int i = 0; i < 100; i++) {
// start = System.currentTimeMillis();
// for (UUID uuid : uuids)
// System.out.println(uuid + ": " + playerSessions.get(uuid));
// took = System.currentTimeMillis() - start;
// System.out.println("took " + took + "ms");
// }
// for (Map.Entry<UUID, String> e:playerSessions.entrySet()){
// System.out.println(e.getKey() + ": " + e.getValue());
// }
// start = System.currentTimeMillis();
// String[] players = { "ThaNODnl", "specialist_nl", "killerman", "crucher", "falcon", "maller" };
// for (int i = 0; i < 1000000; i++)
// playerSessions.put(TimedUUIDGenerator.getTimeBasedUUID(), players[i % players.length]);
// took = System.currentTimeMillis() - start;
// System.out.println("took " + took + "ms");
//
// start = System.currentTimeMillis();
// System.out.println(playerSessions.size());
// took = System.currentTimeMillis() - start;
// System.out.println("took " + took + "ms");
}
Example 31
Project: lucida-master File: QADaemon.java View source code |
public static void main(String[] args) throws TTransportException, IOException, InterruptedException {
connectToCMD();
TProcessor proc = new LucidaService.AsyncProcessor(new QAServiceHandler.AsyncQAServiceHandler());
TNonblockingServerTransport transport = new TNonblockingServerSocket(8083);
TNonblockingServer.Args arguments = new TNonblockingServer.Args(transport).processor(proc).protocolFactory(new TBinaryProtocol.Factory()).transportFactory(new TFramedTransport.Factory());
final TNonblockingServer server = new TNonblockingServer(arguments);
System.out.println("QA at port 8083");
server.serve();
}
Example 32
Project: monitoring-master File: ByteArrayOutputStreamTransportTest.java View source code |
@Test
public void write() throws TTransportException {
transport.write(buf, 0, buf.length);
assertTrue(Arrays.equals(buf, out.toByteArray()));
assertTrue(Arrays.equals(buf, transport.getBuffer()));
transport.write(buf);
assertEquals(out.size(), transport.getBufferPosition());
assertEquals(-1, transport.getBytesRemainingInBuffer());
}
Example 33
Project: nosql-unit-master File: WhenEmbeddedCassandraServerIsRequired.java View source code |
@Test
public void embedded_cassandra_should_be_able_to_receive_data() throws TTransportException, IOException, InterruptedException, ConfigurationException {
EmbeddedCassandraServerHelper embeddedCassandraServerHelper = new EmbeddedCassandraServerHelper();
embeddedCassandraServerHelper.startEmbeddedCassandra("cu-cassandra.yaml", "target" + File.separatorChar + "cassandra-temp");
Cluster cluster = HFactory.getOrCreateCluster("Test Cluster", "localhost:9171");
ColumnFamilyDefinition cfDef = HFactory.createColumnFamilyDefinition("MyKeyspace", "ColumnFamilyName", ComparatorType.BYTESTYPE);
KeyspaceDefinition newKeyspace = HFactory.createKeyspaceDefinition("MyKeyspace", ThriftKsDef.DEF_STRATEGY_CLASS, 1, Arrays.asList(cfDef));
cluster.addKeyspace(newKeyspace, true);
Keyspace keyspaceOperator = HFactory.createKeyspace("MyKeyspace", cluster);
Mutator<String> mutator = HFactory.createMutator(keyspaceOperator, StringSerializer.get());
mutator.insert("jsmith", "ColumnFamilyName", HFactory.createStringColumn("first", "John"));
ColumnQuery<String, String, String> columnQuery = HFactory.createStringColumnQuery(keyspaceOperator);
columnQuery.setColumnFamily("ColumnFamilyName").setKey("jsmith").setName("first");
QueryResult<HColumn<String, String>> result = columnQuery.execute();
assertThat(result.get().getValue(), is("John"));
cluster.getConnectionManager().shutdown();
embeddedCassandraServerHelper.stopEmbeddedCassandra();
}
Example 34
Project: pinpoint-master File: ByteArrayOutputStreamTransportTest.java View source code |
@Test
public void write() throws TTransportException {
transport.write(buf, 0, buf.length);
assertTrue(Arrays.equals(buf, out.toByteArray()));
assertTrue(Arrays.equals(buf, transport.getBuffer()));
transport.write(buf);
assertEquals(out.size(), transport.getBufferPosition());
assertEquals(-1, transport.getBytesRemainingInBuffer());
}
Example 35
Project: plow-master File: RndClient.java View source code |
public void connect() throws TTransportException {
if (socket != null) {
socket.close();
}
socket = new TSocket(host, port);
socket.setTimeout(Defaults.RND_CLIENT_SOCKET_TIMEOUT_MS);
transport = new TFramedTransport(socket);
protocol = new TBinaryProtocol(transport);
transport.open();
service = new RndNodeApi.Client(protocol);
}
Example 36
Project: RDFS-master File: ClusterManagerServer.java View source code |
public static void main(String[] args) throws IOException, TTransportException {
StringUtils.startupShutdownMessage(ClusterManager.class, args, LOG);
Configuration conf = new Configuration();
ClusterManager cm = new ClusterManager(conf);
try {
ClusterManagerServer server = new ClusterManagerServer(conf, cm);
server.start();
server.join();
} catch (InterruptedException e) {
System.exit(0);
}
}
Example 37
Project: Storm-master File: DigestSaslTransportPlugin.java View source code |
public TTransport connect(TTransport transport, String serverHost) throws TTransportException, IOException {
ClientCallbackHandler client_callback_handler = new ClientCallbackHandler(login_conf);
TSaslClientTransport wrapper_transport = new TSaslClientTransport(DIGEST, null, AuthUtils.SERVICE, serverHost, null, client_callback_handler, transport);
wrapper_transport.open();
LOG.debug("SASL DIGEST-MD5 client transport has been established");
return wrapper_transport;
}
Example 38
Project: storm-yarn-master File: MasterClient.java View source code |
@SuppressWarnings("rawtypes")
public static MasterClient getConfiguredClient(Map conf) {
try {
String masterHost = (String) conf.get(Config.MASTER_HOST);
int masterPort = Utils.getInt(conf.get(Config.MASTER_THRIFT_PORT));
try {
Integer timeout = Utils.getInt(conf.get(Config.MASTER_TIMEOUT_SECS));
return new MasterClient(conf, masterHost, masterPort, timeout);
} catch (IllegalArgumentException e) {
return new MasterClient(conf, masterHost, masterPort, null);
}
} catch (TTransportException ex) {
throw new RuntimeException(ex);
}
}
Example 39
Project: suro-master File: TestHealthCheck.java View source code |
@Test
public void test() throws TTransportException, IOException {
InputManager inputManager = mock(InputManager.class);
doReturn(mock(SuroInput.class)).when(inputManager).getInput("thrift");
HealthCheck healthCheck = new HealthCheck(new ServerConfig() {
@Override
public int getPort() {
return suroServer.getServerPort();
}
}, inputManager);
healthCheck.get();
suroServer.getInjector().getInstance(InputManager.class).getInput("thrift").shutdown();
try {
healthCheck.get();
fail("exception should be thrown");
} catch (RuntimeException e) {
assertEquals(e.getMessage(), "NOT ALIVE!!!");
}
}
Example 40
Project: tajo-yarn-master File: ThriftHelper.java View source code |
/** * Thrift doesn't provide access to socket it creates, * this is the only way to know what ephemeral port we bound to. * TODO: Patch thrift to provide access so we don't have to do this. */ static ServerSocket getServerSocketFor(TNonblockingServerSocket thriftSocket) throws TTransportException { try { Field field = TNonblockingServerSocket.class.getDeclaredField("serverSocket_"); field.setAccessible(true); return (ServerSocket) field.get(thriftSocket); } catch (NoSuchFieldException e) { throw new TTransportException("Couldn't get listening port", e); } catch (SecurityException e) { throw new TTransportException("Couldn't get listening port", e); } catch (IllegalAccessException e) { throw new TTransportException("Couldn't get listening port", e); } }
Example 41
Project: tatami-master File: ApplicationConfiguration.java View source code |
/**
* Initializes Tatami.
* <p/>
* Spring profiles can be configured with a system property -Dspring.profiles.active=your-active-profile
* <p/>
* Available profiles are :
* - "apple-push" : for enabling Apple Push notifications
* - "metrics" : for enabling Yammer Metrics
* - "tatamibot" : for enabling the Tatami bot
*/
@PostConstruct
public void initTatami() throws IOException, TTransportException {
log.debug("Looking for Spring profiles... Available profiles are \"metrics\", \"tatamibot\" and \"apple-push\"");
if (env.getActiveProfiles().length == 0) {
log.debug("No Spring profile configured, running with default configuration");
} else {
for (String profile : env.getActiveProfiles()) {
log.debug("Detected Spring profile : " + profile);
}
}
Constants.VERSION = env.getRequiredProperty("tatami.version");
Constants.GOOGLE_ANALYTICS_KEY = env.getProperty("tatami.google.analytics.key");
log.info("Tatami v. {} started!", Constants.VERSION);
log.debug("Google Analytics key : {}", Constants.GOOGLE_ANALYTICS_KEY);
}
Example 42
Project: thrift-protocol-client-master File: TestClient.java View source code |
public void startClient() throws IOException {
TTransport transport;
TSocket socket;
try {
socket = new TSocket("192.168.35.131", 8020);
transport = new TFramedTransport(socket);
TBinaryProtocol protocol = new TBinaryProtocol(transport);
PostLimitServiceFinagle.Client client = new PostLimitServiceFinagle.Client(protocol);
transport.open();
String param = "{\"category_script_index\":4,\"majorcategory_script_index\":-1,\"category_id\":2,\"city_code\":-1,\"user_id\":2}";
OperateResult result = null;
try {
result = client.getPostLimit(param, "test");
} catch (ParamterExceptionOperationException | e) {
e.printStackTrace();
}
transport.close();
System.out.println(result.getData());
System.out.println(result.isSuccess());
System.out.println(result.getErrorMsg());
} catch (TTransportException e) {
e.printStackTrace();
} catch (TException e) {
e.printStackTrace();
}
}
Example 43
Project: Tstream-master File: DigestSaslTransportPlugin.java View source code |
public TTransport connect(TTransport transport, String serverHost) throws TTransportException, IOException {
ClientCallbackHandler client_callback_handler = new ClientCallbackHandler(login_conf);
TSaslClientTransport wrapper_transport = new TSaslClientTransport(DIGEST, null, AuthUtils.SERVICE, serverHost, null, client_callback_handler, transport);
wrapper_transport.open();
LOG.debug("SASL DIGEST-MD5 client transport has been established");
return wrapper_transport;
}
Example 44
Project: accumulo-master File: UGIAssumingTransport.java View source code |
@Override public void open() throws TTransportException { final AtomicReference<TTransportException> holder = new AtomicReference<>(null); try { ugi.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() { try { getWrapped().open(); } catch (TTransportException tte) { holder.set(tte); } return null; } }); } catch (IOExceptionInterruptedException | e) { throw new RuntimeException(e); } // Make sure the transport exception gets (re)thrown if it happened TTransportException tte = holder.get(); if (null != tte) { throw tte; } }
Example 45
Project: AIBombah-master File: TSimpleServer.java View source code |
public void serve() { stopped_ = false; try { serverTransport_.listen(); } catch (TTransportException ttx) { LOGGER.error("Error occurred during listening.", ttx); return; } setServing(true); while (!stopped_) { TTransport client = null; TProcessor processor = null; TTransport inputTransport = null; TTransport outputTransport = null; TProtocol inputProtocol = null; TProtocol outputProtocol = null; try { client = serverTransport_.accept(); if (client != null) { processor = processorFactory_.getProcessor(client); inputTransport = inputTransportFactory_.getTransport(client); outputTransport = outputTransportFactory_.getTransport(client); inputProtocol = inputProtocolFactory_.getProtocol(inputTransport); outputProtocol = outputProtocolFactory_.getProtocol(outputTransport); while (processor.process(inputProtocol, outputProtocol)) { } } } catch (TTransportException ttx) { } catch (TException tx) { if (!stopped_) { LOGGER.error("Thrift error occurred during processing of message.", tx); } } catch (Exception x) { if (!stopped_) { LOGGER.error("Error occurred during processing of message.", x); } } if (inputTransport != null) { inputTransport.close(); } if (outputTransport != null) { outputTransport.close(); } } setServing(false); }
Example 46
Project: Blitz-2015-master File: ThriftHttpTest.java View source code |
private AwesomeService.Client createClient() throws TTransportException {
URIBuilder uriBuilder = new URIBuilder();
uriBuilder.setScheme("http");
uriBuilder.setHost("localhost");
uriBuilder.setPort(SERVER_PORT);
TTransport transport = new THttpClient(uriBuilder.toString());
transport.open();
TProtocol protocol = new TJSONProtocol(transport);
return new AwesomeService.Client(protocol);
}
Example 47
Project: carat-master File: ProtocolClient.java View source code |
/** * FIXME: this needs to come from a factory, so that connections are not * kept open unnecessarily, and that they do not become stale, and that we * handle disconnections gracefully. * * @param c * @return * @throws NumberFormatException * @throws TTransportException */ public static CaratService.Client getInstance(Context c) throws NumberFormatException, TTransportException { if (SERVER_ADDRESS == null) { Properties properties = new Properties(); try { InputStream raw = c.getAssets().open(SERVER_PROPERTIES); if (raw != null) { properties.load(raw); if (properties.containsKey("PORT")) SERVER_PORT = Integer.parseInt(properties.getProperty("PORT", "8080")); if (properties.containsKey("ADDRESS")) SERVER_ADDRESS = properties.getProperty("ADDRESS", "server.caratproject.com"); Log.d(TAG, "Set address=" + SERVER_ADDRESS + " port=" + SERVER_PORT); } else Log.e(TAG, "Could not open server property file!"); } catch (IOException e) { Log.e(TAG, "Could not open server property file: " + e.toString()); } } if (SERVER_ADDRESS == null || SERVER_PORT == 0) return null; TSocket soc = new TSocket(SERVER_ADDRESS, SERVER_PORT, 60000); TProtocol p = new TBinaryProtocol(soc, true, true); CaratService.Client instance = new CaratService.Client(p); if (soc != null && !soc.isOpen()) soc.open(); return instance; }
Example 48
Project: Cassandra-KVPM-master File: TCustomServerSocket.java View source code |
@Override
protected TSocket acceptImpl() throws TTransportException {
TSocket tsocket = super.acceptImpl();
Socket socket = tsocket.getSocket();
try {
socket.setKeepAlive(this.keepAlive);
} catch (SocketException se) {
logger.warn("Failed to set keep-alive on Thrift socket.", se);
}
if (this.sendBufferSize != null) {
try {
socket.setSendBufferSize(this.sendBufferSize.intValue());
} catch (SocketException se) {
logger.warn("Failed to set send buffer size on Thrift socket.", se);
}
}
if (this.recvBufferSize != null) {
try {
socket.setReceiveBufferSize(this.recvBufferSize.intValue());
} catch (SocketException se) {
logger.warn("Failed to set receive buffer size on Thrift socket.", se);
}
}
return tsocket;
}
Example 49
Project: cassandra-rest-master File: ConnectionPool.java View source code |
public static void initializePool() throws TTransportException {
logger.debug("Creating connection pool, initializing [" + MAX_POOL_SIZE + "] connections.");
// Don't need pooling if we are embedded
if (VirgilConfiguration.isEmbedded()) {
embeddedServer = new VirgilConnection(VirgilConfiguration.isEmbedded());
} else {
for (int i = 0; i < MAX_POOL_SIZE; i++) {
free.add(createConnection());
}
}
}
Example 50
Project: CassandraQoS-master File: THsHaDisruptorServer.java View source code |
public TServer buildTServer(Args args) {
if (DatabaseDescriptor.getClientEncryptionOptions().enabled)
throw new RuntimeException("Client SSL is not supported for non-blocking sockets (hsha). Please remove client ssl from the configuration.");
final InetSocketAddress addr = args.addr;
TNonblockingServerTransport serverTransport;
try {
serverTransport = new TCustomNonblockingServerSocket(addr, args.keepAlive, args.sendBufferSize, args.recvBufferSize);
} catch (TTransportException e) {
throw new RuntimeException(String.format("Unable to create thrift socket to %s:%s", addr.getAddress(), addr.getPort()), e);
}
ThreadPoolExecutor invoker = new JMXEnabledThreadPoolExecutor(DatabaseDescriptor.getRpcMinThreads(), DatabaseDescriptor.getRpcMaxThreads(), 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new NamedThreadFactory("RPC-Thread"), "RPC-THREAD-POOL");
com.thinkaurelius.thrift.util.TBinaryProtocol.Factory protocolFactory = new com.thinkaurelius.thrift.util.TBinaryProtocol.Factory(true, true);
TDisruptorServer.Args serverArgs = new TDisruptorServer.Args(serverTransport).useHeapBasedAllocation(true).inputTransportFactory(args.inTransportFactory).outputTransportFactory(args.outTransportFactory).inputProtocolFactory(protocolFactory).outputProtocolFactory(protocolFactory).processor(args.processor).maxFrameSizeInBytes(DatabaseDescriptor.getThriftFramedTransportSize()).invocationExecutor(invoker).alwaysReallocateBuffers(true);
return new THsHaDisruptorServer(serverArgs);
}
Example 51
Project: cdap-master File: ThriftHelper.java View source code |
/**
* generic method to discover a thrift service and start up the
* thrift transport and protocol layer.
*/
public static TProtocol getThriftProtocol(String serviceName, EndpointStrategy endpointStrategy) throws ServerException {
Discoverable endpoint = endpointStrategy.pick();
if (endpoint == null) {
String message = String.format("Service '%s' is not registered in discovery service.", serviceName);
LOG.error(message);
throw new ServerException(message);
}
TTransport transport = new TFramedTransport(new TSocket(endpoint.getSocketAddress().getHostName(), endpoint.getSocketAddress().getPort()));
try {
transport.open();
} catch (TTransportException e) {
String message = String.format("Unable to connect to thrift service %s at %s. Reason: %s", serviceName, endpoint.getSocketAddress(), e.getMessage());
LOG.error(message);
throw new ServerException(message, e);
}
// now try to connect the thrift client
return new TBinaryProtocol(transport);
}
Example 52
Project: Chronos-master File: TestChronosClientWatcher.java View source code |
public ChronosServer createChronosServer(HostPort hostPort) throws IOException, TTransportException, ChronosException {
Properties properties = new Properties();
properties.setProperty(ChronosServer.SERVER_HOST, hostPort.getHost());
properties.setProperty(ChronosServer.SERVER_PORT, String.valueOf(hostPort.getPort()));
properties.setProperty(ChronosServer.BASE_ZNODE, "/chronos/default-cluster");
properties.setProperty(ChronosServer.ZK_QUORUM, ZKConfig.getZKQuorumServersString(TEST_UTIL.getConfiguration()));
properties.setProperty(ChronosServer.SESSION_TIMEOUT, String.valueOf(3000));
properties.setProperty(ChronosServer.MAX_THREAD, "100000");
properties.setProperty(ChronosServer.ZK_ADVANCE_TIMESTAMP, "100000");
properties.setProperty(ChronosServer.CONNECT_RETRY_TIMES, String.valueOf(10));
return new ChronosServer(new ChronosServerWatcher(properties));
}
Example 53
Project: codehaus-mojo-master File: AbstractSchemaCassandraMojo.java View source code |
/**
* Call {@link #executeOperation(Cassandra.Client)} on the implementing class
* @throws MojoExecutionException
* @throws MojoFailureException
*/
protected void executeThrift() throws MojoExecutionException, MojoFailureException {
TSocket socket = new TSocket(rpcAddress, rpcPort);
TTransport transport = new TFramedTransport(socket);
TBinaryProtocol binaryProtocol = new TBinaryProtocol(transport, true, true);
Cassandra.Client cassandraClient = new Cassandra.Client(binaryProtocol);
try {
transport.open();
cassandraClient.set_keyspace(keyspace);
executeOperation(cassandraClient);
} catch (TTransportException tte) {
throw new MojoExecutionException("There was a problemn opening the connection to Apache Cassandra", tte);
} catch (InvalidRequestException ire) {
throw new MojoExecutionException("Invalid request returned. Does the Keyspace '" + keyspace + "' exist?", ire);
} catch (Exception e) {
throw new MojoExecutionException("General exception executing truncate", e);
} finally {
if (transport != null && transport.isOpen()) {
try {
transport.flush();
transport.close();
} catch (Exception e) {
throw new MojoExecutionException("Something went wrong cleaning up", e);
}
}
}
}
Example 54
Project: commons-old-master File: TMonitoredServerSocket.java View source code |
@Override
protected TSocket acceptImpl() throws TTransportException {
final TSocket socket = super.acceptImpl();
final InetSocketAddress remoteAddress = (InetSocketAddress) socket.getSocket().getRemoteSocketAddress();
TSocket monitoredSocket = new TSocket(socket.getSocket()) {
boolean closed = false;
@Override
public void close() {
try {
super.close();
} finally {
if (!closed) {
monitor.released(remoteAddress);
addressMap.remove(this);
}
closed = true;
}
}
};
addressMap.put(monitoredSocket, remoteAddress);
monitor.connected(remoteAddress);
return monitoredSocket;
}
Example 55
Project: cta-otp-master File: OTPServerTask.java View source code |
public void run() {
LOG.info("Run called, port {}", port);
if (otpServiceImpl == null) {
LOG.warn("otpServiceImpl is null, bailing");
return;
}
try {
OTPService.Processor<OTPServiceImpl> processor = new OTPService.Processor<OTPServiceImpl>(otpServiceImpl);
// TODO(flamholz): make the transport, protocol and server type be configurable?
TServerTransport serverTransport = new TServerSocket(port);
TProtocolFactory protocolFactory = new TBinaryProtocol.Factory(true, true);
TThreadPoolServer.Args args = new TThreadPoolServer.Args(serverTransport).processor(processor).protocolFactory(protocolFactory);
TServer server = new TThreadPoolServer(args);
LOG.info("Starting the OTPService on port {}", port);
server.serve();
} catch (TTransportException e) {
e.printStackTrace();
}
}
Example 56
Project: floodlight-qos-beta-master File: PacketStreamerClient.java View source code |
/**
* Send test packets of the given OFMessageType to the packetstreamer server;
* @param client Packetstreamer client object
* @param numPackets number of test packets to be sent
* @param ofType OFMessageType of the test packets
* @param sync true if send with synchronous interface, false for asynchronous interface
* @throws TException
*/
private static void sendPackets(PacketStreamer.Client client, short numPackets, OFMessageType ofType, boolean sync) throws TException {
while (numPackets-- > 0) {
Message msg = new Message();
Packet packet = new Packet();
List<String> sids = new ArrayList<String>();
sids.add("session1");
sids.add("session2");
msg.setSessionIDs(sids);
packet.setMessageType(ofType);
long sw_dpid = numPackets / 40 + 1;
packet.setSwPortTuple(new SwitchPortTuple(sw_dpid, (short) (numPackets - (sw_dpid - 1) * 40)));
String strData = "New data, sequence " + numPackets;
packet.setData(strData.getBytes());
msg.setPacket(packet);
try {
if (sync) {
client.pushMessageSync(msg);
log.debug("Send packet sync: " + msg.toString());
} else {
client.pushMessageAsync(msg);
log.debug("Send packet sync: " + msg.toString());
}
} catch (TTransportException e) {
log.error(e.toString());
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}
Example 57
Project: Flume-Hive-master File: SetupMasterTestEnv.java View source code |
@Before
public void setCfgAndStartMaster() throws TTransportException, IOException {
// Give ZK a temporary directory, otherwise it's possible we'll reload some
// old configs
tmpdir = FileUtil.mktempdir();
FlumeConfiguration.createTestableConfiguration();
FlumeConfiguration.get().set(FlumeConfiguration.WEBAPPS_PATH, "build/webapps");
FlumeConfiguration.get().set(FlumeConfiguration.MASTER_ZK_LOGDIR, tmpdir.getAbsolutePath());
FlumeConfiguration.get().set(FlumeConfiguration.MASTER_STORE, "memory");
flumeMaster = new FlumeMaster(new CommandManager(), new ConfigManager(), new StatusManager(), new MasterAckManager(), FlumeConfiguration.get());
flumeMaster.serve();
}
Example 58
Project: geni-openflow-vertical-handover-master File: PacketStreamerClient.java View source code |
/**
* Send test packets of the given OFMessageType to the packetstreamer server;
* @param client Packetstreamer client object
* @param numPackets number of test packets to be sent
* @param ofType OFMessageType of the test packets
* @param sync true if send with synchronous interface, false for asynchronous interface
* @throws TException
*/
private static void sendPackets(PacketStreamer.Client client, short numPackets, OFMessageType ofType, boolean sync) throws TException {
while (numPackets-- > 0) {
Message msg = new Message();
Packet packet = new Packet();
List<String> sids = new ArrayList<String>();
sids.add("session1");
sids.add("session2");
msg.setSessionIDs(sids);
packet.setMessageType(ofType);
long sw_dpid = numPackets / 40 + 1;
packet.setSwPortTuple(new SwitchPortTuple(sw_dpid, (short) (numPackets - (sw_dpid - 1) * 40)));
String strData = "New data, sequence " + numPackets;
packet.setData(strData.getBytes());
msg.setPacket(packet);
try {
if (sync) {
client.pushMessageSync(msg);
log.debug("Send packet sync: " + msg.toString());
} else {
client.pushMessageAsync(msg);
log.debug("Send packet sync: " + msg.toString());
}
} catch (TTransportException e) {
log.error(e.toString());
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}
Example 59
Project: hadoop-20-master File: ClusterManagerServer.java View source code |
public static void main(String[] args) throws IOException, TTransportException {
StringUtils.startupShutdownMessage(ClusterManager.class, args, LOG);
Configuration conf = new Configuration();
boolean recoverFromDisk = false;
// state
if (args.length > 0) {
if (args.length != 1 || !args[0].equals("-recoverFromDisk")) {
printUsage(args);
System.exit(-1);
} else {
recoverFromDisk = true;
}
}
ClusterManager cm = new ClusterManager(conf, recoverFromDisk);
try {
ClusterManagerServer server = new ClusterManagerServer(conf, cm);
server.start();
server.join();
} catch (InterruptedException e) {
System.exit(0);
}
}
Example 60
Project: HadoopUSC-master File: ClusterManagerServer.java View source code |
public static void main(String[] args) throws IOException, TTransportException {
Configuration conf = new Configuration();
ClusterManager cm = new ClusterManager(conf);
ClusterManagerServer server = new ClusterManagerServer(conf, cm);
server.start();
try {
server.join();
} catch (InterruptedException e) {
System.exit(0);
} catch (Exception e) {
LOG.error(StringUtils.stringifyException(e));
System.exit(-1);
}
}
Example 61
Project: HederaInFloodlight-master File: PacketStreamerClient.java View source code |
/**
* Send test packets of the given OFMessageType to the packetstreamer server;
* @param client Packetstreamer client object
* @param numPackets number of test packets to be sent
* @param ofType OFMessageType of the test packets
* @param sync true if send with synchronous interface, false for asynchronous interface
* @throws TException
*/
private static void sendPackets(PacketStreamer.Client client, short numPackets, OFMessageType ofType, boolean sync) throws TException {
while (numPackets-- > 0) {
Message msg = new Message();
Packet packet = new Packet();
List<String> sids = new ArrayList<String>();
sids.add("session1");
sids.add("session2");
msg.setSessionIDs(sids);
packet.setMessageType(ofType);
long sw_dpid = numPackets / 40 + 1;
packet.setSwPortTuple(new SwitchPortTuple(sw_dpid, (short) (numPackets - (sw_dpid - 1) * 40)));
String strData = "New data, sequence " + numPackets;
packet.setData(strData.getBytes());
msg.setPacket(packet);
try {
if (sync) {
client.pushMessageSync(msg);
log.debug("Send packet sync: " + msg.toString());
} else {
client.pushMessageAsync(msg);
log.debug("Send packet sync: " + msg.toString());
}
} catch (TTransportException e) {
log.error(e.toString());
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}
Example 62
Project: Hobo-master File: Server.java View source code |
private void start() {
try {
TServerSocket serverTransport = new TServerSocket(port);
Hobo.Processor processor = new Hobo.Processor(new HoboServerImpl(index, pageSize));
TServer server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport).processor(processor));
server.serve();
} catch (TTransportException e) {
e.printStackTrace();
}
}
Example 63
Project: incubator-zeppelin-master File: ClientFactory.java View source code |
@Override
public Client create() throws Exception {
TSocket transport = new TSocket(host, port);
try {
transport.open();
} catch (TTransportException e) {
throw new InterpreterException(e);
}
TProtocol protocol = new TBinaryProtocol(transport);
Client client = new RemoteInterpreterService.Client(protocol);
synchronized (clientSocketMap) {
clientSocketMap.put(client, transport);
}
return client;
}
Example 64
Project: janus-master File: ThriftConnectionTest.java View source code |
@Test
public void testConnectionDropped() throws Exception {
CTConnectionFactory connectionFactory = spy(factoryConfig.build());
CTConnection mockConnection = spy(connectionFactory.makeObject("janusgraph"));
when(mockConnection.getConfig()).thenReturn(factoryConfig);
when(mockConnection.isOpen()).thenReturn(true);
TTransport mockClient = spy(mockConnection.getTransport());
assertTrue(connectionFactory.validateObject(null, mockConnection));
when(mockClient.readAll(new byte[0], 0, 0)).thenThrow(new TTransportException("Broken Pipe"));
assertTrue(mockClient.isOpen());
}
Example 65
Project: janusgraph-master File: ThriftConnectionTest.java View source code |
@Test
public void testConnectionDropped() throws Exception {
CTConnectionFactory connectionFactory = spy(factoryConfig.build());
CTConnection mockConnection = spy(connectionFactory.makeObject("janusgraph"));
when(mockConnection.getConfig()).thenReturn(factoryConfig);
when(mockConnection.isOpen()).thenReturn(true);
TTransport mockClient = spy(mockConnection.getTransport());
assertTrue(connectionFactory.validateObject(null, mockConnection));
when(mockClient.readAll(new byte[0], 0, 0)).thenThrow(new TTransportException("Broken Pipe"));
assertTrue(mockClient.isOpen());
}
Example 66
Project: jena-master File: IteratorThriftRDF.java View source code |
@Override protected StreamRowRDF moveToNext() { if (!protocol.getTransport().isOpen()) return null; try { row.read(protocol); } catch (TTransportException e) { if (e.getType() == TTransportException.END_OF_FILE) return null; } catch (TException ex) { TRDF.exception(ex); } TRDF.visit(row, converter); row.clear(); return collector.getRow(); }
Example 67
Project: jst-master File: TBackoffConnect.java View source code |
public TTransport doConnectWithRetry(ITransportPlugin transportPlugin, TTransport underlyingTransport, String host, String asUser) throws IOException {
boolean connected = false;
TTransport transportResult = null;
while (!connected) {
try {
transportResult = transportPlugin.connect(underlyingTransport, host, asUser);
connected = true;
} catch (TTransportException ex) {
retryNext(ex);
}
}
return transportResult;
}
Example 68
Project: jstorm-master File: TBackoffConnect.java View source code |
public TTransport doConnectWithRetry(ITransportPlugin transportPlugin, TTransport underlyingTransport, String host, String asUser) throws IOException {
boolean connected = false;
TTransport transportResult = null;
while (!connected) {
try {
transportResult = transportPlugin.connect(underlyingTransport, host, asUser);
connected = true;
} catch (TTransportException ex) {
retryNext(ex);
}
}
return transportResult;
}
Example 69
Project: luxun-master File: AbstractClient.java View source code |
protected void connect() {
long connectBackoffMs = 1;
long beginTimeMs = System.currentTimeMillis();
while (luxunClient == null && !shutdown) {
try {
TSocket socket = new TSocket(host, port, soTimeoutMs);
transport = new TFramedTransport(socket);
TProtocol protocol = new TBinaryProtocol(transport);
luxunClient = new QueueService.Client(protocol);
transport.open();
logger.info("Connected to " + host + ":" + port + " for operating");
} catch (TTransportException e) {
disconnect();
long endTimeMs = System.currentTimeMillis();
if ((endTimeMs - beginTimeMs + connectBackoffMs) > connectTimeoutMs) {
logger.error("Connection attempt to " + host + ":" + port + " timing out after " + connectTimeoutMs + " ms", e);
throw new ConnectionRefusedException(host + ":" + port, e);
}
logger.error("Connection attempt to " + host + ":" + port + " failed, next attempt in " + connectBackoffMs + " ms", e);
try {
Thread.sleep(connectBackoffMs);
} catch (InterruptedException e1) {
logger.warn(e1.getMessage());
Thread.currentThread().interrupt();
}
connectBackoffMs = Math.min(10 * connectBackoffMs, MaxConnectBackoffMs);
}
}
}
Example 70
Project: magnificent-mileage-master File: OTPServerTask.java View source code |
public void run() {
LOG.info("Run called, port {}", port);
if (otpServiceImpl == null) {
LOG.warn("otpServiceImpl is null, bailing");
return;
}
try {
OTPService.Processor<OTPServiceImpl> processor = new OTPService.Processor<OTPServiceImpl>(otpServiceImpl);
// TODO(flamholz): make the transport, protocol and server type be configurable?
TServerTransport serverTransport = new TServerSocket(port);
TProtocolFactory protocolFactory = new TBinaryProtocol.Factory(true, true);
TThreadPoolServer.Args args = new TThreadPoolServer.Args(serverTransport).processor(processor).protocolFactory(protocolFactory);
TServer server = new TThreadPoolServer(args);
LOG.info("Starting the OTPService on port {}", port);
server.serve();
} catch (TTransportException e) {
e.printStackTrace();
}
}
Example 71
Project: opentsdb-plugins-master File: ThriftServerFactory.java View source code |
public CustomTDisruptorServer disruptorServerProvider() throws TTransportException {
final TBinaryProtocol.Factory protocol = new TBinaryProtocol.Factory();
TDisruptorServer.Args args = new TDisruptorServer.Args(socket).inputTransportFactory(new TFramedTransport.Factory()).outputTransportFactory(new TFramedTransport.Factory()).inputProtocolFactory(protocol).outputProtocolFactory(protocol).processorFactory(processorFactory).useHeapBasedAllocation(true).numAcceptors(acceptors).numSelectors(selectors).numWorkersPerSelector(workers).alwaysReallocateBuffers(true);
return new CustomTDisruptorServer(args);
}
Example 72
Project: presto-master File: KerberosHiveMetastoreAuthentication.java View source code |
@Override
public TTransport authenticate(TTransport rawTransport, String hiveMetastoreHost) throws TTransportException {
try {
String serverPrincipal = getServerPrincipal(hiveMetastoreServicePrincipal, hiveMetastoreHost);
String[] names = SaslRpcServer.splitKerberosName(serverPrincipal);
checkState(names.length == 3, "Kerberos principal name does NOT have the expected hostname part: %s", serverPrincipal);
Map<String, String> saslProps = ImmutableMap.of(Sasl.QOP, "auth", Sasl.SERVER_AUTH, "true");
TTransport saslTransport = new TSaslClientTransport(KERBEROS.getMechanismName(), null, names[0], names[1], saslProps, null, rawTransport);
return new TUGIAssumingTransport(saslTransport, authentication.getUserGroupInformation());
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
Example 73
Project: scylla-tools-java-master File: TCustomNonblockingServerSocket.java View source code |
@Override
@SuppressWarnings("resource")
protected TNonblockingSocket acceptImpl() throws TTransportException {
TNonblockingSocket tsocket = super.acceptImpl();
if (tsocket == null || tsocket.getSocketChannel() == null)
return tsocket;
Socket socket = tsocket.getSocketChannel().socket();
try {
socket.setKeepAlive(this.keepAlive);
} catch (SocketException se) {
logger.warn("Failed to set keep-alive on Thrift socket.", se);
}
if (this.sendBufferSize != null) {
try {
socket.setSendBufferSize(this.sendBufferSize.intValue());
} catch (SocketException se) {
logger.warn("Failed to set send buffer size on Thrift socket.", se);
}
}
if (this.recvBufferSize != null) {
try {
socket.setReceiveBufferSize(this.recvBufferSize.intValue());
} catch (SocketException se) {
logger.warn("Failed to set receive buffer size on Thrift socket.", se);
}
}
return tsocket;
}
Example 74
Project: Solandra-master File: SolandraIndexReaderFactory.java View source code |
@Override
public IndexReader newReader(Directory indexDir, boolean readOnly) throws IOException {
Cassandra.Iface client;
/*try {
client = CassandraUtils.createConnection(cassandraHost,cassandraPort,cassandraFramed);
} catch (TTransportException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new IOException();
} */
client = CassandraUtils.createRobustConnection(cassandraHost, cassandraPort, cassandraFramed, true);
return new IndexReader(indexName, client);
}
Example 75
Project: spring-thrift-service-manager-master File: AbstractRunnableServiceWrapper.java View source code |
@Override
public void run() {
LOGGER.info("Start Service '{}'", serviceName);
try {
initializeServer();
this.startService();
} catch (TTransportException e) {
LOGGER.error("Error initializing service " + serviceName, e);
} catch (Exception e) {
LOGGER.error("Unexpected exception on Thirft Service", e);
} finally {
LOGGER.debug("Service thread closing {}", serviceName);
}
}
Example 76
Project: stratio-cassandra-master File: TCustomNonblockingServerSocket.java View source code |
@Override
protected TNonblockingSocket acceptImpl() throws TTransportException {
TNonblockingSocket tsocket = super.acceptImpl();
if (tsocket == null || tsocket.getSocketChannel() == null)
return tsocket;
Socket socket = tsocket.getSocketChannel().socket();
try {
socket.setKeepAlive(this.keepAlive);
} catch (SocketException se) {
logger.warn("Failed to set keep-alive on Thrift socket.", se);
}
if (this.sendBufferSize != null) {
try {
socket.setSendBufferSize(this.sendBufferSize.intValue());
} catch (SocketException se) {
logger.warn("Failed to set send buffer size on Thrift socket.", se);
}
}
if (this.recvBufferSize != null) {
try {
socket.setReceiveBufferSize(this.recvBufferSize.intValue());
} catch (SocketException se) {
logger.warn("Failed to set receive buffer size on Thrift socket.", se);
}
}
return tsocket;
}
Example 77
Project: thrift_auto_java-master File: TSimpleServer.java View source code |
public void serve() { stopped_ = false; try { serverTransport_.listen(); } catch (TTransportException ttx) { LOGGER.error("Error occurred during listening.", ttx); return; } setServing(true); while (!stopped_) { TTransport client = null; TProcessor processor = null; TTransport inputTransport = null; TTransport outputTransport = null; TProtocol inputProtocol = null; TProtocol outputProtocol = null; try { client = serverTransport_.accept(); if (client != null) { processor = processorFactory_.getProcessor(client); inputTransport = inputTransportFactory_.getTransport(client); outputTransport = outputTransportFactory_.getTransport(client); inputProtocol = inputProtocolFactory_.getProtocol(inputTransport); outputProtocol = outputProtocolFactory_.getProtocol(outputTransport); while (processor.process(inputProtocol, outputProtocol)) { } } } catch (TTransportException ttx) { } catch (TException tx) { if (!stopped_) { LOGGER.error("Thrift error occurred during processing of message.", tx); } } catch (Exception x) { if (!stopped_) { LOGGER.error("Error occurred during processing of message.", x); } } if (inputTransport != null) { inputTransport.close(); } if (outputTransport != null) { outputTransport.close(); } } setServing(false); }
Example 78
Project: topic-modeling-master File: TSimpleServer.java View source code |
public void serve() { stopped_ = false; try { serverTransport_.listen(); } catch (TTransportException ttx) { LOGGER.error("Error occurred during listening.", ttx); return; } setServing(true); while (!stopped_) { TTransport client = null; TProcessor processor = null; TTransport inputTransport = null; TTransport outputTransport = null; TProtocol inputProtocol = null; TProtocol outputProtocol = null; try { client = serverTransport_.accept(); if (client != null) { processor = processorFactory_.getProcessor(client); inputTransport = inputTransportFactory_.getTransport(client); outputTransport = outputTransportFactory_.getTransport(client); inputProtocol = inputProtocolFactory_.getProtocol(inputTransport); outputProtocol = outputProtocolFactory_.getProtocol(outputTransport); while (processor.process(inputProtocol, outputProtocol)) { } } } catch (TTransportException ttx) { } catch (TException tx) { if (!stopped_) { LOGGER.error("Thrift error occurred during processing of message.", tx); } } catch (Exception x) { if (!stopped_) { LOGGER.error("Error occurred during processing of message.", x); } } if (inputTransport != null) { inputTransport.close(); } if (outputTransport != null) { outputTransport.close(); } } setServing(false); }
Example 79
Project: ubuntu-packaging-floodlight-master File: PacketStreamerClient.java View source code |
/**
* Send test packets of the given OFMessageType to the packetstreamer server;
* @param client Packetstreamer client object
* @param numPackets number of test packets to be sent
* @param ofType OFMessageType of the test packets
* @param sync true if send with synchronous interface, false for asynchronous interface
* @throws TException
*/
private static void sendPackets(PacketStreamer.Client client, short numPackets, OFMessageType ofType, boolean sync) throws TException {
while (numPackets-- > 0) {
Message msg = new Message();
Packet packet = new Packet();
List<String> sids = new ArrayList<String>();
sids.add("session1");
sids.add("session2");
msg.setSessionIDs(sids);
packet.setMessageType(ofType);
long sw_dpid = numPackets / 40 + 1;
packet.setSwPortTuple(new SwitchPortTuple(sw_dpid, (short) (numPackets - (sw_dpid - 1) * 40)));
String strData = "New data, sequence " + numPackets;
packet.setData(strData.getBytes());
msg.setPacket(packet);
try {
if (sync) {
client.pushMessageSync(msg);
log.debug("Send packet sync: " + msg.toString());
} else {
client.pushMessageAsync(msg);
log.debug("Send packet sync: " + msg.toString());
}
} catch (TTransportException e) {
log.error(e.toString());
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}
Example 80
Project: URingPaxos-master File: ThriftProposer.java View source code |
@Override
public void run() {
try {
TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(port);
PaxosProposerService.Processor<Iface> processor = new Processor<Iface>(new PaxosProposerServiceImpl(proposer));
TServer server = new TNonblockingServer(new TNonblockingServer.Args(serverTransport).processor(processor));
logger.info("Starting thrift proposer server on port " + port);
server.serve();
} catch (TTransportException e) {
logger.error(e);
}
}
Example 81
Project: zeppelin-master File: ClientFactory.java View source code |
@Override
public Client create() throws Exception {
TSocket transport = new TSocket(host, port);
try {
transport.open();
} catch (TTransportException e) {
throw new InterpreterException(e);
}
TProtocol protocol = new TBinaryProtocol(transport);
Client client = new RemoteInterpreterService.Client(protocol);
synchronized (clientSocketMap) {
clientSocketMap.put(client, transport);
}
return client;
}
Example 82
Project: agiato-master File: Connector.java View source code |
public Cassandra.Client openConnection() {
try {
if (null == trans) {
//trans = new TSocket("localhost", 9160);
trans = new TFramedTransport(new TSocket(getHost().getName(), getHost().getPort()));
TProtocol proto = new TBinaryProtocol(trans);
client = new Cassandra.Client(proto);
trans.open();
}
} catch (TTransportException exception) {
System.out.println("failed to open Cassandra connection" + exception);
exception.printStackTrace();
}
return client;
}
Example 83
Project: annotateThrift-master File: SerializationBenchmark.java View source code |
public static void testSerialization(TProtocolFactory factory, TBase object) throws Exception { TTransport trans = new TTransport() { public void write(byte[] bin, int x, int y) throws TTransportException { } public int read(byte[] bin, int x, int y) throws TTransportException { return 0; } public void close() { } public void open() { } public boolean isOpen() { return true; } }; TProtocol proto = factory.getProtocol(trans); long startTime = System.currentTimeMillis(); for (int i = 0; i < HOW_MANY; i++) { object.write(proto); } long endTime = System.currentTimeMillis(); System.out.println("Serialization test time: " + (endTime - startTime) + " ms"); }
Example 84
Project: apache-cassandra-master File: EmbeddedCassandraServiceTest.java View source code |
/** * Set embedded cassandra up and spawn it in a new thread. * * @throws TTransportException * @throws IOException * @throws InterruptedException */ @BeforeClass public static void setup() throws TTransportException, IOException, InterruptedException { // Tell cassandra where the configuration files are. // Use the test configuration file. System.setProperty("storage-config", "test/conf"); cassandra = new EmbeddedCassandraService(); cassandra.init(); // spawn cassandra in a new thread Thread t = new Thread(cassandra); t.setDaemon(true); t.start(); }
Example 85
Project: archived-net-virt-platform-master File: PacketStreamerClient.java View source code |
/**
* Send test packets of the given OFMessageType to the packetstreamer server;
* @param client Packetstreamer client object
* @param numPackets number of test packets to be sent
* @param ofType OFMessageType of the test packets
* @param sync true if send with synchronous interface, false for asynchronous interface
* @throws TException
*/
private static void sendPackets(PacketStreamer.Client client, short numPackets, OFMessageType ofType, boolean sync) throws TException {
while (numPackets-- > 0) {
Message msg = new Message();
Packet packet = new Packet();
List<String> sids = new ArrayList<String>();
sids.add("session1");
sids.add("session2");
msg.setSessionIDs(sids);
packet.setMessageType(ofType);
long sw_dpid = numPackets / 40 + 1;
packet.setSwPortTuple(new SwitchPortTuple(sw_dpid, (short) (numPackets - (sw_dpid - 1) * 40)));
String strData = "New data, sequence " + numPackets;
packet.setData(strData.getBytes());
msg.setPacket(packet);
try {
if (sync) {
client.pushMessageSync(msg);
log.debug("Send packet sync: " + msg.toString());
} else {
client.pushMessageAsync(msg);
log.debug("Send packet sync: " + msg.toString());
}
} catch (TTransportException e) {
log.error(e.toString());
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}
Example 86
Project: armeria-master File: ThriftOverHttp1Test.java View source code |
@Override protected TTransport newTransport(String uri, HttpHeaders headers) throws TTransportException { final SSLContext sslContext; try { sslContext = SSLContextBuilder.create().loadTrustMaterial((TrustStrategy) ( chain, authType) -> true).build(); } catch (GeneralSecurityException e) { throw new TTransportException("failed to initialize an SSL context", e); } final THttpClient client = new THttpClient(uri, HttpClientBuilder.create().setSSLContext(sslContext).build()); client.setCustomHeaders(headers.names().stream().collect(toImmutableMap(AsciiString::toString, name -> String.join(", ", headers.getAll(name))))); return client; }
Example 87
Project: carbon-analytics-master File: ThriftSecureClientPoolFactory.java View source code |
@Override
public Object createClient(String protocol, String hostName, int port) throws DataEndpointSecurityException, DataEndpointAgentConfigurationException {
if (protocol.equalsIgnoreCase(DataEndpointConfiguration.Protocol.SSL.toString())) {
int timeout = AgentHolder.getInstance().getDataEndpointAgent(DataEndpointConstants.THRIFT_DATA_AGENT_TYPE).getAgentConfiguration().getSocketTimeoutMS();
String sslProtocols = AgentHolder.getInstance().getDataEndpointAgent(DataEndpointConstants.THRIFT_DATA_AGENT_TYPE).getAgentConfiguration().getSslEnabledProtocols();
String ciphers = AgentHolder.getInstance().getDataEndpointAgent(DataEndpointConstants.THRIFT_DATA_AGENT_TYPE).getAgentConfiguration().getCiphers();
try {
TTransport receiverTransport = TSSLTransportFactory.getClientSocket(hostName, port, timeout, params);
TSocket tSocket = (TSocket) receiverTransport;
SSLSocket sslSocket = (SSLSocket) tSocket.getSocket();
if (sslProtocols != null && sslProtocols.length() != 0) {
String[] sslProtocolsArray = sslProtocols.split(",");
sslSocket.setEnabledProtocols(sslProtocolsArray);
}
if (ciphers != null && ciphers.length() != 0) {
String[] ciphersArray = ciphers.split(",");
sslSocket.setEnabledCipherSuites(ciphersArray);
}
TProtocol tProtocol = new TBinaryProtocol(receiverTransport);
return new ThriftSecureEventTransmissionService.Client(tProtocol);
} catch (TTransportException e) {
throw new DataEndpointSecurityException("Error while trying to connect to " + protocol + "://" + hostName + ":" + port, e);
}
}
throw new DataEndpointSecurityException("Unsupported protocol :" + protocol + " used to authenticate the client, only " + DataEndpointConfiguration.Protocol.SSL.toString() + " is supported");
}
Example 88
Project: cass-fate-master File: EmbeddedCassandraServiceTest.java View source code |
/** * Set embedded cassandra up and spawn it in a new thread. * * @throws TTransportException * @throws IOException * @throws InterruptedException */ @BeforeClass public static void setup() throws TTransportException, IOException, InterruptedException { // Tell cassandra where the configuration files are. // Use the test configuration file. System.setProperty("storage-config", "test/conf"); cassandra = new EmbeddedCassandraService(); cassandra.init(); // spawn cassandra in a new thread Thread t = new Thread(cassandra); t.setDaemon(true); t.start(); }
Example 89
Project: cassandra-connection-pool-master File: ConnectionPoolTest.java View source code |
@Test
public void testAbandoned() throws Exception {
PoolConfiguration prop = new PoolProperties();
prop.setHost("127.0.0.1");
prop.setPort(DatabaseDescriptor.getRpcPort());
prop.setInitialSize(2);
prop.setMinIdle(1);
prop.setMaxIdle(4);
prop.setMaxActive(4);
prop.setRemoveAbandonedTimeout(3);
prop.setLogAbandoned(true);
ConnectionPool pool = new ConnectionPool(prop);
// Get a connection
Cassandra.Client connection = pool.getConnection();
Assert.assertNotNull(connection);
Assert.assertEquals(1, pool.getActive());
Assert.assertEquals(1, pool.getIdle());
Assert.assertEquals(2, pool.getSize());
Thread.sleep(5000);
pool.checkAbandoned();
// The connection should now be closed
Assert.assertEquals(0, pool.getActive());
Assert.assertEquals(1, pool.getIdle());
Assert.assertEquals(1, pool.getSize());
try {
connection.describe_cluster_name();
Assert.fail("Connection should have been closed by checkAbandoned()");
} catch (TTransportException e) {
}
pool.close();
}
Example 90
Project: cassandra-old-master File: TCustomServerSocket.java View source code |
@Override
protected TSocket acceptImpl() throws TTransportException {
TSocket tsocket = super.acceptImpl();
Socket socket = tsocket.getSocket();
try {
socket.setKeepAlive(this.keepAlive);
} catch (SocketException se) {
logger.warn("Failed to set keep-alive on Thrift socket.", se);
}
if (this.sendBufferSize != null) {
try {
socket.setSendBufferSize(this.sendBufferSize.intValue());
} catch (SocketException se) {
logger.warn("Failed to set send buffer size on Thrift socket.", se);
}
}
if (this.recvBufferSize != null) {
try {
socket.setReceiveBufferSize(this.recvBufferSize.intValue());
} catch (SocketException se) {
logger.warn("Failed to set receive buffer size on Thrift socket.", se);
}
}
return tsocket;
}
Example 91
Project: cassandra-webconsole-master File: CassandraClientProvider.java View source code |
/** * Get Thrift Client * @return * @throws TTransportException * @throws ConnectException */ public Client getThriftClient() throws TTransportException, ConnectException { if (!properties.hasProperties()) { return null; } String host = properties.getProperty(CassandraProperties.HOST); int port = Integer.parseInt(properties.getProperty(CassandraProperties.THRIFT_PORT)); // Check usage of framed transport String framed = properties.getProperty(CassandraProperties.FRAMED_TRANSPORT); boolean isFramed = (framed != null && Boolean.valueOf(framed)); Client client = th.get(); if (client == null) { TTransport transport = new TSocket(host, port); ((TSocket) transport).setTimeout(10000); // wrap transport if framed transport is enabled if (isFramed) { transport = new TFramedTransport(transport); } TProtocol protocol = new TBinaryProtocol(transport); transport.open(); client = new Client(protocol); th.set(client); } return client; }
Example 92
Project: cs-244-project-master File: PBFTCohortRunner.java View source code |
private static void testViewChange(GroupConfigProvider<PBFTCohort.Client> leaderConfigProvider) {
// make everyone multicast view-change messages
for (int i = 1; i <= numServers; i++) {
GroupMember<PBFTCohort.Client> groupMember = null;
PBFTCohort.Client server = null;
try {
groupMember = leaderConfigProvider.getGroupMember(i);
server = groupMember.getThriftConnection();
server.initiateViewChange();
} catch (TTransportException e) {
System.err.println("Failed to initiate view change from server: " + i);
e.printStackTrace();
} catch (TException e) {
System.err.println("Failed to initiate view change from server: " + i);
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
groupMember.returnThriftConnection(server);
}
}
}
Example 93
Project: elasticsearch-server-master File: SimpleThriftTests.java View source code |
@BeforeMethod
public void setup() throws IOException, TTransportException {
node = nodeBuilder().settings(settingsBuilder().put("path.data", "target/data").put("cluster.name", "test-cluster-" + NetworkUtils.getLocalAddress()).put("gateway.type", "none")).node();
transport = new TSocket("localhost", 9500);
TProtocol protocol = new TBinaryProtocol(transport);
client = new Rest.Client(protocol);
transport.open();
}
Example 94
Project: floe2-master File: AppSubmitter.java View source code |
/**
* Launches all inproc services.
*/
private static void launchInProcServices() {
Thread zkThread = new Thread(new Runnable() {
@Override
public void run() {
LocalZKServer.main(new String[0]);
}
});
Thread coordThread = new Thread(new Runnable() {
@Override
public void run() {
CoordinatorService.main(new String[0]);
}
});
Thread containerThread = new Thread(new Runnable() {
@Override
public void run() {
ContainerService.main(new String[0]);
}
});
try {
zkThread.start();
zkThread.join();
containerThread.start();
containerThread.join();
coordThread.start();
} catch (InterruptedException e) {
e.printStackTrace();
}
//Wait for coordinator to to return.
while (true) {
try {
FloeClient client = FloeClient.getInstance();
break;
} catch (TTransportException e) {
LOGGER.info("Coordinator not yet started.");
}
try {
LOGGER.info("Waiting for coodinator to start.");
Thread.sleep(Utils.Constants.MILLI);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Example 95
Project: floodlight-master File: PacketStreamerClient.java View source code |
/**
* Send test packets of the given OFMessageType to the packetstreamer server;
* @param client Packetstreamer client object
* @param numPackets number of test packets to be sent
* @param ofType OFMessageType of the test packets
* @param sync true if send with synchronous interface, false for asynchronous interface
* @throws TException
*/
private static void sendPackets(PacketStreamer.Client client, short numPackets, OFMessageType ofType, boolean sync) throws TException {
while (numPackets-- > 0) {
Message msg = new Message();
Packet packet = new Packet();
List<String> sids = new ArrayList<String>();
sids.add("session1");
sids.add("session2");
msg.setSessionIDs(sids);
packet.setMessageType(ofType);
long sw_dpid = numPackets / 40 + 1;
packet.setSwPortTuple(new SwitchPortTuple(sw_dpid, (short) (numPackets - (sw_dpid - 1) * 40)));
String strData = "New data, sequence " + numPackets;
packet.setData(strData.getBytes());
msg.setPacket(packet);
try {
if (sync) {
client.pushMessageSync(msg);
log.debug("Send packet sync: " + msg.toString());
} else {
client.pushMessageAsync(msg);
log.debug("Send packet sync: " + msg.toString());
}
} catch (TTransportException e) {
log.error(e.toString());
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}
Example 96
Project: floodlight-nfv-master File: PacketStreamerClient.java View source code |
/**
* Send test packets of the given OFMessageType to the packetstreamer server;
* @param client Packetstreamer client object
* @param numPackets number of test packets to be sent
* @param ofType OFMessageType of the test packets
* @param sync true if send with synchronous interface, false for asynchronous interface
* @throws TException
*/
private static void sendPackets(PacketStreamer.Client client, short numPackets, OFMessageType ofType, boolean sync) throws TException {
while (numPackets-- > 0) {
Message msg = new Message();
Packet packet = new Packet();
List<String> sids = new ArrayList<String>();
sids.add("session1");
sids.add("session2");
msg.setSessionIDs(sids);
packet.setMessageType(ofType);
long sw_dpid = numPackets / 40 + 1;
packet.setSwPortTuple(new SwitchPortTuple(sw_dpid, (short) (numPackets - (sw_dpid - 1) * 40)));
String strData = "New data, sequence " + numPackets;
packet.setData(strData.getBytes());
msg.setPacket(packet);
try {
if (sync) {
client.pushMessageSync(msg);
log.debug("Send packet sync: " + msg.toString());
} else {
client.pushMessageAsync(msg);
log.debug("Send packet sync: " + msg.toString());
}
} catch (TTransportException e) {
log.error(e.toString());
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}
Example 97
Project: floodlightUI-master File: PacketStreamerClient.java View source code |
/**
* Send test packets of the given OFMessageType to the packetstreamer server;
* @param client Packetstreamer client object
* @param numPackets number of test packets to be sent
* @param ofType OFMessageType of the test packets
* @param sync true if send with synchronous interface, false for asynchronous interface
* @throws TException
*/
private static void sendPackets(PacketStreamer.Client client, short numPackets, OFMessageType ofType, boolean sync) throws TException {
while (numPackets-- > 0) {
Message msg = new Message();
Packet packet = new Packet();
List<String> sids = new ArrayList<String>();
sids.add("session1");
sids.add("session2");
msg.setSessionIDs(sids);
packet.setMessageType(ofType);
long sw_dpid = numPackets / 40 + 1;
packet.setSwPortTuple(new SwitchPortTuple(sw_dpid, (short) (numPackets - (sw_dpid - 1) * 40)));
String strData = "New data, sequence " + numPackets;
packet.setData(strData.getBytes());
msg.setPacket(packet);
try {
if (sync) {
client.pushMessageSync(msg);
log.debug("Send packet sync: " + msg.toString());
} else {
client.pushMessageAsync(msg);
log.debug("Send packet sync: " + msg.toString());
}
} catch (TTransportException e) {
log.error(e.toString());
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}
Example 98
Project: floodlight_with_topoguard-master File: PacketStreamerClient.java View source code |
/**
* Send test packets of the given OFMessageType to the packetstreamer server;
* @param client Packetstreamer client object
* @param numPackets number of test packets to be sent
* @param ofType OFMessageType of the test packets
* @param sync true if send with synchronous interface, false for asynchronous interface
* @throws TException
*/
private static void sendPackets(PacketStreamer.Client client, short numPackets, OFMessageType ofType, boolean sync) throws TException {
while (numPackets-- > 0) {
Message msg = new Message();
Packet packet = new Packet();
List<String> sids = new ArrayList<String>();
sids.add("session1");
sids.add("session2");
msg.setSessionIDs(sids);
packet.setMessageType(ofType);
long sw_dpid = numPackets / 40 + 1;
packet.setSwPortTuple(new SwitchPortTuple(sw_dpid, (short) (numPackets - (sw_dpid - 1) * 40)));
String strData = "New data, sequence " + numPackets;
packet.setData(strData.getBytes());
msg.setPacket(packet);
try {
if (sync) {
client.pushMessageSync(msg);
log.debug("Send packet sync: " + msg.toString());
} else {
client.pushMessageAsync(msg);
log.debug("Send packet sync: " + msg.toString());
}
} catch (TTransportException e) {
log.error(e.toString());
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}
Example 99
Project: FL_HAND-master File: PacketStreamerClient.java View source code |
/**
* Send test packets of the given OFMessageType to the packetstreamer server;
* @param client Packetstreamer client object
* @param numPackets number of test packets to be sent
* @param ofType OFMessageType of the test packets
* @param sync true if send with synchronous interface, false for asynchronous interface
* @throws TException
*/
private static void sendPackets(PacketStreamer.Client client, short numPackets, OFMessageType ofType, boolean sync) throws TException {
while (numPackets-- > 0) {
Message msg = new Message();
Packet packet = new Packet();
List<String> sids = new ArrayList<String>();
sids.add("session1");
sids.add("session2");
msg.setSessionIDs(sids);
packet.setMessageType(ofType);
long sw_dpid = numPackets / 40 + 1;
packet.setSwPortTuple(new SwitchPortTuple(sw_dpid, (short) (numPackets - (sw_dpid - 1) * 40)));
String strData = "New data, sequence " + numPackets;
packet.setData(strData.getBytes());
msg.setPacket(packet);
try {
if (sync) {
client.pushMessageSync(msg);
log.debug("Send packet sync: " + msg.toString());
} else {
client.pushMessageAsync(msg);
log.debug("Send packet sync: " + msg.toString());
}
} catch (TTransportException e) {
log.error(e.toString());
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}
Example 100
Project: hector-master File: ExceptionsTranslatorImpl.java View source code |
@Override
public HectorException translate(Throwable original, CassandraHost host) {
HectorException he;
if (original instanceof HectorException) {
he = (HectorException) original;
} else if (original instanceof TApplicationException) {
he = new HCassandraInternalException(((TApplicationException) original).getType(), original.getMessage());
} else if (original instanceof TTransportException) {
// I seem to remember these coming back as TimedOutException previously
if (original.getCause() instanceof SocketTimeoutException) {
he = new HTimedOutException(original);
} else {
he = new HectorTransportException(original);
}
} else if (original instanceof org.apache.cassandra.thrift.TimedOutException) {
he = new HTimedOutException(original);
} else if (original instanceof org.apache.cassandra.thrift.InvalidRequestException) {
// See bug https://issues.apache.org/jira/browse/CASSANDRA-1862
// If a bootstrapping node is accessed it responds with IRE. It makes more sense to throw
// UnavailableException.
// Hector wraps this caveat and fixes this.
String why = ((org.apache.cassandra.thrift.InvalidRequestException) original).getWhy();
if (why != null && why.contains("bootstrap")) {
he = new HUnavailableException(original);
} else {
HInvalidRequestException e = new HInvalidRequestException(original);
e.setWhy(why);
he = e;
}
} else if (original instanceof TProtocolException) {
he = new HInvalidRequestException(original);
} else if (original instanceof org.apache.cassandra.thrift.NotFoundException) {
he = new HNotFoundException(original);
} else if (original instanceof org.apache.cassandra.thrift.UnavailableException) {
he = new HUnavailableException(original);
} else if (original instanceof TException) {
he = new HectorTransportException(original);
} else if (original instanceof NoSuchElementException) {
he = new HPoolExhaustedException(original);
} else if (original instanceof IllegalStateException) {
he = new PoolIllegalStateException(original);
} else {
he = new HectorException(original);
}
he.setHost(host);
return he;
}
Example 101
Project: hive_blinkdb-master File: TUGIAssumingTransport.java View source code |
@Override public void open() throws TTransportException { try { ugi.doAs(new PrivilegedExceptionAction<Void>() { public Void run() { try { wrapped.open(); } catch (TTransportException tte) { throw new RuntimeException(tte); } return null; } }); } catch (IOException ioe) { throw new RuntimeException("Received an ioe we never threw!", ioe); } catch (InterruptedException ie) { throw new RuntimeException("Received an ie we never threw!", ie); } catch (RuntimeException rte) { if (rte.getCause() instanceof TTransportException) { throw (TTransportException) rte.getCause(); } else { throw rte; } } }