回收ThriftSocket连接
171012
@Override
	public synchronized void releaseThriftSocket(ThriftSocket thriftSocket, String host, int port) {
		if (thriftSocket == null || thriftSocket.getSocket() == null
				|| thriftSocket.getSocket().getInetAddress() == null) {
			log.debug("Release unsuccessful .");
			return;
		}
		if (!ServerUtil.checkHostAndPort(host, port)) {
			log.error("Server host or port is null ! Release unsuccessful .");
			return;
		}
		log.debug("Release socket , host is {} and port is {} .", host, port);
		SimpleSocketPoolImpl self = selfMap.get(ServerUtil.buildCacheKey(host, port));
		if (self == null)
			return;
		for (byte i = 0; i < size; i++)
			if (self.socketPool.get(new Byte(i)) == thriftSocket) {
				self.socketStatusArray[i] = Boolean.FALSE;
				return;
			}
		// 如果socket不在池中,就直接关闭
		thriftSocket.close();
	}
1130969
function getEtag(buffer,callback){

    // 判断传入的参数是buffer还是stream还是filepath
    var mode = 'buffer';

    if(typeof buffer === 'string'){
        buffer = require('fs').createReadStream(buffer);
        mode='stream';
    }else if(buffer instanceof require('stream')){
        mode='stream';
    }

    // sha1算法
    var sha1 = function(content){
        var crypto = require('crypto');
        var sha1 = crypto.createHash('sha1');
        sha1.update(content);
        return sha1.digest();
    };

    // 以4M为单位分割
    var blockSize = 4*1024*1024;
    var sha1String = [];
    var prefix = 0x16;
    var blockCount = 0;

    switch(mode){
        case 'buffer':
            var bufferSize = buffer.length;
            blockCount = Math.ceil(bufferSize / blockSize);

            for(var i=0;i<blockCount;i++){
                sha1String.push(sha1(buffer.slice(i*blockSize,(i+1)*blockSize)));
            }
            process.nextTick(function(){
                callback(calcEtag());
            });
            break;
        case 'stream':
            var stream = buffer;
            stream.on('readable', function() {
                var chunk;
                while (chunk = stream.read(blockSize)) {
                    sha1String.push(sha1(chunk));
                    blockCount++;
                }
            });
            stream.on('end',function(){
                callback(calcEtag());
            });
            break;
    }

    function calcEtag(){
        if(!sha1String.length){
            return 'Fto5o-5ea0sNMlW_75VgGJCv2AcJ';
        }
        var sha1Buffer = Buffer.concat(sha1String,blockCount * 20);

        // 如果大于4M，则对各个块的sha1结果再次sha1
        if(blockCount > 1){
            prefix = 0x96;
            sha1Buffer = sha1(sha1Buffer);
        }

        sha1Buffer = Buffer.concat(
            [new Buffer([prefix]),sha1Buffer],
            sha1Buffer.length + 1
        );

        return sha1Buffer.toString('base64')
            .replace(/\//g,'_').replace(/\+/g,'-');

    }

}
656308
private ThriftConnection<T> obtainRawInternalConnection(ThriftServerInfo serverInfo)
			throws ThriftConnectionPoolException {
		// 判断单服务还是多服务模式
		ThriftConnection<T> connection;
		if (this.thriftServiceType == ThriftServiceType.SINGLE_INTERFACE) {
			connection = new DefaultThriftConnection<>(serverInfo.getHost(), serverInfo.getPort(),
					this.connectionTimeOut, this.config.getThriftProtocol(), this.config.getClientClass());
		} else {
			connection = new MulitServiceThriftConnecion<>(serverInfo.getHost(), serverInfo.getPort(),
					this.connectionTimeOut, this.config.getThriftProtocol(), this.config.getThriftClientClasses());
		}
		return connection;
	}
1109983
function ( src, dst, callback ){
      fs.exists( dst, function ( exists ){
          // 已存在
          if( exists ){
              callback( src, dst );
          }

          // 不存在
          else{
              fs.mkdir( dst, function (){
                  callback( src, dst );
              });
          }
      });
  }
698009
async function () {
    const encodedABI = simpleTokenContractObj.methods.transfer(receiverAddress, bigNumAmount.toString(10)).encodeABI();

    const estimateGasObj = new EstimateGasKlass({
      contract_name: simpleTokenContractName,
      contract_address: oThis.contractAddress,
      chain: 'value',
      sender_address: senderAddress,
      method_name: 'transfer',
      method_arguments: [receiverAddress, bigNumAmount.toString(10)]
    });

    const estimateGasResponse = await estimateGasObj.perform()
      , gasToUse = estimateGasResponse.data.gas_to_use
    ;

    // set txParams for firing event
    const rawTxParams = {
      from: senderAddress, to: receiverAddress, value: bigNumAmount.toString(10),
      gasPrice: VC_GAS_PRICE, gas: gasToUse
    };

    // set params in notification data
    notificationData.message.payload.params.txParams = rawTxParams; // one time

    // set txParams for executing transaction
    const txParams = {
      from: senderAddress,
      to: oThis.contractAddress,
      data: encodedABI,
      gasPrice: VC_GAS_PRICE,
      gas: gasToUse
    };

    // Unlock account and send transaction
    return new Promise(function (onResolve, onReject) {
      const onReceipt = function (receipt) {
        // Publish event
        notificationData.message.kind = 'transaction_mined';
        openSTNotification.publishEvent.perform(notificationData);

        // send response
        if (basicHelper.isReturnTypeTxReceipt(returnType)) {
          return onResolve(responseHelper.successWithData({
            transaction_uuid: txUUID,
            transaction_hash: receipt.transactionHash,
            transaction_receipt: receipt
          }));
        }
      };

      web3Provider.eth.personal.unlockAccount(senderAddress, senderPassphrase)
        .then(function () {
          return web3Provider.eth.sendTransaction(txParams)
            .on('transactionHash', function (transactionHash) {
              // set transaction hash in notification data
              notificationData.message.payload.transaction_hash = transactionHash; // one time
              // Publish event
              notificationData.message.kind = 'transaction_initiated';
              openSTNotification.publishEvent.perform(notificationData);

              // send response
              if (basicHelper.isReturnTypeTxHash(returnType)) {
                return onResolve(responseHelper.successWithData({
                  transaction_uuid: txUUID,
                  transaction_hash: transactionHash,
                  transaction_receipt: {}
                }));
              }
            })
            .on('receipt', onReceipt)
        })
        .catch(async function (reason) {
          logger.error("ST :: Transaction failed.\n\t Reason:", reason);

          const onCatchError = function () {
            // set error data in notification data
            notificationData.message.payload.error_data = reason;
            // Publish event
            notificationData.message.kind = 'transaction_error';
            openSTNotification.publishEvent.perform(notificationData);

            // send response
            let errObj = responseHelper.error({
              internal_error_identifier: 'l_ci_st_transfer_6',
              api_error_identifier: 'transaction_failed',
              error_config: basicHelper.fetchErrorConfig()
            });
            return onResolve(errObj);
          };

          const isNotMinedInSomeBlocksError = reason.message.includes('not mined within');
          if (isNotMinedInSomeBlocksError) {
            // get receipt
            const res = await contractInteractHelper.getTransactionReceiptFromTrasactionHash(
              web3Provider,
              notificationData.message.payload.transaction_hash
            );

            if (res.isSuccess()) {
              onReceipt(res.data.receipt);
            } else {
              onCatchError();
            }
          } else {
            onCatchError();
          }

        });

    });

  }
309746
def wait_for_thrift_interface(self, **kwargs):
        
        if self.cluster.version() >= '4':
            return;

        self.watch_log_for("Listening for thrift clients...", **kwargs)

        thrift_itf = self.network_interfaces['thrift']
        if not common.check_socket_listening(thrift_itf, timeout=30):
            warnings.warn("Thrift interface {}:{} is not listening after 30 seconds, node may have failed to start.".format(thrift_itf[0], thrift_itf[1]))
443910
function bindReqSocket(req, socket) {
  //gReqCount++;
  req.onSocket(socket);
  socket._reqCount++;
  socket._used = true;
  timers.unenroll(socket._kpTimer);
}
309512
private static AsynchronousSocketChannel createChannel(InetSocketAddress address, int poolSize) {

		AsynchronousSocketChannel channel;
		try {
			AsynchronousChannelGroup group = AsynchronousChannelGroup.withFixedThreadPool(//
					poolSize, // 默认线程池大小
					ThreadFactoryBuilder.create().setNamePrefix("Huool-socket-").build()//
			);
			channel = AsynchronousSocketChannel.open(group);
		} catch (IOException e) {
			throw new IORuntimeException(e);
		}

		try {
			channel.connect(address).get();
		} catch (InterruptedException | ExecutionException e) {
			throw new SocketRuntimeException(e);
		}
		return channel;
	}
1198306
protected void putConnectionBackInPartition(ThriftConnectionHandle<T> connectionHandle)
			throws ThriftConnectionPoolException {
		BlockingQueue<ThriftConnectionHandle<T>> queue = connectionHandle.getConnectionPartition().getFreeConnections();
		if (!queue.offer(connectionHandle)) { // 如果无法放回则关闭
			connectionHandle.internalClose();
		}
	}
273652
@Override
	public ThriftClient getThriftClient(String serverHost, int serverPort) {
		return new ThriftClientImpl(serverHost, serverPort, thriftClientConfiguration);
	}
1077842
@Override
	public ThriftServer getThriftServer(String serverName, int serverPort, TProcessor processor) {
		return new ThreadPoolThriftServerImpl(serverName, serverPort, thriftServerConfiguration, processor);
	}
1059746
function registerUserSockets(socket) {
  User.schema.post('save', function (doc) {
    onSave(socket, doc);
  });

  User.schema.post('remove', function (doc) {
    onRemove(socket, doc);
  });
}
517257
function(_bid,_text){
        try{
            !!_text&&_text.search('//#DWR')>=0
            ? (new Function(_text))()
            : __onErrorAll(_bid,{
                  code:_g._$CODE_ERRSERV,
                  message:'DWR请求返回数据不合法!'
              });
        }catch(ex){
            __onErrorAll(_bid,{
                code:_g._$CODE_ERREVAL,
                message:'DWR返回脚本执行异常：'+(ex.message||ex)
            });
        }finally{
            __doDestroyBatch(_bid);
        }
    }
270778
private static void doCheck(String appId, String cpId, String privateKey, String publicKey, GameUserData userData, ICheckLoginSignHandler callback) {
        // 创建body参数
        byte[] body = getRequestBody(appId, cpId, privateKey, userData);

        // 发送请求
        sendRequest(URL, body, publicKey, callback);
    }
1045080
function patchAssignSocket (res, callback) {
  var assignSocket = res.assignSocket

  if (typeof assignSocket !== 'function') return

  // res.on('socket', callback) is broken in 0.8
  res.assignSocket = function _assignSocket (socket) {
    assignSocket.call(this, socket)
    callback(socket)
  }
}
733475
function safesocket (expected, fn) {
	return function () {
		var _args = [];
		for (var idx in arguments) {
			_args.push(arguments[idx]);
		}

		var args = _args.filter(notFunction).slice(0, expected);
		for (var i = args.length; i < expected; i++) {
			args.push(undefined);
		}

		var arg = _args.pop();
		args.push((arg instanceof Function) ? arg : noop);

		fn.apply(this, args);
	};
}
1192612
async function doLinks(items,meta) {
										// -----------------------------------------
										function runLinks(links) {
											let prom = async v => { try {
													let S = v.replace(/SocketLink/,''),
														O = JSON.parse(S), 
														Q = O.point,
														R = {
															params: O.params||{},
															query: 	O.query	||{},
															body: 	O.body	||{},
															files: 	O.files	||[] },
														P = {
															true:  ()=>Q.slice(-1)[0].toTitleCase(),
															false: ()=>'/' }[Q.length>1](),
														A = Q[0].toTitleCase(),
														E = REST.Points[A][P],
														err,itms,opts;
													// --------------------------------
													[err,itms,opts] = await E(R);
													itms = await doLinks(itms,opts);
													return FromJS(Assign({},itms));
												} catch (e) { return e; } };
											return Promise.all(links.toArray().map(prom));
										};
										// -----------------------------------------
										let   omits = (v,k)=>!['prev','next'].has(k),
											{ query, body } = meta.Options,
											gtLnk = L=>(typeof(L)=='string'?JSON.parse(L):L),
											doLnk = gtLnk((query||body).links||false),
											filtr = {
												'array': (v,k)=>doLnk.has(k),
												'boolean': ()=>true,
											}, lnks, othr;
										// -----------------------------------------
										if (!!items && !!doLnk) {
											lnks  = Imm	.Map(meta.Links)
														.filter(filtr[ISS(doLnk)])
														.filter(omits);
											if (lnks.size) {
												othr  = await runLinks(lnks);
												items = othr.reduce(
															(R,V)=>R.mergeDeep(V), 
															FromJS(Assign({},items))
														).toJS();
										}	}; 	
										return 	items;
									}