_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q170500 | Initializables.of | test | static <T> Initializable<T> of(final T instance) {
return new Initializable<T>() {
@Override
public T get() {
return instance;
}
@Override
public String toString() {
return String.valueOf(instance);
}
};
} | java | {
"resource": ""
} |
q170501 | ProviderInternalFactory.provision | test | protected T provision(
Provider<? extends T> provider,
Dependency<?> dependency,
ConstructionContext<T> constructionContext)
throws InternalProvisionException {
T t = provider.get();
if (t == null && !dependency.isNullable()) {
InternalProvisionException.onNullInjectedIntoNonNullableDependency(source, dependency);
}
constructionContext.setProxyDelegates(t);
return t;
} | java | {
"resource": ""
} |
q170502 | ConnectionEventListener.onEvent | test | public void onEvent(ConnectionEventType type, String remoteAddr, Connection conn) {
List<ConnectionEventProcessor> processorList = this.processors.get(type);
if (processorList != null) {
for (ConnectionEventProcessor processor : processorList) {
processor.onEvent(remoteAddr, conn);
}
}
} | java | {
"resource": ""
} |
q170503 | ConnectionEventListener.addConnectionEventProcessor | test | public void addConnectionEventProcessor(ConnectionEventType type,
ConnectionEventProcessor processor) {
List<ConnectionEventProcessor> processorList = this.processors.get(type);
if (processorList == null) {
this.processors.putIfAbsent(type, new ArrayList<ConnectionEventProcessor>(1));
processorList = this.processors.get(type);
}
processorList.add(processor);
} | java | {
"resource": ""
} |
q170504 | FutureTaskUtil.getFutureTaskResult | test | public static <T> T getFutureTaskResult(RunStateRecordedFutureTask<T> task, Logger logger) {
T t = null;
if (null != task) {
try {
t = task.getAfterRun();
} catch (InterruptedException e) {
logger.error("Future task interrupted!", e);
} catch (ExecutionException e) {
logger.error("Future task execute failed!", e);
} catch (FutureTaskNotRunYetException e) {
logger.error("Future task has not run yet!", e);
} catch (FutureTaskNotCompleted e) {
logger.error("Future task has not completed!", e);
}
}
return t;
} | java | {
"resource": ""
} |
q170505 | FutureTaskUtil.launderThrowable | test | public static void launderThrowable(Throwable t) {
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else if (t instanceof Error) {
throw (Error) t;
} else {
throw new IllegalStateException("Not unchecked!", t);
}
} | java | {
"resource": ""
} |
q170506 | ProcessorManager.registerProcessor | test | public void registerProcessor(CommandCode cmdCode, RemotingProcessor<?> processor) {
if (this.cmd2processors.containsKey(cmdCode)) {
logger
.warn(
"Processor for cmd={} is already registered, the processor is {}, and changed to {}",
cmdCode, cmd2processors.get(cmdCode).getClass().getName(), processor.getClass()
.getName());
}
this.cmd2processors.put(cmdCode, processor);
} | java | {
"resource": ""
} |
q170507 | ProcessorManager.registerDefaultProcessor | test | public void registerDefaultProcessor(RemotingProcessor<?> processor) {
if (this.defaultProcessor == null) {
this.defaultProcessor = processor;
} else {
throw new IllegalStateException("The defaultProcessor has already been registered: "
+ this.defaultProcessor.getClass());
}
} | java | {
"resource": ""
} |
q170508 | ProcessorManager.getProcessor | test | public RemotingProcessor<?> getProcessor(CommandCode cmdCode) {
RemotingProcessor<?> processor = this.cmd2processors.get(cmdCode);
if (processor != null) {
return processor;
}
return this.defaultProcessor;
} | java | {
"resource": ""
} |
q170509 | RpcAddressParser.tryGet | test | private Url tryGet(String url) {
SoftReference<Url> softRef = Url.parsedUrls.get(url);
return (null == softRef) ? null : softRef.get();
} | java | {
"resource": ""
} |
q170510 | ProtocolCodeBasedDecoder.decodeProtocolCode | test | protected ProtocolCode decodeProtocolCode(ByteBuf in) {
if (in.readableBytes() >= protocolCodeLength) {
byte[] protocolCodeBytes = new byte[protocolCodeLength];
in.readBytes(protocolCodeBytes);
return ProtocolCode.fromBytes(protocolCodeBytes);
}
return null;
} | java | {
"resource": ""
} |
q170511 | DefaultConnectionManager.getAll | test | @Override
public Map<String, List<Connection>> getAll() {
Map<String, List<Connection>> allConnections = new HashMap<String, List<Connection>>();
Iterator<Map.Entry<String, RunStateRecordedFutureTask<ConnectionPool>>> iterator = this
.getConnPools().entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, RunStateRecordedFutureTask<ConnectionPool>> entry = iterator.next();
ConnectionPool pool = FutureTaskUtil.getFutureTaskResult(entry.getValue(), logger);
if (null != pool) {
allConnections.put(entry.getKey(), pool.getAll());
}
}
return allConnections;
} | java | {
"resource": ""
} |
q170512 | DefaultConnectionManager.scan | test | @Override
public void scan() {
if (null != this.connTasks && !this.connTasks.isEmpty()) {
Iterator<String> iter = this.connTasks.keySet().iterator();
while (iter.hasNext()) {
String poolKey = iter.next();
ConnectionPool pool = this.getConnectionPool(this.connTasks.get(poolKey));
if (null != pool) {
pool.scan();
if (pool.isEmpty()) {
if ((System.currentTimeMillis() - pool.getLastAccessTimestamp()) > DEFAULT_EXPIRE_TIME) {
iter.remove();
logger.warn("Remove expired pool task of poolKey {} which is empty.",
poolKey);
}
}
}
}
}
} | java | {
"resource": ""
} |
q170513 | DefaultConnectionManager.getAndCreateIfAbsent | test | @Override
public Connection getAndCreateIfAbsent(Url url) throws InterruptedException, RemotingException {
// get and create a connection pool with initialized connections.
ConnectionPool pool = this.getConnectionPoolAndCreateIfAbsent(url.getUniqueKey(),
new ConnectionPoolCall(url));
if (null != pool) {
return pool.get();
} else {
logger.error("[NOTIFYME] bug detected! pool here must not be null!");
return null;
}
} | java | {
"resource": ""
} |
q170514 | DefaultConnectionManager.createConnectionAndHealIfNeed | test | @Override
public void createConnectionAndHealIfNeed(Url url) throws InterruptedException,
RemotingException {
// get and create a connection pool with initialized connections.
ConnectionPool pool = this.getConnectionPoolAndCreateIfAbsent(url.getUniqueKey(),
new ConnectionPoolCall(url));
if (null != pool) {
healIfNeed(pool, url);
} else {
logger.error("[NOTIFYME] bug detected! pool here must not be null!");
}
} | java | {
"resource": ""
} |
q170515 | DefaultConnectionManager.removeTask | test | private void removeTask(String poolKey) {
RunStateRecordedFutureTask<ConnectionPool> task = this.connTasks.remove(poolKey);
if (null != task) {
ConnectionPool pool = FutureTaskUtil.getFutureTaskResult(task, logger);
if (null != pool) {
pool.removeAllAndTryClose();
}
}
} | java | {
"resource": ""
} |
q170516 | DefaultConnectionManager.healIfNeed | test | private void healIfNeed(ConnectionPool pool, Url url) throws RemotingException,
InterruptedException {
String poolKey = url.getUniqueKey();
// only when async creating connections done
// and the actual size of connections less than expected, the healing task can be run.
if (pool.isAsyncCreationDone() && pool.size() < url.getConnNum()) {
FutureTask<Integer> task = this.healTasks.get(poolKey);
if (null == task) {
task = new FutureTask<Integer>(new HealConnectionCall(url, pool));
task = this.healTasks.putIfAbsent(poolKey, task);
if (null == task) {
task = this.healTasks.get(poolKey);
task.run();
}
}
try {
int numAfterHeal = task.get();
if (logger.isDebugEnabled()) {
logger.debug("[NOTIFYME] - conn num after heal {}, expected {}, warmup {}",
numAfterHeal, url.getConnNum(), url.isConnWarmup());
}
} catch (InterruptedException e) {
this.healTasks.remove(poolKey);
throw e;
} catch (ExecutionException e) {
this.healTasks.remove(poolKey);
Throwable cause = e.getCause();
if (cause instanceof RemotingException) {
throw (RemotingException) cause;
} else {
FutureTaskUtil.launderThrowable(cause);
}
}
// heal task is one-off, remove from cache directly after run
this.healTasks.remove(poolKey);
}
} | java | {
"resource": ""
} |
q170517 | DefaultConnectionManager.doCreate | test | private void doCreate(final Url url, final ConnectionPool pool, final String taskName,
final int syncCreateNumWhenNotWarmup) throws RemotingException {
final int actualNum = pool.size();
final int expectNum = url.getConnNum();
if (actualNum < expectNum) {
if (logger.isDebugEnabled()) {
logger.debug("actual num {}, expect num {}, task name {}", actualNum, expectNum,
taskName);
}
if (url.isConnWarmup()) {
for (int i = actualNum; i < expectNum; ++i) {
Connection connection = create(url);
pool.add(connection);
}
} else {
if (syncCreateNumWhenNotWarmup < 0 || syncCreateNumWhenNotWarmup > url.getConnNum()) {
throw new IllegalArgumentException(
"sync create number when not warmup should be [0," + url.getConnNum() + "]");
}
// create connection in sync way
if (syncCreateNumWhenNotWarmup > 0) {
for (int i = 0; i < syncCreateNumWhenNotWarmup; ++i) {
Connection connection = create(url);
pool.add(connection);
}
if (syncCreateNumWhenNotWarmup == url.getConnNum()) {
return;
}
}
// initialize executor in lazy way
initializeExecutor();
pool.markAsyncCreationStart();// mark the start of async
try {
this.asyncCreateConnectionExecutor.execute(new Runnable() {
@Override
public void run() {
try {
for (int i = pool.size(); i < url.getConnNum(); ++i) {
Connection conn = null;
try {
conn = create(url);
} catch (RemotingException e) {
logger
.error(
"Exception occurred in async create connection thread for {}, taskName {}",
url.getUniqueKey(), taskName, e);
}
pool.add(conn);
}
} finally {
pool.markAsyncCreationDone();// mark the end of async
}
}
});
} catch (RejectedExecutionException e) {
pool.markAsyncCreationDone();// mark the end of async when reject
throw e;
}
} // end of NOT warm up
} // end of if
} | java | {
"resource": ""
} |
q170518 | RpcClient.closeConnection | test | public void closeConnection(String addr) {
Url url = this.addressParser.parse(addr);
this.connectionManager.remove(url.getUniqueKey());
} | java | {
"resource": ""
} |
q170519 | Connection.onClose | test | public void onClose() {
Iterator<Entry<Integer, InvokeFuture>> iter = invokeFutureMap.entrySet().iterator();
while (iter.hasNext()) {
Entry<Integer, InvokeFuture> entry = iter.next();
iter.remove();
InvokeFuture future = entry.getValue();
if (future != null) {
future.putResponse(future.createConnectionClosedResponse(this.getRemoteAddress()));
future.cancelTimeout();
future.tryAsyncExecuteInvokeCallbackAbnormally();
}
}
} | java | {
"resource": ""
} |
q170520 | Connection.close | test | public void close() {
if (closed.compareAndSet(false, true)) {
try {
if (this.getChannel() != null) {
this.getChannel().close().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (logger.isInfoEnabled()) {
logger
.info(
"Close the connection to remote address={}, result={}, cause={}",
RemotingUtil.parseRemoteAddress(Connection.this
.getChannel()), future.isSuccess(), future.cause());
}
}
});
}
} catch (Exception e) {
logger.warn("Exception caught when closing connection {}",
RemotingUtil.parseRemoteAddress(Connection.this.getChannel()), e);
}
}
} | java | {
"resource": ""
} |
q170521 | Connection.setAttributeIfAbsent | test | public Object setAttributeIfAbsent(String key, Object value) {
return attributes.putIfAbsent(key, value);
} | java | {
"resource": ""
} |
q170522 | UserProcessorRegisterHelper.registerUserProcessor | test | public static void registerUserProcessor(UserProcessor<?> processor,
ConcurrentHashMap<String, UserProcessor<?>> userProcessors) {
if (null == processor) {
throw new RuntimeException("User processor should not be null!");
}
if (processor instanceof MultiInterestUserProcessor) {
registerUserProcessor((MultiInterestUserProcessor) processor, userProcessors);
} else {
if (StringUtils.isBlank(processor.interest())) {
throw new RuntimeException("Processor interest should not be blank!");
}
UserProcessor<?> preProcessor = userProcessors.putIfAbsent(processor.interest(),
processor);
if (preProcessor != null) {
String errMsg = "Processor with interest key ["
+ processor.interest()
+ "] has already been registered to rpc server, can not register again!";
throw new RuntimeException(errMsg);
}
}
} | java | {
"resource": ""
} |
q170523 | UserProcessorRegisterHelper.registerUserProcessor | test | private static void registerUserProcessor(MultiInterestUserProcessor<?> processor,
ConcurrentHashMap<String, UserProcessor<?>> userProcessors) {
if (null == processor.multiInterest() || processor.multiInterest().isEmpty()) {
throw new RuntimeException("Processor interest should not be blank!");
}
for (String interest : processor.multiInterest()) {
UserProcessor<?> preProcessor = userProcessors.putIfAbsent(interest, processor);
if (preProcessor != null) {
String errMsg = "Processor with interest key ["
+ interest
+ "] has already been registered to rpc server, can not register again!";
throw new RuntimeException(errMsg);
}
}
} | java | {
"resource": ""
} |
q170524 | RpcRequestProcessor.dispatchToUserProcessor | test | private void dispatchToUserProcessor(RemotingContext ctx, RpcRequestCommand cmd) {
final int id = cmd.getId();
final byte type = cmd.getType();
// processor here must not be null, for it have been checked before
UserProcessor processor = ctx.getUserProcessor(cmd.getRequestClass());
if (processor instanceof AsyncUserProcessor) {
try {
processor.handleRequest(processor.preHandleRequest(ctx, cmd.getRequestObject()),
new RpcAsyncContext(ctx, cmd, this), cmd.getRequestObject());
} catch (RejectedExecutionException e) {
logger
.warn("RejectedExecutionException occurred when do ASYNC process in RpcRequestProcessor");
sendResponseIfNecessary(ctx, type, this.getCommandFactory()
.createExceptionResponse(id, ResponseStatus.SERVER_THREADPOOL_BUSY));
} catch (Throwable t) {
String errMsg = "AYSNC process rpc request failed in RpcRequestProcessor, id=" + id;
logger.error(errMsg, t);
sendResponseIfNecessary(ctx, type, this.getCommandFactory()
.createExceptionResponse(id, t, errMsg));
}
} else {
try {
Object responseObject = processor
.handleRequest(processor.preHandleRequest(ctx, cmd.getRequestObject()),
cmd.getRequestObject());
sendResponseIfNecessary(ctx, type,
this.getCommandFactory().createResponse(responseObject, cmd));
} catch (RejectedExecutionException e) {
logger
.warn("RejectedExecutionException occurred when do SYNC process in RpcRequestProcessor");
sendResponseIfNecessary(ctx, type, this.getCommandFactory()
.createExceptionResponse(id, ResponseStatus.SERVER_THREADPOOL_BUSY));
} catch (Throwable t) {
String errMsg = "SYNC process rpc request failed in RpcRequestProcessor, id=" + id;
logger.error(errMsg, t);
sendResponseIfNecessary(ctx, type, this.getCommandFactory()
.createExceptionResponse(id, t, errMsg));
}
}
} | java | {
"resource": ""
} |
q170525 | RpcRequestProcessor.deserializeRequestCommand | test | private boolean deserializeRequestCommand(RemotingContext ctx, RpcRequestCommand cmd, int level) {
boolean result;
try {
cmd.deserialize(level);
result = true;
} catch (DeserializationException e) {
logger
.error(
"DeserializationException occurred when process in RpcRequestProcessor, id={}, deserializeLevel={}",
cmd.getId(), RpcDeserializeLevel.valueOf(level), e);
sendResponseIfNecessary(ctx, cmd.getType(), this.getCommandFactory()
.createExceptionResponse(cmd.getId(), ResponseStatus.SERVER_DESERIAL_EXCEPTION, e));
result = false;
} catch (Throwable t) {
String errMsg = "Deserialize RpcRequestCommand failed in RpcRequestProcessor, id="
+ cmd.getId() + ", deserializeLevel=" + level;
logger.error(errMsg, t);
sendResponseIfNecessary(ctx, cmd.getType(), this.getCommandFactory()
.createExceptionResponse(cmd.getId(), t, errMsg));
result = false;
}
return result;
} | java | {
"resource": ""
} |
q170526 | RpcRequestProcessor.preProcessRemotingContext | test | private void preProcessRemotingContext(RemotingContext ctx, RpcRequestCommand cmd,
long currentTimestamp) {
ctx.setArriveTimestamp(cmd.getArriveTime());
ctx.setTimeout(cmd.getTimeout());
ctx.setRpcCommandType(cmd.getType());
ctx.getInvokeContext().putIfAbsent(InvokeContext.BOLT_PROCESS_WAIT_TIME,
currentTimestamp - cmd.getArriveTime());
} | java | {
"resource": ""
} |
q170527 | RpcRequestProcessor.timeoutLog | test | private void timeoutLog(final RpcRequestCommand cmd, long currentTimestamp, RemotingContext ctx) {
if (logger.isDebugEnabled()) {
logger
.debug(
"request id [{}] currenTimestamp [{}] - arriveTime [{}] = server cost [{}] >= timeout value [{}].",
cmd.getId(), currentTimestamp, cmd.getArriveTime(),
(currentTimestamp - cmd.getArriveTime()), cmd.getTimeout());
}
String remoteAddr = "UNKNOWN";
if (null != ctx) {
ChannelHandlerContext channelCtx = ctx.getChannelContext();
Channel channel = channelCtx.channel();
if (null != channel) {
remoteAddr = RemotingUtil.parseRemoteAddress(channel);
}
}
logger
.warn(
"Rpc request id[{}], from remoteAddr[{}] stop process, total wait time in queue is [{}], client timeout setting is [{}].",
cmd.getId(), remoteAddr, (currentTimestamp - cmd.getArriveTime()), cmd.getTimeout());
} | java | {
"resource": ""
} |
q170528 | RpcRequestProcessor.debugLog | test | private void debugLog(RemotingContext ctx, RpcRequestCommand cmd, long currentTimestamp) {
if (logger.isDebugEnabled()) {
logger.debug("Rpc request received! requestId={}, from {}", cmd.getId(),
RemotingUtil.parseRemoteAddress(ctx.getChannelContext().channel()));
logger.debug(
"request id {} currenTimestamp {} - arriveTime {} = server cost {} < timeout {}.",
cmd.getId(), currentTimestamp, cmd.getArriveTime(),
(currentTimestamp - cmd.getArriveTime()), cmd.getTimeout());
}
} | java | {
"resource": ""
} |
q170529 | AbstractRemotingProcessor.process | test | @Override
public void process(RemotingContext ctx, T msg, ExecutorService defaultExecutor)
throws Exception {
ProcessTask task = new ProcessTask(ctx, msg);
if (this.getExecutor() != null) {
this.getExecutor().execute(task);
} else {
defaultExecutor.execute(task);
}
} | java | {
"resource": ""
} |
q170530 | BaseRemoting.invokeWithCallback | test | protected void invokeWithCallback(final Connection conn, final RemotingCommand request,
final InvokeCallback invokeCallback, final int timeoutMillis) {
final InvokeFuture future = createInvokeFuture(conn, request, request.getInvokeContext(),
invokeCallback);
conn.addInvokeFuture(future);
final int requestId = request.getId();
try {
Timeout timeout = TimerHolder.getTimer().newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
InvokeFuture future = conn.removeInvokeFuture(requestId);
if (future != null) {
future.putResponse(commandFactory.createTimeoutResponse(conn
.getRemoteAddress()));
future.tryAsyncExecuteInvokeCallbackAbnormally();
}
}
}, timeoutMillis, TimeUnit.MILLISECONDS);
future.addTimeout(timeout);
conn.getChannel().writeAndFlush(request).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture cf) throws Exception {
if (!cf.isSuccess()) {
InvokeFuture f = conn.removeInvokeFuture(requestId);
if (f != null) {
f.cancelTimeout();
f.putResponse(commandFactory.createSendFailedResponse(
conn.getRemoteAddress(), cf.cause()));
f.tryAsyncExecuteInvokeCallbackAbnormally();
}
logger.error("Invoke send failed. The address is {}",
RemotingUtil.parseRemoteAddress(conn.getChannel()), cf.cause());
}
}
});
} catch (Exception e) {
InvokeFuture f = conn.removeInvokeFuture(requestId);
if (f != null) {
f.cancelTimeout();
f.putResponse(commandFactory.createSendFailedResponse(conn.getRemoteAddress(), e));
f.tryAsyncExecuteInvokeCallbackAbnormally();
}
logger.error("Exception caught when sending invocation. The address is {}",
RemotingUtil.parseRemoteAddress(conn.getChannel()), e);
}
} | java | {
"resource": ""
} |
q170531 | BaseRemoting.oneway | test | protected void oneway(final Connection conn, final RemotingCommand request) {
try {
conn.getChannel().writeAndFlush(request).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture f) throws Exception {
if (!f.isSuccess()) {
logger.error("Invoke send failed. The address is {}",
RemotingUtil.parseRemoteAddress(conn.getChannel()), f.cause());
}
}
});
} catch (Exception e) {
if (null == conn) {
logger.error("Conn is null");
} else {
logger.error("Exception caught when sending invocation. The address is {}",
RemotingUtil.parseRemoteAddress(conn.getChannel()), e);
}
}
} | java | {
"resource": ""
} |
q170532 | ProtocolSwitch.toByte | test | public static byte toByte(BitSet bs) {
int value = 0;
for (int i = 0; i < bs.length(); ++i) {
if (bs.get(i)) {
value += 1 << i;
}
}
if (bs.length() > 7) {
throw new IllegalArgumentException("The byte value " + value
+ " generated according to bit set " + bs
+ " is out of range, should be limited between ["
+ Byte.MIN_VALUE + "] to [" + Byte.MAX_VALUE + "]");
}
return (byte) value;
} | java | {
"resource": ""
} |
q170533 | ProtocolSwitch.toBitSet | test | public static BitSet toBitSet(int value) {
if (value > Byte.MAX_VALUE || value < Byte.MIN_VALUE) {
throw new IllegalArgumentException(
"The value " + value + " is out of byte range, should be limited between ["
+ Byte.MIN_VALUE + "] to [" + Byte.MAX_VALUE + "]");
}
BitSet bs = new BitSet();
int index = 0;
while (value != 0) {
if (value % 2 != 0) {
bs.set(index);
}
++index;
value = (byte) (value >> 1);
}
return bs;
} | java | {
"resource": ""
} |
q170534 | ReconnectManager.addReconnectTask | test | public void addReconnectTask(Url url) {
ReconnectTask task = new ReconnectTask();
task.url = url;
tasks.add(task);
} | java | {
"resource": ""
} |
q170535 | ReconnectManager.stop | test | public void stop() {
if (!this.started) {
return;
}
this.started = false;
healConnectionThreads.interrupt();
this.tasks.clear();
this.canceled.clear();
} | java | {
"resource": ""
} |
q170536 | RpcRemoting.toRemotingCommand | test | protected RemotingCommand toRemotingCommand(Object request, Connection conn,
InvokeContext invokeContext, int timeoutMillis)
throws SerializationException {
RpcRequestCommand command = this.getCommandFactory().createRequestCommand(request);
if (null != invokeContext) {
// set client custom serializer for request command if not null
Object clientCustomSerializer = invokeContext.get(InvokeContext.BOLT_CUSTOM_SERIALIZER);
if (null != clientCustomSerializer) {
try {
command.setSerializer((Byte) clientCustomSerializer);
} catch (ClassCastException e) {
throw new IllegalArgumentException(
"Illegal custom serializer [" + clientCustomSerializer
+ "], the type of value should be [byte], but now is ["
+ clientCustomSerializer.getClass().getName() + "].");
}
}
// enable crc by default, user can disable by set invoke context `false` for key `InvokeContext.BOLT_CRC_SWITCH`
Boolean crcSwitch = invokeContext.get(InvokeContext.BOLT_CRC_SWITCH,
ProtocolSwitch.CRC_SWITCH_DEFAULT_VALUE);
if (null != crcSwitch && crcSwitch) {
command.setProtocolSwitch(ProtocolSwitch
.create(new int[] { ProtocolSwitch.CRC_SWITCH_INDEX }));
}
} else {
// enable crc by default, if there is no invoke context.
command.setProtocolSwitch(ProtocolSwitch
.create(new int[] { ProtocolSwitch.CRC_SWITCH_INDEX }));
}
command.setTimeout(timeoutMillis);
command.setRequestClass(request.getClass().getName());
command.setInvokeContext(invokeContext);
command.serialize();
logDebugInfo(command);
return command;
} | java | {
"resource": ""
} |
q170537 | ScheduledDisconnectStrategy.filter | test | @Override
public Map<String, List<Connection>> filter(List<Connection> connections) {
List<Connection> serviceOnConnections = new ArrayList<Connection>();
List<Connection> serviceOffConnections = new ArrayList<Connection>();
Map<String, List<Connection>> filteredConnections = new ConcurrentHashMap<String, List<Connection>>();
for (Connection connection : connections) {
String serviceStatus = (String) connection.getAttribute(Configs.CONN_SERVICE_STATUS);
if (serviceStatus != null) {
if (connection.isInvokeFutureMapFinish()
&& !freshSelectConnections.containsValue(connection)) {
serviceOffConnections.add(connection);
}
} else {
serviceOnConnections.add(connection);
}
}
filteredConnections.put(Configs.CONN_SERVICE_STATUS_ON, serviceOnConnections);
filteredConnections.put(Configs.CONN_SERVICE_STATUS_OFF, serviceOffConnections);
return filteredConnections;
} | java | {
"resource": ""
} |
q170538 | ScheduledDisconnectStrategy.monitor | test | @Override
public void monitor(Map<String, RunStateRecordedFutureTask<ConnectionPool>> connPools) {
try {
if (null != connPools && !connPools.isEmpty()) {
Iterator<Map.Entry<String, RunStateRecordedFutureTask<ConnectionPool>>> iter = connPools
.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, RunStateRecordedFutureTask<ConnectionPool>> entry = iter
.next();
String poolKey = entry.getKey();
ConnectionPool pool = FutureTaskUtil.getFutureTaskResult(entry.getValue(),
logger);
List<Connection> connections = pool.getAll();
Map<String, List<Connection>> filteredConnectons = this.filter(connections);
List<Connection> serviceOnConnections = filteredConnectons
.get(Configs.CONN_SERVICE_STATUS_ON);
List<Connection> serviceOffConnections = filteredConnectons
.get(Configs.CONN_SERVICE_STATUS_OFF);
if (serviceOnConnections.size() > CONNECTION_THRESHOLD) {
Connection freshSelectConnect = serviceOnConnections.get(random
.nextInt(serviceOnConnections.size()));
freshSelectConnect.setAttribute(Configs.CONN_SERVICE_STATUS,
Configs.CONN_SERVICE_STATUS_OFF);
Connection lastSelectConnect = freshSelectConnections.remove(poolKey);
freshSelectConnections.put(poolKey, freshSelectConnect);
closeFreshSelectConnections(lastSelectConnect, serviceOffConnections);
} else {
if (freshSelectConnections.containsKey(poolKey)) {
Connection lastSelectConnect = freshSelectConnections.remove(poolKey);
closeFreshSelectConnections(lastSelectConnect, serviceOffConnections);
}
if (logger.isInfoEnabled()) {
logger
.info(
"the size of serviceOnConnections [{}] reached CONNECTION_THRESHOLD [{}].",
serviceOnConnections.size(), CONNECTION_THRESHOLD);
}
}
for (Connection offConn : serviceOffConnections) {
if (offConn.isFine()) {
offConn.close();
}
}
}
}
} catch (Exception e) {
logger.error("ScheduledDisconnectStrategy monitor error", e);
}
} | java | {
"resource": ""
} |
q170539 | ScheduledDisconnectStrategy.closeFreshSelectConnections | test | private void closeFreshSelectConnections(Connection lastSelectConnect,
List<Connection> serviceOffConnections)
throws InterruptedException {
if (null != lastSelectConnect) {
if (lastSelectConnect.isInvokeFutureMapFinish()) {
serviceOffConnections.add(lastSelectConnect);
} else {
Thread.sleep(RETRY_DETECT_PERIOD);
if (lastSelectConnect.isInvokeFutureMapFinish()) {
serviceOffConnections.add(lastSelectConnect);
} else {
if (logger.isInfoEnabled()) {
logger.info("Address={} won't close at this schedule turn",
RemotingUtil.parseRemoteAddress(lastSelectConnect.getChannel()));
}
}
}
}
} | java | {
"resource": ""
} |
q170540 | ConfigManager.getBool | test | public static boolean getBool(String key, String defaultValue) {
return Boolean.parseBoolean(System.getProperty(key, defaultValue));
} | java | {
"resource": ""
} |
q170541 | ConnectionEventHandler.infoLog | test | private void infoLog(String format, String addr) {
if (logger.isInfoEnabled()) {
if (StringUtils.isNotEmpty(addr)) {
logger.info(format, addr);
} else {
logger.info(format, "UNKNOWN-ADDR");
}
}
} | java | {
"resource": ""
} |
q170542 | RemotingContext.isRequestTimeout | test | public boolean isRequestTimeout() {
if (this.timeout > 0 && (this.rpcCommandType != RpcCommandType.REQUEST_ONEWAY)
&& (System.currentTimeMillis() - this.arriveTimestamp) > this.timeout) {
return true;
}
return false;
} | java | {
"resource": ""
} |
q170543 | RemotingContext.getUserProcessor | test | public UserProcessor<?> getUserProcessor(String className) {
return StringUtils.isBlank(className) ? null : this.userProcessors.get(className);
} | java | {
"resource": ""
} |
q170544 | RandomSelectStrategy.randomGet | test | private Connection randomGet(List<Connection> conns) {
if (null == conns || conns.isEmpty()) {
return null;
}
int size = conns.size();
int tries = 0;
Connection result = null;
while ((result == null || !result.isFine()) && tries++ < MAX_TIMES) {
result = conns.get(this.random.nextInt(size));
}
if (result != null && !result.isFine()) {
result = null;
}
return result;
} | java | {
"resource": ""
} |
q170545 | InvokeContext.get | test | @SuppressWarnings("unchecked")
public <T> T get(String key, T defaultIfNotFound) {
return this.context.get(key) != null ? (T) this.context.get(key) : defaultIfNotFound;
} | java | {
"resource": ""
} |
q170546 | Url.getProperty | test | public String getProperty(String key) {
if (properties == null) {
return null;
}
return properties.getProperty(key);
} | java | {
"resource": ""
} |
q170547 | RpcResponseResolver.resolveResponseObject | test | public static Object resolveResponseObject(ResponseCommand responseCommand, String addr)
throws RemotingException {
preProcess(responseCommand, addr);
if (responseCommand.getResponseStatus() == ResponseStatus.SUCCESS) {
return toResponseObject(responseCommand);
} else {
String msg = String.format("Rpc invocation exception: %s, the address is %s, id=%s",
responseCommand.getResponseStatus(), addr, responseCommand.getId());
logger.warn(msg);
if (responseCommand.getCause() != null) {
throw new InvokeException(msg, responseCommand.getCause());
} else {
throw new InvokeException(msg + ", please check the server log for more.");
}
}
} | java | {
"resource": ""
} |
q170548 | RpcResponseResolver.toResponseObject | test | private static Object toResponseObject(ResponseCommand responseCommand) throws CodecException {
RpcResponseCommand response = (RpcResponseCommand) responseCommand;
response.deserialize();
return response.getResponseObject();
} | java | {
"resource": ""
} |
q170549 | RpcResponseResolver.toThrowable | test | private static Throwable toThrowable(ResponseCommand responseCommand) throws CodecException {
RpcResponseCommand resp = (RpcResponseCommand) responseCommand;
resp.deserialize();
Object ex = resp.getResponseObject();
if (ex != null && ex instanceof Throwable) {
return (Throwable) ex;
}
return null;
} | java | {
"resource": ""
} |
q170550 | RpcResponseResolver.detailErrMsg | test | private static String detailErrMsg(String clientErrMsg, ResponseCommand responseCommand) {
RpcResponseCommand resp = (RpcResponseCommand) responseCommand;
if (StringUtils.isNotBlank(resp.getErrorMsg())) {
return String.format("%s, ServerErrorMsg:%s", clientErrMsg, resp.getErrorMsg());
} else {
return String.format("%s, ServerErrorMsg:null", clientErrMsg);
}
} | java | {
"resource": ""
} |
q170551 | RpcCommandFactory.createServerException | test | private RpcServerException createServerException(Throwable t, String errMsg) {
String formattedErrMsg = String.format(
"[Server]OriginErrorMsg: %s: %s. AdditionalErrorMsg: %s", t.getClass().getName(),
t.getMessage(), errMsg);
RpcServerException e = new RpcServerException(formattedErrMsg);
e.setStackTrace(t.getStackTrace());
return e;
} | java | {
"resource": ""
} |
q170552 | TraceLogUtil.printConnectionTraceLog | test | public static void printConnectionTraceLog(Logger logger, String traceId,
InvokeContext invokeContext) {
String sourceIp = invokeContext.get(InvokeContext.CLIENT_LOCAL_IP);
Integer sourcePort = invokeContext.get(InvokeContext.CLIENT_LOCAL_PORT);
String targetIp = invokeContext.get(InvokeContext.CLIENT_REMOTE_IP);
Integer targetPort = invokeContext.get(InvokeContext.CLIENT_REMOTE_PORT);
StringBuilder logMsg = new StringBuilder();
logMsg.append(traceId).append(",");
logMsg.append(sourceIp).append(",");
logMsg.append(sourcePort).append(",");
logMsg.append(targetIp).append(",");
logMsg.append(targetPort);
if (logger.isInfoEnabled()) {
logger.info(logMsg.toString());
}
} | java | {
"resource": ""
} |
q170553 | NettyEventLoopUtil.newEventLoopGroup | test | public static EventLoopGroup newEventLoopGroup(int nThreads, ThreadFactory threadFactory) {
return epollEnabled ? new EpollEventLoopGroup(nThreads, threadFactory)
: new NioEventLoopGroup(nThreads, threadFactory);
} | java | {
"resource": ""
} |
q170554 | RemotingUtil.parseRemoteAddress | test | public static String parseRemoteAddress(final Channel channel) {
if (null == channel) {
return StringUtils.EMPTY;
}
final SocketAddress remote = channel.remoteAddress();
return doParse(remote != null ? remote.toString().trim() : StringUtils.EMPTY);
} | java | {
"resource": ""
} |
q170555 | RemotingUtil.parseLocalAddress | test | public static String parseLocalAddress(final Channel channel) {
if (null == channel) {
return StringUtils.EMPTY;
}
final SocketAddress local = channel.localAddress();
return doParse(local != null ? local.toString().trim() : StringUtils.EMPTY);
} | java | {
"resource": ""
} |
q170556 | RemotingUtil.parseRemoteIP | test | public static String parseRemoteIP(final Channel channel) {
if (null == channel) {
return StringUtils.EMPTY;
}
final InetSocketAddress remote = (InetSocketAddress) channel.remoteAddress();
if (remote != null) {
return remote.getAddress().getHostAddress();
}
return StringUtils.EMPTY;
} | java | {
"resource": ""
} |
q170557 | RemotingUtil.parseRemoteHostName | test | public static String parseRemoteHostName(final Channel channel) {
if (null == channel) {
return StringUtils.EMPTY;
}
final InetSocketAddress remote = (InetSocketAddress) channel.remoteAddress();
if (remote != null) {
return remote.getAddress().getHostName();
}
return StringUtils.EMPTY;
} | java | {
"resource": ""
} |
q170558 | RemotingUtil.parseLocalIP | test | public static String parseLocalIP(final Channel channel) {
if (null == channel) {
return StringUtils.EMPTY;
}
final InetSocketAddress local = (InetSocketAddress) channel.localAddress();
if (local != null) {
return local.getAddress().getHostAddress();
}
return StringUtils.EMPTY;
} | java | {
"resource": ""
} |
q170559 | RemotingUtil.parseRemotePort | test | public static int parseRemotePort(final Channel channel) {
if (null == channel) {
return -1;
}
final InetSocketAddress remote = (InetSocketAddress) channel.remoteAddress();
if (remote != null) {
return remote.getPort();
}
return -1;
} | java | {
"resource": ""
} |
q170560 | RemotingUtil.parseLocalPort | test | public static int parseLocalPort(final Channel channel) {
if (null == channel) {
return -1;
}
final InetSocketAddress local = (InetSocketAddress) channel.localAddress();
if (local != null) {
return local.getPort();
}
return -1;
} | java | {
"resource": ""
} |
q170561 | RemotingUtil.parseSocketAddressToHostIp | test | public static String parseSocketAddressToHostIp(SocketAddress socketAddress) {
final InetSocketAddress addrs = (InetSocketAddress) socketAddress;
if (addrs != null) {
InetAddress addr = addrs.getAddress();
if (null != addr) {
return addr.getHostAddress();
}
}
return StringUtils.EMPTY;
} | java | {
"resource": ""
} |
q170562 | ConnectionPool.add | test | public void add(Connection connection) {
markAccess();
if (null == connection) {
return;
}
boolean res = this.conns.addIfAbsent(connection);
if (res) {
connection.increaseRef();
}
} | java | {
"resource": ""
} |
q170563 | ConnectionPool.removeAndTryClose | test | public void removeAndTryClose(Connection connection) {
if (null == connection) {
return;
}
boolean res = this.conns.remove(connection);
if (res) {
connection.decreaseRef();
}
if (connection.noRef()) {
connection.close();
}
} | java | {
"resource": ""
} |
q170564 | ConnectionPool.get | test | public Connection get() {
markAccess();
if (null != this.conns) {
List<Connection> snapshot = new ArrayList<Connection>(this.conns);
if (snapshot.size() > 0) {
return this.strategy.select(snapshot);
} else {
return null;
}
} else {
return null;
}
} | java | {
"resource": ""
} |
q170565 | CustomSerializerManager.registerCustomSerializer | test | public static void registerCustomSerializer(String className, CustomSerializer serializer) {
CustomSerializer prevSerializer = classCustomSerializer.putIfAbsent(className, serializer);
if (prevSerializer != null) {
throw new RuntimeException("CustomSerializer has been registered for class: "
+ className + ", the custom serializer is: "
+ prevSerializer.getClass().getName());
}
} | java | {
"resource": ""
} |
q170566 | CustomSerializerManager.getCustomSerializer | test | public static CustomSerializer getCustomSerializer(String className) {
if (!classCustomSerializer.isEmpty()) {
return classCustomSerializer.get(className);
}
return null;
} | java | {
"resource": ""
} |
q170567 | CustomSerializerManager.registerCustomSerializer | test | public static void registerCustomSerializer(CommandCode code, CustomSerializer serializer) {
CustomSerializer prevSerializer = commandCustomSerializer.putIfAbsent(code, serializer);
if (prevSerializer != null) {
throw new RuntimeException("CustomSerializer has been registered for command code: "
+ code + ", the custom serializer is: "
+ prevSerializer.getClass().getName());
}
} | java | {
"resource": ""
} |
q170568 | CustomSerializerManager.getCustomSerializer | test | public static CustomSerializer getCustomSerializer(CommandCode code) {
if (!commandCustomSerializer.isEmpty()) {
return commandCustomSerializer.get(code);
}
return null;
} | java | {
"resource": ""
} |
q170569 | DefaultConnectionMonitor.start | test | public void start() {
/** initial delay to execute schedule task, unit: ms */
long initialDelay = ConfigManager.conn_monitor_initial_delay();
/** period of schedule task, unit: ms*/
long period = ConfigManager.conn_monitor_period();
this.executor = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory(
"ConnectionMonitorThread", true), new ThreadPoolExecutor.AbortPolicy());
MonitorTask monitorTask = new MonitorTask();
this.executor.scheduleAtFixedRate(monitorTask, initialDelay, period, TimeUnit.MILLISECONDS);
} | java | {
"resource": ""
} |
q170570 | RpcServer.isConnected | test | public boolean isConnected(String remoteAddr) {
Url url = this.rpcRemoting.addressParser.parse(remoteAddr);
return this.isConnected(url);
} | java | {
"resource": ""
} |
q170571 | RpcServer.initWriteBufferWaterMark | test | private void initWriteBufferWaterMark() {
int lowWaterMark = this.netty_buffer_low_watermark();
int highWaterMark = this.netty_buffer_high_watermark();
if (lowWaterMark > highWaterMark) {
throw new IllegalArgumentException(
String
.format(
"[server side] bolt netty high water mark {%s} should not be smaller than low water mark {%s} bytes)",
highWaterMark, lowWaterMark));
} else {
logger.warn(
"[server side] bolt netty low water mark is {} bytes, high water mark is {} bytes",
lowWaterMark, highWaterMark);
}
this.bootstrap.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(
lowWaterMark, highWaterMark));
} | java | {
"resource": ""
} |
q170572 | FramedataImpl1.get | test | public static FramedataImpl1 get(Opcode opcode) {
if (opcode== null) {
throw new IllegalArgumentException("Supplied opcode cannot be null");
}
switch (opcode) {
case PING:
return new PingFrame();
case PONG:
return new PongFrame();
case TEXT:
return new TextFrame();
case BINARY:
return new BinaryFrame();
case CLOSING:
return new CloseFrame();
case CONTINUOUS:
return new ContinuousFrame();
default:
throw new IllegalArgumentException("Supplied opcode is invalid");
}
} | java | {
"resource": ""
} |
q170573 | SocketChannelIOHelper.batch | test | public static boolean batch( WebSocketImpl ws, ByteChannel sockchannel ) throws IOException {
if (ws == null) {
return false;
}
ByteBuffer buffer = ws.outQueue.peek();
WrappedByteChannel c = null;
if( buffer == null ) {
if( sockchannel instanceof WrappedByteChannel ) {
c = (WrappedByteChannel) sockchannel;
if( c.isNeedWrite() ) {
c.writeMore();
}
}
} else {
do {// FIXME writing as much as possible is unfair!!
/*int written = */sockchannel.write( buffer );
if( buffer.remaining() > 0 ) {
return false;
} else {
ws.outQueue.poll(); // Buffer finished. Remove it.
buffer = ws.outQueue.peek();
}
} while ( buffer != null );
}
if( ws.outQueue.isEmpty() && ws.isFlushAndClose() && ws.getDraft() != null && ws.getDraft().getRole() != null && ws.getDraft().getRole() == Role.SERVER ) {//
ws.closeConnection();
}
return c == null || !((WrappedByteChannel) sockchannel).isNeedWrite();
} | java | {
"resource": ""
} |
q170574 | CloseFrame.setCode | test | public void setCode(int code) {
this.code = code;
// CloseFrame.TLS_ERROR is not allowed to be transfered over the wire
if (code == CloseFrame.TLS_ERROR) {
this.code = CloseFrame.NOCODE;
this.reason = "";
}
updatePayload();
} | java | {
"resource": ""
} |
q170575 | CloseFrame.validateUtf8 | test | private void validateUtf8(ByteBuffer payload, int mark) throws InvalidDataException {
try {
payload.position( payload.position() + 2 );
reason = Charsetfunctions.stringUtf8( payload );
} catch ( IllegalArgumentException e ) {
throw new InvalidDataException( CloseFrame.NO_UTF8 );
} finally {
payload.position( mark );
}
} | java | {
"resource": ""
} |
q170576 | CloseFrame.updatePayload | test | private void updatePayload() {
byte[] by = Charsetfunctions.utf8Bytes(reason);
ByteBuffer buf = ByteBuffer.allocate(4);
buf.putInt(code);
buf.position(2);
ByteBuffer pay = ByteBuffer.allocate(2 + by.length);
pay.put(buf);
pay.put(by);
pay.rewind();
super.setPayload(pay);
} | java | {
"resource": ""
} |
q170577 | Draft_6455.containsRequestedProtocol | test | private HandshakeState containsRequestedProtocol(String requestedProtocol) {
for( IProtocol knownProtocol : knownProtocols ) {
if( knownProtocol.acceptProvidedProtocol( requestedProtocol ) ) {
protocol = knownProtocol;
log.trace("acceptHandshake - Matching protocol found: {}", protocol);
return HandshakeState.MATCHED;
}
}
return HandshakeState.NOT_MATCHED;
} | java | {
"resource": ""
} |
q170578 | Draft_6455.translateSingleFrameCheckLengthLimit | test | private void translateSingleFrameCheckLengthLimit(long length) throws LimitExceededException {
if( length > Integer.MAX_VALUE ) {
log.trace("Limit exedeed: Payloadsize is to big...");
throw new LimitExceededException("Payloadsize is to big...");
}
if( length > maxFrameSize) {
log.trace( "Payload limit reached. Allowed: {} Current: {}" , maxFrameSize, length);
throw new LimitExceededException( "Payload limit reached.", maxFrameSize );
}
if( length < 0 ) {
log.trace("Limit underflow: Payloadsize is to little...");
throw new LimitExceededException("Payloadsize is to little...");
}
} | java | {
"resource": ""
} |
q170579 | Draft_6455.translateSingleFrameCheckPacketSize | test | private void translateSingleFrameCheckPacketSize(int maxpacketsize, int realpacketsize) throws IncompleteException {
if( maxpacketsize < realpacketsize ) {
log.trace( "Incomplete frame: maxpacketsize < realpacketsize" );
throw new IncompleteException( realpacketsize );
}
} | java | {
"resource": ""
} |
q170580 | Draft_6455.generateFinalKey | test | private String generateFinalKey( String in ) {
String seckey = in.trim();
String acc = seckey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
MessageDigest sh1;
try {
sh1 = MessageDigest.getInstance( "SHA1" );
} catch ( NoSuchAlgorithmException e ) {
throw new IllegalStateException( e );
}
return Base64.encodeBytes( sh1.digest( acc.getBytes() ) );
} | java | {
"resource": ""
} |
q170581 | Draft_6455.processFrameContinuousAndNonFin | test | private void processFrameContinuousAndNonFin(WebSocketImpl webSocketImpl, Framedata frame, Opcode curop) throws InvalidDataException {
if( curop != Opcode.CONTINUOUS ) {
processFrameIsNotFin(frame);
} else if( frame.isFin() ) {
processFrameIsFin(webSocketImpl, frame);
} else if( currentContinuousFrame == null ) {
log.error( "Protocol error: Continuous frame sequence was not started." );
throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Continuous frame sequence was not started." );
}
//Check if the whole payload is valid utf8, when the opcode indicates a text
if( curop == Opcode.TEXT && !Charsetfunctions.isValidUTF8( frame.getPayloadData() ) ) {
log.error( "Protocol error: Payload is not UTF8" );
throw new InvalidDataException( CloseFrame.NO_UTF8 );
}
//Checking if the current continuous frame contains a correct payload with the other frames combined
if( curop == Opcode.CONTINUOUS && currentContinuousFrame != null ) {
addToBufferList(frame.getPayloadData());
}
} | java | {
"resource": ""
} |
q170582 | Draft_6455.processFrameBinary | test | private void processFrameBinary(WebSocketImpl webSocketImpl, Framedata frame) {
try {
webSocketImpl.getWebSocketListener().onWebsocketMessage( webSocketImpl, frame.getPayloadData() );
} catch ( RuntimeException e ) {
logRuntimeException(webSocketImpl, e);
}
} | java | {
"resource": ""
} |
q170583 | Draft_6455.logRuntimeException | test | private void logRuntimeException(WebSocketImpl webSocketImpl, RuntimeException e) {
log.error( "Runtime exception during onWebsocketMessage", e );
webSocketImpl.getWebSocketListener().onWebsocketError( webSocketImpl, e );
} | java | {
"resource": ""
} |
q170584 | Draft_6455.processFrameText | test | private void processFrameText(WebSocketImpl webSocketImpl, Framedata frame) throws InvalidDataException {
try {
webSocketImpl.getWebSocketListener().onWebsocketMessage( webSocketImpl, Charsetfunctions.stringUtf8( frame.getPayloadData() ) );
} catch ( RuntimeException e ) {
logRuntimeException(webSocketImpl, e);
}
} | java | {
"resource": ""
} |
q170585 | Draft_6455.processFrameIsFin | test | private void processFrameIsFin(WebSocketImpl webSocketImpl, Framedata frame) throws InvalidDataException {
if( currentContinuousFrame == null ) {
log.trace( "Protocol error: Previous continuous frame sequence not completed." );
throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Continuous frame sequence was not started." );
}
addToBufferList(frame.getPayloadData());
checkBufferLimit();
if( currentContinuousFrame.getOpcode() == Opcode.TEXT ) {
((FramedataImpl1) currentContinuousFrame).setPayload( getPayloadFromByteBufferList() );
((FramedataImpl1) currentContinuousFrame).isValid();
try {
webSocketImpl.getWebSocketListener().onWebsocketMessage( webSocketImpl, Charsetfunctions.stringUtf8( currentContinuousFrame.getPayloadData() ) );
} catch ( RuntimeException e ) {
logRuntimeException(webSocketImpl, e);
}
} else if( currentContinuousFrame.getOpcode() == Opcode.BINARY ) {
((FramedataImpl1) currentContinuousFrame).setPayload( getPayloadFromByteBufferList() );
((FramedataImpl1) currentContinuousFrame).isValid();
try {
webSocketImpl.getWebSocketListener().onWebsocketMessage( webSocketImpl, currentContinuousFrame.getPayloadData() );
} catch ( RuntimeException e ) {
logRuntimeException(webSocketImpl, e);
}
}
currentContinuousFrame = null;
clearBufferList();
} | java | {
"resource": ""
} |
q170586 | Draft_6455.processFrameIsNotFin | test | private void processFrameIsNotFin(Framedata frame) throws InvalidDataException {
if( currentContinuousFrame != null ) {
log.trace( "Protocol error: Previous continuous frame sequence not completed." );
throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "Previous continuous frame sequence not completed." );
}
currentContinuousFrame = frame;
addToBufferList(frame.getPayloadData());
checkBufferLimit();
} | java | {
"resource": ""
} |
q170587 | Draft_6455.processFrameClosing | test | private void processFrameClosing(WebSocketImpl webSocketImpl, Framedata frame) {
int code = CloseFrame.NOCODE;
String reason = "";
if( frame instanceof CloseFrame ) {
CloseFrame cf = ( CloseFrame ) frame;
code = cf.getCloseCode();
reason = cf.getMessage();
}
if( webSocketImpl.getReadyState() == ReadyState.CLOSING ) {
// complete the close handshake by disconnecting
webSocketImpl.closeConnection( code, reason, true );
} else {
// echo close handshake
if( getCloseHandshakeType() == CloseHandshakeType.TWOWAY )
webSocketImpl.close( code, reason, true );
else
webSocketImpl.flushAndClose( code, reason, false );
}
} | java | {
"resource": ""
} |
q170588 | Draft_6455.checkBufferLimit | test | private void checkBufferLimit() throws LimitExceededException {
long totalSize = getByteBufferListSize();
if( totalSize > maxFrameSize ) {
clearBufferList();
log.trace("Payload limit reached. Allowed: {} Current: {}", maxFrameSize, totalSize);
throw new LimitExceededException(maxFrameSize);
}
} | java | {
"resource": ""
} |
q170589 | Draft_6455.getPayloadFromByteBufferList | test | private ByteBuffer getPayloadFromByteBufferList() throws LimitExceededException {
long totalSize = 0;
ByteBuffer resultingByteBuffer;
synchronized (byteBufferList) {
for (ByteBuffer buffer : byteBufferList) {
totalSize += buffer.limit();
}
checkBufferLimit();
resultingByteBuffer = ByteBuffer.allocate( (int) totalSize );
for (ByteBuffer buffer : byteBufferList) {
resultingByteBuffer.put( buffer );
}
}
resultingByteBuffer.flip();
return resultingByteBuffer;
} | java | {
"resource": ""
} |
q170590 | Draft_6455.getByteBufferListSize | test | private long getByteBufferListSize() {
long totalSize = 0;
synchronized (byteBufferList) {
for (ByteBuffer buffer : byteBufferList) {
totalSize += buffer.limit();
}
}
return totalSize;
} | java | {
"resource": ""
} |
q170591 | Draft.translateHandshakeHttpServer | test | private static HandshakeBuilder translateHandshakeHttpServer(String[] firstLineTokens, String line) throws InvalidHandshakeException {
// translating/parsing the request from the CLIENT
if (!"GET".equalsIgnoreCase(firstLineTokens[0])) {
throw new InvalidHandshakeException( String.format("Invalid request method received: %s Status line: %s", firstLineTokens[0],line));
}
if (!"HTTP/1.1".equalsIgnoreCase(firstLineTokens[2])) {
throw new InvalidHandshakeException( String.format("Invalid status line received: %s Status line: %s", firstLineTokens[2], line));
}
ClientHandshakeBuilder clienthandshake = new HandshakeImpl1Client();
clienthandshake.setResourceDescriptor( firstLineTokens[ 1 ] );
return clienthandshake;
} | java | {
"resource": ""
} |
q170592 | Draft.translateHandshakeHttpClient | test | private static HandshakeBuilder translateHandshakeHttpClient(String[] firstLineTokens, String line) throws InvalidHandshakeException {
// translating/parsing the response from the SERVER
if (!"101".equals(firstLineTokens[1])) {
throw new InvalidHandshakeException( String.format("Invalid status code received: %s Status line: %s", firstLineTokens[1], line));
}
if (!"HTTP/1.1".equalsIgnoreCase(firstLineTokens[0])) {
throw new InvalidHandshakeException( String.format("Invalid status line received: %s Status line: %s", firstLineTokens[0], line));
}
HandshakeBuilder handshake = new HandshakeImpl1Server();
ServerHandshakeBuilder serverhandshake = (ServerHandshakeBuilder) handshake;
serverhandshake.setHttpStatus( Short.parseShort( firstLineTokens[ 1 ] ) );
serverhandshake.setHttpStatusMessage( firstLineTokens[ 2 ] );
return handshake;
} | java | {
"resource": ""
} |
q170593 | WebSocketImpl.decode | test | public void decode( ByteBuffer socketBuffer ) {
assert ( socketBuffer.hasRemaining() );
log.trace( "process({}): ({})", socketBuffer.remaining(), ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ));
if( readyState != ReadyState.NOT_YET_CONNECTED ) {
if( readyState == ReadyState.OPEN ) {
decodeFrames( socketBuffer );
}
} else {
if( decodeHandshake( socketBuffer ) && (!isClosing() && !isClosed())) {
assert ( tmpHandshakeBytes.hasRemaining() != socketBuffer.hasRemaining() || !socketBuffer.hasRemaining() ); // the buffers will never have remaining bytes at the same time
if( socketBuffer.hasRemaining() ) {
decodeFrames( socketBuffer );
} else if( tmpHandshakeBytes.hasRemaining() ) {
decodeFrames( tmpHandshakeBytes );
}
}
}
} | java | {
"resource": ""
} |
q170594 | WebSocketImpl.closeConnectionDueToWrongHandshake | test | private void closeConnectionDueToWrongHandshake( InvalidDataException exception ) {
write( generateHttpResponseDueToError( 404 ) );
flushAndClose( exception.getCloseCode(), exception.getMessage(), false );
} | java | {
"resource": ""
} |
q170595 | WebSocketImpl.closeConnectionDueToInternalServerError | test | private void closeConnectionDueToInternalServerError( RuntimeException exception ) {
write( generateHttpResponseDueToError( 500 ) );
flushAndClose( CloseFrame.NEVER_CONNECTED, exception.getMessage(), false );
} | java | {
"resource": ""
} |
q170596 | WebSocketImpl.generateHttpResponseDueToError | test | private ByteBuffer generateHttpResponseDueToError( int errorCode ) {
String errorCodeDescription;
switch(errorCode) {
case 404:
errorCodeDescription = "404 WebSocket Upgrade Failure";
break;
case 500:
default:
errorCodeDescription = "500 Internal Server Error";
}
return ByteBuffer.wrap( Charsetfunctions.asciiBytes( "HTTP/1.1 " + errorCodeDescription + "\r\nContent-Type: text/html\nServer: TooTallNate Java-WebSocket\r\nContent-Length: " + ( 48 + errorCodeDescription.length() ) + "\r\n\r\n<html><head></head><body><h1>" + errorCodeDescription + "</h1></body></html>" ) );
} | java | {
"resource": ""
} |
q170597 | WebSocketImpl.send | test | @Override
public void send( String text ) {
if( text == null )
throw new IllegalArgumentException( "Cannot send 'null' data to a WebSocketImpl." );
send( draft.createFrames( text, role == Role.CLIENT ) );
} | java | {
"resource": ""
} |
q170598 | WebSocketClient.reset | test | private void reset() {
Thread current = Thread.currentThread();
if (current == writeThread || current == connectReadThread) {
throw new IllegalStateException("You cannot initialize a reconnect out of the websocket thread. Use reconnect in another thread to insure a successful cleanup.");
}
try {
closeBlocking();
if( writeThread != null ) {
this.writeThread.interrupt();
this.writeThread = null;
}
if( connectReadThread != null ) {
this.connectReadThread.interrupt();
this.connectReadThread = null;
}
this.draft.reset();
if( this.socket != null ) {
this.socket.close();
this.socket = null;
}
} catch ( Exception e ) {
onError( e );
engine.closeConnection( CloseFrame.ABNORMAL_CLOSE, e.getMessage() );
return;
}
connectLatch = new CountDownLatch( 1 );
closeLatch = new CountDownLatch( 1 );
this.engine = new WebSocketImpl( this, this.draft );
} | java | {
"resource": ""
} |
q170599 | WebSocketClient.connect | test | public void connect() {
if( connectReadThread != null )
throw new IllegalStateException( "WebSocketClient objects are not reuseable" );
connectReadThread = new Thread( this );
connectReadThread.setName( "WebSocketConnectReadThread-" + connectReadThread.getId() );
connectReadThread.start();
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.