Revert "THRIFT-2729: C++ - .clang-format created and applied"
This reverts commit 74260aa9099c3bb209bc8e524b0e8ba603f62c41.
diff --git a/lib/cpp/Makefile.am b/lib/cpp/Makefile.am
index d0bfe62..5206db8 100755
--- a/lib/cpp/Makefile.am
+++ b/lib/cpp/Makefile.am
@@ -243,6 +243,3 @@
thrift-z.pc.in \
thrift-qt.pc.in \
$(WINDOWS_DIST)
-
-style-local:
- $(CPPSTYLE_CMD)
diff --git a/lib/cpp/src/thrift/TApplicationException.cpp b/lib/cpp/src/thrift/TApplicationException.cpp
index 2f14653..1110ba2 100644
--- a/lib/cpp/src/thrift/TApplicationException.cpp
+++ b/lib/cpp/src/thrift/TApplicationException.cpp
@@ -20,8 +20,7 @@
#include <thrift/TApplicationException.h>
#include <thrift/protocol/TProtocol.h>
-namespace apache {
-namespace thrift {
+namespace apache { namespace thrift {
uint32_t TApplicationException::read(apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
@@ -77,5 +76,5 @@
xfer += oprot->writeStructEnd();
return xfer;
}
-}
-} // apache::thrift
+
+}} // apache::thrift
diff --git a/lib/cpp/src/thrift/TApplicationException.h b/lib/cpp/src/thrift/TApplicationException.h
index 0de5391..d32a21d 100644
--- a/lib/cpp/src/thrift/TApplicationException.h
+++ b/lib/cpp/src/thrift/TApplicationException.h
@@ -22,15 +22,16 @@
#include <thrift/Thrift.h>
-namespace apache {
-namespace thrift {
+
+namespace apache { namespace thrift {
namespace protocol {
-class TProtocol;
+ class TProtocol;
}
class TApplicationException : public TException {
-public:
+ public:
+
/**
* Error codes for the various types of exceptions.
*/
@@ -48,14 +49,22 @@
UNSUPPORTED_CLIENT_TYPE = 10
};
- TApplicationException() : TException(), type_(UNKNOWN) {}
+ TApplicationException() :
+ TException(),
+ type_(UNKNOWN) {}
- TApplicationException(TApplicationExceptionType type) : TException(), type_(type) {}
+ TApplicationException(TApplicationExceptionType type) :
+ TException(),
+ type_(type) {}
- TApplicationException(const std::string& message) : TException(message), type_(UNKNOWN) {}
+ TApplicationException(const std::string& message) :
+ TException(message),
+ type_(UNKNOWN) {}
- TApplicationException(TApplicationExceptionType type, const std::string& message)
- : TException(message), type_(type) {}
+ TApplicationException(TApplicationExceptionType type,
+ const std::string& message) :
+ TException(message),
+ type_(type) {}
virtual ~TApplicationException() throw() {}
@@ -65,35 +74,25 @@
*
* @return Error code
*/
- TApplicationExceptionType getType() { return type_; }
+ TApplicationExceptionType getType() {
+ return type_;
+ }
virtual const char* what() const throw() {
if (message_.empty()) {
switch (type_) {
- case UNKNOWN:
- return "TApplicationException: Unknown application exception";
- case UNKNOWN_METHOD:
- return "TApplicationException: Unknown method";
- case INVALID_MESSAGE_TYPE:
- return "TApplicationException: Invalid message type";
- case WRONG_METHOD_NAME:
- return "TApplicationException: Wrong method name";
- case BAD_SEQUENCE_ID:
- return "TApplicationException: Bad sequence identifier";
- case MISSING_RESULT:
- return "TApplicationException: Missing result";
- case INTERNAL_ERROR:
- return "TApplicationException: Internal error";
- case PROTOCOL_ERROR:
- return "TApplicationException: Protocol error";
- case INVALID_TRANSFORM:
- return "TApplicationException: Invalid transform";
- case INVALID_PROTOCOL:
- return "TApplicationException: Invalid protocol";
- case UNSUPPORTED_CLIENT_TYPE:
- return "TApplicationException: Unsupported client type";
- default:
- return "TApplicationException: (Invalid exception type)";
+ case UNKNOWN : return "TApplicationException: Unknown application exception";
+ case UNKNOWN_METHOD : return "TApplicationException: Unknown method";
+ case INVALID_MESSAGE_TYPE : return "TApplicationException: Invalid message type";
+ case WRONG_METHOD_NAME : return "TApplicationException: Wrong method name";
+ case BAD_SEQUENCE_ID : return "TApplicationException: Bad sequence identifier";
+ case MISSING_RESULT : return "TApplicationException: Missing result";
+ case INTERNAL_ERROR : return "TApplicationException: Internal error";
+ case PROTOCOL_ERROR : return "TApplicationException: Protocol error";
+ case INVALID_TRANSFORM : return "TApplicationException: Invalid transform";
+ case INVALID_PROTOCOL : return "TApplicationException: Invalid protocol";
+ case UNSUPPORTED_CLIENT_TYPE : return "TApplicationException: Unsupported client type";
+ default : return "TApplicationException: (Invalid exception type)";
};
} else {
return message_.c_str();
@@ -103,13 +102,14 @@
uint32_t read(protocol::TProtocol* iprot);
uint32_t write(protocol::TProtocol* oprot) const;
-protected:
+ protected:
/**
* Error code
*/
TApplicationExceptionType type_;
+
};
-}
-} // apache::thrift
+
+}} // apache::thrift
#endif // #ifndef _THRIFT_TAPPLICATIONEXCEPTION_H_
diff --git a/lib/cpp/src/thrift/TDispatchProcessor.h b/lib/cpp/src/thrift/TDispatchProcessor.h
index fd1dce7..33ec22e 100644
--- a/lib/cpp/src/thrift/TDispatchProcessor.h
+++ b/lib/cpp/src/thrift/TDispatchProcessor.h
@@ -21,8 +21,7 @@
#include <thrift/TProcessor.h>
-namespace apache {
-namespace thrift {
+namespace apache { namespace thrift {
/**
* TDispatchProcessor is a helper class to parse the message header then call
@@ -32,7 +31,7 @@
*/
template <class Protocol_>
class TDispatchProcessorT : public TProcessor {
-public:
+ public:
virtual bool process(boost::shared_ptr<protocol::TProtocol> in,
boost::shared_ptr<protocol::TProtocol> out,
void* connectionContext) {
@@ -61,14 +60,15 @@
// (The old generated processor code used to try to skip a T_STRUCT and
// continue. However, that seems unsafe.)
if (mtype != protocol::T_CALL && mtype != protocol::T_ONEWAY) {
- GlobalOutput.printf("received invalid message type %d from client", mtype);
+ GlobalOutput.printf("received invalid message type %d from client",
+ mtype);
return false;
}
return this->dispatchCall(inRaw, outRaw, fname, seqid, connectionContext);
}
-protected:
+ protected:
bool processFast(Protocol_* in, Protocol_* out, void* connectionContext) {
std::string fname;
protocol::TMessageType mtype;
@@ -76,11 +76,13 @@
in->readMessageBegin(fname, mtype, seqid);
if (mtype != protocol::T_CALL && mtype != protocol::T_ONEWAY) {
- GlobalOutput.printf("received invalid message type %d from client", mtype);
+ GlobalOutput.printf("received invalid message type %d from client",
+ mtype);
return false;
}
- return this->dispatchCallTemplated(in, out, fname, seqid, connectionContext);
+ return this->dispatchCallTemplated(in, out, fname,
+ seqid, connectionContext);
}
/**
@@ -88,14 +90,11 @@
*/
virtual bool dispatchCall(apache::thrift::protocol::TProtocol* in,
apache::thrift::protocol::TProtocol* out,
- const std::string& fname,
- int32_t seqid,
+ const std::string& fname, int32_t seqid,
void* callContext) = 0;
- virtual bool dispatchCallTemplated(Protocol_* in,
- Protocol_* out,
- const std::string& fname,
- int32_t seqid,
+ virtual bool dispatchCallTemplated(Protocol_* in, Protocol_* out,
+ const std::string& fname, int32_t seqid,
void* callContext) = 0;
};
@@ -104,7 +103,7 @@
* perform a dynamic_cast.
*/
class TDispatchProcessor : public TProcessor {
-public:
+ public:
virtual bool process(boost::shared_ptr<protocol::TProtocol> in,
boost::shared_ptr<protocol::TProtocol> out,
void* connectionContext) {
@@ -114,28 +113,30 @@
in->readMessageBegin(fname, mtype, seqid);
if (mtype != protocol::T_CALL && mtype != protocol::T_ONEWAY) {
- GlobalOutput.printf("received invalid message type %d from client", mtype);
+ GlobalOutput.printf("received invalid message type %d from client",
+ mtype);
return false;
}
return dispatchCall(in.get(), out.get(), fname, seqid, connectionContext);
}
-protected:
+ protected:
virtual bool dispatchCall(apache::thrift::protocol::TProtocol* in,
apache::thrift::protocol::TProtocol* out,
- const std::string& fname,
- int32_t seqid,
+ const std::string& fname, int32_t seqid,
void* callContext) = 0;
};
// Specialize TDispatchProcessorT for TProtocol and TDummyProtocol just to use
// the generic TDispatchProcessor.
template <>
-class TDispatchProcessorT<protocol::TDummyProtocol> : public TDispatchProcessor {};
+class TDispatchProcessorT<protocol::TDummyProtocol> :
+ public TDispatchProcessor {};
template <>
-class TDispatchProcessorT<protocol::TProtocol> : public TDispatchProcessor {};
-}
-} // apache::thrift
+class TDispatchProcessorT<protocol::TProtocol> :
+ public TDispatchProcessor {};
+
+}} // apache::thrift
#endif // _THRIFT_TDISPATCHPROCESSOR_H_
diff --git a/lib/cpp/src/thrift/TLogging.h b/lib/cpp/src/thrift/TLogging.h
index 096054c..4c8bddc 100644
--- a/lib/cpp/src/thrift/TLogging.h
+++ b/lib/cpp/src/thrift/TLogging.h
@@ -39,11 +39,13 @@
*/
#define T_GLOBAL_DEBUGGING_LEVEL 0
+
/**
* T_GLOBAL_LOGGING_LEVEL = 0: all logging turned off, logging macros undefined
* T_GLOBAL_LOGGING_LEVEL = 1: all logging turned on
*/
-#define T_GLOBAL_LOGGING_LEVEL 1
+#define T_GLOBAL_LOGGING_LEVEL 1
+
/**
* Standard wrapper around fprintf what will prefix the file name and line
@@ -53,40 +55,37 @@
* @param format_string
*/
#if T_GLOBAL_DEBUGGING_LEVEL > 0
-#define T_DEBUG(format_string, ...) \
- if (T_GLOBAL_DEBUGGING_LEVEL > 0) { \
- fprintf(stderr, "[%s,%d] " format_string " \n", __FILE__, __LINE__, ##__VA_ARGS__); \
+ #define T_DEBUG(format_string,...) \
+ if (T_GLOBAL_DEBUGGING_LEVEL > 0) { \
+ fprintf(stderr,"[%s,%d] " format_string " \n", __FILE__, __LINE__,##__VA_ARGS__); \
}
#else
-#define T_DEBUG(format_string, ...)
+ #define T_DEBUG(format_string,...)
#endif
+
/**
* analagous to T_DEBUG but also prints the time
*
* @param string format_string input: printf style format string
*/
#if T_GLOBAL_DEBUGGING_LEVEL > 0
-#define T_DEBUG_T(format_string, ...) \
- { \
- if (T_GLOBAL_DEBUGGING_LEVEL > 0) { \
- time_t now; \
- char dbgtime[26]; \
- time(&now); \
- THRIFT_CTIME_R(&now, dbgtime); \
- dbgtime[24] = '\0'; \
- fprintf(stderr, \
- "[%s,%d] [%s] " format_string " \n", \
- __FILE__, \
- __LINE__, \
- dbgtime, \
- ##__VA_ARGS__); \
- } \
- }
+ #define T_DEBUG_T(format_string,...) \
+ { \
+ if (T_GLOBAL_DEBUGGING_LEVEL > 0) { \
+ time_t now; \
+ char dbgtime[26] ; \
+ time(&now); \
+ THRIFT_CTIME_R(&now, dbgtime); \
+ dbgtime[24] = '\0'; \
+ fprintf(stderr,"[%s,%d] [%s] " format_string " \n", __FILE__, __LINE__,dbgtime,##__VA_ARGS__); \
+ } \
+ }
#else
-#define T_DEBUG_T(format_string, ...)
+ #define T_DEBUG_T(format_string,...)
#endif
+
/**
* analagous to T_DEBUG but uses input level to determine whether or not the string
* should be logged.
@@ -94,74 +93,68 @@
* @param int level: specified debug level
* @param string format_string input: format string
*/
-#define T_DEBUG_L(level, format_string, ...) \
- if ((level) > 0) { \
- fprintf(stderr, "[%s,%d] " format_string " \n", __FILE__, __LINE__, ##__VA_ARGS__); \
+#define T_DEBUG_L(level, format_string,...) \
+ if ((level) > 0) { \
+ fprintf(stderr,"[%s,%d] " format_string " \n", __FILE__, __LINE__,##__VA_ARGS__); \
}
+
/**
* Explicit error logging. Prints time, file name and line number
*
* @param string format_string input: printf style format string
*/
-#define T_ERROR(format_string, ...) \
- { \
- time_t now; \
- char dbgtime[26]; \
- time(&now); \
- THRIFT_CTIME_R(&now, dbgtime); \
- dbgtime[24] = '\0'; \
- fprintf(stderr, \
- "[%s,%d] [%s] ERROR: " format_string " \n", \
- __FILE__, \
- __LINE__, \
- dbgtime, \
- ##__VA_ARGS__); \
+#define T_ERROR(format_string,...) \
+ { \
+ time_t now; \
+ char dbgtime[26] ; \
+ time(&now); \
+ THRIFT_CTIME_R(&now, dbgtime); \
+ dbgtime[24] = '\0'; \
+ fprintf(stderr,"[%s,%d] [%s] ERROR: " format_string " \n", __FILE__, __LINE__,dbgtime,##__VA_ARGS__); \
}
+
/**
* Analagous to T_ERROR, additionally aborting the process.
* WARNING: macro calls abort(), ending program execution
*
* @param string format_string input: printf style format string
*/
-#define T_ERROR_ABORT(format_string, ...) \
- { \
- time_t now; \
- char dbgtime[26]; \
- time(&now); \
- THRIFT_CTIME_R(&now, dbgtime); \
- dbgtime[24] = '\0'; \
- fprintf(stderr, \
- "[%s,%d] [%s] ERROR: Going to abort " format_string " \n", \
- __FILE__, \
- __LINE__, \
- dbgtime, \
- ##__VA_ARGS__); \
- exit(1); \
+#define T_ERROR_ABORT(format_string,...) \
+ { \
+ time_t now; \
+ char dbgtime[26] ; \
+ time(&now); \
+ THRIFT_CTIME_R(&now, dbgtime); \
+ dbgtime[24] = '\0'; \
+ fprintf(stderr,"[%s,%d] [%s] ERROR: Going to abort " format_string " \n", __FILE__, __LINE__,dbgtime,##__VA_ARGS__); \
+ exit(1); \
}
+
/**
* Log input message
*
* @param string format_string input: printf style format string
*/
#if T_GLOBAL_LOGGING_LEVEL > 0
-#define T_LOG_OPER(format_string, ...) \
- { \
- if (T_GLOBAL_LOGGING_LEVEL > 0) { \
- time_t now; \
- char dbgtime[26]; \
- time(&now); \
- THRIFT_CTIME_R(&now, dbgtime); \
- dbgtime[24] = '\0'; \
- fprintf(stderr, "[%s] " format_string " \n", dbgtime, ##__VA_ARGS__); \
- } \
- }
+ #define T_LOG_OPER(format_string,...) \
+ { \
+ if (T_GLOBAL_LOGGING_LEVEL > 0) { \
+ time_t now; \
+ char dbgtime[26] ; \
+ time(&now); \
+ THRIFT_CTIME_R(&now, dbgtime); \
+ dbgtime[24] = '\0'; \
+ fprintf(stderr,"[%s] " format_string " \n", dbgtime,##__VA_ARGS__); \
+ } \
+ }
#else
-#define T_LOG_OPER(format_string, ...)
+ #define T_LOG_OPER(format_string,...)
#endif
+
/**
* T_GLOBAL_DEBUG_VIRTUAL = 0 or unset: normal operation,
* virtual call debug messages disabled
@@ -172,24 +165,29 @@
* apache::thrift::profile_print_info()
*/
#if T_GLOBAL_DEBUG_VIRTUAL > 1
-#define T_VIRTUAL_CALL() ::apache::thrift::profile_virtual_call(typeid(*this))
-#define T_GENERIC_PROTOCOL(template_class, generic_prot, specific_prot) \
- do { \
- if (!(specific_prot)) { \
- ::apache::thrift::profile_generic_protocol(typeid(*template_class), typeid(*generic_prot)); \
- } \
- } while (0)
+ #define T_VIRTUAL_CALL() \
+ ::apache::thrift::profile_virtual_call(typeid(*this))
+ #define T_GENERIC_PROTOCOL(template_class, generic_prot, specific_prot) \
+ do { \
+ if (!(specific_prot)) { \
+ ::apache::thrift::profile_generic_protocol( \
+ typeid(*template_class), typeid(*generic_prot)); \
+ } \
+ } while (0)
#elif T_GLOBAL_DEBUG_VIRTUAL == 1
-#define T_VIRTUAL_CALL() fprintf(stderr, "[%s,%d] virtual call\n", __FILE__, __LINE__)
-#define T_GENERIC_PROTOCOL(template_class, generic_prot, specific_prot) \
- do { \
- if (!(specific_prot)) { \
- fprintf(stderr, "[%s,%d] failed to cast to specific protocol type\n", __FILE__, __LINE__); \
- } \
- } while (0)
+ #define T_VIRTUAL_CALL() \
+ fprintf(stderr,"[%s,%d] virtual call\n", __FILE__, __LINE__)
+ #define T_GENERIC_PROTOCOL(template_class, generic_prot, specific_prot) \
+ do { \
+ if (!(specific_prot)) { \
+ fprintf(stderr, \
+ "[%s,%d] failed to cast to specific protocol type\n", \
+ __FILE__, __LINE__); \
+ } \
+ } while (0)
#else
-#define T_VIRTUAL_CALL()
-#define T_GENERIC_PROTOCOL(template_class, generic_prot, specific_prot)
+ #define T_VIRTUAL_CALL()
+ #define T_GENERIC_PROTOCOL(template_class, generic_prot, specific_prot)
#endif
#endif // #ifndef _THRIFT_TLOGGING_H_
diff --git a/lib/cpp/src/thrift/TProcessor.h b/lib/cpp/src/thrift/TProcessor.h
index d8f86c4..b4a4657 100644
--- a/lib/cpp/src/thrift/TProcessor.h
+++ b/lib/cpp/src/thrift/TProcessor.h
@@ -24,8 +24,7 @@
#include <thrift/protocol/TProtocol.h>
#include <boost/shared_ptr.hpp>
-namespace apache {
-namespace thrift {
+namespace apache { namespace thrift {
/**
* Virtual interface class that can handle events from the processor. To
@@ -35,7 +34,8 @@
* instance's state).
*/
class TProcessorEventHandler {
-public:
+ public:
+
virtual ~TProcessorEventHandler() {}
/**
@@ -45,8 +45,8 @@
* for that function invocation.
*/
virtual void* getContext(const char* fn_name, void* serverContext) {
- (void)fn_name;
- (void)serverContext;
+ (void) fn_name;
+ (void) serverContext;
return NULL;
}
@@ -54,61 +54,61 @@
* Expected to free resources associated with a context.
*/
virtual void freeContext(void* ctx, const char* fn_name) {
- (void)ctx;
- (void)fn_name;
+ (void) ctx;
+ (void) fn_name;
}
/**
* Called before reading arguments.
*/
virtual void preRead(void* ctx, const char* fn_name) {
- (void)ctx;
- (void)fn_name;
+ (void) ctx;
+ (void) fn_name;
}
/**
* Called between reading arguments and calling the handler.
*/
virtual void postRead(void* ctx, const char* fn_name, uint32_t bytes) {
- (void)ctx;
- (void)fn_name;
- (void)bytes;
+ (void) ctx;
+ (void) fn_name;
+ (void) bytes;
}
/**
* Called between calling the handler and writing the response.
*/
virtual void preWrite(void* ctx, const char* fn_name) {
- (void)ctx;
- (void)fn_name;
+ (void) ctx;
+ (void) fn_name;
}
/**
* Called after writing the response.
*/
virtual void postWrite(void* ctx, const char* fn_name, uint32_t bytes) {
- (void)ctx;
- (void)fn_name;
- (void)bytes;
+ (void) ctx;
+ (void) fn_name;
+ (void) bytes;
}
/**
* Called when an async function call completes successfully.
*/
virtual void asyncComplete(void* ctx, const char* fn_name) {
- (void)ctx;
- (void)fn_name;
+ (void) ctx;
+ (void) fn_name;
}
/**
* Called if the handler throws an undeclared exception.
*/
virtual void handlerError(void* ctx, const char* fn_name) {
- (void)ctx;
- (void)fn_name;
+ (void) ctx;
+ (void) fn_name;
}
-protected:
+ protected:
TProcessorEventHandler() {}
};
@@ -116,16 +116,12 @@
* A helper class used by the generated code to free each context.
*/
class TProcessorContextFreer {
-public:
- TProcessorContextFreer(TProcessorEventHandler* handler, void* context, const char* method)
- : handler_(handler), context_(context), method_(method) {}
- ~TProcessorContextFreer() {
- if (handler_ != NULL)
- handler_->freeContext(context_, method_);
- }
+ public:
+ TProcessorContextFreer(TProcessorEventHandler* handler, void* context, const char* method) :
+ handler_(handler), context_(context), method_(method) {}
+ ~TProcessorContextFreer() { if (handler_ != NULL) handler_->freeContext(context_, method_); }
void unregister() { handler_ = NULL; }
-
-private:
+ private:
apache::thrift::TProcessorEventHandler* handler_;
void* context_;
const char* method_;
@@ -139,24 +135,27 @@
*
*/
class TProcessor {
-public:
+ public:
virtual ~TProcessor() {}
virtual bool process(boost::shared_ptr<protocol::TProtocol> in,
boost::shared_ptr<protocol::TProtocol> out,
void* connectionContext) = 0;
- bool process(boost::shared_ptr<apache::thrift::protocol::TProtocol> io, void* connectionContext) {
+ bool process(boost::shared_ptr<apache::thrift::protocol::TProtocol> io,
+ void* connectionContext) {
return process(io, io, connectionContext);
}
- boost::shared_ptr<TProcessorEventHandler> getEventHandler() { return eventHandler_; }
+ boost::shared_ptr<TProcessorEventHandler> getEventHandler() {
+ return eventHandler_;
+ }
void setEventHandler(boost::shared_ptr<TProcessorEventHandler> eventHandler) {
eventHandler_ = eventHandler;
}
-protected:
+ protected:
TProcessor() {}
boost::shared_ptr<TProcessorEventHandler> eventHandler_;
@@ -174,20 +173,20 @@
* parameter to a shared_ptr, so that factory->releaseHandler() will be called
* when the object is no longer needed, instead of deleting the pointer.
*/
-template <typename HandlerFactory_>
+template<typename HandlerFactory_>
class ReleaseHandler {
-public:
- ReleaseHandler(const boost::shared_ptr<HandlerFactory_>& handlerFactory)
- : handlerFactory_(handlerFactory) {}
+ public:
+ ReleaseHandler(const boost::shared_ptr<HandlerFactory_>& handlerFactory) :
+ handlerFactory_(handlerFactory) {}
- void operator()(typename HandlerFactory_::Handler* handler) {
- if (handler) {
- handlerFactory_->releaseHandler(handler);
- }
- }
+ void operator()(typename HandlerFactory_::Handler* handler) {
+ if (handler) {
+ handlerFactory_->releaseHandler(handler);
+ }
+ }
-private:
- boost::shared_ptr<HandlerFactory_> handlerFactory_;
+ private:
+ boost::shared_ptr<HandlerFactory_> handlerFactory_;
};
struct TConnectionInfo {
@@ -202,7 +201,7 @@
};
class TProcessorFactory {
-public:
+ public:
virtual ~TProcessorFactory() {}
/**
@@ -212,19 +211,23 @@
* accepted on. This generally means that this call does not need to be
* thread safe, as it will always be invoked from a single thread.
*/
- virtual boost::shared_ptr<TProcessor> getProcessor(const TConnectionInfo& connInfo) = 0;
+ virtual boost::shared_ptr<TProcessor> getProcessor(
+ const TConnectionInfo& connInfo) = 0;
};
class TSingletonProcessorFactory : public TProcessorFactory {
-public:
- TSingletonProcessorFactory(boost::shared_ptr<TProcessor> processor) : processor_(processor) {}
+ public:
+ TSingletonProcessorFactory(boost::shared_ptr<TProcessor> processor) :
+ processor_(processor) {}
- boost::shared_ptr<TProcessor> getProcessor(const TConnectionInfo&) { return processor_; }
+ boost::shared_ptr<TProcessor> getProcessor(const TConnectionInfo&) {
+ return processor_;
+ }
-private:
+ private:
boost::shared_ptr<TProcessor> processor_;
};
-}
-} // apache::thrift
+
+}} // apache::thrift
#endif // #ifndef _THRIFT_TPROCESSOR_H_
diff --git a/lib/cpp/src/thrift/TReflectionLocal.h b/lib/cpp/src/thrift/TReflectionLocal.h
index 2fc53c8..2ef7511 100644
--- a/lib/cpp/src/thrift/TReflectionLocal.h
+++ b/lib/cpp/src/thrift/TReflectionLocal.h
@@ -31,10 +31,7 @@
*
*/
-namespace apache {
-namespace thrift {
-namespace reflection {
-namespace local {
+namespace apache { namespace thrift { namespace reflection { namespace local {
using apache::thrift::protocol::TType;
@@ -50,7 +47,7 @@
struct TypeSpec {
TType ttype;
- uint8_t fp_prefix[FP_PREFIX_LEN];
+ uint8_t fp_prefix[FP_PREFIX_LEN];
// Use an anonymous union here so we can fit two TypeSpecs in one cache line.
union {
@@ -60,8 +57,8 @@
TypeSpec** specs;
} tstruct;
struct {
- TypeSpec* subtype1;
- TypeSpec* subtype2;
+ TypeSpec *subtype1;
+ TypeSpec *subtype2;
} tcontainer;
};
@@ -69,24 +66,31 @@
// so take the plunge and use constructors.
// Hopefully they'll be evaluated at compile time.
- TypeSpec(TType ttype) : ttype(ttype) { std::memset(fp_prefix, 0, FP_PREFIX_LEN); }
+ TypeSpec(TType ttype) : ttype(ttype) {
+ std::memset(fp_prefix, 0, FP_PREFIX_LEN);
+ }
- TypeSpec(TType ttype, const uint8_t* fingerprint, FieldMeta* metas, TypeSpec** specs)
- : ttype(ttype) {
+ TypeSpec(TType ttype,
+ const uint8_t* fingerprint,
+ FieldMeta* metas,
+ TypeSpec** specs) :
+ ttype(ttype)
+ {
std::memcpy(fp_prefix, fingerprint, FP_PREFIX_LEN);
tstruct.metas = metas;
tstruct.specs = specs;
}
- TypeSpec(TType ttype, TypeSpec* subtype1, TypeSpec* subtype2) : ttype(ttype) {
+ TypeSpec(TType ttype, TypeSpec* subtype1, TypeSpec* subtype2) :
+ ttype(ttype)
+ {
std::memset(fp_prefix, 0, FP_PREFIX_LEN);
tcontainer.subtype1 = subtype1;
tcontainer.subtype2 = subtype2;
}
+
};
-}
-}
-}
-} // apache::thrift::reflection::local
+
+}}}} // apache::thrift::reflection::local
#endif // #ifndef _THRIFT_TREFLECTIONLOCAL_H_
diff --git a/lib/cpp/src/thrift/TToString.h b/lib/cpp/src/thrift/TToString.h
index 5023869..c160e09 100644
--- a/lib/cpp/src/thrift/TToString.h
+++ b/lib/cpp/src/thrift/TToString.h
@@ -28,8 +28,7 @@
#include <string>
#include <sstream>
-namespace apache {
-namespace thrift {
+namespace apache { namespace thrift {
template <typename T>
std::string to_string(const T& t) {
@@ -53,7 +52,8 @@
}
template <typename T>
-std::string to_string(const T& beg, const T& end) {
+std::string to_string(const T& beg, const T& end)
+{
std::ostringstream o;
for (T it = beg; it != end; ++it) {
if (it != beg)
@@ -83,7 +83,7 @@
o << "{" << to_string(s.begin(), s.end()) << "}";
return o.str();
}
-}
-} // apache::thrift
+
+}} // apache::thrift
#endif // _THRIFT_TOSTRING_H_
diff --git a/lib/cpp/src/thrift/Thrift.cpp b/lib/cpp/src/thrift/Thrift.cpp
index 5739d0f..b1e1386 100644
--- a/lib/cpp/src/thrift/Thrift.cpp
+++ b/lib/cpp/src/thrift/Thrift.cpp
@@ -24,12 +24,11 @@
#include <stdarg.h>
#include <stdio.h>
-namespace apache {
-namespace thrift {
+namespace apache { namespace thrift {
TOutput GlobalOutput;
-void TOutput::printf(const char* message, ...) {
+void TOutput::printf(const char *message, ...) {
#ifndef THRIFT_SQUELCH_CONSOLE_OUTPUT
// Try to reduce heap usage, even if printf is called rarely.
static const int STACK_BUF_SIZE = 256;
@@ -59,7 +58,7 @@
}
#endif
- char* heap_buf = (char*)malloc((need + 1) * sizeof(char));
+ char *heap_buf = (char*)malloc((need+1) * sizeof(char));
if (heap_buf == NULL) {
#ifdef _MSC_VER
va_start(ap, message);
@@ -72,7 +71,7 @@
}
va_start(ap, message);
- int rval = vsnprintf(heap_buf, need + 1, message, ap);
+ int rval = vsnprintf(heap_buf, need+1, message, ap);
va_end(ap);
// TODO(shigin): inform user
if (rval != -1) {
@@ -93,7 +92,7 @@
#endif
}
-void TOutput::perror(const char* message, int errno_copy) {
+void TOutput::perror(const char *message, int errno_copy) {
std::string out = message + strerror_s(errno_copy);
f_(out.c_str());
}
@@ -101,18 +100,18 @@
std::string TOutput::strerror_s(int errno_copy) {
#ifndef HAVE_STRERROR_R
return "errno = " + boost::lexical_cast<std::string>(errno_copy);
-#else // HAVE_STRERROR_R
+#else // HAVE_STRERROR_R
- char b_errbuf[1024] = {'\0'};
+ char b_errbuf[1024] = { '\0' };
#ifdef STRERROR_R_CHAR_P
- char* b_error = strerror_r(errno_copy, b_errbuf, sizeof(b_errbuf));
+ char *b_error = strerror_r(errno_copy, b_errbuf, sizeof(b_errbuf));
#else
- char* b_error = b_errbuf;
+ char *b_error = b_errbuf;
int rv = strerror_r(errno_copy, b_errbuf, sizeof(b_errbuf));
if (rv == -1) {
// strerror_r failed. omgwtfbbq.
- return "XSI-compliant strerror_r() failed with errno = "
- + boost::lexical_cast<std::string>(errno_copy);
+ return "XSI-compliant strerror_r() failed with errno = " +
+ boost::lexical_cast<std::string>(errno_copy);
}
#endif
// Can anyone prove that explicit cast is probably not necessary
@@ -120,7 +119,7 @@
// b_error becomes invalid?
return std::string(b_error);
-#endif // HAVE_STRERROR_R
+#endif // HAVE_STRERROR_R
}
-}
-} // apache::thrift
+
+}} // apache::thrift
diff --git a/lib/cpp/src/thrift/Thrift.h b/lib/cpp/src/thrift/Thrift.h
index 9ddf946..4d8d87c 100644
--- a/lib/cpp/src/thrift/Thrift.h
+++ b/lib/cpp/src/thrift/Thrift.h
@@ -62,33 +62,40 @@
* THRIFT_OVERLOAD_IF_DEFN should be used in the function definition, if it is
* defined separately from where it is declared.
*/
-#define THRIFT_OVERLOAD_IF_DEFN(T, Y) \
- typename ::boost::enable_if<typename ::boost::is_convertible<T*, Y*>::type, void*>::type
+#define THRIFT_OVERLOAD_IF_DEFN(T, Y) \
+ typename ::boost::enable_if<typename ::boost::is_convertible<T*, Y*>::type, \
+ void*>::type
-#define THRIFT_OVERLOAD_IF(T, Y) THRIFT_OVERLOAD_IF_DEFN(T, Y) = NULL
+#define THRIFT_OVERLOAD_IF(T, Y) \
+ THRIFT_OVERLOAD_IF_DEFN(T, Y) = NULL
#define THRIFT_UNUSED_VARIABLE(x) ((void)(x))
-namespace apache {
-namespace thrift {
+namespace apache { namespace thrift {
-class TEnumIterator
- : public std::iterator<std::forward_iterator_tag, std::pair<int, const char*> > {
-public:
- TEnumIterator(int n, int* enums, const char** names)
- : ii_(0), n_(n), enums_(enums), names_(names) {}
+class TEnumIterator : public std::iterator<std::forward_iterator_tag, std::pair<int, const char*> > {
+ public:
+ TEnumIterator(int n,
+ int* enums,
+ const char** names) :
+ ii_(0), n_(n), enums_(enums), names_(names) {
+ }
- int operator++() { return ++ii_; }
+ int operator ++() {
+ return ++ii_;
+ }
- bool operator!=(const TEnumIterator& end) {
- (void)end; // avoid "unused" warning with NDEBUG
+ bool operator !=(const TEnumIterator& end) {
+ (void)end; // avoid "unused" warning with NDEBUG
assert(end.n_ == -1);
return (ii_ != n_);
}
- std::pair<int, const char*> operator*() const { return std::make_pair(enums_[ii_], names_[ii_]); }
+ std::pair<int, const char*> operator*() const {
+ return std::make_pair(enums_[ii_], names_[ii_]);
+ }
-private:
+ private:
int ii_;
const int n_;
int* enums_;
@@ -96,40 +103,46 @@
};
class TOutput {
-public:
+ public:
TOutput() : f_(&errorTimeWrapper) {}
- inline void setOutputFunction(void (*function)(const char*)) { f_ = function; }
+ inline void setOutputFunction(void (*function)(const char *)){
+ f_ = function;
+ }
- inline void operator()(const char* message) { f_(message); }
+ inline void operator()(const char *message){
+ f_(message);
+ }
// It is important to have a const char* overload here instead of
// just the string version, otherwise errno could be corrupted
// if there is some problem allocating memory when constructing
// the string.
- void perror(const char* message, int errno_copy);
- inline void perror(const std::string& message, int errno_copy) {
+ void perror(const char *message, int errno_copy);
+ inline void perror(const std::string &message, int errno_copy) {
perror(message.c_str(), errno_copy);
}
- void printf(const char* message, ...);
+ void printf(const char *message, ...);
static void errorTimeWrapper(const char* msg);
/** Just like strerror_r but returns a C++ string object. */
static std::string strerror_s(int errno_copy);
-private:
- void (*f_)(const char*);
+ private:
+ void (*f_)(const char *);
};
extern TOutput GlobalOutput;
class TException : public std::exception {
-public:
- TException() : message_() {}
+ public:
+ TException():
+ message_() {}
- TException(const std::string& message) : message_(message) {}
+ TException(const std::string& message) :
+ message_(message) {}
virtual ~TException() throw() {}
@@ -141,36 +154,33 @@
}
}
-protected:
+ protected:
std::string message_;
+
};
+
// Forward declare this structure used by TDenseProtocol
-namespace reflection {
-namespace local {
+namespace reflection { namespace local {
struct TypeSpec;
-}
-}
+}}
class TDelayedException {
-public:
- template <class E>
- static TDelayedException* delayException(const E& e);
+ public:
+ template <class E> static TDelayedException* delayException(const E& e);
virtual void throw_it() = 0;
- virtual ~TDelayedException(){};
+ virtual ~TDelayedException() {};
};
-template <class E>
-class TExceptionWrapper : public TDelayedException {
-public:
+template <class E> class TExceptionWrapper : public TDelayedException {
+ public:
TExceptionWrapper(const E& e) : e_(e) {}
virtual void throw_it() {
E temp(e_);
delete this;
throw temp;
}
-
-private:
+ private:
E e_;
};
@@ -181,12 +191,13 @@
#if T_GLOBAL_DEBUG_VIRTUAL > 1
void profile_virtual_call(const std::type_info& info);
-void profile_generic_protocol(const std::type_info& template_type, const std::type_info& prot_type);
-void profile_print_info(FILE* f);
+void profile_generic_protocol(const std::type_info& template_type,
+ const std::type_info& prot_type);
+void profile_print_info(FILE *f);
void profile_print_info();
void profile_write_pprof(FILE* gen_calls_f, FILE* virtual_calls_f);
#endif
-}
-} // apache::thrift
+
+}} // apache::thrift
#endif // #ifndef _THRIFT_THRIFT_H_
diff --git a/lib/cpp/src/thrift/VirtualProfiling.cpp b/lib/cpp/src/thrift/VirtualProfiling.cpp
index 6ce346b..180cfb7 100644
--- a/lib/cpp/src/thrift/VirtualProfiling.cpp
+++ b/lib/cpp/src/thrift/VirtualProfiling.cpp
@@ -35,14 +35,14 @@
#error "Thrift virtual function profiling currently requires glibc"
#endif // !__GLIBC__
+
#include <thrift/concurrency/Mutex.h>
#include <ext/hash_map>
#include <execinfo.h>
#include <stdio.h>
-namespace apache {
-namespace thrift {
+namespace apache { namespace thrift {
using ::apache::thrift::concurrency::Mutex;
using ::apache::thrift::concurrency::Guard;
@@ -53,18 +53,20 @@
* A stack trace
*/
class Backtrace {
-public:
+ public:
Backtrace(int skip = 0);
- Backtrace(Backtrace const& bt);
+ Backtrace(Backtrace const &bt);
- void operator=(Backtrace const& bt) {
+ void operator=(Backtrace const &bt) {
numCallers_ = bt.numCallers_;
if (numCallers_ >= 0) {
memcpy(callers_, bt.callers_, numCallers_ * sizeof(void*));
}
}
- bool operator==(Backtrace const& bt) const { return (cmp(bt) == 0); }
+ bool operator==(Backtrace const &bt) const {
+ return (cmp(bt) == 0);
+ }
size_t hash() const {
intptr_t ret = 0;
@@ -81,8 +83,8 @@
}
for (int n = 0; n < numCallers_; ++n) {
- int diff = reinterpret_cast<intptr_t>(callers_[n])
- - reinterpret_cast<intptr_t>(bt.callers_[n]);
+ int diff = reinterpret_cast<intptr_t>(callers_[n]) -
+ reinterpret_cast<intptr_t>(bt.callers_[n]);
if (diff != 0) {
return diff;
}
@@ -91,8 +93,8 @@
return 0;
}
- void print(FILE* f, int indent = 0, int start = 0) const {
- char** strings = backtrace_symbols(callers_, numCallers_);
+ void print(FILE *f, int indent=0, int start=0) const {
+ char **strings = backtrace_symbols(callers_, numCallers_);
if (strings) {
start += skip_;
if (start < 0) {
@@ -107,9 +109,11 @@
}
}
- int getDepth() const { return numCallers_ - skip_; }
+ int getDepth() const {
+ return numCallers_ - skip_;
+ }
- void* getFrame(int index) const {
+ void *getFrame(int index) const {
int adjusted_index = index + skip_;
if (adjusted_index < 0 || adjusted_index >= numCallers_) {
return NULL;
@@ -117,8 +121,8 @@
return callers_[adjusted_index];
}
-private:
- void* callers_[MAX_STACK_DEPTH];
+ private:
+ void *callers_[MAX_STACK_DEPTH];
int numCallers_;
int skip_;
};
@@ -134,7 +138,9 @@
}
}
-Backtrace::Backtrace(Backtrace const& bt) : numCallers_(bt.numCallers_), skip_(bt.skip_) {
+Backtrace::Backtrace(Backtrace const &bt)
+ : numCallers_(bt.numCallers_)
+ , skip_(bt.skip_) {
if (numCallers_ >= 0) {
memcpy(callers_, bt.callers_, numCallers_ * sizeof(void*));
}
@@ -144,20 +150,32 @@
* A backtrace, plus one or two type names
*/
class Key {
-public:
+ public:
class Hash {
- public:
- size_t operator()(Key const& k) const { return k.hash(); }
+ public:
+ size_t operator()(Key const& k) const {
+ return k.hash();
+ }
};
Key(const Backtrace* bt, const std::type_info& type_info)
- : backtrace_(bt), typeName1_(type_info.name()), typeName2_(NULL) {}
+ : backtrace_(bt)
+ , typeName1_(type_info.name())
+ , typeName2_(NULL) {
+ }
- Key(const Backtrace* bt, const std::type_info& type_info1, const std::type_info& type_info2)
- : backtrace_(bt), typeName1_(type_info1.name()), typeName2_(type_info2.name()) {}
+ Key(const Backtrace* bt, const std::type_info& type_info1,
+ const std::type_info& type_info2)
+ : backtrace_(bt)
+ , typeName1_(type_info1.name())
+ , typeName2_(type_info2.name()) {
+ }
Key(const Key& k)
- : backtrace_(k.backtrace_), typeName1_(k.typeName1_), typeName2_(k.typeName2_) {}
+ : backtrace_(k.backtrace_)
+ , typeName1_(k.typeName1_)
+ , typeName2_(k.typeName2_) {
+ }
void operator=(const Key& k) {
backtrace_ = k.backtrace_;
@@ -165,11 +183,17 @@
typeName2_ = k.typeName2_;
}
- const Backtrace* getBacktrace() const { return backtrace_; }
+ const Backtrace* getBacktrace() const {
+ return backtrace_;
+ }
- const char* getTypeName() const { return typeName1_; }
+ const char* getTypeName() const {
+ return typeName1_;
+ }
- const char* getTypeName2() const { return typeName2_; }
+ const char* getTypeName2() const {
+ return typeName2_;
+ }
void makePersistent() {
// Copy the Backtrace object
@@ -209,17 +233,20 @@
return k.typeName2_ - typeName2_;
}
- bool operator==(const Key& k) const { return cmp(k) == 0; }
+ bool operator==(const Key& k) const {
+ return cmp(k) == 0;
+ }
size_t hash() const {
// NOTE: As above, we just use the name pointer value.
// Works with GNU libstdc++, but not guaranteed to be correct on all
// implementations.
- return backtrace_->hash() ^ reinterpret_cast<size_t>(typeName1_)
- ^ reinterpret_cast<size_t>(typeName2_);
+ return backtrace_->hash() ^
+ reinterpret_cast<size_t>(typeName1_) ^
+ reinterpret_cast<size_t>(typeName2_);
}
-private:
+ private:
const Backtrace* backtrace_;
const char* typeName1_;
const char* typeName2_;
@@ -230,8 +257,9 @@
* has a higher count.
*/
class CountGreater {
-public:
- bool operator()(std::pair<Key, size_t> bt1, std::pair<Key, size_t> bt2) const {
+ public:
+ bool operator()(std::pair<Key, size_t> bt1,
+ std::pair<Key, size_t> bt2) const {
return bt1.second > bt2.second;
}
};
@@ -250,7 +278,8 @@
BacktraceMap generic_calls;
Mutex generic_calls_mutex;
-void _record_backtrace(BacktraceMap* map, const Mutex& mutex, Key* k) {
+
+void _record_backtrace(BacktraceMap* map, const Mutex& mutex, Key *k) {
Guard guard(mutex);
BacktraceMap::iterator it = map->find(*k);
@@ -295,7 +324,7 @@
* Print the recorded profiling information to the specified file.
*/
void profile_print_info(FILE* f) {
- typedef std::vector<std::pair<Key, size_t> > BacktraceVector;
+ typedef std::vector< std::pair<Key, size_t> > BacktraceVector;
CountGreater is_greater;
@@ -313,14 +342,13 @@
BacktraceVector gp_sorted(generic_calls.begin(), generic_calls.end());
std::sort(gp_sorted.begin(), gp_sorted.end(), is_greater);
- for (BacktraceVector::const_iterator it = gp_sorted.begin(); it != gp_sorted.end(); ++it) {
- Key const& key = it->first;
+ for (BacktraceVector::const_iterator it = gp_sorted.begin();
+ it != gp_sorted.end();
+ ++it) {
+ Key const &key = it->first;
size_t const count = it->second;
- fprintf(f,
- "T_GENERIC_PROTOCOL: %zu calls to %s with a %s:\n",
- count,
- key.getTypeName(),
- key.getTypeName2());
+ fprintf(f, "T_GENERIC_PROTOCOL: %zu calls to %s with a %s:\n",
+ count, key.getTypeName(), key.getTypeName2());
key.getBacktrace()->print(f, 2);
fprintf(f, "\n");
}
@@ -329,8 +357,10 @@
BacktraceVector vc_sorted(virtual_calls.begin(), virtual_calls.end());
std::sort(vc_sorted.begin(), vc_sorted.end(), is_greater);
- for (BacktraceVector::const_iterator it = vc_sorted.begin(); it != vc_sorted.end(); ++it) {
- Key const& key = it->first;
+ for (BacktraceVector::const_iterator it = vc_sorted.begin();
+ it != vc_sorted.end();
+ ++it) {
+ Key const &key = it->first;
size_t const count = it->second;
fprintf(f, "T_VIRTUAL_CALL: %zu calls on %s:\n", count, key.getTypeName());
key.getBacktrace()->print(f, 2);
@@ -350,7 +380,7 @@
*/
static void profile_write_pprof_file(FILE* f, BacktraceMap const& map) {
// Write the header
- uintptr_t header[5] = {0, 3, 0, 0, 0};
+ uintptr_t header[5] = { 0, 3, 0, 0, 0 };
fwrite(&header, sizeof(header), 1, f);
// Write the profile records
@@ -369,12 +399,12 @@
}
// Write the trailer
- uintptr_t trailer[3] = {0, 1, 0};
+ uintptr_t trailer[3] = { 0, 1, 0 };
fwrite(&trailer, sizeof(trailer), 1, f);
// Write /proc/self/maps
// TODO(simpkins): This only works on linux
- FILE* proc_maps = fopen("/proc/self/maps", "r");
+ FILE *proc_maps = fopen("/proc/self/maps", "r");
if (proc_maps) {
uint8_t buf[4096];
while (true) {
@@ -404,7 +434,7 @@
* profile_virtual_call() will be written to this file.
*/
void profile_write_pprof(FILE* gen_calls_f, FILE* virtual_calls_f) {
- typedef std::vector<std::pair<Key, size_t> > BacktraceVector;
+ typedef std::vector< std::pair<Key, size_t> > BacktraceVector;
CountGreater is_greater;
@@ -419,7 +449,7 @@
// write the info from virtual_calls
profile_write_pprof_file(virtual_calls_f, virtual_calls);
}
-}
-} // apache::thrift
+
+}} // apache::thrift
#endif // T_GLOBAL_PROFILE_VIRTUAL > 0
diff --git a/lib/cpp/src/thrift/async/TAsyncBufferProcessor.h b/lib/cpp/src/thrift/async/TAsyncBufferProcessor.h
index 3c957a6..ad7c639 100644
--- a/lib/cpp/src/thrift/async/TAsyncBufferProcessor.h
+++ b/lib/cpp/src/thrift/async/TAsyncBufferProcessor.h
@@ -25,24 +25,22 @@
#include <thrift/transport/TBufferTransports.h>
-namespace apache {
-namespace thrift {
-namespace async {
+namespace apache { namespace thrift { namespace async {
class TAsyncBufferProcessor {
-public:
+ public:
// Process data in "in", putting the result in "out".
// Call _return(true) when done, or _return(false) to
// forcefully close the connection (if applicable).
// "in" and "out" should be TMemoryBuffer or similar,
// not a wrapper around a socket.
- virtual void process(apache::thrift::stdcxx::function<void(bool healthy)> _return,
- boost::shared_ptr<apache::thrift::transport::TBufferBase> ibuf,
- boost::shared_ptr<apache::thrift::transport::TBufferBase> obuf) = 0;
+ virtual void process(
+ apache::thrift::stdcxx::function<void(bool healthy)> _return,
+ boost::shared_ptr<apache::thrift::transport::TBufferBase> ibuf,
+ boost::shared_ptr<apache::thrift::transport::TBufferBase> obuf) = 0;
virtual ~TAsyncBufferProcessor() {}
};
-}
-}
-} // apache::thrift::async
+
+}}} // apache::thrift::async
#endif // #ifndef _THRIFT_TASYNC_BUFFER_PROCESSOR_H_
diff --git a/lib/cpp/src/thrift/async/TAsyncChannel.cpp b/lib/cpp/src/thrift/async/TAsyncChannel.cpp
index 4716af2..64dfe5f 100644
--- a/lib/cpp/src/thrift/async/TAsyncChannel.cpp
+++ b/lib/cpp/src/thrift/async/TAsyncChannel.cpp
@@ -20,18 +20,15 @@
#include <thrift/async/TAsyncChannel.h>
#include <thrift/cxxfunctional.h>
-namespace apache {
-namespace thrift {
-namespace async {
+namespace apache { namespace thrift { namespace async {
void TAsyncChannel::sendAndRecvMessage(const VoidCallback& cob,
TMemoryBuffer* sendBuf,
TMemoryBuffer* recvBuf) {
- apache::thrift::stdcxx::function<void()> send_done
- = apache::thrift::stdcxx::bind(&TAsyncChannel::recvMessage, this, cob, recvBuf);
+ apache::thrift::stdcxx::function<void()> send_done =
+ apache::thrift::stdcxx::bind(&TAsyncChannel::recvMessage, this, cob, recvBuf);
sendMessage(send_done, sendBuf);
}
-}
-}
-} // apache::thrift::async
+
+}}} // apache::thrift::async
diff --git a/lib/cpp/src/thrift/async/TAsyncChannel.h b/lib/cpp/src/thrift/async/TAsyncChannel.h
index eb3ce2a..0f202fd 100644
--- a/lib/cpp/src/thrift/async/TAsyncChannel.h
+++ b/lib/cpp/src/thrift/async/TAsyncChannel.h
@@ -23,21 +23,15 @@
#include <thrift/cxxfunctional.h>
#include <thrift/Thrift.h>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
class TMemoryBuffer;
-}
-}
-}
+}}}
-namespace apache {
-namespace thrift {
-namespace async {
+namespace apache { namespace thrift { namespace async {
using apache::thrift::transport::TMemoryBuffer;
class TAsyncChannel {
-public:
+ public:
typedef apache::thrift::stdcxx::function<void()> VoidCallback;
virtual ~TAsyncChannel() {}
@@ -51,23 +45,22 @@
* Send a message over the channel.
*/
virtual void sendMessage(const VoidCallback& cob,
- apache::thrift::transport::TMemoryBuffer* message) = 0;
+ apache::thrift::transport::TMemoryBuffer* message) = 0;
/**
* Receive a message from the channel.
*/
virtual void recvMessage(const VoidCallback& cob,
- apache::thrift::transport::TMemoryBuffer* message) = 0;
+ apache::thrift::transport::TMemoryBuffer* message) = 0;
/**
* Send a message over the channel and receive a response.
*/
virtual void sendAndRecvMessage(const VoidCallback& cob,
- apache::thrift::transport::TMemoryBuffer* sendBuf,
- apache::thrift::transport::TMemoryBuffer* recvBuf);
+ apache::thrift::transport::TMemoryBuffer* sendBuf,
+ apache::thrift::transport::TMemoryBuffer* recvBuf);
};
-}
-}
-} // apache::thrift::async
+
+}}} // apache::thrift::async
#endif // #ifndef _THRIFT_ASYNC_TASYNCCHANNEL_H_
diff --git a/lib/cpp/src/thrift/async/TAsyncDispatchProcessor.h b/lib/cpp/src/thrift/async/TAsyncDispatchProcessor.h
index e79c57d..15b5bce 100644
--- a/lib/cpp/src/thrift/async/TAsyncDispatchProcessor.h
+++ b/lib/cpp/src/thrift/async/TAsyncDispatchProcessor.h
@@ -21,9 +21,7 @@
#include <thrift/async/TAsyncProcessor.h>
-namespace apache {
-namespace thrift {
-namespace async {
+namespace apache { namespace thrift { namespace async {
/**
* TAsyncDispatchProcessor is a helper class to parse the message header then
@@ -33,7 +31,7 @@
*/
template <class Protocol_>
class TAsyncDispatchProcessorT : public TAsyncProcessor {
-public:
+ public:
virtual void process(apache::thrift::stdcxx::function<void(bool success)> _return,
boost::shared_ptr<protocol::TProtocol> in,
boost::shared_ptr<protocol::TProtocol> out) {
@@ -62,7 +60,8 @@
// (The old generated processor code used to try to skip a T_STRUCT and
// continue. However, that seems unsafe.)
if (mtype != protocol::T_CALL && mtype != protocol::T_ONEWAY) {
- GlobalOutput.printf("received invalid message type %d from client", mtype);
+ GlobalOutput.printf("received invalid message type %d from client",
+ mtype);
_return(false);
return;
}
@@ -71,15 +70,15 @@
}
void processFast(apache::thrift::stdcxx::function<void(bool success)> _return,
- Protocol_* in,
- Protocol_* out) {
+ Protocol_* in, Protocol_* out) {
std::string fname;
protocol::TMessageType mtype;
int32_t seqid;
in->readMessageBegin(fname, mtype, seqid);
if (mtype != protocol::T_CALL && mtype != protocol::T_ONEWAY) {
- GlobalOutput.printf("received invalid message type %d from client", mtype);
+ GlobalOutput.printf("received invalid message type %d from client",
+ mtype);
_return(false);
return;
}
@@ -90,12 +89,10 @@
virtual void dispatchCall(apache::thrift::stdcxx::function<void(bool ok)> _return,
apache::thrift::protocol::TProtocol* in,
apache::thrift::protocol::TProtocol* out,
- const std::string& fname,
- int32_t seqid) = 0;
+ const std::string& fname, int32_t seqid) = 0;
virtual void dispatchCallTemplated(apache::thrift::stdcxx::function<void(bool ok)> _return,
- Protocol_* in,
- Protocol_* out,
+ Protocol_* in, Protocol_* out,
const std::string& fname,
int32_t seqid) = 0;
};
@@ -105,7 +102,7 @@
* that doesn't bother trying to perform a dynamic_cast.
*/
class TAsyncDispatchProcessor : public TAsyncProcessor {
-public:
+ public:
virtual void process(apache::thrift::stdcxx::function<void(bool success)> _return,
boost::shared_ptr<protocol::TProtocol> in,
boost::shared_ptr<protocol::TProtocol> out) {
@@ -123,7 +120,8 @@
// (The old generated processor code used to try to skip a T_STRUCT and
// continue. However, that seems unsafe.)
if (mtype != protocol::T_CALL && mtype != protocol::T_ONEWAY) {
- GlobalOutput.printf("received invalid message type %d from client", mtype);
+ GlobalOutput.printf("received invalid message type %d from client",
+ mtype);
_return(false);
return;
}
@@ -134,18 +132,18 @@
virtual void dispatchCall(apache::thrift::stdcxx::function<void(bool ok)> _return,
apache::thrift::protocol::TProtocol* in,
apache::thrift::protocol::TProtocol* out,
- const std::string& fname,
- int32_t seqid) = 0;
+ const std::string& fname, int32_t seqid) = 0;
};
// Specialize TAsyncDispatchProcessorT for TProtocol and TDummyProtocol just to
// use the generic TDispatchProcessor.
template <>
-class TAsyncDispatchProcessorT<protocol::TDummyProtocol> : public TAsyncDispatchProcessor {};
+class TAsyncDispatchProcessorT<protocol::TDummyProtocol> :
+ public TAsyncDispatchProcessor {};
template <>
-class TAsyncDispatchProcessorT<protocol::TProtocol> : public TAsyncDispatchProcessor {};
-}
-}
-} // apache::thrift::async
+class TAsyncDispatchProcessorT<protocol::TProtocol> :
+ public TAsyncDispatchProcessor {};
+
+}}} // apache::thrift::async
#endif // _THRIFT_ASYNC_TASYNCDISPATCHPROCESSOR_H_
diff --git a/lib/cpp/src/thrift/async/TAsyncProcessor.h b/lib/cpp/src/thrift/async/TAsyncProcessor.h
index 033f7d9..a03d1dc 100644
--- a/lib/cpp/src/thrift/async/TAsyncProcessor.h
+++ b/lib/cpp/src/thrift/async/TAsyncProcessor.h
@@ -25,9 +25,7 @@
#include <thrift/protocol/TProtocol.h>
#include <thrift/TProcessor.h>
-namespace apache {
-namespace thrift {
-namespace async {
+namespace apache { namespace thrift { namespace async {
/**
* Async version of a TProcessor. It is not expected to complete by the time
@@ -37,7 +35,7 @@
class TEventServer; // forward declaration
class TAsyncProcessor {
-public:
+ public:
virtual ~TAsyncProcessor() {}
virtual void process(apache::thrift::stdcxx::function<void(bool success)> _return,
@@ -49,27 +47,31 @@
return process(_return, io, io);
}
- boost::shared_ptr<TProcessorEventHandler> getEventHandler() { return eventHandler_; }
+ boost::shared_ptr<TProcessorEventHandler> getEventHandler() {
+ return eventHandler_;
+ }
void setEventHandler(boost::shared_ptr<TProcessorEventHandler> eventHandler) {
eventHandler_ = eventHandler;
}
- const TEventServer* getAsyncServer() { return asyncServer_; }
-
-protected:
+ const TEventServer* getAsyncServer() {
+ return asyncServer_;
+ }
+ protected:
TAsyncProcessor() {}
boost::shared_ptr<TProcessorEventHandler> eventHandler_;
const TEventServer* asyncServer_;
-
-private:
+ private:
friend class TEventServer;
- void setAsyncServer(const TEventServer* server) { asyncServer_ = server; }
+ void setAsyncServer(const TEventServer* server) {
+ asyncServer_ = server;
+ }
};
class TAsyncProcessorFactory {
-public:
+ public:
virtual ~TAsyncProcessorFactory() {}
/**
@@ -79,17 +81,17 @@
* accepted on. This generally means that this call does not need to be
* thread safe, as it will always be invoked from a single thread.
*/
- virtual boost::shared_ptr<TAsyncProcessor> getProcessor(const TConnectionInfo& connInfo) = 0;
+ virtual boost::shared_ptr<TAsyncProcessor> getProcessor(
+ const TConnectionInfo& connInfo) = 0;
};
-}
-}
-} // apache::thrift::async
+
+
+
+}}} // apache::thrift::async
// XXX I'm lazy for now
-namespace apache {
-namespace thrift {
+namespace apache { namespace thrift {
using apache::thrift::async::TAsyncProcessor;
-}
-}
+}}
#endif // #ifndef _THRIFT_TASYNCPROCESSOR_H_
diff --git a/lib/cpp/src/thrift/async/TAsyncProtocolProcessor.cpp b/lib/cpp/src/thrift/async/TAsyncProtocolProcessor.cpp
index 5a4f347..2096289 100644
--- a/lib/cpp/src/thrift/async/TAsyncProtocolProcessor.cpp
+++ b/lib/cpp/src/thrift/async/TAsyncProtocolProcessor.cpp
@@ -22,32 +22,30 @@
using apache::thrift::transport::TBufferBase;
using apache::thrift::protocol::TProtocol;
-namespace apache {
-namespace thrift {
-namespace async {
+namespace apache { namespace thrift { namespace async {
-void TAsyncProtocolProcessor::process(apache::thrift::stdcxx::function<void(bool healthy)> _return,
- boost::shared_ptr<TBufferBase> ibuf,
- boost::shared_ptr<TBufferBase> obuf) {
+void TAsyncProtocolProcessor::process(
+ apache::thrift::stdcxx::function<void(bool healthy)> _return,
+ boost::shared_ptr<TBufferBase> ibuf,
+ boost::shared_ptr<TBufferBase> obuf) {
boost::shared_ptr<TProtocol> iprot(pfact_->getProtocol(ibuf));
boost::shared_ptr<TProtocol> oprot(pfact_->getProtocol(obuf));
- return underlying_
- ->process(apache::thrift::stdcxx::bind(&TAsyncProtocolProcessor::finish,
- _return,
- oprot,
- apache::thrift::stdcxx::placeholders::_1),
- iprot,
- oprot);
+ return underlying_->process(
+ apache::thrift::stdcxx::bind(
+ &TAsyncProtocolProcessor::finish,
+ _return,
+ oprot,
+ apache::thrift::stdcxx::placeholders::_1),
+ iprot, oprot);
}
/* static */ void TAsyncProtocolProcessor::finish(
apache::thrift::stdcxx::function<void(bool healthy)> _return,
boost::shared_ptr<TProtocol> oprot,
bool healthy) {
- (void)oprot;
+ (void) oprot;
// This is a stub function to hold a reference to oprot.
return _return(healthy);
}
-}
-}
-} // apache::thrift::async
+
+}}} // apache::thrift::async
diff --git a/lib/cpp/src/thrift/async/TAsyncProtocolProcessor.h b/lib/cpp/src/thrift/async/TAsyncProtocolProcessor.h
index 3f2b394..840b4dd 100644
--- a/lib/cpp/src/thrift/async/TAsyncProtocolProcessor.h
+++ b/lib/cpp/src/thrift/async/TAsyncProtocolProcessor.h
@@ -24,32 +24,34 @@
#include <thrift/async/TAsyncBufferProcessor.h>
#include <thrift/protocol/TProtocol.h>
-namespace apache {
-namespace thrift {
-namespace async {
+namespace apache { namespace thrift { namespace async {
class TAsyncProtocolProcessor : public TAsyncBufferProcessor {
-public:
- TAsyncProtocolProcessor(boost::shared_ptr<TAsyncProcessor> underlying,
- boost::shared_ptr<apache::thrift::protocol::TProtocolFactory> pfact)
- : underlying_(underlying), pfact_(pfact) {}
+ public:
+ TAsyncProtocolProcessor(
+ boost::shared_ptr<TAsyncProcessor> underlying,
+ boost::shared_ptr<apache::thrift::protocol::TProtocolFactory> pfact)
+ : underlying_(underlying)
+ , pfact_(pfact)
+ {}
- virtual void process(apache::thrift::stdcxx::function<void(bool healthy)> _return,
- boost::shared_ptr<apache::thrift::transport::TBufferBase> ibuf,
- boost::shared_ptr<apache::thrift::transport::TBufferBase> obuf);
+ virtual void process(
+ apache::thrift::stdcxx::function<void(bool healthy)> _return,
+ boost::shared_ptr<apache::thrift::transport::TBufferBase> ibuf,
+ boost::shared_ptr<apache::thrift::transport::TBufferBase> obuf);
virtual ~TAsyncProtocolProcessor() {}
-private:
- static void finish(apache::thrift::stdcxx::function<void(bool healthy)> _return,
- boost::shared_ptr<apache::thrift::protocol::TProtocol> oprot,
- bool healthy);
+ private:
+ static void finish(
+ apache::thrift::stdcxx::function<void(bool healthy)> _return,
+ boost::shared_ptr<apache::thrift::protocol::TProtocol> oprot,
+ bool healthy);
boost::shared_ptr<TAsyncProcessor> underlying_;
boost::shared_ptr<apache::thrift::protocol::TProtocolFactory> pfact_;
};
-}
-}
-} // apache::thrift::async
+
+}}} // apache::thrift::async
#endif // #ifndef _THRIFT_TNAME_ME_H_
diff --git a/lib/cpp/src/thrift/async/TEvhttpClientChannel.cpp b/lib/cpp/src/thrift/async/TEvhttpClientChannel.cpp
index bcb87cd..7ad7537 100644
--- a/lib/cpp/src/thrift/async/TEvhttpClientChannel.cpp
+++ b/lib/cpp/src/thrift/async/TEvhttpClientChannel.cpp
@@ -28,16 +28,20 @@
using namespace apache::thrift::protocol;
using apache::thrift::transport::TTransportException;
-namespace apache {
-namespace thrift {
-namespace async {
+namespace apache { namespace thrift { namespace async {
-TEvhttpClientChannel::TEvhttpClientChannel(const std::string& host,
- const std::string& path,
- const char* address,
- int port,
- struct event_base* eb)
- : host_(host), path_(path), recvBuf_(NULL), conn_(NULL) {
+
+TEvhttpClientChannel::TEvhttpClientChannel(
+ const std::string& host,
+ const std::string& path,
+ const char* address,
+ int port,
+ struct event_base* eb)
+ : host_(host)
+ , path_(path)
+ , recvBuf_(NULL)
+ , conn_(NULL)
+{
conn_ = evhttp_connection_new(address, port);
if (conn_ == NULL) {
throw TException("evhttp_connection_new failed");
@@ -45,15 +49,18 @@
evhttp_connection_set_base(conn_, eb);
}
+
TEvhttpClientChannel::~TEvhttpClientChannel() {
if (conn_ != NULL) {
evhttp_connection_free(conn_);
}
}
-void TEvhttpClientChannel::sendAndRecvMessage(const VoidCallback& cob,
- apache::thrift::transport::TMemoryBuffer* sendBuf,
- apache::thrift::transport::TMemoryBuffer* recvBuf) {
+
+void TEvhttpClientChannel::sendAndRecvMessage(
+ const VoidCallback& cob,
+ apache::thrift::transport::TMemoryBuffer* sendBuf,
+ apache::thrift::transport::TMemoryBuffer* recvBuf) {
cob_ = cob;
recvBuf_ = recvBuf;
@@ -88,64 +95,68 @@
}
}
-void TEvhttpClientChannel::sendMessage(const VoidCallback& cob,
- apache::thrift::transport::TMemoryBuffer* message) {
- (void)cob;
- (void)message;
+
+void TEvhttpClientChannel::sendMessage(
+ const VoidCallback& cob, apache::thrift::transport::TMemoryBuffer* message) {
+ (void) cob;
+ (void) message;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
- "Unexpected call to TEvhttpClientChannel::sendMessage");
+ "Unexpected call to TEvhttpClientChannel::sendMessage");
}
-void TEvhttpClientChannel::recvMessage(const VoidCallback& cob,
- apache::thrift::transport::TMemoryBuffer* message) {
- (void)cob;
- (void)message;
+
+void TEvhttpClientChannel::recvMessage(
+ const VoidCallback& cob, apache::thrift::transport::TMemoryBuffer* message) {
+ (void) cob;
+ (void) message;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
- "Unexpected call to TEvhttpClientChannel::recvMessage");
+ "Unexpected call to TEvhttpClientChannel::recvMessage");
}
+
void TEvhttpClientChannel::finish(struct evhttp_request* req) {
if (req == NULL) {
- try {
- cob_();
- } catch (const TTransportException& e) {
- if (e.getType() == TTransportException::END_OF_FILE)
- throw TException("connect failed");
- else
- throw;
- }
- return;
- } else if (req->response_code != 200) {
- try {
- cob_();
- } catch (const TTransportException& e) {
- std::stringstream ss;
- ss << "server returned code " << req->response_code;
- if (req->response_code_line)
- ss << ": " << req->response_code_line;
- if (e.getType() == TTransportException::END_OF_FILE)
- throw TException(ss.str());
- else
- throw;
- }
- return;
+ try {
+ cob_();
+ } catch(const TTransportException& e) {
+ if(e.getType() == TTransportException::END_OF_FILE)
+ throw TException("connect failed");
+ else
+ throw;
}
- recvBuf_->resetBuffer(EVBUFFER_DATA(req->input_buffer),
- static_cast<uint32_t>(EVBUFFER_LENGTH(req->input_buffer)));
+ return;
+ } else if (req->response_code != 200) {
+ try {
+ cob_();
+ } catch(const TTransportException& e) {
+ std::stringstream ss;
+ ss << "server returned code " << req->response_code;
+ if(req->response_code_line)
+ ss << ": " << req->response_code_line;
+ if(e.getType() == TTransportException::END_OF_FILE)
+ throw TException(ss.str());
+ else
+ throw;
+ }
+ return;
+ }
+ recvBuf_->resetBuffer(
+ EVBUFFER_DATA(req->input_buffer),
+ static_cast<uint32_t>(EVBUFFER_LENGTH(req->input_buffer)));
cob_();
return;
}
+
/* static */ void TEvhttpClientChannel::response(struct evhttp_request* req, void* arg) {
TEvhttpClientChannel* self = (TEvhttpClientChannel*)arg;
try {
self->finish(req);
- } catch (std::exception& e) {
+ } catch(std::exception& e) {
// don't propagate a C++ exception in C code (e.g. libevent)
- std::cerr << "TEvhttpClientChannel::response exception thrown (ignored): " << e.what()
- << std::endl;
+ std::cerr << "TEvhttpClientChannel::response exception thrown (ignored): " << e.what() << std::endl;
}
}
-}
-}
-} // apache::thrift::async
+
+
+}}} // apache::thrift::async
diff --git a/lib/cpp/src/thrift/async/TEvhttpClientChannel.h b/lib/cpp/src/thrift/async/TEvhttpClientChannel.h
index 72ed40f..a7229e9 100644
--- a/lib/cpp/src/thrift/async/TEvhttpClientChannel.h
+++ b/lib/cpp/src/thrift/async/TEvhttpClientChannel.h
@@ -28,46 +28,39 @@
struct evhttp_connection;
struct evhttp_request;
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
class TMemoryBuffer;
-}
-}
-}
+}}}
-namespace apache {
-namespace thrift {
-namespace async {
+namespace apache { namespace thrift { namespace async {
class TEvhttpClientChannel : public TAsyncChannel {
-public:
+ public:
using TAsyncChannel::VoidCallback;
- TEvhttpClientChannel(const std::string& host,
- const std::string& path,
- const char* address,
- int port,
- struct event_base* eb);
+ TEvhttpClientChannel(
+ const std::string& host,
+ const std::string& path,
+ const char* address,
+ int port,
+ struct event_base* eb);
~TEvhttpClientChannel();
virtual void sendAndRecvMessage(const VoidCallback& cob,
apache::thrift::transport::TMemoryBuffer* sendBuf,
apache::thrift::transport::TMemoryBuffer* recvBuf);
- virtual void sendMessage(const VoidCallback& cob,
- apache::thrift::transport::TMemoryBuffer* message);
- virtual void recvMessage(const VoidCallback& cob,
- apache::thrift::transport::TMemoryBuffer* message);
+ virtual void sendMessage(const VoidCallback& cob, apache::thrift::transport::TMemoryBuffer* message);
+ virtual void recvMessage(const VoidCallback& cob, apache::thrift::transport::TMemoryBuffer* message);
void finish(struct evhttp_request* req);
- // XXX
+ //XXX
virtual bool good() const { return true; }
virtual bool error() const { return false; }
virtual bool timedOut() const { return false; }
-private:
+ private:
static void response(struct evhttp_request* req, void* arg);
std::string host_;
@@ -75,9 +68,9 @@
VoidCallback cob_;
apache::thrift::transport::TMemoryBuffer* recvBuf_;
struct evhttp_connection* conn_;
+
};
-}
-}
-} // apache::thrift::async
+
+}}} // apache::thrift::async
#endif // #ifndef _THRIFT_TEVHTTP_CLIENT_CHANNEL_H_
diff --git a/lib/cpp/src/thrift/async/TEvhttpServer.cpp b/lib/cpp/src/thrift/async/TEvhttpServer.cpp
index 93fb479..fa8d782 100644
--- a/lib/cpp/src/thrift/async/TEvhttpServer.cpp
+++ b/lib/cpp/src/thrift/async/TEvhttpServer.cpp
@@ -30,9 +30,8 @@
using apache::thrift::transport::TMemoryBuffer;
-namespace apache {
-namespace thrift {
-namespace async {
+namespace apache { namespace thrift { namespace async {
+
struct TEvhttpServer::RequestContext {
struct evhttp_request* req;
@@ -42,12 +41,19 @@
RequestContext(struct evhttp_request* req);
};
+
TEvhttpServer::TEvhttpServer(boost::shared_ptr<TAsyncBufferProcessor> processor)
- : processor_(processor), eb_(NULL), eh_(NULL) {
-}
+ : processor_(processor)
+ , eb_(NULL)
+ , eh_(NULL)
+{}
+
TEvhttpServer::TEvhttpServer(boost::shared_ptr<TAsyncBufferProcessor> processor, int port)
- : processor_(processor), eb_(NULL), eh_(NULL) {
+ : processor_(processor)
+ , eb_(NULL)
+ , eh_(NULL)
+{
// Create event_base and evhttp.
eb_ = event_base_new();
if (eb_ == NULL) {
@@ -64,7 +70,7 @@
if (ret < 0) {
evhttp_free(eh_);
event_base_free(eb_);
- throw TException("evhttp_bind_socket failed");
+ throw TException("evhttp_bind_socket failed");
}
// Register a handler. If you use the other constructor,
@@ -73,6 +79,7 @@
evhttp_set_cb(eh_, "/", request, (void*)this);
}
+
TEvhttpServer::~TEvhttpServer() {
if (eh_ != NULL) {
evhttp_free(eh_);
@@ -82,6 +89,7 @@
}
}
+
int TEvhttpServer::serve() {
if (eb_ == NULL) {
throw TException("Unexpected call to TEvhttpServer::serve");
@@ -89,33 +97,37 @@
return event_base_dispatch(eb_);
}
-TEvhttpServer::RequestContext::RequestContext(struct evhttp_request* req)
- : req(req),
- ibuf(new TMemoryBuffer(EVBUFFER_DATA(req->input_buffer),
- static_cast<uint32_t>(EVBUFFER_LENGTH(req->input_buffer)))),
- obuf(new TMemoryBuffer()) {
-}
+
+TEvhttpServer::RequestContext::RequestContext(struct evhttp_request* req) : req(req)
+ , ibuf(new TMemoryBuffer(EVBUFFER_DATA(req->input_buffer), static_cast<uint32_t>(EVBUFFER_LENGTH(req->input_buffer))))
+ , obuf(new TMemoryBuffer())
+{}
+
void TEvhttpServer::request(struct evhttp_request* req, void* self) {
try {
static_cast<TEvhttpServer*>(self)->process(req);
- } catch (std::exception& e) {
+ } catch(std::exception& e) {
evhttp_send_reply(req, HTTP_INTERNAL, e.what(), 0);
}
}
+
void TEvhttpServer::process(struct evhttp_request* req) {
RequestContext* ctx = new RequestContext(req);
- return processor_->process(apache::thrift::stdcxx::bind(&TEvhttpServer::complete,
- this,
- ctx,
- apache::thrift::stdcxx::placeholders::_1),
- ctx->ibuf,
- ctx->obuf);
+ return processor_->process(
+ apache::thrift::stdcxx::bind(
+ &TEvhttpServer::complete,
+ this,
+ ctx,
+ apache::thrift::stdcxx::placeholders::_1),
+ ctx->ibuf,
+ ctx->obuf);
}
+
void TEvhttpServer::complete(RequestContext* ctx, bool success) {
- (void)success;
+ (void) success;
std::auto_ptr<RequestContext> ptr(ctx);
int code = success ? 200 : 400;
@@ -130,7 +142,7 @@
struct evbuffer* buf = evbuffer_new();
if (buf == NULL) {
// TODO: Log an error.
- std::cerr << "evbuffer_new failed " << __FILE__ << ":" << __LINE__ << std::endl;
+ std::cerr << "evbuffer_new failed " << __FILE__ << ":" << __LINE__ << std::endl;
} else {
uint8_t* obuf;
uint32_t sz;
@@ -138,8 +150,7 @@
int ret = evbuffer_add(buf, obuf, sz);
if (ret != 0) {
// TODO: Log an error.
- std::cerr << "evhttp_add failed with " << ret << " " << __FILE__ << ":" << __LINE__
- << std::endl;
+ std::cerr << "evhttp_add failed with " << ret << " " << __FILE__ << ":" << __LINE__ << std::endl;
}
}
@@ -149,9 +160,10 @@
}
}
+
struct event_base* TEvhttpServer::getEventBase() {
return eb_;
}
-}
-}
-} // apache::thrift::async
+
+
+}}} // apache::thrift::async
diff --git a/lib/cpp/src/thrift/async/TEvhttpServer.h b/lib/cpp/src/thrift/async/TEvhttpServer.h
index 89bf337..edc6ffb 100644
--- a/lib/cpp/src/thrift/async/TEvhttpServer.h
+++ b/lib/cpp/src/thrift/async/TEvhttpServer.h
@@ -26,14 +26,12 @@
struct evhttp;
struct evhttp_request;
-namespace apache {
-namespace thrift {
-namespace async {
+namespace apache { namespace thrift { namespace async {
class TAsyncBufferProcessor;
class TEvhttpServer {
-public:
+ public:
/**
* Create a TEvhttpServer for use with an external evhttp instance.
* Must be manually installed with evhttp_set_cb, using
@@ -57,7 +55,7 @@
struct event_base* getEventBase();
-private:
+ private:
struct RequestContext;
void process(struct evhttp_request* req);
@@ -67,8 +65,7 @@
struct event_base* eb_;
struct evhttp* eh_;
};
-}
-}
-} // apache::thrift::async
+
+}}} // apache::thrift::async
#endif // #ifndef _THRIFT_TEVHTTP_SERVER_H_
diff --git a/lib/cpp/src/thrift/concurrency/BoostMonitor.cpp b/lib/cpp/src/thrift/concurrency/BoostMonitor.cpp
index 6c24d82..1027157 100644
--- a/lib/cpp/src/thrift/concurrency/BoostMonitor.cpp
+++ b/lib/cpp/src/thrift/concurrency/BoostMonitor.cpp
@@ -29,9 +29,7 @@
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
/**
* Monitor implementation using the boost thread library
@@ -40,12 +38,23 @@
*/
class Monitor::Impl : public boost::condition_variable_any {
-public:
- Impl() : ownedMutex_(new Mutex()), mutex_(NULL) { init(ownedMutex_.get()); }
+ public:
- Impl(Mutex* mutex) : mutex_(NULL) { init(mutex); }
+ Impl()
+ : ownedMutex_(new Mutex()),
+ mutex_(NULL) {
+ init(ownedMutex_.get());
+ }
- Impl(Monitor* monitor) : mutex_(NULL) { init(&(monitor->mutex())); }
+ Impl(Mutex* mutex)
+ : mutex_(NULL) {
+ init(mutex);
+ }
+
+ Impl(Monitor* monitor)
+ : mutex_(NULL) {
+ init(&(monitor->mutex()));
+ }
Mutex& mutex() { return *mutex_; }
void lock() { mutex().lock(); }
@@ -63,7 +72,8 @@
if (result == THRIFT_ETIMEDOUT) {
throw TimedOutException();
} else if (result != 0) {
- throw TException("Monitor::wait() failed");
+ throw TException(
+ "Monitor::wait() failed");
}
}
@@ -79,17 +89,14 @@
}
assert(mutex_);
- boost::timed_mutex* mutexImpl
- = reinterpret_cast<boost::timed_mutex*>(mutex_->getUnderlyingImpl());
+ boost::timed_mutex* mutexImpl =
+ reinterpret_cast<boost::timed_mutex*>(mutex_->getUnderlyingImpl());
assert(mutexImpl);
- boost::timed_mutex::scoped_lock lock(*mutexImpl, boost::adopt_lock);
- int res
- = timed_wait(lock, boost::get_system_time() + boost::posix_time::milliseconds(timeout_ms))
- ? 0
- : THRIFT_ETIMEDOUT;
- lock.release();
- return res;
+ boost::timed_mutex::scoped_lock lock(*mutexImpl, boost::adopt_lock);
+ int res = timed_wait(lock, boost::get_system_time()+boost::posix_time::milliseconds(timeout_ms)) ? 0 : THRIFT_ETIMEDOUT;
+ lock.release();
+ return res;
}
/**
@@ -98,7 +105,7 @@
*/
int waitForTime(const THRIFT_TIMESPEC* abstime) {
struct timeval temp;
- temp.tv_sec = static_cast<long>(abstime->tv_sec);
+ temp.tv_sec = static_cast<long>(abstime->tv_sec);
temp.tv_usec = static_cast<long>(abstime->tv_nsec) / 1000;
return waitForTime(&temp);
}
@@ -109,27 +116,27 @@
*/
int waitForTime(const struct timeval* abstime) {
assert(mutex_);
- boost::timed_mutex* mutexImpl = static_cast<boost::timed_mutex*>(mutex_->getUnderlyingImpl());
+ boost::timed_mutex* mutexImpl =
+ static_cast<boost::timed_mutex*>(mutex_->getUnderlyingImpl());
assert(mutexImpl);
struct timeval currenttime;
Util::toTimeval(currenttime, Util::currentTime());
- long tv_sec = static_cast<long>(abstime->tv_sec - currenttime.tv_sec);
- long tv_usec = static_cast<long>(abstime->tv_usec - currenttime.tv_usec);
- if (tv_sec < 0)
- tv_sec = 0;
- if (tv_usec < 0)
- tv_usec = 0;
+ long tv_sec = static_cast<long>(abstime->tv_sec - currenttime.tv_sec);
+ long tv_usec = static_cast<long>(abstime->tv_usec - currenttime.tv_usec);
+ if(tv_sec < 0)
+ tv_sec = 0;
+ if(tv_usec < 0)
+ tv_usec = 0;
- boost::timed_mutex::scoped_lock lock(*mutexImpl, boost::adopt_lock);
- int res = timed_wait(lock,
- boost::get_system_time() + boost::posix_time::seconds(tv_sec)
- + boost::posix_time::microseconds(tv_usec))
- ? 0
- : THRIFT_ETIMEDOUT;
- lock.release();
- return res;
+ boost::timed_mutex::scoped_lock lock(*mutexImpl, boost::adopt_lock);
+ int res = timed_wait(lock, boost::get_system_time() +
+ boost::posix_time::seconds(tv_sec) +
+ boost::posix_time::microseconds(tv_usec)
+ ) ? 0 : THRIFT_ETIMEDOUT;
+ lock.release();
+ return res;
}
/**
@@ -138,53 +145,48 @@
*/
int waitForever() {
assert(mutex_);
- boost::timed_mutex* mutexImpl
- = reinterpret_cast<boost::timed_mutex*>(mutex_->getUnderlyingImpl());
+ boost::timed_mutex* mutexImpl =
+ reinterpret_cast<boost::timed_mutex*>(mutex_->getUnderlyingImpl());
assert(mutexImpl);
- boost::timed_mutex::scoped_lock lock(*mutexImpl, boost::adopt_lock);
- ((boost::condition_variable_any*)this)->wait(lock);
- lock.release();
+ boost::timed_mutex::scoped_lock lock(*mutexImpl, boost::adopt_lock);
+ ((boost::condition_variable_any*)this)->wait(lock);
+ lock.release();
return 0;
}
- void notify() { notify_one(); }
- void notifyAll() { notify_all(); }
+ void notify() {
+ notify_one();
+ }
-private:
- void init(Mutex* mutex) { mutex_ = mutex; }
+ void notifyAll() {
+ notify_all();
+ }
+
+ private:
+
+ void init(Mutex* mutex) {
+ mutex_ = mutex;
+ }
boost::scoped_ptr<Mutex> ownedMutex_;
Mutex* mutex_;
};
-Monitor::Monitor() : impl_(new Monitor::Impl()) {
-}
-Monitor::Monitor(Mutex* mutex) : impl_(new Monitor::Impl(mutex)) {
-}
-Monitor::Monitor(Monitor* monitor) : impl_(new Monitor::Impl(monitor)) {
-}
+Monitor::Monitor() : impl_(new Monitor::Impl()) {}
+Monitor::Monitor(Mutex* mutex) : impl_(new Monitor::Impl(mutex)) {}
+Monitor::Monitor(Monitor* monitor) : impl_(new Monitor::Impl(monitor)) {}
-Monitor::~Monitor() {
- delete impl_;
-}
+Monitor::~Monitor() { delete impl_; }
-Mutex& Monitor::mutex() const {
- return const_cast<Monitor::Impl*>(impl_)->mutex();
-}
+Mutex& Monitor::mutex() const { return const_cast<Monitor::Impl*>(impl_)->mutex(); }
-void Monitor::lock() const {
- const_cast<Monitor::Impl*>(impl_)->lock();
-}
+void Monitor::lock() const { const_cast<Monitor::Impl*>(impl_)->lock(); }
-void Monitor::unlock() const {
- const_cast<Monitor::Impl*>(impl_)->unlock();
-}
+void Monitor::unlock() const { const_cast<Monitor::Impl*>(impl_)->unlock(); }
-void Monitor::wait(int64_t timeout) const {
- const_cast<Monitor::Impl*>(impl_)->wait(timeout);
-}
+void Monitor::wait(int64_t timeout) const { const_cast<Monitor::Impl*>(impl_)->wait(timeout); }
int Monitor::waitForTime(const THRIFT_TIMESPEC* abstime) const {
return const_cast<Monitor::Impl*>(impl_)->waitForTime(abstime);
@@ -202,13 +204,8 @@
return const_cast<Monitor::Impl*>(impl_)->waitForever();
}
-void Monitor::notify() const {
- const_cast<Monitor::Impl*>(impl_)->notify();
-}
+void Monitor::notify() const { const_cast<Monitor::Impl*>(impl_)->notify(); }
-void Monitor::notifyAll() const {
- const_cast<Monitor::Impl*>(impl_)->notifyAll();
-}
-}
-}
-} // apache::thrift::concurrency
+void Monitor::notifyAll() const { const_cast<Monitor::Impl*>(impl_)->notifyAll(); }
+
+}}} // apache::thrift::concurrency
diff --git a/lib/cpp/src/thrift/concurrency/BoostMutex.cpp b/lib/cpp/src/thrift/concurrency/BoostMutex.cpp
index f7cadab..59c3618 100644
--- a/lib/cpp/src/thrift/concurrency/BoostMutex.cpp
+++ b/lib/cpp/src/thrift/concurrency/BoostMutex.cpp
@@ -28,44 +28,31 @@
#include <boost/thread/mutex.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
/**
* Implementation of Mutex class using boost interprocess mutex
*
* @version $Id:$
*/
-class Mutex::impl : public boost::timed_mutex {};
+class Mutex::impl : public boost::timed_mutex {
+};
-Mutex::Mutex(Initializer init) : impl_(new Mutex::impl()) {
- THRIFT_UNUSED_VARIABLE(init);
-}
+Mutex::Mutex(Initializer init) : impl_(new Mutex::impl())
+{ THRIFT_UNUSED_VARIABLE(init); }
-void* Mutex::getUnderlyingImpl() const {
- return impl_.get();
-}
+void* Mutex::getUnderlyingImpl() const { return impl_.get(); }
-void Mutex::lock() const {
- impl_->lock();
-}
+void Mutex::lock() const { impl_->lock(); }
-bool Mutex::trylock() const {
- return impl_->try_lock();
-}
+bool Mutex::trylock() const { return impl_->try_lock(); }
-bool Mutex::timedlock(int64_t ms) const {
- return impl_->timed_lock(boost::get_system_time() + boost::posix_time::milliseconds(ms));
-}
+bool Mutex::timedlock(int64_t ms) const { return impl_->timed_lock(boost::get_system_time()+boost::posix_time::milliseconds(ms)); }
-void Mutex::unlock() const {
- impl_->unlock();
-}
+void Mutex::unlock() const { impl_->unlock(); }
void Mutex::DEFAULT_INITIALIZER(void* arg) {
THRIFT_UNUSED_VARIABLE(arg);
}
-}
-}
-} // apache::thrift::concurrency
+
+}}} // apache::thrift::concurrency
diff --git a/lib/cpp/src/thrift/concurrency/BoostThreadFactory.cpp b/lib/cpp/src/thrift/concurrency/BoostThreadFactory.cpp
index 5f6dade..c45a964 100644
--- a/lib/cpp/src/thrift/concurrency/BoostThreadFactory.cpp
+++ b/lib/cpp/src/thrift/concurrency/BoostThreadFactory.cpp
@@ -29,9 +29,7 @@
#include <boost/weak_ptr.hpp>
#include <boost/thread.hpp>
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
using boost::shared_ptr;
using boost::weak_ptr;
@@ -41,29 +39,38 @@
*
* @version $Id:$
*/
-class BoostThread : public Thread {
-public:
- enum STATE { uninitialized, starting, started, stopping, stopped };
+class BoostThread: public Thread {
+ public:
+
+ enum STATE {
+ uninitialized,
+ starting,
+ started,
+ stopping,
+ stopped
+ };
static void* threadMain(void* arg);
-private:
+ private:
std::auto_ptr<boost::thread> thread_;
STATE state_;
weak_ptr<BoostThread> self_;
bool detached_;
-public:
- BoostThread(bool detached, shared_ptr<Runnable> runnable)
- : state_(uninitialized), detached_(detached) {
- this->Thread::runnable(runnable);
- }
+ public:
+
+ BoostThread(bool detached, shared_ptr<Runnable> runnable) :
+ state_(uninitialized),
+ detached_(detached) {
+ this->Thread::runnable(runnable);
+ }
~BoostThread() {
- if (!detached_) {
+ if(!detached_) {
try {
join();
- } catch (...) {
+ } catch(...) {
// We're really hosed.
}
}
@@ -74,16 +81,15 @@
return;
}
- // Create reference
+ // Create reference
shared_ptr<BoostThread>* selfRef = new shared_ptr<BoostThread>();
*selfRef = self_.lock();
state_ = starting;
- thread_
- = std::auto_ptr<boost::thread>(new boost::thread(boost::bind(threadMain, (void*)selfRef)));
+ thread_ = std::auto_ptr<boost::thread>(new boost::thread(boost::bind(threadMain, (void*)selfRef)));
- if (detached_)
+ if(detached_)
thread_->detach();
}
@@ -93,7 +99,9 @@
}
}
- Thread::id_t getId() { return thread_.get() ? thread_->get_id() : boost::thread::id(); }
+ Thread::id_t getId() {
+ return thread_.get() ? thread_->get_id() : boost::thread::id();
+ }
shared_ptr<Runnable> runnable() const { return Thread::runnable(); }
@@ -131,11 +139,13 @@
*/
class BoostThreadFactory::Impl {
-private:
+ private:
bool detached_;
-public:
- Impl(bool detached) : detached_(detached) {}
+ public:
+
+ Impl(bool detached) :
+ detached_(detached) {}
/**
* Creates a new POSIX thread to run the runnable object
@@ -153,30 +163,22 @@
void setDetached(bool value) { detached_ = value; }
- Thread::id_t getCurrentThreadId() const { return boost::this_thread::get_id(); }
+ Thread::id_t getCurrentThreadId() const {
+ return boost::this_thread::get_id();
+ }
};
-BoostThreadFactory::BoostThreadFactory(bool detached)
- : impl_(new BoostThreadFactory::Impl(detached)) {
-}
+BoostThreadFactory::BoostThreadFactory(bool detached) :
+ impl_(new BoostThreadFactory::Impl(detached)) {}
-shared_ptr<Thread> BoostThreadFactory::newThread(shared_ptr<Runnable> runnable) const {
- return impl_->newThread(runnable);
-}
+shared_ptr<Thread> BoostThreadFactory::newThread(shared_ptr<Runnable> runnable) const { return impl_->newThread(runnable); }
-bool BoostThreadFactory::isDetached() const {
- return impl_->isDetached();
-}
+bool BoostThreadFactory::isDetached() const { return impl_->isDetached(); }
-void BoostThreadFactory::setDetached(bool value) {
- impl_->setDetached(value);
-}
+void BoostThreadFactory::setDetached(bool value) { impl_->setDetached(value); }
-Thread::id_t BoostThreadFactory::getCurrentThreadId() const {
- return impl_->getCurrentThreadId();
-}
-}
-}
-} // apache::thrift::concurrency
+Thread::id_t BoostThreadFactory::getCurrentThreadId() const { return impl_->getCurrentThreadId(); }
+
+}}} // apache::thrift::concurrency
#endif // USE_BOOST_THREAD
diff --git a/lib/cpp/src/thrift/concurrency/BoostThreadFactory.h b/lib/cpp/src/thrift/concurrency/BoostThreadFactory.h
index fc06e56..6a236d3 100644
--- a/lib/cpp/src/thrift/concurrency/BoostThreadFactory.h
+++ b/lib/cpp/src/thrift/concurrency/BoostThreadFactory.h
@@ -24,9 +24,7 @@
#include <boost/shared_ptr.hpp>
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
/**
* A thread factory to create posix threads
@@ -35,21 +33,21 @@
*/
class BoostThreadFactory : public ThreadFactory {
-public:
+ public:
+
/**
* Boost thread factory. All threads created by a factory are reference-counted
* via boost::shared_ptr and boost::weak_ptr. The factory guarantees that threads and
* the Runnable tasks they host will be properly cleaned up once the last strong reference
* to both is given up.
*
- * Threads are created with the specified boost policy, priority, stack-size. A detachable thread
- *is not
+ * Threads are created with the specified boost policy, priority, stack-size. A detachable thread is not
* joinable.
*
* By default threads are not joinable.
*/
- BoostThreadFactory(bool detached = true);
+ BoostThreadFactory(bool detached=true);
// From ThreadFactory;
boost::shared_ptr<Thread> newThread(boost::shared_ptr<Runnable> runnable) const;
@@ -71,8 +69,7 @@
class Impl;
boost::shared_ptr<Impl> impl_;
};
-}
-}
-} // apache::thrift::concurrency
+
+}}} // apache::thrift::concurrency
#endif // #ifndef _THRIFT_CONCURRENCY_BOOSTTHREADFACTORY_H_
diff --git a/lib/cpp/src/thrift/concurrency/Exception.h b/lib/cpp/src/thrift/concurrency/Exception.h
index 6438fda..c62f116 100644
--- a/lib/cpp/src/thrift/concurrency/Exception.h
+++ b/lib/cpp/src/thrift/concurrency/Exception.h
@@ -23,9 +23,7 @@
#include <exception>
#include <thrift/Thrift.h>
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
class NoSuchTaskException : public apache::thrift::TException {};
@@ -41,24 +39,26 @@
class TimedOutException : public apache::thrift::TException {
public:
- TimedOutException() : TException("TimedOutException"){};
- TimedOutException(const std::string& message) : TException(message) {}
+ TimedOutException():TException("TimedOutException"){};
+ TimedOutException(const std::string& message ) :
+ TException(message) {}
};
class TooManyPendingTasksException : public apache::thrift::TException {
public:
- TooManyPendingTasksException() : TException("TooManyPendingTasksException"){};
- TooManyPendingTasksException(const std::string& message) : TException(message) {}
+ TooManyPendingTasksException():TException("TooManyPendingTasksException"){};
+ TooManyPendingTasksException(const std::string& message ) :
+ TException(message) {}
};
class SystemResourceException : public apache::thrift::TException {
public:
- SystemResourceException() {}
+ SystemResourceException() {}
- SystemResourceException(const std::string& message) : TException(message) {}
+ SystemResourceException(const std::string& message) :
+ TException(message) {}
};
-}
-}
-} // apache::thrift::concurrency
+
+}}} // apache::thrift::concurrency
#endif // #ifndef _THRIFT_CONCURRENCY_EXCEPTION_H_
diff --git a/lib/cpp/src/thrift/concurrency/FunctionRunner.h b/lib/cpp/src/thrift/concurrency/FunctionRunner.h
index b776794..e3b2bf3 100644
--- a/lib/cpp/src/thrift/concurrency/FunctionRunner.h
+++ b/lib/cpp/src/thrift/concurrency/FunctionRunner.h
@@ -23,9 +23,7 @@
#include <thrift/cxxfunctional.h>
#include <thrift/concurrency/Thread.h>
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
/**
* Convenient implementation of Runnable that will execute arbitrary callbacks.
@@ -49,9 +47,9 @@
*/
class FunctionRunner : public Runnable {
-public:
+ public:
// This is the type of callback 'pthread_create()' expects.
- typedef void* (*PthreadFuncPtr)(void* arg);
+ typedef void* (*PthreadFuncPtr)(void *arg);
// This a fully-generic void(void) callback for custom bindings.
typedef apache::thrift::stdcxx::function<void()> VoidFunc;
@@ -65,28 +63,32 @@
return boost::shared_ptr<FunctionRunner>(new FunctionRunner(cob));
}
- static boost::shared_ptr<FunctionRunner> create(PthreadFuncPtr func, void* arg) {
+ static boost::shared_ptr<FunctionRunner> create(PthreadFuncPtr func,
+ void* arg) {
return boost::shared_ptr<FunctionRunner>(new FunctionRunner(func, arg));
}
private:
- static void pthread_func_wrapper(PthreadFuncPtr func, void* arg) {
- // discard return value
+ static void pthread_func_wrapper(PthreadFuncPtr func, void *arg)
+ {
+ //discard return value
func(arg);
}
-
public:
/**
* Given a 'pthread_create' style callback, this FunctionRunner will
* execute the given callback. Note that the 'void*' return value is ignored.
*/
FunctionRunner(PthreadFuncPtr func, void* arg)
- : func_(apache::thrift::stdcxx::bind(pthread_func_wrapper, func, arg)) {}
+ : func_(apache::thrift::stdcxx::bind(pthread_func_wrapper, func, arg))
+ { }
/**
* Given a generic callback, this FunctionRunner will execute it.
*/
- FunctionRunner(const VoidFunc& cob) : func_(cob) {}
+ FunctionRunner(const VoidFunc& cob)
+ : func_(cob)
+ { }
/**
* Given a bool foo(...) type callback, FunctionRunner will execute
@@ -94,25 +96,26 @@
* until it returns false. Note that the actual interval between calls will
* be intervalMs plus execution time of the callback.
*/
- FunctionRunner(const BoolFunc& cob, int intervalMs) : repFunc_(cob), intervalMs_(intervalMs) {}
+ FunctionRunner(const BoolFunc& cob, int intervalMs)
+ : repFunc_(cob), intervalMs_(intervalMs)
+ { }
void run() {
if (repFunc_) {
- while (repFunc_()) {
- THRIFT_SLEEP_USEC(intervalMs_ * 1000);
+ while(repFunc_()) {
+ THRIFT_SLEEP_USEC(intervalMs_*1000);
}
} else {
func_();
}
}
-private:
+ private:
VoidFunc func_;
BoolFunc repFunc_;
int intervalMs_;
};
-}
-}
-} // apache::thrift::concurrency
+
+}}} // apache::thrift::concurrency
#endif // #ifndef _THRIFT_CONCURRENCY_FUNCTION_RUNNER_H
diff --git a/lib/cpp/src/thrift/concurrency/Monitor.cpp b/lib/cpp/src/thrift/concurrency/Monitor.cpp
index 5e713c0..d94b2a4 100644
--- a/lib/cpp/src/thrift/concurrency/Monitor.cpp
+++ b/lib/cpp/src/thrift/concurrency/Monitor.cpp
@@ -30,9 +30,7 @@
#include <pthread.h>
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
using boost::scoped_ptr;
@@ -43,14 +41,26 @@
*/
class Monitor::Impl {
-public:
- Impl() : ownedMutex_(new Mutex()), mutex_(NULL), condInitialized_(false) {
+ public:
+
+ Impl()
+ : ownedMutex_(new Mutex()),
+ mutex_(NULL),
+ condInitialized_(false) {
init(ownedMutex_.get());
}
- Impl(Mutex* mutex) : mutex_(NULL), condInitialized_(false) { init(mutex); }
+ Impl(Mutex* mutex)
+ : mutex_(NULL),
+ condInitialized_(false) {
+ init(mutex);
+ }
- Impl(Monitor* monitor) : mutex_(NULL), condInitialized_(false) { init(&(monitor->mutex())); }
+ Impl(Monitor* monitor)
+ : mutex_(NULL),
+ condInitialized_(false) {
+ init(&(monitor->mutex()));
+ }
~Impl() { cleanup(); }
@@ -70,10 +80,11 @@
if (result == THRIFT_ETIMEDOUT) {
// pthread_cond_timedwait has been observed to return early on
// various platforms, so comment out this assert.
- // assert(Util::currentTime() >= (now + timeout));
+ //assert(Util::currentTime() >= (now + timeout));
throw TimedOutException();
} else if (result != 0) {
- throw TException("pthread_cond_wait() or pthread_cond_timedwait() failed");
+ throw TException(
+ "pthread_cond_wait() or pthread_cond_timedwait() failed");
}
}
@@ -99,16 +110,19 @@
*/
int waitForTime(const THRIFT_TIMESPEC* abstime) const {
assert(mutex_);
- pthread_mutex_t* mutexImpl = reinterpret_cast<pthread_mutex_t*>(mutex_->getUnderlyingImpl());
+ pthread_mutex_t* mutexImpl =
+ reinterpret_cast<pthread_mutex_t*>(mutex_->getUnderlyingImpl());
assert(mutexImpl);
// XXX Need to assert that caller owns mutex
- return pthread_cond_timedwait(&pthread_cond_, mutexImpl, abstime);
+ return pthread_cond_timedwait(&pthread_cond_,
+ mutexImpl,
+ abstime);
}
int waitForTime(const struct timeval* abstime) const {
struct THRIFT_TIMESPEC temp;
- temp.tv_sec = abstime->tv_sec;
+ temp.tv_sec = abstime->tv_sec;
temp.tv_nsec = abstime->tv_usec * 1000;
return waitForTime(&temp);
}
@@ -118,11 +132,13 @@
*/
int waitForever() const {
assert(mutex_);
- pthread_mutex_t* mutexImpl = reinterpret_cast<pthread_mutex_t*>(mutex_->getUnderlyingImpl());
+ pthread_mutex_t* mutexImpl =
+ reinterpret_cast<pthread_mutex_t*>(mutex_->getUnderlyingImpl());
assert(mutexImpl);
return pthread_cond_wait(&pthread_cond_, mutexImpl);
}
+
void notify() {
// XXX Need to assert that caller owns mutex
int iret = pthread_cond_signal(&pthread_cond_);
@@ -137,7 +153,8 @@
assert(iret == 0);
}
-private:
+ private:
+
void init(Mutex* mutex) {
mutex_ = mutex;
@@ -167,32 +184,19 @@
mutable bool condInitialized_;
};
-Monitor::Monitor() : impl_(new Monitor::Impl()) {
-}
-Monitor::Monitor(Mutex* mutex) : impl_(new Monitor::Impl(mutex)) {
-}
-Monitor::Monitor(Monitor* monitor) : impl_(new Monitor::Impl(monitor)) {
-}
+Monitor::Monitor() : impl_(new Monitor::Impl()) {}
+Monitor::Monitor(Mutex* mutex) : impl_(new Monitor::Impl(mutex)) {}
+Monitor::Monitor(Monitor* monitor) : impl_(new Monitor::Impl(monitor)) {}
-Monitor::~Monitor() {
- delete impl_;
-}
+Monitor::~Monitor() { delete impl_; }
-Mutex& Monitor::mutex() const {
- return impl_->mutex();
-}
+Mutex& Monitor::mutex() const { return impl_->mutex(); }
-void Monitor::lock() const {
- impl_->lock();
-}
+void Monitor::lock() const { impl_->lock(); }
-void Monitor::unlock() const {
- impl_->unlock();
-}
+void Monitor::unlock() const { impl_->unlock(); }
-void Monitor::wait(int64_t timeout) const {
- impl_->wait(timeout);
-}
+void Monitor::wait(int64_t timeout) const { impl_->wait(timeout); }
int Monitor::waitForTime(const THRIFT_TIMESPEC* abstime) const {
return impl_->waitForTime(abstime);
@@ -210,13 +214,8 @@
return impl_->waitForever();
}
-void Monitor::notify() const {
- impl_->notify();
-}
+void Monitor::notify() const { impl_->notify(); }
-void Monitor::notifyAll() const {
- impl_->notifyAll();
-}
-}
-}
-} // apache::thrift::concurrency
+void Monitor::notifyAll() const { impl_->notifyAll(); }
+
+}}} // apache::thrift::concurrency
diff --git a/lib/cpp/src/thrift/concurrency/Monitor.h b/lib/cpp/src/thrift/concurrency/Monitor.h
index 5472f85..811e0e1 100644
--- a/lib/cpp/src/thrift/concurrency/Monitor.h
+++ b/lib/cpp/src/thrift/concurrency/Monitor.h
@@ -25,9 +25,8 @@
#include <boost/utility.hpp>
-namespace apache {
-namespace thrift {
-namespace concurrency {
+
+namespace apache { namespace thrift { namespace concurrency {
/**
* A monitor is a combination mutex and condition-event. Waiting and
@@ -48,7 +47,7 @@
* @version $Id:$
*/
class Monitor : boost::noncopyable {
-public:
+ public:
/** Creates a new mutex, and takes ownership of it. */
Monitor();
@@ -102,28 +101,30 @@
*/
void wait(int64_t timeout_ms = 0LL) const;
+
/** Wakes up one thread waiting on this monitor. */
virtual void notify() const;
/** Wakes up all waiting threads on this monitor. */
virtual void notifyAll() const;
-private:
+ private:
+
class Impl;
Impl* impl_;
};
class Synchronized {
-public:
- Synchronized(const Monitor* monitor) : g(monitor->mutex()) {}
- Synchronized(const Monitor& monitor) : g(monitor.mutex()) {}
+ public:
+ Synchronized(const Monitor* monitor) : g(monitor->mutex()) { }
+ Synchronized(const Monitor& monitor) : g(monitor.mutex()) { }
-private:
+ private:
Guard g;
};
-}
-}
-} // apache::thrift::concurrency
+
+
+}}} // apache::thrift::concurrency
#endif // #ifndef _THRIFT_CONCURRENCY_MONITOR_H_
diff --git a/lib/cpp/src/thrift/concurrency/Mutex.cpp b/lib/cpp/src/thrift/concurrency/Mutex.cpp
index d9921aa..3f7bb5b 100644
--- a/lib/cpp/src/thrift/concurrency/Mutex.cpp
+++ b/lib/cpp/src/thrift/concurrency/Mutex.cpp
@@ -31,9 +31,7 @@
using boost::shared_ptr;
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
#ifndef THRIFT_NO_CONTENTION_PROFILING
@@ -42,38 +40,40 @@
volatile static sig_atomic_t mutexProfilingCounter = 0;
-void enableMutexProfiling(int32_t profilingSampleRate, MutexWaitCallback callback) {
+void enableMutexProfiling(int32_t profilingSampleRate,
+ MutexWaitCallback callback) {
mutexProfilingSampleRate = profilingSampleRate;
mutexProfilingCallback = callback;
}
-#define PROFILE_MUTEX_START_LOCK() int64_t _lock_startTime = maybeGetProfilingStartTime();
+#define PROFILE_MUTEX_START_LOCK() \
+ int64_t _lock_startTime = maybeGetProfilingStartTime();
-#define PROFILE_MUTEX_NOT_LOCKED() \
- do { \
- if (_lock_startTime > 0) { \
- int64_t endTime = Util::currentTimeUsec(); \
- (*mutexProfilingCallback)(this, endTime - _lock_startTime); \
- } \
+#define PROFILE_MUTEX_NOT_LOCKED() \
+ do { \
+ if (_lock_startTime > 0) { \
+ int64_t endTime = Util::currentTimeUsec(); \
+ (*mutexProfilingCallback)(this, endTime - _lock_startTime); \
+ } \
} while (0)
-#define PROFILE_MUTEX_LOCKED() \
- do { \
- profileTime_ = _lock_startTime; \
- if (profileTime_ > 0) { \
- profileTime_ = Util::currentTimeUsec() - profileTime_; \
- } \
+#define PROFILE_MUTEX_LOCKED() \
+ do { \
+ profileTime_ = _lock_startTime; \
+ if (profileTime_ > 0) { \
+ profileTime_ = Util::currentTimeUsec() - profileTime_; \
+ } \
} while (0)
-#define PROFILE_MUTEX_START_UNLOCK() \
- int64_t _temp_profileTime = profileTime_; \
+#define PROFILE_MUTEX_START_UNLOCK() \
+ int64_t _temp_profileTime = profileTime_; \
profileTime_ = 0;
-#define PROFILE_MUTEX_UNLOCKED() \
- do { \
- if (_temp_profileTime > 0) { \
- (*mutexProfilingCallback)(this, _temp_profileTime); \
- } \
+#define PROFILE_MUTEX_UNLOCKED() \
+ do { \
+ if (_temp_profileTime > 0) { \
+ (*mutexProfilingCallback)(this, _temp_profileTime); \
+ } \
} while (0)
static inline int64_t maybeGetProfilingStartTime() {
@@ -101,11 +101,11 @@
}
#else
-#define PROFILE_MUTEX_START_LOCK()
-#define PROFILE_MUTEX_NOT_LOCKED()
-#define PROFILE_MUTEX_LOCKED()
-#define PROFILE_MUTEX_START_UNLOCK()
-#define PROFILE_MUTEX_UNLOCKED()
+# define PROFILE_MUTEX_START_LOCK()
+# define PROFILE_MUTEX_NOT_LOCKED()
+# define PROFILE_MUTEX_LOCKED()
+# define PROFILE_MUTEX_START_UNLOCK()
+# define PROFILE_MUTEX_UNLOCKED()
#endif // THRIFT_NO_CONTENTION_PROFILING
/**
@@ -114,7 +114,7 @@
* @version $Id:$
*/
class Mutex::impl {
-public:
+ public:
impl(Initializer init) : initialized_(false) {
#ifndef THRIFT_NO_CONTENTION_PROFILING
profileTime_ = 0;
@@ -182,9 +182,9 @@
PROFILE_MUTEX_UNLOCKED();
}
- void* getUnderlyingImpl() const { return (void*)&pthread_mutex_; }
+ void* getUnderlyingImpl() const { return (void*) &pthread_mutex_; }
-private:
+ private:
mutable pthread_mutex_t pthread_mutex_;
mutable bool initialized_;
#ifndef THRIFT_NO_CONTENTION_PROFILING
@@ -192,28 +192,17 @@
#endif
};
-Mutex::Mutex(Initializer init) : impl_(new Mutex::impl(init)) {
-}
+Mutex::Mutex(Initializer init) : impl_(new Mutex::impl(init)) {}
-void* Mutex::getUnderlyingImpl() const {
- return impl_->getUnderlyingImpl();
-}
+void* Mutex::getUnderlyingImpl() const { return impl_->getUnderlyingImpl(); }
-void Mutex::lock() const {
- impl_->lock();
-}
+void Mutex::lock() const { impl_->lock(); }
-bool Mutex::trylock() const {
- return impl_->trylock();
-}
+bool Mutex::trylock() const { return impl_->trylock(); }
-bool Mutex::timedlock(int64_t ms) const {
- return impl_->timedlock(ms);
-}
+bool Mutex::timedlock(int64_t ms) const { return impl_->timedlock(ms); }
-void Mutex::unlock() const {
- impl_->unlock();
-}
+void Mutex::unlock() const { impl_->unlock(); }
void Mutex::DEFAULT_INITIALIZER(void* arg) {
pthread_mutex_t* pthread_mutex = (pthread_mutex_t*)arg;
@@ -222,8 +211,7 @@
assert(ret == 0);
}
-#if defined(PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP) \
- || defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP)
+#if defined(PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP) || defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP)
static void init_with_kind(pthread_mutex_t* mutex, int kind) {
pthread_mutexattr_t mutexattr;
int ret = pthread_mutexattr_init(&mutexattr);
@@ -262,6 +250,7 @@
}
#endif
+
/**
* Implementation of ReadWriteMutex class using POSIX rw lock
*
@@ -280,7 +269,7 @@
}
~impl() {
- if (initialized_) {
+ if(initialized_) {
initialized_ = false;
int ret = pthread_rwlock_destroy(&rw_lock_);
THRIFT_UNUSED_VARIABLE(ret);
@@ -291,7 +280,7 @@
void acquireRead() const {
PROFILE_MUTEX_START_LOCK();
pthread_rwlock_rdlock(&rw_lock_);
- PROFILE_MUTEX_NOT_LOCKED(); // not exclusive, so use not-locked path
+ PROFILE_MUTEX_NOT_LOCKED(); // not exclusive, so use not-locked path
}
void acquireWrite() const {
@@ -318,33 +307,22 @@
#endif
};
-ReadWriteMutex::ReadWriteMutex() : impl_(new ReadWriteMutex::impl()) {
-}
+ReadWriteMutex::ReadWriteMutex() : impl_(new ReadWriteMutex::impl()) {}
-void ReadWriteMutex::acquireRead() const {
- impl_->acquireRead();
-}
+void ReadWriteMutex::acquireRead() const { impl_->acquireRead(); }
-void ReadWriteMutex::acquireWrite() const {
- impl_->acquireWrite();
-}
+void ReadWriteMutex::acquireWrite() const { impl_->acquireWrite(); }
-bool ReadWriteMutex::attemptRead() const {
- return impl_->attemptRead();
-}
+bool ReadWriteMutex::attemptRead() const { return impl_->attemptRead(); }
-bool ReadWriteMutex::attemptWrite() const {
- return impl_->attemptWrite();
-}
+bool ReadWriteMutex::attemptWrite() const { return impl_->attemptWrite(); }
-void ReadWriteMutex::release() const {
- impl_->release();
-}
+void ReadWriteMutex::release() const { impl_->release(); }
-NoStarveReadWriteMutex::NoStarveReadWriteMutex() : writerWaiting_(false) {
-}
+NoStarveReadWriteMutex::NoStarveReadWriteMutex() : writerWaiting_(false) {}
-void NoStarveReadWriteMutex::acquireRead() const {
+void NoStarveReadWriteMutex::acquireRead() const
+{
if (writerWaiting_) {
// writer is waiting, block on the writer's mutex until he's done with it
mutex_.lock();
@@ -354,7 +332,8 @@
ReadWriteMutex::acquireRead();
}
-void NoStarveReadWriteMutex::acquireWrite() const {
+void NoStarveReadWriteMutex::acquireWrite() const
+{
// if we can acquire the rwlock the easy way, we're done
if (attemptWrite()) {
return;
@@ -369,6 +348,6 @@
writerWaiting_ = false;
mutex_.unlock();
}
-}
-}
-} // apache::thrift::concurrency
+
+}}} // apache::thrift::concurrency
+
diff --git a/lib/cpp/src/thrift/concurrency/Mutex.h b/lib/cpp/src/thrift/concurrency/Mutex.h
index e3142fa..3cd8440 100644
--- a/lib/cpp/src/thrift/concurrency/Mutex.h
+++ b/lib/cpp/src/thrift/concurrency/Mutex.h
@@ -23,9 +23,7 @@
#include <boost/shared_ptr.hpp>
#include <boost/noncopyable.hpp>
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
#ifndef THRIFT_NO_CONTENTION_PROFILING
@@ -48,7 +46,8 @@
* particular time period.
*/
typedef void (*MutexWaitCallback)(const void* id, int64_t waitTimeMicros);
-void enableMutexProfiling(int32_t profilingSampleRate, MutexWaitCallback callback);
+void enableMutexProfiling(int32_t profilingSampleRate,
+ MutexWaitCallback callback);
#endif
@@ -58,7 +57,7 @@
* @version $Id:$
*/
class Mutex {
-public:
+ public:
typedef void (*Initializer)(void*);
Mutex(Initializer init = DEFAULT_INITIALIZER);
@@ -74,7 +73,8 @@
static void ADAPTIVE_INITIALIZER(void*);
static void RECURSIVE_INITIALIZER(void*);
-private:
+ private:
+
class impl;
boost::shared_ptr<impl> impl_;
};
@@ -96,6 +96,7 @@
virtual void release() const;
private:
+
class impl;
boost::shared_ptr<impl> impl_;
};
@@ -120,7 +121,7 @@
};
class Guard : boost::noncopyable {
-public:
+ public:
Guard(const Mutex& value, int64_t timeout = 0) : mutex_(&value) {
if (timeout == 0) {
value.lock();
@@ -140,40 +141,48 @@
}
}
- operator bool() const { return (mutex_ != NULL); }
+ operator bool() const {
+ return (mutex_ != NULL);
+ }
-private:
+ private:
const Mutex* mutex_;
};
// Can be used as second argument to RWGuard to make code more readable
// as to whether we're doing acquireRead() or acquireWrite().
-enum RWGuardType { RW_READ = 0, RW_WRITE = 1 };
+enum RWGuardType {
+ RW_READ = 0,
+ RW_WRITE = 1
+};
+
class RWGuard : boost::noncopyable {
-public:
- RWGuard(const ReadWriteMutex& value, bool write = false) : rw_mutex_(value) {
- if (write) {
- rw_mutex_.acquireWrite();
- } else {
- rw_mutex_.acquireRead();
+ public:
+ RWGuard(const ReadWriteMutex& value, bool write = false)
+ : rw_mutex_(value) {
+ if (write) {
+ rw_mutex_.acquireWrite();
+ } else {
+ rw_mutex_.acquireRead();
+ }
}
- }
- RWGuard(const ReadWriteMutex& value, RWGuardType type) : rw_mutex_(value) {
- if (type == RW_WRITE) {
- rw_mutex_.acquireWrite();
- } else {
- rw_mutex_.acquireRead();
+ RWGuard(const ReadWriteMutex& value, RWGuardType type)
+ : rw_mutex_(value) {
+ if (type == RW_WRITE) {
+ rw_mutex_.acquireWrite();
+ } else {
+ rw_mutex_.acquireRead();
+ }
}
- }
- ~RWGuard() { rw_mutex_.release(); }
-
-private:
- const ReadWriteMutex& rw_mutex_;
+ ~RWGuard() {
+ rw_mutex_.release();
+ }
+ private:
+ const ReadWriteMutex& rw_mutex_;
};
-}
-}
-} // apache::thrift::concurrency
+
+}}} // apache::thrift::concurrency
#endif // #ifndef _THRIFT_CONCURRENCY_MUTEX_H_
diff --git a/lib/cpp/src/thrift/concurrency/PlatformThreadFactory.h b/lib/cpp/src/thrift/concurrency/PlatformThreadFactory.h
index 311c3db..6e46dfc 100644
--- a/lib/cpp/src/thrift/concurrency/PlatformThreadFactory.h
+++ b/lib/cpp/src/thrift/concurrency/PlatformThreadFactory.h
@@ -20,7 +20,6 @@
#ifndef _THRIFT_CONCURRENCY_PLATFORMTHREADFACTORY_H_
#define _THRIFT_CONCURRENCY_PLATFORMTHREADFACTORY_H_ 1
-// clang-format off
#include <thrift/thrift-config.h>
#if USE_BOOST_THREAD
# include <thrift/concurrency/BoostThreadFactory.h>
@@ -29,13 +28,9 @@
#else
# include <thrift/concurrency/PosixThreadFactory.h>
#endif
-// clang-format on
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
-// clang-format off
#ifdef USE_BOOST_THREAD
typedef BoostThreadFactory PlatformThreadFactory;
#elif USE_STD_THREAD
@@ -43,10 +38,7 @@
#else
typedef PosixThreadFactory PlatformThreadFactory;
#endif
-// clang-format on
-}
-}
-} // apache::thrift::concurrency
+}}} // apache::thrift::concurrency
#endif // #ifndef _THRIFT_CONCURRENCY_PLATFORMTHREADFACTORY_H_
diff --git a/lib/cpp/src/thrift/concurrency/PosixThreadFactory.cpp b/lib/cpp/src/thrift/concurrency/PosixThreadFactory.cpp
index 47c5034..52ceead 100644
--- a/lib/cpp/src/thrift/concurrency/PosixThreadFactory.cpp
+++ b/lib/cpp/src/thrift/concurrency/PosixThreadFactory.cpp
@@ -23,7 +23,7 @@
#include <thrift/concurrency/Exception.h>
#if GOOGLE_PERFTOOLS_REGISTER_THREAD
-#include <google/profiler.h>
+# include <google/profiler.h>
#endif
#include <assert.h>
@@ -33,9 +33,7 @@
#include <boost/weak_ptr.hpp>
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
using boost::shared_ptr;
using boost::weak_ptr;
@@ -45,15 +43,22 @@
*
* @version $Id:$
*/
-class PthreadThread : public Thread {
-public:
- enum STATE { uninitialized, starting, started, stopping, stopped };
+class PthreadThread: public Thread {
+ public:
+
+ enum STATE {
+ uninitialized,
+ starting,
+ started,
+ stopping,
+ stopped
+ };
static const int MB = 1024 * 1024;
static void* threadMain(void* arg);
-private:
+ private:
pthread_t pthread_;
STATE state_;
int policy_;
@@ -62,23 +67,19 @@
weak_ptr<PthreadThread> self_;
bool detached_;
-public:
- PthreadThread(int policy,
- int priority,
- int stackSize,
- bool detached,
- shared_ptr<Runnable> runnable)
- :
+ public:
+
+ PthreadThread(int policy, int priority, int stackSize, bool detached, shared_ptr<Runnable> runnable) :
#ifndef _WIN32
- pthread_(0),
+ pthread_(0),
#endif // _WIN32
- state_(uninitialized),
- policy_(policy),
- priority_(priority),
- stackSize_(stackSize),
- detached_(detached) {
+ state_(uninitialized),
+ policy_(policy),
+ priority_(priority),
+ stackSize_(stackSize),
+ detached_(detached) {
this->Thread::runnable(runnable);
}
@@ -87,10 +88,10 @@
/* Nothing references this thread, if is is not detached, do a join
now, otherwise the thread-id and, possibly, other resources will
be leaked. */
- if (!detached_) {
+ if(!detached_) {
try {
join();
- } catch (...) {
+ } catch(...) {
// We're really hosed.
}
}
@@ -103,13 +104,14 @@
pthread_attr_t thread_attr;
if (pthread_attr_init(&thread_attr) != 0) {
- throw SystemResourceException("pthread_attr_init failed");
+ throw SystemResourceException("pthread_attr_init failed");
}
- if (pthread_attr_setdetachstate(&thread_attr,
- detached_ ? PTHREAD_CREATE_DETACHED : PTHREAD_CREATE_JOINABLE)
- != 0) {
- throw SystemResourceException("pthread_attr_setdetachstate failed");
+ if(pthread_attr_setdetachstate(&thread_attr,
+ detached_ ?
+ PTHREAD_CREATE_DETACHED :
+ PTHREAD_CREATE_JOINABLE) != 0) {
+ throw SystemResourceException("pthread_attr_setdetachstate failed");
}
// Set thread stack size
@@ -117,12 +119,11 @@
throw SystemResourceException("pthread_attr_setstacksize failed");
}
-// Set thread policy
-#ifdef _WIN32
- // WIN32 Pthread implementation doesn't seem to support sheduling policies other then
- // PosixThreadFactory::OTHER - runtime error
- policy_ = PosixThreadFactory::OTHER;
-#endif
+ // Set thread policy
+ #ifdef _WIN32
+ //WIN32 Pthread implementation doesn't seem to support sheduling policies other then PosixThreadFactory::OTHER - runtime error
+ policy_ = PosixThreadFactory::OTHER;
+ #endif
if (pthread_attr_setschedpolicy(&thread_attr, policy_) != 0) {
throw SystemResourceException("pthread_attr_setschedpolicy failed");
@@ -216,7 +217,7 @@
*/
class PosixThreadFactory::Impl {
-private:
+ private:
POLICY policy_;
PRIORITY priority_;
int stackSize_;
@@ -268,9 +269,13 @@
}
}
-public:
- Impl(POLICY policy, PRIORITY priority, int stackSize, bool detached)
- : policy_(policy), priority_(priority), stackSize_(stackSize), detached_(detached) {}
+ public:
+
+ Impl(POLICY policy, PRIORITY priority, int stackSize, bool detached) :
+ policy_(policy),
+ priority_(priority),
+ stackSize_(stackSize),
+ detached_(detached) {}
/**
* Creates a new POSIX thread to run the runnable object
@@ -278,12 +283,7 @@
* @param runnable A runnable object
*/
shared_ptr<Thread> newThread(shared_ptr<Runnable> runnable) const {
- shared_ptr<PthreadThread> result
- = shared_ptr<PthreadThread>(new PthreadThread(toPthreadPolicy(policy_),
- toPthreadPriority(policy_, priority_),
- stackSize_,
- detached_,
- runnable));
+ shared_ptr<PthreadThread> result = shared_ptr<PthreadThread>(new PthreadThread(toPthreadPolicy(policy_), toPthreadPriority(policy_, priority_), stackSize_, detached_, runnable));
result->weakRef(result);
runnable->thread(result);
return result;
@@ -314,47 +314,28 @@
#else
return (Thread::id_t)pthread_self().p;
#endif // _WIN32
+
}
+
};
-PosixThreadFactory::PosixThreadFactory(POLICY policy,
- PRIORITY priority,
- int stackSize,
- bool detached)
- : impl_(new PosixThreadFactory::Impl(policy, priority, stackSize, detached)) {
-}
+PosixThreadFactory::PosixThreadFactory(POLICY policy, PRIORITY priority, int stackSize, bool detached) :
+ impl_(new PosixThreadFactory::Impl(policy, priority, stackSize, detached)) {}
-shared_ptr<Thread> PosixThreadFactory::newThread(shared_ptr<Runnable> runnable) const {
- return impl_->newThread(runnable);
-}
+shared_ptr<Thread> PosixThreadFactory::newThread(shared_ptr<Runnable> runnable) const { return impl_->newThread(runnable); }
-int PosixThreadFactory::getStackSize() const {
- return impl_->getStackSize();
-}
+int PosixThreadFactory::getStackSize() const { return impl_->getStackSize(); }
-void PosixThreadFactory::setStackSize(int value) {
- impl_->setStackSize(value);
-}
+void PosixThreadFactory::setStackSize(int value) { impl_->setStackSize(value); }
-PosixThreadFactory::PRIORITY PosixThreadFactory::getPriority() const {
- return impl_->getPriority();
-}
+PosixThreadFactory::PRIORITY PosixThreadFactory::getPriority() const { return impl_->getPriority(); }
-void PosixThreadFactory::setPriority(PosixThreadFactory::PRIORITY value) {
- impl_->setPriority(value);
-}
+void PosixThreadFactory::setPriority(PosixThreadFactory::PRIORITY value) { impl_->setPriority(value); }
-bool PosixThreadFactory::isDetached() const {
- return impl_->isDetached();
-}
+bool PosixThreadFactory::isDetached() const { return impl_->isDetached(); }
-void PosixThreadFactory::setDetached(bool value) {
- impl_->setDetached(value);
-}
+void PosixThreadFactory::setDetached(bool value) { impl_->setDetached(value); }
-Thread::id_t PosixThreadFactory::getCurrentThreadId() const {
- return impl_->getCurrentThreadId();
-}
-}
-}
-} // apache::thrift::concurrency
+Thread::id_t PosixThreadFactory::getCurrentThreadId() const { return impl_->getCurrentThreadId(); }
+
+}}} // apache::thrift::concurrency
diff --git a/lib/cpp/src/thrift/concurrency/PosixThreadFactory.h b/lib/cpp/src/thrift/concurrency/PosixThreadFactory.h
index 4004231..72368ca 100644
--- a/lib/cpp/src/thrift/concurrency/PosixThreadFactory.h
+++ b/lib/cpp/src/thrift/concurrency/PosixThreadFactory.h
@@ -24,9 +24,7 @@
#include <boost/shared_ptr.hpp>
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
/**
* A thread factory to create posix threads
@@ -35,11 +33,16 @@
*/
class PosixThreadFactory : public ThreadFactory {
-public:
+ public:
+
/**
* POSIX Thread scheduler policies
*/
- enum POLICY { OTHER, FIFO, ROUND_ROBIN };
+ enum POLICY {
+ OTHER,
+ FIFO,
+ ROUND_ROBIN
+ };
/**
* POSIX Thread scheduler relative priorities,
@@ -75,10 +78,7 @@
* By default threads are not joinable.
*/
- PosixThreadFactory(POLICY policy = ROUND_ROBIN,
- PRIORITY priority = NORMAL,
- int stackSize = 1,
- bool detached = true);
+ PosixThreadFactory(POLICY policy=ROUND_ROBIN, PRIORITY priority=NORMAL, int stackSize=1, bool detached=true);
// From ThreadFactory;
boost::shared_ptr<Thread> newThread(boost::shared_ptr<Runnable> runnable) const;
@@ -120,12 +120,11 @@
*/
virtual bool isDetached() const;
-private:
+ private:
class Impl;
boost::shared_ptr<Impl> impl_;
};
-}
-}
-} // apache::thrift::concurrency
+
+}}} // apache::thrift::concurrency
#endif // #ifndef _THRIFT_CONCURRENCY_POSIXTHREADFACTORY_H_
diff --git a/lib/cpp/src/thrift/concurrency/StdMonitor.cpp b/lib/cpp/src/thrift/concurrency/StdMonitor.cpp
index 7b3b209..cf257e6 100644
--- a/lib/cpp/src/thrift/concurrency/StdMonitor.cpp
+++ b/lib/cpp/src/thrift/concurrency/StdMonitor.cpp
@@ -30,9 +30,7 @@
#include <thread>
#include <mutex>
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
/**
* Monitor implementation using the std thread library
@@ -41,12 +39,26 @@
*/
class Monitor::Impl {
-public:
- Impl() : ownedMutex_(new Mutex()), conditionVariable_(), mutex_(NULL) { init(ownedMutex_.get()); }
+ public:
- Impl(Mutex* mutex) : ownedMutex_(), conditionVariable_(), mutex_(NULL) { init(mutex); }
+ Impl()
+ : ownedMutex_(new Mutex()),
+ conditionVariable_(),
+ mutex_(NULL) {
+ init(ownedMutex_.get());
+ }
- Impl(Monitor* monitor) : ownedMutex_(), conditionVariable_(), mutex_(NULL) {
+ Impl(Mutex* mutex)
+ : ownedMutex_(),
+ conditionVariable_(),
+ mutex_(NULL) {
+ init(mutex);
+ }
+
+ Impl(Monitor* monitor)
+ : ownedMutex_(),
+ conditionVariable_(),
+ mutex_(NULL) {
init(&(monitor->mutex()));
}
@@ -66,7 +78,8 @@
if (result == THRIFT_ETIMEDOUT) {
throw TimedOutException();
} else if (result != 0) {
- throw TException("Monitor::wait() failed");
+ throw TException(
+ "Monitor::wait() failed");
}
}
@@ -82,12 +95,12 @@
}
assert(mutex_);
- std::timed_mutex* mutexImpl = static_cast<std::timed_mutex*>(mutex_->getUnderlyingImpl());
+ std::timed_mutex* mutexImpl =
+ static_cast<std::timed_mutex*>(mutex_->getUnderlyingImpl());
assert(mutexImpl);
std::unique_lock<std::timed_mutex> lock(*mutexImpl, std::adopt_lock);
- bool timedout = (conditionVariable_.wait_for(lock, std::chrono::milliseconds(timeout_ms))
- == std::cv_status::timeout);
+ bool timedout = (conditionVariable_.wait_for(lock, std::chrono::milliseconds(timeout_ms)) == std::cv_status::timeout);
lock.release();
return (timedout ? THRIFT_ETIMEDOUT : 0);
}
@@ -98,7 +111,7 @@
*/
int waitForTime(const THRIFT_TIMESPEC* abstime) {
struct timeval temp;
- temp.tv_sec = static_cast<long>(abstime->tv_sec);
+ temp.tv_sec = static_cast<long>(abstime->tv_sec);
temp.tv_usec = static_cast<long>(abstime->tv_nsec) / 1000;
return waitForTime(&temp);
}
@@ -109,24 +122,24 @@
*/
int waitForTime(const struct timeval* abstime) {
assert(mutex_);
- std::timed_mutex* mutexImpl = static_cast<std::timed_mutex*>(mutex_->getUnderlyingImpl());
+ std::timed_mutex* mutexImpl =
+ static_cast<std::timed_mutex*>(mutex_->getUnderlyingImpl());
assert(mutexImpl);
struct timeval currenttime;
Util::toTimeval(currenttime, Util::currentTime());
- long tv_sec = static_cast<long>(abstime->tv_sec - currenttime.tv_sec);
+ long tv_sec = static_cast<long>(abstime->tv_sec - currenttime.tv_sec);
long tv_usec = static_cast<long>(abstime->tv_usec - currenttime.tv_usec);
- if (tv_sec < 0)
+ if(tv_sec < 0)
tv_sec = 0;
- if (tv_usec < 0)
+ if(tv_usec < 0)
tv_usec = 0;
std::unique_lock<std::timed_mutex> lock(*mutexImpl, std::adopt_lock);
bool timedout = (conditionVariable_.wait_for(lock,
- std::chrono::seconds(tv_sec)
- + std::chrono::microseconds(tv_usec))
- == std::cv_status::timeout);
+ std::chrono::seconds(tv_sec) +
+ std::chrono::microseconds(tv_usec)) == std::cv_status::timeout);
lock.release();
return (timedout ? THRIFT_ETIMEDOUT : 0);
}
@@ -137,7 +150,8 @@
*/
int waitForever() {
assert(mutex_);
- std::timed_mutex* mutexImpl = static_cast<std::timed_mutex*>(mutex_->getUnderlyingImpl());
+ std::timed_mutex* mutexImpl =
+ static_cast<std::timed_mutex*>(mutex_->getUnderlyingImpl());
assert(mutexImpl);
std::unique_lock<std::timed_mutex> lock(*mutexImpl, std::adopt_lock);
@@ -146,44 +160,39 @@
return 0;
}
- void notify() { conditionVariable_.notify_one(); }
- void notifyAll() { conditionVariable_.notify_all(); }
+ void notify() {
+ conditionVariable_.notify_one();
+ }
-private:
- void init(Mutex* mutex) { mutex_ = mutex; }
+ void notifyAll() {
+ conditionVariable_.notify_all();
+ }
+
+ private:
+
+ void init(Mutex* mutex) {
+ mutex_ = mutex;
+ }
const std::unique_ptr<Mutex> ownedMutex_;
std::condition_variable_any conditionVariable_;
Mutex* mutex_;
};
-Monitor::Monitor() : impl_(new Monitor::Impl()) {
-}
-Monitor::Monitor(Mutex* mutex) : impl_(new Monitor::Impl(mutex)) {
-}
-Monitor::Monitor(Monitor* monitor) : impl_(new Monitor::Impl(monitor)) {
-}
+Monitor::Monitor() : impl_(new Monitor::Impl()) {}
+Monitor::Monitor(Mutex* mutex) : impl_(new Monitor::Impl(mutex)) {}
+Monitor::Monitor(Monitor* monitor) : impl_(new Monitor::Impl(monitor)) {}
-Monitor::~Monitor() {
- delete impl_;
-}
+Monitor::~Monitor() { delete impl_; }
-Mutex& Monitor::mutex() const {
- return const_cast<Monitor::Impl*>(impl_)->mutex();
-}
+Mutex& Monitor::mutex() const { return const_cast<Monitor::Impl*>(impl_)->mutex(); }
-void Monitor::lock() const {
- const_cast<Monitor::Impl*>(impl_)->lock();
-}
+void Monitor::lock() const { const_cast<Monitor::Impl*>(impl_)->lock(); }
-void Monitor::unlock() const {
- const_cast<Monitor::Impl*>(impl_)->unlock();
-}
+void Monitor::unlock() const { const_cast<Monitor::Impl*>(impl_)->unlock(); }
-void Monitor::wait(int64_t timeout) const {
- const_cast<Monitor::Impl*>(impl_)->wait(timeout);
-}
+void Monitor::wait(int64_t timeout) const { const_cast<Monitor::Impl*>(impl_)->wait(timeout); }
int Monitor::waitForTime(const THRIFT_TIMESPEC* abstime) const {
return const_cast<Monitor::Impl*>(impl_)->waitForTime(abstime);
@@ -201,13 +210,8 @@
return const_cast<Monitor::Impl*>(impl_)->waitForever();
}
-void Monitor::notify() const {
- const_cast<Monitor::Impl*>(impl_)->notify();
-}
+void Monitor::notify() const { const_cast<Monitor::Impl*>(impl_)->notify(); }
-void Monitor::notifyAll() const {
- const_cast<Monitor::Impl*>(impl_)->notifyAll();
-}
-}
-}
-} // apache::thrift::concurrency
+void Monitor::notifyAll() const { const_cast<Monitor::Impl*>(impl_)->notifyAll(); }
+
+}}} // apache::thrift::concurrency
diff --git a/lib/cpp/src/thrift/concurrency/StdMutex.cpp b/lib/cpp/src/thrift/concurrency/StdMutex.cpp
index 69678a2..28f889a 100644
--- a/lib/cpp/src/thrift/concurrency/StdMutex.cpp
+++ b/lib/cpp/src/thrift/concurrency/StdMutex.cpp
@@ -26,42 +26,30 @@
#include <chrono>
#include <mutex>
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
/**
* Implementation of Mutex class using C++11 std::timed_mutex
*
* @version $Id:$
*/
-class Mutex::impl : public std::timed_mutex {};
+class Mutex::impl : public std::timed_mutex {
+};
-Mutex::Mutex(Initializer init) : impl_(new Mutex::impl()) {
-}
+Mutex::Mutex(Initializer init) : impl_(new Mutex::impl()) {}
-void* Mutex::getUnderlyingImpl() const {
- return impl_.get();
-}
+void* Mutex::getUnderlyingImpl() const { return impl_.get(); }
-void Mutex::lock() const {
- impl_->lock();
-}
+void Mutex::lock() const { impl_->lock(); }
-bool Mutex::trylock() const {
- return impl_->try_lock();
-}
+bool Mutex::trylock() const { return impl_->try_lock(); }
-bool Mutex::timedlock(int64_t ms) const {
- return impl_->try_lock_for(std::chrono::milliseconds(ms));
-}
+bool Mutex::timedlock(int64_t ms) const { return impl_->try_lock_for(std::chrono::milliseconds(ms)); }
-void Mutex::unlock() const {
- impl_->unlock();
-}
+void Mutex::unlock() const { impl_->unlock(); }
void Mutex::DEFAULT_INITIALIZER(void* arg) {
}
-}
-}
-} // apache::thrift::concurrency
+
+}}} // apache::thrift::concurrency
+
diff --git a/lib/cpp/src/thrift/concurrency/StdThreadFactory.cpp b/lib/cpp/src/thrift/concurrency/StdThreadFactory.cpp
index 1ff4e73..6014b32 100644
--- a/lib/cpp/src/thrift/concurrency/StdThreadFactory.cpp
+++ b/lib/cpp/src/thrift/concurrency/StdThreadFactory.cpp
@@ -30,9 +30,7 @@
#include <boost/weak_ptr.hpp>
#include <thread>
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
/**
* The C++11 thread class.
@@ -43,28 +41,37 @@
*
* @version $Id:$
*/
-class StdThread : public Thread, public boost::enable_shared_from_this<StdThread> {
-public:
- enum STATE { uninitialized, starting, started, stopping, stopped };
+class StdThread: public Thread, public boost::enable_shared_from_this<StdThread> {
+ public:
- static void threadMain(boost::shared_ptr<StdThread> thread);
+ enum STATE {
+ uninitialized,
+ starting,
+ started,
+ stopping,
+ stopped
+ };
-private:
+ static void threadMain(boost::shared_ptr<StdThread> thread);
+
+ private:
std::unique_ptr<std::thread> thread_;
STATE state_;
bool detached_;
-public:
- StdThread(bool detached, boost::shared_ptr<Runnable> runnable)
- : state_(uninitialized), detached_(detached) {
+ public:
+
+ StdThread(bool detached, boost::shared_ptr<Runnable> runnable) :
+ state_(uninitialized),
+ detached_(detached) {
this->Thread::runnable(runnable);
}
~StdThread() {
- if (!detached_) {
+ if(!detached_) {
try {
join();
- } catch (...) {
+ } catch(...) {
// We're really hosed.
}
}
@@ -80,7 +87,7 @@
thread_ = std::unique_ptr<std::thread>(new std::thread(threadMain, selfRef));
- if (detached_)
+ if(detached_)
thread_->detach();
}
@@ -90,7 +97,9 @@
}
}
- Thread::id_t getId() { return thread_.get() ? thread_->get_id() : std::thread::id(); }
+ Thread::id_t getId() {
+ return thread_.get() ? thread_->get_id() : std::thread::id();
+ }
boost::shared_ptr<Runnable> runnable() const { return Thread::runnable(); }
@@ -121,11 +130,13 @@
*/
class StdThreadFactory::Impl {
-private:
+ private:
bool detached_;
-public:
- Impl(bool detached) : detached_(detached) {}
+ public:
+
+ Impl(bool detached) :
+ detached_(detached) {}
/**
* Creates a new std::thread to run the runnable object
@@ -133,8 +144,7 @@
* @param runnable A runnable object
*/
boost::shared_ptr<Thread> newThread(boost::shared_ptr<Runnable> runnable) const {
- boost::shared_ptr<StdThread> result
- = boost::shared_ptr<StdThread>(new StdThread(detached_, runnable));
+ boost::shared_ptr<StdThread> result = boost::shared_ptr<StdThread>(new StdThread(detached_, runnable));
runnable->thread(result);
return result;
}
@@ -143,29 +153,23 @@
void setDetached(bool value) { detached_ = value; }
- Thread::id_t getCurrentThreadId() const { return std::this_thread::get_id(); }
+ Thread::id_t getCurrentThreadId() const {
+ return std::this_thread::get_id();
+ }
+
};
-StdThreadFactory::StdThreadFactory(bool detached) : impl_(new StdThreadFactory::Impl(detached)) {
-}
+StdThreadFactory::StdThreadFactory(bool detached) :
+ impl_(new StdThreadFactory::Impl(detached)) {}
-boost::shared_ptr<Thread> StdThreadFactory::newThread(boost::shared_ptr<Runnable> runnable) const {
- return impl_->newThread(runnable);
-}
+boost::shared_ptr<Thread> StdThreadFactory::newThread(boost::shared_ptr<Runnable> runnable) const { return impl_->newThread(runnable); }
-bool StdThreadFactory::isDetached() const {
- return impl_->isDetached();
-}
+bool StdThreadFactory::isDetached() const { return impl_->isDetached(); }
-void StdThreadFactory::setDetached(bool value) {
- impl_->setDetached(value);
-}
+void StdThreadFactory::setDetached(bool value) { impl_->setDetached(value); }
-Thread::id_t StdThreadFactory::getCurrentThreadId() const {
- return impl_->getCurrentThreadId();
-}
-}
-}
-} // apache::thrift::concurrency
+Thread::id_t StdThreadFactory::getCurrentThreadId() const { return impl_->getCurrentThreadId(); }
+
+}}} // apache::thrift::concurrency
#endif // USE_STD_THREAD
diff --git a/lib/cpp/src/thrift/concurrency/StdThreadFactory.h b/lib/cpp/src/thrift/concurrency/StdThreadFactory.h
index fb86bbf..307f970 100644
--- a/lib/cpp/src/thrift/concurrency/StdThreadFactory.h
+++ b/lib/cpp/src/thrift/concurrency/StdThreadFactory.h
@@ -24,9 +24,7 @@
#include <boost/shared_ptr.hpp>
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
/**
* A thread factory to create std::threads.
@@ -35,7 +33,8 @@
*/
class StdThreadFactory : public ThreadFactory {
-public:
+ public:
+
/**
* Std thread factory. All threads created by a factory are reference-counted
* via boost::shared_ptr and boost::weak_ptr. The factory guarantees that threads and
@@ -45,7 +44,7 @@
* By default threads are not joinable.
*/
- StdThreadFactory(bool detached = true);
+ StdThreadFactory(bool detached=true);
// From ThreadFactory;
boost::shared_ptr<Thread> newThread(boost::shared_ptr<Runnable> runnable) const;
@@ -67,8 +66,7 @@
class Impl;
boost::shared_ptr<Impl> impl_;
};
-}
-}
-} // apache::thrift::concurrency
+
+}}} // apache::thrift::concurrency
#endif // #ifndef _THRIFT_CONCURRENCY_STDTHREADFACTORY_H_
diff --git a/lib/cpp/src/thrift/concurrency/Thread.h b/lib/cpp/src/thrift/concurrency/Thread.h
old mode 100644
new mode 100755
index 1d9153f..7012933
--- a/lib/cpp/src/thrift/concurrency/Thread.h
+++ b/lib/cpp/src/thrift/concurrency/Thread.h
@@ -27,18 +27,16 @@
#include <thrift/thrift-config.h>
#if USE_BOOST_THREAD
-#include <boost/thread.hpp>
+# include <boost/thread.hpp>
#elif USE_STD_THREAD
-#include <thread>
+# include <thread>
#else
-#ifdef HAVE_PTHREAD_H
-#include <pthread.h>
-#endif
+# ifdef HAVE_PTHREAD_H
+# include <pthread.h>
+# endif
#endif
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
class Thread;
@@ -49,8 +47,8 @@
*/
class Runnable {
-public:
- virtual ~Runnable(){};
+ public:
+ virtual ~Runnable() {};
virtual void run() = 0;
/**
@@ -65,7 +63,7 @@
*/
virtual void thread(boost::shared_ptr<Thread> value) { thread_ = value; }
-private:
+ private:
boost::weak_ptr<Thread> thread_;
};
@@ -80,7 +78,8 @@
*/
class Thread {
-public:
+ public:
+
#if USE_BOOST_THREAD
typedef boost::thread::id id_t;
@@ -98,7 +97,7 @@
static inline id_t get_current() { return pthread_self(); }
#endif
- virtual ~Thread(){};
+ virtual ~Thread() {};
/**
* Starts the thread. Does platform specific thread creation and
@@ -123,11 +122,12 @@
*/
virtual boost::shared_ptr<Runnable> runnable() const { return _runnable; }
-protected:
+ protected:
virtual void runnable(boost::shared_ptr<Runnable> value) { _runnable = value; }
-private:
+ private:
boost::shared_ptr<Runnable> _runnable;
+
};
/**
@@ -136,19 +136,17 @@
*/
class ThreadFactory {
-public:
+ public:
virtual ~ThreadFactory() {}
virtual boost::shared_ptr<Thread> newThread(boost::shared_ptr<Runnable> runnable) const = 0;
- /** Gets the current thread id or unknown_thread_id if the current thread is not a thrift thread
- */
+ /** Gets the current thread id or unknown_thread_id if the current thread is not a thrift thread */
static const Thread::id_t unknown_thread_id;
virtual Thread::id_t getCurrentThreadId() const = 0;
};
-}
-}
-} // apache::thrift::concurrency
+
+}}} // apache::thrift::concurrency
#endif // #ifndef _THRIFT_CONCURRENCY_THREAD_H_
diff --git a/lib/cpp/src/thrift/concurrency/ThreadManager.cpp b/lib/cpp/src/thrift/concurrency/ThreadManager.cpp
index 9ff2c9a..204d5dc 100644
--- a/lib/cpp/src/thrift/concurrency/ThreadManager.cpp
+++ b/lib/cpp/src/thrift/concurrency/ThreadManager.cpp
@@ -32,11 +32,9 @@
#if defined(DEBUG)
#include <iostream>
-#endif // defined(DEBUG)
+#endif //defined(DEBUG)
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
using boost::shared_ptr;
using boost::dynamic_pointer_cast;
@@ -51,18 +49,18 @@
*
* @version $Id:$
*/
-class ThreadManager::Impl : public ThreadManager {
+class ThreadManager::Impl : public ThreadManager {
-public:
- Impl()
- : workerCount_(0),
- workerMaxCount_(0),
- idleCount_(0),
- pendingTaskCountMax_(0),
- expiredCount_(0),
- state_(ThreadManager::UNINITIALIZED),
- monitor_(&mutex_),
- maxMonitor_(&mutex_) {}
+ public:
+ Impl() :
+ workerCount_(0),
+ workerMaxCount_(0),
+ idleCount_(0),
+ pendingTaskCountMax_(0),
+ expiredCount_(0),
+ state_(ThreadManager::UNINITIALIZED),
+ monitor_(&mutex_),
+ maxMonitor_(&mutex_) {}
~Impl() { stop(); }
@@ -72,7 +70,9 @@
void join() { stopImpl(true); }
- ThreadManager::STATE state() const { return state_; }
+ ThreadManager::STATE state() const {
+ return state_;
+ }
shared_ptr<ThreadFactory> threadFactory() const {
Synchronized s(monitor_);
@@ -88,7 +88,9 @@
void removeWorker(size_t value);
- size_t idleWorkerCount() const { return idleCount_; }
+ size_t idleWorkerCount() const {
+ return idleCount_;
+ }
size_t workerCount() const {
Synchronized s(monitor_);
@@ -147,6 +149,7 @@
ThreadManager::STATE state_;
shared_ptr<ThreadFactory> threadFactory_;
+
friend class ThreadManager::Task;
std::queue<shared_ptr<Task> > tasks_;
Mutex mutex_;
@@ -162,13 +165,18 @@
class ThreadManager::Task : public Runnable {
-public:
- enum STATE { WAITING, EXECUTING, CANCELLED, COMPLETE };
+ public:
+ enum STATE {
+ WAITING,
+ EXECUTING,
+ CANCELLED,
+ COMPLETE
+ };
- Task(shared_ptr<Runnable> runnable, int64_t expiration = 0LL)
- : runnable_(runnable),
- state_(WAITING),
- expireTime_(expiration != 0LL ? Util::currentTime() + expiration : 0LL) {}
+ Task(shared_ptr<Runnable> runnable, int64_t expiration=0LL) :
+ runnable_(runnable),
+ state_(WAITING),
+ expireTime_(expiration != 0LL ? Util::currentTime() + expiration : 0LL) {}
~Task() {}
@@ -179,32 +187,46 @@
}
}
- shared_ptr<Runnable> getRunnable() { return runnable_; }
+ shared_ptr<Runnable> getRunnable() {
+ return runnable_;
+ }
- int64_t getExpireTime() const { return expireTime_; }
+ int64_t getExpireTime() const {
+ return expireTime_;
+ }
-private:
+ private:
shared_ptr<Runnable> runnable_;
friend class ThreadManager::Worker;
STATE state_;
int64_t expireTime_;
};
-class ThreadManager::Worker : public Runnable {
- enum STATE { UNINITIALIZED, STARTING, STARTED, STOPPING, STOPPED };
+class ThreadManager::Worker: public Runnable {
+ enum STATE {
+ UNINITIALIZED,
+ STARTING,
+ STARTED,
+ STOPPING,
+ STOPPED
+ };
-public:
- Worker(ThreadManager::Impl* manager) : manager_(manager), state_(UNINITIALIZED), idle_(false) {}
+ public:
+ Worker(ThreadManager::Impl* manager) :
+ manager_(manager),
+ state_(UNINITIALIZED),
+ idle_(false) {}
~Worker() {}
-private:
+ private:
bool isActive() const {
- return (manager_->workerCount_ <= manager_->workerMaxCount_)
- || (manager_->state_ == JOINING && !manager_->tasks_.empty());
+ return
+ (manager_->workerCount_ <= manager_->workerMaxCount_) ||
+ (manager_->state_ == JOINING && !manager_->tasks_.empty());
}
-public:
+ public:
/**
* Worker entry point
*
@@ -274,8 +296,8 @@
/* If we have a pending task max and we just dropped below it, wakeup any
thread that might be blocked on add. */
- if (manager_->pendingTaskCountMax_ != 0
- && manager_->tasks_.size() <= manager_->pendingTaskCountMax_ - 1) {
+ if (manager_->pendingTaskCountMax_ != 0 &&
+ manager_->tasks_.size() <= manager_->pendingTaskCountMax_ - 1) {
manager_->maxMonitor_.notify();
}
}
@@ -290,7 +312,7 @@
if (task->state_ == ThreadManager::Task::EXECUTING) {
try {
task->run();
- } catch (...) {
+ } catch(...) {
// XXX need to log this
}
}
@@ -308,18 +330,18 @@
return;
}
-private:
- ThreadManager::Impl* manager_;
- friend class ThreadManager::Impl;
- STATE state_;
- bool idle_;
+ private:
+ ThreadManager::Impl* manager_;
+ friend class ThreadManager::Impl;
+ STATE state_;
+ bool idle_;
};
-void ThreadManager::Impl::addWorker(size_t value) {
+
+ void ThreadManager::Impl::addWorker(size_t value) {
std::set<shared_ptr<Thread> > newThreads;
for (size_t ix = 0; ix < value; ix++) {
- shared_ptr<ThreadManager::Worker> worker
- = shared_ptr<ThreadManager::Worker>(new ThreadManager::Worker(this));
+ shared_ptr<ThreadManager::Worker> worker = shared_ptr<ThreadManager::Worker>(new ThreadManager::Worker(this));
newThreads.insert(threadFactory_->newThread(worker));
}
@@ -329,10 +351,8 @@
workers_.insert(newThreads.begin(), newThreads.end());
}
- for (std::set<shared_ptr<Thread> >::iterator ix = newThreads.begin(); ix != newThreads.end();
- ix++) {
- shared_ptr<ThreadManager::Worker> worker
- = dynamic_pointer_cast<ThreadManager::Worker, Runnable>((*ix)->runnable());
+ for (std::set<shared_ptr<Thread> >::iterator ix = newThreads.begin(); ix != newThreads.end(); ix++) {
+ shared_ptr<ThreadManager::Worker> worker = dynamic_pointer_cast<ThreadManager::Worker, Runnable>((*ix)->runnable());
worker->state_ = ThreadManager::Worker::STARTING;
(*ix)->start();
idMap_.insert(std::pair<const Thread::id_t, shared_ptr<Thread> >((*ix)->getId(), *ix));
@@ -376,8 +396,9 @@
{
Synchronized s(monitor_);
- if (state_ != ThreadManager::STOPPING && state_ != ThreadManager::JOINING
- && state_ != ThreadManager::STOPPED) {
+ if (state_ != ThreadManager::STOPPING &&
+ state_ != ThreadManager::JOINING &&
+ state_ != ThreadManager::STOPPED) {
doStop = true;
state_ = join ? ThreadManager::JOINING : ThreadManager::STOPPING;
}
@@ -395,6 +416,7 @@
Synchronized s(monitor_);
state_ = ThreadManager::STOPPED;
}
+
}
void ThreadManager::Impl::removeWorker(size_t value) {
@@ -423,9 +445,7 @@
workerMonitor_.wait();
}
- for (std::set<shared_ptr<Thread> >::iterator ix = deadWorkers_.begin();
- ix != deadWorkers_.end();
- ix++) {
+ for (std::set<shared_ptr<Thread> >::iterator ix = deadWorkers_.begin(); ix != deadWorkers_.end(); ix++) {
idMap_.erase((*ix)->getId());
workers_.erase(*ix);
}
@@ -434,61 +454,60 @@
}
}
-bool ThreadManager::Impl::canSleep() {
- const Thread::id_t id = threadFactory_->getCurrentThreadId();
- return idMap_.find(id) == idMap_.end();
-}
-
-void ThreadManager::Impl::add(shared_ptr<Runnable> value, int64_t timeout, int64_t expiration) {
- Guard g(mutex_, timeout);
-
- if (!g) {
- throw TimedOutException();
+ bool ThreadManager::Impl::canSleep() {
+ const Thread::id_t id = threadFactory_->getCurrentThreadId();
+ return idMap_.find(id) == idMap_.end();
}
- if (state_ != ThreadManager::STARTED) {
- throw IllegalStateException(
- "ThreadManager::Impl::add ThreadManager "
- "not started");
- }
+ void ThreadManager::Impl::add(shared_ptr<Runnable> value,
+ int64_t timeout,
+ int64_t expiration) {
+ Guard g(mutex_, timeout);
- removeExpiredTasks();
- if (pendingTaskCountMax_ > 0 && (tasks_.size() >= pendingTaskCountMax_)) {
- if (canSleep() && timeout >= 0) {
- while (pendingTaskCountMax_ > 0 && tasks_.size() >= pendingTaskCountMax_) {
- // This is thread safe because the mutex is shared between monitors.
- maxMonitor_.wait(timeout);
+ if (!g) {
+ throw TimedOutException();
+ }
+
+ if (state_ != ThreadManager::STARTED) {
+ throw IllegalStateException("ThreadManager::Impl::add ThreadManager "
+ "not started");
+ }
+
+ removeExpiredTasks();
+ if (pendingTaskCountMax_ > 0 && (tasks_.size() >= pendingTaskCountMax_)) {
+ if (canSleep() && timeout >= 0) {
+ while (pendingTaskCountMax_ > 0 && tasks_.size() >= pendingTaskCountMax_) {
+ // This is thread safe because the mutex is shared between monitors.
+ maxMonitor_.wait(timeout);
+ }
+ } else {
+ throw TooManyPendingTasksException();
}
- } else {
- throw TooManyPendingTasksException();
+ }
+
+ tasks_.push(shared_ptr<ThreadManager::Task>(new ThreadManager::Task(value, expiration)));
+
+ // If idle thread is available notify it, otherwise all worker threads are
+ // running and will get around to this task in time.
+ if (idleCount_ > 0) {
+ monitor_.notify();
}
}
- tasks_.push(shared_ptr<ThreadManager::Task>(new ThreadManager::Task(value, expiration)));
-
- // If idle thread is available notify it, otherwise all worker threads are
- // running and will get around to this task in time.
- if (idleCount_ > 0) {
- monitor_.notify();
- }
-}
-
void ThreadManager::Impl::remove(shared_ptr<Runnable> task) {
- (void)task;
+ (void) task;
Synchronized s(monitor_);
if (state_ != ThreadManager::STARTED) {
- throw IllegalStateException(
- "ThreadManager::Impl::remove ThreadManager not "
- "started");
+ throw IllegalStateException("ThreadManager::Impl::remove ThreadManager not "
+ "started");
}
}
boost::shared_ptr<Runnable> ThreadManager::Impl::removeNextPending() {
Guard g(mutex_);
if (state_ != ThreadManager::STARTED) {
- throw IllegalStateException(
- "ThreadManager::Impl::removeNextPending "
- "ThreadManager not started");
+ throw IllegalStateException("ThreadManager::Impl::removeNextPending "
+ "ThreadManager not started");
}
if (tasks_.empty()) {
@@ -524,15 +543,18 @@
}
}
+
void ThreadManager::Impl::setExpireCallback(ExpireCallback expireCallback) {
expireCallback_ = expireCallback;
}
class SimpleThreadManager : public ThreadManager::Impl {
-public:
- SimpleThreadManager(size_t workerCount = 4, size_t pendingTaskCountMax = 0)
- : workerCount_(workerCount), pendingTaskCountMax_(pendingTaskCountMax) {}
+ public:
+ SimpleThreadManager(size_t workerCount=4, size_t pendingTaskCountMax=0) :
+ workerCount_(workerCount),
+ pendingTaskCountMax_(pendingTaskCountMax) {
+ }
void start() {
ThreadManager::Impl::pendingTaskCountMax(pendingTaskCountMax_);
@@ -540,20 +562,20 @@
addWorker(workerCount_);
}
-private:
+ private:
const size_t workerCount_;
const size_t pendingTaskCountMax_;
Monitor monitor_;
};
+
shared_ptr<ThreadManager> ThreadManager::newThreadManager() {
return shared_ptr<ThreadManager>(new ThreadManager::Impl());
}
-shared_ptr<ThreadManager> ThreadManager::newSimpleThreadManager(size_t count,
- size_t pendingTaskCountMax) {
+shared_ptr<ThreadManager> ThreadManager::newSimpleThreadManager(size_t count, size_t pendingTaskCountMax) {
return shared_ptr<ThreadManager>(new SimpleThreadManager(count, pendingTaskCountMax));
}
-}
-}
-} // apache::thrift::concurrency
+
+}}} // apache::thrift::concurrency
+
diff --git a/lib/cpp/src/thrift/concurrency/ThreadManager.h b/lib/cpp/src/thrift/concurrency/ThreadManager.h
index 7bb71d1..0fedc88 100644
--- a/lib/cpp/src/thrift/concurrency/ThreadManager.h
+++ b/lib/cpp/src/thrift/concurrency/ThreadManager.h
@@ -25,9 +25,7 @@
#include <sys/types.h>
#include <thrift/concurrency/Thread.h>
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
/**
* Thread Pool Manager and related classes
@@ -55,10 +53,10 @@
*/
class ThreadManager {
-protected:
+ protected:
ThreadManager() {}
-public:
+ public:
typedef apache::thrift::stdcxx::function<void(boost::shared_ptr<Runnable>)> ExpireCallback;
virtual ~ThreadManager() {}
@@ -85,7 +83,14 @@
*/
virtual void join() = 0;
- enum STATE { UNINITIALIZED, STARTING, STARTED, JOINING, STOPPING, STOPPED };
+ enum STATE {
+ UNINITIALIZED,
+ STARTING,
+ STARTED,
+ JOINING,
+ STOPPING,
+ STOPPED
+ };
virtual STATE state() const = 0;
@@ -93,9 +98,9 @@
virtual void threadFactory(boost::shared_ptr<ThreadFactory> value) = 0;
- virtual void addWorker(size_t value = 1) = 0;
+ virtual void addWorker(size_t value=1) = 0;
- virtual void removeWorker(size_t value = 1) = 0;
+ virtual void removeWorker(size_t value=1) = 0;
/**
* Gets the current number of idle worker threads
@@ -110,7 +115,7 @@
/**
* Gets the current number of pending tasks
*/
- virtual size_t pendingTaskCount() const = 0;
+ virtual size_t pendingTaskCount() const = 0;
/**
* Gets the current number of pending and executing tasks
@@ -146,9 +151,9 @@
*
* @throws TooManyPendingTasksException Pending task count exceeds max pending task count
*/
- virtual void add(boost::shared_ptr<Runnable> task,
- int64_t timeout = 0LL,
- int64_t expiration = 0LL) = 0;
+ virtual void add(boost::shared_ptr<Runnable>task,
+ int64_t timeout=0LL,
+ int64_t expiration=0LL) = 0;
/**
* Removes a pending task
@@ -182,8 +187,7 @@
* a pendingTaskCountMax maximum pending tasks. The default, 0, specified no limit
* on pending tasks
*/
- static boost::shared_ptr<ThreadManager> newSimpleThreadManager(size_t count = 4,
- size_t pendingTaskCountMax = 0);
+ static boost::shared_ptr<ThreadManager> newSimpleThreadManager(size_t count=4, size_t pendingTaskCountMax=0);
class Task;
@@ -191,8 +195,7 @@
class Impl;
};
-}
-}
-} // apache::thrift::concurrency
+
+}}} // apache::thrift::concurrency
#endif // #ifndef _THRIFT_CONCURRENCY_THREADMANAGER_H_
diff --git a/lib/cpp/src/thrift/concurrency/TimerManager.cpp b/lib/cpp/src/thrift/concurrency/TimerManager.cpp
index 60b8c85..6821b2e 100644
--- a/lib/cpp/src/thrift/concurrency/TimerManager.cpp
+++ b/lib/cpp/src/thrift/concurrency/TimerManager.cpp
@@ -25,9 +25,7 @@
#include <iostream>
#include <set>
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
using boost::shared_ptr;
@@ -38,12 +36,20 @@
*/
class TimerManager::Task : public Runnable {
-public:
- enum STATE { WAITING, EXECUTING, CANCELLED, COMPLETE };
+ public:
+ enum STATE {
+ WAITING,
+ EXECUTING,
+ CANCELLED,
+ COMPLETE
+ };
- Task(shared_ptr<Runnable> runnable) : runnable_(runnable), state_(WAITING) {}
+ Task(shared_ptr<Runnable> runnable) :
+ runnable_(runnable),
+ state_(WAITING) {}
- ~Task() {}
+ ~Task() {
+ }
void run() {
if (state_ == EXECUTING) {
@@ -52,16 +58,17 @@
}
}
-private:
+ private:
shared_ptr<Runnable> runnable_;
friend class TimerManager::Dispatcher;
STATE state_;
};
-class TimerManager::Dispatcher : public Runnable {
+class TimerManager::Dispatcher: public Runnable {
-public:
- Dispatcher(TimerManager* manager) : manager_(manager) {}
+ public:
+ Dispatcher(TimerManager* manager) :
+ manager_(manager) {}
~Dispatcher() {}
@@ -86,19 +93,16 @@
Synchronized s(manager_->monitor_);
task_iterator expiredTaskEnd;
int64_t now = Util::currentTime();
- while (manager_->state_ == TimerManager::STARTED
- && (expiredTaskEnd = manager_->taskMap_.upper_bound(now))
- == manager_->taskMap_.begin()) {
+ while (manager_->state_ == TimerManager::STARTED &&
+ (expiredTaskEnd = manager_->taskMap_.upper_bound(now)) == manager_->taskMap_.begin()) {
int64_t timeout = 0LL;
if (!manager_->taskMap_.empty()) {
timeout = manager_->taskMap_.begin()->first - now;
}
- assert((timeout != 0 && manager_->taskCount_ > 0)
- || (timeout == 0 && manager_->taskCount_ == 0));
+ assert((timeout != 0 && manager_->taskCount_ > 0) || (timeout == 0 && manager_->taskCount_ == 0));
try {
manager_->monitor_.wait(timeout);
- } catch (TimedOutException&) {
- }
+ } catch (TimedOutException &) {}
now = Util::currentTime();
}
@@ -115,9 +119,7 @@
}
}
- for (std::set<shared_ptr<Task> >::iterator ix = expiredTasks.begin();
- ix != expiredTasks.end();
- ix++) {
+ for (std::set<shared_ptr<Task> >::iterator ix = expiredTasks.begin(); ix != expiredTasks.end(); ix++) {
(*ix)->run();
}
@@ -133,20 +135,20 @@
return;
}
-private:
+ private:
TimerManager* manager_;
friend class TimerManager;
};
#if defined(_MSC_VER)
#pragma warning(push)
-#pragma warning(disable : 4355) // 'this' used in base member initializer list
+#pragma warning(disable: 4355) // 'this' used in base member initializer list
#endif
-TimerManager::TimerManager()
- : taskCount_(0),
- state_(TimerManager::UNINITIALIZED),
- dispatcher_(shared_ptr<Dispatcher>(new Dispatcher(this))) {
+TimerManager::TimerManager() :
+ taskCount_(0),
+ state_(TimerManager::UNINITIALIZED),
+ dispatcher_(shared_ptr<Dispatcher>(new Dispatcher(this))) {
}
#if defined(_MSC_VER)
@@ -161,7 +163,7 @@
if (state_ != STOPPED) {
try {
stop();
- } catch (...) {
+ } catch(...) {
throw;
// uhoh
}
@@ -201,7 +203,7 @@
Synchronized s(monitor_);
if (state_ == TimerManager::UNINITIALIZED) {
state_ = TimerManager::STOPPED;
- } else if (state_ != STOPPING && state_ != STOPPED) {
+ } else if (state_ != STOPPING && state_ != STOPPED) {
doStop = true;
state_ = STOPPING;
monitor_.notifyAll();
@@ -225,7 +227,7 @@
return threadFactory_;
}
-void TimerManager::threadFactory(shared_ptr<const ThreadFactory> value) {
+void TimerManager::threadFactory(shared_ptr<const ThreadFactory> value) {
Synchronized s(monitor_);
threadFactory_ = value;
}
@@ -250,8 +252,7 @@
bool notifyRequired = (taskCount_ == 0) ? true : timeout < taskMap_.begin()->first;
taskCount_++;
- taskMap_.insert(
- std::pair<int64_t, shared_ptr<Task> >(timeout, shared_ptr<Task>(new Task(task))));
+ taskMap_.insert(std::pair<int64_t, shared_ptr<Task> >(timeout, shared_ptr<Task>(new Task(task))));
// If the task map was empty, or if we have an expiration that is earlier
// than any previously seen, kick the dispatcher so it can update its
@@ -270,7 +271,7 @@
int64_t now = Util::currentTime();
if (expiration < now) {
- throw InvalidArgumentException();
+ throw InvalidArgumentException();
}
add(task, expiration - now);
@@ -284,23 +285,21 @@
int64_t now = Util::currentTime();
if (expiration < now) {
- throw InvalidArgumentException();
+ throw InvalidArgumentException();
}
add(task, expiration - now);
}
void TimerManager::remove(shared_ptr<Runnable> task) {
- (void)task;
+ (void) task;
Synchronized s(monitor_);
if (state_ != TimerManager::STARTED) {
throw IllegalStateException();
}
}
-TimerManager::STATE TimerManager::state() const {
- return state_;
-}
-}
-}
-} // apache::thrift::concurrency
+TimerManager::STATE TimerManager::state() const { return state_; }
+
+}}} // apache::thrift::concurrency
+
diff --git a/lib/cpp/src/thrift/concurrency/TimerManager.h b/lib/cpp/src/thrift/concurrency/TimerManager.h
index 3946827..d8200cb 100644
--- a/lib/cpp/src/thrift/concurrency/TimerManager.h
+++ b/lib/cpp/src/thrift/concurrency/TimerManager.h
@@ -28,9 +28,7 @@
#include <map>
#include <time.h>
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
/**
* Timer Manager
@@ -41,7 +39,8 @@
*/
class TimerManager {
-public:
+ public:
+
TimerManager();
virtual ~TimerManager();
@@ -62,7 +61,7 @@
*/
virtual void stop();
- virtual size_t taskCount() const;
+ virtual size_t taskCount() const ;
/**
* Adds a task to be executed at some time in the future by a worker thread.
@@ -100,11 +99,17 @@
*/
virtual void remove(boost::shared_ptr<Runnable> task);
- enum STATE { UNINITIALIZED, STARTING, STARTED, STOPPING, STOPPED };
+ enum STATE {
+ UNINITIALIZED,
+ STARTING,
+ STARTED,
+ STOPPING,
+ STOPPED
+ };
virtual STATE state() const;
-private:
+ private:
boost::shared_ptr<const ThreadFactory> threadFactory_;
class Task;
friend class Task;
@@ -119,8 +124,7 @@
typedef std::multimap<int64_t, boost::shared_ptr<TimerManager::Task> >::iterator task_iterator;
typedef std::pair<task_iterator, task_iterator> task_range;
};
-}
-}
-} // apache::thrift::concurrency
+
+}}} // apache::thrift::concurrency
#endif // #ifndef _THRIFT_CONCURRENCY_TIMERMANAGER_H_
diff --git a/lib/cpp/src/thrift/concurrency/Util.cpp b/lib/cpp/src/thrift/concurrency/Util.cpp
index dd6d19f..7d9085e 100644
--- a/lib/cpp/src/thrift/concurrency/Util.cpp
+++ b/lib/cpp/src/thrift/concurrency/Util.cpp
@@ -26,19 +26,16 @@
#include <sys/time.h>
#endif
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
int64_t Util::currentTimeTicks(int64_t ticksPerSec) {
int64_t result;
struct timeval now;
int ret = THRIFT_GETTIMEOFDAY(&now, NULL);
assert(ret == 0);
- THRIFT_UNUSED_VARIABLE(ret); // squelching "unused variable" warning
+ THRIFT_UNUSED_VARIABLE(ret); //squelching "unused variable" warning
toTicks(result, now, ticksPerSec);
return result;
}
-}
-}
-} // apache::thrift::concurrency
+
+}}} // apache::thrift::concurrency
diff --git a/lib/cpp/src/thrift/concurrency/Util.h b/lib/cpp/src/thrift/concurrency/Util.h
index ba070b6..63d80a2 100644
--- a/lib/cpp/src/thrift/concurrency/Util.h
+++ b/lib/cpp/src/thrift/concurrency/Util.h
@@ -31,9 +31,7 @@
#include <thrift/transport/PlatformSocket.h>
-namespace apache {
-namespace thrift {
-namespace concurrency {
+namespace apache { namespace thrift { namespace concurrency {
/**
* Utility methods
@@ -57,7 +55,8 @@
static const int64_t NS_PER_US = NS_PER_S / US_PER_S;
static const int64_t US_PER_MS = US_PER_S / MS_PER_S;
-public:
+ public:
+
/**
* Converts millisecond timestamp into a THRIFT_TIMESPEC struct
*
@@ -65,20 +64,17 @@
* @param time or duration in milliseconds
*/
static void toTimespec(struct THRIFT_TIMESPEC& result, int64_t value) {
- result.tv_sec = value / MS_PER_S; // ms to s
+ result.tv_sec = value / MS_PER_S; // ms to s
result.tv_nsec = (value % MS_PER_S) * NS_PER_MS; // ms to ns
}
static void toTimeval(struct timeval& result, int64_t value) {
- result.tv_sec = static_cast<uint32_t>(value / MS_PER_S); // ms to s
+ result.tv_sec = static_cast<uint32_t>(value / MS_PER_S); // ms to s
result.tv_usec = static_cast<uint32_t>((value % MS_PER_S) * US_PER_MS); // ms to us
}
- static void toTicks(int64_t& result,
- int64_t secs,
- int64_t oldTicks,
- int64_t oldTicksPerSec,
- int64_t newTicksPerSec) {
+ static void toTicks(int64_t& result, int64_t secs, int64_t oldTicks,
+ int64_t oldTicksPerSec, int64_t newTicksPerSec) {
result = secs * newTicksPerSec;
result += oldTicks * newTicksPerSec / oldTicksPerSec;
@@ -90,28 +86,34 @@
/**
* Converts struct THRIFT_TIMESPEC to arbitrary-sized ticks since epoch
*/
- static void toTicks(int64_t& result, const struct THRIFT_TIMESPEC& value, int64_t ticksPerSec) {
+ static void toTicks(int64_t& result,
+ const struct THRIFT_TIMESPEC& value,
+ int64_t ticksPerSec) {
return toTicks(result, value.tv_sec, value.tv_nsec, NS_PER_S, ticksPerSec);
}
/**
* Converts struct timeval to arbitrary-sized ticks since epoch
*/
- static void toTicks(int64_t& result, const struct timeval& value, int64_t ticksPerSec) {
+ static void toTicks(int64_t& result,
+ const struct timeval& value,
+ int64_t ticksPerSec) {
return toTicks(result, value.tv_sec, value.tv_usec, US_PER_S, ticksPerSec);
}
/**
* Converts struct THRIFT_TIMESPEC to milliseconds
*/
- static void toMilliseconds(int64_t& result, const struct THRIFT_TIMESPEC& value) {
+ static void toMilliseconds(int64_t& result,
+ const struct THRIFT_TIMESPEC& value) {
return toTicks(result, value, MS_PER_S);
}
/**
* Converts struct timeval to milliseconds
*/
- static void toMilliseconds(int64_t& result, const struct timeval& value) {
+ static void toMilliseconds(int64_t& result,
+ const struct timeval& value) {
return toTicks(result, value, MS_PER_S);
}
@@ -144,8 +146,7 @@
*/
static int64_t currentTimeUsec() { return currentTimeTicks(US_PER_S); }
};
-}
-}
-} // apache::thrift::concurrency
+
+}}} // apache::thrift::concurrency
#endif // #ifndef _THRIFT_CONCURRENCY_UTIL_H_
diff --git a/lib/cpp/src/thrift/cxxfunctional.h b/lib/cpp/src/thrift/cxxfunctional.h
index dadaac3..c24b91b 100644
--- a/lib/cpp/src/thrift/cxxfunctional.h
+++ b/lib/cpp/src/thrift/cxxfunctional.h
@@ -20,8 +20,6 @@
#ifndef _THRIFT_CXXFUNCTIONAL_H_
#define _THRIFT_CXXFUNCTIONAL_H_ 1
-// clang-format off
-
/**
* Loads <functional> from the 'right' location, depending
* on compiler and whether or not it's using C++03 with TR1
diff --git a/lib/cpp/src/thrift/processor/PeekProcessor.cpp b/lib/cpp/src/thrift/processor/PeekProcessor.cpp
index 8c9a463..9303a13 100644
--- a/lib/cpp/src/thrift/processor/PeekProcessor.cpp
+++ b/lib/cpp/src/thrift/processor/PeekProcessor.cpp
@@ -23,16 +23,13 @@
using namespace apache::thrift::protocol;
using namespace apache::thrift;
-namespace apache {
-namespace thrift {
-namespace processor {
+namespace apache { namespace thrift { namespace processor {
PeekProcessor::PeekProcessor() {
memoryBuffer_.reset(new TMemoryBuffer());
targetTransport_ = memoryBuffer_;
}
-PeekProcessor::~PeekProcessor() {
-}
+PeekProcessor::~PeekProcessor() {}
void PeekProcessor::initialize(boost::shared_ptr<TProcessor> actualProcessor,
boost::shared_ptr<TProtocolFactory> protocolFactory,
@@ -52,13 +49,11 @@
if (boost::dynamic_pointer_cast<TMemoryBuffer>(targetTransport_)) {
memoryBuffer_ = boost::dynamic_pointer_cast<TMemoryBuffer>(targetTransport);
} else if (boost::dynamic_pointer_cast<TPipedTransport>(targetTransport_)) {
- memoryBuffer_ = boost::dynamic_pointer_cast<TMemoryBuffer>(
- boost::dynamic_pointer_cast<TPipedTransport>(targetTransport_)->getTargetTransport());
+ memoryBuffer_ = boost::dynamic_pointer_cast<TMemoryBuffer>(boost::dynamic_pointer_cast<TPipedTransport>(targetTransport_)->getTargetTransport());
}
if (!memoryBuffer_) {
- throw TException(
- "Target transport must be a TMemoryBuffer or a TPipedTransport with TMemoryBuffer");
+ throw TException("Target transport must be a TMemoryBuffer or a TPipedTransport with TMemoryBuffer");
}
}
@@ -112,21 +107,21 @@
}
void PeekProcessor::peekName(const std::string& fname) {
- (void)fname;
+ (void) fname;
}
void PeekProcessor::peekBuffer(uint8_t* buffer, uint32_t size) {
- (void)buffer;
- (void)size;
+ (void) buffer;
+ (void) size;
}
-void PeekProcessor::peek(boost::shared_ptr<TProtocol> in, TType ftype, int16_t fid) {
- (void)fid;
+void PeekProcessor::peek(boost::shared_ptr<TProtocol> in,
+ TType ftype,
+ int16_t fid) {
+ (void) fid;
in->skip(ftype);
}
-void PeekProcessor::peekEnd() {
-}
-}
-}
-}
+void PeekProcessor::peekEnd() {}
+
+}}}
diff --git a/lib/cpp/src/thrift/processor/PeekProcessor.h b/lib/cpp/src/thrift/processor/PeekProcessor.h
index 21c5999..9cfb35a 100644
--- a/lib/cpp/src/thrift/processor/PeekProcessor.h
+++ b/lib/cpp/src/thrift/processor/PeekProcessor.h
@@ -27,9 +27,7 @@
#include <thrift/transport/TBufferTransports.h>
#include <boost/shared_ptr.hpp>
-namespace apache {
-namespace thrift {
-namespace processor {
+namespace apache { namespace thrift { namespace processor {
/*
* Class for peeking at the raw data that is being processed by another processor
@@ -38,7 +36,7 @@
*/
class PeekProcessor : public apache::thrift::TProcessor {
-public:
+ public:
PeekProcessor();
virtual ~PeekProcessor();
@@ -46,13 +44,11 @@
// protocolFactory - the protocol factory used to wrap the memory buffer
// transportFactory - this TPipedTransportFactory is used to wrap the source transport
// via a call to getPipedTransport
- void initialize(
- boost::shared_ptr<apache::thrift::TProcessor> actualProcessor,
- boost::shared_ptr<apache::thrift::protocol::TProtocolFactory> protocolFactory,
- boost::shared_ptr<apache::thrift::transport::TPipedTransportFactory> transportFactory);
+ void initialize(boost::shared_ptr<apache::thrift::TProcessor> actualProcessor,
+ boost::shared_ptr<apache::thrift::protocol::TProtocolFactory> protocolFactory,
+ boost::shared_ptr<apache::thrift::transport::TPipedTransportFactory> transportFactory);
- boost::shared_ptr<apache::thrift::transport::TTransport> getPipedTransport(
- boost::shared_ptr<apache::thrift::transport::TTransport> in);
+ boost::shared_ptr<apache::thrift::transport::TTransport> getPipedTransport(boost::shared_ptr<apache::thrift::transport::TTransport> in);
void setTargetTransport(boost::shared_ptr<apache::thrift::transport::TTransport> targetTransport);
@@ -69,15 +65,14 @@
int16_t fid);
virtual void peekEnd();
-private:
+ private:
boost::shared_ptr<apache::thrift::TProcessor> actualProcessor_;
boost::shared_ptr<apache::thrift::protocol::TProtocol> pipedProtocol_;
boost::shared_ptr<apache::thrift::transport::TPipedTransportFactory> transportFactory_;
boost::shared_ptr<apache::thrift::transport::TMemoryBuffer> memoryBuffer_;
boost::shared_ptr<apache::thrift::transport::TTransport> targetTransport_;
};
-}
-}
-} // apache::thrift::processor
+
+}}} // apache::thrift::processor
#endif
diff --git a/lib/cpp/src/thrift/processor/StatsProcessor.h b/lib/cpp/src/thrift/processor/StatsProcessor.h
index e8ca067..0fc123e 100644
--- a/lib/cpp/src/thrift/processor/StatsProcessor.h
+++ b/lib/cpp/src/thrift/processor/StatsProcessor.h
@@ -25,9 +25,7 @@
#include <thrift/protocol/TProtocol.h>
#include <TProcessor.h>
-namespace apache {
-namespace thrift {
-namespace processor {
+namespace apache { namespace thrift { namespace processor {
/*
* Class for keeping track of function call statistics and printing them if desired
@@ -35,8 +33,11 @@
*/
class StatsProcessor : public apache::thrift::TProcessor {
public:
- StatsProcessor(bool print, bool frequency) : print_(print), frequency_(frequency) {}
- virtual ~StatsProcessor(){};
+ StatsProcessor(bool print, bool frequency)
+ : print_(print),
+ frequency_(frequency)
+ {}
+ virtual ~StatsProcessor() {};
virtual bool process(boost::shared_ptr<apache::thrift::protocol::TProtocol> piprot,
boost::shared_ptr<apache::thrift::protocol::TProtocol> poprot,
@@ -87,145 +88,169 @@
return true;
}
- const std::map<std::string, int64_t>& get_frequency_map() { return frequency_map_; }
+ const std::map<std::string, int64_t>& get_frequency_map() {
+ return frequency_map_;
+ }
protected:
void printAndPassToBuffer(apache::thrift::protocol::TType ftype) {
switch (ftype) {
- case apache::thrift::protocol::T_BOOL: {
- bool boolv;
- piprot_->readBool(boolv);
- if (print_) {
- printf("%d", boolv);
- }
- } break;
- case apache::thrift::protocol::T_BYTE: {
- int8_t bytev;
- piprot_->readByte(bytev);
- if (print_) {
- printf("%d", bytev);
- }
- } break;
- case apache::thrift::protocol::T_I16: {
- int16_t i16;
- piprot_->readI16(i16);
- if (print_) {
- printf("%d", i16);
- }
- } break;
- case apache::thrift::protocol::T_I32: {
- int32_t i32;
- piprot_->readI32(i32);
- if (print_) {
- printf("%d", i32);
- }
- } break;
- case apache::thrift::protocol::T_I64: {
- int64_t i64;
- piprot_->readI64(i64);
- if (print_) {
- printf("%ld", i64);
- }
- } break;
- case apache::thrift::protocol::T_DOUBLE: {
- double dub;
- piprot_->readDouble(dub);
- if (print_) {
- printf("%f", dub);
- }
- } break;
- case apache::thrift::protocol::T_STRING: {
- std::string str;
- piprot_->readString(str);
- if (print_) {
- printf("%s", str.c_str());
- }
- } break;
- case apache::thrift::protocol::T_STRUCT: {
- std::string name;
- int16_t fid;
- apache::thrift::protocol::TType ftype;
- piprot_->readStructBegin(name);
- if (print_) {
- printf("<");
- }
- while (true) {
- piprot_->readFieldBegin(name, ftype, fid);
- if (ftype == apache::thrift::protocol::T_STOP) {
- break;
+ case apache::thrift::protocol::T_BOOL:
+ {
+ bool boolv;
+ piprot_->readBool(boolv);
+ if (print_) {
+ printf("%d", boolv);
+ }
}
- printAndPassToBuffer(ftype);
- if (print_) {
- printf(",");
+ break;
+ case apache::thrift::protocol::T_BYTE:
+ {
+ int8_t bytev;
+ piprot_->readByte(bytev);
+ if (print_) {
+ printf("%d", bytev);
+ }
}
- piprot_->readFieldEnd();
- }
- piprot_->readStructEnd();
- if (print_) {
- printf("\b>");
- }
- } break;
- case apache::thrift::protocol::T_MAP: {
- apache::thrift::protocol::TType keyType;
- apache::thrift::protocol::TType valType;
- uint32_t i, size;
- piprot_->readMapBegin(keyType, valType, size);
- if (print_) {
- printf("{");
- }
- for (i = 0; i < size; i++) {
- printAndPassToBuffer(keyType);
- if (print_) {
- printf("=>");
+ break;
+ case apache::thrift::protocol::T_I16:
+ {
+ int16_t i16;
+ piprot_->readI16(i16);
+ if (print_) {
+ printf("%d", i16);
+ }
}
- printAndPassToBuffer(valType);
- if (print_) {
- printf(",");
+ break;
+ case apache::thrift::protocol::T_I32:
+ {
+ int32_t i32;
+ piprot_->readI32(i32);
+ if (print_) {
+ printf("%d", i32);
+ }
}
- }
- piprot_->readMapEnd();
- if (print_) {
- printf("\b}");
- }
- } break;
- case apache::thrift::protocol::T_SET: {
- apache::thrift::protocol::TType elemType;
- uint32_t i, size;
- piprot_->readSetBegin(elemType, size);
- if (print_) {
- printf("{");
- }
- for (i = 0; i < size; i++) {
- printAndPassToBuffer(elemType);
- if (print_) {
- printf(",");
+ break;
+ case apache::thrift::protocol::T_I64:
+ {
+ int64_t i64;
+ piprot_->readI64(i64);
+ if (print_) {
+ printf("%ld", i64);
+ }
}
- }
- piprot_->readSetEnd();
- if (print_) {
- printf("\b}");
- }
- } break;
- case apache::thrift::protocol::T_LIST: {
- apache::thrift::protocol::TType elemType;
- uint32_t i, size;
- piprot_->readListBegin(elemType, size);
- if (print_) {
- printf("[");
- }
- for (i = 0; i < size; i++) {
- printAndPassToBuffer(elemType);
- if (print_) {
- printf(",");
+ break;
+ case apache::thrift::protocol::T_DOUBLE:
+ {
+ double dub;
+ piprot_->readDouble(dub);
+ if (print_) {
+ printf("%f", dub);
+ }
}
- }
- piprot_->readListEnd();
- if (print_) {
- printf("\b]");
- }
- } break;
- default:
- break;
+ break;
+ case apache::thrift::protocol::T_STRING:
+ {
+ std::string str;
+ piprot_->readString(str);
+ if (print_) {
+ printf("%s", str.c_str());
+ }
+ }
+ break;
+ case apache::thrift::protocol::T_STRUCT:
+ {
+ std::string name;
+ int16_t fid;
+ apache::thrift::protocol::TType ftype;
+ piprot_->readStructBegin(name);
+ if (print_) {
+ printf("<");
+ }
+ while (true) {
+ piprot_->readFieldBegin(name, ftype, fid);
+ if (ftype == apache::thrift::protocol::T_STOP) {
+ break;
+ }
+ printAndPassToBuffer(ftype);
+ if (print_) {
+ printf(",");
+ }
+ piprot_->readFieldEnd();
+ }
+ piprot_->readStructEnd();
+ if (print_) {
+ printf("\b>");
+ }
+ }
+ break;
+ case apache::thrift::protocol::T_MAP:
+ {
+ apache::thrift::protocol::TType keyType;
+ apache::thrift::protocol::TType valType;
+ uint32_t i, size;
+ piprot_->readMapBegin(keyType, valType, size);
+ if (print_) {
+ printf("{");
+ }
+ for (i = 0; i < size; i++) {
+ printAndPassToBuffer(keyType);
+ if (print_) {
+ printf("=>");
+ }
+ printAndPassToBuffer(valType);
+ if (print_) {
+ printf(",");
+ }
+ }
+ piprot_->readMapEnd();
+ if (print_) {
+ printf("\b}");
+ }
+ }
+ break;
+ case apache::thrift::protocol::T_SET:
+ {
+ apache::thrift::protocol::TType elemType;
+ uint32_t i, size;
+ piprot_->readSetBegin(elemType, size);
+ if (print_) {
+ printf("{");
+ }
+ for (i = 0; i < size; i++) {
+ printAndPassToBuffer(elemType);
+ if (print_) {
+ printf(",");
+ }
+ }
+ piprot_->readSetEnd();
+ if (print_) {
+ printf("\b}");
+ }
+ }
+ break;
+ case apache::thrift::protocol::T_LIST:
+ {
+ apache::thrift::protocol::TType elemType;
+ uint32_t i, size;
+ piprot_->readListBegin(elemType, size);
+ if (print_) {
+ printf("[");
+ }
+ for (i = 0; i < size; i++) {
+ printAndPassToBuffer(elemType);
+ if (print_) {
+ printf(",");
+ }
+ }
+ piprot_->readListEnd();
+ if (print_) {
+ printf("\b]");
+ }
+ }
+ break;
+ default:
+ break;
}
}
@@ -235,8 +260,7 @@
bool print_;
bool frequency_;
};
-}
-}
-} // apache::thrift::processor
+
+}}} // apache::thrift::processor
#endif
diff --git a/lib/cpp/src/thrift/processor/TMultiplexedProcessor.h b/lib/cpp/src/thrift/processor/TMultiplexedProcessor.h
index a97f6a9..a352d90 100644
--- a/lib/cpp/src/thrift/processor/TMultiplexedProcessor.h
+++ b/lib/cpp/src/thrift/processor/TMultiplexedProcessor.h
@@ -25,177 +25,194 @@
#include <thrift/TProcessor.h>
#include <boost/tokenizer.hpp>
-namespace apache {
-namespace thrift {
-using boost::shared_ptr;
+namespace apache
+{
+ namespace thrift
+ {
+ using boost::shared_ptr;
-namespace protocol {
+ namespace protocol {
-/**
- * To be able to work with any protocol, we needed
- * to allow them to call readMessageBegin() and get a TMessage in exactly
- * the standard format, without the service name prepended to TMessage.name.
- */
-class StoredMessageProtocol : public TProtocolDecorator {
-public:
- StoredMessageProtocol(shared_ptr<protocol::TProtocol> _protocol,
- const std::string& _name,
- const TMessageType _type,
- const int32_t _seqid)
- : TProtocolDecorator(_protocol), name(_name), type(_type), seqid(_seqid) {}
+ /**
+ * To be able to work with any protocol, we needed
+ * to allow them to call readMessageBegin() and get a TMessage in exactly
+ * the standard format, without the service name prepended to TMessage.name.
+ */
+ class StoredMessageProtocol : public TProtocolDecorator
+ {
+ public:
+ StoredMessageProtocol( shared_ptr<protocol::TProtocol> _protocol,
+ const std::string& _name, const TMessageType _type,
+ const int32_t _seqid) :
+ TProtocolDecorator(_protocol),
+ name(_name),
+ type(_type),
+ seqid(_seqid)
+ {
+ }
- uint32_t readMessageBegin_virt(std::string& _name, TMessageType& _type, int32_t& _seqid) {
+ uint32_t readMessageBegin_virt(std::string& _name, TMessageType& _type, int32_t& _seqid)
+ {
- _name = name;
- _type = type;
- _seqid = seqid;
+ _name = name;
+ _type = type;
+ _seqid = seqid;
- return 0; // (Normal TProtocol read functions return number of bytes read)
- }
+ return 0; // (Normal TProtocol read functions return number of bytes read)
+ }
- std::string name;
- TMessageType type;
- int32_t seqid;
-};
-} // namespace protocol
+ std::string name;
+ TMessageType type;
+ int32_t seqid;
+ };
+ } //namespace protocol
-/**
- * <code>TMultiplexedProcessor</code> is a <code>TProcessor</code> allowing
- * a single <code>TServer</code> to provide multiple services.
- *
- * <p>To do so, you instantiate the processor and then register additional
- * processors with it, as shown in the following example:</p>
- *
- * <blockquote><code>
- * shared_ptr<TMultiplexedProcessor> processor(new TMultiplexedProcessor());
- *
- * processor->registerProcessor(
- * "Calculator",
- * shared_ptr<TProcessor>( new CalculatorProcessor(
- * shared_ptr<CalculatorHandler>( new CalculatorHandler()))));
- *
- * processor->registerProcessor(
- * "WeatherReport",
- * shared_ptr<TProcessor>( new WeatherReportProcessor(
- * shared_ptr<WeatherReportHandler>( new WeatherReportHandler()))));
- *
- * shared_ptr<TServerTransport> transport(new TServerSocket(9090));
- * TSimpleServer server(processor, transport);
- *
- * server.serve();
- * </code></blockquote>
- */
-class TMultiplexedProcessor : public TProcessor {
-public:
- typedef std::map<std::string, shared_ptr<TProcessor> > services_t;
+ /**
+ * <code>TMultiplexedProcessor</code> is a <code>TProcessor</code> allowing
+ * a single <code>TServer</code> to provide multiple services.
+ *
+ * <p>To do so, you instantiate the processor and then register additional
+ * processors with it, as shown in the following example:</p>
+ *
+ * <blockquote><code>
+ * shared_ptr<TMultiplexedProcessor> processor(new TMultiplexedProcessor());
+ *
+ * processor->registerProcessor(
+ * "Calculator",
+ * shared_ptr<TProcessor>( new CalculatorProcessor(
+ * shared_ptr<CalculatorHandler>( new CalculatorHandler()))));
+ *
+ * processor->registerProcessor(
+ * "WeatherReport",
+ * shared_ptr<TProcessor>( new WeatherReportProcessor(
+ * shared_ptr<WeatherReportHandler>( new WeatherReportHandler()))));
+ *
+ * shared_ptr<TServerTransport> transport(new TServerSocket(9090));
+ * TSimpleServer server(processor, transport);
+ *
+ * server.serve();
+ * </code></blockquote>
+ */
+ class TMultiplexedProcessor : public TProcessor
+ {
+ public:
+ typedef std::map< std::string, shared_ptr<TProcessor> > services_t;
- /**
- * 'Register' a service with this <code>TMultiplexedProcessor</code>. This
- * allows us to broker requests to individual services by using the service
- * name to select them at request time.
- *
- * \param [in] serviceName Name of a service, has to be identical to the name
- * declared in the Thrift IDL, e.g. "WeatherReport".
- * \param [in] processor Implementation of a service, ususally referred to
- * as "handlers", e.g. WeatherReportHandler,
- * implementing WeatherReportIf interface.
- */
- void registerProcessor(const std::string& serviceName, shared_ptr<TProcessor> processor) {
- services[serviceName] = processor;
- }
+ /**
+ * 'Register' a service with this <code>TMultiplexedProcessor</code>. This
+ * allows us to broker requests to individual services by using the service
+ * name to select them at request time.
+ *
+ * \param [in] serviceName Name of a service, has to be identical to the name
+ * declared in the Thrift IDL, e.g. "WeatherReport".
+ * \param [in] processor Implementation of a service, ususally referred to
+ * as "handlers", e.g. WeatherReportHandler,
+ * implementing WeatherReportIf interface.
+ */
+ void registerProcessor( const std::string & serviceName,
+ shared_ptr<TProcessor> processor )
+ {
+ services[serviceName] = processor;
+ }
- /**
- * This implementation of <code>process</code> performs the following steps:
- *
- * <ol>
- * <li>Read the beginning of the message.</li>
- * <li>Extract the service name from the message.</li>
- * <li>Using the service name to locate the appropriate processor.</li>
- * <li>Dispatch to the processor, with a decorated instance of TProtocol
- * that allows readMessageBegin() to return the original TMessage.</li>
- * </ol>
- *
- * \throws TException If the message type is not T_CALL or T_ONEWAY, if
- * the service name was not found in the message, or if the service
- * name was not found in the service map.
- */
- bool process(shared_ptr<protocol::TProtocol> in,
- shared_ptr<protocol::TProtocol> out,
- void* connectionContext) {
- std::string name;
- protocol::TMessageType type;
- int32_t seqid;
+ /**
+ * This implementation of <code>process</code> performs the following steps:
+ *
+ * <ol>
+ * <li>Read the beginning of the message.</li>
+ * <li>Extract the service name from the message.</li>
+ * <li>Using the service name to locate the appropriate processor.</li>
+ * <li>Dispatch to the processor, with a decorated instance of TProtocol
+ * that allows readMessageBegin() to return the original TMessage.</li>
+ * </ol>
+ *
+ * \throws TException If the message type is not T_CALL or T_ONEWAY, if
+ * the service name was not found in the message, or if the service
+ * name was not found in the service map.
+ */
+ bool process( shared_ptr<protocol::TProtocol> in,
+ shared_ptr<protocol::TProtocol> out,
+ void *connectionContext)
+ {
+ std::string name;
+ protocol::TMessageType type;
+ int32_t seqid;
- // Use the actual underlying protocol (e.g. TBinaryProtocol) to read the
- // message header. This pulls the message "off the wire", which we'll
- // deal with at the end of this method.
- in->readMessageBegin(name, type, seqid);
+ // Use the actual underlying protocol (e.g. TBinaryProtocol) to read the
+ // message header. This pulls the message "off the wire", which we'll
+ // deal with at the end of this method.
+ in->readMessageBegin(name, type, seqid);
- if (type != protocol::T_CALL && type != protocol::T_ONEWAY) {
- // Unexpected message type.
- in->skip(::apache::thrift::protocol::T_STRUCT);
- in->readMessageEnd();
- in->getTransport()->readEnd();
- const std::string msg("TMultiplexedProcessor: Unexpected message type");
- ::apache::thrift::TApplicationException
- x(::apache::thrift::TApplicationException::PROTOCOL_ERROR, msg);
- out->writeMessageBegin(name, ::apache::thrift::protocol::T_EXCEPTION, seqid);
- x.write(out.get());
- out->writeMessageEnd();
- out->getTransport()->writeEnd();
- out->getTransport()->flush();
- throw TException(msg);
+ if( type != protocol::T_CALL && type != protocol::T_ONEWAY ) {
+ // Unexpected message type.
+ in->skip(::apache::thrift::protocol::T_STRUCT);
+ in->readMessageEnd();
+ in->getTransport()->readEnd();
+ const std::string msg("TMultiplexedProcessor: Unexpected message type");
+ ::apache::thrift::TApplicationException x(
+ ::apache::thrift::TApplicationException::PROTOCOL_ERROR,
+ msg);
+ out->writeMessageBegin(name, ::apache::thrift::protocol::T_EXCEPTION, seqid);
+ x.write(out.get());
+ out->writeMessageEnd();
+ out->getTransport()->writeEnd();
+ out->getTransport()->flush();
+ throw TException(msg);
+ }
+
+ // Extract the service name
+
+ boost::tokenizer<boost::char_separator<char> > tok( name, boost::char_separator<char>(":") );
+
+ std::vector<std::string> tokens;
+ std::copy( tok.begin(), tok.end(), std::back_inserter(tokens) );
+
+ // A valid message should consist of two tokens: the service
+ // name and the name of the method to call.
+ if( tokens.size() == 2 )
+ {
+ // Search for a processor associated with this service name.
+ services_t::iterator it = services.find(tokens[0]);
+
+ if( it != services.end() )
+ {
+ shared_ptr<TProcessor> processor = it->second;
+ // Let the processor registered for this service name
+ // process the message.
+ return processor->process(
+ shared_ptr<protocol::TProtocol>(
+ new protocol::StoredMessageProtocol( in, tokens[1], type, seqid ) ),
+ out, connectionContext );
+ }
+ else
+ {
+ // Unknown service.
+ in->skip(::apache::thrift::protocol::T_STRUCT);
+ in->readMessageEnd();
+ in->getTransport()->readEnd();
+
+ std::string msg("TMultiplexedProcessor: Unknown service: ");
+ msg += tokens[0];
+ ::apache::thrift::TApplicationException x(
+ ::apache::thrift::TApplicationException::PROTOCOL_ERROR,
+ msg);
+ out->writeMessageBegin(name, ::apache::thrift::protocol::T_EXCEPTION, seqid);
+ x.write(out.get());
+ out->writeMessageEnd();
+ out->getTransport()->writeEnd();
+ out->getTransport()->flush();
+ msg += ". Did you forget to call registerProcessor()?";
+ throw TException(msg);
+ }
+ }
+ return false;
+ }
+
+ private:
+ /** Map of service processor objects, indexed by service names. */
+ services_t services;
+ };
}
-
- // Extract the service name
-
- boost::tokenizer<boost::char_separator<char> > tok(name, boost::char_separator<char>(":"));
-
- std::vector<std::string> tokens;
- std::copy(tok.begin(), tok.end(), std::back_inserter(tokens));
-
- // A valid message should consist of two tokens: the service
- // name and the name of the method to call.
- if (tokens.size() == 2) {
- // Search for a processor associated with this service name.
- services_t::iterator it = services.find(tokens[0]);
-
- if (it != services.end()) {
- shared_ptr<TProcessor> processor = it->second;
- // Let the processor registered for this service name
- // process the message.
- return processor
- ->process(shared_ptr<protocol::TProtocol>(
- new protocol::StoredMessageProtocol(in, tokens[1], type, seqid)),
- out,
- connectionContext);
- } else {
- // Unknown service.
- in->skip(::apache::thrift::protocol::T_STRUCT);
- in->readMessageEnd();
- in->getTransport()->readEnd();
-
- std::string msg("TMultiplexedProcessor: Unknown service: ");
- msg += tokens[0];
- ::apache::thrift::TApplicationException
- x(::apache::thrift::TApplicationException::PROTOCOL_ERROR, msg);
- out->writeMessageBegin(name, ::apache::thrift::protocol::T_EXCEPTION, seqid);
- x.write(out.get());
- out->writeMessageEnd();
- out->getTransport()->writeEnd();
- out->getTransport()->flush();
- msg += ". Did you forget to call registerProcessor()?";
- throw TException(msg);
- }
- }
- return false;
- }
-
-private:
- /** Map of service processor objects, indexed by service names. */
- services_t services;
-};
-}
}
#endif // THRIFT_TMULTIPLEXEDPROCESSOR_H_
diff --git a/lib/cpp/src/thrift/protocol/TBase64Utils.cpp b/lib/cpp/src/thrift/protocol/TBase64Utils.cpp
index beb76eb..cd343ed 100644
--- a/lib/cpp/src/thrift/protocol/TBase64Utils.cpp
+++ b/lib/cpp/src/thrift/protocol/TBase64Utils.cpp
@@ -23,14 +23,13 @@
using std::string;
-namespace apache {
-namespace thrift {
-namespace protocol {
+namespace apache { namespace thrift { namespace protocol {
-static const uint8_t* kBase64EncodeTable
- = (const uint8_t*)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-void base64_encode(const uint8_t* in, uint32_t len, uint8_t* buf) {
+static const uint8_t *kBase64EncodeTable = (const uint8_t *)
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+void base64_encode(const uint8_t *in, uint32_t len, uint8_t *buf) {
buf[0] = kBase64EncodeTable[(in[0] >> 2) & 0x3f];
if (len == 3) {
buf[1] = kBase64EncodeTable[((in[0] << 4) & 0x30) | ((in[1] >> 4) & 0x0f)];
@@ -39,279 +38,42 @@
} else if (len == 2) {
buf[1] = kBase64EncodeTable[((in[0] << 4) & 0x30) | ((in[1] >> 4) & 0x0f)];
buf[2] = kBase64EncodeTable[(in[1] << 2) & 0x3c];
- } else { // len == 1
+ } else { // len == 1
buf[1] = kBase64EncodeTable[(in[0] << 4) & 0x30];
}
}
-static const uint8_t kBase64DecodeTable[256] = {
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0x3e,
- 0xff,
- 0xff,
- 0xff,
- 0x3f,
- 0x34,
- 0x35,
- 0x36,
- 0x37,
- 0x38,
- 0x39,
- 0x3a,
- 0x3b,
- 0x3c,
- 0x3d,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0x00,
- 0x01,
- 0x02,
- 0x03,
- 0x04,
- 0x05,
- 0x06,
- 0x07,
- 0x08,
- 0x09,
- 0x0a,
- 0x0b,
- 0x0c,
- 0x0d,
- 0x0e,
- 0x0f,
- 0x10,
- 0x11,
- 0x12,
- 0x13,
- 0x14,
- 0x15,
- 0x16,
- 0x17,
- 0x18,
- 0x19,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0x1a,
- 0x1b,
- 0x1c,
- 0x1d,
- 0x1e,
- 0x1f,
- 0x20,
- 0x21,
- 0x22,
- 0x23,
- 0x24,
- 0x25,
- 0x26,
- 0x27,
- 0x28,
- 0x29,
- 0x2a,
- 0x2b,
- 0x2c,
- 0x2d,
- 0x2e,
- 0x2f,
- 0x30,
- 0x31,
- 0x32,
- 0x33,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
- 0xff,
+static const uint8_t kBase64DecodeTable[256] ={
+0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
+0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
+0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x3e,0xff,0xff,0xff,0x3f,
+0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x3b,0x3c,0x3d,0xff,0xff,0xff,0xff,0xff,0xff,
+0xff,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,
+0x0f,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0xff,0xff,0xff,0xff,0xff,
+0xff,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f,0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,
+0x29,0x2a,0x2b,0x2c,0x2d,0x2e,0x2f,0x30,0x31,0x32,0x33,0xff,0xff,0xff,0xff,0xff,
+0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
+0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
+0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
+0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
+0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
+0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
+0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
+0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
};
-void base64_decode(uint8_t* buf, uint32_t len) {
- buf[0] = (kBase64DecodeTable[buf[0]] << 2) | (kBase64DecodeTable[buf[1]] >> 4);
+void base64_decode(uint8_t *buf, uint32_t len) {
+ buf[0] = (kBase64DecodeTable[buf[0]] << 2) |
+ (kBase64DecodeTable[buf[1]] >> 4);
if (len > 2) {
- buf[1] = ((kBase64DecodeTable[buf[1]] << 4) & 0xf0) | (kBase64DecodeTable[buf[2]] >> 2);
+ buf[1] = ((kBase64DecodeTable[buf[1]] << 4) & 0xf0) |
+ (kBase64DecodeTable[buf[2]] >> 2);
if (len > 3) {
- buf[2] = ((kBase64DecodeTable[buf[2]] << 6) & 0xc0) | (kBase64DecodeTable[buf[3]]);
+ buf[2] = ((kBase64DecodeTable[buf[2]] << 6) & 0xc0) |
+ (kBase64DecodeTable[buf[3]]);
}
}
}
-}
-}
-} // apache::thrift::protocol
+
+
+}}} // apache::thrift::protocol
diff --git a/lib/cpp/src/thrift/protocol/TBase64Utils.h b/lib/cpp/src/thrift/protocol/TBase64Utils.h
index 1ea6744..3def733 100644
--- a/lib/cpp/src/thrift/protocol/TBase64Utils.h
+++ b/lib/cpp/src/thrift/protocol/TBase64Utils.h
@@ -23,23 +23,20 @@
#include <stdint.h>
#include <string>
-namespace apache {
-namespace thrift {
-namespace protocol {
+namespace apache { namespace thrift { namespace protocol {
// in must be at least len bytes
// len must be 1, 2, or 3
// buf must be a buffer of at least 4 bytes and may not overlap in
// the data is not padded with '='; the caller can do this if desired
-void base64_encode(const uint8_t* in, uint32_t len, uint8_t* buf);
+void base64_encode(const uint8_t *in, uint32_t len, uint8_t *buf);
// buf must be a buffer of at least 4 bytes and contain base64 encoded values
// buf will be changed to contain output bytes
// len is number of bytes to consume from input (must be 2, 3, or 4)
// no '=' padding should be included in the input
-void base64_decode(uint8_t* buf, uint32_t len);
-}
-}
-} // apache::thrift::protocol
+void base64_decode(uint8_t *buf, uint32_t len);
+
+}}} // apache::thrift::protocol
#endif // #define _THRIFT_PROTOCOL_TBASE64UTILS_H_
diff --git a/lib/cpp/src/thrift/protocol/TBinaryProtocol.h b/lib/cpp/src/thrift/protocol/TBinaryProtocol.h
index 88b91e5..a5b19e5 100644
--- a/lib/cpp/src/thrift/protocol/TBinaryProtocol.h
+++ b/lib/cpp/src/thrift/protocol/TBinaryProtocol.h
@@ -25,9 +25,7 @@
#include <boost/shared_ptr.hpp>
-namespace apache {
-namespace thrift {
-namespace protocol {
+namespace apache { namespace thrift { namespace protocol {
/**
* The default binary protocol for thrift. Writes all data in a very basic
@@ -35,36 +33,37 @@
*
*/
template <class Transport_>
-class TBinaryProtocolT : public TVirtualProtocol<TBinaryProtocolT<Transport_> > {
-protected:
+class TBinaryProtocolT
+ : public TVirtualProtocol< TBinaryProtocolT<Transport_> > {
+ protected:
static const int32_t VERSION_MASK = ((int32_t)0xffff0000);
static const int32_t VERSION_1 = ((int32_t)0x80010000);
// VERSION_2 (0x80020000) is taken by TDenseProtocol.
-public:
- TBinaryProtocolT(boost::shared_ptr<Transport_> trans)
- : TVirtualProtocol<TBinaryProtocolT<Transport_> >(trans),
- trans_(trans.get()),
- string_limit_(0),
- container_limit_(0),
- strict_read_(false),
- strict_write_(true),
- string_buf_(NULL),
- string_buf_size_(0) {}
+ public:
+ TBinaryProtocolT(boost::shared_ptr<Transport_> trans) :
+ TVirtualProtocol< TBinaryProtocolT<Transport_> >(trans),
+ trans_(trans.get()),
+ string_limit_(0),
+ container_limit_(0),
+ strict_read_(false),
+ strict_write_(true),
+ string_buf_(NULL),
+ string_buf_size_(0) {}
TBinaryProtocolT(boost::shared_ptr<Transport_> trans,
int32_t string_limit,
int32_t container_limit,
bool strict_read,
- bool strict_write)
- : TVirtualProtocol<TBinaryProtocolT<Transport_> >(trans),
- trans_(trans.get()),
- string_limit_(string_limit),
- container_limit_(container_limit),
- strict_read_(strict_read),
- strict_write_(strict_write),
- string_buf_(NULL),
- string_buf_size_(0) {}
+ bool strict_write) :
+ TVirtualProtocol< TBinaryProtocolT<Transport_> >(trans),
+ trans_(trans.get()),
+ string_limit_(string_limit),
+ container_limit_(container_limit),
+ strict_read_(strict_read),
+ strict_write_(strict_write),
+ string_buf_(NULL),
+ string_buf_size_(0) {}
~TBinaryProtocolT() {
if (string_buf_ != NULL) {
@@ -73,9 +72,13 @@
}
}
- void setStringSizeLimit(int32_t string_limit) { string_limit_ = string_limit; }
+ void setStringSizeLimit(int32_t string_limit) {
+ string_limit_ = string_limit;
+ }
- void setContainerSizeLimit(int32_t container_limit) { container_limit_ = container_limit; }
+ void setContainerSizeLimit(int32_t container_limit) {
+ container_limit_ = container_limit;
+ }
void setStrict(bool strict_read, bool strict_write) {
strict_read_ = strict_read;
@@ -92,17 +95,22 @@
/*ol*/ uint32_t writeMessageEnd();
+
inline uint32_t writeStructBegin(const char* name);
inline uint32_t writeStructEnd();
- inline uint32_t writeFieldBegin(const char* name, const TType fieldType, const int16_t fieldId);
+ inline uint32_t writeFieldBegin(const char* name,
+ const TType fieldType,
+ const int16_t fieldId);
inline uint32_t writeFieldEnd();
inline uint32_t writeFieldStop();
- inline uint32_t writeMapBegin(const TType keyType, const TType valType, const uint32_t size);
+ inline uint32_t writeMapBegin(const TType keyType,
+ const TType valType,
+ const uint32_t size);
inline uint32_t writeMapEnd();
@@ -135,7 +143,10 @@
* Reading functions
*/
- /*ol*/ uint32_t readMessageBegin(std::string& name, TMessageType& messageType, int32_t& seqid);
+
+ /*ol*/ uint32_t readMessageBegin(std::string& name,
+ TMessageType& messageType,
+ int32_t& seqid);
/*ol*/ uint32_t readMessageEnd();
@@ -143,11 +154,15 @@
inline uint32_t readStructEnd();
- inline uint32_t readFieldBegin(std::string& name, TType& fieldType, int16_t& fieldId);
+ inline uint32_t readFieldBegin(std::string& name,
+ TType& fieldType,
+ int16_t& fieldId);
inline uint32_t readFieldEnd();
- inline uint32_t readMapBegin(TType& keyType, TType& valType, uint32_t& size);
+ inline uint32_t readMapBegin(TType& keyType,
+ TType& valType,
+ uint32_t& size);
inline uint32_t readMapEnd();
@@ -161,7 +176,7 @@
inline uint32_t readBool(bool& value);
// Provide the default readBool() implementation for std::vector<bool>
- using TVirtualProtocol<TBinaryProtocolT<Transport_> >::readBool;
+ using TVirtualProtocol< TBinaryProtocolT<Transport_> >::readBool;
inline uint32_t readByte(int8_t& byte);
@@ -173,13 +188,13 @@
inline uint32_t readDouble(double& dub);
- template <typename StrType>
+ template<typename StrType>
inline uint32_t readString(StrType& str);
inline uint32_t readBinary(std::string& str);
-protected:
- template <typename StrType>
+ protected:
+ template<typename StrType>
uint32_t readStringBody(StrType& str, int32_t sz);
Transport_* trans_;
@@ -195,6 +210,7 @@
// avoid memory churn allocating memory on every string read
uint8_t* string_buf_;
int32_t string_buf_size_;
+
};
typedef TBinaryProtocolT<TTransport> TBinaryProtocol;
@@ -204,24 +220,29 @@
*/
template <class Transport_>
class TBinaryProtocolFactoryT : public TProtocolFactory {
-public:
- TBinaryProtocolFactoryT()
- : string_limit_(0), container_limit_(0), strict_read_(false), strict_write_(true) {}
+ public:
+ TBinaryProtocolFactoryT() :
+ string_limit_(0),
+ container_limit_(0),
+ strict_read_(false),
+ strict_write_(true) {}
- TBinaryProtocolFactoryT(int32_t string_limit,
- int32_t container_limit,
- bool strict_read,
- bool strict_write)
- : string_limit_(string_limit),
- container_limit_(container_limit),
- strict_read_(strict_read),
- strict_write_(strict_write) {}
+ TBinaryProtocolFactoryT(int32_t string_limit, int32_t container_limit,
+ bool strict_read, bool strict_write) :
+ string_limit_(string_limit),
+ container_limit_(container_limit),
+ strict_read_(strict_read),
+ strict_write_(strict_write) {}
virtual ~TBinaryProtocolFactoryT() {}
- void setStringSizeLimit(int32_t string_limit) { string_limit_ = string_limit; }
+ void setStringSizeLimit(int32_t string_limit) {
+ string_limit_ = string_limit;
+ }
- void setContainerSizeLimit(int32_t container_limit) { container_limit_ = container_limit; }
+ void setContainerSizeLimit(int32_t container_limit) {
+ container_limit_ = container_limit;
+ }
void setStrict(bool strict_read, bool strict_write) {
strict_read_ = strict_read;
@@ -229,36 +250,32 @@
}
boost::shared_ptr<TProtocol> getProtocol(boost::shared_ptr<TTransport> trans) {
- boost::shared_ptr<Transport_> specific_trans = boost::dynamic_pointer_cast<Transport_>(trans);
+ boost::shared_ptr<Transport_> specific_trans =
+ boost::dynamic_pointer_cast<Transport_>(trans);
TProtocol* prot;
if (specific_trans) {
- prot = new TBinaryProtocolT<Transport_>(specific_trans,
- string_limit_,
- container_limit_,
- strict_read_,
+ prot = new TBinaryProtocolT<Transport_>(specific_trans, string_limit_,
+ container_limit_, strict_read_,
strict_write_);
} else {
- prot = new TBinaryProtocol(trans,
- string_limit_,
- container_limit_,
- strict_read_,
- strict_write_);
+ prot = new TBinaryProtocol(trans, string_limit_, container_limit_,
+ strict_read_, strict_write_);
}
return boost::shared_ptr<TProtocol>(prot);
}
-private:
+ private:
int32_t string_limit_;
int32_t container_limit_;
bool strict_read_;
bool strict_write_;
+
};
typedef TBinaryProtocolFactoryT<TTransport> TBinaryProtocolFactory;
-}
-}
-} // apache::thrift::protocol
+
+}}} // apache::thrift::protocol
#include <thrift/protocol/TBinaryProtocol.tcc>
diff --git a/lib/cpp/src/thrift/protocol/TBinaryProtocol.tcc b/lib/cpp/src/thrift/protocol/TBinaryProtocol.tcc
index 0d72d8a..40226a5 100644
--- a/lib/cpp/src/thrift/protocol/TBinaryProtocol.tcc
+++ b/lib/cpp/src/thrift/protocol/TBinaryProtocol.tcc
@@ -24,9 +24,8 @@
#include <limits>
-namespace apache {
-namespace thrift {
-namespace protocol {
+
+namespace apache { namespace thrift { namespace protocol {
template <class Transport_>
uint32_t TBinaryProtocolT<Transport_>::writeMessageBegin(const std::string& name,
@@ -55,7 +54,7 @@
template <class Transport_>
uint32_t TBinaryProtocolT<Transport_>::writeStructBegin(const char* name) {
- (void)name;
+ (void) name;
return 0;
}
@@ -68,7 +67,7 @@
uint32_t TBinaryProtocolT<Transport_>::writeFieldBegin(const char* name,
const TType fieldType,
const int16_t fieldId) {
- (void)name;
+ (void) name;
uint32_t wsize = 0;
wsize += writeByte((int8_t)fieldType);
wsize += writeI16(fieldId);
@@ -82,7 +81,8 @@
template <class Transport_>
uint32_t TBinaryProtocolT<Transport_>::writeFieldStop() {
- return writeByte((int8_t)T_STOP);
+ return
+ writeByte((int8_t)T_STOP);
}
template <class Transport_>
@@ -102,9 +102,10 @@
}
template <class Transport_>
-uint32_t TBinaryProtocolT<Transport_>::writeListBegin(const TType elemType, const uint32_t size) {
+uint32_t TBinaryProtocolT<Transport_>::writeListBegin(const TType elemType,
+ const uint32_t size) {
uint32_t wsize = 0;
- wsize += writeByte((int8_t)elemType);
+ wsize += writeByte((int8_t) elemType);
wsize += writeI32((int32_t)size);
return wsize;
}
@@ -115,7 +116,8 @@
}
template <class Transport_>
-uint32_t TBinaryProtocolT<Transport_>::writeSetBegin(const TType elemType, const uint32_t size) {
+uint32_t TBinaryProtocolT<Transport_>::writeSetBegin(const TType elemType,
+ const uint32_t size) {
uint32_t wsize = 0;
wsize += writeByte((int8_t)elemType);
wsize += writeI32((int32_t)size);
@@ -129,7 +131,7 @@
template <class Transport_>
uint32_t TBinaryProtocolT<Transport_>::writeBool(const bool value) {
- uint8_t tmp = value ? 1 : 0;
+ uint8_t tmp = value ? 1 : 0;
this->trans_->write(&tmp, 1);
return 1;
}
@@ -172,10 +174,11 @@
return 8;
}
+
template <class Transport_>
-template <typename StrType>
+template<typename StrType>
uint32_t TBinaryProtocolT<Transport_>::writeString(const StrType& str) {
- if (str.size() > static_cast<size_t>((std::numeric_limits<int32_t>::max)()))
+ if(str.size() > static_cast<size_t>((std::numeric_limits<int32_t>::max)()))
throw TProtocolException(TProtocolException::SIZE_LIMIT);
uint32_t size = static_cast<uint32_t>(str.size());
uint32_t result = writeI32((int32_t)size);
@@ -213,8 +216,7 @@
result += readI32(seqid);
} else {
if (this->strict_read_) {
- throw TProtocolException(TProtocolException::BAD_VERSION,
- "No version identifier... old protocol client in strict mode?");
+ throw TProtocolException(TProtocolException::BAD_VERSION, "No version identifier... old protocol client in strict mode?");
} else {
// Handle pre-versioned input
int8_t type;
@@ -247,7 +249,7 @@
uint32_t TBinaryProtocolT<Transport_>::readFieldBegin(std::string& name,
TType& fieldType,
int16_t& fieldId) {
- (void)name;
+ (void) name;
uint32_t result = 0;
int8_t type;
result += readByte(type);
@@ -292,7 +294,8 @@
}
template <class Transport_>
-uint32_t TBinaryProtocolT<Transport_>::readListBegin(TType& elemType, uint32_t& size) {
+uint32_t TBinaryProtocolT<Transport_>::readListBegin(TType& elemType,
+ uint32_t& size) {
int8_t e;
uint32_t result = 0;
int32_t sizei;
@@ -314,7 +317,8 @@
}
template <class Transport_>
-uint32_t TBinaryProtocolT<Transport_>::readSetBegin(TType& elemType, uint32_t& size) {
+uint32_t TBinaryProtocolT<Transport_>::readSetBegin(TType& elemType,
+ uint32_t& size) {
int8_t e;
uint32_t result = 0;
int32_t sizei;
@@ -400,7 +404,7 @@
}
template <class Transport_>
-template <typename StrType>
+template<typename StrType>
uint32_t TBinaryProtocolT<Transport_>::readString(StrType& str) {
uint32_t result;
int32_t size;
@@ -414,8 +418,9 @@
}
template <class Transport_>
-template <typename StrType>
-uint32_t TBinaryProtocolT<Transport_>::readStringBody(StrType& str, int32_t size) {
+template<typename StrType>
+uint32_t TBinaryProtocolT<Transport_>::readStringBody(StrType& str,
+ int32_t size) {
uint32_t result = 0;
// Catch error cases
@@ -442,11 +447,10 @@
}
str.resize(size);
- this->trans_->readAll(reinterpret_cast<uint8_t*>(&str[0]), size);
+ this->trans_->readAll(reinterpret_cast<uint8_t *>(&str[0]), size);
return (uint32_t)size;
}
-}
-}
-} // apache::thrift::protocol
+
+}}} // apache::thrift::protocol
#endif // #ifndef _THRIFT_PROTOCOL_TBINARYPROTOCOL_TCC_
diff --git a/lib/cpp/src/thrift/protocol/TCompactProtocol.h b/lib/cpp/src/thrift/protocol/TCompactProtocol.h
index 5b7ade2..ce60b45 100644
--- a/lib/cpp/src/thrift/protocol/TCompactProtocol.h
+++ b/lib/cpp/src/thrift/protocol/TCompactProtocol.h
@@ -25,22 +25,21 @@
#include <stack>
#include <boost/shared_ptr.hpp>
-namespace apache {
-namespace thrift {
-namespace protocol {
+namespace apache { namespace thrift { namespace protocol {
/**
* C++ Implementation of the Compact Protocol as described in THRIFT-110
*/
template <class Transport_>
-class TCompactProtocolT : public TVirtualProtocol<TCompactProtocolT<Transport_> > {
+class TCompactProtocolT
+ : public TVirtualProtocol< TCompactProtocolT<Transport_> > {
-protected:
- static const int8_t PROTOCOL_ID = (int8_t)0x82u;
- static const int8_t VERSION_N = 1;
- static const int8_t VERSION_MASK = 0x1f; // 0001 1111
- static const int8_t TYPE_MASK = (int8_t)0xE0u; // 1110 0000
- static const int8_t TYPE_BITS = 0x07; // 0000 0111
+ protected:
+ static const int8_t PROTOCOL_ID = (int8_t)0x82u;
+ static const int8_t VERSION_N = 1;
+ static const int8_t VERSION_MASK = 0x1f; // 0001 1111
+ static const int8_t TYPE_MASK = (int8_t)0xE0u; // 1110 0000
+ static const int8_t TYPE_BITS = 0x07; // 0000 0111
static const int32_t TYPE_SHIFT_AMOUNT = 5;
Transport_* trans_;
@@ -72,34 +71,37 @@
std::stack<int16_t> lastField_;
int16_t lastFieldId_;
-public:
- TCompactProtocolT(boost::shared_ptr<Transport_> trans)
- : TVirtualProtocol<TCompactProtocolT<Transport_> >(trans),
- trans_(trans.get()),
- lastFieldId_(0),
- string_limit_(0),
- string_buf_(NULL),
- string_buf_size_(0),
- container_limit_(0) {
+ public:
+ TCompactProtocolT(boost::shared_ptr<Transport_> trans) :
+ TVirtualProtocol< TCompactProtocolT<Transport_> >(trans),
+ trans_(trans.get()),
+ lastFieldId_(0),
+ string_limit_(0),
+ string_buf_(NULL),
+ string_buf_size_(0),
+ container_limit_(0) {
booleanField_.name = NULL;
boolValue_.hasBoolValue = false;
}
TCompactProtocolT(boost::shared_ptr<Transport_> trans,
int32_t string_limit,
- int32_t container_limit)
- : TVirtualProtocol<TCompactProtocolT<Transport_> >(trans),
- trans_(trans.get()),
- lastFieldId_(0),
- string_limit_(string_limit),
- string_buf_(NULL),
- string_buf_size_(0),
- container_limit_(container_limit) {
+ int32_t container_limit) :
+ TVirtualProtocol< TCompactProtocolT<Transport_> >(trans),
+ trans_(trans.get()),
+ lastFieldId_(0),
+ string_limit_(string_limit),
+ string_buf_(NULL),
+ string_buf_size_(0),
+ container_limit_(container_limit) {
booleanField_.name = NULL;
boolValue_.hasBoolValue = false;
}
- ~TCompactProtocolT() { free(string_buf_); }
+ ~TCompactProtocolT() {
+ free(string_buf_);
+ }
+
/**
* Writing functions
@@ -113,15 +115,21 @@
uint32_t writeStructEnd();
- uint32_t writeFieldBegin(const char* name, const TType fieldType, const int16_t fieldId);
+ uint32_t writeFieldBegin(const char* name,
+ const TType fieldType,
+ const int16_t fieldId);
uint32_t writeFieldStop();
- uint32_t writeListBegin(const TType elemType, const uint32_t size);
+ uint32_t writeListBegin(const TType elemType,
+ const uint32_t size);
- uint32_t writeSetBegin(const TType elemType, const uint32_t size);
+ uint32_t writeSetBegin(const TType elemType,
+ const uint32_t size);
- virtual uint32_t writeMapBegin(const TType keyType, const TType valType, const uint32_t size);
+ virtual uint32_t writeMapBegin(const TType keyType,
+ const TType valType,
+ const uint32_t size);
uint32_t writeBool(const bool value);
@@ -149,7 +157,7 @@
uint32_t writeSetEnd() { return 0; }
uint32_t writeFieldEnd() { return 0; }
-protected:
+ protected:
int32_t writeFieldBeginInternal(const char* name,
const TType fieldType,
const int16_t fieldId,
@@ -161,24 +169,32 @@
uint32_t i32ToZigzag(const int32_t n);
inline int8_t getCompactType(const TType ttype);
-public:
- uint32_t readMessageBegin(std::string& name, TMessageType& messageType, int32_t& seqid);
+ public:
+ uint32_t readMessageBegin(std::string& name,
+ TMessageType& messageType,
+ int32_t& seqid);
uint32_t readStructBegin(std::string& name);
uint32_t readStructEnd();
- uint32_t readFieldBegin(std::string& name, TType& fieldType, int16_t& fieldId);
+ uint32_t readFieldBegin(std::string& name,
+ TType& fieldType,
+ int16_t& fieldId);
- uint32_t readMapBegin(TType& keyType, TType& valType, uint32_t& size);
+ uint32_t readMapBegin(TType& keyType,
+ TType& valType,
+ uint32_t& size);
- uint32_t readListBegin(TType& elemType, uint32_t& size);
+ uint32_t readListBegin(TType& elemType,
+ uint32_t& size);
- uint32_t readSetBegin(TType& elemType, uint32_t& size);
+ uint32_t readSetBegin(TType& elemType,
+ uint32_t& size);
uint32_t readBool(bool& value);
// Provide the default readBool() implementation for std::vector<bool>
- using TVirtualProtocol<TCompactProtocolT<Transport_> >::readBool;
+ using TVirtualProtocol< TCompactProtocolT<Transport_> >::readBool;
uint32_t readByte(int8_t& byte);
@@ -204,7 +220,7 @@
uint32_t readListEnd() { return 0; }
uint32_t readSetEnd() { return 0; }
-protected:
+ protected:
uint32_t readVarint32(int32_t& i32);
uint32_t readVarint64(int64_t& i64);
int32_t zigzagToI32(uint32_t n);
@@ -226,23 +242,32 @@
*/
template <class Transport_>
class TCompactProtocolFactoryT : public TProtocolFactory {
-public:
- TCompactProtocolFactoryT() : string_limit_(0), container_limit_(0) {}
+ public:
+ TCompactProtocolFactoryT() :
+ string_limit_(0),
+ container_limit_(0) {}
- TCompactProtocolFactoryT(int32_t string_limit, int32_t container_limit)
- : string_limit_(string_limit), container_limit_(container_limit) {}
+ TCompactProtocolFactoryT(int32_t string_limit, int32_t container_limit) :
+ string_limit_(string_limit),
+ container_limit_(container_limit) {}
virtual ~TCompactProtocolFactoryT() {}
- void setStringSizeLimit(int32_t string_limit) { string_limit_ = string_limit; }
+ void setStringSizeLimit(int32_t string_limit) {
+ string_limit_ = string_limit;
+ }
- void setContainerSizeLimit(int32_t container_limit) { container_limit_ = container_limit; }
+ void setContainerSizeLimit(int32_t container_limit) {
+ container_limit_ = container_limit;
+ }
boost::shared_ptr<TProtocol> getProtocol(boost::shared_ptr<TTransport> trans) {
- boost::shared_ptr<Transport_> specific_trans = boost::dynamic_pointer_cast<Transport_>(trans);
+ boost::shared_ptr<Transport_> specific_trans =
+ boost::dynamic_pointer_cast<Transport_>(trans);
TProtocol* prot;
if (specific_trans) {
- prot = new TCompactProtocolT<Transport_>(specific_trans, string_limit_, container_limit_);
+ prot = new TCompactProtocolT<Transport_>(specific_trans, string_limit_,
+ container_limit_);
} else {
prot = new TCompactProtocol(trans, string_limit_, container_limit_);
}
@@ -250,15 +275,15 @@
return boost::shared_ptr<TProtocol>(prot);
}
-private:
+ private:
int32_t string_limit_;
int32_t container_limit_;
+
};
typedef TCompactProtocolFactoryT<TTransport> TCompactProtocolFactory;
-}
-}
-} // apache::thrift::protocol
+
+}}} // apache::thrift::protocol
#include <thrift/protocol/TCompactProtocol.tcc>
diff --git a/lib/cpp/src/thrift/protocol/TDebugProtocol.cpp b/lib/cpp/src/thrift/protocol/TDebugProtocol.cpp
index 4687e82..63ea14d 100644
--- a/lib/cpp/src/thrift/protocol/TDebugProtocol.cpp
+++ b/lib/cpp/src/thrift/protocol/TDebugProtocol.cpp
@@ -28,6 +28,7 @@
using std::string;
+
static string byte_to_hex(const uint8_t byte) {
char buf[3];
int ret = std::sprintf(buf, "%02x", (int)byte);
@@ -37,46 +38,28 @@
return buf;
}
-namespace apache {
-namespace thrift {
-namespace protocol {
+
+namespace apache { namespace thrift { namespace protocol {
string TDebugProtocol::fieldTypeName(TType type) {
switch (type) {
- case T_STOP:
- return "stop";
- case T_VOID:
- return "void";
- case T_BOOL:
- return "bool";
- case T_BYTE:
- return "byte";
- case T_I16:
- return "i16";
- case T_I32:
- return "i32";
- case T_U64:
- return "u64";
- case T_I64:
- return "i64";
- case T_DOUBLE:
- return "double";
- case T_STRING:
- return "string";
- case T_STRUCT:
- return "struct";
- case T_MAP:
- return "map";
- case T_SET:
- return "set";
- case T_LIST:
- return "list";
- case T_UTF8:
- return "utf8";
- case T_UTF16:
- return "utf16";
- default:
- return "unknown";
+ case T_STOP : return "stop" ;
+ case T_VOID : return "void" ;
+ case T_BOOL : return "bool" ;
+ case T_BYTE : return "byte" ;
+ case T_I16 : return "i16" ;
+ case T_I32 : return "i32" ;
+ case T_U64 : return "u64" ;
+ case T_I64 : return "i64" ;
+ case T_DOUBLE : return "double" ;
+ case T_STRING : return "string" ;
+ case T_STRUCT : return "struct" ;
+ case T_MAP : return "map" ;
+ case T_SET : return "set" ;
+ case T_LIST : return "list" ;
+ case T_UTF8 : return "utf8" ;
+ case T_UTF16 : return "utf16" ;
+ default: return "unknown";
}
}
@@ -92,19 +75,19 @@
}
uint32_t TDebugProtocol::writePlain(const string& str) {
- if (str.length() > (std::numeric_limits<uint32_t>::max)())
+ if(str.length() > (std::numeric_limits<uint32_t>::max)())
throw TProtocolException(TProtocolException::SIZE_LIMIT);
trans_->write((uint8_t*)str.data(), static_cast<uint32_t>(str.length()));
return static_cast<uint32_t>(str.length());
}
uint32_t TDebugProtocol::writeIndented(const string& str) {
- if (str.length() > (std::numeric_limits<uint32_t>::max)())
+ if(str.length() > (std::numeric_limits<uint32_t>::max)())
throw TProtocolException(TProtocolException::SIZE_LIMIT);
- if (indent_str_.length() > (std::numeric_limits<uint32_t>::max)())
+ if(indent_str_.length() > (std::numeric_limits<uint32_t>::max)())
throw TProtocolException(TProtocolException::SIZE_LIMIT);
uint64_t total_len = indent_str_.length() + str.length();
- if (total_len > (std::numeric_limits<uint32_t>::max)())
+ if(total_len > (std::numeric_limits<uint32_t>::max)())
throw TProtocolException(TProtocolException::SIZE_LIMIT);
trans_->write((uint8_t*)indent_str_.data(), static_cast<uint32_t>(indent_str_.length()));
trans_->write((uint8_t*)str.data(), static_cast<uint32_t>(str.length()));
@@ -115,51 +98,52 @@
uint32_t size;
switch (write_state_.back()) {
- case UNINIT:
- // XXX figure out what to do here.
- // throw TProtocolException(TProtocolException::INVALID_DATA);
- // return writeIndented(str);
- return 0;
- case STRUCT:
- return 0;
- case SET:
- return writeIndented("");
- case MAP_KEY:
- return writeIndented("");
- case MAP_VALUE:
- return writePlain(" -> ");
- case LIST:
- size = writeIndented("[" + boost::lexical_cast<string>(list_idx_.back()) + "] = ");
- list_idx_.back()++;
- return size;
- default:
- throw std::logic_error("Invalid enum value.");
+ case UNINIT:
+ // XXX figure out what to do here.
+ //throw TProtocolException(TProtocolException::INVALID_DATA);
+ //return writeIndented(str);
+ return 0;
+ case STRUCT:
+ return 0;
+ case SET:
+ return writeIndented("");
+ case MAP_KEY:
+ return writeIndented("");
+ case MAP_VALUE:
+ return writePlain(" -> ");
+ case LIST:
+ size = writeIndented(
+ "[" + boost::lexical_cast<string>(list_idx_.back()) + "] = ");
+ list_idx_.back()++;
+ return size;
+ default:
+ throw std::logic_error("Invalid enum value.");
}
}
uint32_t TDebugProtocol::endItem() {
- // uint32_t size;
+ //uint32_t size;
switch (write_state_.back()) {
- case UNINIT:
- // XXX figure out what to do here.
- // throw TProtocolException(TProtocolException::INVALID_DATA);
- // return writeIndented(str);
- return 0;
- case STRUCT:
- return writePlain(",\n");
- case SET:
- return writePlain(",\n");
- case MAP_KEY:
- write_state_.back() = MAP_VALUE;
- return 0;
- case MAP_VALUE:
- write_state_.back() = MAP_KEY;
- return writePlain(",\n");
- case LIST:
- return writePlain(",\n");
- default:
- throw std::logic_error("Invalid enum value.");
+ case UNINIT:
+ // XXX figure out what to do here.
+ //throw TProtocolException(TProtocolException::INVALID_DATA);
+ //return writeIndented(str);
+ return 0;
+ case STRUCT:
+ return writePlain(",\n");
+ case SET:
+ return writePlain(",\n");
+ case MAP_KEY:
+ write_state_.back() = MAP_VALUE;
+ return 0;
+ case MAP_VALUE:
+ write_state_.back() = MAP_KEY;
+ return writePlain(",\n");
+ case LIST:
+ return writePlain(",\n");
+ default:
+ throw std::logic_error("Invalid enum value.");
}
}
@@ -174,21 +158,13 @@
uint32_t TDebugProtocol::writeMessageBegin(const std::string& name,
const TMessageType messageType,
const int32_t seqid) {
- (void)seqid;
+ (void) seqid;
string mtype;
switch (messageType) {
- case T_CALL:
- mtype = "call";
- break;
- case T_REPLY:
- mtype = "reply";
- break;
- case T_EXCEPTION:
- mtype = "exn";
- break;
- case T_ONEWAY:
- mtype = "oneway";
- break;
+ case T_CALL : mtype = "call" ; break;
+ case T_REPLY : mtype = "reply" ; break;
+ case T_EXCEPTION : mtype = "exn" ; break;
+ case T_ONEWAY : mtype = "oneway" ; break;
}
uint32_t size = writeIndented("(" + mtype + ") " + name + "(");
@@ -224,10 +200,12 @@
const int16_t fieldId) {
// sprintf(id_str, "%02d", fieldId);
string id_str = boost::lexical_cast<string>(fieldId);
- if (id_str.length() == 1)
- id_str = '0' + id_str;
+ if (id_str.length() == 1) id_str = '0' + id_str;
- return writeIndented(id_str + ": " + name + " (" + fieldTypeName(fieldType) + ") = ");
+ return writeIndented(
+ id_str + ": " +
+ name + " (" +
+ fieldTypeName(fieldType) + ") = ");
}
uint32_t TDebugProtocol::writeFieldEnd() {
@@ -237,7 +215,7 @@
uint32_t TDebugProtocol::writeFieldStop() {
return 0;
- // writeIndented("***STOP***\n");
+ //writeIndented("***STOP***\n");
}
uint32_t TDebugProtocol::writeMapBegin(const TType keyType,
@@ -263,7 +241,8 @@
return size;
}
-uint32_t TDebugProtocol::writeListBegin(const TType elemType, const uint32_t size) {
+uint32_t TDebugProtocol::writeListBegin(const TType elemType,
+ const uint32_t size) {
// TODO(dreiss): Optimize short arrays.
uint32_t bsize = 0;
bsize += startItem();
@@ -286,7 +265,8 @@
return size;
}
-uint32_t TDebugProtocol::writeSetBegin(const TType elemType, const uint32_t size) {
+uint32_t TDebugProtocol::writeSetBegin(const TType elemType,
+ const uint32_t size) {
// TODO(dreiss): Optimize short sets.
uint32_t bsize = 0;
bsize += startItem();
@@ -331,6 +311,7 @@
return writeItem(boost::lexical_cast<string>(dub));
}
+
uint32_t TDebugProtocol::writeString(const string& str) {
// XXX Raw/UTF-8?
@@ -351,30 +332,16 @@
output += *it;
} else {
switch (*it) {
- case '\a':
- output += "\\a";
- break;
- case '\b':
- output += "\\b";
- break;
- case '\f':
- output += "\\f";
- break;
- case '\n':
- output += "\\n";
- break;
- case '\r':
- output += "\\r";
- break;
- case '\t':
- output += "\\t";
- break;
- case '\v':
- output += "\\v";
- break;
- default:
- output += "\\x";
- output += byte_to_hex(*it);
+ case '\a': output += "\\a"; break;
+ case '\b': output += "\\b"; break;
+ case '\f': output += "\\f"; break;
+ case '\n': output += "\\n"; break;
+ case '\r': output += "\\r"; break;
+ case '\t': output += "\\t"; break;
+ case '\v': output += "\\v"; break;
+ default:
+ output += "\\x";
+ output += byte_to_hex(*it);
}
}
}
@@ -387,6 +354,5 @@
// XXX Hex?
return TDebugProtocol::writeString(str);
}
-}
-}
-} // apache::thrift::protocol
+
+}}} // apache::thrift::protocol
diff --git a/lib/cpp/src/thrift/protocol/TDebugProtocol.h b/lib/cpp/src/thrift/protocol/TDebugProtocol.h
index cc93230..f85e691 100644
--- a/lib/cpp/src/thrift/protocol/TDebugProtocol.h
+++ b/lib/cpp/src/thrift/protocol/TDebugProtocol.h
@@ -24,9 +24,7 @@
#include <boost/shared_ptr.hpp>
-namespace apache {
-namespace thrift {
-namespace protocol {
+namespace apache { namespace thrift { namespace protocol {
/*
@@ -41,30 +39,44 @@
*/
+
/**
* Protocol that prints the payload in a nice human-readable format.
* Reading from this protocol is not supported.
*
*/
class TDebugProtocol : public TVirtualProtocol<TDebugProtocol> {
-private:
- enum write_state_t { UNINIT, STRUCT, LIST, SET, MAP_KEY, MAP_VALUE };
+ private:
+ enum write_state_t
+ { UNINIT
+ , STRUCT
+ , LIST
+ , SET
+ , MAP_KEY
+ , MAP_VALUE
+ };
-public:
+ public:
TDebugProtocol(boost::shared_ptr<TTransport> trans)
- : TVirtualProtocol<TDebugProtocol>(trans),
- trans_(trans.get()),
- string_limit_(DEFAULT_STRING_LIMIT),
- string_prefix_size_(DEFAULT_STRING_PREFIX_SIZE) {
+ : TVirtualProtocol<TDebugProtocol>(trans)
+ , trans_(trans.get())
+ , string_limit_(DEFAULT_STRING_LIMIT)
+ , string_prefix_size_(DEFAULT_STRING_PREFIX_SIZE)
+ {
write_state_.push_back(UNINIT);
}
static const int32_t DEFAULT_STRING_LIMIT = 256;
static const int32_t DEFAULT_STRING_PREFIX_SIZE = 16;
- void setStringSizeLimit(int32_t string_limit) { string_limit_ = string_limit; }
+ void setStringSizeLimit(int32_t string_limit) {
+ string_limit_ = string_limit;
+ }
- void setStringPrefixSize(int32_t string_prefix_size) { string_prefix_size_ = string_prefix_size; }
+ void setStringPrefixSize(int32_t string_prefix_size) {
+ string_prefix_size_ = string_prefix_size;
+ }
+
uint32_t writeMessageBegin(const std::string& name,
const TMessageType messageType,
@@ -72,25 +84,32 @@
uint32_t writeMessageEnd();
+
uint32_t writeStructBegin(const char* name);
uint32_t writeStructEnd();
- uint32_t writeFieldBegin(const char* name, const TType fieldType, const int16_t fieldId);
+ uint32_t writeFieldBegin(const char* name,
+ const TType fieldType,
+ const int16_t fieldId);
uint32_t writeFieldEnd();
uint32_t writeFieldStop();
- uint32_t writeMapBegin(const TType keyType, const TType valType, const uint32_t size);
+ uint32_t writeMapBegin(const TType keyType,
+ const TType valType,
+ const uint32_t size);
uint32_t writeMapEnd();
- uint32_t writeListBegin(const TType elemType, const uint32_t size);
+ uint32_t writeListBegin(const TType elemType,
+ const uint32_t size);
uint32_t writeListEnd();
- uint32_t writeSetBegin(const TType elemType, const uint32_t size);
+ uint32_t writeSetBegin(const TType elemType,
+ const uint32_t size);
uint32_t writeSetEnd();
@@ -110,7 +129,8 @@
uint32_t writeBinary(const std::string& str);
-private:
+
+ private:
void indentUp();
void indentDown();
uint32_t writePlain(const std::string& str);
@@ -137,25 +157,25 @@
* Constructs debug protocol handlers
*/
class TDebugProtocolFactory : public TProtocolFactory {
-public:
+ public:
TDebugProtocolFactory() {}
virtual ~TDebugProtocolFactory() {}
boost::shared_ptr<TProtocol> getProtocol(boost::shared_ptr<TTransport> trans) {
return boost::shared_ptr<TProtocol>(new TDebugProtocol(trans));
}
+
};
-}
-}
-} // apache::thrift::protocol
+
+}}} // apache::thrift::protocol
+
// TODO(dreiss): Move (part of) ThriftDebugString into a .cpp file and remove this.
#include <thrift/transport/TBufferTransports.h>
-namespace apache {
-namespace thrift {
+namespace apache { namespace thrift {
-template <typename ThriftStruct>
+template<typename ThriftStruct>
std::string ThriftDebugString(const ThriftStruct& ts) {
using namespace apache::thrift::transport;
using namespace apache::thrift::protocol;
@@ -198,7 +218,10 @@
return std::string((char*)buf, (unsigned int)size);
}
#endif // 0
-}
-} // apache::thrift
+
+}} // apache::thrift
+
#endif // #ifndef _THRIFT_PROTOCOL_TDEBUGPROTOCOL_H_
+
+
diff --git a/lib/cpp/src/thrift/protocol/TDenseProtocol.cpp b/lib/cpp/src/thrift/protocol/TDenseProtocol.cpp
index d6644b7..4fbfc13 100644
--- a/lib/cpp/src/thrift/protocol/TDenseProtocol.cpp
+++ b/lib/cpp/src/thrift/protocol/TDenseProtocol.cpp
@@ -117,24 +117,24 @@
#define UNLIKELY(val) (val)
#endif
-namespace apache {
-namespace thrift {
-namespace protocol {
+namespace apache { namespace thrift { namespace protocol {
-const int TDenseProtocol::FP_PREFIX_LEN = apache::thrift::reflection::local::FP_PREFIX_LEN;
+const int TDenseProtocol::FP_PREFIX_LEN =
+ apache::thrift::reflection::local::FP_PREFIX_LEN;
// Top TypeSpec. TypeSpec of the structure being encoded.
-#define TTS (ts_stack_.back()) // type = TypeSpec*
+#define TTS (ts_stack_.back()) // type = TypeSpec*
// InDeX. Index into TTS of the current/next field to encode.
-#define IDX (idx_stack_.back()) // type = int
+#define IDX (idx_stack_.back()) // type = int
// Field TypeSpec. TypeSpec of the current/next field to encode.
-#define FTS (TTS->tstruct.specs[IDX]) // type = TypeSpec*
+#define FTS (TTS->tstruct.specs[IDX]) // type = TypeSpec*
// Field MeTa. Metadata of the current/next field to encode.
-#define FMT (TTS->tstruct.metas[IDX]) // type = FieldMeta
+#define FMT (TTS->tstruct.metas[IDX]) // type = FieldMeta
// SubType 1/2. TypeSpec of the first/second subtype of this container.
#define ST1 (TTS->tcontainer.subtype1)
#define ST2 (TTS->tcontainer.subtype2)
+
/**
* Checks that @c ttype is indeed the ttype that we should be writing,
* according to our typespec. Aborts if the test fails and debugging in on.
@@ -161,28 +161,30 @@
switch (TTS->ttype) {
- case T_STRUCT:
- assert(old_tts == FTS);
- break;
+ case T_STRUCT:
+ assert(old_tts == FTS);
+ break;
- case T_LIST:
- case T_SET:
- assert(old_tts == ST1);
- ts_stack_.push_back(old_tts);
- break;
+ case T_LIST:
+ case T_SET:
+ assert(old_tts == ST1);
+ ts_stack_.push_back(old_tts);
+ break;
- case T_MAP:
- assert(old_tts == (mkv_stack_.back() ? ST1 : ST2));
- mkv_stack_.back() = !mkv_stack_.back();
- ts_stack_.push_back(mkv_stack_.back() ? ST1 : ST2);
- break;
+ case T_MAP:
+ assert(old_tts == (mkv_stack_.back() ? ST1 : ST2));
+ mkv_stack_.back() = !mkv_stack_.back();
+ ts_stack_.push_back(mkv_stack_.back() ? ST1 : ST2);
+ break;
- default:
- assert(!"Invalid TType in stateTransition.");
- break;
+ default:
+ assert(!"Invalid TType in stateTransition.");
+ break;
+
}
}
+
/*
* Variable-length quantity functions.
*/
@@ -190,7 +192,7 @@
inline uint32_t TDenseProtocol::vlqRead(uint64_t& vlq) {
uint32_t used = 0;
uint64_t val = 0;
- uint8_t buf[10]; // 64 bits / (7 bits/byte) = 10 bytes.
+ uint8_t buf[10]; // 64 bits / (7 bits/byte) = 10 bytes.
uint32_t buf_size = sizeof(buf);
const uint8_t* borrowed = trans_->borrow(buf, &buf_size);
@@ -208,8 +210,7 @@
// Have to check for invalid data so we don't crash.
if (UNLIKELY(used == sizeof(buf))) {
resetState();
- throw TProtocolException(TProtocolException::INVALID_DATA,
- "Variable-length int over 10 bytes.");
+ throw TProtocolException(TProtocolException::INVALID_DATA, "Variable-length int over 10 bytes.");
}
}
}
@@ -227,15 +228,14 @@
// Might as well check for invalid data on the slow path too.
if (UNLIKELY(used >= sizeof(buf))) {
resetState();
- throw TProtocolException(TProtocolException::INVALID_DATA,
- "Variable-length int over 10 bytes.");
+ throw TProtocolException(TProtocolException::INVALID_DATA, "Variable-length int over 10 bytes.");
}
}
}
}
inline uint32_t TDenseProtocol::vlqWrite(uint64_t vlq) {
- uint8_t buf[10]; // 64 bits / (7 bits/byte) = 10 bytes.
+ uint8_t buf[10]; // 64 bits / (7 bits/byte) = 10 bytes.
int32_t pos = sizeof(buf) - 1;
// Write the thing from back to front.
@@ -253,10 +253,12 @@
// Back up one step before writing.
pos++;
- trans_->write(buf + pos, static_cast<uint32_t>(sizeof(buf) - pos));
+ trans_->write(buf+pos, static_cast<uint32_t>(sizeof(buf) - pos));
return static_cast<uint32_t>(sizeof(buf) - pos);
}
+
+
/*
* Writing functions.
*/
@@ -279,7 +281,7 @@
}
uint32_t TDenseProtocol::writeStructBegin(const char* name) {
- (void)name;
+ (void) name;
uint32_t xfer = 0;
// The TypeSpec stack should be empty if this is the top-level read/write.
@@ -313,7 +315,7 @@
uint32_t TDenseProtocol::writeFieldBegin(const char* name,
const TType fieldType,
const int16_t fieldId) {
- (void)name;
+ (void) name;
uint32_t xfer = 0;
// Skip over optional fields.
@@ -378,7 +380,8 @@
return 0;
}
-uint32_t TDenseProtocol::writeListBegin(const TType elemType, const uint32_t size) {
+uint32_t TDenseProtocol::writeListBegin(const TType elemType,
+ const uint32_t size) {
checkTType(T_LIST);
assert(elemType == ST1->ttype);
@@ -393,7 +396,8 @@
return 0;
}
-uint32_t TDenseProtocol::writeSetBegin(const TType elemType, const uint32_t size) {
+uint32_t TDenseProtocol::writeSetBegin(const TType elemType,
+ const uint32_t size) {
checkTType(T_SET);
assert(elemType == ST1->ttype);
@@ -459,7 +463,7 @@
}
uint32_t TDenseProtocol::subWriteString(const std::string& str) {
- if (str.size() > static_cast<size_t>((std::numeric_limits<int32_t>::max)()))
+ if(str.size() > static_cast<size_t>((std::numeric_limits<int32_t>::max)()))
throw TProtocolException(TProtocolException::SIZE_LIMIT);
uint32_t size = static_cast<uint32_t>(str.size());
uint32_t xfer = subWriteI32((int32_t)size);
@@ -469,6 +473,8 @@
return xfer + size;
}
+
+
/*
* Reading functions
*
@@ -495,8 +501,7 @@
xfer += subReadString(name);
xfer += subReadI32(seqid);
} else {
- throw TProtocolException(TProtocolException::BAD_VERSION,
- "No version identifier... old protocol client in strict mode?");
+ throw TProtocolException(TProtocolException::BAD_VERSION, "No version identifier... old protocol client in strict mode?");
}
return xfer;
}
@@ -506,7 +511,7 @@
}
uint32_t TDenseProtocol::readStructBegin(string& name) {
- (void)name;
+ (void) name;
uint32_t xfer = 0;
if (ts_stack_.empty()) {
@@ -525,7 +530,7 @@
if (std::memcmp(buf, type_spec_->fp_prefix, FP_PREFIX_LEN) != 0) {
resetState();
throw TProtocolException(TProtocolException::INVALID_DATA,
- "Fingerprint in data does not match type_spec.");
+ "Fingerprint in data does not match type_spec.");
}
}
}
@@ -541,8 +546,10 @@
return 0;
}
-uint32_t TDenseProtocol::readFieldBegin(string& name, TType& fieldType, int16_t& fieldId) {
- (void)name;
+uint32_t TDenseProtocol::readFieldBegin(string& name,
+ TType& fieldType,
+ int16_t& fieldId) {
+ (void) name;
uint32_t xfer = 0;
// For optional fields, check to see if they are there.
@@ -558,7 +565,7 @@
// Once we hit a mandatory field, or an optional field that is present,
// we know that FMT and FTS point to the appropriate field.
- fieldId = FMT.tag;
+ fieldId = FMT.tag;
fieldType = FTS->ttype;
// Normally, we push the TypeSpec that we are about to read,
@@ -574,7 +581,9 @@
return 0;
}
-uint32_t TDenseProtocol::readMapBegin(TType& keyType, TType& valType, uint32_t& size) {
+uint32_t TDenseProtocol::readMapBegin(TType& keyType,
+ TType& valType,
+ uint32_t& size) {
checkTType(T_MAP);
uint32_t xfer = 0;
@@ -605,7 +614,8 @@
return 0;
}
-uint32_t TDenseProtocol::readListBegin(TType& elemType, uint32_t& size) {
+uint32_t TDenseProtocol::readListBegin(TType& elemType,
+ uint32_t& size) {
checkTType(T_LIST);
uint32_t xfer = 0;
@@ -633,7 +643,8 @@
return 0;
}
-uint32_t TDenseProtocol::readSetBegin(TType& elemType, uint32_t& size) {
+uint32_t TDenseProtocol::readSetBegin(TType& elemType,
+ uint32_t& size) {
checkTType(T_SET);
uint32_t xfer = 0;
@@ -681,7 +692,8 @@
int64_t val = (int64_t)u64;
if (UNLIKELY(val > INT16_MAX || val < INT16_MIN)) {
resetState();
- throw TProtocolException(TProtocolException::INVALID_DATA, "i16 out of range.");
+ throw TProtocolException(TProtocolException::INVALID_DATA,
+ "i16 out of range.");
}
i16 = (int16_t)val;
return rv;
@@ -695,7 +707,8 @@
int64_t val = (int64_t)u64;
if (UNLIKELY(val > INT32_MAX || val < INT32_MIN)) {
resetState();
- throw TProtocolException(TProtocolException::INVALID_DATA, "i32 out of range.");
+ throw TProtocolException(TProtocolException::INVALID_DATA,
+ "i32 out of range.");
}
i32 = (int32_t)val;
return rv;
@@ -709,7 +722,8 @@
int64_t val = (int64_t)u64;
if (UNLIKELY(val > INT64_MAX || val < INT64_MIN)) {
resetState();
- throw TProtocolException(TProtocolException::INVALID_DATA, "i64 out of range.");
+ throw TProtocolException(TProtocolException::INVALID_DATA,
+ "i64 out of range.");
}
i64 = (int64_t)val;
return rv;
@@ -737,7 +751,8 @@
int64_t val = (int64_t)u64;
if (UNLIKELY(val > INT32_MAX || val < INT32_MIN)) {
resetState();
- throw TProtocolException(TProtocolException::INVALID_DATA, "i32 out of range.");
+ throw TProtocolException(TProtocolException::INVALID_DATA,
+ "i32 out of range.");
}
i32 = (int32_t)val;
return rv;
@@ -749,6 +764,5 @@
xfer = subReadI32(size);
return xfer + readStringBody(str, size);
}
-}
-}
-} // apache::thrift::protocol
+
+}}} // apache::thrift::protocol
diff --git a/lib/cpp/src/thrift/protocol/TDenseProtocol.h b/lib/cpp/src/thrift/protocol/TDenseProtocol.h
index e7f2cd2..4808d79 100644
--- a/lib/cpp/src/thrift/protocol/TDenseProtocol.h
+++ b/lib/cpp/src/thrift/protocol/TDenseProtocol.h
@@ -22,9 +22,7 @@
#include <thrift/protocol/TBinaryProtocol.h>
-namespace apache {
-namespace thrift {
-namespace protocol {
+namespace apache { namespace thrift { namespace protocol {
/**
* !!!WARNING!!!
@@ -58,13 +56,14 @@
* methods within our versions.
*
*/
-class TDenseProtocol : public TVirtualProtocol<TDenseProtocol, TBinaryProtocol> {
-protected:
+class TDenseProtocol
+ : public TVirtualProtocol<TDenseProtocol, TBinaryProtocol> {
+ protected:
static const int32_t VERSION_MASK = ((int32_t)0xffff0000);
// VERSION_1 (0x80010000) is taken by TBinaryProtocol.
static const int32_t VERSION_2 = ((int32_t)0x80020000);
-public:
+ public:
typedef apache::thrift::reflection::local::TypeSpec TypeSpec;
static const int FP_PREFIX_LEN;
@@ -72,13 +71,20 @@
* @param tran The transport to use.
* @param type_spec The TypeSpec of the structures using this protocol.
*/
- TDenseProtocol(boost::shared_ptr<TTransport> trans, TypeSpec* type_spec = NULL)
- : TVirtualProtocol<TDenseProtocol, TBinaryProtocol>(trans),
- type_spec_(type_spec),
- standalone_(true) {}
+ TDenseProtocol(boost::shared_ptr<TTransport> trans,
+ TypeSpec* type_spec = NULL) :
+ TVirtualProtocol<TDenseProtocol, TBinaryProtocol>(trans),
+ type_spec_(type_spec),
+ standalone_(true)
+ {}
- void setTypeSpec(TypeSpec* type_spec) { type_spec_ = type_spec; }
- TypeSpec* getTypeSpec() { return type_spec_; }
+ void setTypeSpec(TypeSpec* type_spec) {
+ type_spec_ = type_spec;
+ }
+ TypeSpec* getTypeSpec() {
+ return type_spec_;
+ }
+
/*
* Writing functions.
@@ -90,17 +96,22 @@
uint32_t writeMessageEnd();
+
uint32_t writeStructBegin(const char* name);
uint32_t writeStructEnd();
- uint32_t writeFieldBegin(const char* name, const TType fieldType, const int16_t fieldId);
+ uint32_t writeFieldBegin(const char* name,
+ const TType fieldType,
+ const int16_t fieldId);
uint32_t writeFieldEnd();
uint32_t writeFieldStop();
- uint32_t writeMapBegin(const TType keyType, const TType valType, const uint32_t size);
+ uint32_t writeMapBegin(const TType keyType,
+ const TType valType,
+ const uint32_t size);
uint32_t writeMapEnd();
@@ -128,6 +139,7 @@
uint32_t writeBinary(const std::string& str);
+
/*
* Helper writing functions (don't do state transitions).
*/
@@ -135,13 +147,18 @@
inline uint32_t subWriteString(const std::string& str);
- uint32_t subWriteBool(const bool value) { return TBinaryProtocol::writeBool(value); }
+ uint32_t subWriteBool(const bool value) {
+ return TBinaryProtocol::writeBool(value);
+ }
+
/*
* Reading functions
*/
- uint32_t readMessageBegin(std::string& name, TMessageType& messageType, int32_t& seqid);
+ uint32_t readMessageBegin(std::string& name,
+ TMessageType& messageType,
+ int32_t& seqid);
uint32_t readMessageEnd();
@@ -149,19 +166,25 @@
uint32_t readStructEnd();
- uint32_t readFieldBegin(std::string& name, TType& fieldType, int16_t& fieldId);
+ uint32_t readFieldBegin(std::string& name,
+ TType& fieldType,
+ int16_t& fieldId);
uint32_t readFieldEnd();
- uint32_t readMapBegin(TType& keyType, TType& valType, uint32_t& size);
+ uint32_t readMapBegin(TType& keyType,
+ TType& valType,
+ uint32_t& size);
uint32_t readMapEnd();
- uint32_t readListBegin(TType& elemType, uint32_t& size);
+ uint32_t readListBegin(TType& elemType,
+ uint32_t& size);
uint32_t readListEnd();
- uint32_t readSetBegin(TType& elemType, uint32_t& size);
+ uint32_t readSetBegin(TType& elemType,
+ uint32_t& size);
uint32_t readSetEnd();
@@ -190,9 +213,13 @@
inline uint32_t subReadString(std::string& str);
- uint32_t subReadBool(bool& value) { return TBinaryProtocol::readBool(value); }
+ uint32_t subReadBool(bool& value) {
+ return TBinaryProtocol::readBool(value);
+ }
-private:
+
+ private:
+
// Implementation functions, documented in the .cpp.
inline void checkTType(const TType ttype);
inline void stateTransition();
@@ -213,16 +240,15 @@
// for standalone protocol objects.
TypeSpec* type_spec_;
- std::vector<TypeSpec*> ts_stack_; // TypeSpec stack.
- std::vector<int> idx_stack_; // InDeX stack.
- std::vector<bool> mkv_stack_; // Map Key/Vlue stack.
- // True = key, False = value.
+ std::vector<TypeSpec*> ts_stack_; // TypeSpec stack.
+ std::vector<int> idx_stack_; // InDeX stack.
+ std::vector<bool> mkv_stack_; // Map Key/Vlue stack.
+ // True = key, False = value.
// True iff this is a standalone instance (no RPC).
bool standalone_;
};
-}
-}
-} // apache::thrift::protocol
+
+}}} // apache::thrift::protocol
#endif // #ifndef _THRIFT_PROTOCOL_TDENSEPROTOCOL_H_
diff --git a/lib/cpp/src/thrift/protocol/TJSONProtocol.cpp b/lib/cpp/src/thrift/protocol/TJSONProtocol.cpp
index ca450f4..a0cc8e2 100644
--- a/lib/cpp/src/thrift/protocol/TJSONProtocol.cpp
+++ b/lib/cpp/src/thrift/protocol/TJSONProtocol.cpp
@@ -26,9 +26,8 @@
using namespace apache::thrift::transport;
-namespace apache {
-namespace thrift {
-namespace protocol {
+namespace apache { namespace thrift { namespace protocol {
+
// Static data
@@ -64,7 +63,7 @@
static const std::string kTypeNameList("lst");
static const std::string kTypeNameSet("set");
-static const std::string& getTypeNameForTypeID(TType typeID) {
+static const std::string &getTypeNameForTypeID(TType typeID) {
switch (typeID) {
case T_BOOL:
return kTypeNameBool;
@@ -89,11 +88,12 @@
case T_LIST:
return kTypeNameList;
default:
- throw TProtocolException(TProtocolException::NOT_IMPLEMENTED, "Unrecognized type");
+ throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
+ "Unrecognized type");
}
}
-static TType getTypeIDForTypeName(const std::string& name) {
+static TType getTypeIDForTypeName(const std::string &name) {
TType result = T_STOP; // Sentinel value
if (name.length() > 1) {
switch (name[0]) {
@@ -128,7 +128,8 @@
case 's':
if (name[1] == 't') {
result = T_STRING;
- } else if (name[1] == 'e') {
+ }
+ else if (name[1] == 'e') {
result = T_SET;
}
break;
@@ -138,67 +139,25 @@
}
}
if (result == T_STOP) {
- throw TProtocolException(TProtocolException::NOT_IMPLEMENTED, "Unrecognized type");
+ throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
+ "Unrecognized type");
}
return result;
}
+
// This table describes the handling for the first 0x30 characters
// 0 : escape using "\u00xx" notation
// 1 : just output index
// <other> : escape using "\<other>" notation
static const uint8_t kJSONCharTable[0x30] = {
- // 0 1 2 3 4 5 6 7 8 9 A B C D E F
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 'b',
- 't',
- 'n',
- 0,
- 'f',
- 'r',
- 0,
- 0, // 0
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0, // 1
- 1,
- 1,
- '"',
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1, // 2
+// 0 1 2 3 4 5 6 7 8 9 A B C D E F
+ 0, 0, 0, 0, 0, 0, 0, 0,'b','t','n', 0,'f','r', 0, 0, // 0
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1
+ 1, 1,'"', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2
};
+
// This string's characters must match up with the elements in kEscapeCharVals.
// I don't have '/' on this list even though it appears on www.json.org --
// it is not in the RFC
@@ -207,26 +166,23 @@
// The elements of this array must match up with the sequence of characters in
// kEscapeChars
const static uint8_t kEscapeCharVals[7] = {
- '"',
- '\\',
- '\b',
- '\f',
- '\n',
- '\r',
- '\t',
+ '"', '\\', '\b', '\f', '\n', '\r', '\t',
};
+
// Static helper functions
// Read 1 character from the transport trans and verify that it is the
// expected character ch.
// Throw a protocol exception if it is not.
-static uint32_t readSyntaxChar(TJSONProtocol::LookaheadReader& reader, uint8_t ch) {
+static uint32_t readSyntaxChar(TJSONProtocol::LookaheadReader &reader,
+ uint8_t ch) {
uint8_t ch2 = reader.read();
if (ch2 != ch) {
throw TProtocolException(TProtocolException::INVALID_DATA,
- "Expected \'" + std::string((char*)&ch, 1) + "\'; got \'"
- + std::string((char*)&ch2, 1) + "\'.");
+ "Expected \'" + std::string((char *)&ch, 1) +
+ "\'; got \'" + std::string((char *)&ch2, 1) +
+ "\'.");
}
return 1;
}
@@ -236,12 +192,14 @@
static uint8_t hexVal(uint8_t ch) {
if ((ch >= '0') && (ch <= '9')) {
return ch - '0';
- } else if ((ch >= 'a') && (ch <= 'f')) {
+ }
+ else if ((ch >= 'a') && (ch <= 'f')) {
return ch - 'a' + 10;
- } else {
+ }
+ else {
throw TProtocolException(TProtocolException::INVALID_DATA,
- "Expected hex val ([0-9a-f]); got \'" + std::string((char*)&ch, 1)
- + "\'.");
+ "Expected hex val ([0-9a-f]); got \'"
+ + std::string((char *)&ch, 1) + "\'.");
}
}
@@ -251,7 +209,8 @@
val &= 0x0F;
if (val < 10) {
return val + '0';
- } else {
+ }
+ else {
return val - 10 + 'a';
}
}
@@ -279,30 +238,32 @@
return false;
}
+
/**
* Class to serve as base JSON context and as base class for other context
* implementations
*/
class TJSONContext {
-public:
- TJSONContext(){};
+ public:
- virtual ~TJSONContext(){};
+ TJSONContext() {};
+
+ virtual ~TJSONContext() {};
/**
* Write context data to the transport. Default is to do nothing.
*/
- virtual uint32_t write(TTransport& trans) {
- (void)trans;
+ virtual uint32_t write(TTransport &trans) {
+ (void) trans;
return 0;
};
/**
* Read context data from the transport. Default is to do nothing.
*/
- virtual uint32_t read(TJSONProtocol::LookaheadReader& reader) {
- (void)reader;
+ virtual uint32_t read(TJSONProtocol::LookaheadReader &reader) {
+ (void) reader;
return 0;
};
@@ -310,33 +271,41 @@
* Return true if numbers need to be escaped as strings in this context.
* Default behavior is to return false.
*/
- virtual bool escapeNum() { return false; }
+ virtual bool escapeNum() {
+ return false;
+ }
};
// Context class for object member key-value pairs
class JSONPairContext : public TJSONContext {
public:
- JSONPairContext() : first_(true), colon_(true) {}
- uint32_t write(TTransport& trans) {
+ JSONPairContext() :
+ first_(true),
+ colon_(true) {
+ }
+
+ uint32_t write(TTransport &trans) {
if (first_) {
first_ = false;
colon_ = true;
return 0;
- } else {
+ }
+ else {
trans.write(colon_ ? &kJSONPairSeparator : &kJSONElemSeparator, 1);
colon_ = !colon_;
return 1;
}
}
- uint32_t read(TJSONProtocol::LookaheadReader& reader) {
+ uint32_t read(TJSONProtocol::LookaheadReader &reader) {
if (first_) {
first_ = false;
colon_ = true;
return 0;
- } else {
+ }
+ else {
uint8_t ch = (colon_ ? kJSONPairSeparator : kJSONElemSeparator);
colon_ = !colon_;
return readSyntaxChar(reader, ch);
@@ -344,51 +313,59 @@
}
// Numbers must be turned into strings if they are the key part of a pair
- virtual bool escapeNum() { return colon_; }
+ virtual bool escapeNum() {
+ return colon_;
+ }
-private:
- bool first_;
- bool colon_;
+ private:
+
+ bool first_;
+ bool colon_;
};
// Context class for lists
class JSONListContext : public TJSONContext {
public:
- JSONListContext() : first_(true) {}
- uint32_t write(TTransport& trans) {
+ JSONListContext() :
+ first_(true) {
+ }
+
+ uint32_t write(TTransport &trans) {
if (first_) {
first_ = false;
return 0;
- } else {
+ }
+ else {
trans.write(&kJSONElemSeparator, 1);
return 1;
}
}
- uint32_t read(TJSONProtocol::LookaheadReader& reader) {
+ uint32_t read(TJSONProtocol::LookaheadReader &reader) {
if (first_) {
first_ = false;
return 0;
- } else {
+ }
+ else {
return readSyntaxChar(reader, kJSONElemSeparator);
}
}
-private:
- bool first_;
+ private:
+ bool first_;
};
-TJSONProtocol::TJSONProtocol(boost::shared_ptr<TTransport> ptrans)
- : TVirtualProtocol<TJSONProtocol>(ptrans),
- trans_(ptrans.get()),
- context_(new TJSONContext()),
- reader_(*ptrans) {
+
+TJSONProtocol::TJSONProtocol(boost::shared_ptr<TTransport> ptrans) :
+ TVirtualProtocol<TJSONProtocol>(ptrans),
+ trans_(ptrans.get()),
+ context_(new TJSONContext()),
+ reader_(*ptrans) {
}
-TJSONProtocol::~TJSONProtocol() {
-}
+TJSONProtocol::~TJSONProtocol() {}
void TJSONProtocol::pushContext(boost::shared_ptr<TJSONContext> c) {
contexts_.push(context_);
@@ -402,7 +379,7 @@
// Write the character ch as a JSON escape sequence ("\u00xx")
uint32_t TJSONProtocol::writeJSONEscapeChar(uint8_t ch) {
- trans_->write((const uint8_t*)kJSONEscapePrefix.c_str(),
+ trans_->write((const uint8_t *)kJSONEscapePrefix.c_str(),
static_cast<uint32_t>(kJSONEscapePrefix.length()));
uint8_t outCh = hexChar(ch >> 4);
trans_->write(&outCh, 1);
@@ -418,21 +395,25 @@
trans_->write(&kJSONBackslash, 1);
trans_->write(&kJSONBackslash, 1);
return 2;
- } else {
+ }
+ else {
trans_->write(&ch, 1);
return 1;
}
- } else {
+ }
+ else {
uint8_t outCh = kJSONCharTable[ch];
// Check if regular character, backslash escaped, or JSON escaped
if (outCh == 1) {
trans_->write(&ch, 1);
return 1;
- } else if (outCh > 1) {
+ }
+ else if (outCh > 1) {
trans_->write(&kJSONBackslash, 1);
trans_->write(&outCh, 1);
return 2;
- } else {
+ }
+ else {
return writeJSONEscapeChar(ch);
}
}
@@ -440,7 +421,7 @@
// Write out the contents of the string str as a JSON string, escaping
// characters as appropriate.
-uint32_t TJSONProtocol::writeJSONString(const std::string& str) {
+uint32_t TJSONProtocol::writeJSONString(const std::string &str) {
uint32_t result = context_->write(*trans_);
result += 2; // For quotes
trans_->write(&kJSONStringDelimiter, 1);
@@ -455,13 +436,13 @@
// Write out the contents of the string as JSON string, base64-encoding
// the string's contents, and escaping as appropriate
-uint32_t TJSONProtocol::writeJSONBase64(const std::string& str) {
+uint32_t TJSONProtocol::writeJSONBase64(const std::string &str) {
uint32_t result = context_->write(*trans_);
result += 2; // For quotes
trans_->write(&kJSONStringDelimiter, 1);
uint8_t b[4];
- const uint8_t* bytes = (const uint8_t*)str.c_str();
- if (str.length() > (std::numeric_limits<uint32_t>::max)())
+ const uint8_t *bytes = (const uint8_t *)str.c_str();
+ if(str.length() > (std::numeric_limits<uint32_t>::max)())
throw TProtocolException(TProtocolException::SIZE_LIMIT);
uint32_t len = static_cast<uint32_t>(str.length());
while (len >= 3) {
@@ -470,7 +451,7 @@
trans_->write(b, 4);
result += 4;
bytes += 3;
- len -= 3;
+ len -=3;
}
if (len) { // Handle remainder
base64_encode(bytes, len, b);
@@ -492,9 +473,9 @@
trans_->write(&kJSONStringDelimiter, 1);
result += 1;
}
- if (val.length() > (std::numeric_limits<uint32_t>::max)())
+ if(val.length() > (std::numeric_limits<uint32_t>::max)())
throw TProtocolException(TProtocolException::SIZE_LIMIT);
- trans_->write((const uint8_t*)val.c_str(), static_cast<uint32_t>(val.length()));
+ trans_->write((const uint8_t *)val.c_str(), static_cast<uint32_t>(val.length()));
result += static_cast<uint32_t>(val.length());
if (escapeNum) {
trans_->write(&kJSONStringDelimiter, 1);
@@ -535,9 +516,9 @@
trans_->write(&kJSONStringDelimiter, 1);
result += 1;
}
- if (val.length() > (std::numeric_limits<uint32_t>::max)())
+ if(val.length() > (std::numeric_limits<uint32_t>::max)())
throw TProtocolException(TProtocolException::SIZE_LIMIT);
- trans_->write((const uint8_t*)val.c_str(), static_cast<uint32_t>(val.length()));
+ trans_->write((const uint8_t *)val.c_str(), static_cast<uint32_t>(val.length()));
result += static_cast<uint32_t>(val.length());
if (escapeNum) {
trans_->write(&kJSONStringDelimiter, 1);
@@ -588,7 +569,7 @@
}
uint32_t TJSONProtocol::writeStructBegin(const char* name) {
- (void)name;
+ (void) name;
return writeJSONObjectStart();
}
@@ -599,7 +580,7 @@
uint32_t TJSONProtocol::writeFieldBegin(const char* name,
const TType fieldType,
const int16_t fieldId) {
- (void)name;
+ (void) name;
uint32_t result = writeJSONInteger(fieldId);
result += writeJSONObjectStart();
result += writeJSONString(getTypeNameForTypeID(fieldType));
@@ -629,7 +610,8 @@
return writeJSONObjectEnd() + writeJSONArrayEnd();
}
-uint32_t TJSONProtocol::writeListBegin(const TType elemType, const uint32_t size) {
+uint32_t TJSONProtocol::writeListBegin(const TType elemType,
+ const uint32_t size) {
uint32_t result = writeJSONArrayStart();
result += writeJSONString(getTypeNameForTypeID(elemType));
result += writeJSONInteger((int64_t)size);
@@ -640,7 +622,8 @@
return writeJSONArrayEnd();
}
-uint32_t TJSONProtocol::writeSetBegin(const TType elemType, const uint32_t size) {
+uint32_t TJSONProtocol::writeSetBegin(const TType elemType,
+ const uint32_t size) {
uint32_t result = writeJSONArrayStart();
result += writeJSONString(getTypeNameForTypeID(elemType));
result += writeJSONInteger((int64_t)size);
@@ -685,9 +668,9 @@
return writeJSONBase64(str);
}
-/**
- * Reading functions
- */
+ /**
+ * Reading functions
+ */
// Reads 1 byte and verifies that it matches ch.
uint32_t TJSONProtocol::readJSONSyntaxChar(uint8_t ch) {
@@ -696,7 +679,7 @@
// Decodes the four hex parts of a JSON escaped string character and returns
// the character via out. The first two characters must be "00".
-uint32_t TJSONProtocol::readJSONEscapeChar(uint8_t* out) {
+uint32_t TJSONProtocol::readJSONEscapeChar(uint8_t *out) {
uint8_t b[2];
readJSONSyntaxChar(kJSONZeroChar);
readJSONSyntaxChar(kJSONZeroChar);
@@ -707,7 +690,7 @@
}
// Decodes a JSON string, including unescaping, and returns the string via str
-uint32_t TJSONProtocol::readJSONString(std::string& str, bool skipContext) {
+uint32_t TJSONProtocol::readJSONString(std::string &str, bool skipContext) {
uint32_t result = (skipContext ? 0 : context_->read(reader_));
result += readJSONSyntaxChar(kJSONStringDelimiter);
uint8_t ch;
@@ -723,12 +706,13 @@
++result;
if (ch == kJSONEscapeChar) {
result += readJSONEscapeChar(&ch);
- } else {
+ }
+ else {
size_t pos = kEscapeChars.find(ch);
if (pos == std::string::npos) {
throw TProtocolException(TProtocolException::INVALID_DATA,
- "Expected control char, got '" + std::string((const char*)&ch, 1)
- + "'.");
+ "Expected control char, got '" +
+ std::string((const char *)&ch, 1) + "'.");
}
ch = kEscapeCharVals[pos];
}
@@ -739,17 +723,17 @@
}
// Reads a block of base64 characters, decoding it, and returns via str
-uint32_t TJSONProtocol::readJSONBase64(std::string& str) {
+uint32_t TJSONProtocol::readJSONBase64(std::string &str) {
std::string tmp;
uint32_t result = readJSONString(tmp);
- uint8_t* b = (uint8_t*)tmp.c_str();
- if (tmp.length() > (std::numeric_limits<uint32_t>::max)())
+ uint8_t *b = (uint8_t *)tmp.c_str();
+ if(tmp.length() > (std::numeric_limits<uint32_t>::max)())
throw TProtocolException(TProtocolException::SIZE_LIMIT);
uint32_t len = static_cast<uint32_t>(tmp.length());
str.clear();
while (len >= 4) {
base64_decode(b, 4);
- str.append((const char*)b, 3);
+ str.append((const char *)b, 3);
b += 4;
len -= 4;
}
@@ -757,14 +741,14 @@
// base64 but legal for skip of regular string type)
if (len > 1) {
base64_decode(b, len);
- str.append((const char*)b, len - 1);
+ str.append((const char *)b, len - 1);
}
return result;
}
// Reads a sequence of characters, stopping at the first one that is not
// a valid JSON numeric character.
-uint32_t TJSONProtocol::readJSONNumericChars(std::string& str) {
+uint32_t TJSONProtocol::readJSONNumericChars(std::string &str) {
uint32_t result = 0;
str.clear();
while (true) {
@@ -782,7 +766,7 @@
// Reads a sequence of characters and assembles them into a number,
// returning them via num
template <typename NumberType>
-uint32_t TJSONProtocol::readJSONInteger(NumberType& num) {
+uint32_t TJSONProtocol::readJSONInteger(NumberType &num) {
uint32_t result = context_->read(reader_);
if (context_->escapeNum()) {
result += readJSONSyntaxChar(kJSONStringDelimiter);
@@ -791,9 +775,11 @@
result += readJSONNumericChars(str);
try {
num = boost::lexical_cast<NumberType>(str);
- } catch (boost::bad_lexical_cast e) {
+ }
+ catch (boost::bad_lexical_cast e) {
throw new TProtocolException(TProtocolException::INVALID_DATA,
- "Expected numeric value; got \"" + str + "\"");
+ "Expected numeric value; got \"" + str +
+ "\"");
}
if (context_->escapeNum()) {
result += readJSONSyntaxChar(kJSONStringDelimiter);
@@ -802,19 +788,22 @@
}
// Reads a JSON number or string and interprets it as a double.
-uint32_t TJSONProtocol::readJSONDouble(double& num) {
+uint32_t TJSONProtocol::readJSONDouble(double &num) {
uint32_t result = context_->read(reader_);
std::string str;
if (reader_.peek() == kJSONStringDelimiter) {
result += readJSONString(str, true);
// Check for NaN, Infinity and -Infinity
if (str == kThriftNan) {
- num = HUGE_VAL / HUGE_VAL; // generates NaN
- } else if (str == kThriftInfinity) {
+ num = HUGE_VAL/HUGE_VAL; // generates NaN
+ }
+ else if (str == kThriftInfinity) {
num = HUGE_VAL;
- } else if (str == kThriftNegativeInfinity) {
+ }
+ else if (str == kThriftNegativeInfinity) {
num = -HUGE_VAL;
- } else {
+ }
+ else {
if (!context_->escapeNum()) {
// Throw exception -- we should not be in a string in this case
throw new TProtocolException(TProtocolException::INVALID_DATA,
@@ -822,12 +811,15 @@
}
try {
num = boost::lexical_cast<double>(str);
- } catch (boost::bad_lexical_cast e) {
+ }
+ catch (boost::bad_lexical_cast e) {
throw new TProtocolException(TProtocolException::INVALID_DATA,
- "Expected numeric value; got \"" + str + "\"");
+ "Expected numeric value; got \"" + str +
+ "\"");
}
}
- } else {
+ }
+ else {
if (context_->escapeNum()) {
// This will throw - we should have had a quote if escapeNum == true
readJSONSyntaxChar(kJSONStringDelimiter);
@@ -835,9 +827,11 @@
result += readJSONNumericChars(str);
try {
num = boost::lexical_cast<double>(str);
- } catch (boost::bad_lexical_cast e) {
+ }
+ catch (boost::bad_lexical_cast e) {
throw new TProtocolException(TProtocolException::INVALID_DATA,
- "Expected numeric value; got \"" + str + "\"");
+ "Expected numeric value; got \"" + str +
+ "\"");
}
}
return result;
@@ -876,13 +870,14 @@
uint64_t tmpVal = 0;
result += readJSONInteger(tmpVal);
if (tmpVal != kThriftVersion1) {
- throw TProtocolException(TProtocolException::BAD_VERSION, "Message contained bad version.");
+ throw TProtocolException(TProtocolException::BAD_VERSION,
+ "Message contained bad version.");
}
result += readJSONString(name);
result += readJSONInteger(tmpVal);
messageType = (TMessageType)tmpVal;
result += readJSONInteger(tmpVal);
- if (tmpVal > static_cast<uint64_t>((std::numeric_limits<int32_t>::max)()))
+ if(tmpVal > static_cast<uint64_t>((std::numeric_limits<int32_t>::max)()))
throw TProtocolException(TProtocolException::SIZE_LIMIT);
seqid = static_cast<int32_t>(tmpVal);
return result;
@@ -893,7 +888,7 @@
}
uint32_t TJSONProtocol::readStructBegin(std::string& name) {
- (void)name;
+ (void) name;
return readJSONObjectStart();
}
@@ -901,18 +896,21 @@
return readJSONObjectEnd();
}
-uint32_t TJSONProtocol::readFieldBegin(std::string& name, TType& fieldType, int16_t& fieldId) {
- (void)name;
+uint32_t TJSONProtocol::readFieldBegin(std::string& name,
+ TType& fieldType,
+ int16_t& fieldId) {
+ (void) name;
uint32_t result = 0;
// Check if we hit the end of the list
uint8_t ch = reader_.peek();
if (ch == kJSONObjectEnd) {
fieldType = apache::thrift::protocol::T_STOP;
- } else {
+ }
+ else {
uint64_t tmpVal = 0;
std::string tmpStr;
result += readJSONInteger(tmpVal);
- if (tmpVal > static_cast<uint32_t>((std::numeric_limits<int16_t>::max)()))
+ if(tmpVal > static_cast<uint32_t>((std::numeric_limits<int16_t>::max)()))
throw TProtocolException(TProtocolException::SIZE_LIMIT);
fieldId = static_cast<int16_t>(tmpVal);
result += readJSONObjectStart();
@@ -926,7 +924,9 @@
return readJSONObjectEnd();
}
-uint32_t TJSONProtocol::readMapBegin(TType& keyType, TType& valType, uint32_t& size) {
+uint32_t TJSONProtocol::readMapBegin(TType& keyType,
+ TType& valType,
+ uint32_t& size) {
uint64_t tmpVal = 0;
std::string tmpStr;
uint32_t result = readJSONArrayStart();
@@ -935,7 +935,7 @@
result += readJSONString(tmpStr);
valType = getTypeIDForTypeName(tmpStr);
result += readJSONInteger(tmpVal);
- if (tmpVal > (std::numeric_limits<uint32_t>::max)())
+ if(tmpVal > (std::numeric_limits<uint32_t>::max)())
throw TProtocolException(TProtocolException::SIZE_LIMIT);
size = static_cast<uint32_t>(tmpVal);
result += readJSONObjectStart();
@@ -946,14 +946,15 @@
return readJSONObjectEnd() + readJSONArrayEnd();
}
-uint32_t TJSONProtocol::readListBegin(TType& elemType, uint32_t& size) {
+uint32_t TJSONProtocol::readListBegin(TType& elemType,
+ uint32_t& size) {
uint64_t tmpVal = 0;
std::string tmpStr;
uint32_t result = readJSONArrayStart();
result += readJSONString(tmpStr);
elemType = getTypeIDForTypeName(tmpStr);
result += readJSONInteger(tmpVal);
- if (tmpVal > (std::numeric_limits<uint32_t>::max)())
+ if(tmpVal > (std::numeric_limits<uint32_t>::max)())
throw TProtocolException(TProtocolException::SIZE_LIMIT);
size = static_cast<uint32_t>(tmpVal);
return result;
@@ -963,14 +964,15 @@
return readJSONArrayEnd();
}
-uint32_t TJSONProtocol::readSetBegin(TType& elemType, uint32_t& size) {
+uint32_t TJSONProtocol::readSetBegin(TType& elemType,
+ uint32_t& size) {
uint64_t tmpVal = 0;
std::string tmpStr;
uint32_t result = readJSONArrayStart();
result += readJSONString(tmpStr);
elemType = getTypeIDForTypeName(tmpStr);
result += readJSONInteger(tmpVal);
- if (tmpVal > (std::numeric_limits<uint32_t>::max)())
+ if(tmpVal > (std::numeric_limits<uint32_t>::max)())
throw TProtocolException(TProtocolException::SIZE_LIMIT);
size = static_cast<uint32_t>(tmpVal);
return result;
@@ -987,8 +989,8 @@
// readByte() must be handled properly becuase boost::lexical cast sees int8_t
// as a text type instead of an integer type
uint32_t TJSONProtocol::readByte(int8_t& byte) {
- int16_t tmp = (int16_t)byte;
- uint32_t result = readJSONInteger(tmp);
+ int16_t tmp = (int16_t) byte;
+ uint32_t result = readJSONInteger(tmp);
assert(tmp < 256);
byte = (int8_t)tmp;
return result;
@@ -1010,13 +1012,12 @@
return readJSONDouble(dub);
}
-uint32_t TJSONProtocol::readString(std::string& str) {
+uint32_t TJSONProtocol::readString(std::string &str) {
return readJSONString(str);
}
-uint32_t TJSONProtocol::readBinary(std::string& str) {
+uint32_t TJSONProtocol::readBinary(std::string &str) {
return readJSONBase64(str);
}
-}
-}
-} // apache::thrift::protocol
+
+}}} // apache::thrift::protocol
diff --git a/lib/cpp/src/thrift/protocol/TJSONProtocol.h b/lib/cpp/src/thrift/protocol/TJSONProtocol.h
index b19c35d..edfc744 100644
--- a/lib/cpp/src/thrift/protocol/TJSONProtocol.h
+++ b/lib/cpp/src/thrift/protocol/TJSONProtocol.h
@@ -24,9 +24,7 @@
#include <stack>
-namespace apache {
-namespace thrift {
-namespace protocol {
+namespace apache { namespace thrift { namespace protocol {
// Forward declaration
class TJSONContext;
@@ -90,12 +88,14 @@
*
*/
class TJSONProtocol : public TVirtualProtocol<TJSONProtocol> {
-public:
+ public:
+
TJSONProtocol(boost::shared_ptr<TTransport> ptrans);
~TJSONProtocol();
-private:
+ private:
+
void pushContext(boost::shared_ptr<TJSONContext> c);
void popContext();
@@ -104,16 +104,16 @@
uint32_t writeJSONChar(uint8_t ch);
- uint32_t writeJSONString(const std::string& str);
+ uint32_t writeJSONString(const std::string &str);
- uint32_t writeJSONBase64(const std::string& str);
+ uint32_t writeJSONBase64(const std::string &str);
template <typename NumberType>
uint32_t writeJSONInteger(NumberType num);
uint32_t writeJSONDouble(double num);
- uint32_t writeJSONObjectStart();
+ uint32_t writeJSONObjectStart() ;
uint32_t writeJSONObjectEnd();
@@ -123,18 +123,18 @@
uint32_t readJSONSyntaxChar(uint8_t ch);
- uint32_t readJSONEscapeChar(uint8_t* out);
+ uint32_t readJSONEscapeChar(uint8_t *out);
- uint32_t readJSONString(std::string& str, bool skipContext = false);
+ uint32_t readJSONString(std::string &str, bool skipContext = false);
- uint32_t readJSONBase64(std::string& str);
+ uint32_t readJSONBase64(std::string &str);
- uint32_t readJSONNumericChars(std::string& str);
+ uint32_t readJSONNumericChars(std::string &str);
template <typename NumberType>
- uint32_t readJSONInteger(NumberType& num);
+ uint32_t readJSONInteger(NumberType &num);
- uint32_t readJSONDouble(double& num);
+ uint32_t readJSONDouble(double &num);
uint32_t readJSONObjectStart();
@@ -144,7 +144,8 @@
uint32_t readJSONArrayEnd();
-public:
+ public:
+
/**
* Writing functions.
*/
@@ -159,21 +160,27 @@
uint32_t writeStructEnd();
- uint32_t writeFieldBegin(const char* name, const TType fieldType, const int16_t fieldId);
+ uint32_t writeFieldBegin(const char* name,
+ const TType fieldType,
+ const int16_t fieldId);
uint32_t writeFieldEnd();
uint32_t writeFieldStop();
- uint32_t writeMapBegin(const TType keyType, const TType valType, const uint32_t size);
+ uint32_t writeMapBegin(const TType keyType,
+ const TType valType,
+ const uint32_t size);
uint32_t writeMapEnd();
- uint32_t writeListBegin(const TType elemType, const uint32_t size);
+ uint32_t writeListBegin(const TType elemType,
+ const uint32_t size);
uint32_t writeListEnd();
- uint32_t writeSetBegin(const TType elemType, const uint32_t size);
+ uint32_t writeSetBegin(const TType elemType,
+ const uint32_t size);
uint32_t writeSetEnd();
@@ -197,7 +204,9 @@
* Reading functions
*/
- uint32_t readMessageBegin(std::string& name, TMessageType& messageType, int32_t& seqid);
+ uint32_t readMessageBegin(std::string& name,
+ TMessageType& messageType,
+ int32_t& seqid);
uint32_t readMessageEnd();
@@ -205,19 +214,25 @@
uint32_t readStructEnd();
- uint32_t readFieldBegin(std::string& name, TType& fieldType, int16_t& fieldId);
+ uint32_t readFieldBegin(std::string& name,
+ TType& fieldType,
+ int16_t& fieldId);
uint32_t readFieldEnd();
- uint32_t readMapBegin(TType& keyType, TType& valType, uint32_t& size);
+ uint32_t readMapBegin(TType& keyType,
+ TType& valType,
+ uint32_t& size);
uint32_t readMapEnd();
- uint32_t readListBegin(TType& elemType, uint32_t& size);
+ uint32_t readListBegin(TType& elemType,
+ uint32_t& size);
uint32_t readListEnd();
- uint32_t readSetBegin(TType& elemType, uint32_t& size);
+ uint32_t readSetBegin(TType& elemType,
+ uint32_t& size);
uint32_t readSetEnd();
@@ -242,13 +257,18 @@
class LookaheadReader {
- public:
- LookaheadReader(TTransport& trans) : trans_(&trans), hasData_(false) {}
+ public:
+
+ LookaheadReader(TTransport &trans) :
+ trans_(&trans),
+ hasData_(false) {
+ }
uint8_t read() {
if (hasData_) {
hasData_ = false;
- } else {
+ }
+ else {
trans_->readAll(&data_, 1);
}
return data_;
@@ -262,13 +282,13 @@
return data_;
}
- private:
- TTransport* trans_;
+ private:
+ TTransport *trans_;
bool hasData_;
uint8_t data_;
};
-private:
+ private:
TTransport* trans_;
std::stack<boost::shared_ptr<TJSONContext> > contexts_;
@@ -280,7 +300,7 @@
* Constructs input and output protocol objects given transports.
*/
class TJSONProtocolFactory : public TProtocolFactory {
-public:
+ public:
TJSONProtocolFactory() {}
virtual ~TJSONProtocolFactory() {}
@@ -289,18 +309,17 @@
return boost::shared_ptr<TProtocol>(new TJSONProtocol(trans));
}
};
-}
-}
-} // apache::thrift::protocol
+
+}}} // apache::thrift::protocol
+
// TODO(dreiss): Move part of ThriftJSONString into a .cpp file and remove this.
#include <thrift/transport/TBufferTransports.h>
-namespace apache {
-namespace thrift {
+namespace apache { namespace thrift {
-template <typename ThriftStruct>
-std::string ThriftJSONString(const ThriftStruct& ts) {
+template<typename ThriftStruct>
+ std::string ThriftJSONString(const ThriftStruct& ts) {
using namespace apache::thrift::transport;
using namespace apache::thrift::protocol;
TMemoryBuffer* buffer = new TMemoryBuffer;
@@ -314,7 +333,7 @@
buffer->getBuffer(&buf, &size);
return std::string((char*)buf, (unsigned int)size);
}
-}
-} // apache::thrift
+
+}} // apache::thrift
#endif // #define _THRIFT_PROTOCOL_TJSONPROTOCOL_H_ 1
diff --git a/lib/cpp/src/thrift/protocol/TMultiplexedProtocol.cpp b/lib/cpp/src/thrift/protocol/TMultiplexedProtocol.cpp
index f0dc69e..756b9b9 100644
--- a/lib/cpp/src/thrift/protocol/TMultiplexedProtocol.cpp
+++ b/lib/cpp/src/thrift/protocol/TMultiplexedProtocol.cpp
@@ -21,20 +21,27 @@
#include <thrift/processor/TMultiplexedProcessor.h>
#include <thrift/protocol/TProtocolDecorator.h>
-namespace apache {
-namespace thrift {
-namespace protocol {
-uint32_t TMultiplexedProtocol::writeMessageBegin_virt(const std::string& _name,
- const TMessageType _type,
- const int32_t _seqid) {
- if (_type == T_CALL || _type == T_ONEWAY) {
- return TProtocolDecorator::writeMessageBegin_virt(serviceName + separator + _name,
- _type,
- _seqid);
- } else {
- return TProtocolDecorator::writeMessageBegin_virt(_name, _type, _seqid);
- }
+namespace apache
+{
+ namespace thrift
+ {
+ namespace protocol
+ {
+ uint32_t TMultiplexedProtocol::writeMessageBegin_virt(
+ const std::string& _name,
+ const TMessageType _type,
+ const int32_t _seqid)
+ {
+ if( _type == T_CALL || _type == T_ONEWAY )
+ {
+ return TProtocolDecorator::writeMessageBegin_virt( serviceName + separator + _name, _type, _seqid );
+ }
+ else
+ {
+ return TProtocolDecorator::writeMessageBegin_virt(_name, _type, _seqid);
+ }
+ }
+ }
+ }
}
-}
-}
-}
+
diff --git a/lib/cpp/src/thrift/protocol/TMultiplexedProtocol.h b/lib/cpp/src/thrift/protocol/TMultiplexedProtocol.h
index 0244fbe..e93f371 100644
--- a/lib/cpp/src/thrift/protocol/TMultiplexedProtocol.h
+++ b/lib/cpp/src/thrift/protocol/TMultiplexedProtocol.h
@@ -22,74 +22,82 @@
#include <thrift/protocol/TProtocolDecorator.h>
-namespace apache {
-namespace thrift {
-namespace protocol {
-using boost::shared_ptr;
+namespace apache
+{
+ namespace thrift
+ {
+ namespace protocol
+ {
+ using boost::shared_ptr;
-/**
- * <code>TMultiplexedProtocol</code> is a protocol-independent concrete decorator
- * that allows a Thrift client to communicate with a multiplexing Thrift server,
- * by prepending the service name to the function name during function calls.
- *
- * \note THIS IS NOT USED BY SERVERS. On the server, use
- * {@link apache::thrift::TMultiplexedProcessor TMultiplexedProcessor} to handle requests
- * from a multiplexing client.
- *
- * This example uses a single socket transport to invoke two services:
- *
- * <blockquote><code>
- * shared_ptr<TSocket> transport(new TSocket("localhost", 9090));
- * transport->open();
- *
- * shared_ptr<TBinaryProtocol> protocol(new TBinaryProtocol(transport));
- *
- * shared_ptr<TMultiplexedProtocol> mp1(new TMultiplexedProtocol(protocol, "Calculator"));
- * shared_ptr<CalculatorClient> service1(new CalculatorClient(mp1));
- *
- * shared_ptr<TMultiplexedProtocol> mp2(new TMultiplexedProtocol(protocol, "WeatherReport"));
- * shared_ptr<WeatherReportClient> service2(new WeatherReportClient(mp2));
- *
- * service1->add(2,2);
- * int temp = service2->getTemperature();
- * </code></blockquote>
- *
- * @see apache::thrift::protocol::TProtocolDecorator
- */
-class TMultiplexedProtocol : public TProtocolDecorator {
-public:
- /**
- * Wrap the specified protocol, allowing it to be used to communicate with a
- * multiplexing server. The <code>serviceName</code> is required as it is
- * prepended to the message header so that the multiplexing server can broker
- * the function call to the proper service.
- *
- * \param _protocol Your communication protocol of choice, e.g. <code>TBinaryProtocol</code>.
- * \param _serviceName The service name of the service communicating via this protocol.
- */
- TMultiplexedProtocol(shared_ptr<TProtocol> _protocol, const std::string& _serviceName)
- : TProtocolDecorator(_protocol), serviceName(_serviceName), separator(":") {}
- virtual ~TMultiplexedProtocol() {}
+ /**
+ * <code>TMultiplexedProtocol</code> is a protocol-independent concrete decorator
+ * that allows a Thrift client to communicate with a multiplexing Thrift server,
+ * by prepending the service name to the function name during function calls.
+ *
+ * \note THIS IS NOT USED BY SERVERS. On the server, use
+ * {@link apache::thrift::TMultiplexedProcessor TMultiplexedProcessor} to handle requests
+ * from a multiplexing client.
+ *
+ * This example uses a single socket transport to invoke two services:
+ *
+ * <blockquote><code>
+ * shared_ptr<TSocket> transport(new TSocket("localhost", 9090));
+ * transport->open();
+ *
+ * shared_ptr<TBinaryProtocol> protocol(new TBinaryProtocol(transport));
+ *
+ * shared_ptr<TMultiplexedProtocol> mp1(new TMultiplexedProtocol(protocol, "Calculator"));
+ * shared_ptr<CalculatorClient> service1(new CalculatorClient(mp1));
+ *
+ * shared_ptr<TMultiplexedProtocol> mp2(new TMultiplexedProtocol(protocol, "WeatherReport"));
+ * shared_ptr<WeatherReportClient> service2(new WeatherReportClient(mp2));
+ *
+ * service1->add(2,2);
+ * int temp = service2->getTemperature();
+ * </code></blockquote>
+ *
+ * @see apache::thrift::protocol::TProtocolDecorator
+ */
+ class TMultiplexedProtocol : public TProtocolDecorator
+ {
+ public:
+ /**
+ * Wrap the specified protocol, allowing it to be used to communicate with a
+ * multiplexing server. The <code>serviceName</code> is required as it is
+ * prepended to the message header so that the multiplexing server can broker
+ * the function call to the proper service.
+ *
+ * \param _protocol Your communication protocol of choice, e.g. <code>TBinaryProtocol</code>.
+ * \param _serviceName The service name of the service communicating via this protocol.
+ */
+ TMultiplexedProtocol( shared_ptr<TProtocol> _protocol, const std::string& _serviceName )
+ : TProtocolDecorator(_protocol),
+ serviceName(_serviceName),
+ separator(":")
+ { }
+ virtual ~TMultiplexedProtocol() {}
- /**
- * Prepends the service name to the function name, separated by TMultiplexedProtocol::SEPARATOR.
- *
- * \param [in] _name The name of the method to be called in the service.
- * \param [in] _type The type of message
- * \param [in] _name The sequential id of the message
- *
- * \throws TException Passed through from wrapped <code>TProtocol</code> instance.
- */
- uint32_t writeMessageBegin_virt(const std::string& _name,
- const TMessageType _type,
- const int32_t _seqid);
+ /**
+ * Prepends the service name to the function name, separated by TMultiplexedProtocol::SEPARATOR.
+ *
+ * \param [in] _name The name of the method to be called in the service.
+ * \param [in] _type The type of message
+ * \param [in] _name The sequential id of the message
+ *
+ * \throws TException Passed through from wrapped <code>TProtocol</code> instance.
+ */
+ uint32_t writeMessageBegin_virt(
+ const std::string& _name,
+ const TMessageType _type,
+ const int32_t _seqid);
+ private:
+ const std::string serviceName;
+ const std::string separator;
+ };
-private:
- const std::string serviceName;
- const std::string separator;
-};
-}
-}
+ }
+ }
}
#endif // THRIFT_TMULTIPLEXEDPROTOCOL_H_
diff --git a/lib/cpp/src/thrift/protocol/TProtocol.h b/lib/cpp/src/thrift/protocol/TProtocol.h
index 0c76cc0..d4c343d 100644
--- a/lib/cpp/src/thrift/protocol/TProtocol.h
+++ b/lib/cpp/src/thrift/protocol/TProtocol.h
@@ -34,6 +34,7 @@
#include <map>
#include <vector>
+
// Use this to get around strict aliasing rules.
// For example, uint64_t i = bitwise_cast<uint64_t>(returns_double());
// The most obvious implementation is to just cast a pointer,
@@ -135,9 +136,7 @@
# error "Can't define htonll or ntohll!"
#endif
-namespace apache {
-namespace thrift {
-namespace protocol {
+namespace apache { namespace thrift { namespace protocol {
using apache::thrift::transport::TTransport;
@@ -187,91 +186,98 @@
template <class Protocol_>
uint32_t skip(Protocol_& prot, TType type) {
switch (type) {
- case T_BOOL: {
- bool boolv;
- return prot.readBool(boolv);
- }
- case T_BYTE: {
- int8_t bytev;
- return prot.readByte(bytev);
- }
- case T_I16: {
- int16_t i16;
- return prot.readI16(i16);
- }
- case T_I32: {
- int32_t i32;
- return prot.readI32(i32);
- }
- case T_I64: {
- int64_t i64;
- return prot.readI64(i64);
- }
- case T_DOUBLE: {
- double dub;
- return prot.readDouble(dub);
- }
- case T_STRING: {
- std::string str;
- return prot.readBinary(str);
- }
- case T_STRUCT: {
- uint32_t result = 0;
- std::string name;
- int16_t fid;
- TType ftype;
- result += prot.readStructBegin(name);
- while (true) {
- result += prot.readFieldBegin(name, ftype, fid);
- if (ftype == T_STOP) {
- break;
+ case T_BOOL:
+ {
+ bool boolv;
+ return prot.readBool(boolv);
+ }
+ case T_BYTE:
+ {
+ int8_t bytev;
+ return prot.readByte(bytev);
+ }
+ case T_I16:
+ {
+ int16_t i16;
+ return prot.readI16(i16);
+ }
+ case T_I32:
+ {
+ int32_t i32;
+ return prot.readI32(i32);
+ }
+ case T_I64:
+ {
+ int64_t i64;
+ return prot.readI64(i64);
+ }
+ case T_DOUBLE:
+ {
+ double dub;
+ return prot.readDouble(dub);
+ }
+ case T_STRING:
+ {
+ std::string str;
+ return prot.readBinary(str);
+ }
+ case T_STRUCT:
+ {
+ uint32_t result = 0;
+ std::string name;
+ int16_t fid;
+ TType ftype;
+ result += prot.readStructBegin(name);
+ while (true) {
+ result += prot.readFieldBegin(name, ftype, fid);
+ if (ftype == T_STOP) {
+ break;
+ }
+ result += skip(prot, ftype);
+ result += prot.readFieldEnd();
}
- result += skip(prot, ftype);
- result += prot.readFieldEnd();
+ result += prot.readStructEnd();
+ return result;
}
- result += prot.readStructEnd();
- return result;
- }
- case T_MAP: {
- uint32_t result = 0;
- TType keyType;
- TType valType;
- uint32_t i, size;
- result += prot.readMapBegin(keyType, valType, size);
- for (i = 0; i < size; i++) {
- result += skip(prot, keyType);
- result += skip(prot, valType);
+ case T_MAP:
+ {
+ uint32_t result = 0;
+ TType keyType;
+ TType valType;
+ uint32_t i, size;
+ result += prot.readMapBegin(keyType, valType, size);
+ for (i = 0; i < size; i++) {
+ result += skip(prot, keyType);
+ result += skip(prot, valType);
+ }
+ result += prot.readMapEnd();
+ return result;
}
- result += prot.readMapEnd();
- return result;
- }
- case T_SET: {
- uint32_t result = 0;
- TType elemType;
- uint32_t i, size;
- result += prot.readSetBegin(elemType, size);
- for (i = 0; i < size; i++) {
- result += skip(prot, elemType);
+ case T_SET:
+ {
+ uint32_t result = 0;
+ TType elemType;
+ uint32_t i, size;
+ result += prot.readSetBegin(elemType, size);
+ for (i = 0; i < size; i++) {
+ result += skip(prot, elemType);
+ }
+ result += prot.readSetEnd();
+ return result;
}
- result += prot.readSetEnd();
- return result;
- }
- case T_LIST: {
- uint32_t result = 0;
- TType elemType;
- uint32_t i, size;
- result += prot.readListBegin(elemType, size);
- for (i = 0; i < size; i++) {
- result += skip(prot, elemType);
+ case T_LIST:
+ {
+ uint32_t result = 0;
+ TType elemType;
+ uint32_t i, size;
+ result += prot.readListBegin(elemType, size);
+ for (i = 0; i < size; i++) {
+ result += skip(prot, elemType);
+ }
+ result += prot.readListEnd();
+ return result;
}
- result += prot.readListEnd();
- return result;
- }
- case T_STOP:
- case T_VOID:
- case T_U64:
- case T_UTF8:
- case T_UTF16:
+ case T_STOP: case T_VOID: case T_U64: case T_UTF8: case T_UTF16:
break;
}
return 0;
@@ -294,7 +300,7 @@
*
*/
class TProtocol {
-public:
+ public:
virtual ~TProtocol() {}
/**
@@ -307,6 +313,7 @@
virtual uint32_t writeMessageEnd_virt() = 0;
+
virtual uint32_t writeStructBegin_virt(const char* name) = 0;
virtual uint32_t writeStructEnd_virt() = 0;
@@ -319,16 +326,19 @@
virtual uint32_t writeFieldStop_virt() = 0;
- virtual uint32_t writeMapBegin_virt(const TType keyType, const TType valType, const uint32_t size)
- = 0;
+ virtual uint32_t writeMapBegin_virt(const TType keyType,
+ const TType valType,
+ const uint32_t size) = 0;
virtual uint32_t writeMapEnd_virt() = 0;
- virtual uint32_t writeListBegin_virt(const TType elemType, const uint32_t size) = 0;
+ virtual uint32_t writeListBegin_virt(const TType elemType,
+ const uint32_t size) = 0;
virtual uint32_t writeListEnd_virt() = 0;
- virtual uint32_t writeSetBegin_virt(const TType elemType, const uint32_t size) = 0;
+ virtual uint32_t writeSetBegin_virt(const TType elemType,
+ const uint32_t size) = 0;
virtual uint32_t writeSetEnd_virt() = 0;
@@ -360,6 +370,7 @@
return writeMessageEnd_virt();
}
+
uint32_t writeStructBegin(const char* name) {
T_VIRTUAL_CALL();
return writeStructBegin_virt(name);
@@ -370,7 +381,9 @@
return writeStructEnd_virt();
}
- uint32_t writeFieldBegin(const char* name, const TType fieldType, const int16_t fieldId) {
+ uint32_t writeFieldBegin(const char* name,
+ const TType fieldType,
+ const int16_t fieldId) {
T_VIRTUAL_CALL();
return writeFieldBegin_virt(name, fieldType, fieldId);
}
@@ -385,7 +398,9 @@
return writeFieldStop_virt();
}
- uint32_t writeMapBegin(const TType keyType, const TType valType, const uint32_t size) {
+ uint32_t writeMapBegin(const TType keyType,
+ const TType valType,
+ const uint32_t size) {
T_VIRTUAL_CALL();
return writeMapBegin_virt(keyType, valType, size);
}
@@ -470,19 +485,24 @@
virtual uint32_t readStructEnd_virt() = 0;
virtual uint32_t readFieldBegin_virt(std::string& name,
- virtual uint32_t readFieldBegin_virt(std::string& name, TType& fieldType, int16_t& fieldId) = 0;
+ TType& fieldType,
+ int16_t& fieldId) = 0;
virtual uint32_t readFieldEnd_virt() = 0;
- virtual uint32_t readMapBegin_virt(TType& keyType, TType& valType, uint32_t& size) = 0;
+ virtual uint32_t readMapBegin_virt(TType& keyType,
+ TType& valType,
+ uint32_t& size) = 0;
virtual uint32_t readMapEnd_virt() = 0;
- virtual uint32_t readListBegin_virt(TType& elemType, uint32_t& size) = 0;
+ virtual uint32_t readListBegin_virt(TType& elemType,
+ uint32_t& size) = 0;
virtual uint32_t readListEnd_virt() = 0;
- virtual uint32_t readSetBegin_virt(TType& elemType, uint32_t& size) = 0;
+ virtual uint32_t readSetBegin_virt(TType& elemType,
+ uint32_t& size) = 0;
virtual uint32_t readSetEnd_virt() = 0;
@@ -504,7 +524,9 @@
virtual uint32_t readBinary_virt(std::string& str) = 0;
- uint32_t readMessageBegin(std::string& name, TMessageType& messageType, int32_t& seqid) {
+ uint32_t readMessageBegin(std::string& name,
+ TMessageType& messageType,
+ int32_t& seqid) {
T_VIRTUAL_CALL();
return readMessageBegin_virt(name, messageType, seqid);
}
@@ -524,7 +546,9 @@
return readStructEnd_virt();
}
- uint32_t readFieldBegin(std::string& name, TType& fieldType, int16_t& fieldId) {
+ uint32_t readFieldBegin(std::string& name,
+ TType& fieldType,
+ int16_t& fieldId) {
T_VIRTUAL_CALL();
return readFieldBegin_virt(name, fieldType, fieldId);
}
@@ -621,14 +645,22 @@
T_VIRTUAL_CALL();
return skip_virt(type);
}
- virtual uint32_t skip_virt(TType type) { return ::apache::thrift::protocol::skip(*this, type); }
+ virtual uint32_t skip_virt(TType type) {
+ return ::apache::thrift::protocol::skip(*this, type);
+ }
- inline boost::shared_ptr<TTransport> getTransport() { return ptrans_; }
+ inline boost::shared_ptr<TTransport> getTransport() {
+ return ptrans_;
+ }
// TODO: remove these two calls, they are for backwards
// compatibility
- inline boost::shared_ptr<TTransport> getInputTransport() { return ptrans_; }
- inline boost::shared_ptr<TTransport> getOutputTransport() { return ptrans_; }
+ inline boost::shared_ptr<TTransport> getInputTransport() {
+ return ptrans_;
+ }
+ inline boost::shared_ptr<TTransport> getOutputTransport() {
+ return ptrans_;
+ }
void incrementRecursionDepth() {
if (recursion_limit_ < ++recursion_depth_) {
@@ -636,15 +668,19 @@
}
}
- void decrementRecursionDepth() { --recursion_depth_; }
+ void decrementRecursionDepth() {
+ --recursion_depth_;
+ }
-protected:
+ protected:
TProtocol(boost::shared_ptr<TTransport> ptrans)
- : ptrans_(ptrans), recursion_depth_(0), recursion_limit_(DEFAULT_RECURSION_LIMIT) {}
+ : ptrans_(ptrans)
+ , recursion_depth_(0)
+ , recursion_limit_(DEFAULT_RECURSION_LIMIT) {}
boost::shared_ptr<TTransport> ptrans_;
-private:
+ private:
TProtocol() {}
uint32_t recursion_depth_;
uint32_t recursion_limit_;
@@ -654,7 +690,7 @@
* Constructs input and output protocol objects given transports.
*/
class TProtocolFactory {
-public:
+ public:
TProtocolFactory() {}
virtual ~TProtocolFactory() {}
@@ -668,9 +704,9 @@
* This class does nothing, and should never be instantiated.
* It is used only by the generator code.
*/
-class TDummyProtocol : public TProtocol {};
-}
-}
-} // apache::thrift::protocol
+class TDummyProtocol : public TProtocol {
+};
+
+}}} // apache::thrift::protocol
#endif // #define _THRIFT_PROTOCOL_TPROTOCOL_H_ 1
diff --git a/lib/cpp/src/thrift/protocol/TProtocolDecorator.h b/lib/cpp/src/thrift/protocol/TProtocolDecorator.h
index 446a81f..570e977 100644
--- a/lib/cpp/src/thrift/protocol/TProtocolDecorator.h
+++ b/lib/cpp/src/thrift/protocol/TProtocolDecorator.h
@@ -23,129 +23,111 @@
#include <thrift/protocol/TProtocol.h>
#include <boost/shared_ptr.hpp>
-namespace apache {
-namespace thrift {
-namespace protocol {
-using boost::shared_ptr;
+namespace apache
+{
+ namespace thrift
+ {
+ namespace protocol
+ {
+ using boost::shared_ptr;
-/**
- * <code>TProtocolDecorator</code> forwards all requests to an enclosed
- * <code>TProtocol</code> instance, providing a way to author concise
- * concrete decorator subclasses.
- *
- * <p>See p.175 of Design Patterns (by Gamma et al.)</p>
- *
- * @see apache::thrift::protocol::TMultiplexedProtocol
- */
-class TProtocolDecorator : public TProtocol {
-public:
- virtual ~TProtocolDecorator() {}
+ /**
+ * <code>TProtocolDecorator</code> forwards all requests to an enclosed
+ * <code>TProtocol</code> instance, providing a way to author concise
+ * concrete decorator subclasses.
+ *
+ * <p>See p.175 of Design Patterns (by Gamma et al.)</p>
+ *
+ * @see apache::thrift::protocol::TMultiplexedProtocol
+ */
+ class TProtocolDecorator : public TProtocol
+ {
+ public:
+ virtual ~TProtocolDecorator() {}
- // Desc: Initializes the protocol decorator object.
- TProtocolDecorator(shared_ptr<TProtocol> proto)
- : TProtocol(proto->getTransport()), protocol(proto) {}
+ // Desc: Initializes the protocol decorator object.
+ TProtocolDecorator( shared_ptr<TProtocol> proto )
+ : TProtocol(proto->getTransport()), protocol(proto)
+ {
+ }
- virtual uint32_t writeMessageBegin_virt(const std::string& name,
- const TMessageType messageType,
- const int32_t seqid) {
- return protocol->writeMessageBegin(name, messageType, seqid);
- }
- virtual uint32_t writeMessageEnd_virt() { return protocol->writeMessageEnd(); }
- virtual uint32_t writeStructBegin_virt(const char* name) {
- return protocol->writeStructBegin(name);
- }
- virtual uint32_t writeStructEnd_virt() { return protocol->writeStructEnd(); }
+ virtual uint32_t writeMessageBegin_virt(
+ const std::string& name,
+ const TMessageType messageType,
+ const int32_t seqid)
+ {
+ return protocol->writeMessageBegin(name, messageType, seqid);
+ }
+ virtual uint32_t writeMessageEnd_virt() { return protocol->writeMessageEnd(); }
+ virtual uint32_t writeStructBegin_virt(const char* name) { return protocol->writeStructBegin(name); }
+ virtual uint32_t writeStructEnd_virt() { return protocol->writeStructEnd(); }
- virtual uint32_t writeFieldBegin_virt(const char* name,
- const TType fieldType,
- const int16_t fieldId) {
- return protocol->writeFieldBegin(name, fieldType, fieldId);
- }
+ virtual uint32_t writeFieldBegin_virt(const char* name,
+ const TType fieldType,
+ const int16_t fieldId) { return protocol->writeFieldBegin(name,fieldType,fieldId); }
- virtual uint32_t writeFieldEnd_virt() { return protocol->writeFieldEnd(); }
- virtual uint32_t writeFieldStop_virt() { return protocol->writeFieldStop(); }
+ virtual uint32_t writeFieldEnd_virt() { return protocol->writeFieldEnd(); }
+ virtual uint32_t writeFieldStop_virt() { return protocol->writeFieldStop(); }
- virtual uint32_t writeMapBegin_virt(const TType keyType,
- const TType valType,
- const uint32_t size) {
- return protocol->writeMapBegin(keyType, valType, size);
- }
+ virtual uint32_t writeMapBegin_virt(const TType keyType,
+ const TType valType,
+ const uint32_t size) { return protocol->writeMapBegin(keyType,valType,size); }
- virtual uint32_t writeMapEnd_virt() { return protocol->writeMapEnd(); }
+ virtual uint32_t writeMapEnd_virt() { return protocol->writeMapEnd(); }
- virtual uint32_t writeListBegin_virt(const TType elemType, const uint32_t size) {
- return protocol->writeListBegin(elemType, size);
- }
- virtual uint32_t writeListEnd_virt() { return protocol->writeListEnd(); }
+ virtual uint32_t writeListBegin_virt(const TType elemType, const uint32_t size) { return protocol->writeListBegin(elemType,size); }
+ virtual uint32_t writeListEnd_virt() { return protocol->writeListEnd(); }
- virtual uint32_t writeSetBegin_virt(const TType elemType, const uint32_t size) {
- return protocol->writeSetBegin(elemType, size);
- }
- virtual uint32_t writeSetEnd_virt() { return protocol->writeSetEnd(); }
+ virtual uint32_t writeSetBegin_virt(const TType elemType, const uint32_t size) { return protocol->writeSetBegin(elemType,size); }
+ virtual uint32_t writeSetEnd_virt() { return protocol->writeSetEnd(); }
- virtual uint32_t writeBool_virt(const bool value) { return protocol->writeBool(value); }
- virtual uint32_t writeByte_virt(const int8_t byte) { return protocol->writeByte(byte); }
- virtual uint32_t writeI16_virt(const int16_t i16) { return protocol->writeI16(i16); }
- virtual uint32_t writeI32_virt(const int32_t i32) { return protocol->writeI32(i32); }
- virtual uint32_t writeI64_virt(const int64_t i64) { return protocol->writeI64(i64); }
+ virtual uint32_t writeBool_virt(const bool value) { return protocol->writeBool(value); }
+ virtual uint32_t writeByte_virt(const int8_t byte) { return protocol->writeByte(byte); }
+ virtual uint32_t writeI16_virt(const int16_t i16) { return protocol->writeI16(i16); }
+ virtual uint32_t writeI32_virt(const int32_t i32) { return protocol->writeI32(i32); }
+ virtual uint32_t writeI64_virt(const int64_t i64) { return protocol->writeI64(i64); }
- virtual uint32_t writeDouble_virt(const double dub) { return protocol->writeDouble(dub); }
- virtual uint32_t writeString_virt(const std::string& str) { return protocol->writeString(str); }
- virtual uint32_t writeBinary_virt(const std::string& str) { return protocol->writeBinary(str); }
+ virtual uint32_t writeDouble_virt(const double dub) { return protocol->writeDouble(dub); }
+ virtual uint32_t writeString_virt(const std::string& str) { return protocol->writeString(str); }
+ virtual uint32_t writeBinary_virt(const std::string& str) { return protocol->writeBinary(str); }
- virtual uint32_t readMessageBegin_virt(std::string& name,
- TMessageType& messageType,
- int32_t& seqid) {
- return protocol->readMessageBegin(name, messageType, seqid);
- }
- virtual uint32_t readMessageEnd_virt() { return protocol->readMessageEnd(); }
+ virtual uint32_t readMessageBegin_virt(std::string& name, TMessageType& messageType, int32_t& seqid) { return protocol->readMessageBegin(name,messageType,seqid); }
+ virtual uint32_t readMessageEnd_virt() { return protocol->readMessageEnd(); }
- virtual uint32_t readStructBegin_virt(std::string& name) {
- return protocol->readStructBegin(name);
- }
- virtual uint32_t readStructEnd_virt() { return protocol->readStructEnd(); }
+ virtual uint32_t readStructBegin_virt(std::string& name) { return protocol->readStructBegin(name); }
+ virtual uint32_t readStructEnd_virt() { return protocol->readStructEnd(); }
- virtual uint32_t readFieldBegin_virt(std::string& name, TType& fieldType, int16_t& fieldId) {
- return protocol->readFieldBegin(name, fieldType, fieldId);
- }
- virtual uint32_t readFieldEnd_virt() { return protocol->readFieldEnd(); }
+ virtual uint32_t readFieldBegin_virt(std::string& name, TType& fieldType, int16_t& fieldId) { return protocol->readFieldBegin(name, fieldType, fieldId); }
+ virtual uint32_t readFieldEnd_virt() { return protocol->readFieldEnd(); }
- virtual uint32_t readMapBegin_virt(TType& keyType, TType& valType, uint32_t& size) {
- return protocol->readMapBegin(keyType, valType, size);
- }
- virtual uint32_t readMapEnd_virt() { return protocol->readMapEnd(); }
+ virtual uint32_t readMapBegin_virt(TType& keyType, TType& valType, uint32_t& size) { return protocol->readMapBegin(keyType,valType,size); }
+ virtual uint32_t readMapEnd_virt() { return protocol->readMapEnd(); }
- virtual uint32_t readListBegin_virt(TType& elemType, uint32_t& size) {
- return protocol->readListBegin(elemType, size);
- }
- virtual uint32_t readListEnd_virt() { return protocol->readListEnd(); }
+ virtual uint32_t readListBegin_virt(TType& elemType, uint32_t& size) { return protocol->readListBegin(elemType,size); }
+ virtual uint32_t readListEnd_virt() { return protocol->readListEnd(); }
- virtual uint32_t readSetBegin_virt(TType& elemType, uint32_t& size) {
- return protocol->readSetBegin(elemType, size);
- }
- virtual uint32_t readSetEnd_virt() { return protocol->readSetEnd(); }
+ virtual uint32_t readSetBegin_virt(TType& elemType, uint32_t& size) { return protocol->readSetBegin(elemType,size); }
+ virtual uint32_t readSetEnd_virt() { return protocol->readSetEnd(); }
- virtual uint32_t readBool_virt(bool& value) { return protocol->readBool(value); }
- virtual uint32_t readBool_virt(std::vector<bool>::reference value) {
- return protocol->readBool(value);
- }
+ virtual uint32_t readBool_virt(bool& value) { return protocol->readBool(value); }
+ virtual uint32_t readBool_virt(std::vector<bool>::reference value) { return protocol->readBool(value); }
- virtual uint32_t readByte_virt(int8_t& byte) { return protocol->readByte(byte); }
+ virtual uint32_t readByte_virt(int8_t& byte) { return protocol->readByte(byte); }
- virtual uint32_t readI16_virt(int16_t& i16) { return protocol->readI16(i16); }
- virtual uint32_t readI32_virt(int32_t& i32) { return protocol->readI32(i32); }
- virtual uint32_t readI64_virt(int64_t& i64) { return protocol->readI64(i64); }
+ virtual uint32_t readI16_virt(int16_t& i16) { return protocol->readI16(i16); }
+ virtual uint32_t readI32_virt(int32_t& i32) { return protocol->readI32(i32); }
+ virtual uint32_t readI64_virt(int64_t& i64) { return protocol->readI64(i64); }
- virtual uint32_t readDouble_virt(double& dub) { return protocol->readDouble(dub); }
+ virtual uint32_t readDouble_virt(double& dub) { return protocol->readDouble(dub); }
- virtual uint32_t readString_virt(std::string& str) { return protocol->readString(str); }
- virtual uint32_t readBinary_virt(std::string& str) { return protocol->readBinary(str); }
+ virtual uint32_t readString_virt(std::string& str) { return protocol->readString(str); }
+ virtual uint32_t readBinary_virt(std::string& str) { return protocol->readBinary(str); }
-private:
- shared_ptr<TProtocol> protocol;
-};
-}
-}
+ private:
+ shared_ptr<TProtocol> protocol;
+ };
+ }
+ }
}
#endif // THRIFT_TPROTOCOLDECORATOR_H_
diff --git a/lib/cpp/src/thrift/protocol/TProtocolException.h b/lib/cpp/src/thrift/protocol/TProtocolException.h
index 18a8ed0..4ddb81e 100644
--- a/lib/cpp/src/thrift/protocol/TProtocolException.h
+++ b/lib/cpp/src/thrift/protocol/TProtocolException.h
@@ -22,9 +22,7 @@
#include <string>
-namespace apache {
-namespace thrift {
-namespace protocol {
+namespace apache { namespace thrift { namespace protocol {
/**
* Class to encapsulate all the possible types of protocol errors that may
@@ -35,29 +33,36 @@
*
*/
class TProtocolException : public apache::thrift::TException {
-public:
+ public:
+
/**
* Error codes for the various types of exceptions.
*/
- enum TProtocolExceptionType {
- UNKNOWN = 0,
- INVALID_DATA = 1,
- NEGATIVE_SIZE = 2,
- SIZE_LIMIT = 3,
- BAD_VERSION = 4,
- NOT_IMPLEMENTED = 5,
- DEPTH_LIMIT = 6
+ enum TProtocolExceptionType
+ { UNKNOWN = 0
+ , INVALID_DATA = 1
+ , NEGATIVE_SIZE = 2
+ , SIZE_LIMIT = 3
+ , BAD_VERSION = 4
+ , NOT_IMPLEMENTED = 5
+ , DEPTH_LIMIT = 6
};
- TProtocolException() : apache::thrift::TException(), type_(UNKNOWN) {}
+ TProtocolException() :
+ apache::thrift::TException(),
+ type_(UNKNOWN) {}
- TProtocolException(TProtocolExceptionType type) : apache::thrift::TException(), type_(type) {}
+ TProtocolException(TProtocolExceptionType type) :
+ apache::thrift::TException(),
+ type_(type) {}
- TProtocolException(const std::string& message)
- : apache::thrift::TException(message), type_(UNKNOWN) {}
+ TProtocolException(const std::string& message) :
+ apache::thrift::TException(message),
+ type_(UNKNOWN) {}
- TProtocolException(TProtocolExceptionType type, const std::string& message)
- : apache::thrift::TException(message), type_(type) {}
+ TProtocolException(TProtocolExceptionType type, const std::string& message) :
+ apache::thrift::TException(message),
+ type_(type) {}
virtual ~TProtocolException() throw() {}
@@ -67,39 +72,34 @@
*
* @return Error code
*/
- TProtocolExceptionType getType() { return type_; }
+ TProtocolExceptionType getType() {
+ return type_;
+ }
virtual const char* what() const throw() {
if (message_.empty()) {
switch (type_) {
- case UNKNOWN:
- return "TProtocolException: Unknown protocol exception";
- case INVALID_DATA:
- return "TProtocolException: Invalid data";
- case NEGATIVE_SIZE:
- return "TProtocolException: Negative size";
- case SIZE_LIMIT:
- return "TProtocolException: Exceeded size limit";
- case BAD_VERSION:
- return "TProtocolException: Invalid version";
- case NOT_IMPLEMENTED:
- return "TProtocolException: Not implemented";
- default:
- return "TProtocolException: (Invalid exception type)";
+ case UNKNOWN : return "TProtocolException: Unknown protocol exception";
+ case INVALID_DATA : return "TProtocolException: Invalid data";
+ case NEGATIVE_SIZE : return "TProtocolException: Negative size";
+ case SIZE_LIMIT : return "TProtocolException: Exceeded size limit";
+ case BAD_VERSION : return "TProtocolException: Invalid version";
+ case NOT_IMPLEMENTED : return "TProtocolException: Not implemented";
+ default : return "TProtocolException: (Invalid exception type)";
}
} else {
return message_.c_str();
}
}
-protected:
+ protected:
/**
* Error code
*/
TProtocolExceptionType type_;
+
};
-}
-}
-} // apache::thrift::protocol
+
+}}} // apache::thrift::protocol
#endif // #ifndef _THRIFT_PROTOCOL_TPROTOCOLEXCEPTION_H_
diff --git a/lib/cpp/src/thrift/protocol/TProtocolTap.h b/lib/cpp/src/thrift/protocol/TProtocolTap.h
index 3e56393..f493f88 100644
--- a/lib/cpp/src/thrift/protocol/TProtocolTap.h
+++ b/lib/cpp/src/thrift/protocol/TProtocolTap.h
@@ -22,9 +22,7 @@
#include <thrift/protocol/TVirtualProtocol.h>
-namespace apache {
-namespace thrift {
-namespace protocol {
+namespace apache { namespace thrift { namespace protocol {
using apache::thrift::transport::TTransport;
@@ -35,11 +33,17 @@
*
*/
class TProtocolTap : public TVirtualProtocol<TProtocolTap> {
-public:
- TProtocolTap(boost::shared_ptr<TProtocol> source, boost::shared_ptr<TProtocol> sink)
- : TVirtualProtocol<TProtocolTap>(source->getTransport()), source_(source), sink_(sink) {}
+ public:
+ TProtocolTap(boost::shared_ptr<TProtocol> source,
+ boost::shared_ptr<TProtocol> sink)
+ : TVirtualProtocol<TProtocolTap>(source->getTransport())
+ , source_(source)
+ , sink_(sink)
+ {}
- uint32_t readMessageBegin(std::string& name, TMessageType& messageType, int32_t& seqid) {
+ uint32_t readMessageBegin(std::string& name,
+ TMessageType& messageType,
+ int32_t& seqid) {
uint32_t rv = source_->readMessageBegin(name, messageType, seqid);
sink_->writeMessageBegin(name, messageType, seqid);
return rv;
@@ -63,7 +67,9 @@
return rv;
}
- uint32_t readFieldBegin(std::string& name, TType& fieldType, int16_t& fieldId) {
+ uint32_t readFieldBegin(std::string& name,
+ TType& fieldType,
+ int16_t& fieldId) {
uint32_t rv = source_->readFieldBegin(name, fieldType, fieldId);
if (fieldType == T_STOP) {
sink_->writeFieldStop();
@@ -73,18 +79,22 @@
return rv;
}
+
uint32_t readFieldEnd() {
uint32_t rv = source_->readFieldEnd();
sink_->writeFieldEnd();
return rv;
}
- uint32_t readMapBegin(TType& keyType, TType& valType, uint32_t& size) {
+ uint32_t readMapBegin(TType& keyType,
+ TType& valType,
+ uint32_t& size) {
uint32_t rv = source_->readMapBegin(keyType, valType, size);
sink_->writeMapBegin(keyType, valType, size);
return rv;
}
+
uint32_t readMapEnd() {
uint32_t rv = source_->readMapEnd();
sink_->writeMapEnd();
@@ -97,6 +107,7 @@
return rv;
}
+
uint32_t readListEnd() {
uint32_t rv = source_->readListEnd();
sink_->writeListEnd();
@@ -109,6 +120,7 @@
return rv;
}
+
uint32_t readSetEnd() {
uint32_t rv = source_->readSetEnd();
sink_->writeSetEnd();
@@ -166,12 +178,11 @@
return rv;
}
-private:
+ private:
boost::shared_ptr<TProtocol> source_;
boost::shared_ptr<TProtocol> sink_;
};
-}
-}
-} // apache::thrift::protocol
+
+}}} // apache::thrift::protocol
#endif // #define _THRIFT_PROTOCOL_TPROTOCOLTAP_H_ 1
diff --git a/lib/cpp/src/thrift/protocol/TVirtualProtocol.h b/lib/cpp/src/thrift/protocol/TVirtualProtocol.h
index 831c3a2..e068725 100644
--- a/lib/cpp/src/thrift/protocol/TVirtualProtocol.h
+++ b/lib/cpp/src/thrift/protocol/TVirtualProtocol.h
@@ -22,9 +22,7 @@
#include <thrift/protocol/TProtocol.h>
-namespace apache {
-namespace thrift {
-namespace protocol {
+namespace apache { namespace thrift { namespace protocol {
using apache::thrift::transport::TTransport;
@@ -40,11 +38,13 @@
* instead.
*/
class TProtocolDefaults : public TProtocol {
-public:
- uint32_t readMessageBegin(std::string& name, TMessageType& messageType, int32_t& seqid) {
- (void)name;
- (void)messageType;
- (void)seqid;
+ public:
+ uint32_t readMessageBegin(std::string& name,
+ TMessageType& messageType,
+ int32_t& seqid) {
+ (void) name;
+ (void) messageType;
+ (void) seqid;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support reading (yet).");
}
@@ -55,7 +55,7 @@
}
uint32_t readStructBegin(std::string& name) {
- (void)name;
+ (void) name;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support reading (yet).");
}
@@ -65,10 +65,12 @@
"this protocol does not support reading (yet).");
}
- uint32_t readFieldBegin(std::string& name, TType& fieldType, int16_t& fieldId) {
- (void)name;
- (void)fieldType;
- (void)fieldId;
+ uint32_t readFieldBegin(std::string& name,
+ TType& fieldType,
+ int16_t& fieldId) {
+ (void) name;
+ (void) fieldType;
+ (void) fieldId;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support reading (yet).");
}
@@ -79,9 +81,9 @@
}
uint32_t readMapBegin(TType& keyType, TType& valType, uint32_t& size) {
- (void)keyType;
- (void)valType;
- (void)size;
+ (void) keyType;
+ (void) valType;
+ (void) size;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support reading (yet).");
}
@@ -92,8 +94,8 @@
}
uint32_t readListBegin(TType& elemType, uint32_t& size) {
- (void)elemType;
- (void)size;
+ (void) elemType;
+ (void) size;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support reading (yet).");
}
@@ -104,8 +106,8 @@
}
uint32_t readSetBegin(TType& elemType, uint32_t& size) {
- (void)elemType;
- (void)size;
+ (void) elemType;
+ (void) size;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support reading (yet).");
}
@@ -116,55 +118,55 @@
}
uint32_t readBool(bool& value) {
- (void)value;
+ (void) value;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support reading (yet).");
}
uint32_t readBool(std::vector<bool>::reference value) {
- (void)value;
+ (void) value;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support reading (yet).");
}
uint32_t readByte(int8_t& byte) {
- (void)byte;
+ (void) byte;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support reading (yet).");
}
uint32_t readI16(int16_t& i16) {
- (void)i16;
+ (void) i16;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support reading (yet).");
}
uint32_t readI32(int32_t& i32) {
- (void)i32;
+ (void) i32;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support reading (yet).");
}
uint32_t readI64(int64_t& i64) {
- (void)i64;
+ (void) i64;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support reading (yet).");
}
uint32_t readDouble(double& dub) {
- (void)dub;
+ (void) dub;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support reading (yet).");
}
uint32_t readString(std::string& str) {
- (void)str;
+ (void) str;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support reading (yet).");
}
uint32_t readBinary(std::string& str) {
- (void)str;
+ (void) str;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support reading (yet).");
}
@@ -172,9 +174,9 @@
uint32_t writeMessageBegin(const std::string& name,
const TMessageType messageType,
const int32_t seqid) {
- (void)name;
- (void)messageType;
- (void)seqid;
+ (void) name;
+ (void) messageType;
+ (void) seqid;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support writing (yet).");
}
@@ -184,8 +186,9 @@
"this protocol does not support writing (yet).");
}
+
uint32_t writeStructBegin(const char* name) {
- (void)name;
+ (void) name;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support writing (yet).");
}
@@ -195,10 +198,12 @@
"this protocol does not support writing (yet).");
}
- uint32_t writeFieldBegin(const char* name, const TType fieldType, const int16_t fieldId) {
- (void)name;
- (void)fieldType;
- (void)fieldId;
+ uint32_t writeFieldBegin(const char* name,
+ const TType fieldType,
+ const int16_t fieldId) {
+ (void) name;
+ (void) fieldType;
+ (void) fieldId;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support writing (yet).");
}
@@ -213,10 +218,12 @@
"this protocol does not support writing (yet).");
}
- uint32_t writeMapBegin(const TType keyType, const TType valType, const uint32_t size) {
- (void)keyType;
- (void)valType;
- (void)size;
+ uint32_t writeMapBegin(const TType keyType,
+ const TType valType,
+ const uint32_t size) {
+ (void) keyType;
+ (void) valType;
+ (void) size;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support writing (yet).");
}
@@ -227,8 +234,8 @@
}
uint32_t writeListBegin(const TType elemType, const uint32_t size) {
- (void)elemType;
- (void)size;
+ (void) elemType;
+ (void) size;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support writing (yet).");
}
@@ -239,8 +246,8 @@
}
uint32_t writeSetBegin(const TType elemType, const uint32_t size) {
- (void)elemType;
- (void)size;
+ (void) elemType;
+ (void) size;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support writing (yet).");
}
@@ -251,66 +258,70 @@
}
uint32_t writeBool(const bool value) {
- (void)value;
+ (void) value;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support writing (yet).");
}
uint32_t writeByte(const int8_t byte) {
- (void)byte;
+ (void) byte;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support writing (yet).");
}
uint32_t writeI16(const int16_t i16) {
- (void)i16;
+ (void) i16;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support writing (yet).");
}
uint32_t writeI32(const int32_t i32) {
- (void)i32;
+ (void) i32;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support writing (yet).");
}
uint32_t writeI64(const int64_t i64) {
- (void)i64;
+ (void) i64;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support writing (yet).");
}
uint32_t writeDouble(const double dub) {
- (void)dub;
+ (void) dub;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support writing (yet).");
}
uint32_t writeString(const std::string& str) {
- (void)str;
+ (void) str;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support writing (yet).");
}
uint32_t writeBinary(const std::string& str) {
- (void)str;
+ (void) str;
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"this protocol does not support writing (yet).");
}
- uint32_t skip(TType type) { return ::apache::thrift::protocol::skip(*this, type); }
+ uint32_t skip(TType type) {
+ return ::apache::thrift::protocol::skip(*this, type);
+ }
-protected:
- TProtocolDefaults(boost::shared_ptr<TTransport> ptrans) : TProtocol(ptrans) {}
+ protected:
+ TProtocolDefaults(boost::shared_ptr<TTransport> ptrans)
+ : TProtocol(ptrans)
+ {}
};
/**
* Concrete TProtocol classes should inherit from TVirtualProtocol
* so they don't have to manually override virtual methods.
*/
-template <class Protocol_, class Super_ = TProtocolDefaults>
+template <class Protocol_, class Super_=TProtocolDefaults>
class TVirtualProtocol : public Super_ {
-public:
+ public:
/**
* Writing functions.
*/
@@ -318,28 +329,37 @@
virtual uint32_t writeMessageBegin_virt(const std::string& name,
const TMessageType messageType,
const int32_t seqid) {
- return static_cast<Protocol_*>(this)->writeMessageBegin(name, messageType, seqid);
+ return static_cast<Protocol_*>(this)->writeMessageBegin(name, messageType,
+ seqid);
}
virtual uint32_t writeMessageEnd_virt() {
return static_cast<Protocol_*>(this)->writeMessageEnd();
}
+
virtual uint32_t writeStructBegin_virt(const char* name) {
return static_cast<Protocol_*>(this)->writeStructBegin(name);
}
- virtual uint32_t writeStructEnd_virt() { return static_cast<Protocol_*>(this)->writeStructEnd(); }
+ virtual uint32_t writeStructEnd_virt() {
+ return static_cast<Protocol_*>(this)->writeStructEnd();
+ }
virtual uint32_t writeFieldBegin_virt(const char* name,
const TType fieldType,
const int16_t fieldId) {
- return static_cast<Protocol_*>(this)->writeFieldBegin(name, fieldType, fieldId);
+ return static_cast<Protocol_*>(this)->writeFieldBegin(name, fieldType,
+ fieldId);
}
- virtual uint32_t writeFieldEnd_virt() { return static_cast<Protocol_*>(this)->writeFieldEnd(); }
+ virtual uint32_t writeFieldEnd_virt() {
+ return static_cast<Protocol_*>(this)->writeFieldEnd();
+ }
- virtual uint32_t writeFieldStop_virt() { return static_cast<Protocol_*>(this)->writeFieldStop(); }
+ virtual uint32_t writeFieldStop_virt() {
+ return static_cast<Protocol_*>(this)->writeFieldStop();
+ }
virtual uint32_t writeMapBegin_virt(const TType keyType,
const TType valType,
@@ -347,19 +367,27 @@
return static_cast<Protocol_*>(this)->writeMapBegin(keyType, valType, size);
}
- virtual uint32_t writeMapEnd_virt() { return static_cast<Protocol_*>(this)->writeMapEnd(); }
+ virtual uint32_t writeMapEnd_virt() {
+ return static_cast<Protocol_*>(this)->writeMapEnd();
+ }
- virtual uint32_t writeListBegin_virt(const TType elemType, const uint32_t size) {
+ virtual uint32_t writeListBegin_virt(const TType elemType,
+ const uint32_t size) {
return static_cast<Protocol_*>(this)->writeListBegin(elemType, size);
}
- virtual uint32_t writeListEnd_virt() { return static_cast<Protocol_*>(this)->writeListEnd(); }
+ virtual uint32_t writeListEnd_virt() {
+ return static_cast<Protocol_*>(this)->writeListEnd();
+ }
- virtual uint32_t writeSetBegin_virt(const TType elemType, const uint32_t size) {
+ virtual uint32_t writeSetBegin_virt(const TType elemType,
+ const uint32_t size) {
return static_cast<Protocol_*>(this)->writeSetBegin(elemType, size);
}
- virtual uint32_t writeSetEnd_virt() { return static_cast<Protocol_*>(this)->writeSetEnd(); }
+ virtual uint32_t writeSetEnd_virt() {
+ return static_cast<Protocol_*>(this)->writeSetEnd();
+ }
virtual uint32_t writeBool_virt(const bool value) {
return static_cast<Protocol_*>(this)->writeBool(value);
@@ -400,40 +428,60 @@
virtual uint32_t readMessageBegin_virt(std::string& name,
TMessageType& messageType,
int32_t& seqid) {
- return static_cast<Protocol_*>(this)->readMessageBegin(name, messageType, seqid);
+ return static_cast<Protocol_*>(this)->readMessageBegin(name, messageType,
+ seqid);
}
- virtual uint32_t readMessageEnd_virt() { return static_cast<Protocol_*>(this)->readMessageEnd(); }
+ virtual uint32_t readMessageEnd_virt() {
+ return static_cast<Protocol_*>(this)->readMessageEnd();
+ }
virtual uint32_t readStructBegin_virt(std::string& name) {
return static_cast<Protocol_*>(this)->readStructBegin(name);
}
- virtual uint32_t readStructEnd_virt() { return static_cast<Protocol_*>(this)->readStructEnd(); }
-
- virtual uint32_t readFieldBegin_virt(std::string& name, TType& fieldType, int16_t& fieldId) {
- return static_cast<Protocol_*>(this)->readFieldBegin(name, fieldType, fieldId);
+ virtual uint32_t readStructEnd_virt() {
+ return static_cast<Protocol_*>(this)->readStructEnd();
}
- virtual uint32_t readFieldEnd_virt() { return static_cast<Protocol_*>(this)->readFieldEnd(); }
+ virtual uint32_t readFieldBegin_virt(std::string& name,
+ TType& fieldType,
+ int16_t& fieldId) {
+ return static_cast<Protocol_*>(this)->readFieldBegin(name, fieldType,
+ fieldId);
+ }
- virtual uint32_t readMapBegin_virt(TType& keyType, TType& valType, uint32_t& size) {
+ virtual uint32_t readFieldEnd_virt() {
+ return static_cast<Protocol_*>(this)->readFieldEnd();
+ }
+
+ virtual uint32_t readMapBegin_virt(TType& keyType,
+ TType& valType,
+ uint32_t& size) {
return static_cast<Protocol_*>(this)->readMapBegin(keyType, valType, size);
}
- virtual uint32_t readMapEnd_virt() { return static_cast<Protocol_*>(this)->readMapEnd(); }
+ virtual uint32_t readMapEnd_virt() {
+ return static_cast<Protocol_*>(this)->readMapEnd();
+ }
- virtual uint32_t readListBegin_virt(TType& elemType, uint32_t& size) {
+ virtual uint32_t readListBegin_virt(TType& elemType,
+ uint32_t& size) {
return static_cast<Protocol_*>(this)->readListBegin(elemType, size);
}
- virtual uint32_t readListEnd_virt() { return static_cast<Protocol_*>(this)->readListEnd(); }
+ virtual uint32_t readListEnd_virt() {
+ return static_cast<Protocol_*>(this)->readListEnd();
+ }
- virtual uint32_t readSetBegin_virt(TType& elemType, uint32_t& size) {
+ virtual uint32_t readSetBegin_virt(TType& elemType,
+ uint32_t& size) {
return static_cast<Protocol_*>(this)->readSetBegin(elemType, size);
}
- virtual uint32_t readSetEnd_virt() { return static_cast<Protocol_*>(this)->readSetEnd(); }
+ virtual uint32_t readSetEnd_virt() {
+ return static_cast<Protocol_*>(this)->readSetEnd();
+ }
virtual uint32_t readBool_virt(bool& value) {
return static_cast<Protocol_*>(this)->readBool(value);
@@ -471,7 +519,9 @@
return static_cast<Protocol_*>(this)->readBinary(str);
}
- virtual uint32_t skip_virt(TType type) { return static_cast<Protocol_*>(this)->skip(type); }
+ virtual uint32_t skip_virt(TType type) {
+ return static_cast<Protocol_*>(this)->skip(type);
+ }
/*
* Provide a default skip() implementation that uses non-virtual read
@@ -503,11 +553,12 @@
}
using Super_::readBool; // so we don't hide readBool(bool&)
-protected:
- TVirtualProtocol(boost::shared_ptr<TTransport> ptrans) : Super_(ptrans) {}
+ protected:
+ TVirtualProtocol(boost::shared_ptr<TTransport> ptrans)
+ : Super_(ptrans)
+ {}
};
-}
-}
-} // apache::thrift::protocol
+
+}}} // apache::thrift::protocol
#endif // #define _THRIFT_PROTOCOL_TVIRTUALPROTOCOL_H_ 1
diff --git a/lib/cpp/src/thrift/qt/TQIODeviceTransport.cpp b/lib/cpp/src/thrift/qt/TQIODeviceTransport.cpp
index 686f242..2c82847 100644
--- a/lib/cpp/src/thrift/qt/TQIODeviceTransport.cpp
+++ b/lib/cpp/src/thrift/qt/TQIODeviceTransport.cpp
@@ -26,37 +26,43 @@
using boost::shared_ptr;
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
-TQIODeviceTransport::TQIODeviceTransport(shared_ptr<QIODevice> dev) : dev_(dev) {
+TQIODeviceTransport::TQIODeviceTransport(shared_ptr<QIODevice> dev)
+ : dev_(dev)
+{
}
-TQIODeviceTransport::~TQIODeviceTransport() {
+TQIODeviceTransport::~TQIODeviceTransport()
+{
dev_->close();
}
-void TQIODeviceTransport::open() {
+void TQIODeviceTransport::open()
+{
if (!isOpen()) {
throw TTransportException(TTransportException::NOT_OPEN,
"open(): underlying QIODevice isn't open");
}
}
-bool TQIODeviceTransport::isOpen() {
+bool TQIODeviceTransport::isOpen()
+{
return dev_->isOpen();
}
-bool TQIODeviceTransport::peek() {
+bool TQIODeviceTransport::peek()
+{
return dev_->bytesAvailable() > 0;
}
-void TQIODeviceTransport::close() {
+void TQIODeviceTransport::close()
+{
dev_->close();
}
-uint32_t TQIODeviceTransport::readAll(uint8_t* buf, uint32_t len) {
+uint32_t TQIODeviceTransport::readAll(uint8_t* buf, uint32_t len)
+{
uint32_t requestLen = len;
while (len) {
uint32_t readSize;
@@ -80,7 +86,8 @@
return requestLen;
}
-uint32_t TQIODeviceTransport::read(uint8_t* buf, uint32_t len) {
+uint32_t TQIODeviceTransport::read(uint8_t* buf, uint32_t len)
+{
uint32_t actualSize;
qint64 readSize;
@@ -90,22 +97,24 @@
}
actualSize = (uint32_t)std::min((qint64)len, dev_->bytesAvailable());
- readSize = dev_->read(reinterpret_cast<char*>(buf), actualSize);
+ readSize = dev_->read(reinterpret_cast<char *>(buf), actualSize);
if (readSize < 0) {
QAbstractSocket* socket;
- if ((socket = qobject_cast<QAbstractSocket*>(dev_.get()))) {
+ if ((socket = qobject_cast<QAbstractSocket* >(dev_.get()))) {
throw TTransportException(TTransportException::UNKNOWN,
"Failed to read() from QAbstractSocket",
socket->error());
}
- throw TTransportException(TTransportException::UNKNOWN, "Failed to read from from QIODevice");
+ throw TTransportException(TTransportException::UNKNOWN,
+ "Failed to read from from QIODevice");
}
return (uint32_t)readSize;
}
-void TQIODeviceTransport::write(const uint8_t* buf, uint32_t len) {
+void TQIODeviceTransport::write(const uint8_t* buf, uint32_t len)
+{
while (len) {
uint32_t written = write_partial(buf, len);
len -= written;
@@ -113,7 +122,8 @@
}
}
-uint32_t TQIODeviceTransport::write_partial(const uint8_t* buf, uint32_t len) {
+uint32_t TQIODeviceTransport::write_partial(const uint8_t* buf, uint32_t len)
+{
qint64 written;
if (!dev_->isOpen()) {
@@ -126,8 +136,7 @@
QAbstractSocket* socket;
if ((socket = qobject_cast<QAbstractSocket*>(dev_.get()))) {
throw TTransportException(TTransportException::UNKNOWN,
- "write_partial(): failed to write to QAbstractSocket",
- socket->error());
+ "write_partial(): failed to write to QAbstractSocket", socket->error());
}
throw TTransportException(TTransportException::UNKNOWN,
@@ -137,7 +146,8 @@
return (uint32_t)written;
}
-void TQIODeviceTransport::flush() {
+void TQIODeviceTransport::flush()
+{
if (!dev_->isOpen()) {
throw TTransportException(TTransportException::NOT_OPEN,
"flush(): underlying QIODevice is not open");
@@ -152,16 +162,18 @@
}
}
-uint8_t* TQIODeviceTransport::borrow(uint8_t* buf, uint32_t* len) {
- (void)buf;
- (void)len;
+uint8_t* TQIODeviceTransport::borrow(uint8_t* buf, uint32_t* len)
+{
+ (void) buf;
+ (void) len;
return NULL;
}
-void TQIODeviceTransport::consume(uint32_t len) {
- (void)len;
+void TQIODeviceTransport::consume(uint32_t len)
+{
+ (void) len;
throw TTransportException(TTransportException::UNKNOWN);
}
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
+
diff --git a/lib/cpp/src/thrift/qt/TQIODeviceTransport.h b/lib/cpp/src/thrift/qt/TQIODeviceTransport.h
index 8091d32..c5221dd 100644
--- a/lib/cpp/src/thrift/qt/TQIODeviceTransport.h
+++ b/lib/cpp/src/thrift/qt/TQIODeviceTransport.h
@@ -26,16 +26,13 @@
class QIODevice;
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
/**
* Transport that operates on a QIODevice (socket, file, etc).
*/
-class TQIODeviceTransport
- : public apache::thrift::transport::TVirtualTransport<TQIODeviceTransport> {
-public:
+class TQIODeviceTransport : public apache::thrift::transport::TVirtualTransport<TQIODeviceTransport> {
+ public:
explicit TQIODeviceTransport(boost::shared_ptr<QIODevice> dev);
virtual ~TQIODeviceTransport();
@@ -44,7 +41,7 @@
bool peek();
void close();
- uint32_t readAll(uint8_t* buf, uint32_t len);
+ uint32_t readAll(uint8_t *buf, uint32_t len);
uint32_t read(uint8_t* buf, uint32_t len);
void write(const uint8_t* buf, uint32_t len);
@@ -55,14 +52,13 @@
uint8_t* borrow(uint8_t* buf, uint32_t* len);
void consume(uint32_t len);
-private:
- TQIODeviceTransport(const TQIODeviceTransport&);
- TQIODeviceTransport& operator=(const TQIODeviceTransport&);
+ private:
+ TQIODeviceTransport(const TQIODeviceTransport&);
+ TQIODeviceTransport& operator=(const TQIODeviceTransport&);
- boost::shared_ptr<QIODevice> dev_;
+ boost::shared_ptr<QIODevice> dev_;
};
-}
-}
-} // apache::thrift::transport
+}}} // apache::thrift::transport
#endif // #ifndef _THRIFT_ASYNC_TQIODEVICE_TRANSPORT_H_
+
diff --git a/lib/cpp/src/thrift/qt/TQTcpServer.cpp b/lib/cpp/src/thrift/qt/TQTcpServer.cpp
index a3211df..2b3cf98 100644
--- a/lib/cpp/src/thrift/qt/TQTcpServer.cpp
+++ b/lib/cpp/src/thrift/qt/TQTcpServer.cpp
@@ -38,9 +38,7 @@
QT_USE_NAMESPACE
-namespace apache {
-namespace thrift {
-namespace async {
+namespace apache { namespace thrift { namespace async {
struct TQTcpServer::ConnectionContext {
shared_ptr<QTcpSocket> connection_;
@@ -52,21 +50,31 @@
shared_ptr<TTransport> transport,
shared_ptr<TProtocol> iprot,
shared_ptr<TProtocol> oprot)
- : connection_(connection), transport_(transport), iprot_(iprot), oprot_(oprot) {}
+ : connection_(connection)
+ , transport_(transport)
+ , iprot_(iprot)
+ , oprot_(oprot)
+ {}
};
TQTcpServer::TQTcpServer(shared_ptr<QTcpServer> server,
shared_ptr<TAsyncProcessor> processor,
shared_ptr<TProtocolFactory> pfact,
QObject* parent)
- : QObject(parent), server_(server), processor_(processor), pfact_(pfact) {
+ : QObject(parent)
+ , server_(server)
+ , processor_(processor)
+ , pfact_(pfact)
+{
connect(server.get(), SIGNAL(newConnection()), SLOT(processIncoming()));
}
-TQTcpServer::~TQTcpServer() {
+TQTcpServer::~TQTcpServer()
+{
}
-void TQTcpServer::processIncoming() {
+void TQTcpServer::processIncoming()
+{
while (server_->hasPendingConnections()) {
// take ownership of the QTcpSocket; technically it could be deleted
// when the QTcpServer is destroyed, but any real app should delete this
@@ -81,22 +89,25 @@
transport = shared_ptr<TTransport>(new TQIODeviceTransport(connection));
iprot = shared_ptr<TProtocol>(pfact_->getProtocol(transport));
oprot = shared_ptr<TProtocol>(pfact_->getProtocol(transport));
- } catch (...) {
+ } catch(...) {
qWarning("[TQTcpServer] Failed to initialize transports/protocols");
continue;
}
- ctxMap_[connection.get()]
- = shared_ptr<ConnectionContext>(new ConnectionContext(connection, transport, iprot, oprot));
+ ctxMap_[connection.get()] =
+ shared_ptr<ConnectionContext>(
+ new ConnectionContext(connection, transport, iprot, oprot));
connect(connection.get(), SIGNAL(readyRead()), SLOT(beginDecode()));
// need to use QueuedConnection since we will be deleting the socket in the slot
- connect(connection.get(), SIGNAL(disconnected()), SLOT(socketClosed()), Qt::QueuedConnection);
+ connect(connection.get(), SIGNAL(disconnected()), SLOT(socketClosed()),
+ Qt::QueuedConnection);
}
}
-void TQTcpServer::beginDecode() {
+void TQTcpServer::beginDecode()
+{
QTcpSocket* connection(qobject_cast<QTcpSocket*>(sender()));
Q_ASSERT(connection);
@@ -108,20 +119,22 @@
shared_ptr<ConnectionContext> ctx = ctxMap_[connection];
try {
- processor_
- ->process(bind(&TQTcpServer::finish, this, ctx, apache::thrift::stdcxx::placeholders::_1),
- ctx->iprot_,
- ctx->oprot_);
- } catch (const TTransportException& ex) {
- qWarning("[TQTcpServer] TTransportException during processing: '%s'", ex.what());
+ processor_->process(
+ bind(&TQTcpServer::finish, this,
+ ctx, apache::thrift::stdcxx::placeholders::_1),
+ ctx->iprot_, ctx->oprot_);
+ } catch(const TTransportException& ex) {
+ qWarning("[TQTcpServer] TTransportException during processing: '%s'",
+ ex.what());
ctxMap_.erase(connection);
- } catch (...) {
+ } catch(...) {
qWarning("[TQTcpServer] Unknown processor exception");
ctxMap_.erase(connection);
}
}
-void TQTcpServer::socketClosed() {
+void TQTcpServer::socketClosed()
+{
QTcpSocket* connection(qobject_cast<QTcpSocket*>(sender()));
Q_ASSERT(connection);
@@ -133,12 +146,12 @@
ctxMap_.erase(connection);
}
-void TQTcpServer::finish(shared_ptr<ConnectionContext> ctx, bool healthy) {
+void TQTcpServer::finish(shared_ptr<ConnectionContext> ctx, bool healthy)
+{
if (!healthy) {
qWarning("[TQTcpServer] Processor failed to process data successfully");
ctxMap_.erase(ctx->connection_.get());
}
}
-}
-}
-} // apache::thrift::async
+
+}}} // apache::thrift::async
diff --git a/lib/cpp/src/thrift/qt/TQTcpServer.h b/lib/cpp/src/thrift/qt/TQTcpServer.h
index 3403f1e..2ef64a7 100644
--- a/lib/cpp/src/thrift/qt/TQTcpServer.h
+++ b/lib/cpp/src/thrift/qt/TQTcpServer.h
@@ -25,17 +25,11 @@
#include <boost/shared_ptr.hpp>
-namespace apache {
-namespace thrift {
-namespace protocol {
+namespace apache { namespace thrift { namespace protocol {
class TProtocolFactory;
-}
-}
-} // apache::thrift::protocol
+}}} // apache::thrift::protocol
-namespace apache {
-namespace thrift {
-namespace async {
+namespace apache { namespace thrift { namespace async {
class TAsyncProcessor;
@@ -45,20 +39,20 @@
* processor and a protocol factory, and then run the Qt event loop.
*/
class TQTcpServer : public QObject {
- Q_OBJECT
-public:
+ Q_OBJECT
+ public:
TQTcpServer(boost::shared_ptr<QTcpServer> server,
boost::shared_ptr<TAsyncProcessor> processor,
boost::shared_ptr<apache::thrift::protocol::TProtocolFactory> protocolFactory,
QT_PREPEND_NAMESPACE(QObject)* parent = NULL);
virtual ~TQTcpServer();
-private Q_SLOTS:
+ private Q_SLOTS:
void processIncoming();
void beginDecode();
void socketClosed();
-private:
+ private:
TQTcpServer(const TQTcpServer&);
TQTcpServer& operator=(const TQTcpServer&);
@@ -72,8 +66,7 @@
std::map<QT_PREPEND_NAMESPACE(QTcpSocket)*, boost::shared_ptr<ConnectionContext> > ctxMap_;
};
-}
-}
-} // apache::thrift::async
+
+}}} // apache::thrift::async
#endif // #ifndef _THRIFT_TASYNC_QTCP_SERVER_H_
diff --git a/lib/cpp/src/thrift/server/TNonblockingServer.cpp b/lib/cpp/src/thrift/server/TNonblockingServer.cpp
index 1cfdef8..86a96c6 100644
--- a/lib/cpp/src/thrift/server/TNonblockingServer.cpp
+++ b/lib/cpp/src/thrift/server/TNonblockingServer.cpp
@@ -65,9 +65,7 @@
#define PRIu64 "I64u"
#endif
-namespace apache {
-namespace thrift {
-namespace server {
+namespace apache { namespace thrift { namespace server {
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
@@ -78,7 +76,11 @@
using boost::shared_ptr;
/// Three states for sockets: recv frame size, recv data, and send mode
-enum TSocketState { SOCKET_RECV_FRAMING, SOCKET_RECV, SOCKET_SEND };
+enum TSocketState {
+ SOCKET_RECV_FRAMING,
+ SOCKET_RECV,
+ SOCKET_SEND
+};
/**
* Five states for the nonblocking server:
@@ -102,7 +104,7 @@
* essentially encapsulates a socket that has some associated libevent state.
*/
class TNonblockingServer::TConnection {
-private:
+ private:
/// Server IO Thread handling this connection
TNonblockingIOThread* ioThread_;
@@ -174,16 +176,22 @@
boost::shared_ptr<TServerEventHandler> serverEventHandler_;
/// Thrift call context, if any
- void* connectionContext_;
+ void *connectionContext_;
/// Go into read mode
- void setRead() { setFlags(EV_READ | EV_PERSIST); }
+ void setRead() {
+ setFlags(EV_READ | EV_PERSIST);
+ }
/// Go into write mode
- void setWrite() { setFlags(EV_WRITE | EV_PERSIST); }
+ void setWrite() {
+ setFlags(EV_WRITE | EV_PERSIST);
+ }
/// Set socket idle
- void setIdle() { setFlags(0); }
+ void setIdle() {
+ setFlags(0);
+ }
/**
* Set event flags for this connection.
@@ -200,14 +208,13 @@
*/
void workSocket();
-public:
+ public:
+
class Task;
/// Constructor
- TConnection(THRIFT_SOCKET socket,
- TNonblockingIOThread* ioThread,
- const sockaddr* addr,
- socklen_t addrLen) {
+ TConnection(THRIFT_SOCKET socket, TNonblockingIOThread* ioThread,
+ const sockaddr* addr, socklen_t addrLen) {
readBuffer_ = NULL;
readBufferSize_ = 0;
@@ -218,29 +225,29 @@
// once per TConnection (they don't need to be reallocated on init() call)
inputTransport_.reset(new TMemoryBuffer(readBuffer_, readBufferSize_));
outputTransport_.reset(
- new TMemoryBuffer(static_cast<uint32_t>(server_->getWriteBufferDefaultSize())));
+ new TMemoryBuffer(static_cast<uint32_t>(server_->getWriteBufferDefaultSize())));
tSocket_.reset(new TSocket());
init(socket, ioThread, addr, addrLen);
}
- ~TConnection() { std::free(readBuffer_); }
+ ~TConnection() {
+ std::free(readBuffer_);
+ }
/// Close this connection and free or reset its resources.
void close();
- /**
- * Check buffers against any size limits and shrink it if exceeded.
- *
- * @param readLimit we reduce read buffer size to this (if nonzero).
- * @param writeLimit if nonzero and write buffer is larger, replace it.
- */
+ /**
+ * Check buffers against any size limits and shrink it if exceeded.
+ *
+ * @param readLimit we reduce read buffer size to this (if nonzero).
+ * @param writeLimit if nonzero and write buffer is larger, replace it.
+ */
void checkIdleBufferMemLimit(size_t readLimit, size_t writeLimit);
/// Initialize
- void init(THRIFT_SOCKET socket,
- TNonblockingIOThread* ioThread,
- const sockaddr* addr,
- socklen_t addrLen);
+ void init(THRIFT_SOCKET socket, TNonblockingIOThread* ioThread,
+ const sockaddr* addr, socklen_t addrLen);
/**
* This is called when the application transitions from one state into
@@ -271,13 +278,17 @@
*
* @return true if successful, false if unable to notify (check THRIFT_GET_SOCKET_ERROR).
*/
- bool notifyIOThread() { return ioThread_->notify(this); }
+ bool notifyIOThread() {
+ return ioThread_->notify(this);
+ }
/*
* Returns the number of this connection's currently assigned IO
* thread.
*/
- int getIOThreadNumber() const { return ioThread_->getThreadNumber(); }
+ int getIOThreadNumber() const {
+ return ioThread_->getThreadNumber();
+ }
/// Force connection shutdown for this connection.
void forceClose() {
@@ -288,33 +299,44 @@
}
/// return the server this connection was initialized for.
- TNonblockingServer* getServer() const { return server_; }
+ TNonblockingServer* getServer() const {
+ return server_;
+ }
/// get state of connection.
- TAppState getState() const { return appState_; }
+ TAppState getState() const {
+ return appState_;
+ }
/// return the TSocket transport wrapping this network connection
- boost::shared_ptr<TSocket> getTSocket() const { return tSocket_; }
+ boost::shared_ptr<TSocket> getTSocket() const {
+ return tSocket_;
+ }
/// return the server event handler if any
- boost::shared_ptr<TServerEventHandler> getServerEventHandler() { return serverEventHandler_; }
+ boost::shared_ptr<TServerEventHandler> getServerEventHandler() {
+ return serverEventHandler_;
+ }
/// return the Thrift connection context if any
- void* getConnectionContext() { return connectionContext_; }
+ void* getConnectionContext() {
+ return connectionContext_;
+ }
+
};
-class TNonblockingServer::TConnection::Task : public Runnable {
-public:
+class TNonblockingServer::TConnection::Task: public Runnable {
+ public:
Task(boost::shared_ptr<TProcessor> processor,
boost::shared_ptr<TProtocol> input,
boost::shared_ptr<TProtocol> output,
- TConnection* connection)
- : processor_(processor),
- input_(input),
- output_(output),
- connection_(connection),
- serverEventHandler_(connection_->getServerEventHandler()),
- connectionContext_(connection_->getConnectionContext()) {}
+ TConnection* connection) :
+ processor_(processor),
+ input_(input),
+ output_(output),
+ connection_(connection),
+ serverEventHandler_(connection_->getServerEventHandler()),
+ connectionContext_(connection_->getConnectionContext()) {}
void run() {
try {
@@ -322,8 +344,8 @@
if (serverEventHandler_) {
serverEventHandler_->processContext(connectionContext_, connection_->getTSocket());
}
- if (!processor_->process(input_, output_, connectionContext_)
- || !input_->getTransport()->peek()) {
+ if (!processor_->process(input_, output_, connectionContext_) ||
+ !input_->getTransport()->peek()) {
break;
}
}
@@ -334,10 +356,10 @@
exit(1);
} catch (const std::exception& x) {
GlobalOutput.printf("TNonblockingServer: process() exception: %s: %s",
- typeid(x).name(),
- x.what());
+ typeid(x).name(), x.what());
} catch (...) {
- GlobalOutput.printf("TNonblockingServer: unknown exception while processing.");
+ GlobalOutput.printf(
+ "TNonblockingServer: unknown exception while processing.");
}
// Signal completion back to the libevent thread via a pipe
@@ -346,9 +368,11 @@
}
}
- TConnection* getTConnection() { return connection_; }
+ TConnection* getTConnection() {
+ return connection_;
+ }
-private:
+ private:
boost::shared_ptr<TProcessor> processor_;
boost::shared_ptr<TProtocol> input_;
boost::shared_ptr<TProtocol> output_;
@@ -381,17 +405,22 @@
callsForResize_ = 0;
// get input/transports
- factoryInputTransport_ = server_->getInputTransportFactory()->getTransport(inputTransport_);
- factoryOutputTransport_ = server_->getOutputTransportFactory()->getTransport(outputTransport_);
+ factoryInputTransport_ = server_->getInputTransportFactory()->getTransport(
+ inputTransport_);
+ factoryOutputTransport_ = server_->getOutputTransportFactory()->getTransport(
+ outputTransport_);
// Create protocol
- inputProtocol_ = server_->getInputProtocolFactory()->getProtocol(factoryInputTransport_);
- outputProtocol_ = server_->getOutputProtocolFactory()->getProtocol(factoryOutputTransport_);
+ inputProtocol_ = server_->getInputProtocolFactory()->getProtocol(
+ factoryInputTransport_);
+ outputProtocol_ = server_->getOutputProtocolFactory()->getProtocol(
+ factoryOutputTransport_);
// Set up for any server event handler
serverEventHandler_ = server_->getEventHandler();
if (serverEventHandler_) {
- connectionContext_ = serverEventHandler_->createContext(inputProtocol_, outputProtocol_);
+ connectionContext_ = serverEventHandler_->createContext(inputProtocol_,
+ outputProtocol_);
} else {
connectionContext_ = NULL;
}
@@ -401,7 +430,7 @@
}
void TNonblockingServer::TConnection::workSocket() {
- int got = 0, left = 0, sent = 0;
+ int got=0, left=0, sent=0;
uint32_t fetch = 0;
switch (socketState_) {
@@ -441,14 +470,12 @@
if (readWant_ > server_->getMaxFrameSize()) {
// Don't allow giant frame sizes. This prevents bad clients from
// causing us to try and allocate a giant buffer.
- GlobalOutput.printf(
- "TNonblockingServer: frame size too large "
- "(%" PRIu32 " > %" PRIu64
- ") from client %s. "
- "Remote side not using TFramedTransport?",
- readWant_,
- (uint64_t)server_->getMaxFrameSize(),
- tSocket_->getSocketInfo().c_str());
+ GlobalOutput.printf("TNonblockingServer: frame size too large "
+ "(%" PRIu32 " > %" PRIu64 ") from client %s. "
+ "Remote side not using TFramedTransport?",
+ readWant_,
+ (uint64_t)server_->getMaxFrameSize(),
+ tSocket_->getSocketInfo().c_str());
close();
return;
}
@@ -464,7 +491,8 @@
// Read from the socket
fetch = readWant_ - readBufferPos_;
got = tSocket_->read(readBuffer_ + readBufferPos_, fetch);
- } catch (TTransportException& te) {
+ }
+ catch (TTransportException& te) {
GlobalOutput.printf("TConnection::workSocket(): %s", te.what());
close();
@@ -504,7 +532,8 @@
try {
left = writeBufferSize_ - writeBufferPos_;
sent = tSocket_->write_partial(writeBuffer_ + writeBufferPos_, left);
- } catch (TTransportException& te) {
+ }
+ catch (TTransportException& te) {
GlobalOutput.printf("TConnection::workSocket(): %s ", te.what());
close();
return;
@@ -557,18 +586,21 @@
// We are setting up a Task to do this work and we will wait on it
// Create task and dispatch to the thread manager
- boost::shared_ptr<Runnable> task = boost::shared_ptr<Runnable>(
- new Task(processor_, inputProtocol_, outputProtocol_, this));
+ boost::shared_ptr<Runnable> task =
+ boost::shared_ptr<Runnable>(new Task(processor_,
+ inputProtocol_,
+ outputProtocol_,
+ this));
// The application is now waiting on the task to finish
appState_ = APP_WAIT_TASK;
- try {
- server_->addTask(task);
- } catch (IllegalStateException& ise) {
- // The ThreadManager is not ready to handle any more tasks (it's probably shutting down).
- GlobalOutput.printf("IllegalStateException: Server::process() %s", ise.what());
- close();
- }
+ try {
+ server_->addTask(task);
+ } catch (IllegalStateException & ise) {
+ // The ThreadManager is not ready to handle any more tasks (it's probably shutting down).
+ GlobalOutput.printf("IllegalStateException: Server::process() %s", ise.what());
+ close();
+ }
// Set this connection idle so that libevent doesn't process more
// data on it while we're still waiting for the threadmanager to
@@ -578,22 +610,21 @@
} else {
try {
if (serverEventHandler_) {
- serverEventHandler_->processContext(connectionContext_, getTSocket());
+ serverEventHandler_->processContext(connectionContext_,
+ getTSocket());
}
// Invoke the processor
- processor_->process(inputProtocol_, outputProtocol_, connectionContext_);
- } catch (const TTransportException& ttx) {
- GlobalOutput.printf(
- "TNonblockingServer transport error in "
- "process(): %s",
- ttx.what());
+ processor_->process(inputProtocol_, outputProtocol_,
+ connectionContext_);
+ } catch (const TTransportException &ttx) {
+ GlobalOutput.printf("TNonblockingServer transport error in "
+ "process(): %s", ttx.what());
server_->decrementActiveProcessors();
close();
return;
- } catch (const std::exception& x) {
+ } catch (const std::exception &x) {
GlobalOutput.printf("Server::process() uncaught exception: %s: %s",
- typeid(x).name(),
- x.what());
+ typeid(x).name(), x.what());
server_->decrementActiveProcessors();
close();
return;
@@ -605,8 +636,8 @@
}
}
- // Intentionally fall through here, the call to process has written into
- // the writeBuffer_
+ // Intentionally fall through here, the call to process has written into
+ // the writeBuffer_
case APP_WAIT_TASK:
// We have now finished processing a task and the result has been written
@@ -656,7 +687,7 @@
callsForResize_ = 0;
}
- // N.B.: We also intentionally fall through here into the INIT state!
+ // N.B.: We also intentionally fall through here into the INIT state!
LABEL_APP_INIT:
case APP_INIT:
@@ -701,7 +732,7 @@
readBufferSize_ = newSize;
}
- readBufferPos_ = 0;
+ readBufferPos_= 0;
// Move into read request state
socketState_ = SOCKET_RECV;
@@ -772,7 +803,8 @@
* ev structure for multiple monitored descriptors; each descriptor needs
* its own ev.
*/
- event_set(&event_, tSocket_->getSocketFD(), eventFlags_, TConnection::eventHandler, this);
+ event_set(&event_, tSocket_->getSocketFD(), eventFlags_,
+ TConnection::eventHandler, this);
event_base_set(ioThread_->getEventBase(), &event_);
// Add the event
@@ -809,7 +841,9 @@
server_->returnConnection(this);
}
-void TNonblockingServer::TConnection::checkIdleBufferMemLimit(size_t readLimit, size_t writeLimit) {
+void TNonblockingServer::TConnection::checkIdleBufferMemLimit(
+ size_t readLimit,
+ size_t writeLimit) {
if (readLimit > 0 && readBufferSize_ > readLimit) {
free(readBuffer_);
readBuffer_ = NULL;
@@ -826,7 +860,7 @@
TNonblockingServer::~TNonblockingServer() {
// Close any active connections (moves them to the idle connection stack)
while (activeConnections_.size()) {
- activeConnections_.front()->close();
+ activeConnections_.front()->close();
}
// Clean up unused TConnection objects in connectionStack_
while (!connectionStack_.empty()) {
@@ -838,9 +872,9 @@
// objects and the Thread objects have shared_ptrs to the TNonblockingIOThread
// objects (as runnable) so these objects will never deallocate without help.
while (!ioThreads_.empty()) {
- boost::shared_ptr<TNonblockingIOThread> iot = ioThreads_.back();
- ioThreads_.pop_back();
- iot->setThread(boost::shared_ptr<Thread>());
+ boost::shared_ptr<TNonblockingIOThread> iot = ioThreads_.back();
+ ioThreads_.pop_back();
+ iot->setThread(boost::shared_ptr<Thread>());
}
}
@@ -848,9 +882,8 @@
* Creates a new connection either by reusing an object off the stack or
* by allocating a new one entirely
*/
-TNonblockingServer::TConnection* TNonblockingServer::createConnection(THRIFT_SOCKET socket,
- const sockaddr* addr,
- socklen_t addrLen) {
+TNonblockingServer::TConnection* TNonblockingServer::createConnection(
+ THRIFT_SOCKET socket, const sockaddr* addr, socklen_t addrLen) {
// Check the stack
Guard g(connMutex_);
@@ -881,12 +914,10 @@
void TNonblockingServer::returnConnection(TConnection* connection) {
Guard g(connMutex_);
- activeConnections_.erase(std::remove(activeConnections_.begin(),
- activeConnections_.end(),
- connection),
- activeConnections_.end());
+ activeConnections_.erase(std::remove(activeConnections_.begin(), activeConnections_.end(), connection), activeConnections_.end());
- if (connectionStackLimit_ && (connectionStack_.size() >= connectionStackLimit_)) {
+ if (connectionStackLimit_ &&
+ (connectionStack_.size() >= connectionStackLimit_)) {
delete connection;
--numTConnections_;
} else {
@@ -900,7 +931,7 @@
* connections on fd and assign TConnection objects to handle those requests.
*/
void TNonblockingServer::handleEvent(THRIFT_SOCKET fd, short which) {
- (void)which;
+ (void) which;
// Make sure that libevent didn't mess up the socket handles
assert(fd == serverSocket_);
@@ -936,16 +967,16 @@
// Explicitly set this socket to NONBLOCK mode
int flags;
- if ((flags = THRIFT_FCNTL(clientSocket, THRIFT_F_GETFL, 0)) < 0
- || THRIFT_FCNTL(clientSocket, THRIFT_F_SETFL, flags | THRIFT_O_NONBLOCK) < 0) {
- GlobalOutput.perror("thriftServerEventHandler: set THRIFT_O_NONBLOCK (THRIFT_FCNTL) ",
- THRIFT_GET_SOCKET_ERROR);
+ if ((flags = THRIFT_FCNTL(clientSocket, THRIFT_F_GETFL, 0)) < 0 ||
+ THRIFT_FCNTL(clientSocket, THRIFT_F_SETFL, flags | THRIFT_O_NONBLOCK) < 0) {
+ GlobalOutput.perror("thriftServerEventHandler: set THRIFT_O_NONBLOCK (THRIFT_FCNTL) ", THRIFT_GET_SOCKET_ERROR);
::THRIFT_CLOSESOCKET(clientSocket);
return;
}
// Create a new TConnection for this client socket.
- TConnection* clientConnection = createConnection(clientSocket, addrp, addrLen);
+ TConnection* clientConnection =
+ createConnection(clientSocket, addrp, addrLen);
// Fail fast if we could not create a TConnection object
if (clientConnection == NULL) {
@@ -976,6 +1007,7 @@
addrLen = sizeof(addrStorage);
}
+
// Done looping accept, now we have to make sure the error is due to
// blocking. Any other error is a problem
if (THRIFT_GET_SOCKET_ERROR != THRIFT_EAGAIN && THRIFT_GET_SOCKET_ERROR != THRIFT_EWOULDBLOCK) {
@@ -1002,8 +1034,8 @@
// Wildcard address
error = getaddrinfo(NULL, port, &hints, &res0);
if (error) {
- throw TException("TNonblockingServer::serve() getaddrinfo "
- + string(THRIFT_GAI_STRERROR(error)));
+ throw TException("TNonblockingServer::serve() getaddrinfo " +
+ string(THRIFT_GAI_STRERROR(error)));
}
// Pick the ipv6 address first since ipv4 addresses can be mapped
@@ -1020,14 +1052,15 @@
throw TException("TNonblockingServer::serve() socket() -1");
}
-#ifdef IPV6_V6ONLY
+ #ifdef IPV6_V6ONLY
if (res->ai_family == AF_INET6) {
int zero = 0;
if (-1 == setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, const_cast_sockopt(&zero), sizeof(zero))) {
GlobalOutput("TServerSocket::listen() IPV6_V6ONLY");
}
}
-#endif // #ifdef IPV6_V6ONLY
+ #endif // #ifdef IPV6_V6ONLY
+
int one = 1;
@@ -1056,8 +1089,8 @@
void TNonblockingServer::listenSocket(THRIFT_SOCKET s) {
// Set socket to nonblocking mode
int flags;
- if ((flags = THRIFT_FCNTL(s, THRIFT_F_GETFL, 0)) < 0
- || THRIFT_FCNTL(s, THRIFT_F_SETFL, flags | THRIFT_O_NONBLOCK) < 0) {
+ if ((flags = THRIFT_FCNTL(s, THRIFT_F_GETFL, 0)) < 0 ||
+ THRIFT_FCNTL(s, THRIFT_F_SETFL, flags | THRIFT_O_NONBLOCK) < 0) {
::THRIFT_CLOSESOCKET(s);
throw TException("TNonblockingServer::serve() THRIFT_O_NONBLOCK");
}
@@ -1071,17 +1104,17 @@
// Turn linger off to avoid hung sockets
setsockopt(s, SOL_SOCKET, SO_LINGER, const_cast_sockopt(&ling), sizeof(ling));
-// Set TCP nodelay if available, MAC OS X Hack
-// See http://lists.danga.com/pipermail/memcached/2005-March/001240.html
-#ifndef TCP_NOPUSH
+ // Set TCP nodelay if available, MAC OS X Hack
+ // See http://lists.danga.com/pipermail/memcached/2005-March/001240.html
+ #ifndef TCP_NOPUSH
setsockopt(s, IPPROTO_TCP, TCP_NODELAY, const_cast_sockopt(&one), sizeof(one));
-#endif
+ #endif
-#ifdef TCP_LOW_MIN_RTO
+ #ifdef TCP_LOW_MIN_RTO
if (TSocket::getUseLowMinRto()) {
setsockopt(s, IPPROTO_TCP, TCP_LOW_MIN_RTO, const_cast_sockopt(&one), sizeof(one));
}
-#endif
+ #endif
if (listen(s, LISTEN_BACKLOG) == -1) {
::THRIFT_CLOSESOCKET(s);
@@ -1095,31 +1128,28 @@
void TNonblockingServer::setThreadManager(boost::shared_ptr<ThreadManager> threadManager) {
threadManager_ = threadManager;
if (threadManager) {
- threadManager->setExpireCallback(
- apache::thrift::stdcxx::bind(&TNonblockingServer::expireClose,
- this,
- apache::thrift::stdcxx::placeholders::_1));
+ threadManager->setExpireCallback(apache::thrift::stdcxx::bind(&TNonblockingServer::expireClose, this, apache::thrift::stdcxx::placeholders::_1));
threadPoolProcessing_ = true;
} else {
threadPoolProcessing_ = false;
}
}
-bool TNonblockingServer::serverOverloaded() {
+bool TNonblockingServer::serverOverloaded() {
size_t activeConnections = numTConnections_ - connectionStack_.size();
- if (numActiveProcessors_ > maxActiveProcessors_ || activeConnections > maxConnections_) {
+ if (numActiveProcessors_ > maxActiveProcessors_ ||
+ activeConnections > maxConnections_) {
if (!overloaded_) {
- GlobalOutput.printf("TNonblockingServer: overload condition begun.");
+ GlobalOutput.printf("TNonblockingServer: overload condition begun.");
overloaded_ = true;
}
} else {
- if (overloaded_ && (numActiveProcessors_ <= overloadHysteresis_ * maxActiveProcessors_)
- && (activeConnections <= overloadHysteresis_ * maxConnections_)) {
- GlobalOutput.printf(
- "TNonblockingServer: overload ended; "
- "%u dropped (%llu total)",
- nConnectionsDropped_,
- nTotalConnectionsDropped_);
+ if (overloaded_ &&
+ (numActiveProcessors_ <= overloadHysteresis_ * maxActiveProcessors_) &&
+ (activeConnections <= overloadHysteresis_ * maxConnections_)) {
+ GlobalOutput.printf("TNonblockingServer: overload ended; "
+ "%u dropped (%llu total)",
+ nConnectionsDropped_, nTotalConnectionsDropped_);
nConnectionsDropped_ = 0;
overloaded_ = false;
}
@@ -1132,8 +1162,10 @@
if (threadManager_) {
boost::shared_ptr<Runnable> task = threadManager_->removeNextPending();
if (task) {
- TConnection* connection = static_cast<TConnection::Task*>(task.get())->getTConnection();
- assert(connection && connection->getServer() && connection->getState() == APP_WAIT_TASK);
+ TConnection* connection =
+ static_cast<TConnection::Task*>(task.get())->getTConnection();
+ assert(connection && connection->getServer()
+ && connection->getState() == APP_WAIT_TASK);
connection->forceClose();
return true;
}
@@ -1142,8 +1174,10 @@
}
void TNonblockingServer::expireClose(boost::shared_ptr<Runnable> task) {
- TConnection* connection = static_cast<TConnection::Task*>(task.get())->getTConnection();
- assert(connection && connection->getServer() && connection->getState() == APP_WAIT_TASK);
+ TConnection* connection =
+ static_cast<TConnection::Task*>(task.get())->getTConnection();
+ assert(connection && connection->getServer() &&
+ connection->getState() == APP_WAIT_TASK);
connection->forceClose();
}
@@ -1172,7 +1206,7 @@
THRIFT_SOCKET listenFd = (id == 0 ? serverSocket_ : THRIFT_INVALID_SOCKET);
shared_ptr<TNonblockingIOThread> thread(
- new TNonblockingIOThread(this, id, listenFd, useHighPriorityIOThreads_));
+ new TNonblockingIOThread(this, id, listenFd, useHighPriorityIOThreads_));
ioThreads_.push_back(thread);
}
@@ -1187,19 +1221,18 @@
assert(ioThreads_.size() > 0);
GlobalOutput.printf("TNonblockingServer: Serving on port %d, %d io threads.",
- port_,
- ioThreads_.size());
+ port_, ioThreads_.size());
// Launch all the secondary IO threads in separate threads
if (ioThreads_.size() > 1) {
ioThreadFactory_.reset(new PlatformThreadFactory(
#if !defined(USE_BOOST_THREAD) && !defined(USE_STD_THREAD)
- PlatformThreadFactory::OTHER, // scheduler
- PlatformThreadFactory::NORMAL, // priority
- 1, // stack size (MB)
+ PlatformThreadFactory::OTHER, // scheduler
+ PlatformThreadFactory::NORMAL, // priority
+ 1, // stack size (MB)
#endif
- false // detached
- ));
+ false // detached
+ ));
assert(ioThreadFactory_.get());
@@ -1238,12 +1271,12 @@
int number,
THRIFT_SOCKET listenSocket,
bool useHighPriority)
- : server_(server),
- number_(number),
- listenSocket_(listenSocket),
- useHighPriority_(useHighPriority),
- eventBase_(NULL),
- ownEventBase_(false) {
+ : server_(server)
+ , number_(number)
+ , listenSocket_(listenSocket)
+ , useHighPriority_(useHighPriority)
+ , eventBase_(NULL)
+ , ownEventBase_(false) {
notificationPipeFDs_[0] = -1;
notificationPipeFDs_[1] = -1;
}
@@ -1259,7 +1292,8 @@
if (listenSocket_ >= 0) {
if (0 != ::THRIFT_CLOSESOCKET(listenSocket_)) {
- GlobalOutput.perror("TNonblockingIOThread listenSocket_ close(): ", THRIFT_GET_SOCKET_ERROR);
+ GlobalOutput.perror("TNonblockingIOThread listenSocket_ close(): ",
+ THRIFT_GET_SOCKET_ERROR);
}
listenSocket_ = THRIFT_INVALID_SOCKET;
}
@@ -1276,12 +1310,12 @@
}
void TNonblockingIOThread::createNotificationPipe() {
- if (evutil_socketpair(AF_LOCAL, SOCK_STREAM, 0, notificationPipeFDs_) == -1) {
+ if(evutil_socketpair(AF_LOCAL, SOCK_STREAM, 0, notificationPipeFDs_) == -1) {
GlobalOutput.perror("TNonblockingServer::createNotificationPipe ", EVUTIL_SOCKET_ERROR());
throw TException("can't create notification pipe");
}
- if (evutil_make_socket_nonblocking(notificationPipeFDs_[0]) < 0
- || evutil_make_socket_nonblocking(notificationPipeFDs_[1]) < 0) {
+ if(evutil_make_socket_nonblocking(notificationPipeFDs_[0])<0 ||
+ evutil_make_socket_nonblocking(notificationPipeFDs_[1])<0) {
::THRIFT_CLOSESOCKET(notificationPipeFDs_[0]);
::THRIFT_CLOSESOCKET(notificationPipeFDs_[1]);
throw TException("TNonblockingServer::createNotificationPipe() THRIFT_O_NONBLOCK");
@@ -1289,16 +1323,15 @@
for (int i = 0; i < 2; ++i) {
#if LIBEVENT_VERSION_NUMBER < 0x02000000
int flags;
- if ((flags = THRIFT_FCNTL(notificationPipeFDs_[i], F_GETFD, 0)) < 0
- || THRIFT_FCNTL(notificationPipeFDs_[i], F_SETFD, flags | FD_CLOEXEC) < 0) {
+ if ((flags = THRIFT_FCNTL(notificationPipeFDs_[i], F_GETFD, 0)) < 0 ||
+ THRIFT_FCNTL(notificationPipeFDs_[i], F_SETFD, flags | FD_CLOEXEC) < 0) {
#else
if (evutil_make_socket_closeonexec(notificationPipeFDs_[i]) < 0) {
#endif
::THRIFT_CLOSESOCKET(notificationPipeFDs_[0]);
::THRIFT_CLOSESOCKET(notificationPipeFDs_[1]);
- throw TException(
- "TNonblockingServer::createNotificationPipe() "
- "FD_CLOEXEC");
+ throw TException("TNonblockingServer::createNotificationPipe() "
+ "FD_CLOEXEC");
}
}
}
@@ -1319,8 +1352,8 @@
// Print some libevent stats
if (number_ == 0) {
GlobalOutput.printf("TNonblockingServer: using libevent %s method %s",
- event_get_version(),
- event_base_get_method(eventBase_));
+ event_get_version(),
+ event_base_get_method(eventBase_));
}
if (listenSocket_ >= 0) {
@@ -1334,11 +1367,11 @@
// Add the event and start up the server
if (-1 == event_add(&serverEvent_, 0)) {
- throw TException(
- "TNonblockingServer::serve(): "
- "event_add() failed on server listen event");
+ throw TException("TNonblockingServer::serve(): "
+ "event_add() failed on server listen event");
}
- GlobalOutput.printf("TNonblocking: IO thread #%d registered for listen.", number_);
+ GlobalOutput.printf("TNonblocking: IO thread #%d registered for listen.",
+ number_);
}
createNotificationPipe();
@@ -1355,11 +1388,11 @@
// Add the event and start up the server
if (-1 == event_add(¬ificationEvent_, 0)) {
- throw TException(
- "TNonblockingServer::serve(): "
- "event_add() failed on task-done notification event");
+ throw TException("TNonblockingServer::serve(): "
+ "event_add() failed on task-done notification event");
}
- GlobalOutput.printf("TNonblocking: IO thread #%d registered for notify.", number_);
+ GlobalOutput.printf("TNonblocking: IO thread #%d registered for notify.",
+ number_);
}
bool TNonblockingIOThread::notify(TNonblockingServer::TConnection* conn) {
@@ -1378,7 +1411,7 @@
/* static */
void TNonblockingIOThread::notifyHandler(evutil_socket_t fd, short which, void* v) {
- TNonblockingIOThread* ioThread = (TNonblockingIOThread*)v;
+ TNonblockingIOThread* ioThread = (TNonblockingIOThread*) v;
assert(ioThread);
(void)which;
@@ -1394,7 +1427,8 @@
connection->transition();
} else if (nBytes > 0) {
// throw away these bytes and hope that next time we get a solid read
- GlobalOutput.printf("notifyHandler: Bad read of %d bytes, wanted %d", nBytes, kSize);
+ GlobalOutput.printf("notifyHandler: Bad read of %d bytes, wanted %d",
+ nBytes, kSize);
ioThread->breakLoop(true);
return;
} else if (nBytes == 0) {
@@ -1402,11 +1436,11 @@
// exit the loop
break;
} else { // nBytes < 0
- if (THRIFT_GET_SOCKET_ERROR != THRIFT_EWOULDBLOCK
- && THRIFT_GET_SOCKET_ERROR != THRIFT_EAGAIN) {
- GlobalOutput.perror("TNonblocking: notifyHandler read() failed: ", THRIFT_GET_SOCKET_ERROR);
- ioThread->breakLoop(true);
- return;
+ if (THRIFT_GET_SOCKET_ERROR != THRIFT_EWOULDBLOCK && THRIFT_GET_SOCKET_ERROR != THRIFT_EAGAIN) {
+ GlobalOutput.perror(
+ "TNonblocking: notifyHandler read() failed: ", THRIFT_GET_SOCKET_ERROR);
+ ioThread->breakLoop(true);
+ return;
}
// exit the loop
break;
@@ -1416,7 +1450,8 @@
void TNonblockingIOThread::breakLoop(bool error) {
if (error) {
- GlobalOutput.printf("TNonblockingServer: IO thread #%d exiting with error.", number_);
+ GlobalOutput.printf(
+ "TNonblockingServer: IO thread #%d exiting with error.", number_);
// TODO: figure out something better to do here, but for now kill the
// whole process.
GlobalOutput.printf("TNonblockingServer: aborting process.");
@@ -1443,7 +1478,7 @@
#ifdef HAVE_SCHED_H
// Start out with a standard, low-priority setup for the sched params.
struct sched_param sp;
- bzero((void*)&sp, sizeof(sp));
+ bzero((void*) &sp, sizeof(sp));
int policy = SCHED_OTHER;
// If desired, set up high-priority sched params structure.
@@ -1452,14 +1487,16 @@
policy = SCHED_FIFO;
// The priority only compares us to other SCHED_FIFO threads, so we
// just pick a random priority halfway between min & max.
- const int priority = (sched_get_priority_max(policy) + sched_get_priority_min(policy)) / 2;
+ const int priority = (sched_get_priority_max(policy) +
+ sched_get_priority_min(policy)) / 2;
sp.sched_priority = priority;
}
// Actually set the sched params for the current thread.
if (0 == pthread_setschedparam(pthread_self(), policy, &sp)) {
- GlobalOutput.printf("TNonblocking: IO Thread #%d using high-priority scheduler!", number_);
+ GlobalOutput.printf(
+ "TNonblocking: IO Thread #%d using high-priority scheduler!", number_);
} else {
GlobalOutput.perror("TNonblocking: pthread_setschedparam(): ", THRIFT_GET_SOCKET_ERROR);
}
@@ -1472,7 +1509,8 @@
if (eventBase_ == NULL)
registerEvents();
- GlobalOutput.printf("TNonblockingServer: IO thread #%d entering loop...", number_);
+ GlobalOutput.printf("TNonblockingServer: IO thread #%d entering loop...",
+ number_);
if (useHighPriority_) {
setCurrentThreadHighPriority(true);
@@ -1488,7 +1526,8 @@
// cleans up our registered events
cleanupEvents();
- GlobalOutput.printf("TNonblockingServer: IO thread #%d run() done!", number_);
+ GlobalOutput.printf("TNonblockingServer: IO thread #%d run() done!",
+ number_);
}
void TNonblockingIOThread::cleanupEvents() {
@@ -1502,6 +1541,7 @@
event_del(¬ificationEvent_);
}
+
void TNonblockingIOThread::stop() {
// This should cause the thread to fall out of its event loop ASAP.
breakLoop(false);
@@ -1515,11 +1555,10 @@
// Note that it is safe to both join() ourselves twice, as well as join
// the current thread as the pthread implementation checks for deadlock.
thread_->join();
- } catch (...) {
+ } catch(...) {
// swallow everything
}
}
}
-}
-}
-} // apache::thrift::server
+
+}}} // apache::thrift::server
diff --git a/lib/cpp/src/thrift/server/TNonblockingServer.h b/lib/cpp/src/thrift/server/TNonblockingServer.h
index 7853d54..532d4ae 100644
--- a/lib/cpp/src/thrift/server/TNonblockingServer.h
+++ b/lib/cpp/src/thrift/server/TNonblockingServer.h
@@ -39,9 +39,9 @@
#endif
#include <event.h>
-namespace apache {
-namespace thrift {
-namespace server {
+
+
+namespace apache { namespace thrift { namespace server {
using apache::thrift::transport::TMemoryBuffer;
using apache::thrift::transport::TSocket;
@@ -63,28 +63,27 @@
#define LIBEVENT_VERSION_MAJOR 1
#define LIBEVENT_VERSION_MINOR 14
#define LIBEVENT_VERSION_REL 13
-#define LIBEVENT_VERSION_NUMBER \
- ((LIBEVENT_VERSION_MAJOR << 24) | (LIBEVENT_VERSION_MINOR << 16) | (LIBEVENT_VERSION_REL << 8))
+#define LIBEVENT_VERSION_NUMBER ((LIBEVENT_VERSION_MAJOR << 24) | (LIBEVENT_VERSION_MINOR << 16) | (LIBEVENT_VERSION_REL << 8))
#endif
#if LIBEVENT_VERSION_NUMBER < 0x02000000
-typedef THRIFT_SOCKET evutil_socket_t;
+ typedef THRIFT_SOCKET evutil_socket_t;
#endif
#ifndef SOCKOPT_CAST_T
-#ifndef _WIN32
-#define SOCKOPT_CAST_T void
-#else
-#define SOCKOPT_CAST_T char
-#endif // _WIN32
+# ifndef _WIN32
+# define SOCKOPT_CAST_T void
+# else
+# define SOCKOPT_CAST_T char
+# endif // _WIN32
#endif
-template <class T>
+template<class T>
inline const SOCKOPT_CAST_T* const_cast_sockopt(const T* v) {
return reinterpret_cast<const SOCKOPT_CAST_T*>(v);
}
-template <class T>
+template<class T>
inline SOCKOPT_CAST_T* cast_sockopt(T* v) {
return reinterpret_cast<SOCKOPT_CAST_T*>(v);
}
@@ -100,22 +99,22 @@
*
*/
+
/// Overload condition actions.
enum TOverloadAction {
- T_OVERLOAD_NO_ACTION, ///< Don't handle overload */
- T_OVERLOAD_CLOSE_ON_ACCEPT, ///< Drop new connections immediately */
- T_OVERLOAD_DRAIN_TASK_QUEUE ///< Drop some tasks from head of task queue */
+ T_OVERLOAD_NO_ACTION, ///< Don't handle overload */
+ T_OVERLOAD_CLOSE_ON_ACCEPT, ///< Drop new connections immediately */
+ T_OVERLOAD_DRAIN_TASK_QUEUE ///< Drop some tasks from head of task queue */
};
class TNonblockingIOThread;
class TNonblockingServer : public TServer {
-private:
+ private:
class TConnection;
friend class TNonblockingIOThread;
-
-private:
+ private:
/// Listen backlog
static const int LISTEN_BACKLOG = 1024;
@@ -300,31 +299,33 @@
nTotalConnectionsDropped_ = 0;
}
-public:
- template <typename ProcessorFactory>
- TNonblockingServer(const boost::shared_ptr<ProcessorFactory>& processorFactory,
- int port,
- THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory))
- : TServer(processorFactory) {
+ public:
+ template<typename ProcessorFactory>
+ TNonblockingServer(
+ const boost::shared_ptr<ProcessorFactory>& processorFactory,
+ int port,
+ THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory)) :
+ TServer(processorFactory) {
init(port);
}
- template <typename Processor>
+ template<typename Processor>
TNonblockingServer(const boost::shared_ptr<Processor>& processor,
int port,
- THRIFT_OVERLOAD_IF(Processor, TProcessor))
- : TServer(processor) {
+ THRIFT_OVERLOAD_IF(Processor, TProcessor)) :
+ TServer(processor) {
init(port);
}
- template <typename ProcessorFactory>
- TNonblockingServer(const boost::shared_ptr<ProcessorFactory>& processorFactory,
- const boost::shared_ptr<TProtocolFactory>& protocolFactory,
- int port,
- const boost::shared_ptr<ThreadManager>& threadManager
- = boost::shared_ptr<ThreadManager>(),
- THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory))
- : TServer(processorFactory) {
+ template<typename ProcessorFactory>
+ TNonblockingServer(
+ const boost::shared_ptr<ProcessorFactory>& processorFactory,
+ const boost::shared_ptr<TProtocolFactory>& protocolFactory,
+ int port,
+ const boost::shared_ptr<ThreadManager>& threadManager =
+ boost::shared_ptr<ThreadManager>(),
+ THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory)) :
+ TServer(processorFactory) {
init(port);
@@ -333,14 +334,15 @@
setThreadManager(threadManager);
}
- template <typename Processor>
- TNonblockingServer(const boost::shared_ptr<Processor>& processor,
- const boost::shared_ptr<TProtocolFactory>& protocolFactory,
- int port,
- const boost::shared_ptr<ThreadManager>& threadManager
- = boost::shared_ptr<ThreadManager>(),
- THRIFT_OVERLOAD_IF(Processor, TProcessor))
- : TServer(processor) {
+ template<typename Processor>
+ TNonblockingServer(
+ const boost::shared_ptr<Processor>& processor,
+ const boost::shared_ptr<TProtocolFactory>& protocolFactory,
+ int port,
+ const boost::shared_ptr<ThreadManager>& threadManager =
+ boost::shared_ptr<ThreadManager>(),
+ THRIFT_OVERLOAD_IF(Processor, TProcessor)) :
+ TServer(processor) {
init(port);
@@ -349,17 +351,18 @@
setThreadManager(threadManager);
}
- template <typename ProcessorFactory>
- TNonblockingServer(const boost::shared_ptr<ProcessorFactory>& processorFactory,
- const boost::shared_ptr<TTransportFactory>& inputTransportFactory,
- const boost::shared_ptr<TTransportFactory>& outputTransportFactory,
- const boost::shared_ptr<TProtocolFactory>& inputProtocolFactory,
- const boost::shared_ptr<TProtocolFactory>& outputProtocolFactory,
- int port,
- const boost::shared_ptr<ThreadManager>& threadManager
- = boost::shared_ptr<ThreadManager>(),
- THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory))
- : TServer(processorFactory) {
+ template<typename ProcessorFactory>
+ TNonblockingServer(
+ const boost::shared_ptr<ProcessorFactory>& processorFactory,
+ const boost::shared_ptr<TTransportFactory>& inputTransportFactory,
+ const boost::shared_ptr<TTransportFactory>& outputTransportFactory,
+ const boost::shared_ptr<TProtocolFactory>& inputProtocolFactory,
+ const boost::shared_ptr<TProtocolFactory>& outputProtocolFactory,
+ int port,
+ const boost::shared_ptr<ThreadManager>& threadManager =
+ boost::shared_ptr<ThreadManager>(),
+ THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory)) :
+ TServer(processorFactory) {
init(port);
@@ -370,17 +373,18 @@
setThreadManager(threadManager);
}
- template <typename Processor>
- TNonblockingServer(const boost::shared_ptr<Processor>& processor,
- const boost::shared_ptr<TTransportFactory>& inputTransportFactory,
- const boost::shared_ptr<TTransportFactory>& outputTransportFactory,
- const boost::shared_ptr<TProtocolFactory>& inputProtocolFactory,
- const boost::shared_ptr<TProtocolFactory>& outputProtocolFactory,
- int port,
- const boost::shared_ptr<ThreadManager>& threadManager
- = boost::shared_ptr<ThreadManager>(),
- THRIFT_OVERLOAD_IF(Processor, TProcessor))
- : TServer(processor) {
+ template<typename Processor>
+ TNonblockingServer(
+ const boost::shared_ptr<Processor>& processor,
+ const boost::shared_ptr<TTransportFactory>& inputTransportFactory,
+ const boost::shared_ptr<TTransportFactory>& outputTransportFactory,
+ const boost::shared_ptr<TProtocolFactory>& inputProtocolFactory,
+ const boost::shared_ptr<TProtocolFactory>& outputProtocolFactory,
+ int port,
+ const boost::shared_ptr<ThreadManager>& threadManager =
+ boost::shared_ptr<ThreadManager>(),
+ THRIFT_OVERLOAD_IF(Processor, TProcessor)) :
+ TServer(processor) {
init(port);
@@ -395,7 +399,9 @@
void setThreadManager(boost::shared_ptr<ThreadManager> threadManager);
- boost::shared_ptr<ThreadManager> getThreadManager() { return threadManager_; }
+ boost::shared_ptr<ThreadManager> getThreadManager() {
+ return threadManager_;
+ }
/**
* Sets the number of IO threads used by this server. Can only be used before
@@ -403,32 +409,46 @@
* PosixThreadFactory for the IO worker threads, because they must joinable
* for clean shutdown.
*/
- void setNumIOThreads(size_t numThreads) { numIOThreads_ = numThreads; }
+ void setNumIOThreads(size_t numThreads) {
+ numIOThreads_ = numThreads;
+ }
/** Return whether the IO threads will get high scheduling priority */
- bool useHighPriorityIOThreads() const { return useHighPriorityIOThreads_; }
+ bool useHighPriorityIOThreads() const {
+ return useHighPriorityIOThreads_;
+ }
/** Set whether the IO threads will get high scheduling priority. */
- void setUseHighPriorityIOThreads(bool val) { useHighPriorityIOThreads_ = val; }
+ void setUseHighPriorityIOThreads(bool val) {
+ useHighPriorityIOThreads_ = val;
+ }
/** Return the number of IO threads used by this server. */
- size_t getNumIOThreads() const { return numIOThreads_; }
+ size_t getNumIOThreads() const {
+ return numIOThreads_;
+ }
/**
* Get the maximum number of unused TConnection we will hold in reserve.
*
* @return the current limit on TConnection pool size.
*/
- size_t getConnectionStackLimit() const { return connectionStackLimit_; }
+ size_t getConnectionStackLimit() const {
+ return connectionStackLimit_;
+ }
/**
* Set the maximum number of unused TConnection we will hold in reserve.
*
* @param sz the new limit for TConnection pool size.
*/
- void setConnectionStackLimit(size_t sz) { connectionStackLimit_ = sz; }
+ void setConnectionStackLimit(size_t sz) {
+ connectionStackLimit_ = sz;
+ }
- bool isThreadPoolProcessing() const { return threadPoolProcessing_; }
+ bool isThreadPoolProcessing() const {
+ return threadPoolProcessing_;
+ }
void addTask(boost::shared_ptr<Runnable> task) {
threadManager_->add(task, 0LL, taskExpireTime_);
@@ -439,21 +459,27 @@
*
* @return count of connected sockets.
*/
- size_t getNumConnections() const { return numTConnections_; }
+ size_t getNumConnections() const {
+ return numTConnections_;
+ }
/**
* Return the count of sockets currently connected to.
*
* @return count of connected sockets.
*/
- size_t getNumActiveConnections() const { return getNumConnections() - getNumIdleConnections(); }
+ size_t getNumActiveConnections() const {
+ return getNumConnections() - getNumIdleConnections();
+ }
/**
* Return the count of connection objects allocated but not in use.
*
* @return count of idle connection objects.
*/
- size_t getNumIdleConnections() const { return connectionStack_.size(); }
+ size_t getNumIdleConnections() const {
+ return connectionStack_.size();
+ }
/**
* Return count of number of connections which are currently processing.
@@ -463,7 +489,9 @@
*
* @return # of connections currently processing.
*/
- size_t getNumActiveProcessors() const { return numActiveProcessors_; }
+ size_t getNumActiveProcessors() const {
+ return numActiveProcessors_;
+ }
/// Increment the count of connections currently processing.
void incrementActiveProcessors() {
@@ -484,21 +512,27 @@
*
* @return current setting.
*/
- size_t getMaxConnections() const { return maxConnections_; }
+ size_t getMaxConnections() const {
+ return maxConnections_;
+ }
/**
* Set the maximum # of connections allowed before overload.
*
* @param maxConnections new setting for maximum # of connections.
*/
- void setMaxConnections(size_t maxConnections) { maxConnections_ = maxConnections; }
+ void setMaxConnections(size_t maxConnections) {
+ maxConnections_ = maxConnections;
+ }
/**
* Get the maximum # of connections waiting in handler/task before overload.
*
* @return current setting.
*/
- size_t getMaxActiveProcessors() const { return maxActiveProcessors_; }
+ size_t getMaxActiveProcessors() const {
+ return maxActiveProcessors_;
+ }
/**
* Set the maximum # of connections waiting in handler/task before overload.
@@ -517,21 +551,27 @@
*
* @return Maxium frame size, in bytes.
*/
- size_t getMaxFrameSize() const { return maxFrameSize_; }
+ size_t getMaxFrameSize() const {
+ return maxFrameSize_;
+ }
/**
* Set the maximum allowed frame size.
*
* @param maxFrameSize The new maximum frame size.
*/
- void setMaxFrameSize(size_t maxFrameSize) { maxFrameSize_ = maxFrameSize; }
+ void setMaxFrameSize(size_t maxFrameSize) {
+ maxFrameSize_ = maxFrameSize;
+ }
/**
* Get fraction of maximum limits before an overload condition is cleared.
*
* @return hysteresis fraction
*/
- double getOverloadHysteresis() const { return overloadHysteresis_; }
+ double getOverloadHysteresis() const {
+ return overloadHysteresis_;
+ }
/**
* Set fraction of maximum limits before an overload condition is cleared.
@@ -550,28 +590,36 @@
*
* @return a TOverloadAction enum value for the currently set action.
*/
- TOverloadAction getOverloadAction() const { return overloadAction_; }
+ TOverloadAction getOverloadAction() const {
+ return overloadAction_;
+ }
/**
* Set the action the server is to take on overload.
*
* @param overloadAction a TOverloadAction enum value for the action.
*/
- void setOverloadAction(TOverloadAction overloadAction) { overloadAction_ = overloadAction; }
+ void setOverloadAction(TOverloadAction overloadAction) {
+ overloadAction_ = overloadAction;
+ }
/**
* Get the time in milliseconds after which a task expires (0 == infinite).
*
* @return a 64-bit time in milliseconds.
*/
- int64_t getTaskExpireTime() const { return taskExpireTime_; }
+ int64_t getTaskExpireTime() const {
+ return taskExpireTime_;
+ }
/**
* Set the time in milliseconds after which a task expires (0 == infinite).
*
* @param taskExpireTime a 64-bit time in milliseconds.
*/
- void setTaskExpireTime(int64_t taskExpireTime) { taskExpireTime_ = taskExpireTime; }
+ void setTaskExpireTime(int64_t taskExpireTime) {
+ taskExpireTime_ = taskExpireTime;
+ }
/**
* Determine if the server is currently overloaded.
@@ -595,21 +643,27 @@
*
* @return # bytes we initialize a TConnection object's write buffer to.
*/
- size_t getWriteBufferDefaultSize() const { return writeBufferDefaultSize_; }
+ size_t getWriteBufferDefaultSize() const {
+ return writeBufferDefaultSize_;
+ }
/**
* Set the starting size of a TConnection object's write buffer.
*
* @param size # bytes we initialize a TConnection object's write buffer to.
*/
- void setWriteBufferDefaultSize(size_t size) { writeBufferDefaultSize_ = size; }
+ void setWriteBufferDefaultSize(size_t size) {
+ writeBufferDefaultSize_ = size;
+ }
/**
* Get the maximum size of read buffer allocated to idle TConnection objects.
*
* @return # bytes beyond which we will dealloc idle buffer.
*/
- size_t getIdleReadBufferLimit() const { return idleReadBufferLimit_; }
+ size_t getIdleReadBufferLimit() const {
+ return idleReadBufferLimit_;
+ }
/**
* [NOTE: This is for backwards compatibility, use getIdleReadBufferLimit().]
@@ -617,7 +671,9 @@
*
* @return # bytes beyond which we will dealloc idle buffer.
*/
- size_t getIdleBufferMemLimit() const { return idleReadBufferLimit_; }
+ size_t getIdleBufferMemLimit() const {
+ return idleReadBufferLimit_;
+ }
/**
* Set the maximum size read buffer allocated to idle TConnection objects.
@@ -628,7 +684,9 @@
*
* @param limit of bytes beyond which we will shrink buffers when checked.
*/
- void setIdleReadBufferLimit(size_t limit) { idleReadBufferLimit_ = limit; }
+ void setIdleReadBufferLimit(size_t limit) {
+ idleReadBufferLimit_ = limit;
+ }
/**
* [NOTE: This is for backwards compatibility, use setIdleReadBufferLimit().]
@@ -640,14 +698,20 @@
*
* @param limit of bytes beyond which we will shrink buffers when checked.
*/
- void setIdleBufferMemLimit(size_t limit) { idleReadBufferLimit_ = limit; }
+ void setIdleBufferMemLimit(size_t limit) {
+ idleReadBufferLimit_ = limit;
+ }
+
+
/**
* Get the maximum size of write buffer allocated to idle TConnection objects.
*
* @return # bytes beyond which we will reallocate buffers when checked.
*/
- size_t getIdleWriteBufferLimit() const { return idleWriteBufferLimit_; }
+ size_t getIdleWriteBufferLimit() const {
+ return idleWriteBufferLimit_;
+ }
/**
* Set the maximum size write buffer allocated to idle TConnection objects.
@@ -658,14 +722,18 @@
*
* @param limit of bytes beyond which we will shrink buffers when idle.
*/
- void setIdleWriteBufferLimit(size_t limit) { idleWriteBufferLimit_ = limit; }
+ void setIdleWriteBufferLimit(size_t limit) {
+ idleWriteBufferLimit_ = limit;
+ }
/**
* Get # of calls made between buffer size checks. 0 means disabled.
*
* @return # of calls between buffer size checks.
*/
- int32_t getResizeBufferEveryN() const { return resizeBufferEveryN_; }
+ int32_t getResizeBufferEveryN() const {
+ return resizeBufferEveryN_;
+ }
/**
* Check buffer sizes every "count" calls. This allows buffer limits
@@ -674,7 +742,9 @@
*
* @param count the number of calls between checks, or 0 to disable
*/
- void setResizeBufferEveryN(int32_t count) { resizeBufferEveryN_ = count; }
+ void setResizeBufferEveryN(int32_t count) {
+ resizeBufferEveryN_ = count;
+ }
/**
* Main workhorse function, starts up the server listening on a port and
@@ -714,7 +784,7 @@
*/
event_base* getUserEventBase() const { return userEventBase_; }
-private:
+ private:
/**
* Callback function that the threadmanager calls when a task reaches
* its expiration time. It is needed to clean up the expired connection.
@@ -733,7 +803,8 @@
* @param addrLen the length of addr
* @return pointer to initialized TConnection object.
*/
- TConnection* createConnection(THRIFT_SOCKET socket, const sockaddr* addr, socklen_t addrLen);
+ TConnection* createConnection(THRIFT_SOCKET socket, const sockaddr* addr,
+ socklen_t addrLen);
/**
* Returns a connection to pool or deletion. If the connection pool
@@ -746,7 +817,7 @@
};
class TNonblockingIOThread : public Runnable {
-public:
+ public:
// Creates an IO thread and sets up the event base. The listenSocket should
// be a valid FD on which listen() has already been called. If the
// listenSocket is < 0, accepting will not be done.
@@ -797,7 +868,7 @@
/// Registers the events for the notification & listen sockets
void registerEvents();
-private:
+ private:
/**
* C-callable event handler for signaling task completion. Provides a
* callback that libevent can understand that will read a connection
@@ -832,7 +903,7 @@
/// Sets (or clears) high priority scheduling status for the current thread.
void setCurrentThreadHighPriority(bool value);
-private:
+ private:
/// associated server
TNonblockingServer* server_;
@@ -861,14 +932,13 @@
/// Used with eventBase_ for task completion notification
struct event notificationEvent_;
- /// File descriptors for pipe used for task completion notification.
+ /// File descriptors for pipe used for task completion notification.
evutil_socket_t notificationPipeFDs_[2];
/// Actual IO Thread
boost::shared_ptr<Thread> thread_;
};
-}
-}
-} // apache::thrift::server
+
+}}} // apache::thrift::server
#endif // #ifndef _THRIFT_SERVER_TNONBLOCKINGSERVER_H_
diff --git a/lib/cpp/src/thrift/server/TServer.cpp b/lib/cpp/src/thrift/server/TServer.cpp
old mode 100644
new mode 100755
index df731c2..5e82ce6
--- a/lib/cpp/src/thrift/server/TServer.cpp
+++ b/lib/cpp/src/thrift/server/TServer.cpp
@@ -30,23 +30,20 @@
#include <unistd.h>
#endif
-namespace apache {
-namespace thrift {
-namespace server {
+namespace apache { namespace thrift { namespace server {
#ifdef HAVE_SYS_RESOURCE_H
-int increase_max_fds(int max_fds = (1 << 24)) {
+int increase_max_fds(int max_fds=(1<<24)) {
struct rlimit fdmaxrl;
- for (fdmaxrl.rlim_cur = max_fds, fdmaxrl.rlim_max = max_fds;
- max_fds && (setrlimit(RLIMIT_NOFILE, &fdmaxrl) < 0);
- fdmaxrl.rlim_cur = max_fds, fdmaxrl.rlim_max = max_fds) {
+ for(fdmaxrl.rlim_cur = max_fds, fdmaxrl.rlim_max = max_fds;
+ max_fds && (setrlimit(RLIMIT_NOFILE, &fdmaxrl) < 0);
+ fdmaxrl.rlim_cur = max_fds, fdmaxrl.rlim_max = max_fds) {
max_fds /= 2;
}
return static_cast<int>(fdmaxrl.rlim_cur);
}
#endif
-}
-}
-} // apache::thrift::server
+
+}}} // apache::thrift::server
diff --git a/lib/cpp/src/thrift/server/TServer.h b/lib/cpp/src/thrift/server/TServer.h
index c0b222f..7f718da 100644
--- a/lib/cpp/src/thrift/server/TServer.h
+++ b/lib/cpp/src/thrift/server/TServer.h
@@ -27,9 +27,7 @@
#include <boost/shared_ptr.hpp>
-namespace apache {
-namespace thrift {
-namespace server {
+namespace apache { namespace thrift { namespace server {
using apache::thrift::TProcessor;
using apache::thrift::protocol::TBinaryProtocolFactory;
@@ -47,7 +45,8 @@
* instance's state).
*/
class TServerEventHandler {
-public:
+ public:
+
virtual ~TServerEventHandler() {}
/**
@@ -70,8 +69,8 @@
* context.
*/
virtual void deleteContext(void* serverContext,
- boost::shared_ptr<TProtocol> input,
- boost::shared_ptr<TProtocol> output) {
+ boost::shared_ptr<TProtocol>input,
+ boost::shared_ptr<TProtocol>output) {
(void)serverContext;
(void)input;
(void)output;
@@ -80,16 +79,19 @@
/**
* Called when a client is about to call the processor.
*/
- virtual void processContext(void* serverContext, boost::shared_ptr<TTransport> transport) {
+ virtual void processContext(void* serverContext,
+ boost::shared_ptr<TTransport> transport) {
(void)serverContext;
(void)transport;
- }
+}
-protected:
+ protected:
+
/**
* Prevent direct instantiation.
*/
TServerEventHandler() {}
+
};
/**
@@ -97,7 +99,8 @@
*
*/
class TServer : public concurrency::Runnable {
-public:
+ public:
+
virtual ~TServer() {}
virtual void serve() = 0;
@@ -105,122 +108,146 @@
virtual void stop() {}
// Allows running the server as a Runnable thread
- virtual void run() { serve(); }
+ virtual void run() {
+ serve();
+ }
- boost::shared_ptr<TProcessorFactory> getProcessorFactory() { return processorFactory_; }
+ boost::shared_ptr<TProcessorFactory> getProcessorFactory() {
+ return processorFactory_;
+ }
- boost::shared_ptr<TServerTransport> getServerTransport() { return serverTransport_; }
+ boost::shared_ptr<TServerTransport> getServerTransport() {
+ return serverTransport_;
+ }
- boost::shared_ptr<TTransportFactory> getInputTransportFactory() { return inputTransportFactory_; }
+ boost::shared_ptr<TTransportFactory> getInputTransportFactory() {
+ return inputTransportFactory_;
+ }
boost::shared_ptr<TTransportFactory> getOutputTransportFactory() {
return outputTransportFactory_;
}
- boost::shared_ptr<TProtocolFactory> getInputProtocolFactory() { return inputProtocolFactory_; }
+ boost::shared_ptr<TProtocolFactory> getInputProtocolFactory() {
+ return inputProtocolFactory_;
+ }
- boost::shared_ptr<TProtocolFactory> getOutputProtocolFactory() { return outputProtocolFactory_; }
+ boost::shared_ptr<TProtocolFactory> getOutputProtocolFactory() {
+ return outputProtocolFactory_;
+ }
- boost::shared_ptr<TServerEventHandler> getEventHandler() { return eventHandler_; }
+ boost::shared_ptr<TServerEventHandler> getEventHandler() {
+ return eventHandler_;
+ }
protected:
- template <typename ProcessorFactory>
+ template<typename ProcessorFactory>
TServer(const boost::shared_ptr<ProcessorFactory>& processorFactory,
- THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory))
- : processorFactory_(processorFactory) {
+ THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory)):
+ processorFactory_(processorFactory) {
+ setInputTransportFactory(boost::shared_ptr<TTransportFactory>(
+ new TTransportFactory()));
+ setOutputTransportFactory(boost::shared_ptr<TTransportFactory>(
+ new TTransportFactory()));
+ setInputProtocolFactory(boost::shared_ptr<TProtocolFactory>(
+ new TBinaryProtocolFactory()));
+ setOutputProtocolFactory(boost::shared_ptr<TProtocolFactory>(
+ new TBinaryProtocolFactory()));
+ }
+
+ template<typename Processor>
+ TServer(const boost::shared_ptr<Processor>& processor,
+ THRIFT_OVERLOAD_IF(Processor, TProcessor)):
+ processorFactory_(new TSingletonProcessorFactory(processor)) {
setInputTransportFactory(boost::shared_ptr<TTransportFactory>(new TTransportFactory()));
setOutputTransportFactory(boost::shared_ptr<TTransportFactory>(new TTransportFactory()));
setInputProtocolFactory(boost::shared_ptr<TProtocolFactory>(new TBinaryProtocolFactory()));
setOutputProtocolFactory(boost::shared_ptr<TProtocolFactory>(new TBinaryProtocolFactory()));
}
- template <typename Processor>
- TServer(const boost::shared_ptr<Processor>& processor, THRIFT_OVERLOAD_IF(Processor, TProcessor))
- : processorFactory_(new TSingletonProcessorFactory(processor)) {
- setInputTransportFactory(boost::shared_ptr<TTransportFactory>(new TTransportFactory()));
- setOutputTransportFactory(boost::shared_ptr<TTransportFactory>(new TTransportFactory()));
- setInputProtocolFactory(boost::shared_ptr<TProtocolFactory>(new TBinaryProtocolFactory()));
- setOutputProtocolFactory(boost::shared_ptr<TProtocolFactory>(new TBinaryProtocolFactory()));
- }
-
- template <typename ProcessorFactory>
+ template<typename ProcessorFactory>
TServer(const boost::shared_ptr<ProcessorFactory>& processorFactory,
const boost::shared_ptr<TServerTransport>& serverTransport,
- THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory))
- : processorFactory_(processorFactory), serverTransport_(serverTransport) {
- setInputTransportFactory(boost::shared_ptr<TTransportFactory>(new TTransportFactory()));
- setOutputTransportFactory(boost::shared_ptr<TTransportFactory>(new TTransportFactory()));
- setInputProtocolFactory(boost::shared_ptr<TProtocolFactory>(new TBinaryProtocolFactory()));
- setOutputProtocolFactory(boost::shared_ptr<TProtocolFactory>(new TBinaryProtocolFactory()));
+ THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory)):
+ processorFactory_(processorFactory),
+ serverTransport_(serverTransport) {
+ setInputTransportFactory(boost::shared_ptr<TTransportFactory>(
+ new TTransportFactory()));
+ setOutputTransportFactory(boost::shared_ptr<TTransportFactory>(
+ new TTransportFactory()));
+ setInputProtocolFactory(boost::shared_ptr<TProtocolFactory>(
+ new TBinaryProtocolFactory()));
+ setOutputProtocolFactory(boost::shared_ptr<TProtocolFactory>(
+ new TBinaryProtocolFactory()));
}
- template <typename Processor>
+ template<typename Processor>
TServer(const boost::shared_ptr<Processor>& processor,
const boost::shared_ptr<TServerTransport>& serverTransport,
- THRIFT_OVERLOAD_IF(Processor, TProcessor))
- : processorFactory_(new TSingletonProcessorFactory(processor)),
- serverTransport_(serverTransport) {
+ THRIFT_OVERLOAD_IF(Processor, TProcessor)):
+ processorFactory_(new TSingletonProcessorFactory(processor)),
+ serverTransport_(serverTransport) {
setInputTransportFactory(boost::shared_ptr<TTransportFactory>(new TTransportFactory()));
setOutputTransportFactory(boost::shared_ptr<TTransportFactory>(new TTransportFactory()));
setInputProtocolFactory(boost::shared_ptr<TProtocolFactory>(new TBinaryProtocolFactory()));
setOutputProtocolFactory(boost::shared_ptr<TProtocolFactory>(new TBinaryProtocolFactory()));
}
- template <typename ProcessorFactory>
+ template<typename ProcessorFactory>
TServer(const boost::shared_ptr<ProcessorFactory>& processorFactory,
const boost::shared_ptr<TServerTransport>& serverTransport,
const boost::shared_ptr<TTransportFactory>& transportFactory,
const boost::shared_ptr<TProtocolFactory>& protocolFactory,
- THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory))
- : processorFactory_(processorFactory),
- serverTransport_(serverTransport),
- inputTransportFactory_(transportFactory),
- outputTransportFactory_(transportFactory),
- inputProtocolFactory_(protocolFactory),
- outputProtocolFactory_(protocolFactory) {}
+ THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory)):
+ processorFactory_(processorFactory),
+ serverTransport_(serverTransport),
+ inputTransportFactory_(transportFactory),
+ outputTransportFactory_(transportFactory),
+ inputProtocolFactory_(protocolFactory),
+ outputProtocolFactory_(protocolFactory) {}
- template <typename Processor>
+ template<typename Processor>
TServer(const boost::shared_ptr<Processor>& processor,
const boost::shared_ptr<TServerTransport>& serverTransport,
const boost::shared_ptr<TTransportFactory>& transportFactory,
const boost::shared_ptr<TProtocolFactory>& protocolFactory,
- THRIFT_OVERLOAD_IF(Processor, TProcessor))
- : processorFactory_(new TSingletonProcessorFactory(processor)),
- serverTransport_(serverTransport),
- inputTransportFactory_(transportFactory),
- outputTransportFactory_(transportFactory),
- inputProtocolFactory_(protocolFactory),
- outputProtocolFactory_(protocolFactory) {}
+ THRIFT_OVERLOAD_IF(Processor, TProcessor)):
+ processorFactory_(new TSingletonProcessorFactory(processor)),
+ serverTransport_(serverTransport),
+ inputTransportFactory_(transportFactory),
+ outputTransportFactory_(transportFactory),
+ inputProtocolFactory_(protocolFactory),
+ outputProtocolFactory_(protocolFactory) {}
- template <typename ProcessorFactory>
+ template<typename ProcessorFactory>
TServer(const boost::shared_ptr<ProcessorFactory>& processorFactory,
const boost::shared_ptr<TServerTransport>& serverTransport,
const boost::shared_ptr<TTransportFactory>& inputTransportFactory,
const boost::shared_ptr<TTransportFactory>& outputTransportFactory,
const boost::shared_ptr<TProtocolFactory>& inputProtocolFactory,
const boost::shared_ptr<TProtocolFactory>& outputProtocolFactory,
- THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory))
- : processorFactory_(processorFactory),
- serverTransport_(serverTransport),
- inputTransportFactory_(inputTransportFactory),
- outputTransportFactory_(outputTransportFactory),
- inputProtocolFactory_(inputProtocolFactory),
- outputProtocolFactory_(outputProtocolFactory) {}
+ THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory)):
+ processorFactory_(processorFactory),
+ serverTransport_(serverTransport),
+ inputTransportFactory_(inputTransportFactory),
+ outputTransportFactory_(outputTransportFactory),
+ inputProtocolFactory_(inputProtocolFactory),
+ outputProtocolFactory_(outputProtocolFactory) {}
- template <typename Processor>
+ template<typename Processor>
TServer(const boost::shared_ptr<Processor>& processor,
const boost::shared_ptr<TServerTransport>& serverTransport,
const boost::shared_ptr<TTransportFactory>& inputTransportFactory,
const boost::shared_ptr<TTransportFactory>& outputTransportFactory,
const boost::shared_ptr<TProtocolFactory>& inputProtocolFactory,
const boost::shared_ptr<TProtocolFactory>& outputProtocolFactory,
- THRIFT_OVERLOAD_IF(Processor, TProcessor))
- : processorFactory_(new TSingletonProcessorFactory(processor)),
- serverTransport_(serverTransport),
- inputTransportFactory_(inputTransportFactory),
- outputTransportFactory_(outputTransportFactory),
- inputProtocolFactory_(inputProtocolFactory),
- outputProtocolFactory_(outputProtocolFactory) {}
+ THRIFT_OVERLOAD_IF(Processor, TProcessor)):
+ processorFactory_(new TSingletonProcessorFactory(processor)),
+ serverTransport_(serverTransport),
+ inputTransportFactory_(inputTransportFactory),
+ outputTransportFactory_(outputTransportFactory),
+ inputProtocolFactory_(inputProtocolFactory),
+ outputProtocolFactory_(outputProtocolFactory) {}
/**
* Get a TProcessor to handle calls on a particular connection.
@@ -229,9 +256,10 @@
* call). This allows the TProcessorFactory to return a different processor
* for each connection if it desires.
*/
- boost::shared_ptr<TProcessor> getProcessor(boost::shared_ptr<TProtocol> inputProtocol,
- boost::shared_ptr<TProtocol> outputProtocol,
- boost::shared_ptr<TTransport> transport) {
+ boost::shared_ptr<TProcessor> getProcessor(
+ boost::shared_ptr<TProtocol> inputProtocol,
+ boost::shared_ptr<TProtocol> outputProtocol,
+ boost::shared_ptr<TTransport> transport) {
TConnectionInfo connInfo;
connInfo.input = inputProtocol;
connInfo.output = outputProtocol;
@@ -271,6 +299,7 @@
void setServerEventHandler(boost::shared_ptr<TServerEventHandler> eventHandler) {
eventHandler_ = eventHandler;
}
+
};
/**
@@ -279,10 +308,9 @@
* By default, tries to increase it to as much as 2^24.
*/
#ifdef HAVE_SYS_RESOURCE_H
-int increase_max_fds(int max_fds = (1 << 24));
+ int increase_max_fds(int max_fds=(1<<24));
#endif
-}
-}
-} // apache::thrift::server
+
+}}} // apache::thrift::server
#endif // #ifndef _THRIFT_SERVER_TSERVER_H_
diff --git a/lib/cpp/src/thrift/server/TSimpleServer.cpp b/lib/cpp/src/thrift/server/TSimpleServer.cpp
index fa6bff5..5fc4c97 100644
--- a/lib/cpp/src/thrift/server/TSimpleServer.cpp
+++ b/lib/cpp/src/thrift/server/TSimpleServer.cpp
@@ -22,9 +22,7 @@
#include <string>
#include <iostream>
-namespace apache {
-namespace thrift {
-namespace server {
+namespace apache { namespace thrift { namespace server {
using namespace std;
using namespace apache::thrift;
@@ -61,50 +59,33 @@
inputProtocol = inputProtocolFactory_->getProtocol(inputTransport);
outputProtocol = outputProtocolFactory_->getProtocol(outputTransport);
} catch (TTransportException& ttx) {
- if (inputTransport) {
- inputTransport->close();
- }
- if (outputTransport) {
- outputTransport->close();
- }
- if (client) {
- client->close();
- }
+ if (inputTransport) { inputTransport->close(); }
+ if (outputTransport) { outputTransport->close(); }
+ if (client) { client->close(); }
if (!stop_ || ttx.getType() != TTransportException::INTERRUPTED) {
- string errStr = string("TServerTransport died on accept: ") + ttx.what();
- GlobalOutput(errStr.c_str());
+ string errStr = string("TServerTransport died on accept: ") + ttx.what();
+ GlobalOutput(errStr.c_str());
}
continue;
} catch (TException& tx) {
- if (inputTransport) {
- inputTransport->close();
- }
- if (outputTransport) {
- outputTransport->close();
- }
- if (client) {
- client->close();
- }
+ if (inputTransport) { inputTransport->close(); }
+ if (outputTransport) { outputTransport->close(); }
+ if (client) { client->close(); }
string errStr = string("Some kind of accept exception: ") + tx.what();
GlobalOutput(errStr.c_str());
continue;
} catch (string s) {
- if (inputTransport) {
- inputTransport->close();
- }
- if (outputTransport) {
- outputTransport->close();
- }
- if (client) {
- client->close();
- }
+ if (inputTransport) { inputTransport->close(); }
+ if (outputTransport) { outputTransport->close(); }
+ if (client) { client->close(); }
string errStr = string("Some kind of accept exception: ") + s;
GlobalOutput(errStr.c_str());
break;
}
// Get the processor
- shared_ptr<TProcessor> processor = getProcessor(inputProtocol, outputProtocol, client);
+ shared_ptr<TProcessor> processor = getProcessor(inputProtocol,
+ outputProtocol, client);
void* connectionContext = NULL;
if (eventHandler_) {
@@ -115,8 +96,9 @@
if (eventHandler_) {
eventHandler_->processContext(connectionContext, client);
}
- if (!processor->process(inputProtocol, outputProtocol, connectionContext) ||
- // Peek ahead, is the remote side closed?
+ if (!processor->process(inputProtocol, outputProtocol,
+ connectionContext) ||
+ // Peek ahead, is the remote side closed?
!inputProtocol->getTransport()->peek()) {
break;
}
@@ -125,7 +107,8 @@
string errStr = string("TSimpleServer client died: ") + ttx.what();
GlobalOutput(errStr.c_str());
} catch (const std::exception& x) {
- GlobalOutput.printf("TSimpleServer exception: %s: %s", typeid(x).name(), x.what());
+ GlobalOutput.printf("TSimpleServer exception: %s: %s",
+ typeid(x).name(), x.what());
} catch (...) {
GlobalOutput("TSimpleServer uncaught exception.");
}
@@ -136,19 +119,22 @@
try {
inputTransport->close();
} catch (const TTransportException& ttx) {
- string errStr = string("TSimpleServer input close failed: ") + ttx.what();
+ string errStr = string("TSimpleServer input close failed: ")
+ + ttx.what();
GlobalOutput(errStr.c_str());
}
try {
outputTransport->close();
} catch (const TTransportException& ttx) {
- string errStr = string("TSimpleServer output close failed: ") + ttx.what();
+ string errStr = string("TSimpleServer output close failed: ")
+ + ttx.what();
GlobalOutput(errStr.c_str());
}
try {
client->close();
} catch (const TTransportException& ttx) {
- string errStr = string("TSimpleServer client close failed: ") + ttx.what();
+ string errStr = string("TSimpleServer client close failed: ")
+ + ttx.what();
GlobalOutput(errStr.c_str());
}
}
@@ -156,13 +142,12 @@
if (stop_) {
try {
serverTransport_->close();
- } catch (TTransportException& ttx) {
+ } catch (TTransportException &ttx) {
string errStr = string("TServerTransport failed on close: ") + ttx.what();
GlobalOutput(errStr.c_str());
}
stop_ = false;
}
}
-}
-}
-} // apache::thrift::server
+
+}}} // apache::thrift::server
diff --git a/lib/cpp/src/thrift/server/TSimpleServer.h b/lib/cpp/src/thrift/server/TSimpleServer.h
index 967f834..f9e0e2b 100644
--- a/lib/cpp/src/thrift/server/TSimpleServer.h
+++ b/lib/cpp/src/thrift/server/TSimpleServer.h
@@ -23,9 +23,7 @@
#include <thrift/server/TServer.h>
#include <thrift/transport/TServerTransport.h>
-namespace apache {
-namespace thrift {
-namespace server {
+namespace apache { namespace thrift { namespace server {
/**
* This is the most basic simple server. It is single-threaded and runs a
@@ -35,54 +33,55 @@
*
*/
class TSimpleServer : public TServer {
-public:
- template <typename ProcessorFactory>
- TSimpleServer(const boost::shared_ptr<ProcessorFactory>& processorFactory,
- const boost::shared_ptr<TServerTransport>& serverTransport,
- const boost::shared_ptr<TTransportFactory>& transportFactory,
- const boost::shared_ptr<TProtocolFactory>& protocolFactory,
- THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory))
- : TServer(processorFactory, serverTransport, transportFactory, protocolFactory), stop_(false) {}
+ public:
+ template<typename ProcessorFactory>
+ TSimpleServer(
+ const boost::shared_ptr<ProcessorFactory>& processorFactory,
+ const boost::shared_ptr<TServerTransport>& serverTransport,
+ const boost::shared_ptr<TTransportFactory>& transportFactory,
+ const boost::shared_ptr<TProtocolFactory>& protocolFactory,
+ THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory)) :
+ TServer(processorFactory, serverTransport, transportFactory,
+ protocolFactory),
+ stop_(false) {}
- template <typename Processor>
- TSimpleServer(const boost::shared_ptr<Processor>& processor,
- const boost::shared_ptr<TServerTransport>& serverTransport,
- const boost::shared_ptr<TTransportFactory>& transportFactory,
- const boost::shared_ptr<TProtocolFactory>& protocolFactory,
- THRIFT_OVERLOAD_IF(Processor, TProcessor))
- : TServer(processor, serverTransport, transportFactory, protocolFactory), stop_(false) {}
+ template<typename Processor>
+ TSimpleServer(
+ const boost::shared_ptr<Processor>& processor,
+ const boost::shared_ptr<TServerTransport>& serverTransport,
+ const boost::shared_ptr<TTransportFactory>& transportFactory,
+ const boost::shared_ptr<TProtocolFactory>& protocolFactory,
+ THRIFT_OVERLOAD_IF(Processor, TProcessor)) :
+ TServer(processor, serverTransport, transportFactory, protocolFactory),
+ stop_(false) {}
- template <typename ProcessorFactory>
- TSimpleServer(const boost::shared_ptr<ProcessorFactory>& processorFactory,
- const boost::shared_ptr<TServerTransport>& serverTransport,
- const boost::shared_ptr<TTransportFactory>& inputTransportFactory,
- const boost::shared_ptr<TTransportFactory>& outputTransportFactory,
- const boost::shared_ptr<TProtocolFactory>& inputProtocolFactory,
- const boost::shared_ptr<TProtocolFactory>& outputProtocolFactory,
- THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory))
- : TServer(processorFactory,
- serverTransport,
- inputTransportFactory,
- outputTransportFactory,
- inputProtocolFactory,
- outputProtocolFactory),
- stop_(false) {}
+ template<typename ProcessorFactory>
+ TSimpleServer(
+ const boost::shared_ptr<ProcessorFactory>& processorFactory,
+ const boost::shared_ptr<TServerTransport>& serverTransport,
+ const boost::shared_ptr<TTransportFactory>& inputTransportFactory,
+ const boost::shared_ptr<TTransportFactory>& outputTransportFactory,
+ const boost::shared_ptr<TProtocolFactory>& inputProtocolFactory,
+ const boost::shared_ptr<TProtocolFactory>& outputProtocolFactory,
+ THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory)) :
+ TServer(processorFactory, serverTransport,
+ inputTransportFactory, outputTransportFactory,
+ inputProtocolFactory, outputProtocolFactory),
+ stop_(false) {}
- template <typename Processor>
- TSimpleServer(const boost::shared_ptr<Processor>& processor,
- const boost::shared_ptr<TServerTransport>& serverTransport,
- const boost::shared_ptr<TTransportFactory>& inputTransportFactory,
- const boost::shared_ptr<TTransportFactory>& outputTransportFactory,
- const boost::shared_ptr<TProtocolFactory>& inputProtocolFactory,
- const boost::shared_ptr<TProtocolFactory>& outputProtocolFactory,
- THRIFT_OVERLOAD_IF(Processor, TProcessor))
- : TServer(processor,
- serverTransport,
- inputTransportFactory,
- outputTransportFactory,
- inputProtocolFactory,
- outputProtocolFactory),
- stop_(false) {}
+ template<typename Processor>
+ TSimpleServer(
+ const boost::shared_ptr<Processor>& processor,
+ const boost::shared_ptr<TServerTransport>& serverTransport,
+ const boost::shared_ptr<TTransportFactory>& inputTransportFactory,
+ const boost::shared_ptr<TTransportFactory>& outputTransportFactory,
+ const boost::shared_ptr<TProtocolFactory>& inputProtocolFactory,
+ const boost::shared_ptr<TProtocolFactory>& outputProtocolFactory,
+ THRIFT_OVERLOAD_IF(Processor, TProcessor)) :
+ TServer(processor, serverTransport,
+ inputTransportFactory, outputTransportFactory,
+ inputProtocolFactory, outputProtocolFactory),
+ stop_(false) {}
~TSimpleServer() {}
@@ -93,11 +92,11 @@
serverTransport_->interrupt();
}
-protected:
+ protected:
bool stop_;
+
};
-}
-}
-} // apache::thrift::server
+
+}}} // apache::thrift::server
#endif // #ifndef _THRIFT_SERVER_TSIMPLESERVER_H_
diff --git a/lib/cpp/src/thrift/server/TThreadPoolServer.cpp b/lib/cpp/src/thrift/server/TThreadPoolServer.cpp
index 0530d8d..da33ec2 100644
--- a/lib/cpp/src/thrift/server/TThreadPoolServer.cpp
+++ b/lib/cpp/src/thrift/server/TThreadPoolServer.cpp
@@ -26,9 +26,7 @@
#include <string>
#include <iostream>
-namespace apache {
-namespace thrift {
-namespace server {
+namespace apache { namespace thrift { namespace server {
using boost::shared_ptr;
using namespace std;
@@ -40,21 +38,24 @@
class TThreadPoolServer::Task : public Runnable {
public:
- Task(TThreadPoolServer& server,
+
+ Task(TThreadPoolServer &server,
shared_ptr<TProcessor> processor,
shared_ptr<TProtocol> input,
shared_ptr<TProtocol> output,
- shared_ptr<TTransport> transport)
- : server_(server),
- processor_(processor),
- input_(input),
- output_(output),
- transport_(transport) {}
+ shared_ptr<TTransport> transport) :
+ server_(server),
+ processor_(processor),
+ input_(input),
+ output_(output),
+ transport_(transport) {
+ }
~Task() {}
void run() {
- boost::shared_ptr<TServerEventHandler> eventHandler = server_.getEventHandler();
+ boost::shared_ptr<TServerEventHandler> eventHandler =
+ server_.getEventHandler();
void* connectionContext = NULL;
if (eventHandler) {
connectionContext = eventHandler->createContext(input_, output_);
@@ -64,8 +65,8 @@
if (eventHandler) {
eventHandler->processContext(connectionContext, transport_);
}
- if (!processor_->process(input_, output_, connectionContext)
- || !input_->getTransport()->peek()) {
+ if (!processor_->process(input_, output_, connectionContext) ||
+ !input_->getTransport()->peek()) {
break;
}
}
@@ -75,11 +76,11 @@
// string errStr = string("TThreadPoolServer client died: ") + ttx.what();
// GlobalOutput(errStr.c_str());
} catch (const std::exception& x) {
- GlobalOutput.printf("TThreadPoolServer exception %s: %s", typeid(x).name(), x.what());
+ GlobalOutput.printf("TThreadPoolServer exception %s: %s",
+ typeid(x).name(), x.what());
} catch (...) {
- GlobalOutput(
- "TThreadPoolServer, unexpected exception in "
- "TThreadPoolServer::Task::run()");
+ GlobalOutput("TThreadPoolServer, unexpected exception in "
+ "TThreadPoolServer::Task::run()");
}
if (eventHandler) {
@@ -98,9 +99,10 @@
string errStr = string("TThreadPoolServer output close failed: ") + ttx.what();
GlobalOutput(errStr.c_str());
}
+
}
-private:
+ private:
TServer& server_;
shared_ptr<TProcessor> processor_;
shared_ptr<TProtocol> input_;
@@ -108,8 +110,7 @@
shared_ptr<TTransport> transport_;
};
-TThreadPoolServer::~TThreadPoolServer() {
-}
+TThreadPoolServer::~TThreadPoolServer() {}
void TThreadPoolServer::serve() {
shared_ptr<TTransport> client;
@@ -143,51 +144,34 @@
inputProtocol = inputProtocolFactory_->getProtocol(inputTransport);
outputProtocol = outputProtocolFactory_->getProtocol(outputTransport);
- shared_ptr<TProcessor> processor = getProcessor(inputProtocol, outputProtocol, client);
+ shared_ptr<TProcessor> processor = getProcessor(inputProtocol,
+ outputProtocol, client);
// Add to threadmanager pool
- shared_ptr<TThreadPoolServer::Task> task(
- new TThreadPoolServer::Task(*this, processor, inputProtocol, outputProtocol, client));
+ shared_ptr<TThreadPoolServer::Task> task(new TThreadPoolServer::Task(
+ *this, processor, inputProtocol, outputProtocol, client));
threadManager_->add(task, timeout_, taskExpiration_);
} catch (TTransportException& ttx) {
- if (inputTransport) {
- inputTransport->close();
- }
- if (outputTransport) {
- outputTransport->close();
- }
- if (client) {
- client->close();
- }
+ if (inputTransport) { inputTransport->close(); }
+ if (outputTransport) { outputTransport->close(); }
+ if (client) { client->close(); }
if (!stop_ || ttx.getType() != TTransportException::INTERRUPTED) {
string errStr = string("TThreadPoolServer: TServerTransport died on accept: ") + ttx.what();
GlobalOutput(errStr.c_str());
}
continue;
} catch (TException& tx) {
- if (inputTransport) {
- inputTransport->close();
- }
- if (outputTransport) {
- outputTransport->close();
- }
- if (client) {
- client->close();
- }
+ if (inputTransport) { inputTransport->close(); }
+ if (outputTransport) { outputTransport->close(); }
+ if (client) { client->close(); }
string errStr = string("TThreadPoolServer: Caught TException: ") + tx.what();
GlobalOutput(errStr.c_str());
continue;
} catch (string s) {
- if (inputTransport) {
- inputTransport->close();
- }
- if (outputTransport) {
- outputTransport->close();
- }
- if (client) {
- client->close();
- }
+ if (inputTransport) { inputTransport->close(); }
+ if (outputTransport) { outputTransport->close(); }
+ if (client) { client->close(); }
string errStr = "TThreadPoolServer: Unknown exception: " + s;
GlobalOutput(errStr.c_str());
break;
@@ -199,12 +183,13 @@
try {
serverTransport_->close();
threadManager_->join();
- } catch (TException& tx) {
+ } catch (TException &tx) {
string errStr = string("TThreadPoolServer: Exception shutting down: ") + tx.what();
GlobalOutput(errStr.c_str());
}
stop_ = false;
}
+
}
int64_t TThreadPoolServer::getTimeout() const {
@@ -222,6 +207,5 @@
void TThreadPoolServer::setTaskExpiration(int64_t value) {
taskExpiration_ = value;
}
-}
-}
-} // apache::thrift::server
+
+}}} // apache::thrift::server
diff --git a/lib/cpp/src/thrift/server/TThreadPoolServer.h b/lib/cpp/src/thrift/server/TThreadPoolServer.h
index ad7e7ef..8a1fc16 100644
--- a/lib/cpp/src/thrift/server/TThreadPoolServer.h
+++ b/lib/cpp/src/thrift/server/TThreadPoolServer.h
@@ -26,9 +26,7 @@
#include <boost/shared_ptr.hpp>
-namespace apache {
-namespace thrift {
-namespace server {
+namespace apache { namespace thrift { namespace server {
using apache::thrift::concurrency::ThreadManager;
using apache::thrift::protocol::TProtocolFactory;
@@ -36,74 +34,73 @@
using apache::thrift::transport::TTransportFactory;
class TThreadPoolServer : public TServer {
-public:
+ public:
class Task;
- template <typename ProcessorFactory>
- TThreadPoolServer(const boost::shared_ptr<ProcessorFactory>& processorFactory,
- const boost::shared_ptr<TServerTransport>& serverTransport,
- const boost::shared_ptr<TTransportFactory>& transportFactory,
- const boost::shared_ptr<TProtocolFactory>& protocolFactory,
- const boost::shared_ptr<ThreadManager>& threadManager,
- THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory))
- : TServer(processorFactory, serverTransport, transportFactory, protocolFactory),
- threadManager_(threadManager),
- stop_(false),
- timeout_(0),
- taskExpiration_(0) {}
+ template<typename ProcessorFactory>
+ TThreadPoolServer(
+ const boost::shared_ptr<ProcessorFactory>& processorFactory,
+ const boost::shared_ptr<TServerTransport>& serverTransport,
+ const boost::shared_ptr<TTransportFactory>& transportFactory,
+ const boost::shared_ptr<TProtocolFactory>& protocolFactory,
+ const boost::shared_ptr<ThreadManager>& threadManager,
+ THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory)) :
+ TServer(processorFactory, serverTransport, transportFactory,
+ protocolFactory),
+ threadManager_(threadManager),
+ stop_(false),
+ timeout_(0),
+ taskExpiration_(0) {}
- template <typename Processor>
- TThreadPoolServer(const boost::shared_ptr<Processor>& processor,
- const boost::shared_ptr<TServerTransport>& serverTransport,
- const boost::shared_ptr<TTransportFactory>& transportFactory,
- const boost::shared_ptr<TProtocolFactory>& protocolFactory,
- const boost::shared_ptr<ThreadManager>& threadManager,
- THRIFT_OVERLOAD_IF(Processor, TProcessor))
- : TServer(processor, serverTransport, transportFactory, protocolFactory),
- threadManager_(threadManager),
- stop_(false),
- timeout_(0),
- taskExpiration_(0) {}
+ template<typename Processor>
+ TThreadPoolServer(
+ const boost::shared_ptr<Processor>& processor,
+ const boost::shared_ptr<TServerTransport>& serverTransport,
+ const boost::shared_ptr<TTransportFactory>& transportFactory,
+ const boost::shared_ptr<TProtocolFactory>& protocolFactory,
+ const boost::shared_ptr<ThreadManager>& threadManager,
+ THRIFT_OVERLOAD_IF(Processor, TProcessor)) :
+ TServer(processor, serverTransport, transportFactory, protocolFactory),
+ threadManager_(threadManager),
+ stop_(false),
+ timeout_(0),
+ taskExpiration_(0) {}
- template <typename ProcessorFactory>
- TThreadPoolServer(const boost::shared_ptr<ProcessorFactory>& processorFactory,
- const boost::shared_ptr<TServerTransport>& serverTransport,
- const boost::shared_ptr<TTransportFactory>& inputTransportFactory,
- const boost::shared_ptr<TTransportFactory>& outputTransportFactory,
- const boost::shared_ptr<TProtocolFactory>& inputProtocolFactory,
- const boost::shared_ptr<TProtocolFactory>& outputProtocolFactory,
- const boost::shared_ptr<ThreadManager>& threadManager,
- THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory))
- : TServer(processorFactory,
- serverTransport,
- inputTransportFactory,
- outputTransportFactory,
- inputProtocolFactory,
- outputProtocolFactory),
- threadManager_(threadManager),
- stop_(false),
- timeout_(0),
- taskExpiration_(0) {}
+ template<typename ProcessorFactory>
+ TThreadPoolServer(
+ const boost::shared_ptr<ProcessorFactory>& processorFactory,
+ const boost::shared_ptr<TServerTransport>& serverTransport,
+ const boost::shared_ptr<TTransportFactory>& inputTransportFactory,
+ const boost::shared_ptr<TTransportFactory>& outputTransportFactory,
+ const boost::shared_ptr<TProtocolFactory>& inputProtocolFactory,
+ const boost::shared_ptr<TProtocolFactory>& outputProtocolFactory,
+ const boost::shared_ptr<ThreadManager>& threadManager,
+ THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory)) :
+ TServer(processorFactory, serverTransport,
+ inputTransportFactory, outputTransportFactory,
+ inputProtocolFactory, outputProtocolFactory),
+ threadManager_(threadManager),
+ stop_(false),
+ timeout_(0),
+ taskExpiration_(0) {}
- template <typename Processor>
- TThreadPoolServer(const boost::shared_ptr<Processor>& processor,
- const boost::shared_ptr<TServerTransport>& serverTransport,
- const boost::shared_ptr<TTransportFactory>& inputTransportFactory,
- const boost::shared_ptr<TTransportFactory>& outputTransportFactory,
- const boost::shared_ptr<TProtocolFactory>& inputProtocolFactory,
- const boost::shared_ptr<TProtocolFactory>& outputProtocolFactory,
- const boost::shared_ptr<ThreadManager>& threadManager,
- THRIFT_OVERLOAD_IF(Processor, TProcessor))
- : TServer(processor,
- serverTransport,
- inputTransportFactory,
- outputTransportFactory,
- inputProtocolFactory,
- outputProtocolFactory),
- threadManager_(threadManager),
- stop_(false),
- timeout_(0),
- taskExpiration_(0) {}
+ template<typename Processor>
+ TThreadPoolServer(
+ const boost::shared_ptr<Processor>& processor,
+ const boost::shared_ptr<TServerTransport>& serverTransport,
+ const boost::shared_ptr<TTransportFactory>& inputTransportFactory,
+ const boost::shared_ptr<TTransportFactory>& outputTransportFactory,
+ const boost::shared_ptr<TProtocolFactory>& inputProtocolFactory,
+ const boost::shared_ptr<TProtocolFactory>& outputProtocolFactory,
+ const boost::shared_ptr<ThreadManager>& threadManager,
+ THRIFT_OVERLOAD_IF(Processor, TProcessor)) :
+ TServer(processor, serverTransport,
+ inputTransportFactory, outputTransportFactory,
+ inputProtocolFactory, outputProtocolFactory),
+ threadManager_(threadManager),
+ stop_(false),
+ timeout_(0),
+ taskExpiration_(0) {}
virtual ~TThreadPoolServer();
@@ -122,7 +119,8 @@
virtual void setTaskExpiration(int64_t value);
-protected:
+ protected:
+
boost::shared_ptr<ThreadManager> threadManager_;
volatile bool stop_;
@@ -130,9 +128,9 @@
volatile int64_t timeout_;
volatile int64_t taskExpiration_;
+
};
-}
-}
-} // apache::thrift::server
+
+}}} // apache::thrift::server
#endif // #ifndef _THRIFT_SERVER_TTHREADPOOLSERVER_H_
diff --git a/lib/cpp/src/thrift/server/TThreadedServer.cpp b/lib/cpp/src/thrift/server/TThreadedServer.cpp
index 929ed86..909c3ce 100644
--- a/lib/cpp/src/thrift/server/TThreadedServer.cpp
+++ b/lib/cpp/src/thrift/server/TThreadedServer.cpp
@@ -28,9 +28,7 @@
#include <unistd.h>
#endif
-namespace apache {
-namespace thrift {
-namespace server {
+namespace apache { namespace thrift { namespace server {
using boost::shared_ptr;
using namespace std;
@@ -39,24 +37,27 @@
using namespace apache::thrift::transport;
using namespace apache::thrift::concurrency;
-class TThreadedServer::Task : public Runnable {
+class TThreadedServer::Task: public Runnable {
public:
+
Task(TThreadedServer& server,
shared_ptr<TProcessor> processor,
shared_ptr<TProtocol> input,
shared_ptr<TProtocol> output,
- shared_ptr<TTransport> transport)
- : server_(server),
- processor_(processor),
- input_(input),
- output_(output),
- transport_(transport) {}
+ shared_ptr<TTransport> transport) :
+ server_(server),
+ processor_(processor),
+ input_(input),
+ output_(output),
+ transport_(transport) {
+ }
~Task() {}
void run() {
- boost::shared_ptr<TServerEventHandler> eventHandler = server_.getEventHandler();
+ boost::shared_ptr<TServerEventHandler> eventHandler =
+ server_.getEventHandler();
void* connectionContext = NULL;
if (eventHandler) {
connectionContext = eventHandler->createContext(input_, output_);
@@ -66,8 +67,8 @@
if (eventHandler) {
eventHandler->processContext(connectionContext, transport_);
}
- if (!processor_->process(input_, output_, connectionContext)
- || !input_->getTransport()->peek()) {
+ if (!processor_->process(input_, output_, connectionContext) ||
+ !input_->getTransport()->peek()) {
break;
}
}
@@ -76,8 +77,9 @@
string errStr = string("TThreadedServer client died: ") + ttx.what();
GlobalOutput(errStr.c_str());
}
- } catch (const std::exception& x) {
- GlobalOutput.printf("TThreadedServer exception: %s: %s", typeid(x).name(), x.what());
+ } catch (const std::exception &x) {
+ GlobalOutput.printf("TThreadedServer exception: %s: %s",
+ typeid(x).name(), x.what());
} catch (...) {
GlobalOutput("TThreadedServer uncaught exception.");
}
@@ -106,9 +108,10 @@
server_.tasksMonitor_.notify();
}
}
+
}
-private:
+ private:
TThreadedServer& server_;
friend class TThreadedServer;
@@ -126,8 +129,7 @@
}
}
-TThreadedServer::~TThreadedServer() {
-}
+TThreadedServer::~TThreadedServer() {}
void TThreadedServer::serve() {
@@ -162,16 +164,22 @@
inputProtocol = inputProtocolFactory_->getProtocol(inputTransport);
outputProtocol = outputProtocolFactory_->getProtocol(outputTransport);
- shared_ptr<TProcessor> processor = getProcessor(inputProtocol, outputProtocol, client);
+ shared_ptr<TProcessor> processor = getProcessor(inputProtocol,
+ outputProtocol, client);
- TThreadedServer::Task* task
- = new TThreadedServer::Task(*this, processor, inputProtocol, outputProtocol, client);
+ TThreadedServer::Task* task = new TThreadedServer::Task(*this,
+ processor,
+ inputProtocol,
+ outputProtocol,
+ client);
// Create a task
- shared_ptr<Runnable> runnable = shared_ptr<Runnable>(task);
+ shared_ptr<Runnable> runnable =
+ shared_ptr<Runnable>(task);
// Create a thread for this task
- shared_ptr<Thread> thread = shared_ptr<Thread>(threadFactory_->newThread(runnable));
+ shared_ptr<Thread> thread =
+ shared_ptr<Thread>(threadFactory_->newThread(runnable));
// Insert thread into the set of threads
{
@@ -183,43 +191,25 @@
thread->start();
} catch (TTransportException& ttx) {
- if (inputTransport) {
- inputTransport->close();
- }
- if (outputTransport) {
- outputTransport->close();
- }
- if (client) {
- client->close();
- }
+ if (inputTransport) { inputTransport->close(); }
+ if (outputTransport) { outputTransport->close(); }
+ if (client) { client->close(); }
if (!stop_ || ttx.getType() != TTransportException::INTERRUPTED) {
string errStr = string("TThreadedServer: TServerTransport died on accept: ") + ttx.what();
GlobalOutput(errStr.c_str());
}
continue;
} catch (TException& tx) {
- if (inputTransport) {
- inputTransport->close();
- }
- if (outputTransport) {
- outputTransport->close();
- }
- if (client) {
- client->close();
- }
+ if (inputTransport) { inputTransport->close(); }
+ if (outputTransport) { outputTransport->close(); }
+ if (client) { client->close(); }
string errStr = string("TThreadedServer: Caught TException: ") + tx.what();
GlobalOutput(errStr.c_str());
continue;
} catch (string s) {
- if (inputTransport) {
- inputTransport->close();
- }
- if (outputTransport) {
- outputTransport->close();
- }
- if (client) {
- client->close();
- }
+ if (inputTransport) { inputTransport->close(); }
+ if (outputTransport) { outputTransport->close(); }
+ if (client) { client->close(); }
string errStr = "TThreadedServer: Unknown exception: " + s;
GlobalOutput(errStr.c_str());
break;
@@ -230,7 +220,7 @@
if (stop_) {
try {
serverTransport_->close();
- } catch (TException& tx) {
+ } catch (TException &tx) {
string errStr = string("TThreadedServer: Exception shutting down: ") + tx.what();
GlobalOutput(errStr.c_str());
}
@@ -239,13 +229,13 @@
while (!tasks_.empty()) {
tasksMonitor_.wait();
}
- } catch (TException& tx) {
+ } catch (TException &tx) {
string errStr = string("TThreadedServer: Exception joining workers: ") + tx.what();
GlobalOutput(errStr.c_str());
}
stop_ = false;
}
+
}
-}
-}
-} // apache::thrift::server
+
+}}} // apache::thrift::server
diff --git a/lib/cpp/src/thrift/server/TThreadedServer.h b/lib/cpp/src/thrift/server/TThreadedServer.h
index 2b1f757..f965fcd 100644
--- a/lib/cpp/src/thrift/server/TThreadedServer.h
+++ b/lib/cpp/src/thrift/server/TThreadedServer.h
@@ -27,9 +27,7 @@
#include <boost/shared_ptr.hpp>
-namespace apache {
-namespace thrift {
-namespace server {
+namespace apache { namespace thrift { namespace server {
using apache::thrift::TProcessor;
using apache::thrift::transport::TServerTransport;
@@ -39,17 +37,17 @@
class TThreadedServer : public TServer {
-public:
+ public:
class Task;
- template <typename ProcessorFactory>
+ template<typename ProcessorFactory>
TThreadedServer(const boost::shared_ptr<ProcessorFactory>& processorFactory,
const boost::shared_ptr<TServerTransport>& serverTransport,
const boost::shared_ptr<TTransportFactory>& transportFactory,
const boost::shared_ptr<TProtocolFactory>& protocolFactory,
THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory));
- template <typename ProcessorFactory>
+ template<typename ProcessorFactory>
TThreadedServer(const boost::shared_ptr<ProcessorFactory>& processorFactory,
const boost::shared_ptr<TServerTransport>& serverTransport,
const boost::shared_ptr<TTransportFactory>& transportFactory,
@@ -57,14 +55,14 @@
const boost::shared_ptr<ThreadFactory>& threadFactory,
THRIFT_OVERLOAD_IF(ProcessorFactory, TProcessorFactory));
- template <typename Processor>
+ template<typename Processor>
TThreadedServer(const boost::shared_ptr<Processor>& processor,
const boost::shared_ptr<TServerTransport>& serverTransport,
const boost::shared_ptr<TTransportFactory>& transportFactory,
const boost::shared_ptr<TProtocolFactory>& protocolFactory,
THRIFT_OVERLOAD_IF(Processor, TProcessor));
- template <typename Processor>
+ template<typename Processor>
TThreadedServer(const boost::shared_ptr<Processor>& processor,
const boost::shared_ptr<TServerTransport>& serverTransport,
const boost::shared_ptr<TTransportFactory>& transportFactory,
@@ -81,7 +79,7 @@
serverTransport_->interrupt();
}
-protected:
+ protected:
void init();
boost::shared_ptr<ThreadFactory> threadFactory_;
@@ -89,53 +87,59 @@
Monitor tasksMonitor_;
std::set<Task*> tasks_;
+
};
-template <typename ProcessorFactory>
-TThreadedServer::TThreadedServer(const boost::shared_ptr<ProcessorFactory>& processorFactory,
- const boost::shared_ptr<TServerTransport>& serverTransport,
- const boost::shared_ptr<TTransportFactory>& transportFactory,
- const boost::shared_ptr<TProtocolFactory>& protocolFactory,
- THRIFT_OVERLOAD_IF_DEFN(ProcessorFactory, TProcessorFactory))
- : TServer(processorFactory, serverTransport, transportFactory, protocolFactory) {
+template<typename ProcessorFactory>
+TThreadedServer::TThreadedServer(
+ const boost::shared_ptr<ProcessorFactory>& processorFactory,
+ const boost::shared_ptr<TServerTransport>& serverTransport,
+ const boost::shared_ptr<TTransportFactory>& transportFactory,
+ const boost::shared_ptr<TProtocolFactory>& protocolFactory,
+ THRIFT_OVERLOAD_IF_DEFN(ProcessorFactory, TProcessorFactory)) :
+ TServer(processorFactory, serverTransport, transportFactory,
+ protocolFactory) {
init();
}
-template <typename ProcessorFactory>
-TThreadedServer::TThreadedServer(const boost::shared_ptr<ProcessorFactory>& processorFactory,
- const boost::shared_ptr<TServerTransport>& serverTransport,
- const boost::shared_ptr<TTransportFactory>& transportFactory,
- const boost::shared_ptr<TProtocolFactory>& protocolFactory,
- const boost::shared_ptr<ThreadFactory>& threadFactory,
- THRIFT_OVERLOAD_IF_DEFN(ProcessorFactory, TProcessorFactory))
- : TServer(processorFactory, serverTransport, transportFactory, protocolFactory),
- threadFactory_(threadFactory) {
+template<typename ProcessorFactory>
+TThreadedServer::TThreadedServer(
+ const boost::shared_ptr<ProcessorFactory>& processorFactory,
+ const boost::shared_ptr<TServerTransport>& serverTransport,
+ const boost::shared_ptr<TTransportFactory>& transportFactory,
+ const boost::shared_ptr<TProtocolFactory>& protocolFactory,
+ const boost::shared_ptr<ThreadFactory>& threadFactory,
+ THRIFT_OVERLOAD_IF_DEFN(ProcessorFactory, TProcessorFactory)) :
+ TServer(processorFactory, serverTransport, transportFactory,
+ protocolFactory),
+ threadFactory_(threadFactory) {
init();
}
-template <typename Processor>
-TThreadedServer::TThreadedServer(const boost::shared_ptr<Processor>& processor,
- const boost::shared_ptr<TServerTransport>& serverTransport,
- const boost::shared_ptr<TTransportFactory>& transportFactory,
- const boost::shared_ptr<TProtocolFactory>& protocolFactory,
- THRIFT_OVERLOAD_IF_DEFN(Processor, TProcessor))
- : TServer(processor, serverTransport, transportFactory, protocolFactory) {
+template<typename Processor>
+TThreadedServer::TThreadedServer(
+ const boost::shared_ptr<Processor>& processor,
+ const boost::shared_ptr<TServerTransport>& serverTransport,
+ const boost::shared_ptr<TTransportFactory>& transportFactory,
+ const boost::shared_ptr<TProtocolFactory>& protocolFactory,
+ THRIFT_OVERLOAD_IF_DEFN(Processor, TProcessor)) :
+ TServer(processor, serverTransport, transportFactory, protocolFactory) {
init();
}
-template <typename Processor>
-TThreadedServer::TThreadedServer(const boost::shared_ptr<Processor>& processor,
- const boost::shared_ptr<TServerTransport>& serverTransport,
- const boost::shared_ptr<TTransportFactory>& transportFactory,
- const boost::shared_ptr<TProtocolFactory>& protocolFactory,
- const boost::shared_ptr<ThreadFactory>& threadFactory,
- THRIFT_OVERLOAD_IF_DEFN(Processor, TProcessor))
- : TServer(processor, serverTransport, transportFactory, protocolFactory),
- threadFactory_(threadFactory) {
+template<typename Processor>
+TThreadedServer::TThreadedServer(
+ const boost::shared_ptr<Processor>& processor,
+ const boost::shared_ptr<TServerTransport>& serverTransport,
+ const boost::shared_ptr<TTransportFactory>& transportFactory,
+ const boost::shared_ptr<TProtocolFactory>& protocolFactory,
+ const boost::shared_ptr<ThreadFactory>& threadFactory,
+ THRIFT_OVERLOAD_IF_DEFN(Processor, TProcessor)) :
+ TServer(processor, serverTransport, transportFactory, protocolFactory),
+ threadFactory_(threadFactory) {
init();
}
-}
-}
-} // apache::thrift::server
+
+}}} // apache::thrift::server
#endif // #ifndef _THRIFT_SERVER_TTHREADEDSERVER_H_
diff --git a/lib/cpp/src/thrift/thrift-config.h b/lib/cpp/src/thrift/thrift-config.h
old mode 100644
new mode 100755
index d648706..b1bcccb
--- a/lib/cpp/src/thrift/thrift-config.h
+++ b/lib/cpp/src/thrift/thrift-config.h
@@ -18,7 +18,7 @@
*/
#ifdef _WIN32
-#include <thrift/windows/config.h>
+# include <thrift/windows/config.h>
#else
-#include <thrift/config.h>
+# include <thrift/config.h>
#endif
diff --git a/lib/cpp/src/thrift/transport/PlatformSocket.h b/lib/cpp/src/thrift/transport/PlatformSocket.h
index 96a3da3..d28978e 100644
--- a/lib/cpp/src/thrift/transport/PlatformSocket.h
+++ b/lib/cpp/src/thrift/transport/PlatformSocket.h
@@ -17,8 +17,6 @@
* under the License.
*/
-// clang-format off
-
#ifndef _THRIFT_TRANSPORT_PLATFORM_SOCKET_H_
# define _THRIFT_TRANSPORT_PLATFORM_SOCKET_H_
diff --git a/lib/cpp/src/thrift/transport/TBufferTransports.cpp b/lib/cpp/src/thrift/transport/TBufferTransports.cpp
index 25adb23..15d8f59 100644
--- a/lib/cpp/src/thrift/transport/TBufferTransports.cpp
+++ b/lib/cpp/src/thrift/transport/TBufferTransports.cpp
@@ -24,9 +24,8 @@
using std::string;
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
+
uint32_t TBufferedTransport::readSlow(uint8_t* buf, uint32_t len) {
uint32_t have = static_cast<uint32_t>(rBound_ - rBase_);
@@ -86,7 +85,7 @@
// The case where we have to do two syscalls.
// This case also covers the case where the buffer is empty,
// but it is clearer (I think) to think of it as two separate cases.
- if ((have_bytes + len >= 2 * wBufSize_) || (have_bytes == 0)) {
+ if ((have_bytes + len >= 2*wBufSize_) || (have_bytes == 0)) {
// TODO(dreiss): writev
if (have_bytes > 0) {
transport_->write(wBuf_.get(), have_bytes);
@@ -110,14 +109,14 @@
}
const uint8_t* TBufferedTransport::borrowSlow(uint8_t* buf, uint32_t* len) {
- (void)buf;
- (void)len;
+ (void) buf;
+ (void) len;
// Simply return NULL. We don't know if there is actually data available on
// the underlying transport, so calling read() might block.
return NULL;
}
-void TBufferedTransport::flush() {
+void TBufferedTransport::flush() {
// Write out any data waiting in the write buffer.
uint32_t have_bytes = static_cast<uint32_t>(wBase_ - wBuf_.get());
if (have_bytes > 0) {
@@ -132,6 +131,7 @@
transport_->flush();
}
+
uint32_t TFramedTransport::readSlow(uint8_t* buf, uint32_t len) {
uint32_t want = len;
uint32_t have = static_cast<uint32_t>(rBound_ - rBase_);
@@ -179,8 +179,9 @@
uint32_t size_bytes_read = 0;
while (size_bytes_read < sizeof(sz)) {
uint8_t* szp = reinterpret_cast<uint8_t*>(&sz) + size_bytes_read;
- uint32_t bytes_read
- = transport_->read(szp, static_cast<uint32_t>(sizeof(sz)) - size_bytes_read);
+ uint32_t bytes_read = transport_->read(
+ szp,
+ static_cast<uint32_t>(sizeof(sz)) - size_bytes_read);
if (bytes_read == 0) {
if (size_bytes_read == 0) {
// EOF before any data was read.
@@ -217,7 +218,7 @@
uint32_t new_size = wBufSize_;
if (len + have < have /* overflow */ || len + have > 0x7fffffff) {
throw TTransportException(TTransportException::BAD_ARGS,
- "Attempted to write over 2 GB to TFramedTransport.");
+ "Attempted to write over 2 GB to TFramedTransport.");
}
while (new_size < len + have) {
new_size = new_size > 0 ? new_size * 2 : 1;
@@ -243,7 +244,7 @@
wBase_ += len;
}
-void TFramedTransport::flush() {
+void TFramedTransport::flush() {
int32_t sz_hbo, sz_nbo;
assert(wBufSize_ > sizeof(sz_nbo));
@@ -260,7 +261,9 @@
wBase_ = wBuf_.get() + sizeof(sz_nbo);
// Write size and frame body.
- transport_->write(wBuf_.get(), static_cast<uint32_t>(sizeof(sz_nbo)) + sz_hbo);
+ transport_->write(
+ wBuf_.get(),
+ static_cast<uint32_t>(sizeof(sz_nbo))+sz_hbo);
}
// Flush the underlying transport.
@@ -283,8 +286,8 @@
}
const uint8_t* TFramedTransport::borrowSlow(uint8_t* buf, uint32_t* len) {
- (void)buf;
- (void)len;
+ (void) buf;
+ (void) len;
// Don't try to be clever with shifting buffers.
// If the fast path failed let the protocol use its slow path.
// Besides, who is going to try to borrow across messages?
@@ -296,9 +299,9 @@
uint32_t bytes_read = static_cast<uint32_t>(rBound_ - rBuf_.get() + sizeof(uint32_t));
if (rBufSize_ > bufReclaimThresh_) {
- rBufSize_ = 0;
- rBuf_.reset();
- setReadBuffer(rBuf_.get(), rBufSize_);
+ rBufSize_ = 0;
+ rBuf_.reset();
+ setReadBuffer(rBuf_.get(), rBufSize_);
}
return bytes_read;
@@ -395,7 +398,7 @@
}
const uint8_t* TMemoryBuffer::borrowSlow(uint8_t* buf, uint32_t* len) {
- (void)buf;
+ (void) buf;
rBound_ = wBase_;
if (available_read() >= *len) {
*len = available_read();
@@ -403,6 +406,5 @@
}
return NULL;
}
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
diff --git a/lib/cpp/src/thrift/transport/TBufferTransports.h b/lib/cpp/src/thrift/transport/TBufferTransports.h
index da75052..2ee9adf 100644
--- a/lib/cpp/src/thrift/transport/TBufferTransports.h
+++ b/lib/cpp/src/thrift/transport/TBufferTransports.h
@@ -35,9 +35,8 @@
#define TDB_UNLIKELY(val) (val)
#endif
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
+
/**
* Base class for all transports that use read/write buffers for performance.
@@ -51,7 +50,8 @@
*/
class TBufferBase : public TVirtualTransport<TBufferBase> {
-public:
+ public:
+
/**
* Fast-path read.
*
@@ -122,11 +122,13 @@
if (TDB_LIKELY(static_cast<ptrdiff_t>(len) <= rBound_ - rBase_)) {
rBase_ += len;
} else {
- throw TTransportException(TTransportException::BAD_ARGS, "consume did not follow a borrow.");
+ throw TTransportException(TTransportException::BAD_ARGS,
+ "consume did not follow a borrow.");
}
}
-protected:
+ protected:
+
/// Slow path read.
virtual uint32_t readSlow(uint8_t* buf, uint32_t len) = 0;
@@ -147,18 +149,23 @@
* performance-sensitive operation, so it is okay to just leave it to
* the concrete class to set up pointers correctly.
*/
- TBufferBase() : rBase_(NULL), rBound_(NULL), wBase_(NULL), wBound_(NULL) {}
+ TBufferBase()
+ : rBase_(NULL)
+ , rBound_(NULL)
+ , wBase_(NULL)
+ , wBound_(NULL)
+ {}
/// Convenience mutator for setting the read buffer.
void setReadBuffer(uint8_t* buf, uint32_t len) {
rBase_ = buf;
- rBound_ = buf + len;
+ rBound_ = buf+len;
}
/// Convenience mutator for setting the write buffer.
void setWriteBuffer(uint8_t* buf, uint32_t len) {
wBase_ = buf;
- wBound_ = buf + len;
+ wBound_ = buf+len;
}
virtual ~TBufferBase() {}
@@ -174,49 +181,59 @@
uint8_t* wBound_;
};
+
/**
* Buffered transport. For reads it will read more data than is requested
* and will serve future data out of a local buffer. For writes, data is
* stored to an in memory buffer before being written out.
*
*/
-class TBufferedTransport : public TVirtualTransport<TBufferedTransport, TBufferBase> {
-public:
+class TBufferedTransport
+ : public TVirtualTransport<TBufferedTransport, TBufferBase> {
+ public:
+
static const int DEFAULT_BUFFER_SIZE = 512;
/// Use default buffer sizes.
TBufferedTransport(boost::shared_ptr<TTransport> transport)
- : transport_(transport),
- rBufSize_(DEFAULT_BUFFER_SIZE),
- wBufSize_(DEFAULT_BUFFER_SIZE),
- rBuf_(new uint8_t[rBufSize_]),
- wBuf_(new uint8_t[wBufSize_]) {
+ : transport_(transport)
+ , rBufSize_(DEFAULT_BUFFER_SIZE)
+ , wBufSize_(DEFAULT_BUFFER_SIZE)
+ , rBuf_(new uint8_t[rBufSize_])
+ , wBuf_(new uint8_t[wBufSize_])
+ {
initPointers();
}
/// Use specified buffer sizes.
TBufferedTransport(boost::shared_ptr<TTransport> transport, uint32_t sz)
- : transport_(transport),
- rBufSize_(sz),
- wBufSize_(sz),
- rBuf_(new uint8_t[rBufSize_]),
- wBuf_(new uint8_t[wBufSize_]) {
+ : transport_(transport)
+ , rBufSize_(sz)
+ , wBufSize_(sz)
+ , rBuf_(new uint8_t[rBufSize_])
+ , wBuf_(new uint8_t[wBufSize_])
+ {
initPointers();
}
/// Use specified read and write buffer sizes.
TBufferedTransport(boost::shared_ptr<TTransport> transport, uint32_t rsz, uint32_t wsz)
- : transport_(transport),
- rBufSize_(rsz),
- wBufSize_(wsz),
- rBuf_(new uint8_t[rBufSize_]),
- wBuf_(new uint8_t[wBufSize_]) {
+ : transport_(transport)
+ , rBufSize_(rsz)
+ , wBufSize_(wsz)
+ , rBuf_(new uint8_t[rBufSize_])
+ , wBuf_(new uint8_t[wBufSize_])
+ {
initPointers();
}
- void open() { transport_->open(); }
+ void open() {
+ transport_->open();
+ }
- bool isOpen() { return transport_->isOpen(); }
+ bool isOpen() {
+ return transport_->isOpen();
+ }
bool peek() {
if (rBase_ == rBound_) {
@@ -239,7 +256,9 @@
/**
* Returns the origin of the underlying transport
*/
- virtual const std::string getOrigin() { return transport_->getOrigin(); }
+ virtual const std::string getOrigin() {
+ return transport_->getOrigin();
+ }
/**
* The following behavior is currently implemented by TBufferedTransport,
@@ -254,15 +273,19 @@
*/
virtual const uint8_t* borrowSlow(uint8_t* buf, uint32_t* len);
- boost::shared_ptr<TTransport> getUnderlyingTransport() { return transport_; }
+ boost::shared_ptr<TTransport> getUnderlyingTransport() {
+ return transport_;
+ }
/*
* TVirtualTransport provides a default implementation of readAll().
* We want to use the TBufferBase version instead.
*/
- uint32_t readAll(uint8_t* buf, uint32_t len) { return TBufferBase::readAll(buf, len); }
+ uint32_t readAll(uint8_t* buf, uint32_t len) {
+ return TBufferBase::readAll(buf, len);
+ }
-protected:
+ protected:
void initPointers() {
setReadBuffer(rBuf_.get(), 0);
setWriteBuffer(wBuf_.get(), wBufSize_);
@@ -277,12 +300,13 @@
boost::scoped_array<uint8_t> wBuf_;
};
+
/**
* Wraps a transport into a buffered one.
*
*/
class TBufferedTransportFactory : public TTransportFactory {
-public:
+ public:
TBufferedTransportFactory() {}
virtual ~TBufferedTransportFactory() {}
@@ -293,8 +317,10 @@
virtual boost::shared_ptr<TTransport> getTransport(boost::shared_ptr<TTransport> trans) {
return boost::shared_ptr<TTransport>(new TBufferedTransport(trans));
}
+
};
+
/**
* Framed transport. All writes go into an in-memory buffer until flush is
* called, at which point the transport writes the length of the entire
@@ -302,38 +328,47 @@
* other end to always do fixed-length reads.
*
*/
-class TFramedTransport : public TVirtualTransport<TFramedTransport, TBufferBase> {
-public:
+class TFramedTransport
+ : public TVirtualTransport<TFramedTransport, TBufferBase> {
+ public:
+
static const int DEFAULT_BUFFER_SIZE = 512;
/// Use default buffer sizes.
TFramedTransport(boost::shared_ptr<TTransport> transport)
- : transport_(transport),
- rBufSize_(0),
- wBufSize_(DEFAULT_BUFFER_SIZE),
- rBuf_(),
- wBuf_(new uint8_t[wBufSize_]),
- bufReclaimThresh_((std::numeric_limits<uint32_t>::max)()) {
+ : transport_(transport)
+ , rBufSize_(0)
+ , wBufSize_(DEFAULT_BUFFER_SIZE)
+ , rBuf_()
+ , wBuf_(new uint8_t[wBufSize_])
+ , bufReclaimThresh_((std::numeric_limits<uint32_t>::max)())
+ {
initPointers();
}
- TFramedTransport(boost::shared_ptr<TTransport> transport,
- uint32_t sz,
- uint32_t bufReclaimThresh = (std::numeric_limits<uint32_t>::max)())
- : transport_(transport),
- rBufSize_(0),
- wBufSize_(sz),
- rBuf_(),
- wBuf_(new uint8_t[wBufSize_]),
- bufReclaimThresh_(bufReclaimThresh) {
+ TFramedTransport(boost::shared_ptr<TTransport> transport, uint32_t sz,
+ uint32_t bufReclaimThresh = (std::numeric_limits<uint32_t>::max)())
+ : transport_(transport)
+ , rBufSize_(0)
+ , wBufSize_(sz)
+ , rBuf_()
+ , wBuf_(new uint8_t[wBufSize_])
+ , bufReclaimThresh_(bufReclaimThresh)
+ {
initPointers();
}
- void open() { transport_->open(); }
+ void open() {
+ transport_->open();
+ }
- bool isOpen() { return transport_->isOpen(); }
+ bool isOpen() {
+ return transport_->isOpen();
+ }
- bool peek() { return (rBase_ < rBound_) || transport_->peek(); }
+ bool peek() {
+ return (rBase_ < rBound_) || transport_->peek();
+ }
void close() {
flush();
@@ -352,20 +387,26 @@
const uint8_t* borrowSlow(uint8_t* buf, uint32_t* len);
- boost::shared_ptr<TTransport> getUnderlyingTransport() { return transport_; }
+ boost::shared_ptr<TTransport> getUnderlyingTransport() {
+ return transport_;
+ }
/*
* TVirtualTransport provides a default implementation of readAll().
* We want to use the TBufferBase version instead.
*/
- uint32_t readAll(uint8_t* buf, uint32_t len) { return TBufferBase::readAll(buf, len); }
+ uint32_t readAll(uint8_t* buf, uint32_t len) {
+ return TBufferBase::readAll(buf,len);
+ }
/**
* Returns the origin of the underlying transport
*/
- virtual const std::string getOrigin() { return transport_->getOrigin(); }
+ virtual const std::string getOrigin() {
+ return transport_->getOrigin();
+ }
-protected:
+ protected:
/**
* Reads a frame of input from the underlying stream.
*
@@ -397,7 +438,7 @@
*
*/
class TFramedTransportFactory : public TTransportFactory {
-public:
+ public:
TFramedTransportFactory() {}
virtual ~TFramedTransportFactory() {}
@@ -408,8 +449,10 @@
virtual boost::shared_ptr<TTransport> getTransport(boost::shared_ptr<TTransport> trans) {
return boost::shared_ptr<TTransport>(new TFramedTransport(trans));
}
+
};
+
/**
* A memory buffer is a tranpsort that simply reads from and writes to an
* in memory buffer. Anytime you call write on it, the data is simply placed
@@ -420,7 +463,8 @@
*
*/
class TMemoryBuffer : public TVirtualTransport<TMemoryBuffer, TBufferBase> {
-private:
+ private:
+
// Common initialization done by all constructors.
void initCommon(uint8_t* buf, uint32_t size, bool owner, uint32_t wPos) {
if (buf == NULL && size != 0) {
@@ -446,7 +490,7 @@
// equal to wBase_. We update it in a few places (computeRead, etc.).
}
-public:
+ public:
static const uint32_t defaultSize = 1024;
/**
@@ -469,13 +513,19 @@
* and will be responsible for freeing it.
* The membory must have been allocated with malloc.
*/
- enum MemoryPolicy { OBSERVE = 1, COPY = 2, TAKE_OWNERSHIP = 3 };
+ enum MemoryPolicy
+ { OBSERVE = 1
+ , COPY = 2
+ , TAKE_OWNERSHIP = 3
+ };
/**
* Construct a TMemoryBuffer with a default-sized buffer,
* owned by the TMemoryBuffer object.
*/
- TMemoryBuffer() { initCommon(NULL, defaultSize, true, 0); }
+ TMemoryBuffer() {
+ initCommon(NULL, defaultSize, true, 0);
+ }
/**
* Construct a TMemoryBuffer with a buffer of a specified size,
@@ -483,7 +533,9 @@
*
* @param sz The initial size of the buffer.
*/
- TMemoryBuffer(uint32_t sz) { initCommon(NULL, sz, true, 0); }
+ TMemoryBuffer(uint32_t sz) {
+ initCommon(NULL, sz, true, 0);
+ }
/**
* Construct a TMemoryBuffer with buf as its initial contents.
@@ -502,17 +554,17 @@
}
switch (policy) {
- case OBSERVE:
- case TAKE_OWNERSHIP:
- initCommon(buf, sz, policy == TAKE_OWNERSHIP, sz);
- break;
- case COPY:
- initCommon(NULL, sz, true, 0);
- this->write(buf, sz);
- break;
- default:
- throw TTransportException(TTransportException::BAD_ARGS,
- "Invalid MemoryPolicy for TMemoryBuffer");
+ case OBSERVE:
+ case TAKE_OWNERSHIP:
+ initCommon(buf, sz, policy == TAKE_OWNERSHIP, sz);
+ break;
+ case COPY:
+ initCommon(NULL, sz, true, 0);
+ this->write(buf, sz);
+ break;
+ default:
+ throw TTransportException(TTransportException::BAD_ARGS,
+ "Invalid MemoryPolicy for TMemoryBuffer");
}
}
@@ -522,9 +574,13 @@
}
}
- bool isOpen() { return true; }
+ bool isOpen() {
+ return true;
+ }
- bool peek() { return (rBase_ < wBase_); }
+ bool peek() {
+ return (rBase_ < wBase_);
+ }
void open() {}
@@ -607,7 +663,7 @@
// return number of bytes read
uint32_t readEnd() {
- // This cast should be safe, because buffer_'s size is a uint32_t
+ //This cast should be safe, because buffer_'s size is a uint32_t
uint32_t bytes = static_cast<uint32_t>(rBase_ - buffer_);
if (rBase_ == wBase_) {
resetBuffer();
@@ -617,7 +673,7 @@
// Return number of bytes written
uint32_t writeEnd() {
- // This cast should be safe, because buffer_'s size is a uint32_t
+ //This cast should be safe, because buffer_'s size is a uint32_t
return static_cast<uint32_t>(wBase_ - buffer_);
}
@@ -626,7 +682,9 @@
return static_cast<uint32_t>(wBase_ - rBase_);
}
- uint32_t available_write() const { return static_cast<uint32_t>(wBound_ - wBase_); }
+ uint32_t available_write() const {
+ return static_cast<uint32_t>(wBound_ - wBase_);
+ }
// Returns a pointer to where the client can write data to append to
// the TMemoryBuffer, and ensures the buffer is big enough to accomodate a
@@ -646,20 +704,22 @@
* TVirtualTransport provides a default implementation of readAll().
* We want to use the TBufferBase version instead.
*/
- uint32_t readAll(uint8_t* buf, uint32_t len) { return TBufferBase::readAll(buf, len); }
+ uint32_t readAll(uint8_t* buf, uint32_t len) {
+ return TBufferBase::readAll(buf,len);
+ }
-protected:
+ protected:
void swap(TMemoryBuffer& that) {
using std::swap;
- swap(buffer_, that.buffer_);
+ swap(buffer_, that.buffer_);
swap(bufferSize_, that.bufferSize_);
- swap(rBase_, that.rBase_);
- swap(rBound_, that.rBound_);
- swap(wBase_, that.wBase_);
- swap(wBound_, that.wBound_);
+ swap(rBase_, that.rBase_);
+ swap(rBound_, that.rBound_);
+ swap(wBase_, that.wBase_);
+ swap(wBound_, that.wBound_);
- swap(owner_, that.owner_);
+ swap(owner_, that.owner_);
}
// Make sure there's at least 'len' bytes available for writing.
@@ -686,8 +746,7 @@
// Don't forget to update constrctors, initCommon, and swap if
// you add new members.
};
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
#endif // #ifndef _THRIFT_TRANSPORT_TBUFFERTRANSPORTS_H_
diff --git a/lib/cpp/src/thrift/transport/TFDTransport.cpp b/lib/cpp/src/thrift/transport/TFDTransport.cpp
index 4bce3a8..26365f0 100644
--- a/lib/cpp/src/thrift/transport/TFDTransport.cpp
+++ b/lib/cpp/src/thrift/transport/TFDTransport.cpp
@@ -33,9 +33,7 @@
using namespace std;
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
void TFDTransport::close() {
if (!isOpen()) {
@@ -47,7 +45,9 @@
fd_ = -1;
// Have to check uncaught_exception because this is called in the destructor.
if (rv < 0 && !std::uncaught_exception()) {
- throw TTransportException(TTransportException::UNKNOWN, "TFDTransport::close()", errno_copy);
+ throw TTransportException(TTransportException::UNKNOWN,
+ "TFDTransport::close()",
+ errno_copy);
}
}
@@ -62,11 +62,13 @@
++retries;
continue;
}
- int errno_copy = THRIFT_ERRNO;
- throw TTransportException(TTransportException::UNKNOWN, "TFDTransport::read()", errno_copy);
+ int errno_copy = THRIFT_ERRNO;
+ throw TTransportException(TTransportException::UNKNOWN,
+ "TFDTransport::read()",
+ errno_copy);
}
- // this should be fine, since we already checked for negative values,
- // and ::read should only return a 32-bit value since len is 32-bit.
+ //this should be fine, since we already checked for negative values,
+ //and ::read should only return a 32-bit value since len is 32-bit.
return static_cast<uint32_t>(rv);
}
}
@@ -76,18 +78,20 @@
THRIFT_SSIZET rv = ::THRIFT_WRITE(fd_, buf, len);
if (rv < 0) {
- int errno_copy = THRIFT_ERRNO;
- throw TTransportException(TTransportException::UNKNOWN, "TFDTransport::write()", errno_copy);
+ int errno_copy = THRIFT_ERRNO;
+ throw TTransportException(TTransportException::UNKNOWN,
+ "TFDTransport::write()",
+ errno_copy);
} else if (rv == 0) {
- throw TTransportException(TTransportException::END_OF_FILE, "TFDTransport::write()");
+ throw TTransportException(TTransportException::END_OF_FILE,
+ "TFDTransport::write()");
}
buf += rv;
- // this should be fine, as we've already checked for negative values, and
+ //this should be fine, as we've already checked for negative values, and
//::write shouldn't return more than a uint32_t since len is a uint32_t
len -= static_cast<uint32_t>(rv);
}
}
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
diff --git a/lib/cpp/src/thrift/transport/TFDTransport.h b/lib/cpp/src/thrift/transport/TFDTransport.h
index 5593d43..a337d8d 100644
--- a/lib/cpp/src/thrift/transport/TFDTransport.h
+++ b/lib/cpp/src/thrift/transport/TFDTransport.h
@@ -28,27 +28,31 @@
#include <thrift/transport/TTransport.h>
#include <thrift/transport/TVirtualTransport.h>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
/**
* Dead-simple wrapper around a file descriptor.
*
*/
class TFDTransport : public TVirtualTransport<TFDTransport> {
-public:
- enum ClosePolicy { NO_CLOSE_ON_DESTROY = 0, CLOSE_ON_DESTROY = 1 };
+ public:
+ enum ClosePolicy
+ { NO_CLOSE_ON_DESTROY = 0
+ , CLOSE_ON_DESTROY = 1
+ };
TFDTransport(int fd, ClosePolicy close_policy = NO_CLOSE_ON_DESTROY)
- : fd_(fd), close_policy_(close_policy) {}
+ : fd_(fd)
+ , close_policy_(close_policy)
+ {}
~TFDTransport() {
if (close_policy_ == CLOSE_ON_DESTROY) {
try {
close();
- } catch (TTransportException& ex) {
- GlobalOutput.printf("~TFDTransport TTransportException: '%s'", ex.what());
+ } catch(TTransportException& ex) {
+ GlobalOutput.printf("~TFDTransport TTransportException: '%s'",
+ ex.what());
}
}
}
@@ -66,12 +70,11 @@
void setFD(int fd) { fd_ = fd; }
int getFD() { return fd_; }
-protected:
+ protected:
int fd_;
ClosePolicy close_policy_;
};
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
#endif // #ifndef _THRIFT_TRANSPORT_TFDTRANSPORT_H_
diff --git a/lib/cpp/src/thrift/transport/TFileTransport.cpp b/lib/cpp/src/thrift/transport/TFileTransport.cpp
index 13e4471..625c877 100644
--- a/lib/cpp/src/thrift/transport/TFileTransport.cpp
+++ b/lib/cpp/src/thrift/transport/TFileTransport.cpp
@@ -48,9 +48,7 @@
#include <io.h>
#endif
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
using boost::scoped_ptr;
using boost::shared_ptr;
@@ -59,34 +57,35 @@
using namespace apache::thrift::concurrency;
TFileTransport::TFileTransport(string path, bool readOnly)
- : readState_(),
- readBuff_(NULL),
- currentEvent_(NULL),
- readBuffSize_(DEFAULT_READ_BUFF_SIZE),
- readTimeout_(NO_TAIL_READ_TIMEOUT),
- chunkSize_(DEFAULT_CHUNK_SIZE),
- eventBufferSize_(DEFAULT_EVENT_BUFFER_SIZE),
- flushMaxUs_(DEFAULT_FLUSH_MAX_US),
- flushMaxBytes_(DEFAULT_FLUSH_MAX_BYTES),
- maxEventSize_(DEFAULT_MAX_EVENT_SIZE),
- maxCorruptedEvents_(DEFAULT_MAX_CORRUPTED_EVENTS),
- eofSleepTime_(DEFAULT_EOF_SLEEP_TIME_US),
- corruptedEventSleepTime_(DEFAULT_CORRUPTED_SLEEP_TIME_US),
- writerThreadIOErrorSleepTime_(DEFAULT_WRITER_THREAD_SLEEP_TIME_US),
- dequeueBuffer_(NULL),
- enqueueBuffer_(NULL),
- notFull_(&mutex_),
- notEmpty_(&mutex_),
- closing_(false),
- flushed_(&mutex_),
- forceFlush_(false),
- filename_(path),
- fd_(0),
- bufferAndThreadInitialized_(false),
- offset_(0),
- lastBadChunk_(0),
- numCorruptedEventsInChunk_(0),
- readOnly_(readOnly) {
+ : readState_()
+ , readBuff_(NULL)
+ , currentEvent_(NULL)
+ , readBuffSize_(DEFAULT_READ_BUFF_SIZE)
+ , readTimeout_(NO_TAIL_READ_TIMEOUT)
+ , chunkSize_(DEFAULT_CHUNK_SIZE)
+ , eventBufferSize_(DEFAULT_EVENT_BUFFER_SIZE)
+ , flushMaxUs_(DEFAULT_FLUSH_MAX_US)
+ , flushMaxBytes_(DEFAULT_FLUSH_MAX_BYTES)
+ , maxEventSize_(DEFAULT_MAX_EVENT_SIZE)
+ , maxCorruptedEvents_(DEFAULT_MAX_CORRUPTED_EVENTS)
+ , eofSleepTime_(DEFAULT_EOF_SLEEP_TIME_US)
+ , corruptedEventSleepTime_(DEFAULT_CORRUPTED_SLEEP_TIME_US)
+ , writerThreadIOErrorSleepTime_(DEFAULT_WRITER_THREAD_SLEEP_TIME_US)
+ , dequeueBuffer_(NULL)
+ , enqueueBuffer_(NULL)
+ , notFull_(&mutex_)
+ , notEmpty_(&mutex_)
+ , closing_(false)
+ , flushed_(&mutex_)
+ , forceFlush_(false)
+ , filename_(path)
+ , fd_(0)
+ , bufferAndThreadInitialized_(false)
+ , offset_(0)
+ , lastBadChunk_(0)
+ , numCorruptedEventsInChunk_(0)
+ , readOnly_(readOnly)
+{
threadFactory_.setDetached(false);
openLogFile();
}
@@ -103,11 +102,9 @@
if (-1 == ::THRIFT_CLOSE(fd_)) {
int errno_copy = THRIFT_ERRNO;
GlobalOutput.perror("TFileTransport: resetOutputFile() ::close() ", errno_copy);
- throw TTransportException(TTransportException::UNKNOWN,
- "TFileTransport: error in file close",
- errno_copy);
+ throw TTransportException(TTransportException::UNKNOWN, "TFileTransport: error in file close", errno_copy);
} else {
- // successfully closed fd
+ //successfully closed fd
fd_ = 0;
}
}
@@ -120,9 +117,10 @@
}
}
+
TFileTransport::~TFileTransport() {
// flush the buffer if a writer thread is active
- if (writerThread_.get()) {
+ if(writerThread_.get()) {
// set state to closing
closing_ = true;
@@ -156,10 +154,10 @@
// close logfile
if (fd_ > 0) {
- if (-1 == ::THRIFT_CLOSE(fd_)) {
+ if(-1 == ::THRIFT_CLOSE(fd_)) {
GlobalOutput.perror("TFileTransport: ~TFileTransport() ::close() ", THRIFT_ERRNO);
} else {
- // successfully closed fd
+ //successfully closed fd
fd_ = 0;
}
}
@@ -171,9 +169,9 @@
return false;
}
- if (!writerThread_.get()) {
+ if(!writerThread_.get()) {
writerThread_ = threadFactory_.newThread(
- apache::thrift::concurrency::FunctionRunner::create(startWriterThread, this));
+ apache::thrift::concurrency::FunctionRunner::create(startWriterThread, this));
writerThread_->start();
}
@@ -199,7 +197,7 @@
}
// make sure that event size is valid
- if ((maxEventSize_ > 0) && (eventLen > maxEventSize_)) {
+ if ( (maxEventSize_ > 0) && (eventLen > maxEventSize_) ) {
T_ERROR("msg size is greater than max event size: %u > %u\n", eventLen, maxEventSize_);
return;
}
@@ -210,7 +208,7 @@
}
eventInfo* toEnqueue = new eventInfo();
- toEnqueue->eventBuff_ = (uint8_t*)std::malloc((sizeof(uint8_t) * eventLen) + 4);
+ toEnqueue->eventBuff_ = (uint8_t *)std::malloc((sizeof(uint8_t) * eventLen) + 4);
if (toEnqueue->eventBuff_ == NULL) {
delete toEnqueue;
throw std::bad_alloc();
@@ -234,7 +232,7 @@
// Can't enqueue while buffer is full
while (enqueueBuffer_->isFull()) {
- notFull_.wait();
+ notFull_.wait();
}
// We shouldn't be trying to enqueue new data while a forced flush is
@@ -280,23 +278,25 @@
}
if (swap) {
- TFileTransportBuffer* temp = enqueueBuffer_;
+ TFileTransportBuffer *temp = enqueueBuffer_;
enqueueBuffer_ = dequeueBuffer_;
dequeueBuffer_ = temp;
}
+
if (swap) {
- notFull_.notify();
+ notFull_.notify();
}
return swap;
}
+
void TFileTransport::writerThread() {
bool hasIOError = false;
// open file if it is not open
- if (!fd_) {
+ if(!fd_) {
try {
openLogFile();
} catch (...) {
@@ -313,7 +313,7 @@
seekToEnd();
// throw away any partial events
offset_ += readState_.lastDispatchPtr_;
- THRIFT_FTRUNCATE(fd_, offset_);
+ THRIFT_FTRUNCATE(fd_, offset_);
readState_.resetAllValues();
} catch (...) {
int errno_copy = THRIFT_ERRNO;
@@ -336,12 +336,12 @@
// Try to empty buffers before exit
if (enqueueBuffer_->isEmpty() && dequeueBuffer_->isEmpty()) {
- ::THRIFT_FSYNC(fd_);
+ ::THRIFT_FSYNC(fd_);
if (-1 == ::THRIFT_CLOSE(fd_)) {
int errno_copy = THRIFT_ERRNO;
GlobalOutput.perror("TFileTransport: writerThread() ::close() ", errno_copy);
} else {
- // fd successfully closed
+ //fd successfully closed
fd_ = 0;
}
return;
@@ -351,18 +351,13 @@
if (swapEventBuffers(&ts_next_flush)) {
eventInfo* outEvent;
while (NULL != (outEvent = dequeueBuffer_->getNext())) {
- // Remove an event from the buffer and write it out to disk. If there is any IO error, for
- // instance,
- // the output file is unmounted or deleted, then this event is dropped. However, the writer
- // thread
- // will: (1) sleep for a short while; (2) try to reopen the file; (3) if successful then
- // start writing
+ // Remove an event from the buffer and write it out to disk. If there is any IO error, for instance,
+ // the output file is unmounted or deleted, then this event is dropped. However, the writer thread
+ // will: (1) sleep for a short while; (2) try to reopen the file; (3) if successful then start writing
// from the end.
while (hasIOError) {
- T_ERROR(
- "TFileTransport: writer thread going to sleep for %d microseconds due to IO errors",
- writerThreadIOErrorSleepTime_);
+ T_ERROR("TFileTransport: writer thread going to sleep for %d microseconds due to IO errors", writerThreadIOErrorSleepTime_);
THRIFT_SLEEP_USEC(writerThreadIOErrorSleepTime_);
if (closing_) {
return;
@@ -376,20 +371,15 @@
seekToEnd();
unflushed = 0;
hasIOError = false;
- T_LOG_OPER(
- "TFileTransport: log file %s reopened by writer thread during error recovery",
- filename_.c_str());
+ T_LOG_OPER("TFileTransport: log file %s reopened by writer thread during error recovery", filename_.c_str());
} catch (...) {
- T_ERROR("TFileTransport: unable to reopen log file %s during error recovery",
- filename_.c_str());
+ T_ERROR("TFileTransport: unable to reopen log file %s during error recovery", filename_.c_str());
}
}
// sanity check on event
if ((maxEventSize_ > 0) && (outEvent->eventSize_ > maxEventSize_)) {
- T_ERROR("msg size is greater than max event size: %u > %u\n",
- outEvent->eventSize_,
- maxEventSize_);
+ T_ERROR("msg size is greater than max event size: %u > %u\n", outEvent->eventSize_, maxEventSize_);
continue;
}
@@ -397,14 +387,12 @@
if ((outEvent->eventSize_ > 0) && (chunkSize_ != 0)) {
// event size must be less than chunk size
if (outEvent->eventSize_ > chunkSize_) {
- T_ERROR("TFileTransport: event size(%u) > chunk size(%u): skipping event",
- outEvent->eventSize_,
- chunkSize_);
+ T_ERROR("TFileTransport: event size(%u) > chunk size(%u): skipping event", outEvent->eventSize_, chunkSize_);
continue;
}
- int64_t chunk1 = offset_ / chunkSize_;
- int64_t chunk2 = (offset_ + outEvent->eventSize_ - 1) / chunkSize_;
+ int64_t chunk1 = offset_/chunkSize_;
+ int64_t chunk2 = (offset_ + outEvent->eventSize_ - 1)/chunkSize_;
// if adding this event will cross a chunk boundary, pad the chunk with zeros
if (chunk1 != chunk2) {
@@ -417,8 +405,7 @@
boost::scoped_array<uint8_t> array(zeros);
if (-1 == ::write(fd_, zeros, padding)) {
int errno_copy = THRIFT_ERRNO;
- GlobalOutput.perror("TFileTransport: writerThread() error while padding zeros ",
- errno_copy);
+ GlobalOutput.perror("TFileTransport: writerThread() error while padding zeros ", errno_copy);
hasIOError = true;
continue;
}
@@ -453,24 +440,24 @@
// time, it could have changed state in between. This will result in us
// making inconsistent decisions.
bool forced_flush = false;
- {
- Guard g(mutex_);
- if (forceFlush_) {
- if (!enqueueBuffer_->isEmpty()) {
- // If forceFlush_ is true, we need to flush all available data.
- // If enqueueBuffer_ is not empty, go back to the start of the loop to
- // write it out.
- //
- // We know the main thread is waiting on forceFlush_ to be cleared,
- // so no new events will be added to enqueueBuffer_ until we clear
- // forceFlush_. Therefore the next time around the loop enqueueBuffer_
- // is guaranteed to be empty. (I.e., we're guaranteed to make progress
- // and clear forceFlush_ the next time around the loop.)
- continue;
- }
- forced_flush = true;
+ {
+ Guard g(mutex_);
+ if (forceFlush_) {
+ if (!enqueueBuffer_->isEmpty()) {
+ // If forceFlush_ is true, we need to flush all available data.
+ // If enqueueBuffer_ is not empty, go back to the start of the loop to
+ // write it out.
+ //
+ // We know the main thread is waiting on forceFlush_ to be cleared,
+ // so no new events will be added to enqueueBuffer_ until we clear
+ // forceFlush_. Therefore the next time around the loop enqueueBuffer_
+ // is guaranteed to be empty. (I.e., we're guaranteed to make progress
+ // and clear forceFlush_ the next time around the loop.)
+ continue;
}
- }
+ forced_flush = true;
+ }
+ }
// determine if we need to perform an fsync
bool flush = false;
@@ -479,9 +466,9 @@
} else {
struct timeval current_time;
THRIFT_GETTIMEOFDAY(¤t_time, NULL);
- if (current_time.tv_sec > ts_next_flush.tv_sec
- || (current_time.tv_sec == ts_next_flush.tv_sec
- && current_time.tv_usec > ts_next_flush.tv_usec)) {
+ if (current_time.tv_sec > ts_next_flush.tv_sec ||
+ (current_time.tv_sec == ts_next_flush.tv_sec &&
+ current_time.tv_usec > ts_next_flush.tv_usec)) {
if (unflushed > 0) {
flush = true;
} else {
@@ -494,7 +481,7 @@
if (flush) {
// sync (force flush) file to disk
- THRIFT_FSYNC(fd_);
+ THRIFT_FSYNC(fd_);
unflushed = 0;
getNextFlushTime(&ts_next_flush);
@@ -504,7 +491,7 @@
forceFlush_ = false;
assert(enqueueBuffer_->isEmpty());
assert(dequeueBuffer_->isEmpty());
- flushed_.notifyAll();
+ flushed_.notifyAll();
}
}
}
@@ -528,12 +515,13 @@
}
}
+
uint32_t TFileTransport::readAll(uint8_t* buf, uint32_t len) {
uint32_t have = 0;
uint32_t get = 0;
while (have < len) {
- get = read(buf + have, len - have);
+ get = read(buf+have, len-have);
if (get <= 0) {
throw TEOFException();
}
@@ -576,9 +564,11 @@
if (remaining <= (int32_t)len) {
// copy over anything thats remaining
if (remaining > 0) {
- memcpy(buf, currentEvent_->eventBuff_ + currentEvent_->eventBuffPos_, remaining);
+ memcpy(buf,
+ currentEvent_->eventBuff_ + currentEvent_->eventBuffPos_,
+ remaining);
}
- delete (currentEvent_);
+ delete(currentEvent_);
currentEvent_ = NULL;
return remaining;
}
@@ -602,7 +592,7 @@
if (readState_.bufferPtr_ == readState_.bufferLen_) {
// advance the offset pointer
offset_ += readState_.bufferLen_;
- readState_.bufferLen_ = static_cast<uint32_t>(::THRIFT_READ(fd_, readBuff_, readBuffSize_));
+ readState_.bufferLen_ = static_cast<uint32_t>(::THRIFT_READ(fd_, readBuff_, readBuffSize_));
// if (readState_.bufferLen_) {
// T_DEBUG_L(1, "Amount read: %u (offset: %lu)", readState_.bufferLen_, offset_);
// }
@@ -614,7 +604,7 @@
readState_.resetAllValues();
GlobalOutput("TFileTransport: error while reading from file");
throw TTransportException("TFileTransport: error while reading from file");
- } else if (readState_.bufferLen_ == 0) { // EOF
+ } else if (readState_.bufferLen_ == 0) { // EOF
// wait indefinitely if there is no timeout
if (readTimeout_ == TAIL_READ_TIMEOUT) {
THRIFT_SLEEP_USEC(eofSleepTime_);
@@ -640,11 +630,11 @@
readTries = 0;
// attempt to read an event from the buffer
- while (readState_.bufferPtr_ < readState_.bufferLen_) {
+ while(readState_.bufferPtr_ < readState_.bufferLen_) {
if (readState_.readingSize_) {
- if (readState_.eventSizeBuffPos_ == 0) {
- if ((offset_ + readState_.bufferPtr_) / chunkSize_
- != ((offset_ + readState_.bufferPtr_ + 3) / chunkSize_)) {
+ if(readState_.eventSizeBuffPos_ == 0) {
+ if ( (offset_ + readState_.bufferPtr_)/chunkSize_ !=
+ ((offset_ + readState_.bufferPtr_ + 3)/chunkSize_)) {
// skip one byte towards chunk boundary
// T_DEBUG_L(1, "Skipping a byte");
readState_.bufferPtr_++;
@@ -652,8 +642,8 @@
}
}
- readState_.eventSizeBuff_[readState_.eventSizeBuffPos_++]
- = readBuff_[readState_.bufferPtr_++];
+ readState_.eventSizeBuff_[readState_.eventSizeBuffPos_++] =
+ readBuff_[readState_.bufferPtr_++];
if (readState_.eventSizeBuffPos_ == 4) {
if (readState_.getEventSize() == 0) {
@@ -665,7 +655,7 @@
// got a valid event
readState_.readingSize_ = false;
if (readState_.event_) {
- delete (readState_.event_);
+ delete(readState_.event_);
}
readState_.event_ = new eventInfo();
readState_.event_->eventSize_ = readState_.getEventSize();
@@ -709,26 +699,24 @@
}
}
}
+
}
}
bool TFileTransport::isEventCorrupted() {
// an error is triggered if:
- if ((maxEventSize_ > 0) && (readState_.event_->eventSize_ > maxEventSize_)) {
+ if ( (maxEventSize_ > 0) && (readState_.event_->eventSize_ > maxEventSize_)) {
// 1. Event size is larger than user-speficied max-event size
T_ERROR("Read corrupt event. Event size(%u) greater than max event size (%u)",
- readState_.event_->eventSize_,
- maxEventSize_);
+ readState_.event_->eventSize_, maxEventSize_);
return true;
} else if (readState_.event_->eventSize_ > chunkSize_) {
// 2. Event size is larger than chunk size
T_ERROR("Read corrupt event. Event size(%u) greater than chunk size (%u)",
- readState_.event_->eventSize_,
- chunkSize_);
+ readState_.event_->eventSize_, chunkSize_);
return true;
- } else if (((offset_ + readState_.bufferPtr_ - 4) / chunkSize_)
- != ((offset_ + readState_.bufferPtr_ + readState_.event_->eventSize_ - 1)
- / chunkSize_)) {
+ } else if( ((offset_ + readState_.bufferPtr_ - 4)/chunkSize_) !=
+ ((offset_ + readState_.bufferPtr_ + readState_.event_->eventSize_ - 1)/chunkSize_) ) {
// 3. size indicates that event crosses chunk boundary
T_ERROR("Read corrupt event. Event crosses chunk boundary. Event size:%u Offset:%lu",
readState_.event_->eventSize_,
@@ -762,7 +750,7 @@
} else if (readTimeout_ == TAIL_READ_TIMEOUT) {
// if tailing the file, wait until there is enough data to start
// the next chunk
- while (curChunk == (getNumChunks() - 1)) {
+ while(curChunk == (getNumChunks() - 1)) {
THRIFT_SLEEP_USEC(corruptedEventSleepTime_);
}
seekToChunk(curChunk + 1);
@@ -772,14 +760,14 @@
readState_.resetState(readState_.lastDispatchPtr_);
currentEvent_ = NULL;
char errorMsg[1024];
- sprintf(errorMsg,
- "TFileTransport: log file corrupted at offset: %lu",
+ sprintf(errorMsg, "TFileTransport: log file corrupted at offset: %lu",
static_cast<unsigned long>(offset_ + readState_.lastDispatchPtr_));
GlobalOutput(errorMsg);
throw TTransportException(errorMsg);
}
}
+
}
void TFileTransport::seekToChunk(int32_t chunk) {
@@ -839,6 +827,7 @@
}
setReadTimeout(oldReadTimeout);
}
+
}
void TFileTransport::seekToEnd() {
@@ -861,7 +850,7 @@
}
if (f_info.st_size > 0) {
- size_t numChunks = ((f_info.st_size) / chunkSize_) + 1;
+ size_t numChunks = ((f_info.st_size)/chunkSize_) + 1;
if (numChunks > (std::numeric_limits<uint32_t>::max)())
throw TTransportException("Too many chunks");
return static_cast<uint32_t>(numChunks);
@@ -872,13 +861,13 @@
}
uint32_t TFileTransport::getCurChunk() {
- return static_cast<uint32_t>(offset_ / chunkSize_);
+ return static_cast<uint32_t>(offset_/chunkSize_);
}
// Utility Functions
void TFileTransport::openLogFile() {
#ifndef _WIN32
- mode_t mode = readOnly_ ? S_IRUSR | S_IRGRP | S_IROTH : S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
+ mode_t mode = readOnly_ ? S_IRUSR | S_IRGRP | S_IROTH : S_IRUSR | S_IWUSR| S_IRGRP | S_IROTH;
int flags = readOnly_ ? O_RDONLY : O_RDWR | O_CREAT | O_APPEND;
#else
int mode = readOnly_ ? _S_IREAD : _S_IREAD | _S_IWRITE;
@@ -888,11 +877,12 @@
offset_ = 0;
// make sure open call was successful
- if (fd_ == -1) {
+ if(fd_ == -1) {
int errno_copy = THRIFT_ERRNO;
GlobalOutput.perror("TFileTransport: openLogFile() ::open() file: " + filename_, errno_copy);
throw TTransportException(TTransportException::NOT_OPEN, filename_, errno_copy);
}
+
}
void TFileTransport::getNextFlushTime(struct timeval* ts_next_flush) {
@@ -907,8 +897,12 @@
}
TFileTransportBuffer::TFileTransportBuffer(uint32_t size)
- : bufferMode_(WRITE), writePoint_(0), readPoint_(0), size_(size) {
- buffer_ = new eventInfo* [size];
+ : bufferMode_(WRITE)
+ , writePoint_(0)
+ , readPoint_(0)
+ , size_(size)
+{
+ buffer_ = new eventInfo*[size];
}
TFileTransportBuffer::~TFileTransportBuffer() {
@@ -921,7 +915,7 @@
}
}
-bool TFileTransportBuffer::addEvent(eventInfo* event) {
+bool TFileTransportBuffer::addEvent(eventInfo *event) {
if (bufferMode_ == READ) {
GlobalOutput("Trying to write to a buffer in read mode");
}
@@ -969,11 +963,11 @@
TFileProcessor::TFileProcessor(shared_ptr<TProcessor> processor,
shared_ptr<TProtocolFactory> protocolFactory,
- shared_ptr<TFileReaderTransport> inputTransport)
- : processor_(processor),
- inputProtocolFactory_(protocolFactory),
- outputProtocolFactory_(protocolFactory),
- inputTransport_(inputTransport) {
+ shared_ptr<TFileReaderTransport> inputTransport):
+ processor_(processor),
+ inputProtocolFactory_(protocolFactory),
+ outputProtocolFactory_(protocolFactory),
+ inputTransport_(inputTransport) {
// default the output transport to a null transport (common case)
outputTransport_ = shared_ptr<TNullTransport>(new TNullTransport());
@@ -982,11 +976,11 @@
TFileProcessor::TFileProcessor(shared_ptr<TProcessor> processor,
shared_ptr<TProtocolFactory> inputProtocolFactory,
shared_ptr<TProtocolFactory> outputProtocolFactory,
- shared_ptr<TFileReaderTransport> inputTransport)
- : processor_(processor),
- inputProtocolFactory_(inputProtocolFactory),
- outputProtocolFactory_(outputProtocolFactory),
- inputTransport_(inputTransport) {
+ shared_ptr<TFileReaderTransport> inputTransport):
+ processor_(processor),
+ inputProtocolFactory_(inputProtocolFactory),
+ outputProtocolFactory_(outputProtocolFactory),
+ inputTransport_(inputTransport) {
// default the output transport to a null transport (common case)
outputTransport_ = shared_ptr<TNullTransport>(new TNullTransport());
@@ -995,13 +989,12 @@
TFileProcessor::TFileProcessor(shared_ptr<TProcessor> processor,
shared_ptr<TProtocolFactory> protocolFactory,
shared_ptr<TFileReaderTransport> inputTransport,
- shared_ptr<TTransport> outputTransport)
- : processor_(processor),
- inputProtocolFactory_(protocolFactory),
- outputProtocolFactory_(protocolFactory),
- inputTransport_(inputTransport),
- outputTransport_(outputTransport) {
-}
+ shared_ptr<TTransport> outputTransport):
+ processor_(processor),
+ inputProtocolFactory_(protocolFactory),
+ outputProtocolFactory_(protocolFactory),
+ inputTransport_(inputTransport),
+ outputTransport_(outputTransport) {}
void TFileProcessor::process(uint32_t numEvents, bool tail) {
shared_ptr<TProtocol> inputProtocol = inputProtocolFactory_->getProtocol(inputTransport_);
@@ -1015,20 +1008,20 @@
}
uint32_t numProcessed = 0;
- while (1) {
+ while(1) {
// bad form to use exceptions for flow control but there is really
// no other way around it
try {
processor_->process(inputProtocol, outputProtocol, NULL);
numProcessed++;
- if ((numEvents > 0) && (numProcessed == numEvents)) {
+ if ( (numEvents > 0) && (numProcessed == numEvents)) {
return;
}
} catch (TEOFException&) {
if (!tail) {
break;
}
- } catch (TException& te) {
+ } catch (TException &te) {
cerr << te.what() << endl;
break;
}
@@ -1038,6 +1031,7 @@
if (tail) {
inputTransport_->setReadTimeout(oldReadTimeout);
}
+
}
void TFileProcessor::processChunk() {
@@ -1046,7 +1040,7 @@
uint32_t curChunk = inputTransport_->getCurChunk();
- while (1) {
+ while(1) {
// bad form to use exceptions for flow control but there is really
// no other way around it
try {
@@ -1056,12 +1050,11 @@
}
} catch (TEOFException&) {
break;
- } catch (TException& te) {
+ } catch (TException &te) {
cerr << te.what() << endl;
break;
}
}
}
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
diff --git a/lib/cpp/src/thrift/transport/TFileTransport.h b/lib/cpp/src/thrift/transport/TFileTransport.h
index acd7bf9..75941cf 100644
--- a/lib/cpp/src/thrift/transport/TFileTransport.h
+++ b/lib/cpp/src/thrift/transport/TFileTransport.h
@@ -35,9 +35,7 @@
#include <thrift/concurrency/PlatformThreadFactory.h>
#include <thrift/concurrency/Thread.h>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
using apache::thrift::TProcessor;
using apache::thrift::protocol::TProtocolFactory;
@@ -50,7 +48,7 @@
uint32_t eventSize_;
uint32_t eventBuffPos_;
- eventInfo() : eventBuff_(NULL), eventSize_(0), eventBuffPos_(0){};
+ eventInfo():eventBuff_(NULL), eventSize_(0), eventBuffPos_(0){};
~eventInfo() {
if (eventBuff_) {
delete[] eventBuff_;
@@ -63,13 +61,13 @@
eventInfo* event_;
// keep track of event size
- uint8_t eventSizeBuff_[4];
- uint8_t eventSizeBuffPos_;
- bool readingSize_;
+ uint8_t eventSizeBuff_[4];
+ uint8_t eventSizeBuffPos_;
+ bool readingSize_;
// read buffer variables
- int32_t bufferPtr_;
- int32_t bufferLen_;
+ int32_t bufferPtr_;
+ int32_t bufferLen_;
// last successful dispatch point
int32_t lastDispatchPtr_;
@@ -85,24 +83,24 @@
bufferPtr_ = 0;
bufferLen_ = 0;
if (event_) {
- delete (event_);
+ delete(event_);
}
event_ = 0;
}
inline uint32_t getEventSize() {
- const void* buffer = reinterpret_cast<const void*>(eventSizeBuff_);
- return *reinterpret_cast<const uint32_t*>(buffer);
+ const void *buffer=reinterpret_cast<const void *>(eventSizeBuff_);
+ return *reinterpret_cast<const uint32_t *>(buffer);
}
readState() {
event_ = 0;
- resetAllValues();
+ resetAllValues();
}
~readState() {
if (event_) {
- delete (event_);
+ delete(event_);
}
}
@@ -123,33 +121,36 @@
*
*/
class TFileTransportBuffer {
-public:
- TFileTransportBuffer(uint32_t size);
- ~TFileTransportBuffer();
+ public:
+ TFileTransportBuffer(uint32_t size);
+ ~TFileTransportBuffer();
- bool addEvent(eventInfo* event);
- eventInfo* getNext();
- void reset();
- bool isFull();
- bool isEmpty();
+ bool addEvent(eventInfo *event);
+ eventInfo* getNext();
+ void reset();
+ bool isFull();
+ bool isEmpty();
-private:
- TFileTransportBuffer(); // should not be used
+ private:
+ TFileTransportBuffer(); // should not be used
- enum mode { WRITE, READ };
- mode bufferMode_;
+ enum mode {
+ WRITE,
+ READ
+ };
+ mode bufferMode_;
- uint32_t writePoint_;
- uint32_t readPoint_;
- uint32_t size_;
- eventInfo** buffer_;
+ uint32_t writePoint_;
+ uint32_t readPoint_;
+ uint32_t size_;
+ eventInfo** buffer_;
};
/**
* Abstract interface for transports used to read files
*/
class TFileReaderTransport : virtual public TTransport {
-public:
+ public:
virtual int32_t getReadTimeout() = 0;
virtual void setReadTimeout(int32_t readTimeout) = 0;
@@ -163,7 +164,7 @@
* Abstract interface for transports used to write files
*/
class TFileWriterTransport : virtual public TTransport {
-public:
+ public:
virtual uint32_t getChunkSize() = 0;
virtual void setChunkSize(uint32_t chunkSize) = 0;
};
@@ -173,14 +174,17 @@
* file on disk.
*
*/
-class TFileTransport : public TFileReaderTransport, public TFileWriterTransport {
-public:
- TFileTransport(std::string path, bool readOnly = false);
+class TFileTransport : public TFileReaderTransport,
+ public TFileWriterTransport {
+ public:
+ TFileTransport(std::string path, bool readOnly=false);
~TFileTransport();
// TODO: what is the correct behaviour for this?
// the log file is generally always open
- bool isOpen() { return true; }
+ bool isOpen() {
+ return true;
+ }
void write(const uint8_t* buf, uint32_t len);
void flush();
@@ -204,19 +208,27 @@
readBuffSize_ = readBuffSize;
}
}
- uint32_t getReadBuffSize() { return readBuffSize_; }
+ uint32_t getReadBuffSize() {
+ return readBuffSize_;
+ }
static const int32_t TAIL_READ_TIMEOUT = -1;
static const int32_t NO_TAIL_READ_TIMEOUT = 0;
- void setReadTimeout(int32_t readTimeout) { readTimeout_ = readTimeout; }
- int32_t getReadTimeout() { return readTimeout_; }
+ void setReadTimeout(int32_t readTimeout) {
+ readTimeout_ = readTimeout;
+ }
+ int32_t getReadTimeout() {
+ return readTimeout_;
+ }
void setChunkSize(uint32_t chunkSize) {
if (chunkSize) {
chunkSize_ = chunkSize;
}
}
- uint32_t getChunkSize() { return chunkSize_; }
+ uint32_t getChunkSize() {
+ return chunkSize_;
+ }
void setEventBufferSize(uint32_t bufferSize) {
if (bufferAndThreadInitialized_) {
@@ -226,47 +238,67 @@
eventBufferSize_ = bufferSize;
}
- uint32_t getEventBufferSize() { return eventBufferSize_; }
+ uint32_t getEventBufferSize() {
+ return eventBufferSize_;
+ }
void setFlushMaxUs(uint32_t flushMaxUs) {
if (flushMaxUs) {
flushMaxUs_ = flushMaxUs;
}
}
- uint32_t getFlushMaxUs() { return flushMaxUs_; }
+ uint32_t getFlushMaxUs() {
+ return flushMaxUs_;
+ }
void setFlushMaxBytes(uint32_t flushMaxBytes) {
if (flushMaxBytes) {
flushMaxBytes_ = flushMaxBytes;
}
}
- uint32_t getFlushMaxBytes() { return flushMaxBytes_; }
+ uint32_t getFlushMaxBytes() {
+ return flushMaxBytes_;
+ }
- void setMaxEventSize(uint32_t maxEventSize) { maxEventSize_ = maxEventSize; }
- uint32_t getMaxEventSize() { return maxEventSize_; }
+ void setMaxEventSize(uint32_t maxEventSize) {
+ maxEventSize_ = maxEventSize;
+ }
+ uint32_t getMaxEventSize() {
+ return maxEventSize_;
+ }
void setMaxCorruptedEvents(uint32_t maxCorruptedEvents) {
maxCorruptedEvents_ = maxCorruptedEvents;
}
- uint32_t getMaxCorruptedEvents() { return maxCorruptedEvents_; }
+ uint32_t getMaxCorruptedEvents() {
+ return maxCorruptedEvents_;
+ }
void setEofSleepTimeUs(uint32_t eofSleepTime) {
if (eofSleepTime) {
eofSleepTime_ = eofSleepTime;
}
}
- uint32_t getEofSleepTimeUs() { return eofSleepTime_; }
+ uint32_t getEofSleepTimeUs() {
+ return eofSleepTime_;
+ }
/*
* Override TTransport *_virt() functions to invoke our implementations.
* We cannot use TVirtualTransport to provide these, since we need to inherit
* virtually from TTransport.
*/
- virtual uint32_t read_virt(uint8_t* buf, uint32_t len) { return this->read(buf, len); }
- virtual uint32_t readAll_virt(uint8_t* buf, uint32_t len) { return this->readAll(buf, len); }
- virtual void write_virt(const uint8_t* buf, uint32_t len) { this->write(buf, len); }
+ virtual uint32_t read_virt(uint8_t* buf, uint32_t len) {
+ return this->read(buf, len);
+ }
+ virtual uint32_t readAll_virt(uint8_t* buf, uint32_t len) {
+ return this->readAll(buf, len);
+ }
+ virtual void write_virt(const uint8_t* buf, uint32_t len) {
+ this->write(buf, len);
+ }
-private:
+ private:
// helper functions for writing to a file
void enqueueEvent(const uint8_t* buf, uint32_t eventLen);
bool swapEventBuffers(struct timeval* deadline);
@@ -343,8 +375,8 @@
// buffers to hold data before it is flushed. Each element of the buffer stores a msg that
// needs to be written to the file. The buffers are swapped by the writer thread.
- TFileTransportBuffer* dequeueBuffer_;
- TFileTransportBuffer* enqueueBuffer_;
+ TFileTransportBuffer *dequeueBuffer_;
+ TFileTransportBuffer *enqueueBuffer_;
// conditions used to block when the buffer is full or empty
Monitor notFull_, notEmpty_;
@@ -376,13 +408,15 @@
// Exception thrown when EOF is hit
class TEOFException : public TTransportException {
-public:
- TEOFException() : TTransportException(TTransportException::END_OF_FILE){};
+ public:
+ TEOFException():
+ TTransportException(TTransportException::END_OF_FILE) {};
};
+
// wrapper class to process events from a file containing thrift events
class TFileProcessor {
-public:
+ public:
/**
* Constructor that defaults output transport to null transport
*
@@ -426,15 +460,15 @@
*/
void processChunk();
-private:
+ private:
boost::shared_ptr<TProcessor> processor_;
boost::shared_ptr<TProtocolFactory> inputProtocolFactory_;
boost::shared_ptr<TProtocolFactory> outputProtocolFactory_;
boost::shared_ptr<TFileReaderTransport> inputTransport_;
boost::shared_ptr<TTransport> outputTransport_;
};
-}
-}
-} // apache::thrift::transport
+
+
+}}} // apache::thrift::transport
#endif // _THRIFT_TRANSPORT_TFILETRANSPORT_H_
diff --git a/lib/cpp/src/thrift/transport/THttpClient.cpp b/lib/cpp/src/thrift/transport/THttpClient.cpp
index c610636..cb94d5e 100644
--- a/lib/cpp/src/thrift/transport/THttpClient.cpp
+++ b/lib/cpp/src/thrift/transport/THttpClient.cpp
@@ -25,33 +25,26 @@
#include <thrift/transport/THttpClient.h>
#include <thrift/transport/TSocket.h>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
using namespace std;
-THttpClient::THttpClient(boost::shared_ptr<TTransport> transport,
- std::string host,
- std::string path)
- : THttpTransport(transport), host_(host), path_(path) {
+THttpClient::THttpClient(boost::shared_ptr<TTransport> transport, std::string host, std::string path) :
+ THttpTransport(transport), host_(host), path_(path) {
}
-THttpClient::THttpClient(string host, int port, string path)
- : THttpTransport(boost::shared_ptr<TTransport>(new TSocket(host, port))),
- host_(host),
- path_(path) {
+THttpClient::THttpClient(string host, int port, string path) :
+ THttpTransport(boost::shared_ptr<TTransport>(new TSocket(host, port))), host_(host), path_(path) {
}
-THttpClient::~THttpClient() {
-}
+THttpClient::~THttpClient() {}
void THttpClient::parseHeader(char* header) {
char* colon = strchr(header, ':');
if (colon == NULL) {
return;
}
- char* value = colon + 1;
+ char* value = colon+1;
if (boost::istarts_with(header, "Transfer-Encoding")) {
if (boost::iends_with(value, "chunked")) {
@@ -72,8 +65,7 @@
}
*code = '\0';
- while (*(code++) == ' ') {
- };
+ while (*(code++) == ' ') {};
char* msg = strchr(code, ' ');
if (msg == NULL) {
@@ -100,13 +92,17 @@
// Construct the HTTP header
std::ostringstream h;
- h << "POST " << path_ << " HTTP/1.1" << CRLF << "Host: " << host_ << CRLF
- << "Content-Type: application/x-thrift" << CRLF << "Content-Length: " << len << CRLF
- << "Accept: application/x-thrift" << CRLF << "User-Agent: Thrift/" << VERSION
- << " (C++/THttpClient)" << CRLF << CRLF;
+ h <<
+ "POST " << path_ << " HTTP/1.1" << CRLF <<
+ "Host: " << host_ << CRLF <<
+ "Content-Type: application/x-thrift" << CRLF <<
+ "Content-Length: " << len << CRLF <<
+ "Accept: application/x-thrift" << CRLF <<
+ "User-Agent: Thrift/" << VERSION << " (C++/THttpClient)" << CRLF <<
+ CRLF;
string header = h.str();
- if (header.size() > (std::numeric_limits<uint32_t>::max)())
+ if(header.size() > (std::numeric_limits<uint32_t>::max)())
throw TTransportException("Header too big");
// Write the header, then the data, then flush
transport_->write((const uint8_t*)header.c_str(), static_cast<uint32_t>(header.size()));
@@ -117,6 +113,5 @@
writeBuffer_.resetBuffer();
readHeaders_ = true;
}
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
diff --git a/lib/cpp/src/thrift/transport/THttpClient.h b/lib/cpp/src/thrift/transport/THttpClient.h
index 64e7332..0898b11 100644
--- a/lib/cpp/src/thrift/transport/THttpClient.h
+++ b/lib/cpp/src/thrift/transport/THttpClient.h
@@ -22,29 +22,28 @@
#include <thrift/transport/THttpTransport.h>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
class THttpClient : public THttpTransport {
-public:
- THttpClient(boost::shared_ptr<TTransport> transport, std::string host, std::string path = "");
+ public:
+ THttpClient(boost::shared_ptr<TTransport> transport, std::string host, std::string path="");
- THttpClient(std::string host, int port, std::string path = "");
+ THttpClient(std::string host, int port, std::string path="");
virtual ~THttpClient();
virtual void flush();
-protected:
+ protected:
+
std::string host_;
std::string path_;
virtual void parseHeader(char* header);
virtual bool parseStatusLine(char* status);
+
};
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
#endif // #ifndef _THRIFT_TRANSPORT_THTTPCLIENT_H_
diff --git a/lib/cpp/src/thrift/transport/THttpServer.cpp b/lib/cpp/src/thrift/transport/THttpServer.cpp
index 12c55dc..620bbd2 100644
--- a/lib/cpp/src/thrift/transport/THttpServer.cpp
+++ b/lib/cpp/src/thrift/transport/THttpServer.cpp
@@ -24,17 +24,15 @@
#include <thrift/transport/THttpServer.h>
#include <thrift/transport/TSocket.h>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
using namespace std;
-THttpServer::THttpServer(boost::shared_ptr<TTransport> transport) : THttpTransport(transport) {
+THttpServer::THttpServer(boost::shared_ptr<TTransport> transport) :
+ THttpTransport(transport) {
}
-THttpServer::~THttpServer() {
-}
+THttpServer::~THttpServer() {}
void THttpServer::parseHeader(char* header) {
char* colon = strchr(header, ':');
@@ -42,7 +40,7 @@
return;
}
size_t sz = colon - header;
- char* value = colon + 1;
+ char* value = colon+1;
if (strncmp(header, "Transfer-Encoding", sz) == 0) {
if (strstr(value, "chunked") != NULL) {
@@ -65,8 +63,7 @@
}
*path = '\0';
- while (*(++path) == ' ') {
- };
+ while (*(++path) == ' ') {};
char* http = strchr(path, ' ');
if (http == NULL) {
@@ -77,7 +74,8 @@
if (strcmp(method, "POST") == 0) {
// POST method ok, looking for content.
return true;
- } else if (strcmp(method, "OPTIONS") == 0) {
+ }
+ else if (strcmp(method, "OPTIONS") == 0) {
// preflight OPTIONS method, we don't need further content.
// how to graciously close connection?
uint8_t* buf;
@@ -86,9 +84,13 @@
// Construct the HTTP header
std::ostringstream h;
- h << "HTTP/1.1 200 OK" << CRLF << "Date: " << getTimeRFC1123() << CRLF
- << "Access-Control-Allow-Origin: *" << CRLF << "Access-Control-Allow-Methods: POST, OPTIONS"
- << CRLF << "Access-Control-Allow-Headers: Content-Type" << CRLF << CRLF;
+ h <<
+ "HTTP/1.1 200 OK" << CRLF <<
+ "Date: " << getTimeRFC1123() << CRLF <<
+ "Access-Control-Allow-Origin: *" << CRLF <<
+ "Access-Control-Allow-Methods: POST, OPTIONS" << CRLF <<
+ "Access-Control-Allow-Headers: Content-Type" << CRLF <<
+ CRLF;
string header = h.str();
// Write the header, then the data, then flush
@@ -112,10 +114,15 @@
// Construct the HTTP header
std::ostringstream h;
- h << "HTTP/1.1 200 OK" << CRLF << "Date: " << getTimeRFC1123() << CRLF << "Server: Thrift/"
- << VERSION << CRLF << "Access-Control-Allow-Origin: *" << CRLF
- << "Content-Type: application/x-thrift" << CRLF << "Content-Length: " << len << CRLF
- << "Connection: Keep-Alive" << CRLF << CRLF;
+ h <<
+ "HTTP/1.1 200 OK" << CRLF <<
+ "Date: " << getTimeRFC1123() << CRLF <<
+ "Server: Thrift/" << VERSION << CRLF <<
+ "Access-Control-Allow-Origin: *" << CRLF <<
+ "Content-Type: application/x-thrift" << CRLF <<
+ "Content-Length: " << len << CRLF <<
+ "Connection: Keep-Alive" << CRLF <<
+ CRLF;
string header = h.str();
// Write the header, then the data, then flush
@@ -129,25 +136,19 @@
readHeaders_ = true;
}
-std::string THttpServer::getTimeRFC1123() {
- static const char* Days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
- static const char* Months[]
- = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
+std::string THttpServer::getTimeRFC1123()
+{
+ static const char* Days[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
+ static const char* Months[] = {"Jan","Feb","Mar", "Apr", "May", "Jun", "Jul","Aug", "Sep", "Oct","Nov","Dec"};
char buff[128];
time_t t = time(NULL);
tm* broken_t = gmtime(&t);
- sprintf(buff,
- "%s, %d %s %d %d:%d:%d GMT",
- Days[broken_t->tm_wday],
- broken_t->tm_mday,
- Months[broken_t->tm_mon],
+ sprintf(buff,"%s, %d %s %d %d:%d:%d GMT",
+ Days[broken_t->tm_wday], broken_t->tm_mday, Months[broken_t->tm_mon],
broken_t->tm_year + 1900,
- broken_t->tm_hour,
- broken_t->tm_min,
- broken_t->tm_sec);
+ broken_t->tm_hour,broken_t->tm_min,broken_t->tm_sec);
return std::string(buff);
}
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
diff --git a/lib/cpp/src/thrift/transport/THttpServer.h b/lib/cpp/src/thrift/transport/THttpServer.h
index a7ab944..bf69dbe 100644
--- a/lib/cpp/src/thrift/transport/THttpServer.h
+++ b/lib/cpp/src/thrift/transport/THttpServer.h
@@ -22,30 +22,30 @@
#include <thrift/transport/THttpTransport.h>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
class THttpServer : public THttpTransport {
-public:
+ public:
THttpServer(boost::shared_ptr<TTransport> transport);
virtual ~THttpServer();
virtual void flush();
-protected:
+ protected:
+
void readHeaders();
virtual void parseHeader(char* header);
virtual bool parseStatusLine(char* status);
std::string getTimeRFC1123();
+
};
/**
* Wraps a transport into HTTP protocol
*/
class THttpServerTransportFactory : public TTransportFactory {
-public:
+ public:
THttpServerTransportFactory() {}
virtual ~THttpServerTransportFactory() {}
@@ -56,9 +56,9 @@
virtual boost::shared_ptr<TTransport> getTransport(boost::shared_ptr<TTransport> trans) {
return boost::shared_ptr<TTransport>(new THttpServer(trans));
}
+
};
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
#endif // #ifndef _THRIFT_TRANSPORT_THTTPSERVER_H_
diff --git a/lib/cpp/src/thrift/transport/THttpTransport.cpp b/lib/cpp/src/thrift/transport/THttpTransport.cpp
index eccac90..79ee7d5 100644
--- a/lib/cpp/src/thrift/transport/THttpTransport.cpp
+++ b/lib/cpp/src/thrift/transport/THttpTransport.cpp
@@ -21,9 +21,7 @@
#include <thrift/transport/THttpTransport.h>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
using namespace std;
@@ -31,23 +29,23 @@
const char* THttpTransport::CRLF = "\r\n";
const int THttpTransport::CRLF_LEN = 2;
-THttpTransport::THttpTransport(boost::shared_ptr<TTransport> transport)
- : transport_(transport),
- origin_(""),
- readHeaders_(true),
- chunked_(false),
- chunkedDone_(false),
- chunkSize_(0),
- contentLength_(0),
- httpBuf_(NULL),
- httpPos_(0),
- httpBufLen_(0),
- httpBufSize_(1024) {
+THttpTransport::THttpTransport(boost::shared_ptr<TTransport> transport) :
+ transport_(transport),
+ origin_(""),
+ readHeaders_(true),
+ chunked_(false),
+ chunkedDone_(false),
+ chunkSize_(0),
+ contentLength_(0),
+ httpBuf_(NULL),
+ httpPos_(0),
+ httpBufLen_(0),
+ httpBufSize_(1024) {
init();
}
void THttpTransport::init() {
- httpBuf_ = (char*)std::malloc(httpBufSize_ + 1);
+ httpBuf_ = (char*)std::malloc(httpBufSize_+1);
if (httpBuf_ == NULL) {
throw std::bad_alloc();
}
@@ -154,7 +152,7 @@
if (need < give) {
give = need;
}
- readBuffer_.write((uint8_t*)(httpBuf_ + httpPos_), give);
+ readBuffer_.write((uint8_t*)(httpBuf_+httpPos_), give);
httpPos_ += give;
need -= give;
}
@@ -165,7 +163,7 @@
while (true) {
char* eol = NULL;
- eol = strstr(httpBuf_ + httpPos_, CRLF);
+ eol = strstr(httpBuf_+httpPos_, CRLF);
// No CRLF yet?
if (eol == NULL) {
@@ -175,18 +173,19 @@
} else {
// Return pointer to next line
*eol = '\0';
- char* line = httpBuf_ + httpPos_;
- httpPos_ = static_cast<uint32_t>((eol - httpBuf_) + CRLF_LEN);
+ char* line = httpBuf_+httpPos_;
+ httpPos_ = static_cast<uint32_t>((eol-httpBuf_) + CRLF_LEN);
return line;
}
}
+
}
void THttpTransport::shift() {
if (httpBufLen_ > httpPos_) {
// Shift down remaining data and read more
uint32_t length = httpBufLen_ - httpPos_;
- memmove(httpBuf_, httpBuf_ + httpPos_, length);
+ memmove(httpBuf_, httpBuf_+httpPos_, length);
httpBufLen_ = length;
} else {
httpBufLen_ = 0;
@@ -199,14 +198,14 @@
uint32_t avail = httpBufSize_ - httpBufLen_;
if (avail <= (httpBufSize_ / 4)) {
httpBufSize_ *= 2;
- httpBuf_ = (char*)std::realloc(httpBuf_, httpBufSize_ + 1);
+ httpBuf_ = (char*)std::realloc(httpBuf_, httpBufSize_+1);
if (httpBuf_ == NULL) {
throw std::bad_alloc();
}
}
// Read more data
- uint32_t got = transport_->read((uint8_t*)(httpBuf_ + httpBufLen_), httpBufSize_ - httpBufLen_);
+ uint32_t got = transport_->read((uint8_t*)(httpBuf_+httpBufLen_), httpBufSize_-httpBufLen_);
httpBufLen_ += got;
httpBuf_[httpBufLen_] = '\0';
@@ -255,12 +254,11 @@
const std::string THttpTransport::getOrigin() {
std::ostringstream oss;
- if (!origin_.empty()) {
+ if ( !origin_.empty()) {
oss << origin_ << ", ";
}
oss << transport_->getOrigin();
return oss.str();
}
-}
-}
-}
+
+}}}
diff --git a/lib/cpp/src/thrift/transport/THttpTransport.h b/lib/cpp/src/thrift/transport/THttpTransport.h
index a9f564c..8967c74 100644
--- a/lib/cpp/src/thrift/transport/THttpTransport.h
+++ b/lib/cpp/src/thrift/transport/THttpTransport.h
@@ -23,9 +23,7 @@
#include <thrift/transport/TBufferTransports.h>
#include <thrift/transport/TVirtualTransport.h>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
/**
* HTTP implementation of the thrift transport. This was irritating
@@ -35,18 +33,26 @@
* chunked transfer encoding, keepalive, etc. Tested against Apache.
*/
class THttpTransport : public TVirtualTransport<THttpTransport> {
-public:
+ public:
THttpTransport(boost::shared_ptr<TTransport> transport);
virtual ~THttpTransport();
- void open() { transport_->open(); }
+ void open() {
+ transport_->open();
+ }
- bool isOpen() { return transport_->isOpen(); }
+ bool isOpen() {
+ return transport_->isOpen();
+ }
- bool peek() { return transport_->peek(); }
+ bool peek() {
+ return transport_->peek();
+ }
- void close() { transport_->close(); }
+ void close() {
+ transport_->close();
+ }
uint32_t read(uint8_t* buf, uint32_t len);
@@ -58,7 +64,8 @@
virtual const std::string getOrigin();
-protected:
+ protected:
+
boost::shared_ptr<TTransport> transport_;
std::string origin_;
@@ -97,8 +104,7 @@
static const char* CRLF;
static const int CRLF_LEN;
};
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
#endif // #ifndef _THRIFT_TRANSPORT_THTTPCLIENT_H_
diff --git a/lib/cpp/src/thrift/transport/TPipe.cpp b/lib/cpp/src/thrift/transport/TPipe.cpp
index 15e4845..3bb3dac 100644
--- a/lib/cpp/src/thrift/transport/TPipe.cpp
+++ b/lib/cpp/src/thrift/transport/TPipe.cpp
@@ -20,13 +20,11 @@
#include <thrift/transport/TTransportException.h>
#include <thrift/transport/TPipe.h>
#ifdef _WIN32
-#include <thrift/windows/OverlappedSubmissionThread.h>
-#include <thrift/windows/Sync.h>
+ #include <thrift/windows/OverlappedSubmissionThread.h>
+ #include <thrift/windows/Sync.h>
#endif
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
using namespace std;
@@ -48,9 +46,9 @@
virtual ~TPipeImpl() = 0 {}
virtual uint32_t read(uint8_t* buf, uint32_t len) = 0;
virtual void write(const uint8_t* buf, uint32_t len) = 0;
- virtual HANDLE getPipeHandle() = 0; // doubles as the read handle for anon pipe
+ virtual HANDLE getPipeHandle() = 0; //doubles as the read handle for anon pipe
virtual void setPipeHandle(HANDLE pipehandle) = 0;
- virtual HANDLE getWrtPipeHandle() { return INVALID_HANDLE_VALUE; }
+ virtual HANDLE getWrtPipeHandle() {return INVALID_HANDLE_VALUE;}
virtual void setWrtPipeHandle(HANDLE) {}
virtual bool isBufferedDataAvailable() { return false; }
virtual HANDLE getNativeWaitHandle() { return INVALID_HANDLE_VALUE; }
@@ -60,16 +58,15 @@
public:
explicit TNamedPipeImpl(HANDLE pipehandle) : Pipe_(pipehandle) {}
virtual ~TNamedPipeImpl() {}
- virtual uint32_t read(uint8_t* buf, uint32_t len) {
- return pseudo_sync_read(Pipe_.h, read_event_.h, buf, len);
+ virtual uint32_t read(uint8_t* buf, uint32_t len) {
+ return pseudo_sync_read (Pipe_.h, read_event_.h, buf, len);
}
virtual void write(const uint8_t* buf, uint32_t len) {
pseudo_sync_write(Pipe_.h, write_event_.h, buf, len);
}
- virtual HANDLE getPipeHandle() { return Pipe_.h; }
- virtual void setPipeHandle(HANDLE pipehandle) { Pipe_.reset(pipehandle); }
-
+ virtual HANDLE getPipeHandle() {return Pipe_.h;}
+ virtual void setPipeHandle(HANDLE pipehandle) {Pipe_.reset(pipehandle);}
private:
TManualResetEvent read_event_;
TManualResetEvent write_event_;
@@ -80,14 +77,13 @@
public:
TAnonPipeImpl(HANDLE PipeRd, HANDLE PipeWrt) : PipeRd_(PipeRd), PipeWrt_(PipeWrt) {}
virtual ~TAnonPipeImpl() {}
- virtual uint32_t read(uint8_t* buf, uint32_t len) { return pipe_read(PipeRd_.h, buf, len); }
- virtual void write(const uint8_t* buf, uint32_t len) { pipe_write(PipeWrt_.h, buf, len); }
+ virtual uint32_t read(uint8_t* buf, uint32_t len) {return pipe_read (PipeRd_.h, buf, len);}
+ virtual void write(const uint8_t* buf, uint32_t len) { pipe_write(PipeWrt_.h, buf, len);}
- virtual HANDLE getPipeHandle() { return PipeRd_.h; }
- virtual void setPipeHandle(HANDLE PipeRd) { PipeRd_.reset(PipeRd); }
- virtual HANDLE getWrtPipeHandle() { return PipeWrt_.h; }
- virtual void setWrtPipeHandle(HANDLE PipeWrt) { PipeWrt_.reset(PipeWrt); }
-
+ virtual HANDLE getPipeHandle() {return PipeRd_.h;}
+ virtual void setPipeHandle(HANDLE PipeRd) {PipeRd_.reset(PipeRd);}
+ virtual HANDLE getWrtPipeHandle() {return PipeWrt_.h;}
+ virtual void setWrtPipeHandle(HANDLE PipeWrt) {PipeWrt_.reset(PipeWrt);}
private:
TAutoHandle PipeRd_;
TAutoHandle PipeWrt_;
@@ -98,8 +94,11 @@
// than using the regular named pipe implementation
class TWaitableNamedPipeImpl : public TPipeImpl {
public:
- explicit TWaitableNamedPipeImpl(HANDLE pipehandle)
- : Pipe_(pipehandle), begin_unread_idx_(0), end_unread_idx_(0) {
+ explicit TWaitableNamedPipeImpl(HANDLE pipehandle) :
+ Pipe_(pipehandle),
+ begin_unread_idx_(0),
+ end_unread_idx_(0)
+ {
readOverlap_.action = TOverlappedWorkItem::READ;
readOverlap_.h = Pipe_.h;
cancelOverlap_.action = TOverlappedWorkItem::CANCELIO;
@@ -109,7 +108,7 @@
}
virtual ~TWaitableNamedPipeImpl() {
// see if there is an outstanding read request
- if (begin_unread_idx_ == end_unread_idx_) {
+ if(begin_unread_idx_ == end_unread_idx_) {
// if so, cancel it, and wait for the dead completion
thread_->addWorkItem(&cancelOverlap_);
readOverlap_.overlappedResults(false /*ignore errors*/);
@@ -120,11 +119,10 @@
pseudo_sync_write(Pipe_.h, write_event_.h, buf, len);
}
- virtual HANDLE getPipeHandle() { return Pipe_.h; }
- virtual void setPipeHandle(HANDLE pipehandle) { Pipe_.reset(pipehandle); }
- virtual bool isBufferedDataAvailable() { return begin_unread_idx_ < end_unread_idx_; }
+ virtual HANDLE getPipeHandle() {return Pipe_.h;}
+ virtual void setPipeHandle(HANDLE pipehandle) {Pipe_.reset(pipehandle);}
+ virtual bool isBufferedDataAvailable() {return begin_unread_idx_ < end_unread_idx_;}
virtual HANDLE getNativeWaitHandle() { return ready_event_.h; }
-
private:
void beginAsyncRead(uint8_t* buf, uint32_t len);
uint32_t endAsyncRead();
@@ -140,29 +138,34 @@
uint32_t end_unread_idx_;
};
-void TWaitableNamedPipeImpl::beginAsyncRead(uint8_t* buf, uint32_t len) {
+void TWaitableNamedPipeImpl::beginAsyncRead(uint8_t* buf, uint32_t len)
+{
begin_unread_idx_ = end_unread_idx_ = 0;
readOverlap_.reset(buf, len, ready_event_.h);
thread_->addWorkItem(&readOverlap_);
- if (readOverlap_.success == FALSE && readOverlap_.last_error != ERROR_IO_PENDING) {
+ if(readOverlap_.success == FALSE && readOverlap_.last_error != ERROR_IO_PENDING)
+ {
GlobalOutput.perror("TPipe ::ReadFile errored GLE=", readOverlap_.last_error);
throw TTransportException(TTransportException::UNKNOWN, "TPipe: ReadFile failed");
}
}
-uint32_t TWaitableNamedPipeImpl::endAsyncRead() {
+uint32_t TWaitableNamedPipeImpl::endAsyncRead()
+{
return readOverlap_.overlappedResults();
}
-uint32_t TWaitableNamedPipeImpl::read(uint8_t* buf, uint32_t len) {
- if (begin_unread_idx_ == end_unread_idx_) {
+uint32_t TWaitableNamedPipeImpl::read(uint8_t* buf, uint32_t len)
+{
+ if(begin_unread_idx_ == end_unread_idx_) {
end_unread_idx_ = endAsyncRead();
}
- uint32_t bytes_to_copy = (std::min)(len, end_unread_idx_ - begin_unread_idx_);
+ uint32_t bytes_to_copy = (std::min)(len, end_unread_idx_-begin_unread_idx_);
memcpy(buf, &buffer_[begin_unread_idx_], bytes_to_copy);
begin_unread_idx_ += bytes_to_copy;
- if (begin_unread_idx_ != end_unread_idx_) {
+ if(begin_unread_idx_ != end_unread_idx_)
+ {
assert(len == bytes_to_copy);
// we were able to fulfill the read with just the bytes in our
// buffer, and we still have buffer left
@@ -170,29 +173,33 @@
}
uint32_t bytes_copied = bytes_to_copy;
- // all of the requested data has been read. Kick off an async read for the next round.
+ //all of the requested data has been read. Kick off an async read for the next round.
beginAsyncRead(&buffer_[0], static_cast<uint32_t>(buffer_.size()));
return bytes_copied;
}
-void pseudo_sync_write(HANDLE pipe, HANDLE event, const uint8_t* buf, uint32_t len) {
+void pseudo_sync_write(HANDLE pipe, HANDLE event, const uint8_t* buf, uint32_t len)
+{
OVERLAPPED tempOverlap;
- memset(&tempOverlap, 0, sizeof(tempOverlap));
+ memset( &tempOverlap, 0, sizeof(tempOverlap));
tempOverlap.hEvent = event;
uint32_t written = 0;
- while (written < len) {
- BOOL result = ::WriteFile(pipe, buf + written, len - written, NULL, &tempOverlap);
+ while(written < len)
+ {
+ BOOL result = ::WriteFile(pipe, buf+written, len-written, NULL, &tempOverlap);
- if (result == FALSE && ::GetLastError() != ERROR_IO_PENDING) {
+ if(result == FALSE && ::GetLastError() != ERROR_IO_PENDING)
+ {
GlobalOutput.perror("TPipe ::WriteFile errored GLE=", ::GetLastError());
throw TTransportException(TTransportException::UNKNOWN, "TPipe: write failed");
}
DWORD bytes = 0;
result = ::GetOverlappedResult(pipe, &tempOverlap, &bytes, TRUE);
- if (!result) {
+ if(!result)
+ {
GlobalOutput.perror("TPipe ::GetOverlappedResult errored GLE=", ::GetLastError());
throw TTransportException(TTransportException::UNKNOWN, "TPipe: GetOverlappedResult failed");
}
@@ -200,21 +207,24 @@
}
}
-uint32_t pseudo_sync_read(HANDLE pipe, HANDLE event, uint8_t* buf, uint32_t len) {
+uint32_t pseudo_sync_read(HANDLE pipe, HANDLE event, uint8_t* buf, uint32_t len)
+{
OVERLAPPED tempOverlap;
- memset(&tempOverlap, 0, sizeof(tempOverlap));
+ memset( &tempOverlap, 0, sizeof(tempOverlap));
tempOverlap.hEvent = event;
BOOL result = ::ReadFile(pipe, buf, len, NULL, &tempOverlap);
- if (result == FALSE && ::GetLastError() != ERROR_IO_PENDING) {
+ if(result == FALSE && ::GetLastError() != ERROR_IO_PENDING)
+ {
GlobalOutput.perror("TPipe ::ReadFile errored GLE=", ::GetLastError());
throw TTransportException(TTransportException::UNKNOWN, "TPipe: read failed");
}
DWORD bytes = 0;
result = ::GetOverlappedResult(pipe, &tempOverlap, &bytes, TRUE);
- if (!result) {
+ if(!result)
+ {
GlobalOutput.perror("TPipe ::GetOverlappedResult errored GLE=", ::GetLastError());
throw TTransportException(TTransportException::UNKNOWN, "TPipe: GetOverlappedResult failed");
}
@@ -222,27 +232,38 @@
}
//---- Constructors ----
-TPipe::TPipe(HANDLE Pipe)
- : impl_(new TWaitableNamedPipeImpl(Pipe)), TimeoutSeconds_(3), isAnonymous_(false) {
-}
+TPipe::TPipe(HANDLE Pipe) :
+ impl_(new TWaitableNamedPipeImpl(Pipe)),
+ TimeoutSeconds_(3),
+ isAnonymous_(false)
+{}
-TPipe::TPipe(const char* pipename) : TimeoutSeconds_(3), isAnonymous_(false) {
+TPipe::TPipe(const char *pipename) :
+ TimeoutSeconds_(3),
+ isAnonymous_(false)
+{
setPipename(pipename);
}
-TPipe::TPipe(const std::string& pipename) : TimeoutSeconds_(3), isAnonymous_(false) {
+TPipe::TPipe(const std::string &pipename) :
+ TimeoutSeconds_(3),
+ isAnonymous_(false)
+{
setPipename(pipename);
}
-TPipe::TPipe(HANDLE PipeRd, HANDLE PipeWrt)
- : impl_(new TAnonPipeImpl(PipeRd, PipeWrt)), TimeoutSeconds_(3), isAnonymous_(true) {
-}
+TPipe::TPipe(HANDLE PipeRd, HANDLE PipeWrt) :
+ impl_(new TAnonPipeImpl(PipeRd, PipeWrt)),
+ TimeoutSeconds_(3),
+ isAnonymous_(true)
+{}
-TPipe::TPipe() : TimeoutSeconds_(3), isAnonymous_(false) {
-}
+TPipe::TPipe() :
+ TimeoutSeconds_(3),
+ isAnonymous_(false)
+{}
-TPipe::~TPipe() {
-}
+TPipe::~TPipe() {}
//---------------------------------------------------------
// Transport callbacks
@@ -262,24 +283,27 @@
TAutoHandle hPipe;
do {
DWORD flags = FILE_FLAG_OVERLAPPED; // async mode, so we can do reads at the same time as writes
- hPipe.reset(CreateFile(pipename_.c_str(),
- GENERIC_READ | GENERIC_WRITE,
- 0, // no sharing
- NULL, // default security attributes
- OPEN_EXISTING, // opens existing pipe
- flags,
- NULL)); // no template file
+ hPipe.reset(CreateFile(
+ pipename_.c_str(),
+ GENERIC_READ | GENERIC_WRITE,
+ 0, // no sharing
+ NULL, // default security attributes
+ OPEN_EXISTING, // opens existing pipe
+ flags,
+ NULL)); // no template file
if (hPipe.h != INVALID_HANDLE_VALUE)
- break; // success!
+ break; //success!
- if (::GetLastError() != ERROR_PIPE_BUSY) {
+ if(::GetLastError() != ERROR_PIPE_BUSY)
+ {
GlobalOutput.perror("TPipe::open ::CreateFile errored GLE=", ::GetLastError());
throw TTransportException(TTransportException::NOT_OPEN, "Unable to open pipe");
}
- } while (::WaitNamedPipe(pipename_.c_str(), TimeoutSeconds_ * 1000));
+ } while( ::WaitNamedPipe(pipename_.c_str(), TimeoutSeconds_*1000) );
- if (hPipe.h == INVALID_HANDLE_VALUE) {
+ if(hPipe.h == INVALID_HANDLE_VALUE)
+ {
GlobalOutput.perror("TPipe::open ::CreateFile errored GLE=", ::GetLastError());
throw TTransportException(TTransportException::NOT_OPEN, "Unable to open pipe");
}
@@ -288,6 +312,7 @@
hPipe.release();
}
+
void TPipe::close() {
impl_.reset();
}
@@ -298,15 +323,17 @@
return impl_->read(buf, len);
}
-uint32_t pipe_read(HANDLE pipe, uint8_t* buf, uint32_t len) {
- DWORD cbRead;
- int fSuccess = ReadFile(pipe, // pipe handle
- buf, // buffer to receive reply
- len, // size of buffer
- &cbRead, // number of bytes read
- NULL); // not overlapped
+uint32_t pipe_read(HANDLE pipe, uint8_t* buf, uint32_t len)
+{
+ DWORD cbRead;
+ int fSuccess = ReadFile(
+ pipe, // pipe handle
+ buf, // buffer to receive reply
+ len, // size of buffer
+ &cbRead, // number of bytes read
+ NULL); // not overlapped
- if (!fSuccess && GetLastError() != ERROR_MORE_DATA)
+ if ( !fSuccess && GetLastError() != ERROR_MORE_DATA )
return 0; // No more data, possibly because client disconnected.
return cbRead;
@@ -318,15 +345,17 @@
impl_->write(buf, len);
}
-void pipe_write(HANDLE pipe, const uint8_t* buf, uint32_t len) {
- DWORD cbWritten;
- int fSuccess = WriteFile(pipe, // pipe handle
- buf, // message
- len, // message length
- &cbWritten, // bytes written
- NULL); // not overlapped
+void pipe_write(HANDLE pipe, const uint8_t* buf, uint32_t len)
+{
+ DWORD cbWritten;
+ int fSuccess = WriteFile(
+ pipe, // pipe handle
+ buf, // message
+ len, // message length
+ &cbWritten, // bytes written
+ NULL); // not overlapped
- if (!fSuccess)
+ if ( !fSuccess)
throw TTransportException(TTransportException::NOT_OPEN, "Write to pipe failed");
}
@@ -338,40 +367,36 @@
return pipename_;
}
-void TPipe::setPipename(const std::string& pipename) {
- if (pipename.find("\\\\") == -1)
+void TPipe::setPipename(const std::string &pipename) {
+ if(pipename.find("\\\\") == -1)
pipename_ = "\\\\.\\pipe\\" + pipename;
else
pipename_ = pipename;
}
HANDLE TPipe::getPipeHandle() {
- if (impl_)
- return impl_->getPipeHandle();
+ if(impl_) return impl_->getPipeHandle();
return INVALID_HANDLE_VALUE;
}
void TPipe::setPipeHandle(HANDLE pipehandle) {
- if (isAnonymous_)
+ if(isAnonymous_)
impl_->setPipeHandle(pipehandle);
else
impl_.reset(new TNamedPipeImpl(pipehandle));
}
HANDLE TPipe::getWrtPipeHandle() {
- if (impl_)
- return impl_->getWrtPipeHandle();
+ if(impl_) return impl_->getWrtPipeHandle();
return INVALID_HANDLE_VALUE;
}
void TPipe::setWrtPipeHandle(HANDLE pipehandle) {
- if (impl_)
- impl_->setWrtPipeHandle(pipehandle);
+ if(impl_) impl_->setWrtPipeHandle(pipehandle);
}
HANDLE TPipe::getNativeWaitHandle() {
- if (impl_)
- return impl_->getNativeWaitHandle();
+ if(impl_) return impl_->getNativeWaitHandle();
return INVALID_HANDLE_VALUE;
}
@@ -384,6 +409,5 @@
}
#endif //_WIN32
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
diff --git a/lib/cpp/src/thrift/transport/TPipe.h b/lib/cpp/src/thrift/transport/TPipe.h
index ef957c6..2e4539c 100644
--- a/lib/cpp/src/thrift/transport/TPipe.h
+++ b/lib/cpp/src/thrift/transport/TPipe.h
@@ -23,13 +23,11 @@
#include <thrift/transport/TTransport.h>
#include <thrift/transport/TVirtualTransport.h>
#ifndef _WIN32
-#include <thrift/transport/TSocket.h>
+# include <thrift/transport/TSocket.h>
#endif
#include <boost/noncopyable.hpp>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
/**
* Windows Pipes implementation of the TTransport interface.
@@ -41,14 +39,14 @@
class TPipeImpl;
class TPipe : public TVirtualTransport<TPipe> {
-public:
+ public:
// Constructs a new pipe object.
TPipe();
// Named pipe constructors -
- explicit TPipe(HANDLE Pipe); // HANDLE is a void*
- // need a const char * overload so string literals don't go to the HANDLE overload
- explicit TPipe(const char* pipename);
- explicit TPipe(const std::string& pipename);
+ explicit TPipe(HANDLE Pipe); //HANDLE is a void*
+ //need a const char * overload so string literals don't go to the HANDLE overload
+ explicit TPipe(const char *pipename);
+ explicit TPipe(const std::string &pipename);
// Anonymous pipe -
TPipe(HANDLE PipeRd, HANDLE PipeWrt);
@@ -73,21 +71,21 @@
// Writes to the pipe.
virtual void write(const uint8_t* buf, uint32_t len);
- // Accessors
+
+ //Accessors
std::string getPipename();
- void setPipename(const std::string& pipename);
- HANDLE getPipeHandle(); // doubles as the read handle for anon pipe
+ void setPipename(const std::string &pipename);
+ HANDLE getPipeHandle(); //doubles as the read handle for anon pipe
void setPipeHandle(HANDLE pipehandle);
HANDLE getWrtPipeHandle();
void setWrtPipeHandle(HANDLE pipehandle);
long getConnectTimeout();
void setConnectTimeout(long seconds);
- // this function is intended to be used in generic / template situations,
- // so its name needs to be the same as TPipeServer's
+ //this function is intended to be used in generic / template situations,
+ //so its name needs to be the same as TPipeServer's
HANDLE getNativeWaitHandle();
-
-private:
+ private:
boost::shared_ptr<TPipeImpl> impl_;
std::string pipename_;
@@ -99,8 +97,8 @@
#else
typedef TSocket TPipe;
#endif
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
#endif // #ifndef _THRIFT_TRANSPORT_TPIPE_H_
+
diff --git a/lib/cpp/src/thrift/transport/TPipeServer.cpp b/lib/cpp/src/thrift/transport/TPipeServer.cpp
index a8e72d0..e14a94a 100644
--- a/lib/cpp/src/thrift/transport/TPipeServer.cpp
+++ b/lib/cpp/src/thrift/transport/TPipeServer.cpp
@@ -26,14 +26,12 @@
#include <boost/noncopyable.hpp>
#ifdef _WIN32
-#include <thrift/windows/OverlappedSubmissionThread.h>
-#include <AccCtrl.h>
-#include <Aclapi.h>
+# include <thrift/windows/OverlappedSubmissionThread.h>
+# include <AccCtrl.h>
+# include <Aclapi.h>
#endif //_WIN32
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
#ifdef _WIN32
@@ -50,27 +48,27 @@
virtual HANDLE getPipeHandle() = 0;
virtual HANDLE getWrtPipeHandle() = 0;
- virtual HANDLE getClientRdPipeHandle() = 0;
- virtual HANDLE getClientWrtPipeHandle() = 0;
- virtual HANDLE getNativeWaitHandle() { return NULL; }
+ virtual HANDLE getClientRdPipeHandle()= 0;
+ virtual HANDLE getClientWrtPipeHandle()= 0;
+ virtual HANDLE getNativeWaitHandle() {return NULL;}
};
class TAnonPipeServer : public TPipeServerImpl {
public:
- TAnonPipeServer() {
- // The anonymous pipe needs to be created first so that the server can
- // pass the handles on to the client before the serve (acceptImpl)
- // blocking call.
+ TAnonPipeServer()
+ {
+ //The anonymous pipe needs to be created first so that the server can
+ //pass the handles on to the client before the serve (acceptImpl)
+ //blocking call.
if (!createAnonPipe()) {
GlobalOutput.perror("TPipeServer Create(Anon)Pipe failed, GLE=", GetLastError());
- throw TTransportException(TTransportException::NOT_OPEN,
- " TPipeServer Create(Anon)Pipe failed");
+ throw TTransportException(TTransportException::NOT_OPEN, " TPipeServer Create(Anon)Pipe failed");
}
}
virtual ~TAnonPipeServer() {}
- virtual void interrupt() {} // not currently implemented
+ virtual void interrupt() {} //not currently implemented
virtual void close() {
PipeR_.reset();
PipeW_.reset();
@@ -80,18 +78,17 @@
virtual boost::shared_ptr<TTransport> acceptImpl();
- virtual HANDLE getPipeHandle() { return PipeR_.h; }
- virtual HANDLE getWrtPipeHandle() { return PipeW_.h; }
- virtual HANDLE getClientRdPipeHandle() { return ClientAnonRead_.h; }
- virtual HANDLE getClientWrtPipeHandle() { return ClientAnonWrite_.h; }
-
+ virtual HANDLE getPipeHandle() {return PipeR_.h;}
+ virtual HANDLE getWrtPipeHandle() {return PipeW_.h;}
+ virtual HANDLE getClientRdPipeHandle() {return ClientAnonRead_.h;}
+ virtual HANDLE getClientWrtPipeHandle() {return ClientAnonWrite_.h;}
private:
bool createAnonPipe();
TAutoHandle PipeR_; // Anonymous Pipe (R)
TAutoHandle PipeW_; // Anonymous Pipe (W)
- // Client side anonymous pipe handles
+ //Client side anonymous pipe handles
//? Do we need duplicates to send to client?
TAutoHandle ClientAnonRead_;
TAutoHandle ClientAnonWrite_;
@@ -99,18 +96,26 @@
class TNamedPipeServer : public TPipeServerImpl {
public:
- TNamedPipeServer(const std::string& pipename, uint32_t bufsize, uint32_t maxconnections)
- : stopping_(false), pipename_(pipename), bufsize_(bufsize), maxconns_(maxconnections) {
+ TNamedPipeServer(
+ const std::string &pipename,
+ uint32_t bufsize,
+ uint32_t maxconnections) :
+ stopping_(false),
+ pipename_(pipename),
+ bufsize_(bufsize),
+ maxconns_(maxconnections)
+ {
connectOverlap_.action = TOverlappedWorkItem::CONNECT;
cancelOverlap_.action = TOverlappedWorkItem::CANCELIO;
initiateNamedConnect();
}
virtual ~TNamedPipeServer() {}
- virtual void interrupt() {
+ virtual void interrupt()
+ {
TAutoCrit lock(pipe_protect_);
cached_client_.reset();
- if (Pipe_.h != INVALID_HANDLE_VALUE) {
+ if(Pipe_.h != INVALID_HANDLE_VALUE) {
stopping_ = true;
cancelOverlap_.h = Pipe_.h;
// This should wake up GetOverlappedResult
@@ -119,16 +124,17 @@
}
}
- virtual void close() { Pipe_.reset(); }
+ virtual void close() {
+ Pipe_.reset();
+ }
virtual boost::shared_ptr<TTransport> acceptImpl();
- virtual HANDLE getPipeHandle() { return Pipe_.h; }
- virtual HANDLE getWrtPipeHandle() { return INVALID_HANDLE_VALUE; }
- virtual HANDLE getClientRdPipeHandle() { return INVALID_HANDLE_VALUE; }
- virtual HANDLE getClientWrtPipeHandle() { return INVALID_HANDLE_VALUE; }
- virtual HANDLE getNativeWaitHandle() { return listen_event_.h; }
-
+ virtual HANDLE getPipeHandle() {return Pipe_.h;}
+ virtual HANDLE getWrtPipeHandle() {return INVALID_HANDLE_VALUE;}
+ virtual HANDLE getClientRdPipeHandle() {return INVALID_HANDLE_VALUE;}
+ virtual HANDLE getClientWrtPipeHandle() {return INVALID_HANDLE_VALUE;}
+ virtual HANDLE getNativeWaitHandle() {return listen_event_.h;}
private:
bool createNamedPipe();
void initiateNamedConnect();
@@ -147,50 +153,61 @@
TCriticalSection pipe_protect_;
};
-HANDLE TPipeServer::getNativeWaitHandle() {
- if (impl_)
- return impl_->getNativeWaitHandle();
+HANDLE TPipeServer::getNativeWaitHandle()
+{
+ if(impl_) return impl_->getNativeWaitHandle();
return NULL;
}
//---- Constructors ----
-TPipeServer::TPipeServer(const std::string& pipename, uint32_t bufsize)
- : bufsize_(bufsize), isAnonymous_(false) {
+TPipeServer::TPipeServer(const std::string &pipename, uint32_t bufsize) :
+ bufsize_(bufsize),
+ isAnonymous_(false)
+{
setMaxConnections(TPIPE_SERVER_MAX_CONNS_DEFAULT);
setPipename(pipename);
}
-TPipeServer::TPipeServer(const std::string& pipename, uint32_t bufsize, uint32_t maxconnections)
- : bufsize_(bufsize), isAnonymous_(false) {
+TPipeServer::TPipeServer(const std::string &pipename, uint32_t bufsize, uint32_t maxconnections) :
+ bufsize_(bufsize),
+ isAnonymous_(false)
+{
setMaxConnections(maxconnections);
setPipename(pipename);
}
-TPipeServer::TPipeServer(const std::string& pipename) : bufsize_(1024), isAnonymous_(false) {
+TPipeServer::TPipeServer(const std::string &pipename) :
+ bufsize_(1024),
+ isAnonymous_(false)
+{
setMaxConnections(TPIPE_SERVER_MAX_CONNS_DEFAULT);
setPipename(pipename);
}
-TPipeServer::TPipeServer(int bufsize) : bufsize_(bufsize), isAnonymous_(true) {
+TPipeServer::TPipeServer(int bufsize) :
+ bufsize_(bufsize),
+ isAnonymous_(true)
+{
setMaxConnections(1);
impl_.reset(new TAnonPipeServer);
}
-TPipeServer::TPipeServer() : bufsize_(1024), isAnonymous_(true) {
+TPipeServer::TPipeServer() :
+ bufsize_(1024),
+ isAnonymous_(true)
+{
setMaxConnections(1);
impl_.reset(new TAnonPipeServer);
}
//---- Destructor ----
-TPipeServer::~TPipeServer() {
-}
+TPipeServer::~TPipeServer() {}
//---------------------------------------------------------
// Transport callbacks
//---------------------------------------------------------
void TPipeServer::listen() {
- if (isAnonymous_)
- return;
+ if(isAnonymous_) return;
impl_.reset(new TNamedPipeServer(pipename_, bufsize_, maxconns_));
}
@@ -199,27 +216,26 @@
}
shared_ptr<TTransport> TAnonPipeServer::acceptImpl() {
- // This 0-byte read serves merely as a blocking call.
+ //This 0-byte read serves merely as a blocking call.
byte buf;
DWORD br;
- int fSuccess = ReadFile(PipeR_.h, // pipe handle
- &buf, // buffer to receive reply
- 0, // size of buffer
- &br, // number of bytes read
- NULL); // not overlapped
+ int fSuccess = ReadFile(
+ PipeR_.h, // pipe handle
+ &buf, // buffer to receive reply
+ 0, // size of buffer
+ &br, // number of bytes read
+ NULL); // not overlapped
- if (!fSuccess && GetLastError() != ERROR_MORE_DATA) {
+ if ( !fSuccess && GetLastError() != ERROR_MORE_DATA ) {
GlobalOutput.perror("TPipeServer unable to initiate pipe comms, GLE=", GetLastError());
- throw TTransportException(TTransportException::NOT_OPEN,
- " TPipeServer unable to initiate pipe comms");
+ throw TTransportException(TTransportException::NOT_OPEN, " TPipeServer unable to initiate pipe comms");
}
shared_ptr<TPipe> client(new TPipe(PipeR_.h, PipeW_.h));
return client;
}
void TNamedPipeServer::initiateNamedConnect() {
- if (stopping_)
- return;
+ if (stopping_) return;
if (!createNamedPipe()) {
GlobalOutput.perror("TPipeServer CreateNamedPipe failed, GLE=", GetLastError());
throw TTransportException(TTransportException::NOT_OPEN, " TPipeServer CreateNamedPipe failed");
@@ -234,7 +250,8 @@
// Wait for the client to connect; if it succeeds, the
// function returns a nonzero value. If the function returns
// zero, GetLastError should return ERROR_PIPE_CONNECTED.
- if (connectOverlap_.success) {
+ if( connectOverlap_.success )
+ {
GlobalOutput.printf("Client connected.");
cached_client_.reset(new TPipe(Pipe_.h));
Pipe_.release();
@@ -244,7 +261,8 @@
}
DWORD dwErr = connectOverlap_.last_error;
- switch (dwErr) {
+ switch( dwErr)
+ {
case ERROR_PIPE_CONNECTED:
GlobalOutput.printf("Client connected.");
cached_client_.reset(new TPipe(Pipe_.h));
@@ -253,68 +271,68 @@
SetEvent(listen_event_.h);
return;
case ERROR_IO_PENDING:
- return; // acceptImpl will do the appropriate WaitForMultipleObjects
+ return; //acceptImpl will do the appropriate WaitForMultipleObjects
default:
GlobalOutput.perror("TPipeServer ConnectNamedPipe failed, GLE=", dwErr);
- throw TTransportException(TTransportException::NOT_OPEN,
- " TPipeServer ConnectNamedPipe failed");
+ throw TTransportException(TTransportException::NOT_OPEN, " TPipeServer ConnectNamedPipe failed");
}
}
shared_ptr<TTransport> TNamedPipeServer::acceptImpl() {
{
TAutoCrit lock(pipe_protect_);
- if (cached_client_.get() != NULL) {
+ if(cached_client_.get() != NULL)
+ {
shared_ptr<TPipe> client;
- // zero out cached_client, since we are about to return it.
+ //zero out cached_client, since we are about to return it.
client.swap(cached_client_);
- // kick off the next connection before returning
+ //kick off the next connection before returning
initiateNamedConnect();
- return client; // success!
+ return client; //success!
}
}
- if (Pipe_.h == INVALID_HANDLE_VALUE) {
- throw TTransportException(TTransportException::NOT_OPEN,
- "TNamedPipeServer: someone called accept on a closed pipe server");
+ if(Pipe_.h == INVALID_HANDLE_VALUE) {
+ throw TTransportException(
+ TTransportException::NOT_OPEN,
+ "TNamedPipeServer: someone called accept on a closed pipe server");
}
DWORD dwDummy = 0;
- if (GetOverlappedResult(Pipe_.h, &connectOverlap_.overlap, &dwDummy, TRUE)) {
+ if(GetOverlappedResult(Pipe_.h, &connectOverlap_.overlap, &dwDummy, TRUE))
+ {
TAutoCrit lock(pipe_protect_);
GlobalOutput.printf("Client connected.");
shared_ptr<TPipe> client(new TPipe(Pipe_.h));
Pipe_.release();
- // kick off the next connection before returning
+ //kick off the next connection before returning
initiateNamedConnect();
- return client; // success!
+ return client; //success!
}
- // if we got here, then we are in an error / shutdown case
- DWORD gle = GetLastError(); // save error before doing cleanup
+ //if we got here, then we are in an error / shutdown case
+ DWORD gle = GetLastError(); //save error before doing cleanup
close();
GlobalOutput.perror("TPipeServer ConnectNamedPipe GLE=", gle);
throw TTransportException(TTransportException::NOT_OPEN, "TPipeServer: client connection failed");
}
void TPipeServer::interrupt() {
- if (impl_)
- impl_->interrupt();
+ if(impl_) impl_->interrupt();
}
void TPipeServer::close() {
- if (impl_)
- impl_->close();
+ if(impl_) impl_->close();
}
+
bool TNamedPipeServer::createNamedPipe() {
- // Windows - set security to allow non-elevated apps
- // to access pipes created by elevated apps.
+ //Windows - set security to allow non-elevated apps
+ //to access pipes created by elevated apps.
SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY;
PSID everyone_sid = NULL;
- AllocateAndInitializeSid(
- &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &everyone_sid);
+ AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &everyone_sid);
EXPLICIT_ACCESS ea;
ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS));
@@ -323,12 +341,12 @@
ea.grfInheritance = NO_INHERITANCE;
ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
ea.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
- ea.Trustee.ptstrName = (LPSTR)everyone_sid;
+ ea.Trustee.ptstrName = (LPSTR)everyone_sid;
PACL acl = NULL;
SetEntriesInAcl(1, &ea, NULL, &acl);
- PSECURITY_DESCRIPTOR sd = (PSECURITY_DESCRIPTOR)LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
+ PSECURITY_DESCRIPTOR sd = (PSECURITY_DESCRIPTOR)LocalAlloc(LPTR,SECURITY_DESCRIPTOR_MIN_LENGTH);
InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(sd, TRUE, acl, FALSE);
@@ -338,23 +356,23 @@
sa.bInheritHandle = FALSE;
// Create an instance of the named pipe
- TAutoHandle hPipe(CreateNamedPipe(pipename_.c_str(), // pipe name
- PIPE_ACCESS_DUPLEX | // read/write access
- FILE_FLAG_OVERLAPPED, // async mode
- PIPE_TYPE_BYTE | // byte type pipe
- PIPE_READMODE_BYTE, // byte read mode
- maxconns_, // max. instances
- bufsize_, // output buffer size
- bufsize_, // input buffer size
- 0, // client time-out
- &sa)); // security attributes
+ TAutoHandle hPipe(CreateNamedPipe(
+ pipename_.c_str(), // pipe name
+ PIPE_ACCESS_DUPLEX | // read/write access
+ FILE_FLAG_OVERLAPPED, // async mode
+ PIPE_TYPE_BYTE | // byte type pipe
+ PIPE_READMODE_BYTE, // byte read mode
+ maxconns_, // max. instances
+ bufsize_, // output buffer size
+ bufsize_, // input buffer size
+ 0, // client time-out
+ &sa)); // security attributes
- if (hPipe.h == INVALID_HANDLE_VALUE) {
+ if(hPipe.h == INVALID_HANDLE_VALUE)
+ {
Pipe_.reset();
GlobalOutput.perror("TPipeServer::TCreateNamedPipe() GLE=", GetLastError());
- throw TTransportException(TTransportException::NOT_OPEN,
- "TCreateNamedPipe() failed",
- GetLastError());
+ throw TTransportException(TTransportException::NOT_OPEN, "TCreateNamedPipe() failed", GetLastError());
return false;
}
@@ -364,21 +382,21 @@
bool TAnonPipeServer::createAnonPipe() {
SECURITY_ATTRIBUTES sa;
- SECURITY_DESCRIPTOR sd; // security information for pipes
+ SECURITY_DESCRIPTOR sd; //security information for pipes
- InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
+ InitializeSecurityDescriptor(&sd,SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(&sd, true, NULL, false);
sa.lpSecurityDescriptor = &sd;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
- sa.bInheritHandle = true; // allow passing handle to child
+ sa.bInheritHandle = true; //allow passing handle to child
HANDLE ClientAnonReadH, PipeW_H, ClientAnonWriteH, Pipe_H;
- if (!CreatePipe(&ClientAnonReadH, &PipeW_H, &sa, 0)) // create stdin pipe
+ if (!CreatePipe(&ClientAnonReadH,&PipeW_H,&sa,0)) //create stdin pipe
{
GlobalOutput.perror("TPipeServer CreatePipe (anon) failed, GLE=", GetLastError());
return false;
}
- if (!CreatePipe(&Pipe_H, &ClientAnonWriteH, &sa, 0)) // create stdout pipe
+ if (!CreatePipe(&Pipe_H,&ClientAnonWriteH,&sa,0)) //create stdout pipe
{
GlobalOutput.perror("TPipeServer CreatePipe (anon) failed, GLE=", GetLastError());
CloseHandle(ClientAnonReadH);
@@ -397,46 +415,29 @@
//---------------------------------------------------------
// Accessors
//---------------------------------------------------------
-string TPipeServer::getPipename() {
- return pipename_;
-}
+string TPipeServer::getPipename() {return pipename_;}
-void TPipeServer::setPipename(const std::string& pipename) {
- if (pipename.find("\\\\") == -1)
+void TPipeServer::setPipename(const std::string &pipename) {
+ if(pipename.find("\\\\") == -1)
pipename_ = "\\\\.\\pipe\\" + pipename;
else
pipename_ = pipename;
}
-int TPipeServer::getBufferSize() {
- return bufsize_;
-}
-void TPipeServer::setBufferSize(int bufsize) {
- bufsize_ = bufsize;
-}
+int TPipeServer::getBufferSize() {return bufsize_;}
+void TPipeServer::setBufferSize(int bufsize) {bufsize_ = bufsize;}
-HANDLE TPipeServer::getPipeHandle() {
- return impl_ ? impl_->getPipeHandle() : INVALID_HANDLE_VALUE;
-}
-HANDLE TPipeServer::getWrtPipeHandle() {
- return impl_ ? impl_->getWrtPipeHandle() : INVALID_HANDLE_VALUE;
-}
-HANDLE TPipeServer::getClientRdPipeHandle() {
- return impl_ ? impl_->getClientRdPipeHandle() : INVALID_HANDLE_VALUE;
-}
-HANDLE TPipeServer::getClientWrtPipeHandle() {
- return impl_ ? impl_->getClientWrtPipeHandle() : INVALID_HANDLE_VALUE;
-}
+HANDLE TPipeServer::getPipeHandle() {return impl_?impl_->getPipeHandle() :INVALID_HANDLE_VALUE;}
+HANDLE TPipeServer::getWrtPipeHandle() {return impl_?impl_->getWrtPipeHandle() :INVALID_HANDLE_VALUE;}
+HANDLE TPipeServer::getClientRdPipeHandle() {return impl_?impl_->getClientRdPipeHandle() :INVALID_HANDLE_VALUE;}
+HANDLE TPipeServer::getClientWrtPipeHandle() {return impl_?impl_->getClientWrtPipeHandle():INVALID_HANDLE_VALUE;}
-bool TPipeServer::getAnonymous() {
- return isAnonymous_;
-}
-void TPipeServer::setAnonymous(bool anon) {
- isAnonymous_ = anon;
-}
+bool TPipeServer::getAnonymous() { return isAnonymous_; }
+void TPipeServer::setAnonymous(bool anon) { isAnonymous_ = anon;}
-void TPipeServer::setMaxConnections(uint32_t maxconnections) {
- if (maxconnections == 0)
+void TPipeServer::setMaxConnections(uint32_t maxconnections)
+{
+ if(maxconnections == 0)
maxconns_ = 1;
else if (maxconnections > PIPE_UNLIMITED_INSTANCES)
maxconns_ = PIPE_UNLIMITED_INSTANCES;
@@ -445,6 +446,5 @@
}
#endif //_WIN32
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
diff --git a/lib/cpp/src/thrift/transport/TPipeServer.h b/lib/cpp/src/thrift/transport/TPipeServer.h
old mode 100644
new mode 100755
index 405793e..98ecde0
--- a/lib/cpp/src/thrift/transport/TPipeServer.h
+++ b/lib/cpp/src/thrift/transport/TPipeServer.h
@@ -23,17 +23,15 @@
#include <thrift/transport/TServerTransport.h>
#include <boost/shared_ptr.hpp>
#ifndef _WIN32
-#include <thrift/transport/TServerSocket.h>
+# include <thrift/transport/TServerSocket.h>
#endif
#ifdef _WIN32
-#include <thrift/windows/Sync.h>
+# include <thrift/windows/Sync.h>
#endif
#define TPIPE_SERVER_MAX_CONNS_DEFAULT PIPE_UNLIMITED_INSTANCES
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
/**
* Windows Pipes implementation of TServerTransport.
@@ -46,30 +44,30 @@
class TPipe;
class TPipeServer : public TServerTransport {
-public:
- // Constructors
+ public:
+ //Constructors
// Named Pipe -
- TPipeServer(const std::string& pipename, uint32_t bufsize);
- TPipeServer(const std::string& pipename, uint32_t bufsize, uint32_t maxconnections);
- TPipeServer(const std::string& pipename);
+ TPipeServer(const std::string &pipename, uint32_t bufsize);
+ TPipeServer(const std::string &pipename, uint32_t bufsize, uint32_t maxconnections);
+ TPipeServer(const std::string &pipename);
// Anonymous pipe -
TPipeServer(int bufsize);
TPipeServer();
- // Destructor
+ //Destructor
virtual ~TPipeServer();
- // Standard transport callbacks
+ //Standard transport callbacks
virtual void interrupt();
virtual void close();
virtual void listen();
- // Accessors
+ //Accessors
std::string getPipename();
- void setPipename(const std::string& pipename);
- int getBufferSize();
+ void setPipename(const std::string &pipename);
+ int getBufferSize();
void setBufferSize(int bufsize);
- HANDLE getPipeHandle(); // Named Pipe R/W -or- Anonymous pipe Read handle
+ HANDLE getPipeHandle(); //Named Pipe R/W -or- Anonymous pipe Read handle
HANDLE getWrtPipeHandle();
HANDLE getClientRdPipeHandle();
HANDLE getClientWrtPipeHandle();
@@ -77,14 +75,13 @@
void setAnonymous(bool anon);
void setMaxConnections(uint32_t maxconnections);
- // this function is intended to be used in generic / template situations,
- // so its name needs to be the same as TPipe's
+ //this function is intended to be used in generic / template situations,
+ //so its name needs to be the same as TPipe's
HANDLE getNativeWaitHandle();
-
protected:
virtual boost::shared_ptr<TTransport> acceptImpl();
-private:
+ private:
boost::shared_ptr<TPipeServerImpl> impl_;
std::string pipename_;
@@ -96,8 +93,7 @@
//*NIX named pipe implementation uses domain socket
typedef TServerSocket TPipeServer;
#endif
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
#endif // #ifndef _THRIFT_TRANSPORT_TSERVERWINPIPES_H_
diff --git a/lib/cpp/src/thrift/transport/TSSLServerSocket.cpp b/lib/cpp/src/thrift/transport/TSSLServerSocket.cpp
index cf686e0..45301f8 100644
--- a/lib/cpp/src/thrift/transport/TSSLServerSocket.cpp
+++ b/lib/cpp/src/thrift/transport/TSSLServerSocket.cpp
@@ -20,29 +20,26 @@
#include <thrift/transport/TSSLServerSocket.h>
#include <thrift/transport/TSSLSocket.h>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
/**
* SSL server socket implementation.
*/
-TSSLServerSocket::TSSLServerSocket(THRIFT_SOCKET port, boost::shared_ptr<TSSLSocketFactory> factory)
- : TServerSocket(port), factory_(factory) {
+TSSLServerSocket::TSSLServerSocket(THRIFT_SOCKET port,
+ boost::shared_ptr<TSSLSocketFactory> factory):
+ TServerSocket(port), factory_(factory) {
factory_->server(true);
}
-TSSLServerSocket::TSSLServerSocket(int port,
- int sendTimeout,
- int recvTimeout,
- boost::shared_ptr<TSSLSocketFactory> factory)
- : TServerSocket(port, sendTimeout, recvTimeout), factory_(factory) {
+TSSLServerSocket::TSSLServerSocket(int port, int sendTimeout, int recvTimeout,
+ boost::shared_ptr<TSSLSocketFactory> factory):
+ TServerSocket(port, sendTimeout, recvTimeout),
+ factory_(factory) {
factory_->server(true);
}
boost::shared_ptr<TSocket> TSSLServerSocket::createSocket(THRIFT_SOCKET client) {
return factory_->createSocket(client);
}
-}
-}
-}
+
+}}}
diff --git a/lib/cpp/src/thrift/transport/TSSLServerSocket.h b/lib/cpp/src/thrift/transport/TSSLServerSocket.h
index bb52b04..3a4b44d 100644
--- a/lib/cpp/src/thrift/transport/TSSLServerSocket.h
+++ b/lib/cpp/src/thrift/transport/TSSLServerSocket.h
@@ -23,17 +23,15 @@
#include <boost/shared_ptr.hpp>
#include <thrift/transport/TServerSocket.h>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
class TSSLSocketFactory;
/**
* Server socket that accepts SSL connections.
*/
-class TSSLServerSocket : public TServerSocket {
-public:
+class TSSLServerSocket: public TServerSocket {
+ public:
/**
* Constructor.
*
@@ -49,17 +47,13 @@
* @param recvTimeout Socket receive timeout
* @param factory SSL socket factory implementation
*/
- TSSLServerSocket(int port,
- int sendTimeout,
- int recvTimeout,
+ TSSLServerSocket(int port, int sendTimeout, int recvTimeout,
boost::shared_ptr<TSSLSocketFactory> factory);
-
-protected:
+ protected:
boost::shared_ptr<TSocket> createSocket(THRIFT_SOCKET socket);
boost::shared_ptr<TSSLSocketFactory> factory_;
};
-}
-}
-}
+
+}}}
#endif
diff --git a/lib/cpp/src/thrift/transport/TSSLSocket.cpp b/lib/cpp/src/thrift/transport/TSSLSocket.cpp
index de5876c..fd285db 100644
--- a/lib/cpp/src/thrift/transport/TSSLSocket.cpp
+++ b/lib/cpp/src/thrift/transport/TSSLSocket.cpp
@@ -47,9 +47,7 @@
Mutex mutex;
};
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
// OpenSSL initialization/cleanup
@@ -66,7 +64,7 @@
#if (OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_NO_THREAD_ID)
static unsigned long callbackThreadID() {
- return (unsigned long)pthread_self();
+ return (unsigned long) pthread_self();
}
#endif
@@ -74,7 +72,9 @@
return new CRYPTO_dynlock_value;
}
-static void dyn_lock(int mode, struct CRYPTO_dynlock_value* lock, const char*, int) {
+static void dyn_lock(int mode,
+ struct CRYPTO_dynlock_value* lock,
+ const char*, int) {
if (lock != NULL) {
if (mode & CRYPTO_LOCK) {
lock->mutex.lock();
@@ -96,11 +96,11 @@
SSL_library_init();
SSL_load_error_strings();
// static locking
- mutexes = boost::shared_array<Mutex>(new Mutex[ ::CRYPTO_num_locks()]);
+ mutexes = boost::shared_array<Mutex>(new Mutex[::CRYPTO_num_locks()]);
if (mutexes == NULL) {
throw TTransportException(TTransportException::INTERNAL_ERROR,
- "initializeOpenSSL() failed, "
- "out of memory while creating mutex array");
+ "initializeOpenSSL() failed, "
+ "out of memory while creating mutex array");
}
#if (OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_NO_THREAD_ID)
CRYPTO_set_id_callback(callbackThreadID);
@@ -137,17 +137,28 @@
// SSLContext implementation
SSLContext::SSLContext(const SSLProtocol& protocol) {
- if (protocol == SSLTLS) {
+ if(protocol == SSLTLS)
+ {
ctx_ = SSL_CTX_new(SSLv23_method());
- } else if (protocol == SSLv3) {
+ }
+ else if(protocol == SSLv3)
+ {
ctx_ = SSL_CTX_new(SSLv3_method());
- } else if (protocol == TLSv1_0) {
+ }
+ else if(protocol == TLSv1_0)
+ {
ctx_ = SSL_CTX_new(TLSv1_method());
- } else if (protocol == TLSv1_1) {
+ }
+ else if(protocol == TLSv1_1)
+ {
ctx_ = SSL_CTX_new(TLSv1_1_method());
- } else if (protocol == TLSv1_2) {
+ }
+ else if(protocol == TLSv1_2)
+ {
ctx_ = SSL_CTX_new(TLSv1_2_method());
- } else {
+ }
+ else
+ {
/// UNKNOWN PROTOCOL!
throw TSSLException("SSL_CTX_new: Unknown protocol");
}
@@ -160,7 +171,8 @@
SSL_CTX_set_mode(ctx_, SSL_MODE_AUTO_RETRY);
// Disable horribly insecure SSLv2!
- if (protocol == SSLTLS) {
+ if(protocol == SSLTLS)
+ {
SSL_CTX_set_options(ctx_, SSL_OP_NO_SSLv2);
}
}
@@ -183,16 +195,16 @@
}
// TSSLSocket implementation
-TSSLSocket::TSSLSocket(boost::shared_ptr<SSLContext> ctx)
- : TSocket(), server_(false), ssl_(NULL), ctx_(ctx) {
+TSSLSocket::TSSLSocket(boost::shared_ptr<SSLContext> ctx):
+ TSocket(), server_(false), ssl_(NULL), ctx_(ctx) {
}
-TSSLSocket::TSSLSocket(boost::shared_ptr<SSLContext> ctx, THRIFT_SOCKET socket)
- : TSocket(socket), server_(false), ssl_(NULL), ctx_(ctx) {
+TSSLSocket::TSSLSocket(boost::shared_ptr<SSLContext> ctx, THRIFT_SOCKET socket):
+ TSocket(socket), server_(false), ssl_(NULL), ctx_(ctx) {
}
-TSSLSocket::TSSLSocket(boost::shared_ptr<SSLContext> ctx, string host, int port)
- : TSocket(host, port), server_(false), ssl_(NULL), ctx_(ctx) {
+TSSLSocket::TSSLSocket(boost::shared_ptr<SSLContext> ctx, string host, int port):
+ TSocket(host, port), server_(false), ssl_(NULL), ctx_(ctx) {
}
TSSLSocket::~TSSLSocket() {
@@ -206,7 +218,7 @@
int shutdown = SSL_get_shutdown(ssl_);
// "!!" is squelching C4800 "forcing bool -> true or false" perfomance warning
bool shutdownReceived = !!(shutdown & SSL_RECEIVED_SHUTDOWN);
- bool shutdownSent = !!(shutdown & SSL_SENT_SHUTDOWN);
+ bool shutdownSent = !!(shutdown & SSL_SENT_SHUTDOWN);
if (shutdownReceived && shutdownSent) {
return false;
}
@@ -262,7 +274,7 @@
uint32_t TSSLSocket::read(uint8_t* buf, uint32_t len) {
checkHandshake();
int32_t bytes = 0;
- for (int32_t retries = 0; retries < maxRecvRetries_; retries++) {
+ for (int32_t retries = 0; retries < maxRecvRetries_; retries++){
bytes = SSL_read(ssl_, buf, len);
if (bytes >= 0)
break;
@@ -340,8 +352,9 @@
void TSSLSocket::authorize() {
int rc = SSL_get_verify_result(ssl_);
- if (rc != X509_V_OK) { // verify authentication result
- throw TSSLException(string("SSL_get_verify_result(), ") + X509_verify_cert_error_string(rc));
+ if (rc != X509_V_OK) { // verify authentication result
+ throw TSSLException(string("SSL_get_verify_result(), ") +
+ X509_verify_cert_error_string(rc));
}
X509* cert = SSL_get_peer_certificate(ssl_);
@@ -382,8 +395,8 @@
}
// extract subjectAlternativeName
- STACK_OF(GENERAL_NAME)* alternatives
- = (STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
+ STACK_OF(GENERAL_NAME)* alternatives = (STACK_OF(GENERAL_NAME)*)
+ X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
if (alternatives != NULL) {
const int count = sk_GENERAL_NAME_num(alternatives);
for (int i = 0; decision == AccessManager::SKIP && i < count; i++) {
@@ -394,15 +407,15 @@
char* data = (char*)ASN1_STRING_data(name->d.ia5);
int length = ASN1_STRING_length(name->d.ia5);
switch (name->type) {
- case GEN_DNS:
- if (host.empty()) {
- host = (server() ? getPeerHost() : getHost());
- }
- decision = access_->verify(host, data, length);
- break;
- case GEN_IPADD:
- decision = access_->verify(sa, data, length);
- break;
+ case GEN_DNS:
+ if (host.empty()) {
+ host = (server() ? getPeerHost() : getHost());
+ }
+ decision = access_->verify(host, data, length);
+ break;
+ case GEN_IPADD:
+ decision = access_->verify(sa, data, length);
+ break;
}
}
sk_GENERAL_NAME_pop_free(alternatives, GENERAL_NAME_free);
@@ -446,10 +459,10 @@
// TSSLSocketFactory implementation
uint64_t TSSLSocketFactory::count_ = 0;
-Mutex TSSLSocketFactory::mutex_;
-bool TSSLSocketFactory::manualOpenSSLInitialization_ = false;
+Mutex TSSLSocketFactory::mutex_;
+bool TSSLSocketFactory::manualOpenSSLInitialization_ = false;
-TSSLSocketFactory::TSSLSocketFactory(const SSLProtocol& protocol) : server_(false) {
+TSSLSocketFactory::TSSLSocketFactory(const SSLProtocol& protocol): server_(false) {
Guard guard(mutex_);
if (count_ == 0) {
if (!manualOpenSSLInitialization_) {
@@ -482,7 +495,8 @@
return ssl;
}
-boost::shared_ptr<TSSLSocket> TSSLSocketFactory::createSocket(const string& host, int port) {
+boost::shared_ptr<TSSLSocket> TSSLSocketFactory::createSocket(const string& host,
+ int port) {
boost::shared_ptr<TSSLSocket> ssl(new TSSLSocket(ctx_, host, port));
setup(ssl);
return ssl;
@@ -513,7 +527,7 @@
void TSSLSocketFactory::authenticate(bool required) {
int mode;
if (required) {
- mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE;
+ mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE;
} else {
mode = SSL_VERIFY_NONE;
}
@@ -523,7 +537,7 @@
void TSSLSocketFactory::loadCertificate(const char* path, const char* format) {
if (path == NULL || format == NULL) {
throw TTransportException(TTransportException::BAD_ARGS,
- "loadCertificateChain: either <path> or <format> is NULL");
+ "loadCertificateChain: either <path> or <format> is NULL");
}
if (strcmp(format, "PEM") == 0) {
if (SSL_CTX_use_certificate_chain_file(ctx_->get(), path) == 0) {
@@ -540,7 +554,7 @@
void TSSLSocketFactory::loadPrivateKey(const char* path, const char* format) {
if (path == NULL || format == NULL) {
throw TTransportException(TTransportException::BAD_ARGS,
- "loadPrivateKey: either <path> or <format> is NULL");
+ "loadPrivateKey: either <path> or <format> is NULL");
}
if (strcmp(format, "PEM") == 0) {
if (SSL_CTX_use_PrivateKey_file(ctx_->get(), path, SSL_FILETYPE_PEM) == 0) {
@@ -555,7 +569,7 @@
void TSSLSocketFactory::loadTrustedCertificates(const char* path) {
if (path == NULL) {
throw TTransportException(TTransportException::BAD_ARGS,
- "loadTrustedCertificates: <path> is NULL");
+ "loadTrustedCertificates: <path> is NULL");
}
if (SSL_CTX_load_verify_locations(ctx_->get(), path, NULL) == 0) {
int errno_copy = THRIFT_GET_SOCKET_ERROR;
@@ -574,7 +588,10 @@
SSL_CTX_set_default_passwd_cb_userdata(ctx_->get(), this);
}
-int TSSLSocketFactory::passwordCallback(char* password, int size, int, void* data) {
+int TSSLSocketFactory::passwordCallback(char* password,
+ int size,
+ int,
+ void* data) {
TSSLSocketFactory* factory = (TSSLSocketFactory*)data;
string userPassword;
factory->getPassword(userPassword, size);
@@ -588,8 +605,8 @@
// extract error messages from error queue
void buildErrors(string& errors, int errno_copy) {
- unsigned long errorCode;
- char message[256];
+ unsigned long errorCode;
+ char message[256];
errors.reserve(512);
while ((errorCode = ERR_get_error()) != 0) {
@@ -616,8 +633,9 @@
/**
* Default implementation of AccessManager
*/
-Decision DefaultClientAccessManager::verify(const sockaddr_storage& sa) throw() {
- (void)sa;
+Decision DefaultClientAccessManager::verify(const sockaddr_storage& sa)
+ throw() {
+ (void) sa;
return SKIP;
}
@@ -673,16 +691,16 @@
match = true;
}
return match;
+
}
// This is to work around the Turkish locale issue, i.e.,
// toupper('i') != toupper('I') if locale is "tr_TR"
-char uppercase(char c) {
+char uppercase (char c) {
if ('a' <= c && c <= 'z') {
return c + ('A' - 'a');
}
return c;
}
-}
-}
-}
+
+}}}
diff --git a/lib/cpp/src/thrift/transport/TSSLSocket.h b/lib/cpp/src/thrift/transport/TSSLSocket.h
index 8d4277a..a4b805b 100644
--- a/lib/cpp/src/thrift/transport/TSSLSocket.h
+++ b/lib/cpp/src/thrift/transport/TSSLSocket.h
@@ -26,22 +26,21 @@
#include <thrift/concurrency/Mutex.h>
#include <thrift/transport/TSocket.h>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
class AccessManager;
class SSLContext;
enum SSLProtocol {
- SSLTLS = 0, // Supports SSLv3 and TLSv1.
- // SSLv2 = 1, // HORRIBLY INSECURE!
- SSLv3 = 2, // Supports SSLv3 only.
- TLSv1_0 = 3, // Supports TLSv1_0 only.
- TLSv1_1 = 4, // Supports TLSv1_1 only.
- TLSv1_2 = 5 // Supports TLSv1_2 only.
+ SSLTLS = 0, // Supports SSLv3 and TLSv1.
+ //SSLv2 = 1, // HORRIBLY INSECURE!
+ SSLv3 = 2, // Supports SSLv3 only.
+ TLSv1_0 = 3, // Supports TLSv1_0 only.
+ TLSv1_1 = 4, // Supports TLSv1_1 only.
+ TLSv1_2 = 5 // Supports TLSv1_2 only.
};
+
/**
* Initialize OpenSSL library. This function, or some other
* equivalent function to initialize OpenSSL, must be called before
@@ -62,24 +61,24 @@
/**
* OpenSSL implementation for SSL socket interface.
*/
-class TSSLSocket : public TSocket {
-public:
- ~TSSLSocket();
+class TSSLSocket: public TSocket {
+ public:
+ ~TSSLSocket();
/**
* TTransport interface.
*/
- bool isOpen();
- bool peek();
- void open();
- void close();
+ bool isOpen();
+ bool peek();
+ void open();
+ void close();
uint32_t read(uint8_t* buf, uint32_t len);
- void write(const uint8_t* buf, uint32_t len);
- void flush();
- /**
- * Set whether to use client or server side SSL handshake protocol.
- *
- * @param flag Use server side handshake protocol if true.
- */
+ void write(const uint8_t* buf, uint32_t len);
+ void flush();
+ /**
+ * Set whether to use client or server side SSL handshake protocol.
+ *
+ * @param flag Use server side handshake protocol if true.
+ */
void server(bool flag) { server_ = flag; }
/**
* Determine whether the SSL socket is server or client mode.
@@ -90,8 +89,9 @@
*
* @param manager Instance of AccessManager
*/
- virtual void access(boost::shared_ptr<AccessManager> manager) { access_ = manager; }
-
+ virtual void access(boost::shared_ptr<AccessManager> manager) {
+ access_ = manager;
+ }
protected:
/**
* Constructor.
@@ -109,7 +109,9 @@
* @param host Remote host name
* @param port Remote port number
*/
- TSSLSocket(boost::shared_ptr<SSLContext> ctx, std::string host, int port);
+ TSSLSocket(boost::shared_ptr<SSLContext> ctx,
+ std::string host,
+ int port);
/**
* Authorize peer access after SSL handshake completes.
*/
@@ -130,7 +132,7 @@
* SSL socket factory. SSL sockets should be created via SSL factory.
*/
class TSSLSocketFactory {
-public:
+ public:
/**
* Constructor/Destructor
*
@@ -148,13 +150,14 @@
* @param socket An existing socket.
*/
virtual boost::shared_ptr<TSSLSocket> createSocket(THRIFT_SOCKET socket);
- /**
- * Create an instance of TSSLSocket.
- *
- * @param host Remote host to be connected to
- * @param port Remote port to be connected to
- */
- virtual boost::shared_ptr<TSSLSocket> createSocket(const std::string& host, int port);
+ /**
+ * Create an instance of TSSLSocket.
+ *
+ * @param host Remote host to be connected to
+ * @param port Remote port to be connected to
+ */
+ virtual boost::shared_ptr<TSSLSocket> createSocket(const std::string& host,
+ int port);
/**
* Set ciphers to be used in SSL handshake process.
*
@@ -212,12 +215,13 @@
*
* @param manager The AccessManager instance
*/
- virtual void access(boost::shared_ptr<AccessManager> manager) { access_ = manager; }
+ virtual void access(boost::shared_ptr<AccessManager> manager) {
+ access_ = manager;
+ }
static void setManualOpenSSLInitialization(bool manualOpenSSLInitialization) {
manualOpenSSLInitialization_ = manualOpenSSLInitialization;
}
-
-protected:
+ protected:
boost::shared_ptr<SSLContext> ctx_;
/**
@@ -228,8 +232,7 @@
* @param size Maximum length of password including NULL character
*/
virtual void getPassword(std::string& /* password */, int /* size */) {}
-
-private:
+ private:
bool server_;
boost::shared_ptr<AccessManager> access_;
static concurrency::Mutex mutex_;
@@ -242,10 +245,10 @@
/**
* SSL exception.
*/
-class TSSLException : public TTransportException {
-public:
- TSSLException(const std::string& message)
- : TTransportException(TTransportException::INTERNAL_ERROR, message) {}
+class TSSLException: public TTransportException {
+ public:
+ TSSLException(const std::string& message):
+ TTransportException(TTransportException::INTERNAL_ERROR, message) {}
virtual const char* what() const throw() {
if (message_.empty()) {
@@ -260,13 +263,12 @@
* Wrap OpenSSL SSL_CTX into a class.
*/
class SSLContext {
-public:
+ public:
SSLContext(const SSLProtocol& protocol = SSLTLS);
virtual ~SSLContext();
SSL* createSSL();
SSL_CTX* get() { return ctx_; }
-
-private:
+ private:
SSL_CTX* ctx_;
};
@@ -277,73 +279,67 @@
* object.
*/
class AccessManager {
-public:
+ public:
enum Decision {
- DENY = -1, // deny access
- SKIP = 0, // cannot make decision, move on to next (if any)
- ALLOW = 1 // allow access
+ DENY = -1, // deny access
+ SKIP = 0, // cannot make decision, move on to next (if any)
+ ALLOW = 1 // allow access
};
- /**
- * Destructor
- */
- virtual ~AccessManager() {}
- /**
- * Determine whether the peer should be granted access or not. It's called
- * once after the SSL handshake completes successfully, before peer certificate
- * is examined.
- *
- * If a valid decision (ALLOW or DENY) is returned, the peer certificate is
- * not to be verified.
- *
- * @param sa Peer IP address
- * @return True if the peer is trusted, false otherwise
- */
- virtual Decision verify(const sockaddr_storage& /* sa */) throw() { return DENY; }
- /**
- * Determine whether the peer should be granted access or not. It's called
- * every time a DNS subjectAltName/common name is extracted from peer's
- * certificate.
- *
- * @param host Client mode: host name returned by TSocket::getHost()
- * Server mode: host name returned by TSocket::getPeerHost()
- * @param name SubjectAltName or common name extracted from peer certificate
- * @param size Length of name
- * @return True if the peer is trusted, false otherwise
- *
- * Note: The "name" parameter may be UTF8 encoded.
- */
- virtual Decision verify(const std::string& /* host */,
- const char* /* name */,
- int /* size */) throw() {
- return DENY;
- }
- /**
- * Determine whether the peer should be granted access or not. It's called
- * every time an IP subjectAltName is extracted from peer's certificate.
- *
- * @param sa Peer IP address retrieved from the underlying socket
- * @param data IP address extracted from certificate
- * @param size Length of the IP address
- * @return True if the peer is trusted, false otherwise
- */
- virtual Decision verify(const sockaddr_storage& /* sa */,
- const char* /* data */,
- int /* size */) throw() {
- return DENY;
- }
+ /**
+ * Destructor
+ */
+ virtual ~AccessManager() {}
+ /**
+ * Determine whether the peer should be granted access or not. It's called
+ * once after the SSL handshake completes successfully, before peer certificate
+ * is examined.
+ *
+ * If a valid decision (ALLOW or DENY) is returned, the peer certificate is
+ * not to be verified.
+ *
+ * @param sa Peer IP address
+ * @return True if the peer is trusted, false otherwise
+ */
+ virtual Decision verify(const sockaddr_storage& /* sa */ ) throw() { return DENY; }
+ /**
+ * Determine whether the peer should be granted access or not. It's called
+ * every time a DNS subjectAltName/common name is extracted from peer's
+ * certificate.
+ *
+ * @param host Client mode: host name returned by TSocket::getHost()
+ * Server mode: host name returned by TSocket::getPeerHost()
+ * @param name SubjectAltName or common name extracted from peer certificate
+ * @param size Length of name
+ * @return True if the peer is trusted, false otherwise
+ *
+ * Note: The "name" parameter may be UTF8 encoded.
+ */
+ virtual Decision verify(const std::string& /* host */, const char* /* name */, int /* size */)
+ throw() { return DENY; }
+ /**
+ * Determine whether the peer should be granted access or not. It's called
+ * every time an IP subjectAltName is extracted from peer's certificate.
+ *
+ * @param sa Peer IP address retrieved from the underlying socket
+ * @param data IP address extracted from certificate
+ * @param size Length of the IP address
+ * @return True if the peer is trusted, false otherwise
+ */
+ virtual Decision verify(const sockaddr_storage& /* sa */, const char* /* data */, int /* size */)
+ throw() { return DENY; }
};
typedef AccessManager::Decision Decision;
-class DefaultClientAccessManager : public AccessManager {
-public:
+class DefaultClientAccessManager: public AccessManager {
+ public:
// AccessManager interface
Decision verify(const sockaddr_storage& sa) throw();
Decision verify(const std::string& host, const char* name, int size) throw();
Decision verify(const sockaddr_storage& sa, const char* data, int size) throw();
};
-}
-}
-}
+
+
+}}}
#endif
diff --git a/lib/cpp/src/thrift/transport/TServerSocket.cpp b/lib/cpp/src/thrift/transport/TServerSocket.cpp
old mode 100644
new mode 100755
index e228dab..0ce1bce
--- a/lib/cpp/src/thrift/transport/TServerSocket.cpp
+++ b/lib/cpp/src/thrift/transport/TServerSocket.cpp
@@ -52,78 +52,76 @@
#endif
#ifndef SOCKOPT_CAST_T
-#ifndef _WIN32
-#define SOCKOPT_CAST_T void
-#else
-#define SOCKOPT_CAST_T char
-#endif // _WIN32
+# ifndef _WIN32
+# define SOCKOPT_CAST_T void
+# else
+# define SOCKOPT_CAST_T char
+# endif // _WIN32
#endif
-template <class T>
+template<class T>
inline const SOCKOPT_CAST_T* const_cast_sockopt(const T* v) {
- return reinterpret_cast<const SOCKOPT_CAST_T*>(v);
+ return reinterpret_cast<const SOCKOPT_CAST_T*>(v);
}
-template <class T>
+template<class T>
inline SOCKOPT_CAST_T* cast_sockopt(T* v) {
- return reinterpret_cast<SOCKOPT_CAST_T*>(v);
+ return reinterpret_cast<SOCKOPT_CAST_T*>(v);
}
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
using namespace std;
using boost::shared_ptr;
-TServerSocket::TServerSocket(int port)
- : port_(port),
- serverSocket_(THRIFT_INVALID_SOCKET),
- acceptBacklog_(DEFAULT_BACKLOG),
- sendTimeout_(0),
- recvTimeout_(0),
- accTimeout_(-1),
- retryLimit_(0),
- retryDelay_(0),
- tcpSendBuffer_(0),
- tcpRecvBuffer_(0),
- keepAlive_(false),
- intSock1_(THRIFT_INVALID_SOCKET),
- intSock2_(THRIFT_INVALID_SOCKET) {
-}
+TServerSocket::TServerSocket(int port) :
+ port_(port),
+ serverSocket_(THRIFT_INVALID_SOCKET),
+ acceptBacklog_(DEFAULT_BACKLOG),
+ sendTimeout_(0),
+ recvTimeout_(0),
+ accTimeout_(-1),
+ retryLimit_(0),
+ retryDelay_(0),
+ tcpSendBuffer_(0),
+ tcpRecvBuffer_(0),
+ keepAlive_(false),
+ intSock1_(THRIFT_INVALID_SOCKET),
+ intSock2_(THRIFT_INVALID_SOCKET)
+{}
-TServerSocket::TServerSocket(int port, int sendTimeout, int recvTimeout)
- : port_(port),
- serverSocket_(THRIFT_INVALID_SOCKET),
- acceptBacklog_(DEFAULT_BACKLOG),
- sendTimeout_(sendTimeout),
- recvTimeout_(recvTimeout),
- accTimeout_(-1),
- retryLimit_(0),
- retryDelay_(0),
- tcpSendBuffer_(0),
- tcpRecvBuffer_(0),
- keepAlive_(false),
- intSock1_(THRIFT_INVALID_SOCKET),
- intSock2_(THRIFT_INVALID_SOCKET) {
-}
+TServerSocket::TServerSocket(int port, int sendTimeout, int recvTimeout) :
+ port_(port),
+ serverSocket_(THRIFT_INVALID_SOCKET),
+ acceptBacklog_(DEFAULT_BACKLOG),
+ sendTimeout_(sendTimeout),
+ recvTimeout_(recvTimeout),
+ accTimeout_(-1),
+ retryLimit_(0),
+ retryDelay_(0),
+ tcpSendBuffer_(0),
+ tcpRecvBuffer_(0),
+ keepAlive_(false),
+ intSock1_(THRIFT_INVALID_SOCKET),
+ intSock2_(THRIFT_INVALID_SOCKET)
+{}
-TServerSocket::TServerSocket(string path)
- : port_(0),
- path_(path),
- serverSocket_(THRIFT_INVALID_SOCKET),
- acceptBacklog_(DEFAULT_BACKLOG),
- sendTimeout_(0),
- recvTimeout_(0),
- accTimeout_(-1),
- retryLimit_(0),
- retryDelay_(0),
- tcpSendBuffer_(0),
- tcpRecvBuffer_(0),
- keepAlive_(false),
- intSock1_(THRIFT_INVALID_SOCKET),
- intSock2_(THRIFT_INVALID_SOCKET) {
-}
+TServerSocket::TServerSocket(string path) :
+ port_(0),
+ path_(path),
+ serverSocket_(THRIFT_INVALID_SOCKET),
+ acceptBacklog_(DEFAULT_BACKLOG),
+ sendTimeout_(0),
+ recvTimeout_(0),
+ accTimeout_(-1),
+ retryLimit_(0),
+ retryDelay_(0),
+ tcpSendBuffer_(0),
+ tcpRecvBuffer_(0),
+ keepAlive_(false),
+ intSock1_(THRIFT_INVALID_SOCKET),
+ intSock2_(THRIFT_INVALID_SOCKET)
+{}
TServerSocket::~TServerSocket() {
close();
@@ -163,7 +161,7 @@
void TServerSocket::listen() {
#ifdef _WIN32
- TWinsockSingleton::create();
+ TWinsockSingleton::create();
#endif // _WIN32
THRIFT_SOCKET sv[2];
if (-1 == THRIFT_SOCKETPAIR(AF_LOCAL, SOCK_STREAM, 0, sv)) {
@@ -189,8 +187,7 @@
if (error) {
GlobalOutput.printf("getaddrinfo %d: %s", error, THRIFT_GAI_STRERROR(error));
close();
- throw TTransportException(TTransportException::NOT_OPEN,
- "Could not resolve host for server socket.");
+ throw TTransportException(TTransportException::NOT_OPEN, "Could not resolve host for server socket.");
}
// Pick the ipv6 address first since ipv4 addresses can be mapped
@@ -200,7 +197,7 @@
break;
}
- if (!path_.empty()) {
+ if (! path_.empty()) {
serverSocket_ = socket(PF_UNIX, SOCK_STREAM, IPPROTO_IP);
} else {
serverSocket_ = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
@@ -210,93 +207,72 @@
int errno_copy = THRIFT_GET_SOCKET_ERROR;
GlobalOutput.perror("TServerSocket::listen() socket() ", errno_copy);
close();
- throw TTransportException(TTransportException::NOT_OPEN,
- "Could not create server socket.",
- errno_copy);
+ throw TTransportException(TTransportException::NOT_OPEN, "Could not create server socket.", errno_copy);
}
// Set THRIFT_NO_SOCKET_CACHING to prevent 2MSL delay on accept
int one = 1;
- if (-1 == setsockopt(serverSocket_,
- SOL_SOCKET,
- THRIFT_NO_SOCKET_CACHING,
- cast_sockopt(&one),
- sizeof(one))) {
-// ignore errors coming out of this setsockopt on Windows. This is because
-// SO_EXCLUSIVEADDRUSE requires admin privileges on WinXP, but we don't
-// want to force servers to be an admin.
+ if (-1 == setsockopt(serverSocket_, SOL_SOCKET, THRIFT_NO_SOCKET_CACHING,
+ cast_sockopt(&one), sizeof(one))) {
+ //ignore errors coming out of this setsockopt on Windows. This is because
+ //SO_EXCLUSIVEADDRUSE requires admin privileges on WinXP, but we don't
+ //want to force servers to be an admin.
#ifndef _WIN32
int errno_copy = THRIFT_GET_SOCKET_ERROR;
- GlobalOutput.perror("TServerSocket::listen() setsockopt() THRIFT_NO_SOCKET_CACHING ",
- errno_copy);
+ GlobalOutput.perror("TServerSocket::listen() setsockopt() THRIFT_NO_SOCKET_CACHING ", errno_copy);
close();
- throw TTransportException(TTransportException::NOT_OPEN,
- "Could not set THRIFT_NO_SOCKET_CACHING",
- errno_copy);
+ throw TTransportException(TTransportException::NOT_OPEN, "Could not set THRIFT_NO_SOCKET_CACHING", errno_copy);
#endif
}
// Set TCP buffer sizes
if (tcpSendBuffer_ > 0) {
- if (-1 == setsockopt(serverSocket_,
- SOL_SOCKET,
- SO_SNDBUF,
- cast_sockopt(&tcpSendBuffer_),
- sizeof(tcpSendBuffer_))) {
+ if (-1 == setsockopt(serverSocket_, SOL_SOCKET, SO_SNDBUF,
+ cast_sockopt(&tcpSendBuffer_), sizeof(tcpSendBuffer_))) {
int errno_copy = THRIFT_GET_SOCKET_ERROR;
GlobalOutput.perror("TServerSocket::listen() setsockopt() SO_SNDBUF ", errno_copy);
close();
- throw TTransportException(TTransportException::NOT_OPEN,
- "Could not set SO_SNDBUF",
- errno_copy);
+ throw TTransportException(TTransportException::NOT_OPEN, "Could not set SO_SNDBUF", errno_copy);
}
}
if (tcpRecvBuffer_ > 0) {
- if (-1 == setsockopt(serverSocket_,
- SOL_SOCKET,
- SO_RCVBUF,
- cast_sockopt(&tcpRecvBuffer_),
- sizeof(tcpRecvBuffer_))) {
+ if (-1 == setsockopt(serverSocket_, SOL_SOCKET, SO_RCVBUF,
+ cast_sockopt(&tcpRecvBuffer_), sizeof(tcpRecvBuffer_))) {
int errno_copy = THRIFT_GET_SOCKET_ERROR;
GlobalOutput.perror("TServerSocket::listen() setsockopt() SO_RCVBUF ", errno_copy);
close();
- throw TTransportException(TTransportException::NOT_OPEN,
- "Could not set SO_RCVBUF",
- errno_copy);
+ throw TTransportException(TTransportException::NOT_OPEN, "Could not set SO_RCVBUF", errno_copy);
}
}
-// Defer accept
-#ifdef TCP_DEFER_ACCEPT
+ // Defer accept
+ #ifdef TCP_DEFER_ACCEPT
if (path_.empty()) {
- if (-1 == setsockopt(serverSocket_, IPPROTO_TCP, TCP_DEFER_ACCEPT, &one, sizeof(one))) {
+ if (-1 == setsockopt(serverSocket_, IPPROTO_TCP, TCP_DEFER_ACCEPT,
+ &one, sizeof(one))) {
int errno_copy = THRIFT_GET_SOCKET_ERROR;
GlobalOutput.perror("TServerSocket::listen() setsockopt() TCP_DEFER_ACCEPT ", errno_copy);
close();
- throw TTransportException(TTransportException::NOT_OPEN,
- "Could not set TCP_DEFER_ACCEPT",
- errno_copy);
+ throw TTransportException(TTransportException::NOT_OPEN, "Could not set TCP_DEFER_ACCEPT", errno_copy);
}
}
-#endif // #ifdef TCP_DEFER_ACCEPT
+ #endif // #ifdef TCP_DEFER_ACCEPT
-#ifdef IPV6_V6ONLY
+ #ifdef IPV6_V6ONLY
if (res->ai_family == AF_INET6 && path_.empty()) {
int zero = 0;
- if (-1 == setsockopt(serverSocket_,
- IPPROTO_IPV6,
- IPV6_V6ONLY,
- cast_sockopt(&zero),
- sizeof(zero))) {
+ if (-1 == setsockopt(serverSocket_, IPPROTO_IPV6, IPV6_V6ONLY,
+ cast_sockopt(&zero), sizeof(zero))) {
GlobalOutput.perror("TServerSocket::listen() IPV6_V6ONLY ", THRIFT_GET_SOCKET_ERROR);
}
}
-#endif // #ifdef IPV6_V6ONLY
+ #endif // #ifdef IPV6_V6ONLY
// Turn linger off, don't want to block on calls to close
struct linger ling = {0, 0};
- if (-1 == setsockopt(serverSocket_, SOL_SOCKET, SO_LINGER, cast_sockopt(&ling), sizeof(ling))) {
+ if (-1 == setsockopt(serverSocket_, SOL_SOCKET, SO_LINGER,
+ cast_sockopt(&ling), sizeof(ling))) {
int errno_copy = THRIFT_GET_SOCKET_ERROR;
GlobalOutput.perror("TServerSocket::listen() setsockopt() SO_LINGER ", errno_copy);
close();
@@ -306,14 +282,12 @@
// Unix Sockets do not need that
if (path_.empty()) {
// TCP Nodelay, speed over bandwidth
- if (-1
- == setsockopt(serverSocket_, IPPROTO_TCP, TCP_NODELAY, cast_sockopt(&one), sizeof(one))) {
+ if (-1 == setsockopt(serverSocket_, IPPROTO_TCP, TCP_NODELAY,
+ cast_sockopt(&one), sizeof(one))) {
int errno_copy = THRIFT_GET_SOCKET_ERROR;
GlobalOutput.perror("TServerSocket::listen() setsockopt() TCP_NODELAY ", errno_copy);
close();
- throw TTransportException(TTransportException::NOT_OPEN,
- "Could not set TCP_NODELAY",
- errno_copy);
+ throw TTransportException(TTransportException::NOT_OPEN, "Could not set TCP_NODELAY", errno_copy);
}
}
@@ -336,7 +310,7 @@
// always seem to work. The client can configure the retry variables.
int retries = 0;
- if (!path_.empty()) {
+ if (! path_.empty()) {
#ifndef _WIN32
@@ -354,15 +328,14 @@
socklen_t structlen = static_cast<socklen_t>(sizeof(address));
do {
- if (0 == ::bind(serverSocket_, (struct sockaddr*)&address, structlen)) {
+ if (0 == ::bind(serverSocket_, (struct sockaddr *) &address, structlen)) {
break;
}
// use short circuit evaluation here to only sleep if we need to
} while ((retries++ < retryLimit_) && (THRIFT_SLEEP_SEC(retryDelay_) == 0));
#else
GlobalOutput.perror("TSocket::open() Unix Domain socket path not supported on windows", -99);
- throw TTransportException(TTransportException::NOT_OPEN,
- " Unix Domain socket path not supported");
+ throw TTransportException(TTransportException::NOT_OPEN, " Unix Domain socket path not supported");
#endif
} else {
do {
@@ -383,12 +356,16 @@
if (::getsockname(serverSocket_, &sa, &len) < 0) {
int errno_copy = errno;
GlobalOutput.perror("TServerSocket::getPort() getsockname() ", errno_copy);
- } else {
+ }
+ else {
if (sa.sa_family == AF_INET6) {
- const struct sockaddr_in6* sin = reinterpret_cast<const struct sockaddr_in6*>(&sa);
+ const struct sockaddr_in6*
+ sin = reinterpret_cast<const struct sockaddr_in6 *>(&sa);
port_ = ntohs(sin->sin6_port);
- } else {
- const struct sockaddr_in* sin = reinterpret_cast<const struct sockaddr_in*>(&sa);
+ }
+ else {
+ const struct sockaddr_in*
+ sin = reinterpret_cast<const struct sockaddr_in *>(&sa);
port_ = ntohs(sin->sin_port);
}
}
@@ -398,20 +375,19 @@
// throw an error if we failed to bind properly
if (retries > retryLimit_) {
char errbuf[1024];
- if (!path_.empty()) {
+ if (! path_.empty()) {
sprintf(errbuf, "TServerSocket::listen() PATH %s", path_.c_str());
- } else {
+ }
+ else {
sprintf(errbuf, "TServerSocket::listen() BIND %d", port_);
}
GlobalOutput(errbuf);
close();
- throw TTransportException(TTransportException::NOT_OPEN,
- "Could not bind",
+ throw TTransportException(TTransportException::NOT_OPEN, "Could not bind",
THRIFT_GET_SOCKET_ERROR);
}
- if (listenCallback_)
- listenCallback_(serverSocket_);
+ if(listenCallback_) listenCallback_(serverSocket_);
// Call listen
if (-1 == ::listen(serverSocket_, acceptBacklog_)) {
@@ -425,7 +401,7 @@
}
int TServerSocket::getPort() {
- return port_;
+ return port_;
}
shared_ptr<TTransport> TServerSocket::acceptImpl() {
@@ -439,7 +415,7 @@
int numEintrs = 0;
while (true) {
- std::memset(fds, 0, sizeof(fds));
+ std::memset(fds, 0 , sizeof(fds));
fds[0].fd = serverSocket_;
fds[0].events = THRIFT_POLLIN;
if (intSock2_ != THRIFT_INVALID_SOCKET) {
@@ -464,11 +440,11 @@
throw TTransportException(TTransportException::UNKNOWN, "Unknown", errno_copy);
} else if (ret > 0) {
// Check for an interrupt signal
- if (intSock2_ != THRIFT_INVALID_SOCKET && (fds[1].revents & THRIFT_POLLIN)) {
+ if (intSock2_ != THRIFT_INVALID_SOCKET
+ && (fds[1].revents & THRIFT_POLLIN)) {
int8_t buf;
if (-1 == recv(intSock2_, cast_sockopt(&buf), sizeof(int8_t), 0)) {
- GlobalOutput.perror("TServerSocket::acceptImpl() recv() interrupt ",
- THRIFT_GET_SOCKET_ERROR);
+ GlobalOutput.perror("TServerSocket::acceptImpl() recv() interrupt ", THRIFT_GET_SOCKET_ERROR);
}
throw TTransportException(TTransportException::INTERRUPTED);
}
@@ -485,8 +461,9 @@
struct sockaddr_storage clientAddress;
int size = sizeof(clientAddress);
- THRIFT_SOCKET clientSocket
- = ::accept(serverSocket_, (struct sockaddr*)&clientAddress, (socklen_t*)&size);
+ THRIFT_SOCKET clientSocket = ::accept(serverSocket_,
+ (struct sockaddr *) &clientAddress,
+ (socklen_t *) &size);
if (clientSocket == -1) {
int errno_copy = THRIFT_GET_SOCKET_ERROR;
@@ -499,19 +476,13 @@
if (flags == -1) {
int errno_copy = THRIFT_GET_SOCKET_ERROR;
GlobalOutput.perror("TServerSocket::acceptImpl() THRIFT_FCNTL() THRIFT_F_GETFL ", errno_copy);
- throw TTransportException(TTransportException::UNKNOWN,
- "THRIFT_FCNTL(THRIFT_F_GETFL)",
- errno_copy);
+ throw TTransportException(TTransportException::UNKNOWN, "THRIFT_FCNTL(THRIFT_F_GETFL)", errno_copy);
}
if (-1 == THRIFT_FCNTL(clientSocket, THRIFT_F_SETFL, flags & ~THRIFT_O_NONBLOCK)) {
int errno_copy = THRIFT_GET_SOCKET_ERROR;
- GlobalOutput
- .perror("TServerSocket::acceptImpl() THRIFT_FCNTL() THRIFT_F_SETFL ~THRIFT_O_NONBLOCK ",
- errno_copy);
- throw TTransportException(TTransportException::UNKNOWN,
- "THRIFT_FCNTL(THRIFT_F_SETFL)",
- errno_copy);
+ GlobalOutput.perror("TServerSocket::acceptImpl() THRIFT_FCNTL() THRIFT_F_SETFL ~THRIFT_O_NONBLOCK ", errno_copy);
+ throw TTransportException(TTransportException::UNKNOWN, "THRIFT_FCNTL(THRIFT_F_SETFL)", errno_copy);
}
shared_ptr<TSocket> client = createSocket(clientSocket);
@@ -524,10 +495,9 @@
if (keepAlive_) {
client->setKeepAlive(keepAlive_);
}
- client->setCachedAddress((sockaddr*)&clientAddress, size);
+ client->setCachedAddress((sockaddr*) &clientAddress, size);
- if (acceptCallback_)
- acceptCallback_(clientSocket);
+ if(acceptCallback_) acceptCallback_(clientSocket);
return client;
}
@@ -551,7 +521,7 @@
::THRIFT_CLOSESOCKET(serverSocket_);
}
if (intSock1_ != THRIFT_INVALID_SOCKET) {
- ::THRIFT_CLOSESOCKET(intSock1_);
+ ::THRIFT_CLOSESOCKET(intSock1_);
}
if (intSock2_ != THRIFT_INVALID_SOCKET) {
::THRIFT_CLOSESOCKET(intSock2_);
@@ -560,6 +530,5 @@
intSock1_ = THRIFT_INVALID_SOCKET;
intSock2_ = THRIFT_INVALID_SOCKET;
}
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
diff --git a/lib/cpp/src/thrift/transport/TServerSocket.h b/lib/cpp/src/thrift/transport/TServerSocket.h
index 1533937..56ec2b5 100644
--- a/lib/cpp/src/thrift/transport/TServerSocket.h
+++ b/lib/cpp/src/thrift/transport/TServerSocket.h
@@ -25,9 +25,7 @@
#include <thrift/cxxfunctional.h>
#include <boost/shared_ptr.hpp>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
class TSocket;
@@ -37,7 +35,7 @@
*
*/
class TServerSocket : public TServerTransport {
-public:
+ public:
typedef apache::thrift::stdcxx::function<void(THRIFT_SOCKET fd)> socket_func_t;
const static int DEFAULT_BACKLOG = 1024;
@@ -57,7 +55,7 @@
void setRetryLimit(int retryLimit);
void setRetryDelay(int retryDelay);
- void setKeepAlive(bool keepAlive) { keepAlive_ = keepAlive; }
+ void setKeepAlive(bool keepAlive) {keepAlive_ = keepAlive;}
void setTcpSendBuffer(int tcpSendBuffer);
void setTcpRecvBuffer(int tcpRecvBuffer);
@@ -65,13 +63,13 @@
// listenCallback gets called just before listen, and after all Thrift
// setsockopt calls have been made. If you have custom setsockopt
// things that need to happen on the listening socket, this is the place to do it.
- void setListenCallback(const socket_func_t& listenCallback) { listenCallback_ = listenCallback; }
+ void setListenCallback(const socket_func_t &listenCallback) { listenCallback_ = listenCallback; }
// acceptCallback gets called after each accept call, on the newly created socket.
// It is called after all Thrift setsockopt calls have been made. If you have
// custom setsockopt things that need to happen on the accepted
// socket, this is the place to do it.
- void setAcceptCallback(const socket_func_t& acceptCallback) { acceptCallback_ = acceptCallback; }
+ void setAcceptCallback(const socket_func_t &acceptCallback) { acceptCallback_ = acceptCallback; }
void listen();
void close();
@@ -79,11 +77,11 @@
void interrupt();
int getPort();
-protected:
+ protected:
boost::shared_ptr<TTransport> acceptImpl();
virtual boost::shared_ptr<TSocket> createSocket(THRIFT_SOCKET client);
-private:
+ private:
int port_;
std::string path_;
THRIFT_SOCKET serverSocket_;
@@ -103,8 +101,7 @@
socket_func_t listenCallback_;
socket_func_t acceptCallback_;
};
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
#endif // #ifndef _THRIFT_TRANSPORT_TSERVERSOCKET_H_
diff --git a/lib/cpp/src/thrift/transport/TServerTransport.h b/lib/cpp/src/thrift/transport/TServerTransport.h
index 7c4a7c3..2ddee0d 100644
--- a/lib/cpp/src/thrift/transport/TServerTransport.h
+++ b/lib/cpp/src/thrift/transport/TServerTransport.h
@@ -24,9 +24,7 @@
#include <thrift/transport/TTransportException.h>
#include <boost/shared_ptr.hpp>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
/**
* Server transport framework. A server needs to have some facility for
@@ -34,7 +32,7 @@
*
*/
class TServerTransport {
-public:
+ public:
virtual ~TServerTransport() {}
/**
@@ -76,7 +74,7 @@
*/
virtual void close() = 0;
-protected:
+ protected:
TServerTransport() {}
/**
@@ -86,9 +84,9 @@
* @throw TTransportException If an error occurs
*/
virtual boost::shared_ptr<TTransport> acceptImpl() = 0;
+
};
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
#endif // #ifndef _THRIFT_TRANSPORT_TSERVERTRANSPORT_H_
diff --git a/lib/cpp/src/thrift/transport/TShortReadTransport.h b/lib/cpp/src/thrift/transport/TShortReadTransport.h
index f2ecae1..8def354 100644
--- a/lib/cpp/src/thrift/transport/TShortReadTransport.h
+++ b/lib/cpp/src/thrift/transport/TShortReadTransport.h
@@ -25,10 +25,7 @@
#include <thrift/transport/TTransport.h>
#include <thrift/transport/TVirtualTransport.h>
-namespace apache {
-namespace thrift {
-namespace transport {
-namespace test {
+namespace apache { namespace thrift { namespace transport { namespace test {
/**
* This class is only meant for testing. It wraps another transport.
@@ -37,46 +34,64 @@
*
*/
class TShortReadTransport : public TVirtualTransport<TShortReadTransport> {
-public:
+ public:
TShortReadTransport(boost::shared_ptr<TTransport> transport, double full_prob)
- : transport_(transport), fullProb_(full_prob) {}
+ : transport_(transport)
+ , fullProb_(full_prob)
+ {}
- bool isOpen() { return transport_->isOpen(); }
+ bool isOpen() {
+ return transport_->isOpen();
+ }
- bool peek() { return transport_->peek(); }
+ bool peek() {
+ return transport_->peek();
+ }
- void open() { transport_->open(); }
+ void open() {
+ transport_->open();
+ }
- void close() { transport_->close(); }
+ void close() {
+ transport_->close();
+ }
uint32_t read(uint8_t* buf, uint32_t len) {
if (len == 0) {
return 0;
}
- if (rand() / (double)RAND_MAX >= fullProb_) {
- len = 1 + rand() % len;
+ if (rand()/(double)RAND_MAX >= fullProb_) {
+ len = 1 + rand()%len;
}
return transport_->read(buf, len);
}
- void write(const uint8_t* buf, uint32_t len) { transport_->write(buf, len); }
+ void write(const uint8_t* buf, uint32_t len) {
+ transport_->write(buf, len);
+ }
- void flush() { transport_->flush(); }
+ void flush() {
+ transport_->flush();
+ }
- const uint8_t* borrow(uint8_t* buf, uint32_t* len) { return transport_->borrow(buf, len); }
+ const uint8_t* borrow(uint8_t* buf, uint32_t* len) {
+ return transport_->borrow(buf, len);
+ }
- void consume(uint32_t len) { return transport_->consume(len); }
+ void consume(uint32_t len) {
+ return transport_->consume(len);
+ }
- boost::shared_ptr<TTransport> getUnderlyingTransport() { return transport_; }
+ boost::shared_ptr<TTransport> getUnderlyingTransport() {
+ return transport_;
+ }
-protected:
+ protected:
boost::shared_ptr<TTransport> transport_;
double fullProb_;
};
-}
-}
-}
-} // apache::thrift::transport::test
+
+}}}} // apache::thrift::transport::test
#endif // #ifndef _THRIFT_TRANSPORT_TSHORTREADTRANSPORT_H_
diff --git a/lib/cpp/src/thrift/transport/TSimpleFileTransport.cpp b/lib/cpp/src/thrift/transport/TSimpleFileTransport.cpp
index 4b1399e..6bd716e 100644
--- a/lib/cpp/src/thrift/transport/TSimpleFileTransport.cpp
+++ b/lib/cpp/src/thrift/transport/TSimpleFileTransport.cpp
@@ -31,12 +31,11 @@
#include <io.h>
#endif
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
-TSimpleFileTransport::TSimpleFileTransport(const std::string& path, bool read, bool write)
- : TFDTransport(-1, TFDTransport::CLOSE_ON_DESTROY) {
+TSimpleFileTransport::
+TSimpleFileTransport(const std::string& path, bool read, bool write)
+ : TFDTransport(-1, TFDTransport::CLOSE_ON_DESTROY) {
int flags = 0;
if (read && write) {
flags = O_RDWR;
@@ -51,17 +50,18 @@
flags |= O_CREAT | O_APPEND;
}
#ifndef _WIN32
- mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
+ mode_t mode = S_IRUSR | S_IWUSR| S_IRGRP | S_IROTH;
#else
int mode = _S_IREAD | _S_IWRITE;
#endif
- int fd = ::THRIFT_OPEN(path.c_str(), flags, mode);
+ int fd = ::THRIFT_OPEN(path.c_str(),
+ flags,
+ mode);
if (fd < 0) {
throw TTransportException("failed to open file for writing: " + path);
}
setFD(fd);
open();
}
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
diff --git a/lib/cpp/src/thrift/transport/TSimpleFileTransport.h b/lib/cpp/src/thrift/transport/TSimpleFileTransport.h
index 32e1897..985a1d3 100644
--- a/lib/cpp/src/thrift/transport/TSimpleFileTransport.h
+++ b/lib/cpp/src/thrift/transport/TSimpleFileTransport.h
@@ -22,9 +22,7 @@
#include <thrift/transport/TFDTransport.h>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
/**
* Dead-simple wrapper around a file.
@@ -32,11 +30,12 @@
* Writeable files are opened with O_CREAT and O_APPEND
*/
class TSimpleFileTransport : public TFDTransport {
-public:
- TSimpleFileTransport(const std::string& path, bool read = true, bool write = false);
+ public:
+ TSimpleFileTransport(const std::string& path,
+ bool read = true,
+ bool write = false);
};
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
#endif // _THRIFT_TRANSPORT_TSIMPLEFILETRANSPORT_H_
diff --git a/lib/cpp/src/thrift/transport/TSocket.cpp b/lib/cpp/src/thrift/transport/TSocket.cpp
index ea85bfb..af7240a 100644
--- a/lib/cpp/src/thrift/transport/TSocket.cpp
+++ b/lib/cpp/src/thrift/transport/TSocket.cpp
@@ -46,26 +46,24 @@
#include <thrift/transport/PlatformSocket.h>
#ifndef SOCKOPT_CAST_T
-#ifndef _WIN32
-#define SOCKOPT_CAST_T void
-#else
-#define SOCKOPT_CAST_T char
-#endif // _WIN32
+# ifndef _WIN32
+# define SOCKOPT_CAST_T void
+# else
+# define SOCKOPT_CAST_T char
+# endif // _WIN32
#endif
-template <class T>
+template<class T>
inline const SOCKOPT_CAST_T* const_cast_sockopt(const T* v) {
- return reinterpret_cast<const SOCKOPT_CAST_T*>(v);
+ return reinterpret_cast<const SOCKOPT_CAST_T*>(v);
}
-template <class T>
+template<class T>
inline SOCKOPT_CAST_T* cast_sockopt(T* v) {
- return reinterpret_cast<SOCKOPT_CAST_T*>(v);
+ return reinterpret_cast<SOCKOPT_CAST_T*>(v);
}
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
using namespace std;
@@ -77,66 +75,66 @@
*
*/
-TSocket::TSocket(string host, int port)
- : host_(host),
- port_(port),
- path_(""),
- socket_(THRIFT_INVALID_SOCKET),
- connTimeout_(0),
- sendTimeout_(0),
- recvTimeout_(0),
- keepAlive_(false),
- lingerOn_(1),
- lingerVal_(0),
- noDelay_(1),
- maxRecvRetries_(5) {
+TSocket::TSocket(string host, int port) :
+ host_(host),
+ port_(port),
+ path_(""),
+ socket_(THRIFT_INVALID_SOCKET),
+ connTimeout_(0),
+ sendTimeout_(0),
+ recvTimeout_(0),
+ keepAlive_(false),
+ lingerOn_(1),
+ lingerVal_(0),
+ noDelay_(1),
+ maxRecvRetries_(5) {
}
-TSocket::TSocket(string path)
- : host_(""),
- port_(0),
- path_(path),
- socket_(THRIFT_INVALID_SOCKET),
- connTimeout_(0),
- sendTimeout_(0),
- recvTimeout_(0),
- keepAlive_(false),
- lingerOn_(1),
- lingerVal_(0),
- noDelay_(1),
- maxRecvRetries_(5) {
+TSocket::TSocket(string path) :
+ host_(""),
+ port_(0),
+ path_(path),
+ socket_(THRIFT_INVALID_SOCKET),
+ connTimeout_(0),
+ sendTimeout_(0),
+ recvTimeout_(0),
+ keepAlive_(false),
+ lingerOn_(1),
+ lingerVal_(0),
+ noDelay_(1),
+ maxRecvRetries_(5) {
cachedPeerAddr_.ipv4.sin_family = AF_UNSPEC;
}
-TSocket::TSocket()
- : host_(""),
- port_(0),
- path_(""),
- socket_(THRIFT_INVALID_SOCKET),
- connTimeout_(0),
- sendTimeout_(0),
- recvTimeout_(0),
- keepAlive_(false),
- lingerOn_(1),
- lingerVal_(0),
- noDelay_(1),
- maxRecvRetries_(5) {
+TSocket::TSocket() :
+ host_(""),
+ port_(0),
+ path_(""),
+ socket_(THRIFT_INVALID_SOCKET),
+ connTimeout_(0),
+ sendTimeout_(0),
+ recvTimeout_(0),
+ keepAlive_(false),
+ lingerOn_(1),
+ lingerVal_(0),
+ noDelay_(1),
+ maxRecvRetries_(5) {
cachedPeerAddr_.ipv4.sin_family = AF_UNSPEC;
}
-TSocket::TSocket(THRIFT_SOCKET socket)
- : host_(""),
- port_(0),
- path_(""),
- socket_(socket),
- connTimeout_(0),
- sendTimeout_(0),
- recvTimeout_(0),
- keepAlive_(false),
- lingerOn_(1),
- lingerVal_(0),
- noDelay_(1),
- maxRecvRetries_(5) {
+TSocket::TSocket(THRIFT_SOCKET socket) :
+ host_(""),
+ port_(0),
+ path_(""),
+ socket_(socket),
+ connTimeout_(0),
+ sendTimeout_(0),
+ recvTimeout_(0),
+ keepAlive_(false),
+ lingerOn_(1),
+ lingerVal_(0),
+ noDelay_(1),
+ maxRecvRetries_(5) {
cachedPeerAddr_.ipv4.sin_family = AF_UNSPEC;
#ifdef SO_NOSIGPIPE
{
@@ -162,29 +160,30 @@
int r = static_cast<int>(recv(socket_, cast_sockopt(&buf), 1, MSG_PEEK));
if (r == -1) {
int errno_copy = THRIFT_GET_SOCKET_ERROR;
-#if defined __FreeBSD__ || defined __MACH__
+ #if defined __FreeBSD__ || defined __MACH__
/* shigin:
* freebsd returns -1 and THRIFT_ECONNRESET if socket was closed by
* the other side
*/
- if (errno_copy == THRIFT_ECONNRESET) {
+ if (errno_copy == THRIFT_ECONNRESET)
+ {
close();
return false;
}
-#endif
+ #endif
GlobalOutput.perror("TSocket::peek() recv() " + getSocketInfo(), errno_copy);
throw TTransportException(TTransportException::UNKNOWN, "recv()", errno_copy);
}
return (r > 0);
}
-void TSocket::openConnection(struct addrinfo* res) {
+void TSocket::openConnection(struct addrinfo *res) {
if (isOpen()) {
return;
}
- if (!path_.empty()) {
+ if (! path_.empty()) {
socket_ = socket(PF_UNIX, SOCK_STREAM, IPPROTO_IP);
} else {
socket_ = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
@@ -206,7 +205,7 @@
setRecvTimeout(recvTimeout_);
}
- if (keepAlive_) {
+ if(keepAlive_) {
setKeepAlive(keepAlive_);
}
@@ -223,7 +222,7 @@
}
#endif
-// Uses a low min RTO if asked to.
+ // Uses a low min RTO if asked to.
#ifdef TCP_LOW_MIN_RTO
if (getUseLowMinRto()) {
int one = 1;
@@ -231,6 +230,7 @@
}
#endif
+
// Set the socket to be non blocking for connect if a timeout exists
int flags = THRIFT_FCNTL(socket_, THRIFT_F_GETFL, 0);
if (connTimeout_ > 0) {
@@ -249,7 +249,7 @@
// Connect the socket
int ret;
- if (!path_.empty()) {
+ if (! path_.empty()) {
#ifndef _WIN32
size_t len = path_.size() + 1;
@@ -263,11 +263,10 @@
address.sun_family = AF_UNIX;
memcpy(address.sun_path, path_.c_str(), len);
socklen_t structlen = static_cast<socklen_t>(sizeof(address));
- ret = connect(socket_, (struct sockaddr*)&address, structlen);
+ ret = connect(socket_, (struct sockaddr *) &address, structlen);
#else
- GlobalOutput.perror("TSocket::open() Unix Domain socket path not supported on windows", -99);
- throw TTransportException(TTransportException::NOT_OPEN,
- " Unix Domain socket path not supported");
+ GlobalOutput.perror("TSocket::open() Unix Domain socket path not supported on windows", -99);
+ throw TTransportException(TTransportException::NOT_OPEN, " Unix Domain socket path not supported");
#endif
} else {
@@ -279,15 +278,15 @@
goto done;
}
- if ((THRIFT_GET_SOCKET_ERROR != THRIFT_EINPROGRESS)
- && (THRIFT_GET_SOCKET_ERROR != THRIFT_EWOULDBLOCK)) {
+ if ((THRIFT_GET_SOCKET_ERROR != THRIFT_EINPROGRESS) && (THRIFT_GET_SOCKET_ERROR != THRIFT_EWOULDBLOCK)) {
int errno_copy = THRIFT_GET_SOCKET_ERROR;
GlobalOutput.perror("TSocket::open() connect() " + getSocketInfo(), errno_copy);
throw TTransportException(TTransportException::NOT_OPEN, "connect() failed", errno_copy);
}
+
struct THRIFT_POLLFD fds[1];
- std::memset(fds, 0, sizeof(fds));
+ std::memset(fds, 0 , sizeof(fds));
fds[0].fd = socket_;
fds[0].events = THRIFT_POLLOUT;
ret = THRIFT_POLL(fds, 1, connTimeout_);
@@ -307,8 +306,7 @@
if (val == 0) {
goto done;
}
- GlobalOutput.perror("TSocket::open() error on socket (after THRIFT_POLL) " + getSocketInfo(),
- val);
+ GlobalOutput.perror("TSocket::open() error on socket (after THRIFT_POLL) " + getSocketInfo(), val);
throw TTransportException(TTransportException::NOT_OPEN, "socket open() error", val);
} else if (ret == 0) {
// socket timed out
@@ -322,7 +320,7 @@
throw TTransportException(TTransportException::NOT_OPEN, "THRIFT_POLL() failed", errno_copy);
}
-done:
+ done:
// Set socket back to normal mode (blocking)
THRIFT_FCNTL(socket_, THRIFT_F_SETFL, flags);
@@ -335,24 +333,24 @@
if (isOpen()) {
return;
}
- if (!path_.empty()) {
+ if (! path_.empty()) {
unix_open();
} else {
local_open();
}
}
-void TSocket::unix_open() {
- if (!path_.empty()) {
+void TSocket::unix_open(){
+ if (! path_.empty()) {
// Unix Domain SOcket does not need addrinfo struct, so we pass NULL
openConnection(NULL);
}
}
-void TSocket::local_open() {
+void TSocket::local_open(){
#ifdef _WIN32
- TWinsockSingleton::create();
+ TWinsockSingleton::create();
#endif // _WIN32
if (isOpen()) {
@@ -385,12 +383,10 @@
#endif
if (error) {
- string errStr = "TSocket::open() getaddrinfo() " + getSocketInfo()
- + string(THRIFT_GAI_STRERROR(error));
+ string errStr = "TSocket::open() getaddrinfo() " + getSocketInfo() + string(THRIFT_GAI_STRERROR(error));
GlobalOutput(errStr.c_str());
close();
- throw TTransportException(TTransportException::NOT_OPEN,
- "Could not resolve host for client socket.");
+ throw TTransportException(TTransportException::NOT_OPEN, "Could not resolve host for client socket.");
}
// Cycle through all the returned addresses until one
@@ -445,10 +441,10 @@
// if a readTimeout is specified along with a max number of recv retries, then
// the threshold will ensure that the read timeout is not exceeded even in the
// case of resource errors
- eagainThresholdMicros = (recvTimeout_ * 1000) / ((maxRecvRetries_ > 0) ? maxRecvRetries_ : 2);
+ eagainThresholdMicros = (recvTimeout_*1000)/ ((maxRecvRetries_>0) ? maxRecvRetries_ : 2);
}
-try_again:
+ try_again:
// Read from the socket
struct timeval begin;
if (recvTimeout_ > 0) {
@@ -459,8 +455,7 @@
begin.tv_sec = begin.tv_usec = 0;
}
int got = static_cast<int>(recv(socket_, cast_sockopt(buf), len, 0));
- int errno_copy = THRIFT_GET_SOCKET_ERROR; // THRIFT_GETTIMEOFDAY can change
- // THRIFT_GET_SOCKET_ERROR
+ int errno_copy = THRIFT_GET_SOCKET_ERROR; //THRIFT_GETTIMEOFDAY can change THRIFT_GET_SOCKET_ERROR
++g_socket_syscalls;
// Check for error on read
@@ -469,14 +464,14 @@
// if no timeout we can assume that resource exhaustion has occurred.
if (recvTimeout_ == 0) {
throw TTransportException(TTransportException::TIMED_OUT,
- "THRIFT_EAGAIN (unavailable resources)");
+ "THRIFT_EAGAIN (unavailable resources)");
}
// check if this is the lack of resources or timeout case
struct timeval end;
THRIFT_GETTIMEOFDAY(&end, NULL);
- uint32_t readElapsedMicros
- = static_cast<uint32_t>(((end.tv_sec - begin.tv_sec) * 1000 * 1000)
- + (((uint64_t)(end.tv_usec - begin.tv_usec))));
+ uint32_t readElapsedMicros = static_cast<uint32_t>(
+ ((end.tv_sec - begin.tv_sec) * 1000 * 1000)
+ + (((uint64_t)(end.tv_usec - begin.tv_usec))));
if (!eagainThresholdMicros || (readElapsedMicros < eagainThresholdMicros)) {
if (retries++ < maxRecvRetries_) {
@@ -488,7 +483,8 @@
}
} else {
// infer that timeout has been hit
- throw TTransportException(TTransportException::TIMED_OUT, "THRIFT_EAGAIN (timed out)");
+ throw TTransportException(TTransportException::TIMED_OUT,
+ "THRIFT_EAGAIN (timed out)");
}
}
@@ -497,7 +493,7 @@
goto try_again;
}
-#if defined __FreeBSD__ || defined __MACH__
+ #if defined __FreeBSD__ || defined __MACH__
if (errno_copy == THRIFT_ECONNRESET) {
/* shigin: freebsd doesn't follow POSIX semantic of recv and fails with
* THRIFT_ECONNRESET if peer performed shutdown
@@ -505,10 +501,10 @@
*/
return 0;
}
-#endif
+ #endif
#ifdef _WIN32
- if (errno_copy == WSAECONNRESET) {
+ if(errno_copy == WSAECONNRESET) {
return 0; // EOF
}
#endif
@@ -554,7 +550,8 @@
if (b == 0) {
// This should only happen if the timeout set with SO_SNDTIMEO expired.
// Raise an exception.
- throw TTransportException(TTransportException::TIMED_OUT, "send timeout expired");
+ throw TTransportException(TTransportException::TIMED_OUT,
+ "send timeout expired");
}
sent += b;
}
@@ -585,8 +582,7 @@
int errno_copy = THRIFT_GET_SOCKET_ERROR;
GlobalOutput.perror("TSocket::write_partial() send() " + getSocketInfo(), errno_copy);
- if (errno_copy == THRIFT_EPIPE || errno_copy == THRIFT_ECONNRESET
- || errno_copy == THRIFT_ENOTCONN) {
+ if (errno_copy == THRIFT_EPIPE || errno_copy == THRIFT_ECONNRESET || errno_copy == THRIFT_ENOTCONN) {
close();
throw TTransportException(TTransportException::NOT_OPEN, "write() send()", errno_copy);
}
@@ -632,8 +628,7 @@
int ret = setsockopt(socket_, SOL_SOCKET, SO_LINGER, cast_sockopt(&l), sizeof(l));
if (ret == -1) {
- int errno_copy
- = THRIFT_GET_SOCKET_ERROR; // Copy THRIFT_GET_SOCKET_ERROR because we're allocating memory.
+ int errno_copy = THRIFT_GET_SOCKET_ERROR; // Copy THRIFT_GET_SOCKET_ERROR because we're allocating memory.
GlobalOutput.perror("TSocket::setLinger() setsockopt() " + getSocketInfo(), errno_copy);
}
}
@@ -648,8 +643,7 @@
int v = noDelay_ ? 1 : 0;
int ret = setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, cast_sockopt(&v), sizeof(v));
if (ret == -1) {
- int errno_copy
- = THRIFT_GET_SOCKET_ERROR; // Copy THRIFT_GET_SOCKET_ERROR because we're allocating memory.
+ int errno_copy = THRIFT_GET_SOCKET_ERROR; // Copy THRIFT_GET_SOCKET_ERROR because we're allocating memory.
GlobalOutput.perror("TSocket::setNoDelay() setsockopt() " + getSocketInfo(), errno_copy);
}
}
@@ -658,7 +652,8 @@
connTimeout_ = ms;
}
-void setGenericTimeout(THRIFT_SOCKET s, int timeout_ms, int optname) {
+void setGenericTimeout(THRIFT_SOCKET s, int timeout_ms, int optname)
+{
if (timeout_ms < 0) {
char errBuf[512];
sprintf(errBuf, "TSocket::setGenericTimeout with negative input: %d\n", timeout_ms);
@@ -670,16 +665,17 @@
return;
}
-#ifdef _WIN32
+ #ifdef _WIN32
DWORD platform_time = static_cast<DWORD>(timeout_ms);
-#else
- struct timeval platform_time = {(int)(timeout_ms / 1000), (int)((timeout_ms % 1000) * 1000)};
-#endif
+ #else
+ struct timeval platform_time = {
+ (int)(timeout_ms/1000),
+ (int)((timeout_ms%1000)*1000)};
+ #endif
int ret = setsockopt(s, SOL_SOCKET, optname, cast_sockopt(&platform_time), sizeof(platform_time));
if (ret == -1) {
- int errno_copy
- = THRIFT_GET_SOCKET_ERROR; // Copy THRIFT_GET_SOCKET_ERROR because we're allocating memory.
+ int errno_copy = THRIFT_GET_SOCKET_ERROR; // Copy THRIFT_GET_SOCKET_ERROR because we're allocating memory.
GlobalOutput.perror("TSocket::setGenericTimeout() setsockopt() ", errno_copy);
}
}
@@ -702,12 +698,10 @@
}
int value = keepAlive_;
- int ret
- = setsockopt(socket_, SOL_SOCKET, SO_KEEPALIVE, const_cast_sockopt(&value), sizeof(value));
+ int ret = setsockopt(socket_, SOL_SOCKET, SO_KEEPALIVE, const_cast_sockopt(&value), sizeof(value));
if (ret == -1) {
- int errno_copy
- = THRIFT_GET_SOCKET_ERROR; // Copy THRIFT_GET_SOCKET_ERROR because we're allocating memory.
+ int errno_copy = THRIFT_GET_SOCKET_ERROR; // Copy THRIFT_GET_SOCKET_ERROR because we're allocating memory.
GlobalOutput.perror("TSocket::setKeepAlive() setsockopt() " + getSocketInfo(), errno_copy);
}
}
@@ -741,7 +735,7 @@
if (addrPtr == NULL) {
addrLen = sizeof(addr);
- if (getpeername(socket_, (sockaddr*)&addr, &addrLen) != 0) {
+ if (getpeername(socket_, (sockaddr*) &addr, &addrLen) != 0) {
return peerHost_;
}
addrPtr = (sockaddr*)&addr;
@@ -752,13 +746,9 @@
char clienthost[NI_MAXHOST];
char clientservice[NI_MAXSERV];
- getnameinfo((sockaddr*)addrPtr,
- addrLen,
- clienthost,
- sizeof(clienthost),
- clientservice,
- sizeof(clientservice),
- 0);
+ getnameinfo((sockaddr*) addrPtr, addrLen,
+ clienthost, sizeof(clienthost),
+ clientservice, sizeof(clientservice), 0);
peerHost_ = clienthost;
}
@@ -779,7 +769,7 @@
if (addrPtr == NULL) {
addrLen = sizeof(addr);
- if (getpeername(socket_, (sockaddr*)&addr, &addrLen) != 0) {
+ if (getpeername(socket_, (sockaddr*) &addr, &addrLen) != 0) {
return peerAddress_;
}
addrPtr = (sockaddr*)&addr;
@@ -790,13 +780,10 @@
char clienthost[NI_MAXHOST];
char clientservice[NI_MAXSERV];
- getnameinfo(addrPtr,
- addrLen,
- clienthost,
- sizeof(clienthost),
- clientservice,
- sizeof(clientservice),
- NI_NUMERICHOST | NI_NUMERICSERV);
+ getnameinfo(addrPtr, addrLen,
+ clienthost, sizeof(clienthost),
+ clientservice, sizeof(clientservice),
+ NI_NUMERICHOST|NI_NUMERICSERV);
peerAddress_ = clienthost;
peerPort_ = std::atoi(clientservice);
@@ -833,11 +820,11 @@
switch (cachedPeerAddr_.ipv4.sin_family) {
case AF_INET:
*len = sizeof(sockaddr_in);
- return (sockaddr*)&cachedPeerAddr_.ipv4;
+ return (sockaddr*) &cachedPeerAddr_.ipv4;
case AF_INET6:
*len = sizeof(sockaddr_in6);
- return (sockaddr*)&cachedPeerAddr_.ipv6;
+ return (sockaddr*) &cachedPeerAddr_.ipv6;
default:
return NULL;
@@ -857,6 +844,5 @@
oss << getPeerHost() << ":" << getPeerPort();
return oss.str();
}
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
diff --git a/lib/cpp/src/thrift/transport/TSocket.h b/lib/cpp/src/thrift/transport/TSocket.h
index 38bd789..c873218 100644
--- a/lib/cpp/src/thrift/transport/TSocket.h
+++ b/lib/cpp/src/thrift/transport/TSocket.h
@@ -37,16 +37,14 @@
#include <netdb.h>
#endif
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
/**
* TCP Socket implementation of the TTransport interface.
*
*/
class TSocket : public TVirtualTransport<TSocket> {
-public:
+ public:
/**
* Constructs a new socket. Note that this does NOT actually connect the
* socket.
@@ -208,7 +206,9 @@
/**
* Returns the underlying socket file descriptor.
*/
- THRIFT_SOCKET getSocketFD() { return socket_; }
+ THRIFT_SOCKET getSocketFD() {
+ return socket_;
+ }
/**
* (Re-)initialize a TSocket for the supplied descriptor. This is only
@@ -252,9 +252,9 @@
*/
void setCachedAddress(const sockaddr* addr, socklen_t len);
-protected:
+ protected:
/** connect, called by open */
- void openConnection(struct addrinfo* res);
+ void openConnection(struct addrinfo *res);
/** Host to connect to */
std::string host_;
@@ -310,12 +310,12 @@
/** Whether to use low minimum TCP retransmission timeout */
static bool useLowMinRto_;
-private:
+ private:
void unix_open();
void local_open();
};
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
#endif // #ifndef _THRIFT_TRANSPORT_TSOCKET_H_
+
diff --git a/lib/cpp/src/thrift/transport/TSocketPool.cpp b/lib/cpp/src/thrift/transport/TSocketPool.cpp
index ccab258..e0b286a 100644
--- a/lib/cpp/src/thrift/transport/TSocketPool.cpp
+++ b/lib/cpp/src/thrift/transport/TSocketPool.cpp
@@ -24,9 +24,7 @@
#include <thrift/transport/TSocketPool.h>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
using namespace std;
@@ -37,41 +35,43 @@
*
*/
TSocketPoolServer::TSocketPoolServer()
- : host_(""), port_(0), socket_(THRIFT_INVALID_SOCKET), lastFailTime_(0), consecutiveFailures_(0) {
-}
+ : host_(""),
+ port_(0),
+ socket_(THRIFT_INVALID_SOCKET),
+ lastFailTime_(0),
+ consecutiveFailures_(0) {}
/**
* Constructor for TSocketPool server
*/
-TSocketPoolServer::TSocketPoolServer(const string& host, int port)
+TSocketPoolServer::TSocketPoolServer(const string &host, int port)
: host_(host),
port_(port),
socket_(THRIFT_INVALID_SOCKET),
lastFailTime_(0),
- consecutiveFailures_(0) {
-}
+ consecutiveFailures_(0) {}
/**
* TSocketPool implementation.
*
*/
-TSocketPool::TSocketPool()
- : TSocket(),
- numRetries_(1),
- retryInterval_(60),
- maxConsecutiveFailures_(1),
- randomize_(true),
- alwaysTryLast_(true) {
+TSocketPool::TSocketPool() : TSocket(),
+ numRetries_(1),
+ retryInterval_(60),
+ maxConsecutiveFailures_(1),
+ randomize_(true),
+ alwaysTryLast_(true) {
}
-TSocketPool::TSocketPool(const vector<string>& hosts, const vector<int>& ports)
- : TSocket(),
- numRetries_(1),
- retryInterval_(60),
- maxConsecutiveFailures_(1),
- randomize_(true),
- alwaysTryLast_(true) {
+TSocketPool::TSocketPool(const vector<string> &hosts,
+ const vector<int> &ports) : TSocket(),
+ numRetries_(1),
+ retryInterval_(60),
+ maxConsecutiveFailures_(1),
+ randomize_(true),
+ alwaysTryLast_(true)
+{
if (hosts.size() != ports.size()) {
GlobalOutput("TSocketPool::TSocketPool: hosts.size != ports.size");
throw TTransportException(TTransportException::BAD_ARGS);
@@ -82,41 +82,41 @@
}
}
-TSocketPool::TSocketPool(const vector<pair<string, int> >& servers)
- : TSocket(),
- numRetries_(1),
- retryInterval_(60),
- maxConsecutiveFailures_(1),
- randomize_(true),
- alwaysTryLast_(true) {
+TSocketPool::TSocketPool(const vector<pair<string, int> >& servers) : TSocket(),
+ numRetries_(1),
+ retryInterval_(60),
+ maxConsecutiveFailures_(1),
+ randomize_(true),
+ alwaysTryLast_(true)
+{
for (unsigned i = 0; i < servers.size(); ++i) {
addServer(servers[i].first, servers[i].second);
}
}
-TSocketPool::TSocketPool(const vector<shared_ptr<TSocketPoolServer> >& servers)
- : TSocket(),
- servers_(servers),
- numRetries_(1),
- retryInterval_(60),
- maxConsecutiveFailures_(1),
- randomize_(true),
- alwaysTryLast_(true) {
+TSocketPool::TSocketPool(const vector< shared_ptr<TSocketPoolServer> >& servers) : TSocket(),
+ servers_(servers),
+ numRetries_(1),
+ retryInterval_(60),
+ maxConsecutiveFailures_(1),
+ randomize_(true),
+ alwaysTryLast_(true)
+{
}
-TSocketPool::TSocketPool(const string& host, int port)
- : TSocket(),
- numRetries_(1),
- retryInterval_(60),
- maxConsecutiveFailures_(1),
- randomize_(true),
- alwaysTryLast_(true) {
+TSocketPool::TSocketPool(const string& host, int port) : TSocket(),
+ numRetries_(1),
+ retryInterval_(60),
+ maxConsecutiveFailures_(1),
+ randomize_(true),
+ alwaysTryLast_(true)
+{
addServer(host, port);
}
TSocketPool::~TSocketPool() {
- vector<shared_ptr<TSocketPoolServer> >::const_iterator iter = servers_.begin();
- vector<shared_ptr<TSocketPoolServer> >::const_iterator iterEnd = servers_.end();
+ vector< shared_ptr<TSocketPoolServer> >::const_iterator iter = servers_.begin();
+ vector< shared_ptr<TSocketPoolServer> >::const_iterator iterEnd = servers_.end();
for (; iter != iterEnd; ++iter) {
setCurrentServer(*iter);
TSocketPool::close();
@@ -127,17 +127,17 @@
servers_.push_back(shared_ptr<TSocketPoolServer>(new TSocketPoolServer(host, port)));
}
-void TSocketPool::addServer(shared_ptr<TSocketPoolServer>& server) {
+void TSocketPool::addServer(shared_ptr<TSocketPoolServer> &server) {
if (server) {
servers_.push_back(server);
}
}
-void TSocketPool::setServers(const vector<shared_ptr<TSocketPoolServer> >& servers) {
+void TSocketPool::setServers(const vector< shared_ptr<TSocketPoolServer> >& servers) {
servers_ = servers;
}
-void TSocketPool::getServers(vector<shared_ptr<TSocketPoolServer> >& servers) {
+void TSocketPool::getServers(vector< shared_ptr<TSocketPoolServer> >& servers) {
servers = servers_;
}
@@ -149,6 +149,7 @@
retryInterval_ = retryInterval;
}
+
void TSocketPool::setMaxConsecutiveFailures(int maxConsecutiveFailures) {
maxConsecutiveFailures_ = maxConsecutiveFailures;
}
@@ -161,7 +162,7 @@
alwaysTryLast_ = alwaysTryLast;
}
-void TSocketPool::setCurrentServer(const shared_ptr<TSocketPoolServer>& server) {
+void TSocketPool::setCurrentServer(const shared_ptr<TSocketPoolServer> &server) {
currentServer_ = server;
host_ = server->host_;
port_ = server->port_;
@@ -191,7 +192,7 @@
for (size_t i = 0; i < numServers; ++i) {
- shared_ptr<TSocketPoolServer>& server = servers_[i];
+ shared_ptr<TSocketPoolServer> &server = servers_[i];
// Impersonate the server socket
setCurrentServer(server);
@@ -216,7 +217,7 @@
try {
TSocket::open();
} catch (TException e) {
- string errStr = "TSocketPool::open failed " + getSocketInfo() + ": " + e.what();
+ string errStr = "TSocketPool::open failed "+getSocketInfo()+": "+e.what();
GlobalOutput(errStr.c_str());
socket_ = THRIFT_INVALID_SOCKET;
continue;
@@ -249,6 +250,5 @@
currentServer_->socket_ = THRIFT_INVALID_SOCKET;
}
}
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
diff --git a/lib/cpp/src/thrift/transport/TSocketPool.h b/lib/cpp/src/thrift/transport/TSocketPool.h
index 78f0ebf..7728257 100644
--- a/lib/cpp/src/thrift/transport/TSocketPool.h
+++ b/lib/cpp/src/thrift/transport/TSocketPool.h
@@ -23,17 +23,15 @@
#include <vector>
#include <thrift/transport/TSocket.h>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
-/**
- * Class to hold server information for TSocketPool
- *
- */
+ /**
+ * Class to hold server information for TSocketPool
+ *
+ */
class TSocketPoolServer {
-public:
+ public:
/**
* Default constructor for server info
*/
@@ -42,7 +40,7 @@
/**
* Constructor for TSocketPool server
*/
- TSocketPoolServer(const std::string& host, int port);
+ TSocketPoolServer(const std::string &host, int port);
// Host name
std::string host_;
@@ -66,130 +64,133 @@
*/
class TSocketPool : public TSocket {
-public:
- /**
- * Socket pool constructor
- */
- TSocketPool();
+ public:
- /**
- * Socket pool constructor
- *
- * @param hosts list of host names
- * @param ports list of port names
- */
- TSocketPool(const std::vector<std::string>& hosts, const std::vector<int>& ports);
+ /**
+ * Socket pool constructor
+ */
+ TSocketPool();
- /**
- * Socket pool constructor
- *
- * @param servers list of pairs of host name and port
- */
- TSocketPool(const std::vector<std::pair<std::string, int> >& servers);
+ /**
+ * Socket pool constructor
+ *
+ * @param hosts list of host names
+ * @param ports list of port names
+ */
+ TSocketPool(const std::vector<std::string> &hosts,
+ const std::vector<int> &ports);
- /**
- * Socket pool constructor
- *
- * @param servers list of TSocketPoolServers
- */
- TSocketPool(const std::vector<boost::shared_ptr<TSocketPoolServer> >& servers);
+ /**
+ * Socket pool constructor
+ *
+ * @param servers list of pairs of host name and port
+ */
+ TSocketPool(const std::vector<std::pair<std::string, int> >& servers);
- /**
- * Socket pool constructor
- *
- * @param host single host
- * @param port single port
- */
- TSocketPool(const std::string& host, int port);
+ /**
+ * Socket pool constructor
+ *
+ * @param servers list of TSocketPoolServers
+ */
+ TSocketPool(const std::vector< boost::shared_ptr<TSocketPoolServer> >& servers);
- /**
- * Destroyes the socket object, closing it if necessary.
- */
- virtual ~TSocketPool();
+ /**
+ * Socket pool constructor
+ *
+ * @param host single host
+ * @param port single port
+ */
+ TSocketPool(const std::string& host, int port);
- /**
- * Add a server to the pool
- */
- void addServer(const std::string& host, int port);
+ /**
+ * Destroyes the socket object, closing it if necessary.
+ */
+ virtual ~TSocketPool();
- /**
- * Add a server to the pool
- */
- void addServer(boost::shared_ptr<TSocketPoolServer>& server);
+ /**
+ * Add a server to the pool
+ */
+ void addServer(const std::string& host, int port);
- /**
- * Set list of servers in this pool
- */
- void setServers(const std::vector<boost::shared_ptr<TSocketPoolServer> >& servers);
+ /**
+ * Add a server to the pool
+ */
+ void addServer(boost::shared_ptr<TSocketPoolServer> &server);
- /**
- * Get list of servers in this pool
- */
- void getServers(std::vector<boost::shared_ptr<TSocketPoolServer> >& servers);
+ /**
+ * Set list of servers in this pool
+ */
+ void setServers(const std::vector< boost::shared_ptr<TSocketPoolServer> >& servers);
- /**
- * Sets how many times to keep retrying a host in the connect function.
- */
- void setNumRetries(int numRetries);
+ /**
+ * Get list of servers in this pool
+ */
+ void getServers(std::vector< boost::shared_ptr<TSocketPoolServer> >& servers);
- /**
- * Sets how long to wait until retrying a host if it was marked down
- */
- void setRetryInterval(int retryInterval);
+ /**
+ * Sets how many times to keep retrying a host in the connect function.
+ */
+ void setNumRetries(int numRetries);
- /**
- * Sets how many times to keep retrying a host before marking it as down.
- */
- void setMaxConsecutiveFailures(int maxConsecutiveFailures);
+ /**
+ * Sets how long to wait until retrying a host if it was marked down
+ */
+ void setRetryInterval(int retryInterval);
- /**
- * Turns randomization in connect order on or off.
- */
- void setRandomize(bool randomize);
+ /**
+ * Sets how many times to keep retrying a host before marking it as down.
+ */
+ void setMaxConsecutiveFailures(int maxConsecutiveFailures);
- /**
- * Whether to always try the last server.
- */
- void setAlwaysTryLast(bool alwaysTryLast);
+ /**
+ * Turns randomization in connect order on or off.
+ */
+ void setRandomize(bool randomize);
- /**
- * Creates and opens the UNIX socket.
- */
- void open();
+ /**
+ * Whether to always try the last server.
+ */
+ void setAlwaysTryLast(bool alwaysTryLast);
- /*
- * Closes the UNIX socket
- */
- void close();
+ /**
+ * Creates and opens the UNIX socket.
+ */
+ void open();
-protected:
- void setCurrentServer(const boost::shared_ptr<TSocketPoolServer>& server);
+ /*
+ * Closes the UNIX socket
+ */
+ void close();
- /** List of servers to connect to */
- std::vector<boost::shared_ptr<TSocketPoolServer> > servers_;
+ protected:
+
+ void setCurrentServer(const boost::shared_ptr<TSocketPoolServer> &server);
+
+ /** List of servers to connect to */
+ std::vector< boost::shared_ptr<TSocketPoolServer> > servers_;
/** Current server */
boost::shared_ptr<TSocketPoolServer> currentServer_;
- /** How many times to retry each host in connect */
- int numRetries_;
+ /** How many times to retry each host in connect */
+ int numRetries_;
- /** Retry interval in seconds, how long to not try a host if it has been
- * marked as down.
- */
- time_t retryInterval_;
+ /** Retry interval in seconds, how long to not try a host if it has been
+ * marked as down.
+ */
+ time_t retryInterval_;
- /** Max consecutive failures before marking a host down. */
- int maxConsecutiveFailures_;
+ /** Max consecutive failures before marking a host down. */
+ int maxConsecutiveFailures_;
- /** Try hosts in order? or Randomized? */
- bool randomize_;
+ /** Try hosts in order? or Randomized? */
+ bool randomize_;
- /** Always try last host, even if marked down? */
- bool alwaysTryLast_;
+ /** Always try last host, even if marked down? */
+ bool alwaysTryLast_;
};
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
#endif // #ifndef _THRIFT_TRANSPORT_TSOCKETPOOL_H_
+
diff --git a/lib/cpp/src/thrift/transport/TTransport.h b/lib/cpp/src/thrift/transport/TTransport.h
index d06b0f8..6e9a698 100644
--- a/lib/cpp/src/thrift/transport/TTransport.h
+++ b/lib/cpp/src/thrift/transport/TTransport.h
@@ -25,22 +25,21 @@
#include <thrift/transport/TTransportException.h>
#include <string>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
/**
* Helper template to hoist readAll implementation out of TTransport
*/
template <class Transport_>
-uint32_t readAll(Transport_& trans, uint8_t* buf, uint32_t len) {
+uint32_t readAll(Transport_ &trans, uint8_t* buf, uint32_t len) {
uint32_t have = 0;
uint32_t get = 0;
while (have < len) {
- get = trans.read(buf + have, len - have);
+ get = trans.read(buf+have, len-have);
if (get <= 0) {
- throw TTransportException(TTransportException::END_OF_FILE, "No more data to read.");
+ throw TTransportException(TTransportException::END_OF_FILE,
+ "No more data to read.");
}
have += get;
}
@@ -48,13 +47,14 @@
return have;
}
+
/**
* Generic interface for a method of transporting data. A TTransport may be
* capable of either reading or writing, but not necessarily both.
*
*/
class TTransport {
-public:
+ public:
/**
* Virtual deconstructor.
*/
@@ -63,7 +63,9 @@
/**
* Whether this transport is open.
*/
- virtual bool isOpen() { return false; }
+ virtual bool isOpen() {
+ return false;
+ }
/**
* Tests whether there is more data to read or if the remote side is
@@ -73,7 +75,9 @@
* This is used by a server to check if it should listen for another
* request.
*/
- virtual bool peek() { return isOpen(); }
+ virtual bool peek() {
+ return isOpen();
+ }
/**
* Opens the transport for communications.
@@ -105,7 +109,8 @@
return read_virt(buf, len);
}
virtual uint32_t read_virt(uint8_t* /* buf */, uint32_t /* len */) {
- throw TTransportException(TTransportException::NOT_OPEN, "Base TTransport cannot read.");
+ throw TTransportException(TTransportException::NOT_OPEN,
+ "Base TTransport cannot read.");
}
/**
@@ -153,7 +158,8 @@
write_virt(buf, len);
}
virtual void write_virt(const uint8_t* /* buf */, uint32_t /* len */) {
- throw TTransportException(TTransportException::NOT_OPEN, "Base TTransport cannot write.");
+ throw TTransportException(TTransportException::NOT_OPEN,
+ "Base TTransport cannot write.");
}
/**
@@ -209,7 +215,9 @@
T_VIRTUAL_CALL();
return borrow_virt(buf, len);
}
- virtual const uint8_t* borrow_virt(uint8_t* /* buf */, uint32_t* /* len */) { return NULL; }
+ virtual const uint8_t* borrow_virt(uint8_t* /* buf */, uint32_t* /* len */) {
+ return NULL;
+ }
/**
* Remove len bytes from the transport. This should always follow a borrow
@@ -225,7 +233,8 @@
consume_virt(len);
}
virtual void consume_virt(uint32_t /* len */) {
- throw TTransportException(TTransportException::NOT_OPEN, "Base TTransport cannot consume.");
+ throw TTransportException(TTransportException::NOT_OPEN,
+ "Base TTransport cannot consume.");
}
/**
@@ -236,9 +245,11 @@
*
* The returned value can be used in a log message for example
*/
- virtual const std::string getOrigin() { return "Unknown"; }
+ virtual const std::string getOrigin() {
+ return "Unknown";
+ }
-protected:
+ protected:
/**
* Simple constructor.
*/
@@ -252,7 +263,7 @@
*
*/
class TTransportFactory {
-public:
+ public:
TTransportFactory() {}
virtual ~TTransportFactory() {}
@@ -263,9 +274,9 @@
virtual boost::shared_ptr<TTransport> getTransport(boost::shared_ptr<TTransport> trans) {
return trans;
}
+
};
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
#endif // #ifndef _THRIFT_TRANSPORT_TTRANSPORT_H_
diff --git a/lib/cpp/src/thrift/transport/TTransportException.cpp b/lib/cpp/src/thrift/transport/TTransportException.cpp
index 612e7b7..2b1430c 100644
--- a/lib/cpp/src/thrift/transport/TTransportException.cpp
+++ b/lib/cpp/src/thrift/transport/TTransportException.cpp
@@ -26,36 +26,25 @@
using std::string;
using boost::lexical_cast;
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
-const char* TTransportException::what() const throw() {
- if (message_.empty()) {
- switch (type_) {
- case UNKNOWN:
- return "TTransportException: Unknown transport exception";
- case NOT_OPEN:
- return "TTransportException: Transport not open";
- case TIMED_OUT:
- return "TTransportException: Timed out";
- case END_OF_FILE:
- return "TTransportException: End of file";
- case INTERRUPTED:
- return "TTransportException: Interrupted";
- case BAD_ARGS:
- return "TTransportException: Invalid arguments";
- case CORRUPTED_DATA:
- return "TTransportException: Corrupted Data";
- case INTERNAL_ERROR:
- return "TTransportException: Internal error";
- default:
- return "TTransportException: (Invalid exception type)";
+ const char* TTransportException::what() const throw() {
+ if (message_.empty()) {
+ switch (type_) {
+ case UNKNOWN : return "TTransportException: Unknown transport exception";
+ case NOT_OPEN : return "TTransportException: Transport not open";
+ case TIMED_OUT : return "TTransportException: Timed out";
+ case END_OF_FILE : return "TTransportException: End of file";
+ case INTERRUPTED : return "TTransportException: Interrupted";
+ case BAD_ARGS : return "TTransportException: Invalid arguments";
+ case CORRUPTED_DATA : return "TTransportException: Corrupted Data";
+ case INTERNAL_ERROR : return "TTransportException: Internal error";
+ default : return "TTransportException: (Invalid exception type)";
+ }
+ } else {
+ return message_.c_str();
}
- } else {
- return message_.c_str();
}
-}
-}
-}
-} // apache::thrift::transport
+
+
+}}} // apache::thrift::transport
diff --git a/lib/cpp/src/thrift/transport/TTransportException.h b/lib/cpp/src/thrift/transport/TTransportException.h
index 83e876a..8558837 100644
--- a/lib/cpp/src/thrift/transport/TTransportException.h
+++ b/lib/cpp/src/thrift/transport/TTransportException.h
@@ -23,9 +23,7 @@
#include <string>
#include <thrift/Thrift.h>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
/**
* Class to encapsulate all the possible types of transport errors that may
@@ -36,33 +34,42 @@
*
*/
class TTransportException : public apache::thrift::TException {
-public:
+ public:
/**
* Error codes for the various types of exceptions.
*/
- enum TTransportExceptionType {
- UNKNOWN = 0,
- NOT_OPEN = 1,
- TIMED_OUT = 2,
- END_OF_FILE = 3,
- INTERRUPTED = 4,
- BAD_ARGS = 5,
- CORRUPTED_DATA = 6,
- INTERNAL_ERROR = 7
+ enum TTransportExceptionType
+ { UNKNOWN = 0
+ , NOT_OPEN = 1
+ , TIMED_OUT = 2
+ , END_OF_FILE = 3
+ , INTERRUPTED = 4
+ , BAD_ARGS = 5
+ , CORRUPTED_DATA = 6
+ , INTERNAL_ERROR = 7
};
- TTransportException() : apache::thrift::TException(), type_(UNKNOWN) {}
+ TTransportException() :
+ apache::thrift::TException(),
+ type_(UNKNOWN) {}
- TTransportException(TTransportExceptionType type) : apache::thrift::TException(), type_(type) {}
+ TTransportException(TTransportExceptionType type) :
+ apache::thrift::TException(),
+ type_(type) {}
- TTransportException(const std::string& message)
- : apache::thrift::TException(message), type_(UNKNOWN) {}
+ TTransportException(const std::string& message) :
+ apache::thrift::TException(message),
+ type_(UNKNOWN) {}
- TTransportException(TTransportExceptionType type, const std::string& message)
- : apache::thrift::TException(message), type_(type) {}
+ TTransportException(TTransportExceptionType type, const std::string& message) :
+ apache::thrift::TException(message),
+ type_(type) {}
- TTransportException(TTransportExceptionType type, const std::string& message, int errno_copy)
- : apache::thrift::TException(message + ": " + TOutput::strerror_s(errno_copy)), type_(type) {}
+ TTransportException(TTransportExceptionType type,
+ const std::string& message,
+ int errno_copy) :
+ apache::thrift::TException(message + ": " + TOutput::strerror_s(errno_copy)),
+ type_(type) {}
virtual ~TTransportException() throw() {}
@@ -72,19 +79,21 @@
*
* @return Error code
*/
- TTransportExceptionType getType() const throw() { return type_; }
+ TTransportExceptionType getType() const throw() {
+ return type_;
+ }
virtual const char* what() const throw();
-protected:
+ protected:
/** Just like strerror_r but returns a C++ string object. */
std::string strerror_s(int errno_copy);
/** Error code */
TTransportExceptionType type_;
+
};
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
#endif // #ifndef _THRIFT_TRANSPORT_TTRANSPORTEXCEPTION_H_
diff --git a/lib/cpp/src/thrift/transport/TTransportUtils.cpp b/lib/cpp/src/thrift/transport/TTransportUtils.cpp
index 0f24c95..44f6101 100644
--- a/lib/cpp/src/thrift/transport/TTransportUtils.cpp
+++ b/lib/cpp/src/thrift/transport/TTransportUtils.cpp
@@ -21,40 +21,39 @@
using std::string;
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
uint32_t TPipedTransport::read(uint8_t* buf, uint32_t len) {
uint32_t need = len;
// We don't have enough data yet
- if (rLen_ - rPos_ < need) {
+ if (rLen_-rPos_ < need) {
// Copy out whatever we have
- if (rLen_ - rPos_ > 0) {
- memcpy(buf, rBuf_ + rPos_, rLen_ - rPos_);
- need -= rLen_ - rPos_;
- buf += rLen_ - rPos_;
+ if (rLen_-rPos_ > 0) {
+ memcpy(buf, rBuf_+rPos_, rLen_-rPos_);
+ need -= rLen_-rPos_;
+ buf += rLen_-rPos_;
rPos_ = rLen_;
}
// Double the size of the underlying buffer if it is full
if (rLen_ == rBufSize_) {
- rBufSize_ *= 2;
- rBuf_ = (uint8_t*)std::realloc(rBuf_, sizeof(uint8_t) * rBufSize_);
+ rBufSize_ *=2;
+ rBuf_ = (uint8_t *)std::realloc(rBuf_, sizeof(uint8_t) * rBufSize_);
}
// try to fill up the buffer
- rLen_ += srcTrans_->read(rBuf_ + rPos_, rBufSize_ - rPos_);
+ rLen_ += srcTrans_->read(rBuf_+rPos_, rBufSize_ - rPos_);
}
+
// Hand over whatever we have
uint32_t give = need;
- if (rLen_ - rPos_ < give) {
- give = rLen_ - rPos_;
+ if (rLen_-rPos_ < give) {
+ give = rLen_-rPos_;
}
if (give > 0) {
- memcpy(buf, rBuf_ + rPos_, give);
+ memcpy(buf, rBuf_+rPos_, give);
rPos_ += give;
need -= give;
}
@@ -69,11 +68,11 @@
// Make the buffer as big as it needs to be
if ((len + wLen_) >= wBufSize_) {
- uint32_t newBufSize = wBufSize_ * 2;
+ uint32_t newBufSize = wBufSize_*2;
while ((len + wLen_) >= newBufSize) {
newBufSize *= 2;
}
- wBuf_ = (uint8_t*)std::realloc(wBuf_, sizeof(uint8_t) * newBufSize);
+ wBuf_ = (uint8_t *)std::realloc(wBuf_, sizeof(uint8_t) * newBufSize);
wBufSize_ = newBufSize;
}
@@ -82,7 +81,7 @@
wLen_ += len;
}
-void TPipedTransport::flush() {
+void TPipedTransport::flush() {
// Write out any data waiting in the write buffer
if (wLen_ > 0) {
srcTrans_->write(wBuf_, wLen_);
@@ -93,10 +92,9 @@
srcTrans_->flush();
}
-TPipedFileReaderTransport::TPipedFileReaderTransport(
- boost::shared_ptr<TFileReaderTransport> srcTrans,
- boost::shared_ptr<TTransport> dstTrans)
- : TPipedTransport(srcTrans, dstTrans), srcTrans_(srcTrans) {
+TPipedFileReaderTransport::TPipedFileReaderTransport(boost::shared_ptr<TFileReaderTransport> srcTrans, boost::shared_ptr<TTransport> dstTrans)
+ : TPipedTransport(srcTrans, dstTrans),
+ srcTrans_(srcTrans) {
}
TPipedFileReaderTransport::~TPipedFileReaderTransport() {
@@ -127,7 +125,7 @@
uint32_t get = 0;
while (have < len) {
- get = read(buf + have, len - have);
+ get = read(buf+have, len-have);
if (get <= 0) {
throw TEOFException();
}
@@ -176,6 +174,5 @@
void TPipedFileReaderTransport::seekToEnd() {
srcTrans_->seekToEnd();
}
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
diff --git a/lib/cpp/src/thrift/transport/TTransportUtils.h b/lib/cpp/src/thrift/transport/TTransportUtils.h
index c221836..aa294b4 100644
--- a/lib/cpp/src/thrift/transport/TTransportUtils.h
+++ b/lib/cpp/src/thrift/transport/TTransportUtils.h
@@ -29,9 +29,7 @@
#include <thrift/transport/TBufferTransports.h>
#include <thrift/transport/TFileTransport.h>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
/**
* The null transport is a dummy transport that doesn't actually do anything.
@@ -41,18 +39,24 @@
*
*/
class TNullTransport : public TVirtualTransport<TNullTransport> {
-public:
+ public:
TNullTransport() {}
~TNullTransport() {}
- bool isOpen() { return true; }
+ bool isOpen() {
+ return true;
+ }
void open() {}
- void write(const uint8_t* /* buf */, uint32_t /* len */) { return; }
+ void write(const uint8_t* /* buf */, uint32_t /* len */) {
+ return;
+ }
+
};
+
/**
* TPipedTransport. This transport allows piping of a request from one
* transport to another either when readEnd() or writeEnd(). The typical
@@ -62,25 +66,23 @@
*
*/
class TPipedTransport : virtual public TTransport {
-public:
- TPipedTransport(boost::shared_ptr<TTransport> srcTrans, boost::shared_ptr<TTransport> dstTrans)
- : srcTrans_(srcTrans),
- dstTrans_(dstTrans),
- rBufSize_(512),
- rPos_(0),
- rLen_(0),
- wBufSize_(512),
- wLen_(0) {
+ public:
+ TPipedTransport(boost::shared_ptr<TTransport> srcTrans,
+ boost::shared_ptr<TTransport> dstTrans) :
+ srcTrans_(srcTrans),
+ dstTrans_(dstTrans),
+ rBufSize_(512), rPos_(0), rLen_(0),
+ wBufSize_(512), wLen_(0) {
// default is to to pipe the request when readEnd() is called
pipeOnRead_ = true;
pipeOnWrite_ = false;
- rBuf_ = (uint8_t*)std::malloc(sizeof(uint8_t) * rBufSize_);
+ rBuf_ = (uint8_t*) std::malloc(sizeof(uint8_t) * rBufSize_);
if (rBuf_ == NULL) {
throw std::bad_alloc();
}
- wBuf_ = (uint8_t*)std::malloc(sizeof(uint8_t) * wBufSize_);
+ wBuf_ = (uint8_t*) std::malloc(sizeof(uint8_t) * wBufSize_);
if (wBuf_ == NULL) {
throw std::bad_alloc();
}
@@ -88,20 +90,17 @@
TPipedTransport(boost::shared_ptr<TTransport> srcTrans,
boost::shared_ptr<TTransport> dstTrans,
- uint32_t sz)
- : srcTrans_(srcTrans),
- dstTrans_(dstTrans),
- rBufSize_(512),
- rPos_(0),
- rLen_(0),
- wBufSize_(sz),
- wLen_(0) {
+ uint32_t sz) :
+ srcTrans_(srcTrans),
+ dstTrans_(dstTrans),
+ rBufSize_(512), rPos_(0), rLen_(0),
+ wBufSize_(sz), wLen_(0) {
- rBuf_ = (uint8_t*)std::malloc(sizeof(uint8_t) * rBufSize_);
+ rBuf_ = (uint8_t*) std::malloc(sizeof(uint8_t) * rBufSize_);
if (rBuf_ == NULL) {
throw std::bad_alloc();
}
- wBuf_ = (uint8_t*)std::malloc(sizeof(uint8_t) * wBufSize_);
+ wBuf_ = (uint8_t*) std::malloc(sizeof(uint8_t) * wBufSize_);
if (wBuf_ == NULL) {
throw std::bad_alloc();
}
@@ -112,29 +111,40 @@
std::free(wBuf_);
}
- bool isOpen() { return srcTrans_->isOpen(); }
+ bool isOpen() {
+ return srcTrans_->isOpen();
+ }
bool peek() {
if (rPos_ >= rLen_) {
// Double the size of the underlying buffer if it is full
if (rLen_ == rBufSize_) {
- rBufSize_ *= 2;
- rBuf_ = (uint8_t*)std::realloc(rBuf_, sizeof(uint8_t) * rBufSize_);
+ rBufSize_ *=2;
+ rBuf_ = (uint8_t *)std::realloc(rBuf_, sizeof(uint8_t) * rBufSize_);
}
// try to fill up the buffer
- rLen_ += srcTrans_->read(rBuf_ + rPos_, rBufSize_ - rPos_);
+ rLen_ += srcTrans_->read(rBuf_+rPos_, rBufSize_ - rPos_);
}
return (rLen_ > rPos_);
}
- void open() { srcTrans_->open(); }
- void close() { srcTrans_->close(); }
+ void open() {
+ srcTrans_->open();
+ }
- void setPipeOnRead(bool pipeVal) { pipeOnRead_ = pipeVal; }
+ void close() {
+ srcTrans_->close();
+ }
- void setPipeOnWrite(bool pipeVal) { pipeOnWrite_ = pipeVal; }
+ void setPipeOnRead(bool pipeVal) {
+ pipeOnRead_ = pipeVal;
+ }
+
+ void setPipeOnWrite(bool pipeVal) {
+ pipeOnWrite_ = pipeVal;
+ }
uint32_t read(uint8_t* buf, uint32_t len);
@@ -170,17 +180,23 @@
void flush();
- boost::shared_ptr<TTransport> getTargetTransport() { return dstTrans_; }
+ boost::shared_ptr<TTransport> getTargetTransport() {
+ return dstTrans_;
+ }
/*
* Override TTransport *_virt() functions to invoke our implementations.
* We cannot use TVirtualTransport to provide these, since we need to inherit
* virtually from TTransport.
*/
- virtual uint32_t read_virt(uint8_t* buf, uint32_t len) { return this->read(buf, len); }
- virtual void write_virt(const uint8_t* buf, uint32_t len) { this->write(buf, len); }
+ virtual uint32_t read_virt(uint8_t* buf, uint32_t len) {
+ return this->read(buf, len);
+ }
+ virtual void write_virt(const uint8_t* buf, uint32_t len) {
+ this->write(buf, len);
+ }
-protected:
+ protected:
boost::shared_ptr<TTransport> srcTrans_;
boost::shared_ptr<TTransport> dstTrans_;
@@ -197,12 +213,13 @@
bool pipeOnWrite_;
};
+
/**
* Wraps a transport into a pipedTransport instance.
*
*/
class TPipedTransportFactory : public TTransportFactory {
-public:
+ public:
TPipedTransportFactory() {}
TPipedTransportFactory(boost::shared_ptr<TTransport> dstTrans) {
initializeTargetTransport(dstTrans);
@@ -224,7 +241,7 @@
}
}
-protected:
+ protected:
boost::shared_ptr<TTransport> dstTrans_;
};
@@ -234,10 +251,10 @@
* TTransport can still access the original transport.
*
*/
-class TPipedFileReaderTransport : public TPipedTransport, public TFileReaderTransport {
-public:
- TPipedFileReaderTransport(boost::shared_ptr<TFileReaderTransport> srcTrans,
- boost::shared_ptr<TTransport> dstTrans);
+class TPipedFileReaderTransport : public TPipedTransport,
+ public TFileReaderTransport {
+ public:
+ TPipedFileReaderTransport(boost::shared_ptr<TFileReaderTransport> srcTrans, boost::shared_ptr<TTransport> dstTrans);
~TPipedFileReaderTransport();
@@ -266,11 +283,17 @@
* We cannot use TVirtualTransport to provide these, since we need to inherit
* virtually from TTransport.
*/
- virtual uint32_t read_virt(uint8_t* buf, uint32_t len) { return this->read(buf, len); }
- virtual uint32_t readAll_virt(uint8_t* buf, uint32_t len) { return this->readAll(buf, len); }
- virtual void write_virt(const uint8_t* buf, uint32_t len) { this->write(buf, len); }
+ virtual uint32_t read_virt(uint8_t* buf, uint32_t len) {
+ return this->read(buf, len);
+ }
+ virtual uint32_t readAll_virt(uint8_t* buf, uint32_t len) {
+ return this->readAll(buf, len);
+ }
+ virtual void write_virt(const uint8_t* buf, uint32_t len) {
+ this->write(buf, len);
+ }
-protected:
+ protected:
// shouldn't be used
TPipedFileReaderTransport();
boost::shared_ptr<TFileReaderTransport> srcTrans_;
@@ -281,15 +304,15 @@
*
*/
class TPipedFileReaderTransportFactory : public TPipedTransportFactory {
-public:
+ public:
TPipedFileReaderTransportFactory() {}
TPipedFileReaderTransportFactory(boost::shared_ptr<TTransport> dstTrans)
- : TPipedTransportFactory(dstTrans) {}
+ : TPipedTransportFactory(dstTrans)
+ {}
virtual ~TPipedFileReaderTransportFactory() {}
boost::shared_ptr<TTransport> getTransport(boost::shared_ptr<TTransport> srcTrans) {
- boost::shared_ptr<TFileReaderTransport> pFileReaderTransport
- = boost::dynamic_pointer_cast<TFileReaderTransport>(srcTrans);
+ boost::shared_ptr<TFileReaderTransport> pFileReaderTransport = boost::dynamic_pointer_cast<TFileReaderTransport>(srcTrans);
if (pFileReaderTransport.get() != NULL) {
return getFileReaderTransport(pFileReaderTransport);
} else {
@@ -297,14 +320,11 @@
}
}
- boost::shared_ptr<TFileReaderTransport> getFileReaderTransport(
- boost::shared_ptr<TFileReaderTransport> srcTrans) {
- return boost::shared_ptr<TFileReaderTransport>(
- new TPipedFileReaderTransport(srcTrans, dstTrans_));
+ boost::shared_ptr<TFileReaderTransport> getFileReaderTransport(boost::shared_ptr<TFileReaderTransport> srcTrans) {
+ return boost::shared_ptr<TFileReaderTransport>(new TPipedFileReaderTransport(srcTrans, dstTrans_));
}
};
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
#endif // #ifndef _THRIFT_TRANSPORT_TTRANSPORTUTILS_H_
diff --git a/lib/cpp/src/thrift/transport/TVirtualTransport.h b/lib/cpp/src/thrift/transport/TVirtualTransport.h
index 0cacf61..575f547 100644
--- a/lib/cpp/src/thrift/transport/TVirtualTransport.h
+++ b/lib/cpp/src/thrift/transport/TVirtualTransport.h
@@ -22,9 +22,8 @@
#include <thrift/transport/TTransport.h>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
+
/**
* Helper class that provides default implementations of TTransport methods.
@@ -43,20 +42,28 @@
* read_virt().)
*/
class TTransportDefaults : public TTransport {
-public:
+ public:
/*
* TTransport *_virt() methods provide reasonable default implementations.
* Invoke them non-virtually.
*/
- uint32_t read(uint8_t* buf, uint32_t len) { return this->TTransport::read_virt(buf, len); }
- uint32_t readAll(uint8_t* buf, uint32_t len) { return this->TTransport::readAll_virt(buf, len); }
- void write(const uint8_t* buf, uint32_t len) { this->TTransport::write_virt(buf, len); }
+ uint32_t read(uint8_t* buf, uint32_t len) {
+ return this->TTransport::read_virt(buf, len);
+ }
+ uint32_t readAll(uint8_t* buf, uint32_t len) {
+ return this->TTransport::readAll_virt(buf, len);
+ }
+ void write(const uint8_t* buf, uint32_t len) {
+ this->TTransport::write_virt(buf, len);
+ }
const uint8_t* borrow(uint8_t* buf, uint32_t* len) {
return this->TTransport::borrow_virt(buf, len);
}
- void consume(uint32_t len) { this->TTransport::consume_virt(len); }
+ void consume(uint32_t len) {
+ this->TTransport::consume_virt(len);
+ }
-protected:
+ protected:
TTransportDefaults() {}
};
@@ -77,9 +84,9 @@
*
* @author Chad Walters <chad@powerset.com>
*/
-template <class Transport_, class Super_ = TTransportDefaults>
+template <class Transport_, class Super_=TTransportDefaults>
class TVirtualTransport : public Super_ {
-public:
+ public:
/*
* Implementations of the *_virt() functions, to call the subclass's
* non-virtual implementation function.
@@ -100,7 +107,9 @@
return static_cast<Transport_*>(this)->borrow(buf, len);
}
- virtual void consume_virt(uint32_t len) { static_cast<Transport_*>(this)->consume(len); }
+ virtual void consume_virt(uint32_t len) {
+ static_cast<Transport_*>(this)->consume(len);
+ }
/*
* Provide a default readAll() implementation that invokes
@@ -117,7 +126,7 @@
return ::apache::thrift::transport::readAll(*trans, buf, len);
}
-protected:
+ protected:
TVirtualTransport() {}
/*
@@ -126,15 +135,12 @@
* additional versions can be added as needed.
*/
template <typename Arg_>
- TVirtualTransport(Arg_ const& arg)
- : Super_(arg) {}
+ TVirtualTransport(Arg_ const& arg) : Super_(arg) { }
template <typename Arg1_, typename Arg2_>
- TVirtualTransport(Arg1_ const& a1, Arg2_ const& a2)
- : Super_(a1, a2) {}
+ TVirtualTransport(Arg1_ const& a1, Arg2_ const& a2) : Super_(a1, a2) { }
};
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
#endif // #ifndef _THRIFT_TRANSPORT_TVIRTUALTRANSPORT_H_
diff --git a/lib/cpp/src/thrift/transport/TZlibTransport.cpp b/lib/cpp/src/thrift/transport/TZlibTransport.cpp
index fb5cc5d..cdde7c3 100644
--- a/lib/cpp/src/thrift/transport/TZlibTransport.cpp
+++ b/lib/cpp/src/thrift/transport/TZlibTransport.cpp
@@ -24,9 +24,7 @@
using std::string;
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
// Don't call this outside of the constructor.
void TZlibTransport::initZlib() {
@@ -38,17 +36,17 @@
rstream_->zalloc = Z_NULL;
wstream_->zalloc = Z_NULL;
- rstream_->zfree = Z_NULL;
- wstream_->zfree = Z_NULL;
+ rstream_->zfree = Z_NULL;
+ wstream_->zfree = Z_NULL;
rstream_->opaque = Z_NULL;
wstream_->opaque = Z_NULL;
- rstream_->next_in = crbuf_;
- wstream_->next_in = uwbuf_;
- rstream_->next_out = urbuf_;
- wstream_->next_out = cwbuf_;
- rstream_->avail_in = 0;
- wstream_->avail_in = 0;
+ rstream_->next_in = crbuf_;
+ wstream_->next_in = uwbuf_;
+ rstream_->next_out = urbuf_;
+ wstream_->next_out = cwbuf_;
+ rstream_->avail_in = 0;
+ wstream_->avail_in = 0;
rstream_->avail_out = urbuf_size_;
wstream_->avail_out = cwbuf_size_;
@@ -81,8 +79,8 @@
inline void TZlibTransport::checkZlibRvNothrow(int status, const char* message) {
if (status != Z_OK) {
- string output = "TZlibTransport: zlib failure in destructor: "
- + TZlibTransportException::errorMessage(status, message);
+ string output = "TZlibTransport: zlib failure in destructor: " +
+ TZlibTransportException::errorMessage(status, message);
GlobalOutput(output.c_str());
}
}
@@ -118,6 +116,8 @@
return (readAvail() > 0) || (rstream_->avail_in > 0) || transport_->peek();
}
+
+
// READING STRATEGY
//
// We have two buffers for reading: one containing the compressed data (crbuf_)
@@ -143,7 +143,7 @@
while (true) {
// Copy out whatever we have available, then give them the min of
// what we have and what they want, then advance indices.
- int give = (std::min)((uint32_t)readAvail(), need);
+ int give = (std::min)((uint32_t) readAvail(), need);
memcpy(buf, urbuf_ + urpos_, give);
need -= give;
buf += give;
@@ -170,7 +170,7 @@
}
// The uncompressed read buffer is empty, so reset the stream fields.
- rstream_->next_out = urbuf_;
+ rstream_->next_out = urbuf_;
rstream_->avail_out = urbuf_size_;
urpos_ = 0;
@@ -195,7 +195,7 @@
if (got == 0) {
return false;
}
- rstream_->next_in = crbuf_;
+ rstream_->next_in = crbuf_;
rstream_->avail_in = got;
}
@@ -211,6 +211,7 @@
return true;
}
+
// WRITING STRATEGY
//
// We buffer up small writes before sending them to zlib, so our logic is:
@@ -231,7 +232,8 @@
void TZlibTransport::write(const uint8_t* buf, uint32_t len) {
if (output_finished_) {
- throw TTransportException(TTransportException::BAD_ARGS, "write() called after finish()");
+ throw TTransportException(TTransportException::BAD_ARGS,
+ "write() called after finish()");
}
// zlib's "deflate" function has enough logic in it that I think
@@ -250,23 +252,25 @@
}
}
-void TZlibTransport::flush() {
+void TZlibTransport::flush() {
if (output_finished_) {
- throw TTransportException(TTransportException::BAD_ARGS, "flush() called after finish()");
+ throw TTransportException(TTransportException::BAD_ARGS,
+ "flush() called after finish()");
}
flushToTransport(Z_FULL_FLUSH);
}
-void TZlibTransport::finish() {
+void TZlibTransport::finish() {
if (output_finished_) {
- throw TTransportException(TTransportException::BAD_ARGS, "finish() called more than once");
+ throw TTransportException(TTransportException::BAD_ARGS,
+ "finish() called more than once");
}
flushToTransport(Z_FINISH);
}
-void TZlibTransport::flushToTransport(int flush) {
+void TZlibTransport::flushToTransport(int flush) {
// write pending data in uwbuf_ to zlib
flushToZlib(uwbuf_, uwpos_, flush);
uwpos_ = 0;
@@ -281,7 +285,7 @@
}
void TZlibTransport::flushToZlib(const uint8_t* buf, int len, int flush) {
- wstream_->next_in = const_cast<uint8_t*>(buf);
+ wstream_->next_in = const_cast<uint8_t*>(buf);
wstream_->avail_in = len;
while (true) {
@@ -292,7 +296,7 @@
// If our ouput buffer is full, flush to the underlying transport.
if (wstream_->avail_out == 0) {
transport_->write(cwbuf_, cwbuf_size_);
- wstream_->next_out = cwbuf_;
+ wstream_->next_out = cwbuf_;
wstream_->avail_out = cwbuf_size_;
}
@@ -306,15 +310,15 @@
checkZlibRv(zlib_rv, wstream_->msg);
- if ((flush == Z_SYNC_FLUSH || flush == Z_FULL_FLUSH) && wstream_->avail_in == 0
- && wstream_->avail_out != 0) {
+ if ((flush == Z_SYNC_FLUSH || flush == Z_FULL_FLUSH) &&
+ wstream_->avail_in == 0 && wstream_->avail_out != 0) {
break;
}
}
}
const uint8_t* TZlibTransport::borrow(uint8_t* buf, uint32_t* len) {
- (void)buf;
+ (void) buf;
// Don't try to be clever with shifting buffers.
// If we have enough data, give a pointer to it,
// otherwise let the protcol use its slow path.
@@ -329,7 +333,8 @@
if (readAvail() >= (int)len) {
urpos_ += len;
} else {
- throw TTransportException(TTransportException::BAD_ARGS, "consume did not follow a borrow.");
+ throw TTransportException(TTransportException::BAD_ARGS,
+ "consume did not follow a borrow.");
}
}
@@ -343,13 +348,14 @@
// This should only be called when reading is complete.
// If the caller still has unread data, throw an exception.
if (readAvail() > 0) {
- throw TTransportException(TTransportException::CORRUPTED_DATA,
- "verifyChecksum() called before end of zlib stream");
+ throw TTransportException(
+ TTransportException::CORRUPTED_DATA,
+ "verifyChecksum() called before end of zlib stream");
}
// Reset the rstream fields, in case avail_out is 0.
// (Since readAvail() is 0, we know there is no unread data in urbuf_)
- rstream_->next_out = urbuf_;
+ rstream_->next_out = urbuf_;
rstream_->avail_out = urbuf_size_;
urpos_ = 0;
@@ -388,6 +394,6 @@
"verifyChecksum() called before end of "
"zlib stream");
}
-}
-}
-} // apache::thrift::transport
+
+
+}}} // apache::thrift::transport
diff --git a/lib/cpp/src/thrift/transport/TZlibTransport.h b/lib/cpp/src/thrift/transport/TZlibTransport.h
index 1e7b5ec..565ecaa 100644
--- a/lib/cpp/src/thrift/transport/TZlibTransport.h
+++ b/lib/cpp/src/thrift/transport/TZlibTransport.h
@@ -27,16 +27,15 @@
struct z_stream_s;
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
class TZlibTransportException : public TTransportException {
-public:
- TZlibTransportException(int status, const char* msg)
- : TTransportException(TTransportException::INTERNAL_ERROR, errorMessage(status, msg)),
- zlib_status_(status),
- zlib_msg_(msg == NULL ? "(null)" : msg) {}
+ public:
+ TZlibTransportException(int status, const char* msg) :
+ TTransportException(TTransportException::INTERNAL_ERROR,
+ errorMessage(status, msg)),
+ zlib_status_(status),
+ zlib_msg_(msg == NULL ? "(null)" : msg) {}
virtual ~TZlibTransportException() throw() {}
@@ -68,7 +67,8 @@
*
*/
class TZlibTransport : public TVirtualTransport<TZlibTransport> {
-public:
+ public:
+
/**
* @param transport The transport to read compressed data from
* and write compressed data to.
@@ -83,29 +83,31 @@
int crbuf_size = DEFAULT_CRBUF_SIZE,
int uwbuf_size = DEFAULT_UWBUF_SIZE,
int cwbuf_size = DEFAULT_CWBUF_SIZE,
- int16_t comp_level = Z_DEFAULT_COMPRESSION)
- : transport_(transport),
- urpos_(0),
- uwpos_(0),
- input_ended_(false),
- output_finished_(false),
- urbuf_size_(urbuf_size),
- crbuf_size_(crbuf_size),
- uwbuf_size_(uwbuf_size),
- cwbuf_size_(cwbuf_size),
- urbuf_(NULL),
- crbuf_(NULL),
- uwbuf_(NULL),
- cwbuf_(NULL),
- rstream_(NULL),
- wstream_(NULL),
- comp_level_(comp_level) {
+ int16_t comp_level = Z_DEFAULT_COMPRESSION) :
+ transport_(transport),
+ urpos_(0),
+ uwpos_(0),
+ input_ended_(false),
+ output_finished_(false),
+ urbuf_size_(urbuf_size),
+ crbuf_size_(crbuf_size),
+ uwbuf_size_(uwbuf_size),
+ cwbuf_size_(cwbuf_size),
+ urbuf_(NULL),
+ crbuf_(NULL),
+ uwbuf_(NULL),
+ cwbuf_(NULL),
+ rstream_(NULL),
+ wstream_(NULL),
+ comp_level_(comp_level)
+ {
if (uwbuf_size_ < MIN_DIRECT_DEFLATE_SIZE) {
// Have to copy this into a local because of a linking issue.
int minimum = MIN_DIRECT_DEFLATE_SIZE;
- throw TTransportException(TTransportException::BAD_ARGS,
- "TZLibTransport: uncompressed write buffer must be at least"
- + boost::lexical_cast<std::string>(minimum) + ".");
+ throw TTransportException(
+ TTransportException::BAD_ARGS,
+ "TZLibTransport: uncompressed write buffer must be at least"
+ + boost::lexical_cast<std::string>(minimum) + ".");
}
try {
@@ -141,9 +143,13 @@
bool isOpen();
bool peek();
- void open() { transport_->open(); }
+ void open() {
+ transport_->open();
+ }
- void close() { transport_->close(); }
+ void close() {
+ transport_->close();
+ }
uint32_t read(uint8_t* buf, uint32_t len);
@@ -172,15 +178,16 @@
*/
void verifyChecksum();
- /**
- * TODO(someone_smart): Choose smart defaults.
- */
+ /**
+ * TODO(someone_smart): Choose smart defaults.
+ */
static const int DEFAULT_URBUF_SIZE = 128;
static const int DEFAULT_CRBUF_SIZE = 1024;
static const int DEFAULT_UWBUF_SIZE = 128;
static const int DEFAULT_CWBUF_SIZE = 1024;
-protected:
+ protected:
+
inline void checkZlibRv(int status, const char* msg);
inline void checkZlibRvNothrow(int status, const char* msg);
inline int readAvail();
@@ -188,7 +195,7 @@
void flushToZlib(const uint8_t* buf, int len, int flush);
bool readFromZlib();
-protected:
+ protected:
// Writes smaller than this are buffered up.
// Larger (or equal) writes are dumped straight to zlib.
static const uint32_t MIN_DIRECT_DEFLATE_SIZE = 32;
@@ -219,22 +226,24 @@
const int comp_level_;
};
+
/**
* Wraps a transport into a zlibbed one.
*
*/
class TZlibTransportFactory : public TTransportFactory {
-public:
+ public:
TZlibTransportFactory() {}
virtual ~TZlibTransportFactory() {}
- virtual boost::shared_ptr<TTransport> getTransport(boost::shared_ptr<TTransport> trans) {
+ virtual boost::shared_ptr<TTransport> getTransport(
+ boost::shared_ptr<TTransport> trans) {
return boost::shared_ptr<TTransport>(new TZlibTransport(trans));
}
};
-}
-}
-} // apache::thrift::transport
+
+
+}}} // apache::thrift::transport
#endif // #ifndef _THRIFT_TRANSPORT_TZLIBTRANSPORT_H_
diff --git a/lib/cpp/src/thrift/windows/GetTimeOfDay.cpp b/lib/cpp/src/thrift/windows/GetTimeOfDay.cpp
index 654d005..c5667e4 100644
--- a/lib/cpp/src/thrift/windows/GetTimeOfDay.cpp
+++ b/lib/cpp/src/thrift/windows/GetTimeOfDay.cpp
@@ -24,73 +24,89 @@
#include <time.h>
#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
-#define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64
+# define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64
#else
-#define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL
+# define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL
#endif
-struct timezone {
- int tz_minuteswest; /* minutes W of Greenwich */
- int tz_dsttime; /* type of dst correction */
+struct timezone
+{
+ int tz_minuteswest; /* minutes W of Greenwich */
+ int tz_dsttime; /* type of dst correction */
};
-int thrift_gettimeofday(struct timeval* tv, struct timezone* tz) {
- FILETIME ft;
- unsigned __int64 tmpres(0);
- static int tzflag;
+int thrift_gettimeofday(struct timeval * tv, struct timezone * tz)
+{
+ FILETIME ft;
+ unsigned __int64 tmpres(0);
+ static int tzflag;
- if (NULL != tv) {
- GetSystemTimeAsFileTime(&ft);
+ if (NULL != tv)
+ {
+ GetSystemTimeAsFileTime(&ft);
- tmpres |= ft.dwHighDateTime;
- tmpres <<= 32;
- tmpres |= ft.dwLowDateTime;
+ tmpres |= ft.dwHighDateTime;
+ tmpres <<= 32;
+ tmpres |= ft.dwLowDateTime;
- /*converting file time to unix epoch*/
- tmpres -= DELTA_EPOCH_IN_MICROSECS;
- tmpres /= 10; /*convert into microseconds*/
- tv->tv_sec = (long)(tmpres / 1000000UL);
- tv->tv_usec = (long)(tmpres % 1000000UL);
- }
-
- if (NULL != tz) {
- if (!tzflag) {
- _tzset();
- tzflag++;
+ /*converting file time to unix epoch*/
+ tmpres -= DELTA_EPOCH_IN_MICROSECS;
+ tmpres /= 10; /*convert into microseconds*/
+ tv->tv_sec = (long)(tmpres / 1000000UL);
+ tv->tv_usec = (long)(tmpres % 1000000UL);
}
- long time_zone(0);
- errno_t err(_get_timezone(&time_zone));
- if (err == NO_ERROR) {
- tz->tz_minuteswest = time_zone / 60;
- } else {
- return -1;
+ if (NULL != tz)
+ {
+ if (!tzflag)
+ {
+ _tzset();
+ tzflag++;
+ }
+
+ long time_zone(0);
+ errno_t err(_get_timezone(&time_zone));
+ if (err == NO_ERROR)
+ {
+ tz->tz_minuteswest = time_zone / 60;
+ }
+ else
+ {
+ return -1;
+ }
+
+ int day_light(0);
+ err = (_get_daylight(&day_light));
+ if (err == NO_ERROR)
+ {
+ tz->tz_dsttime = day_light;
+ return 0;
+ }
+ else
+ {
+ return -1;
+ }
}
- int day_light(0);
- err = (_get_daylight(&day_light));
- if (err == NO_ERROR) {
- tz->tz_dsttime = day_light;
- return 0;
- } else {
- return -1;
- }
- }
-
- return 0;
+ return 0;
}
-int thrift_sleep(unsigned int seconds) {
+int thrift_sleep(unsigned int seconds)
+{
::Sleep(seconds * 1000);
return 0;
}
-int thrift_usleep(unsigned int microseconds) {
- unsigned int milliseconds = (microseconds + 999) / 1000;
+int thrift_usleep(unsigned int microseconds)
+{
+ unsigned int milliseconds = (microseconds + 999)/ 1000;
::Sleep(milliseconds);
return 0;
}
-char* thrift_ctime_r(const time_t* _clock, char* _buf) {
- strcpy(_buf, ctime(_clock));
- return _buf;
+char *thrift_ctime_r(const time_t *_clock, char *_buf)
+{
+ strcpy(_buf, ctime(_clock));
+ return _buf;
}
+
+
diff --git a/lib/cpp/src/thrift/windows/GetTimeOfDay.h b/lib/cpp/src/thrift/windows/GetTimeOfDay.h
index 6e90ba1..27b8a84 100644
--- a/lib/cpp/src/thrift/windows/GetTimeOfDay.h
+++ b/lib/cpp/src/thrift/windows/GetTimeOfDay.h
@@ -35,9 +35,9 @@
int64_t tv_nsec;
};
-int thrift_gettimeofday(struct timeval* tv, struct timezone* tz);
+int thrift_gettimeofday(struct timeval * tv, struct timezone * tz);
int thrift_sleep(unsigned int seconds);
int thrift_usleep(unsigned int micro_seconds);
-char* thrift_ctime_r(const time_t* _clock, char* _buf);
+char *thrift_ctime_r(const time_t *_clock, char *_buf);
#endif // _THRIFT_WINDOWS_GETTIMEOFDAY_H_
diff --git a/lib/cpp/src/thrift/windows/Operators.h b/lib/cpp/src/thrift/windows/Operators.h
index 9b86096..95d8e3e 100644
--- a/lib/cpp/src/thrift/windows/Operators.h
+++ b/lib/cpp/src/thrift/windows/Operators.h
@@ -24,17 +24,17 @@
#pragma once
#endif // _MSC_VER
-namespace apache {
-namespace thrift {
+namespace apache { namespace thrift {
class TEnumIterator;
-inline bool operator==(const TEnumIterator&, const TEnumIterator&) {
- // Not entirely sure what the test should be here. It is only to enable
- // iterator debugging and is not used in release mode.
- return true;
+inline bool operator == (const TEnumIterator&, const TEnumIterator&)
+{
+ // Not entirely sure what the test should be here. It is only to enable
+ // iterator debugging and is not used in release mode.
+ return true;
}
-}
-} // apache::thrift
+
+}} // apache::thrift
#endif // _THRIFT_WINDOWS_OPERATORS_H_
diff --git a/lib/cpp/src/thrift/windows/OverlappedSubmissionThread.cpp b/lib/cpp/src/thrift/windows/OverlappedSubmissionThread.cpp
index 5ac6fe0..5dec390 100644
--- a/lib/cpp/src/thrift/windows/OverlappedSubmissionThread.cpp
+++ b/lib/cpp/src/thrift/windows/OverlappedSubmissionThread.cpp
@@ -23,23 +23,21 @@
#include <boost/scope_exit.hpp>
#include <process.h>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
-TOverlappedWorkItem::TOverlappedWorkItem()
- : SLIST_ENTRY(),
- action(UNKNOWN),
- h(INVALID_HANDLE_VALUE),
- buffer(NULL),
- buffer_len(0),
- overlap(),
- last_error(0),
- success(TRUE) {
-}
+TOverlappedWorkItem::TOverlappedWorkItem() :
+ SLIST_ENTRY(),
+ action(UNKNOWN),
+ h(INVALID_HANDLE_VALUE),
+ buffer(NULL),
+ buffer_len(0),
+ overlap(),
+ last_error(0),
+ success(TRUE)
+{}
-void TOverlappedWorkItem::reset(uint8_t* buf, uint32_t len, HANDLE event) {
- memset(&overlap, 0, sizeof(overlap));
+void TOverlappedWorkItem::reset(uint8_t *buf, uint32_t len, HANDLE event) {
+ memset( &overlap, 0, sizeof(overlap));
overlap.hEvent = event;
buffer = buf;
buffer_len = len;
@@ -50,7 +48,7 @@
uint32_t TOverlappedWorkItem::overlappedResults(bool signal_failure) {
DWORD bytes = 0;
BOOL result = ::GetOverlappedResult(h, &overlap, &bytes, TRUE);
- if (signal_failure && !result) // get overlapped error case
+ if(signal_failure && !result) //get overlapped error case
{
GlobalOutput.perror("TPipe ::GetOverlappedResult errored GLE=", ::GetLastError());
throw TTransportException(TTransportException::UNKNOWN, "TPipe: GetOverlappedResult failed");
@@ -59,40 +57,42 @@
}
bool TOverlappedWorkItem::process() {
- BOOST_SCOPE_EXIT((&doneSubmittingEvent)) { SetEvent(doneSubmittingEvent.h); }
- BOOST_SCOPE_EXIT_END
+ BOOST_SCOPE_EXIT( (&doneSubmittingEvent) ) {
+ SetEvent(doneSubmittingEvent.h);
+ } BOOST_SCOPE_EXIT_END
- switch (action) {
- case (CONNECT):
+ switch(action) {
+ case(CONNECT):
success = ::ConnectNamedPipe(h, &overlap);
- if (success == FALSE)
+ if(success == FALSE)
last_error = ::GetLastError();
return true;
- case (READ):
+ case(READ):
success = ::ReadFile(h, buffer, buffer_len, NULL, &overlap);
- if (success == FALSE)
+ if(success == FALSE)
last_error = ::GetLastError();
return true;
- case (CANCELIO):
+ case(CANCELIO):
success = ::CancelIo(h);
- if (success == FALSE)
+ if(success == FALSE)
last_error = ::GetLastError();
return true;
- case (STOP):
+ case(STOP):
default:
return false;
}
}
-void TOverlappedSubmissionThread::addWorkItem(TOverlappedWorkItem* item) {
+void TOverlappedSubmissionThread::addWorkItem(TOverlappedWorkItem *item) {
InterlockedPushEntrySList(&workList_, item);
SetEvent(workAvailableEvent_.h);
WaitForSingleObject(item->doneSubmittingEvent.h, INFINITE);
}
-TOverlappedSubmissionThread* TOverlappedSubmissionThread::acquire_instance() {
+TOverlappedSubmissionThread *TOverlappedSubmissionThread::acquire_instance() {
TAutoCrit lock(instanceGuard_);
- if (instance_ == NULL) {
+ if(instance_ == NULL)
+ {
assert(instanceRefCount_ == 0);
instance_ = new TOverlappedSubmissionThread;
}
@@ -101,7 +101,8 @@
}
void TOverlappedSubmissionThread::release_instance() {
TAutoCrit lock(instanceGuard_);
- if (--instanceRefCount_ == 0) {
+ if(--instanceRefCount_ == 0)
+ {
delete instance_;
instance_ = NULL;
}
@@ -111,11 +112,16 @@
stopItem_.action = TOverlappedWorkItem::STOP;
InitializeSListHead(&workList_);
- thread_ = (HANDLE)_beginthreadex(NULL, 0, thread_proc, this, 0, NULL);
- if (thread_ == 0) {
+ thread_ = (HANDLE)_beginthreadex(
+ NULL,
+ 0,
+ thread_proc,
+ this,
+ 0,
+ NULL);
+ if(thread_ == 0) {
GlobalOutput.perror("TOverlappedSubmissionThread unable to create thread, errno=", errno);
- throw TTransportException(TTransportException::NOT_OPEN,
- " TOverlappedSubmissionThread unable to create thread");
+ throw TTransportException(TTransportException::NOT_OPEN, " TOverlappedSubmissionThread unable to create thread");
}
}
@@ -126,26 +132,25 @@
}
void TOverlappedSubmissionThread::run() {
- for (;;) {
+ for(;;) {
WaitForSingleObject(workAvailableEvent_.h, INFINITE);
- // todo check result
- SLIST_ENTRY* entry = NULL;
- while ((entry = InterlockedPopEntrySList(&workList_)) != NULL) {
- TOverlappedWorkItem& item = *static_cast<TOverlappedWorkItem*>(entry);
- if (!item.process())
+ //todo check result
+ SLIST_ENTRY *entry = NULL;
+ while( (entry = InterlockedPopEntrySList(&workList_)) != NULL) {
+ TOverlappedWorkItem &item = *static_cast<TOverlappedWorkItem *>(entry);
+ if(!item.process())
return;
}
}
}
-unsigned __stdcall TOverlappedSubmissionThread::thread_proc(void* addr) {
- static_cast<TOverlappedSubmissionThread*>(addr)->run();
+unsigned __stdcall TOverlappedSubmissionThread::thread_proc(void *addr) {
+ static_cast<TOverlappedSubmissionThread *>(addr)->run();
return 0;
}
TCriticalSection TOverlappedSubmissionThread::instanceGuard_;
TOverlappedSubmissionThread* TOverlappedSubmissionThread::instance_;
-uint32_t TOverlappedSubmissionThread::instanceRefCount_ = 0;
-}
-}
-} // apach::thrift::transport
+uint32_t TOverlappedSubmissionThread::instanceRefCount_=0;
+
+}}} //apach::thrift::transport
diff --git a/lib/cpp/src/thrift/windows/OverlappedSubmissionThread.h b/lib/cpp/src/thrift/windows/OverlappedSubmissionThread.h
index 56684bb..16b7e24 100644
--- a/lib/cpp/src/thrift/windows/OverlappedSubmissionThread.h
+++ b/lib/cpp/src/thrift/windows/OverlappedSubmissionThread.h
@@ -59,15 +59,13 @@
until the operation has completed.
*/
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
DECLSPEC_ALIGN(MEMORY_ALLOCATION_ALIGNMENT) struct TOverlappedWorkItem : public SLIST_ENTRY {
TOverlappedWorkItem();
enum action_t {
- UNKNOWN = 3000,
+ UNKNOWN = 3000,
CONNECT,
READ,
CANCELIO,
@@ -77,38 +75,38 @@
TAutoResetEvent doneSubmittingEvent;
action_t action;
HANDLE h;
- uint8_t* buffer;
+ uint8_t *buffer;
uint32_t buffer_len;
OVERLAPPED overlap;
DWORD last_error;
BOOL success;
- void reset(uint8_t* buf, uint32_t len, HANDLE event);
+ void reset(uint8_t *buf, uint32_t len, HANDLE event);
uint32_t overlappedResults(bool signal_failure = true);
bool process();
};
-class TOverlappedSubmissionThread : boost::noncopyable {
+class TOverlappedSubmissionThread : boost::noncopyable
+{
public:
- void addWorkItem(TOverlappedWorkItem* item);
+ void addWorkItem(TOverlappedWorkItem *item);
- // singleton stuff
+//singleton stuff
public:
- static TOverlappedSubmissionThread* acquire_instance();
+ static TOverlappedSubmissionThread *acquire_instance();
static void release_instance();
-
private:
static TCriticalSection instanceGuard_;
- static TOverlappedSubmissionThread* instance_;
+ static TOverlappedSubmissionThread *instance_;
static uint32_t instanceRefCount_;
- // thread details
+//thread details
private:
TOverlappedSubmissionThread();
~TOverlappedSubmissionThread();
void run();
- static unsigned __stdcall thread_proc(void* addr);
+ static unsigned __stdcall thread_proc(void *addr);
private:
DECLSPEC_ALIGN(MEMORY_ALLOCATION_ALIGNMENT) SLIST_HEADER workList_;
@@ -119,15 +117,13 @@
class TAutoOverlapThread : boost::noncopyable {
private:
- TOverlappedSubmissionThread* p;
-
+ TOverlappedSubmissionThread *p;
public:
TAutoOverlapThread() : p(TOverlappedSubmissionThread::acquire_instance()) {}
- ~TAutoOverlapThread() { TOverlappedSubmissionThread::release_instance(); }
- TOverlappedSubmissionThread* operator->() { return p; }
+ ~TAutoOverlapThread() {TOverlappedSubmissionThread::release_instance();}
+ TOverlappedSubmissionThread *operator->() {return p;}
};
-}
-}
-} // apache::thrift::transport
+
+}}} //apache::thrift::transport
#endif
diff --git a/lib/cpp/src/thrift/windows/SocketPair.cpp b/lib/cpp/src/thrift/windows/SocketPair.cpp
index 7228832..4b65e6b 100644
--- a/lib/cpp/src/thrift/windows/SocketPair.cpp
+++ b/lib/cpp/src/thrift/windows/SocketPair.cpp
@@ -36,65 +36,67 @@
// Win32
#include <WS2tcpip.h>
-int thrift_socketpair(int d, int type, int protocol, THRIFT_SOCKET sv[2]) {
- THRIFT_UNUSED_VARIABLE(protocol);
- THRIFT_UNUSED_VARIABLE(type);
- THRIFT_UNUSED_VARIABLE(d);
+int thrift_socketpair(int d, int type, int protocol, THRIFT_SOCKET sv[2])
+{
+ THRIFT_UNUSED_VARIABLE(protocol);
+ THRIFT_UNUSED_VARIABLE(type);
+ THRIFT_UNUSED_VARIABLE(d);
- union {
- struct sockaddr_in inaddr;
- struct sockaddr addr;
- } a;
- THRIFT_SOCKET listener;
- int e;
- socklen_t addrlen = sizeof(a.inaddr);
- DWORD flags = 0;
- int reuse = 1;
+ union {
+ struct sockaddr_in inaddr;
+ struct sockaddr addr;
+ } a;
+ THRIFT_SOCKET listener;
+ int e;
+ socklen_t addrlen = sizeof(a.inaddr);
+ DWORD flags = 0;
+ int reuse = 1;
- if (sv == 0) {
- WSASetLastError(WSAEINVAL);
- return SOCKET_ERROR;
- }
+ if (sv == 0) {
+ WSASetLastError(WSAEINVAL);
+ return SOCKET_ERROR;
+ }
- listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
- if (listener == INVALID_SOCKET)
- return SOCKET_ERROR;
+ listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+ if (listener == INVALID_SOCKET)
+ return SOCKET_ERROR;
- memset(&a, 0, sizeof(a));
- a.inaddr.sin_family = AF_INET;
- a.inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
- a.inaddr.sin_port = 0;
+ memset(&a, 0, sizeof(a));
+ a.inaddr.sin_family = AF_INET;
+ a.inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ a.inaddr.sin_port = 0;
- sv[0] = sv[1] = INVALID_SOCKET;
- do {
- // ignore errors coming out of this setsockopt. This is because
- // SO_EXCLUSIVEADDRUSE requires admin privileges on WinXP, but we don't
- // want to force socket pairs to be an admin.
- setsockopt(listener, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char*)&reuse, (socklen_t)sizeof(reuse));
- if (bind(listener, &a.addr, sizeof(a.inaddr)) == SOCKET_ERROR)
- break;
- if (getsockname(listener, &a.addr, &addrlen) == SOCKET_ERROR)
- break;
- if (listen(listener, 1) == SOCKET_ERROR)
- break;
- sv[0] = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, flags);
- if (sv[0] == INVALID_SOCKET)
- break;
- if (connect(sv[0], &a.addr, sizeof(a.inaddr)) == SOCKET_ERROR)
- break;
- sv[1] = accept(listener, NULL, NULL);
- if (sv[1] == INVALID_SOCKET)
- break;
+ sv[0] = sv[1] = INVALID_SOCKET;
+ do {
+ //ignore errors coming out of this setsockopt. This is because
+ //SO_EXCLUSIVEADDRUSE requires admin privileges on WinXP, but we don't
+ //want to force socket pairs to be an admin.
+ setsockopt(listener, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
+ (char*) &reuse, (socklen_t) sizeof(reuse));
+ if (bind(listener, &a.addr, sizeof(a.inaddr)) == SOCKET_ERROR)
+ break;
+ if (getsockname(listener, &a.addr, &addrlen) == SOCKET_ERROR)
+ break;
+ if (listen(listener, 1) == SOCKET_ERROR)
+ break;
+ sv[0] = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, flags);
+ if (sv[0] == INVALID_SOCKET)
+ break;
+ if (connect(sv[0], &a.addr, sizeof(a.inaddr)) == SOCKET_ERROR)
+ break;
+ sv[1] = accept(listener, NULL, NULL);
+ if (sv[1] == INVALID_SOCKET)
+ break;
+ closesocket(listener);
+ return 0;
+
+ } while (0);
+
+ e = WSAGetLastError();
closesocket(listener);
- return 0;
-
- } while (0);
-
- e = WSAGetLastError();
- closesocket(listener);
- closesocket(sv[0]);
- closesocket(sv[1]);
- WSASetLastError(e);
- return SOCKET_ERROR;
+ closesocket(sv[0]);
+ closesocket(sv[1]);
+ WSASetLastError(e);
+ return SOCKET_ERROR;
}
diff --git a/lib/cpp/src/thrift/windows/Sync.h b/lib/cpp/src/thrift/windows/Sync.h
index 5d32199..ded6ea3 100644
--- a/lib/cpp/src/thrift/windows/Sync.h
+++ b/lib/cpp/src/thrift/windows/Sync.h
@@ -33,55 +33,53 @@
code, use the classes found in the concurrency namespace
*/
-namespace apache {
-namespace thrift {
+namespace apache { namespace thrift {
struct TCriticalSection : boost::noncopyable {
CRITICAL_SECTION cs;
- TCriticalSection() { InitializeCriticalSection(&cs); }
- ~TCriticalSection() { DeleteCriticalSection(&cs); }
+ TCriticalSection() {InitializeCriticalSection(&cs);}
+ ~TCriticalSection() {DeleteCriticalSection(&cs);}
};
class TAutoCrit : boost::noncopyable {
private:
- CRITICAL_SECTION* cs_;
-
+ CRITICAL_SECTION *cs_;
public:
- explicit TAutoCrit(TCriticalSection& cs) : cs_(&cs.cs) { EnterCriticalSection(cs_); }
- ~TAutoCrit() { LeaveCriticalSection(cs_); }
+ explicit TAutoCrit(TCriticalSection &cs) : cs_(&cs.cs) {EnterCriticalSection(cs_);}
+ ~TAutoCrit() {LeaveCriticalSection(cs_);}
};
struct TAutoResetEvent : boost::noncopyable {
HANDLE h;
TAutoResetEvent() {
- h = CreateEvent(NULL, FALSE, FALSE, NULL);
- if (h == NULL) {
+ h = CreateEvent( NULL, FALSE, FALSE, NULL);
+ if(h == NULL) {
GlobalOutput.perror("TAutoResetEvent unable to create event, GLE=", GetLastError());
throw apache::thrift::concurrency::SystemResourceException("CreateEvent failed");
}
}
- ~TAutoResetEvent() { CloseHandle(h); }
+ ~TAutoResetEvent() {CloseHandle(h);}
};
struct TManualResetEvent : boost::noncopyable {
HANDLE h;
TManualResetEvent() {
- h = CreateEvent(NULL, TRUE, FALSE, NULL);
- if (h == NULL) {
+ h = CreateEvent( NULL, TRUE, FALSE, NULL);
+ if(h == NULL) {
GlobalOutput.perror("TManualResetEvent unable to create event, GLE=", GetLastError());
throw apache::thrift::concurrency::SystemResourceException("CreateEvent failed");
}
}
- ~TManualResetEvent() { CloseHandle(h); }
+ ~TManualResetEvent() {CloseHandle(h);}
};
struct TAutoHandle : boost::noncopyable {
HANDLE h;
explicit TAutoHandle(HANDLE h_ = INVALID_HANDLE_VALUE) : h(h_) {}
~TAutoHandle() {
- if (h != INVALID_HANDLE_VALUE)
+ if(h != INVALID_HANDLE_VALUE)
CloseHandle(h);
}
@@ -91,14 +89,14 @@
return retval;
}
void reset(HANDLE h_ = INVALID_HANDLE_VALUE) {
- if (h_ == h)
+ if(h_ == h)
return;
- if (h != INVALID_HANDLE_VALUE)
+ if(h != INVALID_HANDLE_VALUE)
CloseHandle(h);
h = h_;
}
};
-}
-} // apache::thrift
+
+}} //apache::thrift
#endif
diff --git a/lib/cpp/src/thrift/windows/TWinsockSingleton.cpp b/lib/cpp/src/thrift/windows/TWinsockSingleton.cpp
index 2e0ccf5..2e306c6 100644
--- a/lib/cpp/src/thrift/windows/TWinsockSingleton.cpp
+++ b/lib/cpp/src/thrift/windows/TWinsockSingleton.cpp
@@ -23,49 +23,51 @@
#include <boost/assert.hpp>
#include <stdexcept>
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
TWinsockSingleton::instance_ptr TWinsockSingleton::instance_ptr_(NULL);
#if USE_BOOST_THREAD
-boost::once_flag TWinsockSingleton::flags_ = BOOST_ONCE_INIT;
+boost::once_flag TWinsockSingleton::flags_ = BOOST_ONCE_INIT;
#elif USE_STD_THREAD
-std::once_flag TWinsockSingleton::flags_;
+std::once_flag TWinsockSingleton::flags_;
#else
#error For windows you must choose USE_BOOST_THREAD or USE_STD_THREAD
#endif
//------------------------------------------------------------------------------
-TWinsockSingleton::TWinsockSingleton(void) {
- WORD version(MAKEWORD(2, 2));
- WSAData data = {0};
+TWinsockSingleton::TWinsockSingleton(void)
+{
+ WORD version(MAKEWORD(2, 2));
+ WSAData data = {0};
- int error(WSAStartup(version, &data));
- if (error != 0) {
- BOOST_ASSERT(false);
- throw std::runtime_error("Failed to initialise Winsock.");
- }
+ int error(WSAStartup(version, &data));
+ if (error != 0)
+ {
+ BOOST_ASSERT(false);
+ throw std::runtime_error("Failed to initialise Winsock.");
+ }
}
//------------------------------------------------------------------------------
-TWinsockSingleton::~TWinsockSingleton(void) {
- WSACleanup();
+TWinsockSingleton::~TWinsockSingleton(void)
+{
+ WSACleanup();
}
//------------------------------------------------------------------------------
-void TWinsockSingleton::create(void) {
+void TWinsockSingleton::create(void)
+{
#if USE_BOOST_THREAD
- boost::call_once(init, flags_);
+ boost::call_once(init, flags_);
#elif USE_STD_THREAD
- std::call_once(flags_, init);
+ std::call_once(flags_, init);
#endif
}
//------------------------------------------------------------------------------
-void TWinsockSingleton::init(void) {
- instance_ptr_.reset(new TWinsockSingleton);
+void TWinsockSingleton::init(void)
+{
+ instance_ptr_.reset(new TWinsockSingleton);
}
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
diff --git a/lib/cpp/src/thrift/windows/TWinsockSingleton.h b/lib/cpp/src/thrift/windows/TWinsockSingleton.h
index dc1b52f..ab12c22 100644
--- a/lib/cpp/src/thrift/windows/TWinsockSingleton.h
+++ b/lib/cpp/src/thrift/windows/TWinsockSingleton.h
@@ -42,43 +42,47 @@
#error For windows you must choose USE_BOOST_THREAD or USE_STD_THREAD
#endif
-namespace apache {
-namespace thrift {
-namespace transport {
+namespace apache { namespace thrift { namespace transport {
/**
* Winsock2 must be intialised once only in order to create sockets. This class
* performs a one time initialisation when create is called.
*/
-class TWinsockSingleton : private boost::noncopyable {
+class TWinsockSingleton : private boost::noncopyable
+{
public:
- typedef boost::scoped_ptr<TWinsockSingleton> instance_ptr;
+
+ typedef boost::scoped_ptr<TWinsockSingleton> instance_ptr;
private:
- TWinsockSingleton(void);
+
+ TWinsockSingleton(void);
public:
- ~TWinsockSingleton(void);
+
+ ~TWinsockSingleton(void);
public:
- static void create(void);
+
+ static void create(void);
private:
- static void init(void);
+
+ static void init(void);
private:
- static instance_ptr instance_ptr_;
+
+ static instance_ptr instance_ptr_;
#if USE_BOOST_THREAD
- static boost::once_flag flags_;
+ static boost::once_flag flags_;
#elif USE_STD_THREAD
- static std::once_flag flags_;
+ static std::once_flag flags_;
#else
#error Need a non-Boost non-C++11 way to track single initialization here.
#endif
};
-}
-}
-} // apache::thrift::transport
+
+}}} // apache::thrift::transport
#endif // _THRIFT_TRANSPORT_WINDOWS_TWINSOCKSINGLETON_H_
diff --git a/lib/cpp/src/thrift/windows/WinFcntl.cpp b/lib/cpp/src/thrift/windows/WinFcntl.cpp
index c8b85f3..3dd4e3d 100644
--- a/lib/cpp/src/thrift/windows/WinFcntl.cpp
+++ b/lib/cpp/src/thrift/windows/WinFcntl.cpp
@@ -19,46 +19,54 @@
#include <thrift/windows/WinFcntl.h>
-int thrift_fcntl(THRIFT_SOCKET fd, int cmd, int flags) {
- if (cmd != THRIFT_F_GETFL && cmd != THRIFT_F_SETFL) {
- return -1;
- }
+int thrift_fcntl(THRIFT_SOCKET fd, int cmd, int flags)
+{
+ if(cmd != THRIFT_F_GETFL && cmd != THRIFT_F_SETFL)
+ {
+ return -1;
+ }
- if (flags != THRIFT_O_NONBLOCK && flags != 0) {
- return -1;
- }
+ if(flags != THRIFT_O_NONBLOCK && flags != 0)
+ {
+ return -1;
+ }
- if (cmd == THRIFT_F_GETFL) {
- return 0;
- }
+ if(cmd == THRIFT_F_GETFL)
+ {
+ return 0;
+ }
- int res;
- if (flags) {
- res = ioctlsocket(fd, FIONBIO, reinterpret_cast<u_long*>(&(flags = 1)));
- } else {
- res = ioctlsocket(fd, FIONBIO, reinterpret_cast<u_long*>(&(flags = 0)));
- }
+ int res;
+ if(flags)
+ {
+ res = ioctlsocket(fd, FIONBIO, reinterpret_cast<u_long *>(&(flags = 1)));
+ }
+ else
+ {
+ res = ioctlsocket(fd, FIONBIO, reinterpret_cast<u_long *>(&(flags = 0)));
+ }
- return res;
+ return res;
}
-#if WINVER <= 0x0502 // XP, Server2003
-int thrift_poll(THRIFT_POLLFD* fdArray, ULONG nfds, INT timeout) {
+#if WINVER <= 0x0502 //XP, Server2003
+int thrift_poll(THRIFT_POLLFD *fdArray, ULONG nfds, INT timeout)
+{
fd_set read_fds, write_fds;
- fd_set* read_fds_ptr = NULL;
+ fd_set* read_fds_ptr = NULL;
fd_set* write_fds_ptr = NULL;
FD_ZERO(&read_fds);
FD_ZERO(&write_fds);
- for (ULONG i = 0; i < nfds; i++) {
- // Read (in) socket
- if ((fdArray[i].events & THRIFT_POLLIN) == THRIFT_POLLIN) {
+ for(ULONG i=0; i<nfds; i++) {
+ //Read (in) socket
+ if((fdArray[i].events & THRIFT_POLLIN) == THRIFT_POLLIN) {
read_fds_ptr = &read_fds;
FD_SET(fdArray[i].fd, &read_fds);
}
- // Write (out) socket
- else if ((fdArray[i].events & THRIFT_POLLOUT) == THRIFT_POLLOUT) {
+ //Write (out) socket
+ else if((fdArray[i].events & THRIFT_POLLOUT) == THRIFT_POLLOUT) {
write_fds_ptr = &write_fds;
FD_SET(fdArray[i].fd, &write_fds);
}
@@ -66,35 +74,37 @@
timeval time_out;
timeval* time_out_ptr = NULL;
- if (timeout >= 0) {
+ if(timeout >= 0) {
timeval time_out = {timeout / 1000, (timeout % 1000) * 1000};
time_out_ptr = &time_out;
- } else { // to avoid compiler warnings
+ }
+ else { //to avoid compiler warnings
(void)time_out;
(void)timeout;
}
int sktready = select(1, read_fds_ptr, write_fds_ptr, NULL, time_out_ptr);
- if (sktready > 0) {
- for (ULONG i = 0; i < nfds; i++) {
+ if(sktready > 0) {
+ for(ULONG i=0; i<nfds; i++) {
fdArray[i].revents = 0;
- if (FD_ISSET(fdArray[i].fd, &read_fds))
+ if(FD_ISSET(fdArray[i].fd, &read_fds))
fdArray[i].revents |= THRIFT_POLLIN;
- if (FD_ISSET(fdArray[i].fd, &write_fds))
+ if(FD_ISSET(fdArray[i].fd, &write_fds))
fdArray[i].revents |= THRIFT_POLLOUT;
}
}
return sktready;
}
-#else // Vista, Win7...
-int thrift_poll(THRIFT_POLLFD* fdArray, ULONG nfds, INT timeout) {
+#else //Vista, Win7...
+int thrift_poll(THRIFT_POLLFD *fdArray, ULONG nfds, INT timeout)
+{
return WSAPoll(fdArray, nfds, timeout);
}
#endif // WINVER
#ifdef _WIN32_WCE
std::string thrift_wstr2str(std::wstring ws) {
- std::string s(ws.begin(), ws.end());
- return s;
+ std::string s(ws.begin(), ws.end());
+ return s;
}
#endif
diff --git a/lib/cpp/src/thrift/windows/WinFcntl.h b/lib/cpp/src/thrift/windows/WinFcntl.h
index 6c6be97..118c9a4 100644
--- a/lib/cpp/src/thrift/windows/WinFcntl.h
+++ b/lib/cpp/src/thrift/windows/WinFcntl.h
@@ -36,17 +36,17 @@
#include <Winsock2.h>
#include <thrift/transport/PlatformSocket.h>
-#if WINVER <= 0x0502 // XP, Server2003
+#if WINVER <= 0x0502 //XP, Server2003
struct thrift_pollfd {
- THRIFT_SOCKET fd;
- SHORT events;
- SHORT revents;
+ THRIFT_SOCKET fd;
+ SHORT events;
+ SHORT revents;
};
#endif
extern "C" {
int thrift_fcntl(THRIFT_SOCKET fd, int cmd, int flags);
-int thrift_poll(THRIFT_POLLFD* fdArray, ULONG nfds, INT timeout);
+int thrift_poll(THRIFT_POLLFD *fdArray, ULONG nfds, INT timeout);
}
#ifdef _WIN32_WCE
diff --git a/lib/cpp/src/thrift/windows/config.h b/lib/cpp/src/thrift/windows/config.h
index dd0da35..9261ca8 100644
--- a/lib/cpp/src/thrift/windows/config.h
+++ b/lib/cpp/src/thrift/windows/config.h
@@ -30,53 +30,53 @@
// use std::thread in MSVC11 (2012) or newer
#if _MSC_VER >= 1700
-#define USE_STD_THREAD 1
+# define USE_STD_THREAD 1
// otherwise use boost threads
#else
-#define USE_BOOST_THREAD 1
+# define USE_BOOST_THREAD 1
#endif
#ifndef TARGET_WIN_XP
-#define TARGET_WIN_XP 1
+# define TARGET_WIN_XP 1
#endif
#if TARGET_WIN_XP
-#ifndef WINVER
-#define WINVER 0x0501
-#endif
-#ifndef _WIN32_WINNT
-#define _WIN32_WINNT 0x0501
-#endif
+# ifndef WINVER
+# define WINVER 0x0501
+# endif
+# ifndef _WIN32_WINNT
+# define _WIN32_WINNT 0x0501
+# endif
#endif
#ifndef _WIN32_WINNT
-#define _WIN32_WINNT 0x0601
+# define _WIN32_WINNT 0x0601
#endif
#if defined(_M_IX86) || defined(_M_X64)
-#define ARITHMETIC_RIGHT_SHIFT 1
-#define SIGNED_RIGHT_SHIFT_IS 1
+# define ARITHMETIC_RIGHT_SHIFT 1
+# define SIGNED_RIGHT_SHIFT_IS 1
#endif
-#pragma warning(disable : 4996) // Deprecated posix name.
+#pragma warning(disable: 4996) // Deprecated posix name.
#define VERSION "1.0.0-dev"
#define HAVE_GETTIMEOFDAY 1
#define HAVE_SYS_STAT_H 1
#ifdef HAVE_STDINT_H
-#include <stdint.h>
+# include <stdint.h>
#else
-#include <boost/cstdint.hpp>
+# include <boost/cstdint.hpp>
-typedef boost::int64_t int64_t;
-typedef boost::uint64_t uint64_t;
-typedef boost::int32_t int32_t;
-typedef boost::uint32_t uint32_t;
-typedef boost::int16_t int16_t;
-typedef boost::uint16_t uint16_t;
-typedef boost::int8_t int8_t;
-typedef boost::uint8_t uint8_t;
+typedef boost::int64_t int64_t;
+typedef boost::uint64_t uint64_t;
+typedef boost::int32_t int32_t;
+typedef boost::uint32_t uint32_t;
+typedef boost::int16_t int16_t;
+typedef boost::uint16_t uint16_t;
+typedef boost::int8_t int8_t;
+typedef boost::uint8_t uint8_t;
#endif
#include <thrift/transport/PlatformSocket.h>
@@ -93,6 +93,6 @@
#pragma comment(lib, "Ws2.lib")
#else
#pragma comment(lib, "Ws2_32.lib")
-#pragma comment(lib, "advapi32.lib") // For security APIs in TPipeServer
+#pragma comment(lib, "advapi32.lib") //For security APIs in TPipeServer
#endif
#endif // _THRIFT_WINDOWS_CONFIG_H_
diff --git a/lib/cpp/test/AllProtocolTests.cpp b/lib/cpp/test/AllProtocolTests.cpp
index 29ba193..65d1927 100644
--- a/lib/cpp/test/AllProtocolTests.cpp
+++ b/lib/cpp/test/AllProtocolTests.cpp
@@ -31,8 +31,8 @@
char errorMessage[ERR_LEN];
int main(int argc, char** argv) {
- (void)argc;
- (void)argv;
+ (void) argc;
+ (void) argv;
try {
testProtocol<TBinaryProtocol>("TBinaryProtocol");
testProtocol<TCompactProtocol>("TCompactProtocol");
diff --git a/lib/cpp/test/AllProtocolTests.tcc b/lib/cpp/test/AllProtocolTests.tcc
index 8c8eaa8..3c98943 100644
--- a/lib/cpp/test/AllProtocolTests.tcc
+++ b/lib/cpp/test/AllProtocolTests.tcc
@@ -45,10 +45,7 @@
Val out;
GenericIO::read(protocol, out);
if (out != val) {
- THRIFT_SNPRINTF(errorMessage,
- ERR_LEN,
- "Invalid naked test (type: %s)",
- ClassNames::getName<Val>());
+ THRIFT_SNPRINTF(errorMessage, ERR_LEN, "Invalid naked test (type: %s)", ClassNames::getName<Val>());
throw TException(errorMessage);
}
}
@@ -100,18 +97,22 @@
const char* name;
TMessageType type;
int32_t seqid;
- } messages[] = {{"short message name", T_CALL, 0},
- {"1", T_REPLY, 12345},
- {"loooooooooooooooooooooooooooooooooong", T_EXCEPTION, 1 << 16},
- {"one way push", T_ONEWAY, 12},
- {"Janky", T_CALL, 0}};
+ } messages[] = {
+ {"short message name", T_CALL, 0},
+ {"1", T_REPLY, 12345},
+ {"loooooooooooooooooooooooooooooooooong", T_EXCEPTION, 1 << 16},
+ {"one way push", T_ONEWAY, 12},
+ {"Janky", T_CALL, 0}
+ };
const int messages_count = sizeof(messages) / sizeof(TMessage);
for (int i = 0; i < messages_count; i++) {
shared_ptr<TTransport> transport(new TMemoryBuffer());
shared_ptr<TProtocol> protocol(new TProto(transport));
- protocol->writeMessageBegin(messages[i].name, messages[i].type, messages[i].seqid);
+ protocol->writeMessageBegin(messages[i].name,
+ messages[i].type,
+ messages[i].seqid);
protocol->writeMessageEnd();
std::string name;
@@ -119,7 +120,9 @@
int32_t seqid;
protocol->readMessageBegin(name, type, seqid);
- if (name != messages[i].name || type != messages[i].type || seqid != messages[i].seqid) {
+ if (name != messages[i].name ||
+ type != messages[i].type ||
+ seqid != messages[i].seqid) {
throw TException("readMessageBegin failed.");
}
}
@@ -188,6 +191,7 @@
testNaked<TProto, int64_t>((std::numeric_limits<int64_t>::min)());
testNaked<TProto, int64_t>((std::numeric_limits<int64_t>::max)());
+
testNaked<TProto, int64_t>(0);
for (int64_t i = 0; i < 62; i++) {
testNaked<TProto, int64_t>(1L << i);
@@ -206,7 +210,7 @@
testNaked<TProto, std::string>("short");
testNaked<TProto, std::string>("borderlinetiny");
testNaked<TProto, std::string>("a bit longer than the smallest possible");
- testNaked<TProto, std::string>("\x1\x2\x3\x4\x5\x6\x7\x8\x9\xA"); // kinda binary test
+ testNaked<TProto, std::string>("\x1\x2\x3\x4\x5\x6\x7\x8\x9\xA"); //kinda binary test
testField<TProto, T_STRING, std::string>("");
testField<TProto, T_STRING, std::string>("short");
diff --git a/lib/cpp/test/Base64Test.cpp b/lib/cpp/test/Base64Test.cpp
index e9e86dd..5caaae8 100644
--- a/lib/cpp/test/Base64Test.cpp
+++ b/lib/cpp/test/Base64Test.cpp
@@ -23,7 +23,7 @@
using apache::thrift::protocol::base64_encode;
using apache::thrift::protocol::base64_decode;
-BOOST_AUTO_TEST_SUITE(Base64Test)
+BOOST_AUTO_TEST_SUITE( Base64Test )
void setupTestData(int i, uint8_t* data, int& len) {
len = 0;
@@ -42,7 +42,7 @@
}
}
-BOOST_AUTO_TEST_CASE(test_Base64_Encode_Decode) {
+BOOST_AUTO_TEST_CASE( test_Base64_Encode_Decode ) {
int len;
uint8_t testInput[3];
uint8_t testOutput[4];
@@ -64,6 +64,7 @@
// decode output and check that it matches input
base64_decode(testOutput, len + 1);
BOOST_ASSERT(0 == memcmp(testInput, testOutput, len));
+
}
}
diff --git a/lib/cpp/test/Benchmark.cpp b/lib/cpp/test/Benchmark.cpp
index cf6b79a..3571150 100644
--- a/lib/cpp/test/Benchmark.cpp
+++ b/lib/cpp/test/Benchmark.cpp
@@ -34,8 +34,12 @@
public:
timeval vStart;
- Timer() { THRIFT_GETTIMEOFDAY(&vStart, 0); }
- void start() { THRIFT_GETTIMEOFDAY(&vStart, 0); }
+ Timer() {
+ THRIFT_GETTIMEOFDAY(&vStart, 0);
+ }
+ void start() {
+ THRIFT_GETTIMEOFDAY(&vStart, 0);
+ }
double frame() {
timeval vEnd;
@@ -44,6 +48,7 @@
double dend = vEnd.tv_sec + ((double)vEnd.tv_usec / 1000000.0);
return dend - dstart;
}
+
};
int main() {
@@ -54,15 +59,15 @@
using namespace boost;
OneOfEach ooe;
- ooe.im_true = true;
- ooe.im_false = false;
- ooe.a_bite = 0x7f;
+ ooe.im_true = true;
+ ooe.im_false = false;
+ ooe.a_bite = 0x7f;
ooe.integer16 = 27000;
- ooe.integer32 = 1 << 24;
+ ooe.integer32 = 1<<24;
ooe.integer64 = (uint64_t)6000 * 1000 * 1000;
ooe.double_precision = M_PI;
- ooe.some_characters = "JSON THIS! \"\1";
- ooe.zomg_unicode = "\xd7\n\a\t";
+ ooe.some_characters = "JSON THIS! \"\1";
+ ooe.zomg_unicode = "\xd7\n\a\t";
ooe.base64 = "\1\2\3\255";
boost::shared_ptr<TMemoryBuffer> buf(new TMemoryBuffer());
@@ -72,7 +77,7 @@
{
Timer timer;
- for (int i = 0; i < num; i++) {
+ for (int i = 0; i < num; i ++) {
buf->resetBuffer();
TBinaryProtocolT<TBufferBase> prot(buf);
ooe.write(&prot);
@@ -89,17 +94,18 @@
Timer timer;
- for (int i = 0; i < num; i++) {
+ for (int i = 0; i < num; i ++) {
OneOfEach ooe2;
boost::shared_ptr<TMemoryBuffer> buf2(new TMemoryBuffer(data, datasize));
- // buf2->resetBuffer(data, datasize);
+ //buf2->resetBuffer(data, datasize);
TBinaryProtocolT<TBufferBase> prot(buf2);
ooe2.read(&prot);
- // cout << apache::thrift::ThriftDebugString(ooe2) << endl << endl;
+ //cout << apache::thrift::ThriftDebugString(ooe2) << endl << endl;
}
cout << " Read: " << num / (1000 * timer.frame()) << " kHz" << endl;
}
+
return 0;
}
diff --git a/lib/cpp/test/DebugProtoTest.cpp b/lib/cpp/test/DebugProtoTest.cpp
index 98c66b8..5649e18 100644
--- a/lib/cpp/test/DebugProtoTest.cpp
+++ b/lib/cpp/test/DebugProtoTest.cpp
@@ -28,34 +28,37 @@
using std::endl;
using namespace thrift::test::debug;
+
OneOfEach ooe;
- ooe.im_true = true;
- ooe.im_false = false;
- ooe.a_bite = 0x7f;
+ ooe.im_true = true;
+ ooe.im_false = false;
+ ooe.a_bite = 0x7f;
ooe.integer16 = 27000;
- ooe.integer32 = 1 << 24;
+ ooe.integer32 = 1<<24;
ooe.integer64 = (uint64_t)6000 * 1000 * 1000;
ooe.double_precision = M_PI;
- ooe.some_characters = "Debug THIS!";
- ooe.zomg_unicode = "\xd7\n\a\t";
+ ooe.some_characters = "Debug THIS!";
+ ooe.zomg_unicode = "\xd7\n\a\t";
cout << apache::thrift::ThriftDebugString(ooe) << endl << endl;
+
Nesting n;
n.my_ooe = ooe;
n.my_ooe.integer16 = 16;
n.my_ooe.integer32 = 32;
n.my_ooe.integer64 = 64;
- n.my_ooe.double_precision = (std::sqrt(5.0) + 1) / 2;
- n.my_ooe.some_characters = ":R (me going \"rrrr\")";
+ n.my_ooe.double_precision = (std::sqrt(5.0)+1)/2;
+ n.my_ooe.some_characters = ":R (me going \"rrrr\")";
n.my_ooe.zomg_unicode = "\xd3\x80\xe2\x85\xae\xce\x9d\x20"
"\xd0\x9d\xce\xbf\xe2\x85\xbf\xd0\xbe\xc9\xa1\xd0\xb3\xd0\xb0\xcf\x81\xe2\x84\x8e"
"\x20\xce\x91\x74\x74\xce\xb1\xe2\x85\xbd\xce\xba\xc7\x83\xe2\x80\xbc";
- n.my_bonk.type = 31337;
+ n.my_bonk.type = 31337;
n.my_bonk.message = "I am a bonk... xor!";
cout << apache::thrift::ThriftDebugString(n) << endl << endl;
+
HolyMoley hm;
hm.big.push_back(ooe);
@@ -77,26 +80,27 @@
std::vector<Bonk> stage2;
hm.bonks["nothing"] = stage2;
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 1;
stage2.back().message = "Wait.";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 2;
stage2.back().message = "What?";
hm.bonks["something"] = stage2;
stage2.clear();
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 3;
stage2.back().message = "quoth";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 4;
stage2.back().message = "the raven";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 5;
stage2.back().message = "nevermore";
hm.bonks["poe"] = stage2;
cout << apache::thrift::ThriftDebugString(hm) << endl << endl;
+
return 0;
}
diff --git a/lib/cpp/test/DebugProtoTest_extras.cpp b/lib/cpp/test/DebugProtoTest_extras.cpp
index 5c4fd35..c89db74 100644
--- a/lib/cpp/test/DebugProtoTest_extras.cpp
+++ b/lib/cpp/test/DebugProtoTest_extras.cpp
@@ -21,15 +21,13 @@
#include "gen-cpp/DebugProtoTest_types.h"
-namespace thrift {
-namespace test {
-namespace debug {
+
+namespace thrift { namespace test { namespace debug {
bool Empty::operator<(Empty const& other) const {
- (void)other;
+ (void) other;
// It is empty, so all are equal.
return false;
}
-}
-}
-}
+
+}}}
diff --git a/lib/cpp/test/DenseProtoTest.cpp b/lib/cpp/test/DenseProtoTest.cpp
index d827d3c..f73579f 100644
--- a/lib/cpp/test/DenseProtoTest.cpp
+++ b/lib/cpp/test/DenseProtoTest.cpp
@@ -42,6 +42,7 @@
#include <thrift/protocol/TDenseProtocol.h>
#include <thrift/transport/TBufferTransports.h>
+
// Can't use memcmp here. GCC is too smart.
bool my_memeq(const char* str1, const char* str2, int len) {
for (int i = 0; i < len; i++) {
@@ -52,6 +53,7 @@
return true;
}
+
int main() {
using std::string;
using std::cout;
@@ -61,33 +63,36 @@
using namespace apache::thrift::transport;
using namespace apache::thrift::protocol;
+
OneOfEach ooe;
- ooe.im_true = true;
- ooe.im_false = false;
- ooe.a_bite = 0xd6;
+ ooe.im_true = true;
+ ooe.im_false = false;
+ ooe.a_bite = 0xd6;
ooe.integer16 = 27000;
- ooe.integer32 = 1 << 24;
+ ooe.integer32 = 1<<24;
ooe.integer64 = (uint64_t)6000 * 1000 * 1000;
ooe.double_precision = M_PI;
- ooe.some_characters = "Debug THIS!";
- ooe.zomg_unicode = "\xd7\n\a\t";
+ ooe.some_characters = "Debug THIS!";
+ ooe.zomg_unicode = "\xd7\n\a\t";
- // cout << apache::thrift::ThriftDebugString(ooe) << endl << endl;
+ //cout << apache::thrift::ThriftDebugString(ooe) << endl << endl;
+
Nesting n;
n.my_ooe = ooe;
n.my_ooe.integer16 = 16;
n.my_ooe.integer32 = 32;
n.my_ooe.integer64 = 64;
- n.my_ooe.double_precision = (std::sqrt(5) + 1) / 2;
- n.my_ooe.some_characters = ":R (me going \"rrrr\")";
+ n.my_ooe.double_precision = (std::sqrt(5)+1)/2;
+ n.my_ooe.some_characters = ":R (me going \"rrrr\")";
n.my_ooe.zomg_unicode = "\xd3\x80\xe2\x85\xae\xce\x9d\x20"
"\xd0\x9d\xce\xbf\xe2\x85\xbf\xd0\xbe\xc9\xa1\xd0\xb3\xd0\xb0\xcf\x81\xe2\x84\x8e"
"\x20\xce\x91\x74\x74\xce\xb1\xe2\x85\xbd\xce\xba\xc7\x83\xe2\x80\xbc";
- n.my_bonk.type = 31337;
+ n.my_bonk.type = 31337;
n.my_bonk.message = "I am a bonk... xor!";
- // cout << apache::thrift::ThriftDebugString(n) << endl << endl;
+ //cout << apache::thrift::ThriftDebugString(n) << endl << endl;
+
HolyMoley hm;
@@ -110,26 +115,26 @@
std::vector<Bonk> stage2;
hm.bonks["nothing"] = stage2;
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 1;
stage2.back().message = "Wait.";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 2;
stage2.back().message = "What?";
hm.bonks["something"] = stage2;
stage2.clear();
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 3;
stage2.back().message = "quoth";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 4;
stage2.back().message = "the raven";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 5;
stage2.back().message = "nevermore";
hm.bonks["poe"] = stage2;
- // cout << apache::thrift::ThriftDebugString(hm) << endl << endl;
+ //cout << apache::thrift::ThriftDebugString(hm) << endl << endl;
shared_ptr<TMemoryBuffer> buffer(new TMemoryBuffer());
shared_ptr<TDenseProtocol> proto(new TDenseProtocol(buffer));
@@ -141,16 +146,16 @@
assert(hm == hm2);
+
// Let's test out the variable-length ints, shall we?
uint64_t vlq;
-#define checkout(i, c) \
- { \
- buffer->resetBuffer(); \
- proto->vlqWrite(i); \
- proto->getTransport()->flush(); \
- assert(my_memeq(buffer->getBufferAsString().data(), c, sizeof(c) - 1)); \
- proto->vlqRead(vlq); \
- assert(vlq == i); \
+ #define checkout(i, c) { \
+ buffer->resetBuffer(); \
+ proto->vlqWrite(i); \
+ proto->getTransport()->flush(); \
+ assert(my_memeq(buffer->getBufferAsString().data(), c, sizeof(c)-1)); \
+ proto->vlqRead(vlq); \
+ assert(vlq == i); \
}
checkout(0x00000000, "\x00");
@@ -287,6 +292,7 @@
assert(mo1 == mo6);
+
// Test fingerprint checking stuff.
{
@@ -360,7 +366,7 @@
buffer->resetBuffer();
// Make sure the fingerprint prefix is right.
buffer->write(Nesting::binary_fingerprint, 4);
- for (int j = 0; j < 1024 * 1024; j++) {
+ for (int j = 0; j < 1024*1024; j++) {
uint8_t r = std::rand();
buffer->write(&r, 1);
}
diff --git a/lib/cpp/test/EnumTest.cpp b/lib/cpp/test/EnumTest.cpp
index 0e34b16..72f98bb 100644
--- a/lib/cpp/test/EnumTest.cpp
+++ b/lib/cpp/test/EnumTest.cpp
@@ -20,9 +20,9 @@
#include <boost/test/unit_test.hpp>
#include "gen-cpp/EnumTest_types.h"
-BOOST_AUTO_TEST_SUITE(EnumTest)
+BOOST_AUTO_TEST_SUITE( EnumTest )
-BOOST_AUTO_TEST_CASE(test_enum) {
+BOOST_AUTO_TEST_CASE( test_enum ) {
// Check that all the enum values match what we expect
BOOST_CHECK_EQUAL(MyEnum1::ME1_0, 0);
BOOST_CHECK_EQUAL(MyEnum1::ME1_1, 1);
@@ -49,7 +49,7 @@
BOOST_CHECK_EQUAL(MyEnum4::ME4_C, 0x7fffffff);
}
-BOOST_AUTO_TEST_CASE(test_enum_constant) {
+BOOST_AUTO_TEST_CASE( test_enum_constant ) {
MyStruct ms;
BOOST_CHECK_EQUAL(ms.me2_2, 2);
BOOST_CHECK_EQUAL(ms.me3_n2, -2);
diff --git a/lib/cpp/test/GenericHelpers.h b/lib/cpp/test/GenericHelpers.h
index c175561..1853a37 100644
--- a/lib/cpp/test/GenericHelpers.h
+++ b/lib/cpp/test/GenericHelpers.h
@@ -29,41 +29,22 @@
/* ClassName Helper for cleaner exceptions */
class ClassNames {
-public:
+ public:
template <typename T>
- static const char* getName() {
- return "Unknown type";
- }
+ static const char* getName() { return "Unknown type"; }
};
-template <>
-const char* ClassNames::getName<int8_t>() {
- return "byte";
-}
-template <>
-const char* ClassNames::getName<int16_t>() {
- return "short";
-}
-template <>
-const char* ClassNames::getName<int32_t>() {
- return "int";
-}
-template <>
-const char* ClassNames::getName<int64_t>() {
- return "long";
-}
-template <>
-const char* ClassNames::getName<double>() {
- return "double";
-}
-template <>
-const char* ClassNames::getName<std::string>() {
- return "string";
-}
+template <> const char* ClassNames::getName<int8_t>() { return "byte"; }
+template <> const char* ClassNames::getName<int16_t>() { return "short"; }
+template <> const char* ClassNames::getName<int32_t>() { return "int"; }
+template <> const char* ClassNames::getName<int64_t>() { return "long"; }
+template <> const char* ClassNames::getName<double>() { return "double"; }
+template <> const char* ClassNames::getName<std::string>() { return "string"; }
/* Generic Protocol I/O function for tests */
class GenericIO {
-public:
+ public:
+
/* Write functions */
static uint32_t write(shared_ptr<TProtocol> proto, const int8_t& val) {
@@ -92,19 +73,30 @@
/* Read functions */
- static uint32_t read(shared_ptr<TProtocol> proto, int8_t& val) { return proto->readByte(val); }
+ static uint32_t read(shared_ptr<TProtocol> proto, int8_t& val) {
+ return proto->readByte(val);
+ }
- static uint32_t read(shared_ptr<TProtocol> proto, int16_t& val) { return proto->readI16(val); }
+ static uint32_t read(shared_ptr<TProtocol> proto, int16_t& val) {
+ return proto->readI16(val);
+ }
- static uint32_t read(shared_ptr<TProtocol> proto, int32_t& val) { return proto->readI32(val); }
+ static uint32_t read(shared_ptr<TProtocol> proto, int32_t& val) {
+ return proto->readI32(val);
+ }
- static uint32_t read(shared_ptr<TProtocol> proto, int64_t& val) { return proto->readI64(val); }
+ static uint32_t read(shared_ptr<TProtocol> proto, int64_t& val) {
+ return proto->readI64(val);
+ }
- static uint32_t read(shared_ptr<TProtocol> proto, double& val) { return proto->readDouble(val); }
+ static uint32_t read(shared_ptr<TProtocol> proto, double& val) {
+ return proto->readDouble(val);
+ }
static uint32_t read(shared_ptr<TProtocol> proto, std::string& val) {
return proto->readString(val);
}
+
};
#endif
diff --git a/lib/cpp/test/JSONProtoTest.cpp b/lib/cpp/test/JSONProtoTest.cpp
index aa07f93..a3259c0 100644
--- a/lib/cpp/test/JSONProtoTest.cpp
+++ b/lib/cpp/test/JSONProtoTest.cpp
@@ -32,33 +32,35 @@
using apache::thrift::protocol::TJSONProtocol;
OneOfEach ooe;
- ooe.im_true = true;
- ooe.im_false = false;
- ooe.a_bite = 0x7f;
+ ooe.im_true = true;
+ ooe.im_false = false;
+ ooe.a_bite = 0x7f;
ooe.integer16 = 27000;
- ooe.integer32 = 1 << 24;
+ ooe.integer32 = 1<<24;
ooe.integer64 = (uint64_t)6000 * 1000 * 1000;
ooe.double_precision = M_PI;
- ooe.some_characters = "JSON THIS! \"\1";
- ooe.zomg_unicode = "\xd7\n\a\t";
+ ooe.some_characters = "JSON THIS! \"\1";
+ ooe.zomg_unicode = "\xd7\n\a\t";
ooe.base64 = "\1\2\3\255";
cout << apache::thrift::ThriftJSONString(ooe) << endl << endl;
+
Nesting n;
n.my_ooe = ooe;
n.my_ooe.integer16 = 16;
n.my_ooe.integer32 = 32;
n.my_ooe.integer64 = 64;
- n.my_ooe.double_precision = (std::sqrt(5.0) + 1) / 2;
- n.my_ooe.some_characters = ":R (me going \"rrrr\")";
+ n.my_ooe.double_precision = (std::sqrt(5.0)+1)/2;
+ n.my_ooe.some_characters = ":R (me going \"rrrr\")";
n.my_ooe.zomg_unicode = "\xd3\x80\xe2\x85\xae\xce\x9d\x20"
"\xd0\x9d\xce\xbf\xe2\x85\xbf\xd0\xbe\xc9\xa1\xd0\xb3\xd0\xb0\xcf\x81\xe2\x84\x8e"
"\x20\xce\x91\x74\x74\xce\xb1\xe2\x85\xbd\xce\xba\xc7\x83\xe2\x80\xbc";
- n.my_bonk.type = 31337;
+ n.my_bonk.type = 31337;
n.my_bonk.message = "I am a bonk... xor!";
cout << apache::thrift::ThriftJSONString(n) << endl << endl;
+
HolyMoley hm;
hm.big.push_back(ooe);
@@ -80,21 +82,21 @@
std::vector<Bonk> stage2;
hm.bonks["nothing"] = stage2;
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 1;
stage2.back().message = "Wait.";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 2;
stage2.back().message = "What?";
hm.bonks["something"] = stage2;
stage2.clear();
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 3;
stage2.back().message = "quoth";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 4;
stage2.back().message = "the raven";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 5;
stage2.back().message = "nevermore";
hm.bonks["poe"] = stage2;
@@ -104,6 +106,7 @@
boost::shared_ptr<TMemoryBuffer> buffer(new TMemoryBuffer());
boost::shared_ptr<TJSONProtocol> proto(new TJSONProtocol(buffer));
+
cout << "Testing ooe" << endl;
ooe.write(proto.get());
@@ -112,6 +115,7 @@
assert(ooe == ooe2);
+
cout << "Testing hm" << endl;
hm.write(proto.get());
@@ -125,10 +129,10 @@
assert(hm != hm2);
Doubles dub;
- dub.nan = HUGE_VAL / HUGE_VAL;
+ dub.nan = HUGE_VAL/HUGE_VAL;
dub.inf = HUGE_VAL;
dub.neginf = -HUGE_VAL;
- dub.repeating = 10.0 / 3.0;
+ dub.repeating = 10.0/3.0;
dub.big = 1E+305;
dub.tiny = 1E-305;
dub.zero = 0.0;
diff --git a/lib/cpp/test/OpenSSLManualInitTest.cpp b/lib/cpp/test/OpenSSLManualInitTest.cpp
index b04ed43..fbecbc3 100644
--- a/lib/cpp/test/OpenSSLManualInitTest.cpp
+++ b/lib/cpp/test/OpenSSLManualInitTest.cpp
@@ -69,7 +69,8 @@
boost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[]) {
THRIFT_UNUSED_VARIABLE(argc);
THRIFT_UNUSED_VARIABLE(argv);
- boost::unit_test::test_suite* suite = &boost::unit_test::framework::master_test_suite();
+ boost::unit_test::test_suite* suite =
+ &boost::unit_test::framework::master_test_suite();
suite->p_name.value = "OpenSSLManualInit";
suite->add(BOOST_TEST_CASE(test_openssl_availability));
diff --git a/lib/cpp/test/OptionalRequiredTest.cpp b/lib/cpp/test/OptionalRequiredTest.cpp
index 79fa697..44b6885 100644
--- a/lib/cpp/test/OptionalRequiredTest.cpp
+++ b/lib/cpp/test/OptionalRequiredTest.cpp
@@ -38,6 +38,7 @@
using namespace apache::thrift::transport;
using namespace apache::thrift::protocol;
+
/*
template<typename Struct>
void trywrite(const Struct& s, bool should_work) {
@@ -54,12 +55,13 @@
*/
template <typename Struct1, typename Struct2>
-void write_to_read(const Struct1& w, Struct2& r) {
+void write_to_read(const Struct1 & w, Struct2 & r) {
TBinaryProtocol protocol(boost::shared_ptr<TTransport>(new TMemoryBuffer));
w.write(&protocol);
r.read(&protocol);
}
+
int main() {
cout << "This old school struct should have three fields." << endl;
@@ -96,22 +98,22 @@
Simple s1, s2, s3;
s1.im_optional = 10;
assert(!s1.__isset.im_default);
- // assert(!s1.__isset.im_required); // Compile error.
+ //assert(!s1.__isset.im_required); // Compile error.
assert(!s1.__isset.im_optional);
write_to_read(s1, s2);
- assert(s2.__isset.im_default);
- // assert( s2.__isset.im_required); // Compile error.
+ assert( s2.__isset.im_default);
+ //assert( s2.__isset.im_required); // Compile error.
assert(!s2.__isset.im_optional);
assert(s3.im_optional == 0);
s1.__isset.im_optional = true;
write_to_read(s1, s3);
- assert(s3.__isset.im_default);
- // assert( s3.__isset.im_required); // Compile error.
- assert(s3.__isset.im_optional);
+ assert( s3.__isset.im_default);
+ //assert( s3.__isset.im_required); // Compile error.
+ assert( s3.__isset.im_optional);
assert(s3.im_optional == 10);
}
@@ -124,7 +126,7 @@
write_to_read(t2, t1);
write_to_read(t1, t2);
assert(!t1.__isset.im_default);
- assert(t2.__isset.im_optional);
+ assert( t2.__isset.im_optional);
assert(t1.im_default == t2.im_optional);
assert(t1.im_default == 0);
}
@@ -154,8 +156,8 @@
try {
write_to_read(t2, t3);
abort();
- } catch (const TProtocolException&) {
}
+ catch (const TProtocolException&) {}
write_to_read(t3, t2);
assert(t2.__isset.im_optional);
@@ -167,6 +169,7 @@
cout << ThriftDebugString(c) << endl;
}
+
{
Tricky1 t1;
Tricky2 t2;
@@ -191,12 +194,12 @@
assert(o1 == o2);
o1.__isset.im_str = o2.__isset.im_str = true;
assert(o1 == o2);
- map<int32_t, string> mymap;
+ map<int32_t,string> mymap;
mymap[1] = "bar";
mymap[2] = "baz";
- o1.im_big.push_back(map<int32_t, string>());
+ o1.im_big.push_back(map<int32_t,string>());
assert(o1 != o2);
- o2.im_big.push_back(map<int32_t, string>());
+ o2.im_big.push_back(map<int32_t,string>());
assert(o1 == o2);
o2.im_big.push_back(mymap);
assert(o1 != o2);
@@ -217,7 +220,7 @@
o3.im_big.push_back(mymap);
assert(o1 == o3);
- // cout << ThriftDebugString(o3) << endl;
+ //cout << ThriftDebugString(o3) << endl;
}
{
diff --git a/lib/cpp/test/RWMutexStarveTest.cpp b/lib/cpp/test/RWMutexStarveTest.cpp
index 32c1531..e6cccf2 100644
--- a/lib/cpp/test/RWMutexStarveTest.cpp
+++ b/lib/cpp/test/RWMutexStarveTest.cpp
@@ -33,13 +33,16 @@
using namespace apache::thrift::concurrency;
using namespace std;
-class Locker : public Runnable {
+class Locker : public Runnable
+{
protected:
- Locker(boost::shared_ptr<ReadWriteMutex> rwlock, bool writer)
- : rwlock_(rwlock), writer_(writer), started_(false), gotLock_(false), signaled_(false) {}
+ Locker(boost::shared_ptr<ReadWriteMutex> rwlock, bool writer) :
+ rwlock_(rwlock), writer_(writer),
+ started_(false), gotLock_(false), signaled_(false) { }
public:
- virtual void run() {
+ virtual void run()
+ {
started_ = true;
if (writer_) {
rwlock_->acquireWrite();
@@ -65,17 +68,20 @@
volatile bool signaled_;
};
-class Reader : public Locker {
+class Reader : public Locker
+{
public:
- Reader(boost::shared_ptr<ReadWriteMutex> rwlock) : Locker(rwlock, false) {}
+ Reader(boost::shared_ptr<ReadWriteMutex> rwlock) : Locker(rwlock, false) { }
};
-class Writer : public Locker {
+class Writer : public Locker
+{
public:
- Writer(boost::shared_ptr<ReadWriteMutex> rwlock) : Locker(rwlock, true) {}
+ Writer(boost::shared_ptr<ReadWriteMutex> rwlock) : Locker(rwlock, true) { }
};
-void test_starve(PosixThreadFactory::POLICY policy) {
+void test_starve(PosixThreadFactory::POLICY policy)
+{
// the man pages for pthread_wrlock_rdlock suggest that any OS guarantee about
// writer starvation may be influenced by the scheduling policy, so let's try
// all 3 policies to see if any of them work.
@@ -142,17 +148,20 @@
BOOST_CHECK_MESSAGE(success, "writer is starving");
}
-BOOST_AUTO_TEST_SUITE(RWMutexStarveTest)
+BOOST_AUTO_TEST_SUITE( RWMutexStarveTest )
-BOOST_AUTO_TEST_CASE(test_starve_other) {
+BOOST_AUTO_TEST_CASE( test_starve_other )
+{
test_starve(PosixThreadFactory::OTHER);
}
-BOOST_AUTO_TEST_CASE(test_starve_rr) {
+BOOST_AUTO_TEST_CASE( test_starve_rr )
+{
test_starve(PosixThreadFactory::ROUND_ROBIN);
}
-BOOST_AUTO_TEST_CASE(test_starve_fifo) {
+BOOST_AUTO_TEST_CASE( test_starve_fifo )
+{
test_starve(PosixThreadFactory::FIFO);
}
diff --git a/lib/cpp/test/RecursiveTest.cpp b/lib/cpp/test/RecursiveTest.cpp
index a74be91..24c0f7c 100644
--- a/lib/cpp/test/RecursiveTest.cpp
+++ b/lib/cpp/test/RecursiveTest.cpp
@@ -27,7 +27,7 @@
using apache::thrift::transport::TMemoryBuffer;
using apache::thrift::protocol::TBinaryProtocol;
-using boost::shared_ptr;
+ using boost::shared_ptr;
int main() {
shared_ptr<TMemoryBuffer> buf(new TMemoryBuffer());
@@ -71,4 +71,5 @@
assert(false);
} catch (const apache::thrift::protocol::TProtocolException& e) {
}
+
}
diff --git a/lib/cpp/test/SpecializationTest.cpp b/lib/cpp/test/SpecializationTest.cpp
index 856bdac..0bef12a 100644
--- a/lib/cpp/test/SpecializationTest.cpp
+++ b/lib/cpp/test/SpecializationTest.cpp
@@ -12,20 +12,20 @@
using namespace apache::thrift::protocol;
typedef TBinaryProtocolT<TMemoryBuffer> MyProtocol;
-// typedef TBinaryProtocolT<TTransport> MyProtocol;
+//typedef TBinaryProtocolT<TTransport> MyProtocol;
int main() {
OneOfEach ooe;
- ooe.im_true = true;
- ooe.im_false = false;
- ooe.a_bite = 0x7f;
+ ooe.im_true = true;
+ ooe.im_false = false;
+ ooe.a_bite = 0x7f;
ooe.integer16 = 27000;
- ooe.integer32 = 1 << 24;
+ ooe.integer32 = 1<<24;
ooe.integer64 = (uint64_t)6000 * 1000 * 1000;
ooe.double_precision = M_PI;
- ooe.some_characters = "JSON THIS! \"\1";
- ooe.zomg_unicode = "\xd7\n\a\t";
+ ooe.some_characters = "JSON THIS! \"\1";
+ ooe.zomg_unicode = "\xd7\n\a\t";
ooe.base64 = "\1\2\3\255";
Nesting n;
@@ -33,12 +33,12 @@
n.my_ooe.integer16 = 16;
n.my_ooe.integer32 = 32;
n.my_ooe.integer64 = 64;
- n.my_ooe.double_precision = (std::sqrt(5.0) + 1) / 2;
- n.my_ooe.some_characters = ":R (me going \"rrrr\")";
+ n.my_ooe.double_precision = (std::sqrt(5.0)+1)/2;
+ n.my_ooe.some_characters = ":R (me going \"rrrr\")";
n.my_ooe.zomg_unicode = "\xd3\x80\xe2\x85\xae\xce\x9d\x20"
"\xd0\x9d\xce\xbf\xe2\x85\xbf\xd0\xbe\xc9\xa1\xd0\xb3\xd0\xb0\xcf\x81\xe2\x84\x8e"
"\x20\xce\x91\x74\x74\xce\xb1\xe2\x85\xbd\xce\xba\xc7\x83\xe2\x80\xbc";
- n.my_bonk.type = 31337;
+ n.my_bonk.type = 31337;
n.my_bonk.message = "I am a bonk... xor!";
HolyMoley hm;
@@ -62,21 +62,21 @@
std::vector<Bonk> stage2;
hm.bonks["nothing"] = stage2;
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 1;
stage2.back().message = "Wait.";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 2;
stage2.back().message = "What?";
hm.bonks["something"] = stage2;
stage2.clear();
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 3;
stage2.back().message = "quoth";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 4;
stage2.back().message = "the raven";
- stage2.resize(stage2.size() + 1);
+ stage2.resize(stage2.size()+1);
stage2.back().type = 5;
stage2.back().message = "nevermore";
hm.bonks["poe"] = stage2;
@@ -92,6 +92,7 @@
assert(ooe == ooe2);
+
cout << "Testing hm" << endl;
hm.write(proto.get());
diff --git a/lib/cpp/test/TFDTransportTest.cpp b/lib/cpp/test/TFDTransportTest.cpp
index 9d2bd90..7b962d8 100644
--- a/lib/cpp/test/TFDTransportTest.cpp
+++ b/lib/cpp/test/TFDTransportTest.cpp
@@ -25,10 +25,13 @@
using apache::thrift::transport::TTransportException;
using apache::thrift::transport::TFDTransport;
-class DummyException : std::exception {};
+class DummyException : std::exception {
+};
int main() {
- { TFDTransport t(256, TFDTransport::NO_CLOSE_ON_DESTROY); }
+ {
+ TFDTransport t(256, TFDTransport::NO_CLOSE_ON_DESTROY);
+ }
try {
{
@@ -53,4 +56,5 @@
}
return 0;
+
}
diff --git a/lib/cpp/test/TFileTransportTest.cpp b/lib/cpp/test/TFileTransportTest.cpp
old mode 100644
new mode 100755
index 294c9a6..67e05e3
--- a/lib/cpp/test/TFileTransportTest.cpp
+++ b/lib/cpp/test/TFileTransportTest.cpp
@@ -41,6 +41,7 @@
class FsyncLog;
FsyncLog* fsync_log;
+
/**************************************************************************
* Helper code
**************************************************************************/
@@ -48,11 +49,11 @@
// Provide BOOST_WARN_LT() and BOOST_WARN_GT(), in case we're compiled
// with an older version of boost
#ifndef BOOST_WARN_LT
-#define BOOST_WARN_CMP(a, b, op, check_fn) \
- check_fn((a)op(b), \
- "check " BOOST_STRINGIZE(a) " " BOOST_STRINGIZE(op) " " BOOST_STRINGIZE( \
- b) " failed: " BOOST_STRINGIZE(a) "=" \
- << (a) << " " BOOST_STRINGIZE(b) "=" << (b))
+#define BOOST_WARN_CMP(a, b, op, check_fn) \
+ check_fn((a) op (b), \
+ "check " BOOST_STRINGIZE(a) " " BOOST_STRINGIZE(op) " " \
+ BOOST_STRINGIZE(b) " failed: " BOOST_STRINGIZE(a) "=" << (a) << \
+ " " BOOST_STRINGIZE(b) "=" << (b))
#define BOOST_WARN_LT(a, b) BOOST_WARN_CMP(a, b, <, BOOST_WARN_MESSAGE)
#define BOOST_WARN_GT(a, b) BOOST_WARN_CMP(a, b, >, BOOST_WARN_MESSAGE)
@@ -63,7 +64,7 @@
* Class to record calls to fsync
*/
class FsyncLog {
-public:
+ public:
struct FsyncCall {
struct timeval time;
int fd;
@@ -73,15 +74,17 @@
FsyncLog() {}
void fsync(int fd) {
- (void)fd;
+ (void) fd;
FsyncCall call;
gettimeofday(&call.time, NULL);
calls_.push_back(call);
}
- const CallList* getCalls() const { return &calls_; }
+ const CallList* getCalls() const {
+ return &calls_;
+ }
-private:
+ private:
CallList calls_;
};
@@ -89,7 +92,7 @@
* Helper class to clean up temporary files
*/
class TempFile {
-public:
+ public:
TempFile(const char* directory, const char* prefix) {
size_t path_len = strlen(directory) + strlen(prefix) + 8;
path_ = new char[path_len];
@@ -106,9 +109,13 @@
close();
}
- const char* getPath() const { return path_; }
+ const char* getPath() const {
+ return path_;
+ }
- int getFD() const { return fd_; }
+ int getFD() const {
+ return fd_;
+ }
void unlink() {
if (path_) {
@@ -127,7 +134,7 @@
fd_ = -1;
}
-private:
+ private:
char* path_;
int fd_;
};
@@ -135,7 +142,8 @@
// Use our own version of fsync() for testing.
// This returns immediately, so timing in test_destructor() isn't affected by
// waiting on the actual filesystem.
-extern "C" int fsync(int fd) {
+extern "C"
+int fsync(int fd) {
if (fsync_log) {
fsync_log->fsync(fd);
}
@@ -146,6 +154,7 @@
return (t2->tv_usec - t1->tv_usec) + (t2->tv_sec - t1->tv_sec) * 1000000;
}
+
/**************************************************************************
* Test cases
**************************************************************************/
@@ -212,7 +221,8 @@
/**
* Make sure setFlushMaxUs() is honored.
*/
-void test_flush_max_us_impl(uint32_t flush_us, uint32_t write_us, uint32_t test_us) {
+void test_flush_max_us_impl(uint32_t flush_us, uint32_t write_us,
+ uint32_t test_us) {
// TFileTransport only calls fsync() if data has been written,
// so make sure the write interval is smaller than the flush interval.
BOOST_WARN(write_us < flush_us);
@@ -267,10 +277,13 @@
const FsyncLog::CallList* calls = log.getCalls();
// We added 1 fsync call above.
// Make sure TFileTransport called fsync at least once
- BOOST_WARN_GE(calls->size(), static_cast<FsyncLog::CallList::size_type>(1));
+ BOOST_WARN_GE(calls->size(),
+ static_cast<FsyncLog::CallList::size_type>(1));
const struct timeval* prev_time = NULL;
- for (FsyncLog::CallList::const_iterator it = calls->begin(); it != calls->end(); ++it) {
+ for (FsyncLog::CallList::const_iterator it = calls->begin();
+ it != calls->end();
+ ++it) {
if (prev_time) {
int delta = time_diff(prev_time, &it->time);
BOOST_WARN_LT(delta, max_allowed_delta);
@@ -339,8 +352,11 @@
}
void parse_args(int argc, char* argv[]) {
- struct option long_opts[]
- = {{"help", false, NULL, 'h'}, {"tmp-dir", true, NULL, 't'}, {NULL, 0, NULL, 0}};
+ struct option long_opts[] = {
+ { "help", false, NULL, 'h' },
+ { "tmp-dir", true, NULL, 't' },
+ { NULL, 0, NULL, 0 }
+ };
while (true) {
optopt = 1;
@@ -350,25 +366,26 @@
}
switch (optchar) {
- case 't':
- tmp_dir = optarg;
- break;
- case 'h':
- print_usage(stdout, argv[0]);
- exit(0);
- case '?':
- exit(1);
- default:
- // Only happens if someone adds another option to the optarg string,
- // but doesn't update the switch statement to handle it.
- fprintf(stderr, "unknown option \"-%c\"\n", optchar);
- exit(1);
+ case 't':
+ tmp_dir = optarg;
+ break;
+ case 'h':
+ print_usage(stdout, argv[0]);
+ exit(0);
+ case '?':
+ exit(1);
+ default:
+ // Only happens if someone adds another option to the optarg string,
+ // but doesn't update the switch statement to handle it.
+ fprintf(stderr, "unknown option \"-%c\"\n", optchar);
+ exit(1);
}
}
}
boost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[]) {
- boost::unit_test::framework::master_test_suite().p_name.value = "TFileTransportTest";
+ boost::unit_test::framework::master_test_suite().p_name.value =
+ "TFileTransportTest";
// Parse arguments
parse_args(argc, argv);
diff --git a/lib/cpp/test/TMemoryBufferTest.cpp b/lib/cpp/test/TMemoryBufferTest.cpp
index cf49477..b81a667 100644
--- a/lib/cpp/test/TMemoryBufferTest.cpp
+++ b/lib/cpp/test/TMemoryBufferTest.cpp
@@ -25,84 +25,84 @@
#include <thrift/protocol/TBinaryProtocol.h>
#include "gen-cpp/ThriftTest_types.h"
-BOOST_AUTO_TEST_SUITE(TMemoryBufferTest)
+BOOST_AUTO_TEST_SUITE( TMemoryBufferTest )
-BOOST_AUTO_TEST_CASE(test_roundtrip) {
- using apache::thrift::transport::TMemoryBuffer;
- using apache::thrift::protocol::TBinaryProtocol;
- using boost::shared_ptr;
+BOOST_AUTO_TEST_CASE( test_roundtrip ) {
+ using apache::thrift::transport::TMemoryBuffer;
+ using apache::thrift::protocol::TBinaryProtocol;
+ using boost::shared_ptr;
- shared_ptr<TMemoryBuffer> strBuffer(new TMemoryBuffer());
- shared_ptr<TBinaryProtocol> binaryProtcol(new TBinaryProtocol(strBuffer));
+ shared_ptr<TMemoryBuffer> strBuffer(new TMemoryBuffer());
+ shared_ptr<TBinaryProtocol> binaryProtcol(new TBinaryProtocol(strBuffer));
- thrift::test::Xtruct a;
- a.i32_thing = 10;
- a.i64_thing = 30;
- a.string_thing = "holla back a";
+ thrift::test::Xtruct a;
+ a.i32_thing = 10;
+ a.i64_thing = 30;
+ a.string_thing ="holla back a";
- a.write(binaryProtcol.get());
- std::string serialized = strBuffer->getBufferAsString();
+ a.write(binaryProtcol.get());
+ std::string serialized = strBuffer->getBufferAsString();
- shared_ptr<TMemoryBuffer> strBuffer2(new TMemoryBuffer());
- shared_ptr<TBinaryProtocol> binaryProtcol2(new TBinaryProtocol(strBuffer2));
+ shared_ptr<TMemoryBuffer> strBuffer2(new TMemoryBuffer());
+ shared_ptr<TBinaryProtocol> binaryProtcol2(new TBinaryProtocol(strBuffer2));
- strBuffer2->resetBuffer((uint8_t*)serialized.data(), static_cast<uint32_t>(serialized.length()));
- thrift::test::Xtruct a2;
- a2.read(binaryProtcol2.get());
+ strBuffer2->resetBuffer((uint8_t*)serialized.data(), static_cast<uint32_t>(serialized.length()));
+ thrift::test::Xtruct a2;
+ a2.read(binaryProtcol2.get());
- assert(a == a2);
-}
-
-BOOST_AUTO_TEST_CASE(test_copy) {
- using apache::thrift::transport::TMemoryBuffer;
- using std::string;
- using std::cout;
- using std::endl;
-
- string* str1 = new string("abcd1234");
- const char* data1 = str1->data();
- TMemoryBuffer buf((uint8_t*)str1->data(),
- static_cast<uint32_t>(str1->length()),
- TMemoryBuffer::COPY);
- delete str1;
- string* str2 = new string("plsreuse");
- bool obj_reuse = (str1 == str2);
- bool dat_reuse = (data1 == str2->data());
- cout << "Object reuse: " << obj_reuse << " Data reuse: " << dat_reuse
- << ((obj_reuse && dat_reuse) ? " YAY!" : "") << endl;
- delete str2;
-
- string str3 = "wxyz", str4 = "6789";
- buf.readAppendToString(str3, 4);
- buf.readAppendToString(str4, INT_MAX);
-
- assert(str3 == "wxyzabcd");
- assert(str4 == "67891234");
-}
-
-BOOST_AUTO_TEST_CASE(test_exceptions) {
- using apache::thrift::transport::TTransportException;
- using apache::thrift::transport::TMemoryBuffer;
- using std::string;
-
- char data[] = "foo\0bar";
-
- TMemoryBuffer buf1((uint8_t*)data, 7, TMemoryBuffer::OBSERVE);
- string str = buf1.getBufferAsString();
- assert(str.length() == 7);
- buf1.resetBuffer();
- try {
- buf1.write((const uint8_t*)"foo", 3);
- assert(false);
- } catch (TTransportException&) {
+ assert(a == a2);
}
- TMemoryBuffer buf2((uint8_t*)data, 7, TMemoryBuffer::COPY);
- try {
- buf2.write((const uint8_t*)"bar", 3);
- } catch (TTransportException&) {
- assert(false);
+BOOST_AUTO_TEST_CASE( test_copy )
+ {
+ using apache::thrift::transport::TMemoryBuffer;
+ using std::string;
+ using std::cout;
+ using std::endl;
+
+ string* str1 = new string("abcd1234");
+ const char* data1 = str1->data();
+ TMemoryBuffer buf((uint8_t*)str1->data(), static_cast<uint32_t>(str1->length()), TMemoryBuffer::COPY);
+ delete str1;
+ string* str2 = new string("plsreuse");
+ bool obj_reuse = (str1 == str2);
+ bool dat_reuse = (data1 == str2->data());
+ cout << "Object reuse: " << obj_reuse << " Data reuse: " << dat_reuse
+ << ((obj_reuse && dat_reuse) ? " YAY!" : "") << endl;
+ delete str2;
+
+ string str3 = "wxyz", str4 = "6789";
+ buf.readAppendToString(str3, 4);
+ buf.readAppendToString(str4, INT_MAX);
+
+ assert(str3 == "wxyzabcd");
+ assert(str4 == "67891234");
}
-}
+
+BOOST_AUTO_TEST_CASE( test_exceptions )
+ {
+ using apache::thrift::transport::TTransportException;
+ using apache::thrift::transport::TMemoryBuffer;
+ using std::string;
+
+ char data[] = "foo\0bar";
+
+ TMemoryBuffer buf1((uint8_t*)data, 7, TMemoryBuffer::OBSERVE);
+ string str = buf1.getBufferAsString();
+ assert(str.length() == 7);
+ buf1.resetBuffer();
+ try {
+ buf1.write((const uint8_t*)"foo", 3);
+ assert(false);
+ } catch (TTransportException&) {}
+
+ TMemoryBuffer buf2((uint8_t*)data, 7, TMemoryBuffer::COPY);
+ try {
+ buf2.write((const uint8_t*)"bar", 3);
+ } catch (TTransportException&) {
+ assert(false);
+ }
+ }
BOOST_AUTO_TEST_SUITE_END()
+
diff --git a/lib/cpp/test/TPipedTransportTest.cpp b/lib/cpp/test/TPipedTransportTest.cpp
index 53a6fb5..7762f05 100644
--- a/lib/cpp/test/TPipedTransportTest.cpp
+++ b/lib/cpp/test/TPipedTransportTest.cpp
@@ -36,17 +36,18 @@
underlying->write((uint8_t*)"abcd", 4);
trans->readAll(buffer, 2);
- assert(string((char*)buffer, 2) == "ab");
+ assert( string((char*)buffer, 2) == "ab" );
trans->readEnd();
- assert(pipe->getBufferAsString() == "ab");
+ assert( pipe->getBufferAsString() == "ab" );
pipe->resetBuffer();
underlying->write((uint8_t*)"ef", 2);
trans->readAll(buffer, 2);
- assert(string((char*)buffer, 2) == "cd");
+ assert( string((char*)buffer, 2) == "cd" );
trans->readAll(buffer, 2);
- assert(string((char*)buffer, 2) == "ef");
+ assert( string((char*)buffer, 2) == "ef" );
trans->readEnd();
- assert(pipe->getBufferAsString() == "cdef");
+ assert( pipe->getBufferAsString() == "cdef" );
return 0;
+
}
diff --git a/lib/cpp/test/ThriftTest_extras.cpp b/lib/cpp/test/ThriftTest_extras.cpp
index af5606e..33f681f 100644
--- a/lib/cpp/test/ThriftTest_extras.cpp
+++ b/lib/cpp/test/ThriftTest_extras.cpp
@@ -22,12 +22,12 @@
#include <thrift/protocol/TDebugProtocol.h>
#include "gen-cpp/ThriftTest_types.h"
-namespace thrift {
-namespace test {
+
+namespace thrift { namespace test {
bool Insanity::operator<(thrift::test::Insanity const& other) const {
using apache::thrift::ThriftDebugString;
return ThriftDebugString(*this) < ThriftDebugString(other);
}
-}
-}
+
+}}
diff --git a/lib/cpp/test/ToStringTest.cpp b/lib/cpp/test/ToStringTest.cpp
index d204cb3..1a89c11 100644
--- a/lib/cpp/test/ToStringTest.cpp
+++ b/lib/cpp/test/ToStringTest.cpp
@@ -30,9 +30,9 @@
using apache::thrift::to_string;
-BOOST_AUTO_TEST_SUITE(ToStringTest)
+BOOST_AUTO_TEST_SUITE( ToStringTest )
-BOOST_AUTO_TEST_CASE(base_types_to_string) {
+BOOST_AUTO_TEST_CASE( base_types_to_string ) {
BOOST_CHECK_EQUAL(to_string(10), "10");
BOOST_CHECK_EQUAL(to_string(true), "1");
BOOST_CHECK_EQUAL(to_string('a'), "a");
@@ -40,91 +40,91 @@
BOOST_CHECK_EQUAL(to_string("abc"), "abc");
}
-BOOST_AUTO_TEST_CASE(empty_vector_to_string) {
+BOOST_AUTO_TEST_CASE( empty_vector_to_string ) {
std::vector<int> l;
BOOST_CHECK_EQUAL(to_string(l), "[]");
}
-BOOST_AUTO_TEST_CASE(single_item_vector_to_string) {
+BOOST_AUTO_TEST_CASE( single_item_vector_to_string ) {
std::vector<int> l;
l.push_back(100);
BOOST_CHECK_EQUAL(to_string(l), "[100]");
}
-BOOST_AUTO_TEST_CASE(multiple_item_vector_to_string) {
+BOOST_AUTO_TEST_CASE( multiple_item_vector_to_string ) {
std::vector<int> l;
l.push_back(100);
l.push_back(150);
BOOST_CHECK_EQUAL(to_string(l), "[100, 150]");
}
-BOOST_AUTO_TEST_CASE(empty_map_to_string) {
+BOOST_AUTO_TEST_CASE( empty_map_to_string ) {
std::map<int, std::string> m;
BOOST_CHECK_EQUAL(to_string(m), "{}");
}
-BOOST_AUTO_TEST_CASE(single_item_map_to_string) {
+BOOST_AUTO_TEST_CASE( single_item_map_to_string ) {
std::map<int, std::string> m;
m[12] = "abc";
BOOST_CHECK_EQUAL(to_string(m), "{12: abc}");
}
-BOOST_AUTO_TEST_CASE(multi_item_map_to_string) {
+BOOST_AUTO_TEST_CASE( multi_item_map_to_string ) {
std::map<int, std::string> m;
m[12] = "abc";
m[31] = "xyz";
BOOST_CHECK_EQUAL(to_string(m), "{12: abc, 31: xyz}");
}
-BOOST_AUTO_TEST_CASE(empty_set_to_string) {
+BOOST_AUTO_TEST_CASE( empty_set_to_string ) {
std::set<char> s;
BOOST_CHECK_EQUAL(to_string(s), "{}");
}
-BOOST_AUTO_TEST_CASE(single_item_set_to_string) {
+BOOST_AUTO_TEST_CASE( single_item_set_to_string ) {
std::set<char> s;
s.insert('c');
BOOST_CHECK_EQUAL(to_string(s), "{c}");
}
-BOOST_AUTO_TEST_CASE(multi_item_set_to_string) {
+BOOST_AUTO_TEST_CASE( multi_item_set_to_string ) {
std::set<char> s;
s.insert('a');
s.insert('z');
BOOST_CHECK_EQUAL(to_string(s), "{a, z}");
}
-BOOST_AUTO_TEST_CASE(generated_empty_object_to_string) {
+BOOST_AUTO_TEST_CASE( generated_empty_object_to_string ) {
thrift::test::EmptyStruct e;
BOOST_CHECK_EQUAL(to_string(e), "EmptyStruct()");
}
-BOOST_AUTO_TEST_CASE(generated_single_basic_field_object_to_string) {
+BOOST_AUTO_TEST_CASE( generated_single_basic_field_object_to_string ) {
thrift::test::StructA a;
a.__set_s("abcd");
BOOST_CHECK_EQUAL(to_string(a), "StructA(s=abcd)");
}
-BOOST_AUTO_TEST_CASE(generated_two_basic_fields_object_to_string) {
+BOOST_AUTO_TEST_CASE( generated_two_basic_fields_object_to_string ) {
thrift::test::Bonk a;
a.__set_message("abcd");
a.__set_type(1234);
BOOST_CHECK_EQUAL(to_string(a), "Bonk(message=abcd, type=1234)");
}
-BOOST_AUTO_TEST_CASE(generated_optional_fields_object_to_string) {
+BOOST_AUTO_TEST_CASE( generated_optional_fields_object_to_string ) {
thrift::test::Tricky2 a;
BOOST_CHECK_EQUAL(to_string(a), "Tricky2(im_optional=<null>)");
a.__set_im_optional(123);
BOOST_CHECK_EQUAL(to_string(a), "Tricky2(im_optional=123)");
}
-BOOST_AUTO_TEST_CASE(generated_nested_object_to_string) {
+BOOST_AUTO_TEST_CASE( generated_nested_object_to_string ) {
thrift::test::OneField a;
BOOST_CHECK_EQUAL(to_string(a), "OneField(field=EmptyStruct())");
}
-BOOST_AUTO_TEST_CASE(generated_nested_list_object_to_string) {
+BOOST_AUTO_TEST_CASE( generated_nested_list_object_to_string ) {
thrift::test::ListBonks l;
l.bonk.assign(2, thrift::test::Bonk());
l.bonk[0].__set_message("a");
diff --git a/lib/cpp/test/TransportTest.cpp b/lib/cpp/test/TransportTest.cpp
old mode 100644
new mode 100755
index 0305732..c1cb976
--- a/lib/cpp/test/TransportTest.cpp
+++ b/lib/cpp/test/TransportTest.cpp
@@ -36,9 +36,10 @@
#include <thrift/concurrency/FunctionRunner.h>
#if _WIN32
-#include <thrift/windows/TWinsockSingleton.h>
+ #include <thrift/windows/TWinsockSingleton.h>
#endif
+
using namespace apache::thrift::transport;
static boost::mt19937 rng;
@@ -48,14 +49,14 @@
}
class SizeGenerator {
-public:
+ public:
virtual ~SizeGenerator() {}
virtual uint32_t nextSize() = 0;
virtual std::string describe() const = 0;
};
class ConstantSizeGenerator : public SizeGenerator {
-public:
+ public:
ConstantSizeGenerator(uint32_t value) : value_(value) {}
uint32_t nextSize() { return value_; }
std::string describe() const {
@@ -64,14 +65,14 @@
return desc.str();
}
-private:
+ private:
uint32_t value_;
};
class RandomSizeGenerator : public SizeGenerator {
-public:
- RandomSizeGenerator(uint32_t min, uint32_t max)
- : generator_(rng, boost::uniform_int<int>(min, max)) {}
+ public:
+ RandomSizeGenerator(uint32_t min, uint32_t max) :
+ generator_(rng, boost::uniform_int<int>(min, max)) {}
uint32_t nextSize() { return generator_(); }
@@ -84,8 +85,9 @@
uint32_t getMin() const { return (generator_.distribution().min)(); }
uint32_t getMax() const { return (generator_.distribution().max)(); }
-private:
- boost::variate_generator<boost::mt19937&, boost::uniform_int<int> > generator_;
+ private:
+ boost::variate_generator< boost::mt19937&, boost::uniform_int<int> >
+ generator_;
};
/**
@@ -96,15 +98,16 @@
* to make a copy of the generator to bind it to the test function.)
*/
class GenericSizeGenerator : public SizeGenerator {
-public:
- GenericSizeGenerator(uint32_t value) : generator_(new ConstantSizeGenerator(value)) {}
- GenericSizeGenerator(uint32_t min, uint32_t max)
- : generator_(new RandomSizeGenerator(min, max)) {}
+ public:
+ GenericSizeGenerator(uint32_t value) :
+ generator_(new ConstantSizeGenerator(value)) {}
+ GenericSizeGenerator(uint32_t min, uint32_t max) :
+ generator_(new RandomSizeGenerator(min, max)) {}
uint32_t nextSize() { return generator_->nextSize(); }
std::string describe() const { return generator_->describe(); }
-private:
+ private:
boost::shared_ptr<SizeGenerator> generator_;
};
@@ -122,7 +125,7 @@
*/
template <class Transport_>
class CoupledTransports {
-public:
+ public:
virtual ~CoupledTransports() {}
typedef Transport_ TransportType;
@@ -131,17 +134,18 @@
boost::shared_ptr<Transport_> in;
boost::shared_ptr<Transport_> out;
-private:
+ private:
CoupledTransports(const CoupledTransports&);
- CoupledTransports& operator=(const CoupledTransports&);
+ CoupledTransports &operator=(const CoupledTransports&);
};
/**
* Coupled TMemoryBuffers
*/
class CoupledMemoryBuffers : public CoupledTransports<TMemoryBuffer> {
-public:
- CoupledMemoryBuffers() : buf(new TMemoryBuffer) {
+ public:
+ CoupledMemoryBuffers() :
+ buf(new TMemoryBuffer) {
in = buf;
out = buf;
}
@@ -155,7 +159,7 @@
*/
template <class WrapperTransport_, class InnerCoupledTransports_>
class CoupledWrapperTransportsT : public CoupledTransports<WrapperTransport_> {
-public:
+ public:
CoupledWrapperTransportsT() {
if (inner_.in) {
this->in.reset(new WrapperTransport_(inner_.in));
@@ -172,27 +176,34 @@
* Coupled TBufferedTransports.
*/
template <class InnerTransport_>
-class CoupledBufferedTransportsT
- : public CoupledWrapperTransportsT<TBufferedTransport, InnerTransport_> {};
+class CoupledBufferedTransportsT :
+ public CoupledWrapperTransportsT<TBufferedTransport, InnerTransport_> {
+};
-typedef CoupledBufferedTransportsT<CoupledMemoryBuffers> CoupledBufferedTransports;
+typedef CoupledBufferedTransportsT<CoupledMemoryBuffers>
+ CoupledBufferedTransports;
/**
* Coupled TFramedTransports.
*/
template <class InnerTransport_>
-class CoupledFramedTransportsT
- : public CoupledWrapperTransportsT<TFramedTransport, InnerTransport_> {};
+class CoupledFramedTransportsT :
+ public CoupledWrapperTransportsT<TFramedTransport, InnerTransport_> {
+};
-typedef CoupledFramedTransportsT<CoupledMemoryBuffers> CoupledFramedTransports;
+typedef CoupledFramedTransportsT<CoupledMemoryBuffers>
+ CoupledFramedTransports;
/**
* Coupled TZlibTransports.
*/
template <class InnerTransport_>
-class CoupledZlibTransportsT : public CoupledWrapperTransportsT<TZlibTransport, InnerTransport_> {};
+class CoupledZlibTransportsT :
+ public CoupledWrapperTransportsT<TZlibTransport, InnerTransport_> {
+};
-typedef CoupledZlibTransportsT<CoupledMemoryBuffers> CoupledZlibTransports;
+typedef CoupledZlibTransportsT<CoupledMemoryBuffers>
+ CoupledZlibTransports;
#ifndef _WIN32
// FD transport doesn't make much sense on Windows.
@@ -200,7 +211,7 @@
* Coupled TFDTransports.
*/
class CoupledFDTransports : public CoupledTransports<TFDTransport> {
-public:
+ public:
CoupledFDTransports() {
int pipes[2];
@@ -218,7 +229,7 @@
* Coupled TSockets
*/
class CoupledSocketTransports : public CoupledTransports<TSocket> {
-public:
+ public:
CoupledSocketTransports() {
THRIFT_SOCKET sockets[2] = {0};
if (THRIFT_SOCKETPAIR(PF_UNIX, SOCK_STREAM, 0, sockets) != 0) {
@@ -231,34 +242,39 @@
}
};
-// These could be made to work on Windows, but I don't care enough to make it happen
+//These could be made to work on Windows, but I don't care enough to make it happen
#ifndef _WIN32
/**
* Coupled TFileTransports
*/
class CoupledFileTransports : public CoupledTransports<TFileTransport> {
-public:
+ public:
CoupledFileTransports() {
#ifndef _WIN32
const char* tmp_dir = "/tmp";
-#define FILENAME_SUFFIX "/thrift.transport_test"
+ #define FILENAME_SUFFIX "/thrift.transport_test"
#else
const char* tmp_dir = getenv("TMP");
-#define FILENAME_SUFFIX "\\thrift.transport_test"
+ #define FILENAME_SUFFIX "\\thrift.transport_test"
#endif
// Create a temporary file to use
filename.resize(strlen(tmp_dir) + strlen(FILENAME_SUFFIX));
- THRIFT_SNPRINTF(&filename[0], filename.size(), "%s" FILENAME_SUFFIX, tmp_dir);
-#undef FILENAME_SUFFIX
+ THRIFT_SNPRINTF(&filename[0], filename.size(),
+ "%s" FILENAME_SUFFIX, tmp_dir);
+ #undef FILENAME_SUFFIX
- { std::ofstream dummy_creation(filename.c_str(), std::ofstream::trunc); }
+ {
+ std::ofstream dummy_creation(filename.c_str(), std::ofstream::trunc);
+ }
in.reset(new TFileTransport(filename, true));
out.reset(new TFileTransport(filename));
}
- ~CoupledFileTransports() { remove(filename.c_str()); }
+ ~CoupledFileTransports() {
+ remove(filename.c_str());
+ }
std::string filename;
};
@@ -274,7 +290,7 @@
*/
template <class CoupledTransports_>
class CoupledTTransports : public CoupledTransports<TTransport> {
-public:
+ public:
CoupledTTransports() : transports() {
in = transports.in;
out = transports.out;
@@ -292,7 +308,7 @@
*/
template <class CoupledTransports_>
class CoupledBufferBases : public CoupledTransports<TBufferBase> {
-public:
+ public:
CoupledBufferBases() : transports() {
in = transports.in;
out = transports.out;
@@ -316,8 +332,12 @@
**************************************************************************/
struct TriggerInfo {
- TriggerInfo(int seconds, const boost::shared_ptr<TTransport>& transport, uint32_t writeLength)
- : timeoutSeconds(seconds), transport(transport), writeLength(writeLength), next(NULL) {}
+ TriggerInfo(int seconds, const boost::shared_ptr<TTransport>& transport,
+ uint32_t writeLength) :
+ timeoutSeconds(seconds),
+ transport(transport),
+ writeLength(writeLength),
+ next(NULL) {}
int timeoutSeconds;
boost::shared_ptr<TTransport> transport;
@@ -331,7 +351,7 @@
bool g_teardown = false;
void alarm_handler() {
- TriggerInfo* info = NULL;
+ TriggerInfo *info = NULL;
{
apache::thrift::concurrency::Synchronized s(g_alarm_monitor);
// The alarm timed out, which almost certainly means we're stuck
@@ -363,26 +383,26 @@
}
void alarm_handler_wrapper() {
- int64_t timeout = 0; // timeout of 0 means wait forever
- while (true) {
+ int64_t timeout = 0; //timeout of 0 means wait forever
+ while(true) {
bool fireHandler = false;
{
apache::thrift::concurrency::Synchronized s(g_alarm_monitor);
- if (g_teardown)
- return;
- // calculate timeout
+ if(g_teardown)
+ return;
+ //calculate timeout
if (g_triggerInfo == NULL) {
timeout = 0;
} else {
- timeout = g_triggerInfo->timeoutSeconds * 1000;
+ timeout = g_triggerInfo->timeoutSeconds * 1000;
}
int waitResult = g_alarm_monitor.waitForTimeRelative(timeout);
- if (waitResult == THRIFT_ETIMEDOUT)
+ if(waitResult == THRIFT_ETIMEDOUT)
fireHandler = true;
}
- if (fireHandler)
- alarm_handler(); // calling outside the lock
+ if(fireHandler)
+ alarm_handler(); //calling outside the lock
}
}
@@ -395,7 +415,7 @@
* to the end.)
*/
void add_trigger(unsigned int seconds,
- const boost::shared_ptr<TTransport>& transport,
+ const boost::shared_ptr<TTransport> &transport,
uint32_t write_len) {
TriggerInfo* info = new TriggerInfo(seconds, transport, write_len);
{
@@ -417,7 +437,7 @@
}
void clear_triggers() {
- TriggerInfo* info = NULL;
+ TriggerInfo *info = NULL;
{
apache::thrift::concurrency::Synchronized s(g_alarm_monitor);
@@ -435,7 +455,7 @@
}
void set_trigger(unsigned int seconds,
- const boost::shared_ptr<TTransport>& transport,
+ const boost::shared_ptr<TTransport> &transport,
uint32_t write_len) {
clear_triggers();
add_trigger(seconds, transport, write_len);
@@ -479,8 +499,10 @@
BOOST_REQUIRE(transports.in != NULL);
BOOST_REQUIRE(transports.out != NULL);
- boost::shared_array<uint8_t> wbuf = boost::shared_array<uint8_t>(new uint8_t[totalSize]);
- boost::shared_array<uint8_t> rbuf = boost::shared_array<uint8_t>(new uint8_t[totalSize]);
+ boost::shared_array<uint8_t> wbuf =
+ boost::shared_array<uint8_t>(new uint8_t[totalSize]);
+ boost::shared_array<uint8_t> rbuf =
+ boost::shared_array<uint8_t>(new uint8_t[totalSize]);
// store some data in wbuf
for (uint32_t n = 0; n < totalSize; ++n) {
@@ -500,7 +522,8 @@
// Make sure (total_written - total_read) + wchunk_size
// is less than maxOutstanding
- if (maxOutstanding > 0 && wchunk_size > maxOutstanding - (total_written - total_read)) {
+ if (maxOutstanding > 0 &&
+ wchunk_size > maxOutstanding - (total_written - total_read)) {
wchunk_size = maxOutstanding - (total_written - total_read);
}
@@ -514,7 +537,8 @@
try {
transports.out->write(wbuf.get() + total_written, write_size);
- } catch (TTransportException& te) {
+ }
+ catch (TTransportException & te) {
if (te.getType() == TTransportException::TIMED_OUT)
break;
throw te;
@@ -548,15 +572,17 @@
try {
bytes_read = transports.in->read(rbuf.get() + total_read, read_size);
} catch (TTransportException& e) {
- BOOST_FAIL("read(pos=" << total_read << ", size=" << read_size << ") threw exception \""
- << e.what() << "\"; written so far: " << total_written << " / "
- << totalSize << " bytes");
+ BOOST_FAIL("read(pos=" << total_read << ", size=" << read_size <<
+ ") threw exception \"" << e.what() <<
+ "\"; written so far: " << total_written << " / " <<
+ totalSize << " bytes");
}
BOOST_REQUIRE_MESSAGE(bytes_read > 0,
- "read(pos=" << total_read << ", size=" << read_size << ") returned "
- << bytes_read << "; written so far: " << total_written
- << " / " << totalSize << " bytes");
+ "read(pos=" << total_read << ", size=" <<
+ read_size << ") returned " << bytes_read <<
+ "; written so far: " << total_written << " / " <<
+ totalSize << " bytes");
chunk_read += bytes_read;
total_read += bytes_read;
}
@@ -566,6 +592,7 @@
BOOST_CHECK_EQUAL(memcmp(rbuf.get(), wbuf.get(), totalSize), 0);
}
+
template <class CoupledTransports>
void test_read_part_available() {
CoupledTransports transports;
@@ -582,8 +609,8 @@
transports.out->flush();
set_trigger(3, transports.out, 1);
uint32_t bytes_read = transports.in->read(read_buf, 10);
- BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int)0);
- BOOST_CHECK_EQUAL(bytes_read, (uint32_t)9);
+ BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int) 0);
+ BOOST_CHECK_EQUAL(bytes_read, (uint32_t) 9);
clear_triggers();
}
@@ -649,7 +676,7 @@
// Now read 4 bytes, so that we are partway through the written data.
uint32_t bytes_read = transports.in->read(read_buf, 4);
- BOOST_CHECK_EQUAL(bytes_read, (uint32_t)4);
+ BOOST_CHECK_EQUAL(bytes_read, (uint32_t) 4);
// Now attempt to read 10 bytes. Only 9 more are available.
//
@@ -662,13 +689,13 @@
while (total_read < 9) {
set_trigger(3, transports.out, 1);
bytes_read = transports.in->read(read_buf, 10);
- BOOST_REQUIRE_EQUAL(g_numTriggersFired, (unsigned int)0);
- BOOST_REQUIRE_GT(bytes_read, (uint32_t)0);
+ BOOST_REQUIRE_EQUAL(g_numTriggersFired, (unsigned int) 0);
+ BOOST_REQUIRE_GT(bytes_read, (uint32_t) 0);
total_read += bytes_read;
- BOOST_REQUIRE_LE(total_read, (uint32_t)9);
+ BOOST_REQUIRE_LE(total_read, (uint32_t) 9);
}
- BOOST_CHECK_EQUAL(total_read, (uint32_t)9);
+ BOOST_CHECK_EQUAL(total_read, (uint32_t) 9);
clear_triggers();
}
@@ -690,7 +717,7 @@
set_trigger(3, transports.out, 1);
uint32_t borrow_len = 10;
const uint8_t* borrowed_buf = transports.in->borrow(read_buf, &borrow_len);
- BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int)0);
+ BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int) 0);
BOOST_CHECK(borrowed_buf == NULL);
clear_triggers();
@@ -716,11 +743,11 @@
add_trigger(1, transports.out, 8);
uint32_t bytes_read = transports.in->read(read_buf, 10);
if (bytes_read == 0) {
- BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int)0);
+ BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int) 0);
clear_triggers();
} else {
- BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int)1);
- BOOST_CHECK_EQUAL(bytes_read, (uint32_t)2);
+ BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int) 1);
+ BOOST_CHECK_EQUAL(bytes_read, (uint32_t) 2);
}
clear_triggers();
@@ -740,7 +767,7 @@
uint32_t borrow_len = 10;
const uint8_t* borrowed_buf = transports.in->borrow(NULL, &borrow_len);
BOOST_CHECK(borrowed_buf == NULL);
- BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int)0);
+ BOOST_CHECK_EQUAL(g_numTriggersFired, (unsigned int) 0);
clear_triggers();
}
@@ -761,40 +788,47 @@
* is compiler-dependent. gcc returns mangled names.)
**************************************************************************/
-#define ADD_TEST_RW(CoupledTransports, totalSize, ...) \
- addTestRW<CoupledTransports>(BOOST_STRINGIZE(CoupledTransports), totalSize, ##__VA_ARGS__);
+#define ADD_TEST_RW(CoupledTransports, totalSize, ...) \
+ addTestRW< CoupledTransports >(BOOST_STRINGIZE(CoupledTransports), \
+ totalSize, ## __VA_ARGS__);
-#define TEST_RW(CoupledTransports, totalSize, ...) \
- do { \
- /* Add the test as specified, to test the non-virtual function calls */ \
- ADD_TEST_RW(CoupledTransports, totalSize, ##__VA_ARGS__); \
- /* \
- * Also test using the transport as a TTransport*, to test \
- * the read_virt()/write_virt() calls \
- */ \
- ADD_TEST_RW(CoupledTTransports<CoupledTransports>, totalSize, ##__VA_ARGS__); \
- /* Test wrapping the transport with TBufferedTransport */ \
- ADD_TEST_RW(CoupledBufferedTransportsT<CoupledTransports>, totalSize, ##__VA_ARGS__); \
- /* Test wrapping the transport with TFramedTransports */ \
- ADD_TEST_RW(CoupledFramedTransportsT<CoupledTransports>, totalSize, ##__VA_ARGS__); \
- /* Test wrapping the transport with TZlibTransport */ \
- ADD_TEST_RW(CoupledZlibTransportsT<CoupledTransports>, totalSize, ##__VA_ARGS__); \
+#define TEST_RW(CoupledTransports, totalSize, ...) \
+ do { \
+ /* Add the test as specified, to test the non-virtual function calls */ \
+ ADD_TEST_RW(CoupledTransports, totalSize, ## __VA_ARGS__); \
+ /* \
+ * Also test using the transport as a TTransport*, to test \
+ * the read_virt()/write_virt() calls \
+ */ \
+ ADD_TEST_RW(CoupledTTransports<CoupledTransports>, \
+ totalSize, ## __VA_ARGS__); \
+ /* Test wrapping the transport with TBufferedTransport */ \
+ ADD_TEST_RW(CoupledBufferedTransportsT<CoupledTransports>, \
+ totalSize, ## __VA_ARGS__); \
+ /* Test wrapping the transport with TFramedTransports */ \
+ ADD_TEST_RW(CoupledFramedTransportsT<CoupledTransports>, \
+ totalSize, ## __VA_ARGS__); \
+ /* Test wrapping the transport with TZlibTransport */ \
+ ADD_TEST_RW(CoupledZlibTransportsT<CoupledTransports>, \
+ totalSize, ## __VA_ARGS__); \
} while (0)
-#define ADD_TEST_BLOCKING(CoupledTransports) \
- addTestBlocking<CoupledTransports>(BOOST_STRINGIZE(CoupledTransports));
+#define ADD_TEST_BLOCKING(CoupledTransports) \
+ addTestBlocking< CoupledTransports >(BOOST_STRINGIZE(CoupledTransports));
-#define TEST_BLOCKING_BEHAVIOR(CoupledTransports) \
- ADD_TEST_BLOCKING(CoupledTransports); \
- ADD_TEST_BLOCKING(CoupledTTransports<CoupledTransports>); \
- ADD_TEST_BLOCKING(CoupledBufferedTransportsT<CoupledTransports>); \
- ADD_TEST_BLOCKING(CoupledFramedTransportsT<CoupledTransports>); \
+#define TEST_BLOCKING_BEHAVIOR(CoupledTransports) \
+ ADD_TEST_BLOCKING(CoupledTransports); \
+ ADD_TEST_BLOCKING(CoupledTTransports<CoupledTransports>); \
+ ADD_TEST_BLOCKING(CoupledBufferedTransportsT<CoupledTransports>); \
+ ADD_TEST_BLOCKING(CoupledFramedTransportsT<CoupledTransports>); \
ADD_TEST_BLOCKING(CoupledZlibTransportsT<CoupledTransports>);
class TransportTestGen {
-public:
- TransportTestGen(boost::unit_test::test_suite* suite, float sizeMultiplier)
- : suite_(suite), sizeMultiplier_(sizeMultiplier) {}
+ public:
+ TransportTestGen(boost::unit_test::test_suite* suite,
+ float sizeMultiplier) :
+ suite_(suite),
+ sizeMultiplier_(sizeMultiplier) {}
void generate() {
GenericSizeGenerator rand4k(1, 4096);
@@ -805,15 +839,15 @@
*/
// TMemoryBuffer tests
- TEST_RW(CoupledMemoryBuffers, 1024 * 1024, 0, 0);
- TEST_RW(CoupledMemoryBuffers, 1024 * 256, rand4k, rand4k);
- TEST_RW(CoupledMemoryBuffers, 1024 * 256, 167, 163);
- TEST_RW(CoupledMemoryBuffers, 1024 * 16, 1, 1);
+ TEST_RW(CoupledMemoryBuffers, 1024*1024, 0, 0);
+ TEST_RW(CoupledMemoryBuffers, 1024*256, rand4k, rand4k);
+ TEST_RW(CoupledMemoryBuffers, 1024*256, 167, 163);
+ TEST_RW(CoupledMemoryBuffers, 1024*16, 1, 1);
- TEST_RW(CoupledMemoryBuffers, 1024 * 256, 0, 0, rand4k, rand4k);
- TEST_RW(CoupledMemoryBuffers, 1024 * 256, rand4k, rand4k, rand4k, rand4k);
- TEST_RW(CoupledMemoryBuffers, 1024 * 256, 167, 163, rand4k, rand4k);
- TEST_RW(CoupledMemoryBuffers, 1024 * 16, 1, 1, rand4k, rand4k);
+ TEST_RW(CoupledMemoryBuffers, 1024*256, 0, 0, rand4k, rand4k);
+ TEST_RW(CoupledMemoryBuffers, 1024*256, rand4k, rand4k, rand4k, rand4k);
+ TEST_RW(CoupledMemoryBuffers, 1024*256, 167, 163, rand4k, rand4k);
+ TEST_RW(CoupledMemoryBuffers, 1024*16, 1, 1, rand4k, rand4k);
TEST_BLOCKING_BEHAVIOR(CoupledMemoryBuffers);
@@ -822,57 +856,68 @@
// Since CoupledFDTransports tests with a pipe, writes will block
// if there is too much outstanding unread data in the pipe.
uint32_t fd_max_outstanding = 4096;
- TEST_RW(CoupledFDTransports, 1024 * 1024, 0, 0, 0, 0, fd_max_outstanding);
- TEST_RW(CoupledFDTransports, 1024 * 256, rand4k, rand4k, 0, 0, fd_max_outstanding);
- TEST_RW(CoupledFDTransports, 1024 * 256, 167, 163, 0, 0, fd_max_outstanding);
- TEST_RW(CoupledFDTransports, 1024 * 16, 1, 1, 0, 0, fd_max_outstanding);
+ TEST_RW(CoupledFDTransports, 1024*1024, 0, 0,
+ 0, 0, fd_max_outstanding);
+ TEST_RW(CoupledFDTransports, 1024*256, rand4k, rand4k,
+ 0, 0, fd_max_outstanding);
+ TEST_RW(CoupledFDTransports, 1024*256, 167, 163,
+ 0, 0, fd_max_outstanding);
+ TEST_RW(CoupledFDTransports, 1024*16, 1, 1,
+ 0, 0, fd_max_outstanding);
- TEST_RW(CoupledFDTransports, 1024 * 256, 0, 0, rand4k, rand4k, fd_max_outstanding);
- TEST_RW(CoupledFDTransports, 1024 * 256, rand4k, rand4k, rand4k, rand4k, fd_max_outstanding);
- TEST_RW(CoupledFDTransports, 1024 * 256, 167, 163, rand4k, rand4k, fd_max_outstanding);
- TEST_RW(CoupledFDTransports, 1024 * 16, 1, 1, rand4k, rand4k, fd_max_outstanding);
+ TEST_RW(CoupledFDTransports, 1024*256, 0, 0,
+ rand4k, rand4k, fd_max_outstanding);
+ TEST_RW(CoupledFDTransports, 1024*256, rand4k, rand4k,
+ rand4k, rand4k, fd_max_outstanding);
+ TEST_RW(CoupledFDTransports, 1024*256, 167, 163,
+ rand4k, rand4k, fd_max_outstanding);
+ TEST_RW(CoupledFDTransports, 1024*16, 1, 1,
+ rand4k, rand4k, fd_max_outstanding);
TEST_BLOCKING_BEHAVIOR(CoupledFDTransports);
#endif //_WIN32
// TSocket tests
uint32_t socket_max_outstanding = 4096;
- TEST_RW(CoupledSocketTransports, 1024 * 1024, 0, 0, 0, 0, socket_max_outstanding);
- TEST_RW(CoupledSocketTransports, 1024 * 256, rand4k, rand4k, 0, 0, socket_max_outstanding);
- TEST_RW(CoupledSocketTransports, 1024 * 256, 167, 163, 0, 0, socket_max_outstanding);
+ TEST_RW(CoupledSocketTransports, 1024*1024, 0, 0,
+ 0, 0, socket_max_outstanding);
+ TEST_RW(CoupledSocketTransports, 1024*256, rand4k, rand4k,
+ 0, 0, socket_max_outstanding);
+ TEST_RW(CoupledSocketTransports, 1024*256, 167, 163,
+ 0, 0, socket_max_outstanding);
// Doh. Apparently writing to a socket has some additional overhead for
// each send() call. If we have more than ~400 outstanding 1-byte write
// requests, additional send() calls start blocking.
- TEST_RW(CoupledSocketTransports, 1024 * 16, 1, 1, 0, 0, socket_max_outstanding);
- TEST_RW(CoupledSocketTransports, 1024 * 256, 0, 0, rand4k, rand4k, socket_max_outstanding);
- TEST_RW(CoupledSocketTransports,
- 1024 * 256,
- rand4k,
- rand4k,
- rand4k,
- rand4k,
- socket_max_outstanding);
- TEST_RW(CoupledSocketTransports, 1024 * 256, 167, 163, rand4k, rand4k, socket_max_outstanding);
- TEST_RW(CoupledSocketTransports, 1024 * 16, 1, 1, rand4k, rand4k, socket_max_outstanding);
+ TEST_RW(CoupledSocketTransports, 1024*16, 1, 1,
+ 0, 0, socket_max_outstanding);
+ TEST_RW(CoupledSocketTransports, 1024*256, 0, 0,
+ rand4k, rand4k, socket_max_outstanding);
+ TEST_RW(CoupledSocketTransports, 1024*256, rand4k, rand4k,
+ rand4k, rand4k, socket_max_outstanding);
+ TEST_RW(CoupledSocketTransports, 1024*256, 167, 163,
+ rand4k, rand4k, socket_max_outstanding);
+ TEST_RW(CoupledSocketTransports, 1024*16, 1, 1,
+ rand4k, rand4k, socket_max_outstanding);
TEST_BLOCKING_BEHAVIOR(CoupledSocketTransports);
-// These could be made to work on Windows, but I don't care enough to make it happen
+//These could be made to work on Windows, but I don't care enough to make it happen
#ifndef _WIN32
// TFileTransport tests
// We use smaller buffer sizes here, since TFileTransport is fairly slow.
//
// TFileTransport can't write more than 16MB at once
- uint32_t max_write_at_once = 1024 * 1024 * 16 - 4;
- TEST_RW(CoupledFileTransports, 1024 * 1024, max_write_at_once, 0);
- TEST_RW(CoupledFileTransports, 1024 * 128, rand4k, rand4k);
- TEST_RW(CoupledFileTransports, 1024 * 128, 167, 163);
- TEST_RW(CoupledFileTransports, 1024 * 2, 1, 1);
+ uint32_t max_write_at_once = 1024*1024*16 - 4;
+ TEST_RW(CoupledFileTransports, 1024*1024, max_write_at_once, 0);
+ TEST_RW(CoupledFileTransports, 1024*128, rand4k, rand4k);
+ TEST_RW(CoupledFileTransports, 1024*128, 167, 163);
+ TEST_RW(CoupledFileTransports, 1024*2, 1, 1);
- TEST_RW(CoupledFileTransports, 1024 * 64, 0, 0, rand4k, rand4k);
- TEST_RW(CoupledFileTransports, 1024 * 64, rand4k, rand4k, rand4k, rand4k);
- TEST_RW(CoupledFileTransports, 1024 * 64, 167, 163, rand4k, rand4k);
- TEST_RW(CoupledFileTransports, 1024 * 2, 1, 1, rand4k, rand4k);
+ TEST_RW(CoupledFileTransports, 1024*64, 0, 0, rand4k, rand4k);
+ TEST_RW(CoupledFileTransports, 1024*64,
+ rand4k, rand4k, rand4k, rand4k);
+ TEST_RW(CoupledFileTransports, 1024*64, 167, 163, rand4k, rand4k);
+ TEST_RW(CoupledFileTransports, 1024*2, 1, 1, rand4k, rand4k);
TEST_BLOCKING_BEHAVIOR(CoupledFileTransports);
#endif
@@ -880,45 +925,23 @@
// Add some tests that access TBufferedTransport and TFramedTransport
// via TTransport pointers and TBufferBase pointers.
ADD_TEST_RW(CoupledTTransports<CoupledBufferedTransports>,
- 1024 * 1024,
- rand4k,
- rand4k,
- rand4k,
- rand4k);
+ 1024*1024, rand4k, rand4k, rand4k, rand4k);
ADD_TEST_RW(CoupledBufferBases<CoupledBufferedTransports>,
- 1024 * 1024,
- rand4k,
- rand4k,
- rand4k,
- rand4k);
+ 1024*1024, rand4k, rand4k, rand4k, rand4k);
ADD_TEST_RW(CoupledTTransports<CoupledFramedTransports>,
- 1024 * 1024,
- rand4k,
- rand4k,
- rand4k,
- rand4k);
+ 1024*1024, rand4k, rand4k, rand4k, rand4k);
ADD_TEST_RW(CoupledBufferBases<CoupledFramedTransports>,
- 1024 * 1024,
- rand4k,
- rand4k,
- rand4k,
- rand4k);
+ 1024*1024, rand4k, rand4k, rand4k, rand4k);
// Test using TZlibTransport via a TTransport pointer
ADD_TEST_RW(CoupledTTransports<CoupledZlibTransports>,
- 1024 * 1024,
- rand4k,
- rand4k,
- rand4k,
- rand4k);
+ 1024*1024, rand4k, rand4k, rand4k, rand4k);
}
-private:
+ private:
template <class CoupledTransports>
- void addTestRW(const char* transport_name,
- uint32_t totalSize,
- GenericSizeGenerator wSizeGen,
- GenericSizeGenerator rSizeGen,
+ void addTestRW(const char* transport_name, uint32_t totalSize,
+ GenericSizeGenerator wSizeGen, GenericSizeGenerator rSizeGen,
GenericSizeGenerator wChunkSizeGen = 0,
GenericSizeGenerator rChunkSizeGen = 0,
uint32_t maxOutstanding = 0,
@@ -927,50 +950,60 @@
totalSize = static_cast<uint32_t>(totalSize * sizeMultiplier_);
std::ostringstream name;
- name << transport_name << "::test_rw(" << totalSize << ", " << wSizeGen.describe() << ", "
- << rSizeGen.describe() << ", " << wChunkSizeGen.describe() << ", "
- << rChunkSizeGen.describe() << ", " << maxOutstanding << ")";
+ name << transport_name << "::test_rw(" << totalSize << ", " <<
+ wSizeGen.describe() << ", " << rSizeGen.describe() << ", " <<
+ wChunkSizeGen.describe() << ", " << rChunkSizeGen.describe() << ", " <<
+ maxOutstanding << ")";
- boost::unit_test::callback0<> test_func
- = apache::thrift::stdcxx::bind(test_rw<CoupledTransports>,
- totalSize,
- wSizeGen,
- rSizeGen,
- wChunkSizeGen,
- rChunkSizeGen,
- maxOutstanding);
- boost::unit_test::test_case* tc = boost::unit_test::make_test_case(test_func, name.str());
+ boost::unit_test::callback0<> test_func =
+ apache::thrift::stdcxx::bind(test_rw<CoupledTransports>, totalSize,
+ wSizeGen, rSizeGen, wChunkSizeGen, rChunkSizeGen,
+ maxOutstanding);
+ boost::unit_test::test_case* tc =
+ boost::unit_test::make_test_case(test_func, name.str());
suite_->add(tc, expectedFailures);
}
template <class CoupledTransports>
- void addTestBlocking(const char* transportName, uint32_t expectedFailures = 0) {
+ void addTestBlocking(const char* transportName,
+ uint32_t expectedFailures = 0) {
char name[1024];
boost::unit_test::test_case* tc;
- THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_part_available()", transportName);
- tc = boost::unit_test::make_test_case(test_read_part_available<CoupledTransports>, name);
+ THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_part_available()",
+ transportName);
+ tc = boost::unit_test::make_test_case(
+ test_read_part_available<CoupledTransports>, name);
suite_->add(tc, expectedFailures);
- THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_part_available_in_chunks()", transportName);
- tc = boost::unit_test::make_test_case(test_read_part_available_in_chunks<CoupledTransports>,
- name);
+ THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_part_available_in_chunks()",
+ transportName);
+ tc = boost::unit_test::make_test_case(
+ test_read_part_available_in_chunks<CoupledTransports>, name);
suite_->add(tc, expectedFailures);
- THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_partial_midframe()", transportName);
- tc = boost::unit_test::make_test_case(test_read_partial_midframe<CoupledTransports>, name);
+ THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_partial_midframe()",
+ transportName);
+ tc = boost::unit_test::make_test_case(
+ test_read_partial_midframe<CoupledTransports>, name);
suite_->add(tc, expectedFailures);
- THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_none_available()", transportName);
- tc = boost::unit_test::make_test_case(test_read_none_available<CoupledTransports>, name);
+ THRIFT_SNPRINTF(name, sizeof(name), "%s::test_read_none_available()",
+ transportName);
+ tc = boost::unit_test::make_test_case(
+ test_read_none_available<CoupledTransports>, name);
suite_->add(tc, expectedFailures);
- THRIFT_SNPRINTF(name, sizeof(name), "%s::test_borrow_part_available()", transportName);
- tc = boost::unit_test::make_test_case(test_borrow_part_available<CoupledTransports>, name);
+ THRIFT_SNPRINTF(name, sizeof(name), "%s::test_borrow_part_available()",
+ transportName);
+ tc = boost::unit_test::make_test_case(
+ test_borrow_part_available<CoupledTransports>, name);
suite_->add(tc, expectedFailures);
- THRIFT_SNPRINTF(name, sizeof(name), "%s::test_borrow_none_available()", transportName);
- tc = boost::unit_test::make_test_case(test_borrow_none_available<CoupledTransports>, name);
+ THRIFT_SNPRINTF(name, sizeof(name), "%s::test_borrow_none_available()",
+ transportName);
+ tc = boost::unit_test::make_test_case(
+ test_borrow_none_available<CoupledTransports>, name);
suite_->add(tc, expectedFailures);
}
@@ -989,15 +1022,15 @@
struct global_fixture {
boost::shared_ptr<apache::thrift::concurrency::Thread> alarmThread_;
global_fixture() {
-#if _WIN32
+ #if _WIN32
apache::thrift::transport::TWinsockSingleton::create();
-#endif
+ #endif
apache::thrift::concurrency::PlatformThreadFactory factory;
factory.setDetached(false);
alarmThread_ = factory.newThread(
- apache::thrift::concurrency::FunctionRunner::create(alarm_handler_wrapper));
+ apache::thrift::concurrency::FunctionRunner::create(alarm_handler_wrapper));
alarmThread_->start();
}
~global_fixture() {
@@ -1021,7 +1054,8 @@
initrand(seed);
- boost::unit_test::test_suite* suite = &boost::unit_test::framework::master_test_suite();
+ boost::unit_test::test_suite* suite =
+ &boost::unit_test::framework::master_test_suite();
suite->p_name.value = "TransportTest";
TransportTestGen transport_test_generator(suite, 1);
transport_test_generator.generate();
diff --git a/lib/cpp/test/ZlibTest.cpp b/lib/cpp/test/ZlibTest.cpp
index 14b1a37..49c5514 100644
--- a/lib/cpp/test/ZlibTest.cpp
+++ b/lib/cpp/test/ZlibTest.cpp
@@ -48,24 +48,26 @@
*/
class SizeGenerator {
-public:
+ public:
virtual ~SizeGenerator() {}
virtual unsigned int getSize() = 0;
};
class ConstantSizeGenerator : public SizeGenerator {
-public:
+ public:
ConstantSizeGenerator(unsigned int value) : value_(value) {}
- virtual unsigned int getSize() { return value_; }
+ virtual unsigned int getSize() {
+ return value_;
+ }
-private:
+ private:
unsigned int value_;
};
class LogNormalSizeGenerator : public SizeGenerator {
-public:
- LogNormalSizeGenerator(double mean, double std_dev)
- : gen_(rng, boost::lognormal_distribution<double>(mean, std_dev)) {}
+ public:
+ LogNormalSizeGenerator(double mean, double std_dev) :
+ gen_(rng, boost::lognormal_distribution<double>(mean, std_dev)) {}
virtual unsigned int getSize() {
// Loop until we get a size of 1 or more
@@ -77,8 +79,8 @@
}
}
-private:
- boost::variate_generator<boost::mt19937, boost::lognormal_distribution<double> > gen_;
+ private:
+ boost::variate_generator< boost::mt19937, boost::lognormal_distribution<double> > gen_;
};
uint8_t* gen_uniform_buffer(uint32_t buf_len, uint8_t c) {
@@ -93,10 +95,10 @@
// Generate small runs of alternately increasing and decreasing bytes
boost::uniform_smallint<uint32_t> run_length_distribution(1, 64);
boost::uniform_smallint<uint8_t> byte_distribution(0, UINT8_MAX);
- boost::variate_generator<boost::mt19937, boost::uniform_smallint<uint8_t> >
- byte_generator(rng, byte_distribution);
- boost::variate_generator<boost::mt19937, boost::uniform_smallint<uint32_t> >
- run_len_generator(rng, run_length_distribution);
+ boost::variate_generator< boost::mt19937, boost::uniform_smallint<uint8_t> >
+ byte_generator(rng, byte_distribution);
+ boost::variate_generator< boost::mt19937, boost::uniform_smallint<uint32_t> >
+ run_len_generator(rng, run_length_distribution);
uint32_t idx = 0;
int8_t step = 1;
@@ -123,8 +125,8 @@
uint8_t* buf = new uint8_t[buf_len];
boost::uniform_smallint<uint8_t> distribution(0, UINT8_MAX);
- boost::variate_generator<boost::mt19937, boost::uniform_smallint<uint8_t> >
- generator(rng, distribution);
+ boost::variate_generator< boost::mt19937, boost::uniform_smallint<uint8_t> >
+ generator(rng, distribution);
for (uint32_t n = 0; n < buf_len; ++n) {
buf[n] = generator();
@@ -165,7 +167,7 @@
membuf->appendBufferToString(tmp_buf);
zlib_trans.reset(new TZlibTransport(membuf,
TZlibTransport::DEFAULT_URBUF_SIZE,
- static_cast<uint32_t>(tmp_buf.length() - 1)));
+ static_cast<uint32_t>(tmp_buf.length()-1)));
boost::shared_array<uint8_t> mirror(new uint8_t[buf_len]);
uint32_t got = zlib_trans->readAll(mirror.get(), buf_len);
@@ -184,7 +186,8 @@
string tmp_buf;
membuf->appendBufferToString(tmp_buf);
tmp_buf.erase(tmp_buf.length() - 1);
- membuf->resetBuffer(const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(tmp_buf.data())),
+ membuf->resetBuffer(const_cast<uint8_t*>(
+ reinterpret_cast<const uint8_t*>(tmp_buf.data())),
static_cast<uint32_t>(tmp_buf.length()));
boost::shared_array<uint8_t> mirror(new uint8_t[buf_len]);
@@ -199,8 +202,7 @@
}
}
-void test_read_write_mix(const uint8_t* buf,
- uint32_t buf_len,
+void test_read_write_mix(const uint8_t* buf, uint32_t buf_len,
const boost::shared_ptr<SizeGenerator>& write_gen,
const boost::shared_ptr<SizeGenerator>& read_gen) {
// Try it with a mix of read/write sizes.
@@ -230,7 +232,7 @@
}
uint32_t got = zlib_trans->read(mirror.get() + tot, read_len);
BOOST_REQUIRE_LE(got, expected_read_len);
- BOOST_REQUIRE_NE(got, (uint32_t)0);
+ BOOST_REQUIRE_NE(got, (uint32_t) 0);
tot += got;
}
@@ -262,7 +264,8 @@
// error when only modifying checksum bytes.
int index = static_cast<int>(tmp_buf.size() - 1);
tmp_buf[index]++;
- membuf->resetBuffer(const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(tmp_buf.data())),
+ membuf->resetBuffer(const_cast<uint8_t*>(
+ reinterpret_cast<const uint8_t*>(tmp_buf.data())),
static_cast<uint32_t>(tmp_buf.length()));
boost::shared_array<uint8_t> mirror(new uint8_t[buf_len]);
@@ -320,22 +323,21 @@
TZlibTransport w_zlib_trans(membuf);
}
- BOOST_CHECK_EQUAL(membuf->available_read(), (uint32_t)0);
+ BOOST_CHECK_EQUAL(membuf->available_read(), (uint32_t) 0);
}
/*
* Initialization
*/
-#define ADD_TEST_CASE(suite, name, function, ...) \
- do { \
- ::std::ostringstream name_ss; \
- name_ss << name << "-" << BOOST_STRINGIZE(function); \
- ::boost::unit_test::test_case* tc \
- = ::boost::unit_test::make_test_case(::apache::thrift::stdcxx::bind(function, \
- ##__VA_ARGS__), \
- name_ss.str()); \
- (suite)->add(tc); \
+#define ADD_TEST_CASE(suite, name, function, ...) \
+ do { \
+ ::std::ostringstream name_ss; \
+ name_ss << name << "-" << BOOST_STRINGIZE(function); \
+ ::boost::unit_test::test_case* tc = ::boost::unit_test::make_test_case( \
+ ::apache::thrift::stdcxx::bind(function, ## __VA_ARGS__), \
+ name_ss.str()); \
+ (suite)->add(tc); \
} while (0)
void add_tests(boost::unit_test::test_suite* suite,
@@ -348,30 +350,20 @@
ADD_TEST_CASE(suite, name, test_invalid_checksum, buf, buf_len);
ADD_TEST_CASE(suite, name, test_write_after_flush, buf, buf_len);
- boost::shared_ptr<SizeGenerator> size_32k(new ConstantSizeGenerator(1 << 15));
+ boost::shared_ptr<SizeGenerator> size_32k(new ConstantSizeGenerator(1<<15));
boost::shared_ptr<SizeGenerator> size_lognormal(new LogNormalSizeGenerator(20, 30));
- ADD_TEST_CASE(suite, name << "-constant", test_read_write_mix, buf, buf_len, size_32k, size_32k);
- ADD_TEST_CASE(suite,
- name << "-lognormal-write",
- test_read_write_mix,
- buf,
- buf_len,
- size_lognormal,
- size_32k);
- ADD_TEST_CASE(suite,
- name << "-lognormal-read",
- test_read_write_mix,
- buf,
- buf_len,
- size_32k,
- size_lognormal);
- ADD_TEST_CASE(suite,
- name << "-lognormal-both",
- test_read_write_mix,
- buf,
- buf_len,
- size_lognormal,
- size_lognormal);
+ ADD_TEST_CASE(suite, name << "-constant",
+ test_read_write_mix, buf, buf_len,
+ size_32k, size_32k);
+ ADD_TEST_CASE(suite, name << "-lognormal-write",
+ test_read_write_mix, buf, buf_len,
+ size_lognormal, size_32k);
+ ADD_TEST_CASE(suite, name << "-lognormal-read",
+ test_read_write_mix, buf, buf_len,
+ size_32k, size_lognormal);
+ ADD_TEST_CASE(suite, name << "-lognormal-both",
+ test_read_write_mix, buf, buf_len,
+ size_lognormal, size_lognormal);
// Test with a random size distribution,
// but use the exact same distribution for reading as for writing.
@@ -381,13 +373,9 @@
// both start with random number generators in the same state.
boost::shared_ptr<SizeGenerator> write_size_gen(new LogNormalSizeGenerator(20, 30));
boost::shared_ptr<SizeGenerator> read_size_gen(new LogNormalSizeGenerator(20, 30));
- ADD_TEST_CASE(suite,
- name << "-lognormal-same-distribution",
- test_read_write_mix,
- buf,
- buf_len,
- write_size_gen,
- read_size_gen);
+ ADD_TEST_CASE(suite, name << "-lognormal-same-distribution",
+ test_read_write_mix, buf, buf_len,
+ write_size_gen, read_size_gen);
}
void print_usage(FILE* f, const char* argv0) {
@@ -404,10 +392,11 @@
printf("seed: %" PRIu32 "\n", seed);
rng.seed(seed);
- boost::unit_test::test_suite* suite = &boost::unit_test::framework::master_test_suite();
+ boost::unit_test::test_suite* suite =
+ &boost::unit_test::framework::master_test_suite();
suite->p_name.value = "ZlibTest";
- uint32_t buf_len = 1024 * 32;
+ uint32_t buf_len = 1024*32;
add_tests(suite, gen_uniform_buffer(buf_len, 'a'), buf_len, "uniform");
add_tests(suite, gen_compressible_buffer(buf_len), buf_len, "compressible");
add_tests(suite, gen_random_buffer(buf_len), buf_len, "random");
diff --git a/lib/cpp/test/concurrency/Tests.cpp b/lib/cpp/test/concurrency/Tests.cpp
index 0d81d7e..c80bb88 100644
--- a/lib/cpp/test/concurrency/Tests.cpp
+++ b/lib/cpp/test/concurrency/Tests.cpp
@@ -29,7 +29,7 @@
std::string arg;
- std::vector<std::string> args(argc - 1 > 1 ? argc - 1 : 1);
+ std::vector<std::string> args(argc - 1 > 1 ? argc - 1 : 1);
args[0] = "all";
@@ -45,9 +45,9 @@
std::cout << "ThreadFactory tests..." << std::endl;
- size_t count = 1000;
- size_t floodLoops = 1;
- size_t floodCount = 100000;
+ size_t count = 1000;
+ size_t floodLoops = 1;
+ size_t floodCount = 100000;
std::cout << "\t\tThreadFactory reap N threads test: N = " << count << std::endl;
@@ -89,6 +89,7 @@
std::cout << "\t\t\tscall per ms: " << count / (time01 - time00) << std::endl;
}
+
if (runAll || args[0].compare("timer-manager") == 0) {
std::cout << "TimerManager tests..." << std::endl;
@@ -112,17 +113,16 @@
int64_t delay = 10LL;
- std::cout << "\t\tThreadManager load test: worker count: " << workerCount
- << " task count: " << taskCount << " delay: " << delay << std::endl;
+ std::cout << "\t\tThreadManager load test: worker count: " << workerCount << " task count: " << taskCount << " delay: " << delay << std::endl;
ThreadManagerTests threadManagerTests;
assert(threadManagerTests.loadTest(taskCount, delay, workerCount));
- std::cout << "\t\tThreadManager block test: worker count: " << workerCount
- << " delay: " << delay << std::endl;
+ std::cout << "\t\tThreadManager block test: worker count: " << workerCount << " delay: " << delay << std::endl;
assert(threadManagerTests.blockTest(delay, workerCount));
+
}
}
@@ -140,12 +140,11 @@
int64_t delay = 10LL;
- for (size_t workerCount = minWorkerCount; workerCount < maxWorkerCount; workerCount *= 2) {
+ for (size_t workerCount = minWorkerCount; workerCount < maxWorkerCount; workerCount*= 2) {
size_t taskCount = workerCount * tasksPerWorker;
- std::cout << "\t\tThreadManager load test: worker count: " << workerCount
- << " task count: " << taskCount << " delay: " << delay << std::endl;
+ std::cout << "\t\tThreadManager load test: worker count: " << workerCount << " task count: " << taskCount << " delay: " << delay << std::endl;
ThreadManagerTests threadManagerTests;
diff --git a/lib/cpp/test/concurrency/ThreadFactoryTests.h b/lib/cpp/test/concurrency/ThreadFactoryTests.h
old mode 100644
new mode 100755
index d7431a8..2d97337
--- a/lib/cpp/test/concurrency/ThreadFactoryTests.h
+++ b/lib/cpp/test/concurrency/ThreadFactoryTests.h
@@ -27,10 +27,7 @@
#include <iostream>
#include <set>
-namespace apache {
-namespace thrift {
-namespace concurrency {
-namespace test {
+namespace apache { namespace thrift { namespace concurrency { namespace test {
using boost::shared_ptr;
using namespace apache::thrift::concurrency;
@@ -43,14 +40,18 @@
class ThreadFactoryTests {
public:
+
static const double TEST_TOLERANCE;
- class Task : public Runnable {
+ class Task: public Runnable {
public:
+
Task() {}
- void run() { std::cout << "\t\t\tHello World" << std::endl; }
+ void run() {
+ std::cout << "\t\t\tHello World" << std::endl;
+ }
};
/**
@@ -76,17 +77,20 @@
/**
* Reap N threads
*/
- class ReapNTask : public Runnable {
+ class ReapNTask: public Runnable {
- public:
- ReapNTask(Monitor& monitor, int& activeCount) : _monitor(monitor), _count(activeCount) {}
+ public:
+
+ ReapNTask(Monitor& monitor, int& activeCount) :
+ _monitor(monitor),
+ _count(activeCount) {}
void run() {
Synchronized s(_monitor);
_count--;
- // std::cout << "\t\t\tthread count: " << _count << std::endl;
+ //std::cout << "\t\t\tthread count: " << _count << std::endl;
if (_count == 0) {
_monitor.notify();
@@ -98,15 +102,15 @@
int& _count;
};
- bool reapNThreads(int loop = 1, int count = 10) {
+ bool reapNThreads(int loop=1, int count=10) {
- PlatformThreadFactory threadFactory = PlatformThreadFactory();
+ PlatformThreadFactory threadFactory = PlatformThreadFactory();
Monitor* monitor = new Monitor();
- for (int lix = 0; lix < loop; lix++) {
+ for(int lix = 0; lix < loop; lix++) {
- int* activeCount = new int(count);
+ int* activeCount = new int(count);
std::set<shared_ptr<Thread> > threads;
@@ -114,25 +118,20 @@
for (tix = 0; tix < count; tix++) {
try {
- threads.insert(
- threadFactory.newThread(shared_ptr<Runnable>(new ReapNTask(*monitor, *activeCount))));
- } catch (SystemResourceException& e) {
- std::cout << "\t\t\tfailed to create " << lix* count + tix << " thread " << e.what()
- << std::endl;
+ threads.insert(threadFactory.newThread(shared_ptr<Runnable>(new ReapNTask(*monitor, *activeCount))));
+ } catch(SystemResourceException& e) {
+ std::cout << "\t\t\tfailed to create " << lix * count + tix << " thread " << e.what() << std::endl;
throw e;
}
}
tix = 0;
- for (std::set<shared_ptr<Thread> >::const_iterator thread = threads.begin();
- thread != threads.end();
- tix++, ++thread) {
+ for (std::set<shared_ptr<Thread> >::const_iterator thread = threads.begin(); thread != threads.end(); tix++, ++thread) {
try {
(*thread)->start();
- } catch (SystemResourceException& e) {
- std::cout << "\t\t\tfailed to start " << lix* count + tix << " thread " << e.what()
- << std::endl;
+ } catch(SystemResourceException& e) {
+ std::cout << "\t\t\tfailed to start " << lix * count + tix << " thread " << e.what() << std::endl;
throw e;
}
}
@@ -144,7 +143,7 @@
}
}
delete activeCount;
- std::cout << "\t\t\treaped " << lix* count << " threads" << std::endl;
+ std::cout << "\t\t\treaped " << lix * count << " threads" << std::endl;
}
std::cout << "\t\t\tSuccess!" << std::endl;
@@ -152,12 +151,21 @@
return true;
}
- class SynchStartTask : public Runnable {
+ class SynchStartTask: public Runnable {
- public:
- enum STATE { UNINITIALIZED, STARTING, STARTED, STOPPING, STOPPED };
+ public:
- SynchStartTask(Monitor& monitor, volatile STATE& state) : _monitor(monitor), _state(state) {}
+ enum STATE {
+ UNINITIALIZED,
+ STARTING,
+ STARTED,
+ STOPPING,
+ STOPPED
+ };
+
+ SynchStartTask(Monitor& monitor, volatile STATE& state) :
+ _monitor(monitor),
+ _state(state) {}
void run() {
{
@@ -181,9 +189,9 @@
}
}
- private:
+ private:
Monitor& _monitor;
- volatile STATE& _state;
+ volatile STATE& _state;
};
bool synchStartTest() {
@@ -192,10 +200,9 @@
SynchStartTask::STATE state = SynchStartTask::UNINITIALIZED;
- shared_ptr<SynchStartTask> task
- = shared_ptr<SynchStartTask>(new SynchStartTask(monitor, state));
+ shared_ptr<SynchStartTask> task = shared_ptr<SynchStartTask>(new SynchStartTask(monitor, state));
- PlatformThreadFactory threadFactory = PlatformThreadFactory();
+ PlatformThreadFactory threadFactory = PlatformThreadFactory();
shared_ptr<Thread> thread = threadFactory.newThread(task);
@@ -219,8 +226,8 @@
Synchronized s(monitor);
try {
- monitor.wait(100);
- } catch (TimedOutException& e) {
+ monitor.wait(100);
+ } catch(TimedOutException& e) {
}
if (state == SynchStartTask::STARTED) {
@@ -246,7 +253,7 @@
/** See how accurate monitor timeout is. */
- bool monitorTimeoutTest(size_t count = 1000, int64_t timeout = 10) {
+ bool monitorTimeoutTest(size_t count=1000, int64_t timeout=10) {
Monitor monitor;
@@ -256,8 +263,8 @@
{
Synchronized s(monitor);
try {
- monitor.wait(timeout);
- } catch (TimedOutException& e) {
+ monitor.wait(timeout);
+ } catch(TimedOutException& e) {
}
}
}
@@ -266,32 +273,31 @@
double error = ((endTime - startTime) - (count * timeout)) / (double)(count * timeout);
- if (error < 0.0) {
+ if (error < 0.0) {
error *= 1.0;
}
bool success = error < ThreadFactoryTests::TEST_TOLERANCE;
- std::cout << "\t\t\t" << (success ? "Success" : "Failure")
- << "! expected time: " << count * timeout
- << "ms elapsed time: " << endTime - startTime << "ms error%: " << error * 100.0
- << std::endl;
+ std::cout << "\t\t\t" << (success ? "Success" : "Failure") << "! expected time: " << count * timeout << "ms elapsed time: "<< endTime - startTime << "ms error%: " << error * 100.0 << std::endl;
return success;
}
+
class FloodTask : public Runnable {
public:
- FloodTask(const size_t id) : _id(id) {}
- ~FloodTask() {
- if (_id % 1000 == 0) {
+
+ FloodTask(const size_t id) :_id(id) {}
+ ~FloodTask(){
+ if(_id % 1000 == 0) {
std::cout << "\t\tthread " << _id << " done" << std::endl;
}
}
- void run() {
- if (_id % 1000 == 0) {
+ void run(){
+ if(_id % 1000 == 0) {
std::cout << "\t\tthread " << _id << " started" << std::endl;
}
@@ -300,41 +306,42 @@
const size_t _id;
};
- void foo(PlatformThreadFactory* tf) { (void)tf; }
+ void foo(PlatformThreadFactory *tf) {
+ (void) tf;
+ }
- bool floodNTest(size_t loop = 1, size_t count = 100000) {
+ bool floodNTest(size_t loop=1, size_t count=100000) {
bool success = false;
- for (size_t lix = 0; lix < loop; lix++) {
+ for(size_t lix = 0; lix < loop; lix++) {
PlatformThreadFactory threadFactory = PlatformThreadFactory();
threadFactory.setDetached(true);
- for (size_t tix = 0; tix < count; tix++) {
+ for(size_t tix = 0; tix < count; tix++) {
- try {
+ try {
- shared_ptr<FloodTask> task(new FloodTask(lix * count + tix));
+ shared_ptr<FloodTask> task(new FloodTask(lix * count + tix ));
- shared_ptr<Thread> thread = threadFactory.newThread(task);
+ shared_ptr<Thread> thread = threadFactory.newThread(task);
- thread->start();
+ thread->start();
- THRIFT_SLEEP_USEC(1);
+ THRIFT_SLEEP_USEC(1);
- } catch (TException& e) {
+ } catch (TException& e) {
- std::cout << "\t\t\tfailed to start " << lix* count + tix << " thread " << e.what()
- << std::endl;
+ std::cout << "\t\t\tfailed to start " << lix * count + tix << " thread " << e.what() << std::endl;
- return success;
+ return success;
+ }
}
- }
- std::cout << "\t\t\tflooded " << (lix + 1) * count << " threads" << std::endl;
+ std::cout << "\t\t\tflooded " << (lix + 1) * count << " threads" << std::endl;
- success = true;
+ success = true;
}
return success;
@@ -342,7 +349,5 @@
};
const double ThreadFactoryTests::TEST_TOLERANCE = .20;
-}
-}
-}
-} // apache::thrift::concurrency::test
+
+}}}} // apache::thrift::concurrency::test
diff --git a/lib/cpp/test/concurrency/ThreadManagerTests.h b/lib/cpp/test/concurrency/ThreadManagerTests.h
old mode 100644
new mode 100755
index 27bf6c5..c08448b
--- a/lib/cpp/test/concurrency/ThreadManagerTests.h
+++ b/lib/cpp/test/concurrency/ThreadManagerTests.h
@@ -29,10 +29,7 @@
#include <set>
#include <stdint.h>
-namespace apache {
-namespace thrift {
-namespace concurrency {
-namespace test {
+namespace apache { namespace thrift { namespace concurrency { namespace test {
using namespace apache::thrift::concurrency;
@@ -41,11 +38,15 @@
static const double TEST_TOLERANCE;
public:
- class Task : public Runnable {
+ class Task: public Runnable {
public:
- Task(Monitor& monitor, size_t& count, int64_t timeout)
- : _monitor(monitor), _count(count), _timeout(timeout), _done(false) {}
+
+ Task(Monitor& monitor, size_t& count, int64_t timeout) :
+ _monitor(monitor),
+ _count(count),
+ _timeout(timeout),
+ _done(false) {}
void run() {
@@ -56,9 +57,9 @@
try {
_sleep.wait(_timeout);
- } catch (TimedOutException& e) {
+ } catch(TimedOutException& e) {
;
- } catch (...) {
+ }catch(...) {
assert(0);
}
}
@@ -95,7 +96,7 @@
* completes. Verify that all tasks completed and that thread manager cleans
* up properly on delete.
*/
- bool loadTest(size_t count = 100, int64_t timeout = 100LL, size_t workerCount = 4) {
+ bool loadTest(size_t count=100, int64_t timeout=100LL, size_t workerCount=4) {
Monitor monitor;
@@ -103,8 +104,7 @@
shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(workerCount);
- shared_ptr<PlatformThreadFactory> threadFactory
- = shared_ptr<PlatformThreadFactory>(new PlatformThreadFactory());
+ shared_ptr<PlatformThreadFactory> threadFactory = shared_ptr<PlatformThreadFactory>(new PlatformThreadFactory());
#ifndef USE_BOOST_THREAD
threadFactory->setPriority(PosixThreadFactory::HIGHEST);
@@ -117,23 +117,20 @@
for (size_t ix = 0; ix < count; ix++) {
- tasks.insert(shared_ptr<ThreadManagerTests::Task>(
- new ThreadManagerTests::Task(monitor, activeCount, timeout)));
+ tasks.insert(shared_ptr<ThreadManagerTests::Task>(new ThreadManagerTests::Task(monitor, activeCount, timeout)));
}
int64_t time00 = Util::currentTime();
- for (std::set<shared_ptr<ThreadManagerTests::Task> >::iterator ix = tasks.begin();
- ix != tasks.end();
- ix++) {
+ for (std::set<shared_ptr<ThreadManagerTests::Task> >::iterator ix = tasks.begin(); ix != tasks.end(); ix++) {
- threadManager->add(*ix);
+ threadManager->add(*ix);
}
{
Synchronized s(monitor);
- while (activeCount > 0) {
+ while(activeCount > 0) {
monitor.wait();
}
@@ -148,9 +145,7 @@
int64_t minTime = 9223372036854775807LL;
int64_t maxTime = 0;
- for (std::set<shared_ptr<ThreadManagerTests::Task> >::iterator ix = tasks.begin();
- ix != tasks.end();
- ix++) {
+ for (std::set<shared_ptr<ThreadManagerTests::Task> >::iterator ix = tasks.begin(); ix != tasks.end(); ix++) {
shared_ptr<ThreadManagerTests::Task> task = *ix;
@@ -174,43 +169,43 @@
maxTime = delta;
}
- averageTime += delta;
+ averageTime+= delta;
}
averageTime /= count;
- std::cout << "\t\t\tfirst start: " << firstTime << "ms Last end: " << lastTime
- << "ms min: " << minTime << "ms max: " << maxTime << "ms average: " << averageTime
- << "ms" << std::endl;
+ std::cout << "\t\t\tfirst start: " << firstTime << "ms Last end: " << lastTime << "ms min: " << minTime << "ms max: " << maxTime << "ms average: " << averageTime << "ms" << std::endl;
double expectedTime = ((count + (workerCount - 1)) / workerCount) * timeout;
double error = ((time01 - time00) - expectedTime) / expectedTime;
if (error < 0) {
- error *= -1.0;
+ error*= -1.0;
}
bool success = error < TEST_TOLERANCE;
- std::cout << "\t\t\t" << (success ? "Success" : "Failure")
- << "! expected time: " << expectedTime << "ms elapsed time: " << time01 - time00
- << "ms error%: " << error * 100.0 << std::endl;
+ std::cout << "\t\t\t" << (success ? "Success" : "Failure") << "! expected time: " << expectedTime << "ms elapsed time: "<< time01 - time00 << "ms error%: " << error * 100.0 << std::endl;
return success;
}
- class BlockTask : public Runnable {
+ class BlockTask: public Runnable {
public:
- BlockTask(Monitor& monitor, Monitor& bmonitor, size_t& count)
- : _monitor(monitor), _bmonitor(bmonitor), _count(count) {}
+
+ BlockTask(Monitor& monitor, Monitor& bmonitor, size_t& count) :
+ _monitor(monitor),
+ _bmonitor(bmonitor),
+ _count(count) {}
void run() {
{
Synchronized s(_bmonitor);
_bmonitor.wait();
+
}
{
@@ -234,8 +229,8 @@
* Block test. Create pendingTaskCountMax tasks. Verify that we block adding the
* pendingTaskCountMax + 1th task. Verify that we unblock when a task completes */
- bool blockTest(int64_t timeout = 100LL, size_t workerCount = 2) {
- (void)timeout;
+ bool blockTest(int64_t timeout=100LL, size_t workerCount=2) {
+ (void) timeout;
bool success = false;
try {
@@ -247,11 +242,9 @@
size_t activeCounts[] = {workerCount, pendingTaskMaxCount, 1};
- shared_ptr<ThreadManager> threadManager
- = ThreadManager::newSimpleThreadManager(workerCount, pendingTaskMaxCount);
+ shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(workerCount, pendingTaskMaxCount);
- shared_ptr<PlatformThreadFactory> threadFactory
- = shared_ptr<PlatformThreadFactory>(new PlatformThreadFactory());
+ shared_ptr<PlatformThreadFactory> threadFactory = shared_ptr<PlatformThreadFactory>(new PlatformThreadFactory());
#ifndef USE_BOOST_THREAD
threadFactory->setPriority(PosixThreadFactory::HIGHEST);
@@ -264,49 +257,43 @@
for (size_t ix = 0; ix < workerCount; ix++) {
- tasks.insert(shared_ptr<ThreadManagerTests::BlockTask>(
- new ThreadManagerTests::BlockTask(monitor, bmonitor, activeCounts[0])));
+ tasks.insert(shared_ptr<ThreadManagerTests::BlockTask>(new ThreadManagerTests::BlockTask(monitor, bmonitor,activeCounts[0])));
}
for (size_t ix = 0; ix < pendingTaskMaxCount; ix++) {
- tasks.insert(shared_ptr<ThreadManagerTests::BlockTask>(
- new ThreadManagerTests::BlockTask(monitor, bmonitor, activeCounts[1])));
+ tasks.insert(shared_ptr<ThreadManagerTests::BlockTask>(new ThreadManagerTests::BlockTask(monitor, bmonitor,activeCounts[1])));
}
- for (std::set<shared_ptr<ThreadManagerTests::BlockTask> >::iterator ix = tasks.begin();
- ix != tasks.end();
- ix++) {
+ for (std::set<shared_ptr<ThreadManagerTests::BlockTask> >::iterator ix = tasks.begin(); ix != tasks.end(); ix++) {
threadManager->add(*ix);
}
- if (!(success = (threadManager->totalTaskCount() == pendingTaskMaxCount + workerCount))) {
+ if(!(success = (threadManager->totalTaskCount() == pendingTaskMaxCount + workerCount))) {
throw TException("Unexpected pending task count");
}
- shared_ptr<ThreadManagerTests::BlockTask> extraTask(
- new ThreadManagerTests::BlockTask(monitor, bmonitor, activeCounts[2]));
+ shared_ptr<ThreadManagerTests::BlockTask> extraTask(new ThreadManagerTests::BlockTask(monitor, bmonitor, activeCounts[2]));
try {
threadManager->add(extraTask, 1);
throw TException("Unexpected success adding task in excess of pending task count");
- } catch (TooManyPendingTasksException& e) {
+ } catch(TooManyPendingTasksException& e) {
throw TException("Should have timed out adding task in excess of pending task count");
- } catch (TimedOutException& e) {
+ } catch(TimedOutException& e) {
// Expected result
}
try {
threadManager->add(extraTask, -1);
throw TException("Unexpected success adding task in excess of pending task count");
- } catch (TimedOutException& e) {
+ } catch(TimedOutException& e) {
throw TException("Unexpected timeout adding task in excess of pending task count");
- } catch (TooManyPendingTasksException& e) {
+ } catch(TooManyPendingTasksException& e) {
// Expected result
}
- std::cout << "\t\t\t"
- << "Pending tasks " << threadManager->pendingTaskCount() << std::endl;
+ std::cout << "\t\t\t" << "Pending tasks " << threadManager->pendingTaskCount() << std::endl;
{
Synchronized s(bmonitor);
@@ -317,24 +304,21 @@
{
Synchronized s(monitor);
- while (activeCounts[0] != 0) {
+ while(activeCounts[0] != 0) {
monitor.wait();
}
}
- std::cout << "\t\t\t"
- << "Pending tasks " << threadManager->pendingTaskCount() << std::endl;
+ std::cout << "\t\t\t" << "Pending tasks " << threadManager->pendingTaskCount() << std::endl;
try {
threadManager->add(extraTask, 1);
- } catch (TimedOutException& e) {
- std::cout << "\t\t\t"
- << "add timed out unexpectedly" << std::endl;
+ } catch(TimedOutException& e) {
+ std::cout << "\t\t\t" << "add timed out unexpectedly" << std::endl;
throw TException("Unexpected timeout adding task");
- } catch (TooManyPendingTasksException& e) {
- std::cout << "\t\t\t"
- << "add encountered too many pending exepctions" << std::endl;
+ } catch(TooManyPendingTasksException& e) {
+ std::cout << "\t\t\t" << "add encountered too many pending exepctions" << std::endl;
throw TException("Unexpected timeout adding task");
}
@@ -349,7 +333,7 @@
{
Synchronized s(monitor);
- while (activeCounts[1] != 0) {
+ while(activeCounts[1] != 0) {
monitor.wait();
}
}
@@ -365,28 +349,26 @@
{
Synchronized s(monitor);
- while (activeCounts[2] != 0) {
+ while(activeCounts[2] != 0) {
monitor.wait();
}
}
- if (!(success = (threadManager->totalTaskCount() == 0))) {
+ if(!(success = (threadManager->totalTaskCount() == 0))) {
throw TException("Unexpected pending task count");
}
- } catch (TException& e) {
+ } catch(TException& e) {
std::cout << "ERROR: " << e.what() << std::endl;
}
std::cout << "\t\t\t" << (success ? "Success" : "Failure") << std::endl;
return success;
- }
+ }
};
const double ThreadManagerTests::TEST_TOLERANCE = .20;
-}
-}
-}
-} // apache::thrift::concurrency
+
+}}}} // apache::thrift::concurrency
using namespace apache::thrift::concurrency::test;
diff --git a/lib/cpp/test/concurrency/TimerManagerTests.h b/lib/cpp/test/concurrency/TimerManagerTests.h
index dda16ed..62eb4f4 100644
--- a/lib/cpp/test/concurrency/TimerManagerTests.h
+++ b/lib/cpp/test/concurrency/TimerManagerTests.h
@@ -25,10 +25,7 @@
#include <assert.h>
#include <iostream>
-namespace apache {
-namespace thrift {
-namespace concurrency {
-namespace test {
+namespace apache { namespace thrift { namespace concurrency { namespace test {
using namespace apache::thrift::concurrency;
@@ -36,15 +33,16 @@
static const double TEST_TOLERANCE;
-public:
- class Task : public Runnable {
- public:
- Task(Monitor& monitor, int64_t timeout)
- : _timeout(timeout),
- _startTime(Util::currentTime()),
- _monitor(monitor),
- _success(false),
- _done(false) {}
+ public:
+ class Task: public Runnable {
+ public:
+
+ Task(Monitor& monitor, int64_t timeout) :
+ _timeout(timeout),
+ _startTime(Util::currentTime()),
+ _monitor(monitor),
+ _success(false),
+ _done(false) {}
~Task() { std::cerr << this << std::endl; }
@@ -56,20 +54,20 @@
int64_t delta = _endTime - _startTime;
- delta = delta > _timeout ? delta - _timeout : _timeout - delta;
+
+ delta = delta > _timeout ? delta - _timeout : _timeout - delta;
float error = delta / _timeout;
- if (error < TEST_TOLERANCE) {
+ if(error < TEST_TOLERANCE) {
_success = true;
}
_done = true;
- std::cout << "\t\t\tTimerManagerTests::Task[" << this << "] done" << std::endl; // debug
+ std::cout << "\t\t\tTimerManagerTests::Task[" << this << "] done" << std::endl; //debug
- {
- Synchronized s(_monitor);
+ {Synchronized s(_monitor);
_monitor.notifyAll();
}
}
@@ -88,10 +86,9 @@
* properly clean up itself and the remaining orphaned timeout task when the
* manager goes out of scope and its destructor is called.
*/
- bool test00(int64_t timeout = 1000LL) {
+ bool test00(int64_t timeout=1000LL) {
- shared_ptr<TimerManagerTests::Task> orphanTask
- = shared_ptr<TimerManagerTests::Task>(new TimerManagerTests::Task(_monitor, 10 * timeout));
+ shared_ptr<TimerManagerTests::Task> orphanTask = shared_ptr<TimerManagerTests::Task>(new TimerManagerTests::Task(_monitor, 10 * timeout));
{
@@ -116,13 +113,12 @@
// Wait for 1 second in order to give timerManager a chance to start sleeping in response
// to adding orphanTask. We need to do this so we can verify that adding the second task
// kicks the dispatcher out of the current wait and starts the new 1 second wait.
- _monitor.wait(1000);
- assert(
- 0 == "ERROR: This wait should time out. TimerManager dispatcher may have a problem.");
- } catch (TimedOutException& ex) {
+ _monitor.wait (1000);
+ assert (0 == "ERROR: This wait should time out. TimerManager dispatcher may have a problem.");
+ } catch (TimedOutException &ex) {
}
- task.reset(new TimerManagerTests::Task(_monitor, timeout));
+ task.reset (new TimerManagerTests::Task(_monitor, timeout));
timerManager.add(task, timeout);
@@ -131,6 +127,7 @@
assert(task->_done);
+
std::cout << "\t\t\t" << (task->_success ? "Success" : "Failure") << "!" << std::endl;
}
@@ -147,7 +144,5 @@
};
const double TimerManagerTests::TEST_TOLERANCE = .20;
-}
-}
-}
-} // apache::thrift::concurrency
+
+}}}} // apache::thrift::concurrency
diff --git a/lib/cpp/test/processor/EventLog.cpp b/lib/cpp/test/processor/EventLog.cpp
index d4b8372..0ac3028 100644
--- a/lib/cpp/test/processor/EventLog.cpp
+++ b/lib/cpp/test/processor/EventLog.cpp
@@ -36,11 +36,10 @@
fprintf(stderr, "\n");
}
+
}
-namespace apache {
-namespace thrift {
-namespace test {
+namespace apache { namespace thrift { namespace test {
uint32_t EventLog::nextId_ = 0;
@@ -75,12 +74,11 @@
debug("New log: %d", id_);
}
-void EventLog::append(EventType type,
- uint32_t connectionId,
- uint32_t callId,
+void EventLog::append(EventType type, uint32_t connectionId, uint32_t callId,
const string& message) {
Synchronized s(monitor_);
- debug("%d <-- %u, %u, %s \"%s\"", id_, connectionId, callId, type, message.c_str());
+ debug("%d <-- %u, %u, %s \"%s\"", id_, connectionId, callId, type,
+ message.c_str());
Event e(type, connectionId, callId, message);
events_.push_back(e);
@@ -127,6 +125,5 @@
}
}
}
-}
-}
-} // apache::thrift::test
+
+}}} // apache::thrift::test
diff --git a/lib/cpp/test/processor/EventLog.h b/lib/cpp/test/processor/EventLog.h
index 4f8275d..d731cec 100644
--- a/lib/cpp/test/processor/EventLog.h
+++ b/lib/cpp/test/processor/EventLog.h
@@ -21,9 +21,7 @@
#include <thrift/concurrency/Monitor.h>
-namespace apache {
-namespace thrift {
-namespace test {
+namespace apache { namespace thrift { namespace test {
// Initially I made EventType an enum, but using char* results
// in much more readable error messages when there is a mismatch.
@@ -33,17 +31,21 @@
typedef const char* EventType;
struct Event {
- Event(EventType type, uint32_t connectionId, uint32_t callId, const std::string& message)
- : type(type), connectionId(connectionId), callId(callId), message(message) {}
+ Event(EventType type, uint32_t connectionId, uint32_t callId,
+ const std::string& message) :
+ type(type),
+ connectionId(connectionId),
+ callId(callId),
+ message(message) {}
EventType type;
- uint32_t connectionId;
- uint32_t callId;
- std::string message;
+ uint32_t connectionId;
+ uint32_t callId;
+ std::string message;
};
class EventLog {
-public:
+ public:
static EventType ET_LOG_END;
static EventType ET_CONN_CREATED;
static EventType ET_CONN_DESTROYED;
@@ -71,15 +73,13 @@
EventLog();
- void append(EventType type,
- uint32_t connectionId,
- uint32_t callId,
+ void append(EventType type, uint32_t connectionId, uint32_t callId,
const std::string& message = "");
Event waitForEvent(int64_t timeout = 500);
Event waitForConnEvent(uint32_t connId, int64_t timeout = 500);
-protected:
+ protected:
typedef std::list<Event> EventList;
concurrency::Monitor monitor_;
@@ -88,8 +88,7 @@
static uint32_t nextId_;
};
-}
-}
-} // apache::thrift::test
+
+}}} // apache::thrift::test
#endif // _THRIFT_TEST_EVENTLOG_H_
diff --git a/lib/cpp/test/processor/Handlers.h b/lib/cpp/test/processor/Handlers.h
index d894107..75f4349 100644
--- a/lib/cpp/test/processor/Handlers.h
+++ b/lib/cpp/test/processor/Handlers.h
@@ -23,14 +23,15 @@
#include "gen-cpp/ParentService.h"
#include "gen-cpp/ChildService.h"
-namespace apache {
-namespace thrift {
-namespace test {
+namespace apache { namespace thrift { namespace test {
class ParentHandler : virtual public ParentServiceIf {
-public:
- ParentHandler(const boost::shared_ptr<EventLog>& log)
- : triggerMonitor(&mutex_), generation_(0), wait_(false), log_(log) {}
+ public:
+ ParentHandler(const boost::shared_ptr<EventLog>& log) :
+ triggerMonitor(&mutex_),
+ generation_(0),
+ wait_(false),
+ log_(log) { }
int32_t incrementGeneration() {
concurrency::Guard g(mutex_);
@@ -115,7 +116,7 @@
triggerMonitor.notifyAll();
}
-protected:
+ protected:
/**
* blockUntilTriggered() won't return until triggerPendingCalls() is invoked
* in another thread.
@@ -140,8 +141,10 @@
};
class ChildHandler : public ParentHandler, virtual public ChildServiceIf {
-public:
- ChildHandler(const boost::shared_ptr<EventLog>& log) : ParentHandler(log), value_(0) {}
+ public:
+ ChildHandler(const boost::shared_ptr<EventLog>& log) :
+ ParentHandler(log),
+ value_(0) {}
int32_t setValue(int32_t value) {
concurrency::Guard g(mutex_);
@@ -159,16 +162,18 @@
return value_;
}
-protected:
+ protected:
int32_t value_;
};
struct ConnContext {
-public:
+ public:
ConnContext(boost::shared_ptr<protocol::TProtocol> in,
boost::shared_ptr<protocol::TProtocol> out,
- uint32_t id)
- : input(in), output(out), id(id) {}
+ uint32_t id) :
+ input(in),
+ output(out),
+ id(id) {}
boost::shared_ptr<protocol::TProtocol> input;
boost::shared_ptr<protocol::TProtocol> output;
@@ -176,18 +181,22 @@
};
struct CallContext {
-public:
- CallContext(ConnContext* context, uint32_t id, const std::string& name)
- : connContext(context), name(name), id(id) {}
+ public:
+ CallContext(ConnContext *context, uint32_t id, const std::string& name) :
+ connContext(context),
+ name(name),
+ id(id) {}
- ConnContext* connContext;
+ ConnContext *connContext;
std::string name;
uint32_t id;
};
class ServerEventHandler : public server::TServerEventHandler {
-public:
- ServerEventHandler(const boost::shared_ptr<EventLog>& log) : nextId_(1), log_(log) {}
+ public:
+ ServerEventHandler(const boost::shared_ptr<EventLog>& log) :
+ nextId_(1),
+ log_(log) {}
virtual void preServe() {}
@@ -200,8 +209,8 @@
}
virtual void deleteContext(void* serverContext,
- boost::shared_ptr<protocol::TProtocol> input,
- boost::shared_ptr<protocol::TProtocol> output) {
+ boost::shared_ptr<protocol::TProtocol>input,
+ boost::shared_ptr<protocol::TProtocol>output) {
ConnContext* context = reinterpret_cast<ConnContext*>(serverContext);
if (input != context->input) {
@@ -216,21 +225,22 @@
delete context;
}
- virtual void processContext(void* serverContext,
- boost::shared_ptr<transport::TTransport> transport) {
-// TODO: We currently don't test the behavior of the processContext()
-// calls. The various server implementations call processContext() at
-// slightly different times, and it is too annoying to try and account for
-// their various differences.
-//
-// TThreadedServer, TThreadPoolServer, and TSimpleServer usually wait until
-// they see the first byte of a request before calling processContext().
-// However, they don't wait for the first byte of the very first request,
-// and instead immediately call processContext() before any data is
-// received.
-//
-// TNonblockingServer always waits until receiving the full request before
-// calling processContext().
+ virtual void processContext(
+ void* serverContext,
+ boost::shared_ptr<transport::TTransport> transport) {
+ // TODO: We currently don't test the behavior of the processContext()
+ // calls. The various server implementations call processContext() at
+ // slightly different times, and it is too annoying to try and account for
+ // their various differences.
+ //
+ // TThreadedServer, TThreadPoolServer, and TSimpleServer usually wait until
+ // they see the first byte of a request before calling processContext().
+ // However, they don't wait for the first byte of the very first request,
+ // and instead immediately call processContext() before any data is
+ // received.
+ //
+ // TNonblockingServer always waits until receiving the full request before
+ // calling processContext().
#if 0
ConnContext* context = reinterpret_cast<ConnContext*>(serverContext);
log_->append(EventLog::ET_PROCESS, context->id, 0);
@@ -240,14 +250,16 @@
#endif
}
-protected:
+ protected:
uint32_t nextId_;
boost::shared_ptr<EventLog> log_;
};
class ProcessorEventHandler : public TProcessorEventHandler {
-public:
- ProcessorEventHandler(const boost::shared_ptr<EventLog>& log) : nextId_(1), log_(log) {}
+ public:
+ ProcessorEventHandler(const boost::shared_ptr<EventLog>& log) :
+ nextId_(1),
+ log_(log) {}
void* getContext(const char* fnName, void* serverContext) {
ConnContext* connContext = reinterpret_cast<ConnContext*>(serverContext);
@@ -255,65 +267,71 @@
CallContext* context = new CallContext(connContext, nextId_, fnName);
++nextId_;
- log_->append(EventLog::ET_CALL_STARTED, connContext->id, context->id, fnName);
+ log_->append(EventLog::ET_CALL_STARTED, connContext->id, context->id,
+ fnName);
return context;
}
void freeContext(void* ctx, const char* fnName) {
CallContext* context = reinterpret_cast<CallContext*>(ctx);
checkName(context, fnName);
- log_->append(EventLog::ET_CALL_FINISHED, context->connContext->id, context->id, fnName);
+ log_->append(EventLog::ET_CALL_FINISHED, context->connContext->id,
+ context->id, fnName);
delete context;
}
void preRead(void* ctx, const char* fnName) {
CallContext* context = reinterpret_cast<CallContext*>(ctx);
checkName(context, fnName);
- log_->append(EventLog::ET_PRE_READ, context->connContext->id, context->id, fnName);
+ log_->append(EventLog::ET_PRE_READ, context->connContext->id, context->id,
+ fnName);
}
void postRead(void* ctx, const char* fnName, uint32_t bytes) {
THRIFT_UNUSED_VARIABLE(bytes);
CallContext* context = reinterpret_cast<CallContext*>(ctx);
checkName(context, fnName);
- log_->append(EventLog::ET_POST_READ, context->connContext->id, context->id, fnName);
+ log_->append(EventLog::ET_POST_READ, context->connContext->id, context->id,
+ fnName);
}
void preWrite(void* ctx, const char* fnName) {
CallContext* context = reinterpret_cast<CallContext*>(ctx);
checkName(context, fnName);
- log_->append(EventLog::ET_PRE_WRITE, context->connContext->id, context->id, fnName);
+ log_->append(EventLog::ET_PRE_WRITE, context->connContext->id, context->id,
+ fnName);
}
void postWrite(void* ctx, const char* fnName, uint32_t bytes) {
THRIFT_UNUSED_VARIABLE(bytes);
CallContext* context = reinterpret_cast<CallContext*>(ctx);
checkName(context, fnName);
- log_->append(EventLog::ET_POST_WRITE, context->connContext->id, context->id, fnName);
+ log_->append(EventLog::ET_POST_WRITE, context->connContext->id,
+ context->id, fnName);
}
void asyncComplete(void* ctx, const char* fnName) {
CallContext* context = reinterpret_cast<CallContext*>(ctx);
checkName(context, fnName);
- log_->append(EventLog::ET_ASYNC_COMPLETE, context->connContext->id, context->id, fnName);
+ log_->append(EventLog::ET_ASYNC_COMPLETE, context->connContext->id,
+ context->id, fnName);
}
void handlerError(void* ctx, const char* fnName) {
CallContext* context = reinterpret_cast<CallContext*>(ctx);
checkName(context, fnName);
- log_->append(EventLog::ET_HANDLER_ERROR, context->connContext->id, context->id, fnName);
+ log_->append(EventLog::ET_HANDLER_ERROR, context->connContext->id,
+ context->id, fnName);
}
-protected:
+ protected:
void checkName(const CallContext* context, const char* fnName) {
// Note: we can't use BOOST_CHECK_EQUAL here, since the handler runs in a
// different thread from the test functions. Just abort if the names are
// different
if (context->name != fnName) {
- fprintf(stderr,
- "call context name mismatch: \"%s\" != \"%s\"\n",
- context->name.c_str(),
- fnName);
+ fprintf(stderr, "call context name mismatch: \"%s\" != \"%s\"\n",
+ context->name.c_str(), fnName);
fflush(stderr);
abort();
}
@@ -322,8 +340,7 @@
uint32_t nextId_;
boost::shared_ptr<EventLog> log_;
};
-}
-}
-} // apache::thrift::test
+
+}}} // apache::thrift::test
#endif // _THRIFT_PROCESSOR_TEST_HANDLERS_H_
diff --git a/lib/cpp/test/processor/ProcessorTest.cpp b/lib/cpp/test/processor/ProcessorTest.cpp
index 300b729..eee90c7 100644
--- a/lib/cpp/test/processor/ProcessorTest.cpp
+++ b/lib/cpp/test/processor/ProcessorTest.cpp
@@ -54,7 +54,7 @@
*/
class TSimpleServerTraits {
-public:
+ public:
typedef TSimpleServer ServerType;
boost::shared_ptr<TSimpleServer> createServer(
@@ -63,13 +63,13 @@
const boost::shared_ptr<TTransportFactory>& transportFactory,
const boost::shared_ptr<TProtocolFactory>& protocolFactory) {
boost::shared_ptr<TServerSocket> socket(new TServerSocket(port));
- return boost::shared_ptr<TSimpleServer>(
- new TSimpleServer(processor, socket, transportFactory, protocolFactory));
+ return boost::shared_ptr<TSimpleServer>(new TSimpleServer(
+ processor, socket, transportFactory, protocolFactory));
}
};
class TThreadedServerTraits {
-public:
+ public:
typedef TThreadedServer ServerType;
boost::shared_ptr<TThreadedServer> createServer(
@@ -78,13 +78,13 @@
const boost::shared_ptr<TTransportFactory>& transportFactory,
const boost::shared_ptr<TProtocolFactory>& protocolFactory) {
boost::shared_ptr<TServerSocket> socket(new TServerSocket(port));
- return boost::shared_ptr<TThreadedServer>(
- new TThreadedServer(processor, socket, transportFactory, protocolFactory));
+ return boost::shared_ptr<TThreadedServer>(new TThreadedServer(
+ processor, socket, transportFactory, protocolFactory));
}
};
class TThreadPoolServerTraits {
-public:
+ public:
typedef TThreadPoolServer ServerType;
boost::shared_ptr<TThreadPoolServer> createServer(
@@ -95,17 +95,19 @@
boost::shared_ptr<TServerSocket> socket(new TServerSocket(port));
boost::shared_ptr<PosixThreadFactory> threadFactory(new PosixThreadFactory);
- boost::shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(8);
+ boost::shared_ptr<ThreadManager> threadManager =
+ ThreadManager::newSimpleThreadManager(8);
threadManager->threadFactory(threadFactory);
threadManager->start();
- return boost::shared_ptr<TThreadPoolServer>(
- new TThreadPoolServer(processor, socket, transportFactory, protocolFactory, threadManager));
+ return boost::shared_ptr<TThreadPoolServer>(new TThreadPoolServer(
+ processor, socket, transportFactory, protocolFactory,
+ threadManager));
}
};
class TNonblockingServerTraits {
-public:
+ public:
typedef TNonblockingServer ServerType;
boost::shared_ptr<TNonblockingServer> createServer(
@@ -116,24 +118,25 @@
// TNonblockingServer automatically uses TFramedTransport.
// Raise an exception if the supplied transport factory is not a
// TFramedTransportFactory
- TFramedTransportFactory* framedFactory
- = dynamic_cast<TFramedTransportFactory*>(transportFactory.get());
+ TFramedTransportFactory* framedFactory =
+ dynamic_cast<TFramedTransportFactory*>(transportFactory.get());
if (framedFactory == NULL) {
throw TException("TNonblockingServer must use TFramedTransport");
}
boost::shared_ptr<PosixThreadFactory> threadFactory(new PosixThreadFactory);
- boost::shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(8);
+ boost::shared_ptr<ThreadManager> threadManager =
+ ThreadManager::newSimpleThreadManager(8);
threadManager->threadFactory(threadFactory);
threadManager->start();
- return boost::shared_ptr<TNonblockingServer>(
- new TNonblockingServer(processor, protocolFactory, port, threadManager));
+ return boost::shared_ptr<TNonblockingServer>(new TNonblockingServer(
+ processor, protocolFactory, port, threadManager));
}
};
class TNonblockingServerNoThreadsTraits {
-public:
+ public:
typedef TNonblockingServer ServerType;
boost::shared_ptr<TNonblockingServer> createServer(
@@ -144,16 +147,16 @@
// TNonblockingServer automatically uses TFramedTransport.
// Raise an exception if the supplied transport factory is not a
// TFramedTransportFactory
- TFramedTransportFactory* framedFactory
- = dynamic_cast<TFramedTransportFactory*>(transportFactory.get());
+ TFramedTransportFactory* framedFactory =
+ dynamic_cast<TFramedTransportFactory*>(transportFactory.get());
if (framedFactory == NULL) {
throw TException("TNonblockingServer must use TFramedTransport");
}
// Use a NULL ThreadManager
boost::shared_ptr<ThreadManager> threadManager;
- return boost::shared_ptr<TNonblockingServer>(
- new TNonblockingServer(processor, protocolFactory, port, threadManager));
+ return boost::shared_ptr<TNonblockingServer>(new TNonblockingServer(
+ processor, protocolFactory, port, threadManager));
}
};
@@ -170,7 +173,7 @@
*/
class UntemplatedTraits {
-public:
+ public:
typedef TBinaryProtocolFactory ProtocolFactory;
typedef TBinaryProtocol Protocol;
@@ -181,7 +184,7 @@
};
class TemplatedTraits {
-public:
+ public:
typedef TBinaryProtocolFactoryT<TBufferBase> ProtocolFactory;
typedef TBinaryProtocolT<TBufferBase> Protocol;
@@ -191,9 +194,10 @@
typedef ChildServiceClientT<Protocol> ChildClient;
};
-template <typename TemplateTraits_>
+
+template<typename TemplateTraits_>
class ParentServiceTraits {
-public:
+ public:
typedef typename TemplateTraits_::ParentProcessor Processor;
typedef typename TemplateTraits_::ParentClient Client;
typedef ParentHandler Handler;
@@ -202,9 +206,9 @@
typedef typename TemplateTraits_::Protocol Protocol;
};
-template <typename TemplateTraits_>
+template<typename TemplateTraits_>
class ChildServiceTraits {
-public:
+ public:
typedef typename TemplateTraits_::ChildProcessor Processor;
typedef typename TemplateTraits_::ChildClient Client;
typedef ChildHandler Handler;
@@ -220,18 +224,17 @@
// It would also be niec if they used covariant return types. Unfortunately,
// since they return shared_ptr instead of raw pointers, covariant return types
// won't work.
-template <typename ServerTraits_,
- typename ServiceTraits_,
- typename TransportFactory_ = TFramedTransportFactory,
- typename Transport_ = TFramedTransport>
+template<typename ServerTraits_, typename ServiceTraits_,
+ typename TransportFactory_ = TFramedTransportFactory,
+ typename Transport_ = TFramedTransport>
class ServiceState : public ServerState {
-public:
+ public:
typedef typename ServiceTraits_::Processor Processor;
typedef typename ServiceTraits_::Client Client;
typedef typename ServiceTraits_::Handler Handler;
- ServiceState()
- : port_(0),
+ ServiceState() :
+ port_(0),
log_(new EventLog),
handler_(new Handler(log_)),
processor_(new Processor(handler_)),
@@ -244,18 +247,29 @@
boost::shared_ptr<TServer> createServer(uint16_t port) {
ServerTraits_ serverTraits;
- return serverTraits.createServer(processor_, port, transportFactory_, protocolFactory_);
+ return serverTraits.createServer(processor_, port, transportFactory_,
+ protocolFactory_);
}
- boost::shared_ptr<TServerEventHandler> getServerEventHandler() { return serverEventHandler_; }
+ boost::shared_ptr<TServerEventHandler> getServerEventHandler() {
+ return serverEventHandler_;
+ }
- void bindSuccessful(uint16_t port) { port_ = port; }
+ void bindSuccessful(uint16_t port) {
+ port_ = port;
+ }
- uint16_t getPort() const { return port_; }
+ uint16_t getPort() const {
+ return port_;
+ }
- const boost::shared_ptr<EventLog>& getLog() const { return log_; }
+ const boost::shared_ptr<EventLog>& getLog() const {
+ return log_;
+ }
- const boost::shared_ptr<Handler>& getHandler() const { return handler_; }
+ const boost::shared_ptr<Handler>& getHandler() const {
+ return handler_;
+ }
boost::shared_ptr<Client> createClient() {
typedef typename ServiceTraits_::Protocol Protocol;
@@ -269,7 +283,7 @@
return client;
}
-private:
+ private:
uint16_t port_;
boost::shared_ptr<EventLog> log_;
boost::shared_ptr<Handler> handler_;
@@ -280,6 +294,7 @@
boost::shared_ptr<TProcessorEventHandler> processorEventHandler_;
};
+
/**
* Check that there are no more events in the log
*/
@@ -421,7 +436,7 @@
* Test functions
*/
-template <typename State_>
+template<typename State_>
void testParentService(const boost::shared_ptr<State_>& state) {
boost::shared_ptr<typename State_::Client> client = state->createClient();
@@ -443,7 +458,7 @@
BOOST_REQUIRE_EQUAL("asdf", strings[2]);
}
-template <typename State_>
+template<typename State_>
void testChildService(const boost::shared_ptr<State_>& state) {
boost::shared_ptr<typename State_::Client> client = state->createClient();
@@ -461,9 +476,10 @@
BOOST_CHECK_EQUAL(99, client->getValue());
}
-template <typename ServerTraits, typename TemplateTraits>
+template<typename ServerTraits, typename TemplateTraits>
void testBasicService() {
- typedef ServiceState<ServerTraits, ParentServiceTraits<TemplateTraits> > State;
+ typedef ServiceState< ServerTraits, ParentServiceTraits<TemplateTraits> >
+ State;
// Start the server
boost::shared_ptr<State> state(new State);
@@ -472,9 +488,10 @@
testParentService(state);
}
-template <typename ServerTraits, typename TemplateTraits>
+template<typename ServerTraits, typename TemplateTraits>
void testInheritedService() {
- typedef ServiceState<ServerTraits, ChildServiceTraits<TemplateTraits> > State;
+ typedef ServiceState< ServerTraits, ChildServiceTraits<TemplateTraits> >
+ State;
// Start the server
boost::shared_ptr<State> state(new State);
@@ -488,16 +505,15 @@
* Test to make sure that the TServerEventHandler and TProcessorEventHandler
* methods are invoked in the correct order with the actual events.
*/
-template <typename ServerTraits, typename TemplateTraits>
+template<typename ServerTraits, typename TemplateTraits>
void testEventSequencing() {
// We use TBufferedTransport for this test, instead of TFramedTransport.
// This way the server will start processing data as soon as it is received,
// instead of waiting for the full request. This is necessary so we can
// separate the preRead() and postRead() events.
- typedef ServiceState<ServerTraits,
- ChildServiceTraits<TemplateTraits>,
- TBufferedTransportFactory,
- TBufferedTransport> State;
+ typedef ServiceState< ServerTraits, ChildServiceTraits<TemplateTraits>,
+ TBufferedTransportFactory, TBufferedTransport>
+ State;
// Start the server
boost::shared_ptr<State> state(new State);
@@ -546,7 +562,7 @@
// Send the rest of the request
protocol.writeStructBegin("ParentService_getDataNotified_pargs");
protocol.writeFieldBegin("length", apache::thrift::protocol::T_I32, 1);
- protocol.writeI32(8 * 1024 * 1024);
+ protocol.writeI32(8*1024*1024);
protocol.writeFieldEnd();
protocol.writeFieldStop();
protocol.writeStructEnd();
@@ -628,9 +644,10 @@
checkNoEvents(log);
}
-template <typename ServerTraits, typename TemplateTraits>
+template<typename ServerTraits, typename TemplateTraits>
void testSeparateConnections() {
- typedef ServiceState<ServerTraits, ChildServiceTraits<TemplateTraits> > State;
+ typedef ServiceState< ServerTraits, ChildServiceTraits<TemplateTraits> >
+ State;
// Start the server
boost::shared_ptr<State> state(new State);
@@ -656,19 +673,20 @@
// Make a call, and check for the proper events
int32_t value = 5;
client1->setValue(value);
- uint32_t call1
- = checkCallEvents(log, client1Id, EventLog::ET_CALL_SET_VALUE, "ChildService.setValue");
+ uint32_t call1 = checkCallEvents(log, client1Id, EventLog::ET_CALL_SET_VALUE,
+ "ChildService.setValue");
// Make a call with client2
int32_t v = client2->getValue();
BOOST_CHECK_EQUAL(value, v);
- checkCallEvents(log, client2Id, EventLog::ET_CALL_GET_VALUE, "ChildService.getValue");
+ checkCallEvents(log, client2Id, EventLog::ET_CALL_GET_VALUE,
+ "ChildService.getValue");
// Make another call with client1
v = client1->getValue();
BOOST_CHECK_EQUAL(value, v);
- uint32_t call2
- = checkCallEvents(log, client1Id, EventLog::ET_CALL_GET_VALUE, "ChildService.getValue");
+ uint32_t call2 = checkCallEvents(log, client1Id, EventLog::ET_CALL_GET_VALUE,
+ "ChildService.getValue");
BOOST_CHECK_NE(call1, call2);
// Close the second client, and check for the appropriate events
@@ -676,9 +694,10 @@
checkCloseEvents(log, client2Id);
}
-template <typename ServerTraits, typename TemplateTraits>
+template<typename ServerTraits, typename TemplateTraits>
void testOnewayCall() {
- typedef ServiceState<ServerTraits, ChildServiceTraits<TemplateTraits> > State;
+ typedef ServiceState< ServerTraits, ChildServiceTraits<TemplateTraits> >
+ State;
// Start the server
boost::shared_ptr<State> state(new State);
@@ -696,7 +715,9 @@
state->getHandler()->prepareTriggeredCall();
client->onewayWait();
string callName = "ParentService.onewayWait";
- uint32_t callId = checkCallHandlerEvents(log, connId, EventLog::ET_CALL_ONEWAY_WAIT, callName);
+ uint32_t callId = checkCallHandlerEvents(log, connId,
+ EventLog::ET_CALL_ONEWAY_WAIT,
+ callName);
// There shouldn't be any more events
checkNoEvents(log);
@@ -728,9 +749,10 @@
checkNoEvents(log);
}
-template <typename ServerTraits, typename TemplateTraits>
+template<typename ServerTraits, typename TemplateTraits>
void testExpectedError() {
- typedef ServiceState<ServerTraits, ChildServiceTraits<TemplateTraits> > State;
+ typedef ServiceState< ServerTraits, ChildServiceTraits<TemplateTraits> >
+ State;
// Start the server
boost::shared_ptr<State> state(new State);
@@ -747,7 +769,9 @@
string message = "test 1234 test";
client->send_exceptionWait(message);
string callName = "ParentService.exceptionWait";
- uint32_t callId = checkCallHandlerEvents(log, connId, EventLog::ET_CALL_EXCEPTION_WAIT, callName);
+ uint32_t callId = checkCallHandlerEvents(log, connId,
+ EventLog::ET_CALL_EXCEPTION_WAIT,
+ callName);
// There shouldn't be any more events
checkNoEvents(log);
@@ -780,9 +804,10 @@
checkNoEvents(log);
}
-template <typename ServerTraits, typename TemplateTraits>
+template<typename ServerTraits, typename TemplateTraits>
void testUnexpectedError() {
- typedef ServiceState<ServerTraits, ChildServiceTraits<TemplateTraits> > State;
+ typedef ServiceState< ServerTraits, ChildServiceTraits<TemplateTraits> >
+ State;
// Start the server
boost::shared_ptr<State> state(new State);
@@ -799,8 +824,8 @@
string message = "1234 test 5678";
client->send_unexpectedExceptionWait(message);
string callName = "ParentService.unexpectedExceptionWait";
- uint32_t callId
- = checkCallHandlerEvents(log, connId, EventLog::ET_CALL_UNEXPECTED_EXCEPTION_WAIT, callName);
+ uint32_t callId = checkCallHandlerEvents(
+ log, connId, EventLog::ET_CALL_UNEXPECTED_EXCEPTION_WAIT, callName);
// There shouldn't be any more events
checkNoEvents(log);
@@ -846,46 +871,47 @@
checkNoEvents(log);
}
+
// Macro to define simple tests that can be used with all server types
-#define DEFINE_SIMPLE_TESTS(Server, Template) \
- BOOST_AUTO_TEST_CASE(Server##_##Template##_basicService) { \
- testBasicService<Server##Traits, Template##Traits>(); \
- } \
- BOOST_AUTO_TEST_CASE(Server##_##Template##_inheritedService) { \
- testInheritedService<Server##Traits, Template##Traits>(); \
- } \
- BOOST_AUTO_TEST_CASE(Server##_##Template##_oneway) { \
- testOnewayCall<Server##Traits, Template##Traits>(); \
- } \
- BOOST_AUTO_TEST_CASE(Server##_##Template##_exception) { \
- testExpectedError<Server##Traits, Template##Traits>(); \
- } \
- BOOST_AUTO_TEST_CASE(Server##_##Template##_unexpectedException) { \
- testUnexpectedError<Server##Traits, Template##Traits>(); \
+#define DEFINE_SIMPLE_TESTS(Server, Template) \
+ BOOST_AUTO_TEST_CASE(Server##_##Template##_basicService) { \
+ testBasicService<Server##Traits, Template##Traits>(); \
+ } \
+ BOOST_AUTO_TEST_CASE(Server##_##Template##_inheritedService) { \
+ testInheritedService<Server##Traits, Template##Traits>(); \
+ } \
+ BOOST_AUTO_TEST_CASE(Server##_##Template##_oneway) { \
+ testOnewayCall<Server##Traits, Template##Traits>(); \
+ } \
+ BOOST_AUTO_TEST_CASE(Server##_##Template##_exception) { \
+ testExpectedError<Server##Traits, Template##Traits>(); \
+ } \
+ BOOST_AUTO_TEST_CASE(Server##_##Template##_unexpectedException) { \
+ testUnexpectedError<Server##Traits, Template##Traits>(); \
}
// Tests that require the server to process multiple connections concurrently
// (i.e., not TSimpleServer)
-#define DEFINE_CONCURRENT_SERVER_TESTS(Server, Template) \
- BOOST_AUTO_TEST_CASE(Server##_##Template##_separateConnections) { \
- testSeparateConnections<Server##Traits, Template##Traits>(); \
+#define DEFINE_CONCURRENT_SERVER_TESTS(Server, Template) \
+ BOOST_AUTO_TEST_CASE(Server##_##Template##_separateConnections) { \
+ testSeparateConnections<Server##Traits, Template##Traits>(); \
}
// The testEventSequencing() test manually generates a request for the server,
// and doesn't work with TFramedTransport. Therefore we can't test it with
// TNonblockingServer.
-#define DEFINE_NOFRAME_TESTS(Server, Template) \
- BOOST_AUTO_TEST_CASE(Server##_##Template##_eventSequencing) { \
- testEventSequencing<Server##Traits, Template##Traits>(); \
+#define DEFINE_NOFRAME_TESTS(Server, Template) \
+ BOOST_AUTO_TEST_CASE(Server##_##Template##_eventSequencing) { \
+ testEventSequencing<Server##Traits, Template##Traits>(); \
}
-#define DEFINE_TNONBLOCKINGSERVER_TESTS(Server, Template) \
- DEFINE_SIMPLE_TESTS(Server, Template) \
+#define DEFINE_TNONBLOCKINGSERVER_TESTS(Server, Template) \
+ DEFINE_SIMPLE_TESTS(Server, Template) \
DEFINE_CONCURRENT_SERVER_TESTS(Server, Template)
-#define DEFINE_ALL_SERVER_TESTS(Server, Template) \
- DEFINE_SIMPLE_TESTS(Server, Template) \
- DEFINE_CONCURRENT_SERVER_TESTS(Server, Template) \
+#define DEFINE_ALL_SERVER_TESTS(Server, Template) \
+ DEFINE_SIMPLE_TESTS(Server, Template) \
+ DEFINE_CONCURRENT_SERVER_TESTS(Server, Template) \
DEFINE_NOFRAME_TESTS(Server, Template)
DEFINE_ALL_SERVER_TESTS(TThreadedServer, Templated)
diff --git a/lib/cpp/test/processor/ServerThread.cpp b/lib/cpp/test/processor/ServerThread.cpp
index aa6fd7f..9f2087c 100644
--- a/lib/cpp/test/processor/ServerThread.cpp
+++ b/lib/cpp/test/processor/ServerThread.cpp
@@ -27,9 +27,7 @@
#include <thrift/transport/TBufferTransports.h>
#include <thrift/transport/TServerSocket.h>
-namespace apache {
-namespace thrift {
-namespace test {
+namespace apache { namespace thrift { namespace test {
void ServerThread::start() {
assert(!running_);
@@ -50,8 +48,9 @@
}
if (error_) {
- throw transport::TTransportException(transport::TTransportException::NOT_OPEN,
- "failed to bind on server socket");
+ throw transport::TTransportException(
+ transport::TTransportException::NOT_OPEN,
+ "failed to bind on server socket");
}
}
@@ -128,8 +127,8 @@
serverState_->bindSuccessful(port_);
// Set the real server event handler (replacing ourself)
- boost::shared_ptr<server::TServerEventHandler> serverEventHandler
- = serverState_->getServerEventHandler();
+ boost::shared_ptr<server::TServerEventHandler> serverEventHandler =
+ serverState_->getServerEventHandler();
server_->setServerEventHandler(serverEventHandler);
// Notify the main thread that we have successfully started serving requests
@@ -143,8 +142,7 @@
serverEventHandler->preServe();
}
}
-}
-}
-} // apache::thrift::test
+
+}}} // apache::thrift::test
#endif // _THRIFT_TEST_SERVERTHREAD_TCC_
diff --git a/lib/cpp/test/processor/ServerThread.h b/lib/cpp/test/processor/ServerThread.h
index eed3469..f7fa0d5 100644
--- a/lib/cpp/test/processor/ServerThread.h
+++ b/lib/cpp/test/processor/ServerThread.h
@@ -26,15 +26,13 @@
#include "EventLog.h"
-namespace apache {
-namespace thrift {
-namespace test {
+namespace apache { namespace thrift { namespace test {
/**
* A helper class to tell ServerThread how to create the server
*/
class ServerState {
-public:
+ public:
virtual ~ServerState() {}
/**
@@ -52,7 +50,8 @@
* start serving traffic. It is invoked from the server thread, rather than
* the main thread.
*/
- virtual boost::shared_ptr<server::TServerEventHandler> getServerEventHandler() {
+ virtual boost::shared_ptr<server::TServerEventHandler>
+ getServerEventHandler() {
return boost::shared_ptr<server::TServerEventHandler>();
}
@@ -62,16 +61,17 @@
* Subclasses may override this method if they wish to record the final
* port that was used for the server.
*/
- virtual void bindSuccessful(uint16_t /*port*/) {}
+ virtual void bindSuccessful(uint16_t /*port*/) {
+ }
};
/**
* ServerThread starts a thrift server running in a separate thread.
*/
class ServerThread {
-public:
- ServerThread(const boost::shared_ptr<ServerState>& state, bool autoStart)
- : helper_(new Helper(this)),
+ public:
+ ServerThread(const boost::shared_ptr<ServerState>& state, bool autoStart) :
+ helper_(new Helper(this)),
port_(0),
running_(false),
serving_(false),
@@ -85,7 +85,9 @@
void start();
void stop();
- uint16_t getPort() const { return port_; }
+ uint16_t getPort() const {
+ return port_;
+ }
~ServerThread() {
if (running_) {
@@ -97,20 +99,26 @@
}
}
-protected:
+ protected:
// Annoying. thrift forces us to use shared_ptr, so we have to use
// a helper class that we can allocate on the heap and give to thrift.
// It would be simpler if we could just make Runnable and TServerEventHandler
// private base classes of ServerThread.
- class Helper : public concurrency::Runnable, public server::TServerEventHandler {
- public:
- Helper(ServerThread* serverThread) : serverThread_(serverThread) {}
+ class Helper : public concurrency::Runnable,
+ public server::TServerEventHandler {
+ public:
+ Helper(ServerThread* serverThread)
+ : serverThread_(serverThread) {}
- void run() { serverThread_->run(); }
+ void run() {
+ serverThread_->run();
+ }
- void preServe() { serverThread_->preServe(); }
+ void preServe() {
+ serverThread_->preServe();
+ }
- private:
+ private:
ServerThread* serverThread_;
};
@@ -129,8 +137,7 @@
boost::shared_ptr<server::TServer> server_;
boost::shared_ptr<concurrency::Thread> thread_;
};
-}
-}
-} // apache::thrift::test
+
+}}} // apache::thrift::test
#endif // _THRIFT_TEST_SERVERTHREAD_H_