注册 Service Providers
324052
protected function registerProviders()
    {
        if (isset($this->container['providers'])) {
            foreach ($this->container['providers'] as $provider) {
                if (!is_subclass_of($provider, ServiceProvider::class)) {
                    throw new UnexpectedValueException($provider .
                        ' must return instance of ' . ServiceProvider::class);
                }

                (new $provider($this))->register();
            }
        }
    }
710460
async function handle(sofar) {
    if (!sofar.fn) {
        sofar.fn = ret => { }; // 兼容 notify 和 jsonp 两种情形
    }
    if (!sofar.socket) {
        sofar.socket = {};  //兼容WS、Socket、Http等模式
    }

    //更新时间戳
    sofar.socket.stamp = (new Date()).valueOf(); 

    //对数据进行规整
    sofar.msg.control = sofar.msg.control || 'index';
    sofar.msg.func = sofar.msg.func || 'login';
    sofar.msg.oemInfo = sofar.msg.oemInfo || {};
    if (sofar.msg.oemInfo.constructor == String) {
        sofar.msg.oemInfo = JSON.parse(sofar.msg.oemInfo);
    }
    sofar.msg.oemInfo.domain = !!sofar.msg.oemInfo.domain ? sofar.msg.oemInfo.domain : "official";
    if (sofar.facade.options.serverType == "Test") {
        facade.CoreOfLogic.mapping.map(lt=>{
            let reg = new RegExp(lt, 'g');
            sofar.msg.oemInfo.domain = sofar.msg.oemInfo.domain.replace(reg, "Test");
        });
    }
    sofar.msg.token = sofar.msg.token || {};
    if(sofar.msg.token.constructor == String){
        sofar.msg.token = JSON.parse(sofar.msg.token);
    }
    sofar.msg.userinfo = sofar.msg.userinfo || {};
    if(sofar.msg.userinfo.constructor == String){
        sofar.msg.userinfo = JSON.parse(sofar.msg.userinfo);
    }
    sofar.msg.domainId = !!sofar.msg.oemInfo.openid ? sofar.msg.oemInfo.domain + '.' + sofar.msg.oemInfo.openid : '';
}
314526
function server({ router, allowOrign = '*' } = {}) {
    let app = express(),
        listen = app.listen;


    // 允许跨域
    app.use((req, res, next) => {
        res.header('Access-Control-Allow-Origin', allowOrign);
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
        res.header('Access-Control-Allow-Headers', 'X-Requested-With');
        res.header('Access-Control-Allow-Credentials', 'true');
        next();
    });

    // 监听静态文件
    app.use(express.static(path.resolve(cwd, 'public')));
    app.use(express.static(path.resolve(cwd, 'static')));

    // 解析【body】
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));

    // 加载路由
    if (router) {
        app.use(router);
    }

    // 定义配置接口
    app.adopt = install => {
        if (install) {
            if (typeof install === 'function' && install.length === 1) {
                install.call(app, app);
            } else if (typeof install === 'object' && typeof install.install === 'function') {
                install.install(app);
            }
        }
    };

    // 启动监听
    app.listen = (port, host, callback) => {

        // 重载参数
        if (typeof host === 'function') {
            return app.listen(port, 'localhost', host);
        }

        // 监听错误信息
        app.use(function (err, req, res, next) {

            // 打印错误
            console.error(err.stack);

            // 返回错误信息
            if (req.xhr) {
                res.status(500).send({ error: 'Something failed!' });
            } else {
                next(err);
            }
        });

        // 启动服务
        listen.call(app, port, host, function() {
            let { address, port } = this.address();

            // 设置本地地址
            if (!address || address === '::') {
                address = 'localhost';
            }

            // 打印信息
            console.log('-'.repeat(60));
            console.log(`Server running at: http://${ address }:${ port || '80' }/`);
            console.log('-'.repeat(60));

            // 执行回调
            callback && callback(app);
        });
    };

    // 返回结果
    return app;
}
1098753
protected void doRegister(String appName, String serviceName, ProviderInfo providerInfo) {
        if (LOGGER.isInfoEnabled(appName)) {
            LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_ROUTE_REGISTRY_PUB, serviceName));
        }
        //{service : [provider...]}
        ProviderGroup oldGroup = memoryCache.get(serviceName);
        if (oldGroup != null) { // 存在老的key
            oldGroup.add(providerInfo);
        } else { // 没有老的key，第一次加入
            List<ProviderInfo> news = new ArrayList<ProviderInfo>();
            news.add(providerInfo);
            memoryCache.put(serviceName, new ProviderGroup(news));
        }
        // 备份到文件 改为定时写
        needBackup = true;
        doWriteFile();

        if (subscribe) {
            notifyConsumerListeners(serviceName, memoryCache.get(serviceName));
        }
    }
381551
function() {
		var hostsstr = fs.readFileSync(HOSTS, 'utf-8');
		//一个domain 对应一个ip
		//先分组，再去重
		//之后去重
		var lines = hostsstr.split(EOL);
		var hostsobject = {};
		var currentName;
		var currentLog = [];
		var uniq = {};
		notes = {};
		for (var i = 0; i < lines.length; i++) {
			var line = this._parseLine(lines[i]);
			if (!line) continue;
			var type = line.type;
			var val = line.value;
			switch (type) {
			case 1:
				if (!currentName) {
					currentName = this.defaultName;
					hostsobject[currentName] = [];
					if (currentLog.length > 0) {
						notes[currentName] = currentLog.join(EOL);
						currentLog = [];
					}
				}
				val.forEach(function(item) {
					var _item = uniq[currentName + item.domain + item.ip];
					if (!_item) {
						hostsobject[currentName].push(item);
						_item = uniq[currentName + item.domain + item.ip] = item;
					}
					if (currentLog.length > 0) {
						_item.note = (_item.note ? (_item.note + EOL) : '') + currentLog.join(EOL);
					}

				});
				currentLog = [];
				break;
			case 2:
				currentLog.push(val);
				break;
			case 3:
				currentName = val;
				hostsobject[currentName] = [];
				if (currentLog.length > 0) {
					notes[currentName] = currentLog.join(EOL);
					currentLog = [];
				}
				break;
			default:
				break;
			}
		}
		if (currentLog.length > 0) {
			notes.bottom = currentLog.join(EOL);
			currentLog = [];
		}
		return hostsobject;
	}
1189049
function callServer(params,key) {
  debug("enter proxy!");
  
  //调用接口的配置
  var options = {
    url: params.domain + params.api.url,
    method: params.api.method,
  };
  
  //如果设置api的方法,就使用API的方法
  if (params.api.apiMethod) {
    options.method = params.api.apiMethod;
  }

  //如果是GET采用head传参，否则使用表单传参
  if(options.method === 'GET') {
    options.qs = params.params;
  } else {
    options.form = params.params;
  }
  
  //如果是json字符串，按json raw方式传递
  if(params.api.isJsonRaw) {
    options.headers =  {
       'Content-Type' : 'application/json'
    };
    options.body = JSON.stringify(params.params);
    delete options.form;
  }
  //如果自定义headers，加到服务调用
  if(params.req._yoheaders) {
    options.headers = options.headers||{};
    options.headers = _.merge(options.headers,params.req._yoheaders);
  }

  params.req.app.yolog.api.log('verbose','server api input: ',options);
  params.req.app.yolog.profile('proxy api time:'+options.url,'api');
  request(options, function(error, response, body) {
    params.req.app.yolog.profile('proxy api time:'+options.url,'api');
    if (response && response.statusCode === 200) {
      params.req.app.yolog.api.log('verbose','server api status 200 output:',body);
      if (params.res.setCache && params.api.cache) {
        var cacheKey = params.res.genKey(params.domain, params.api.url, JSON.stringify(params.params));

        params.res.setCache(cacheKey, body, params.api.cache);
      }
      params.body = body;
      debug("proxy callback!");
      debug(params);
      procRet(params,key);
    } else {
      //如果调用出错,设置错误返回
      params.req.input = {
          error:true,
          message:'api server error!'
      };
      params.req.app.yolog.log('error','server api error input: %j',options,{});
      //如果有响应，修改返回
      if (response) {
        params.req.input.message = 'error: ' + response.statusCode;
        params.req.app.yolog.log('error','server api error %d output: %j',response.statusCode,body,{});
      } else {
        params.req.app.yolog.log('error','call server api yo response: %j',params.req.input,{});
      }
      params.next();
    }
  });
}
327129
function Requester(options, context) {
        this.uid = createUID();
        this.resolver = new Resolver();
        this.promise = this.resolver.promise();
        this.context = context;
        this.handleSuccess = false;
        this.handleFail = false;

        options = options || {};
        // 触发全局`before`事件
        context.emit('before', this, options);

        // 请求头设置
        options.headers = extend({}, context.data.headers, options.headers);

        // 请求方法设置
        options.method = options.method || METHOD.GET;

        // 添加默认的请求头标示
        options.headers['X-Requested-With'] = 'XMLHttpRequest';

        // 对GET请求进行处理
        // 注意此时由于平台限制没有对POST进行处理（默认请求头与数据处理）
        // 需要在后续Kernel做处理
        var url = options.url;
        var data = options.data;
        if (options.method === METHOD.GET && data) {
            if (options.stringify !== false
                && !util.isString(data)
            ) {
                data = util.stringify(data);
            }
            url = util.append(url, data);
            data = '';
        }
        options.data = data;
        this.url = url;

        // 添加请求地址前缀
        ['prefix', 'host'].forEach(function (item) {
            item = context.data[item];
            if (item) {
                url = item + url;
            }
        });
        options.url = url;

        // 发起请求
        this.xhr = new Kernel(options, this);

        // 在请求完成后触发全局事件
        this.promise.then(
            bind(context.emit, context, 'success', this),
            bind(context.emit, context, 'fail', this)
        );
    }
1156314
void addProviderInfoListener(String dataId, ConsumerConfig consumerConfig,
                                 ProviderInfoListener listener) {
        providerInfoListeners.put(consumerConfig, listener);

        // 同一个key重复订阅多次，提醒用户需要检查一下是否是代码问题
        if (LOGGER.isWarnEnabled(consumerConfig.getAppName()) && providerInfoListeners.size() > 5) {
            LOGGER.warnWithApp(consumerConfig.getAppName(),
                "Duplicate to add provider listener of {} " +
                    "more than 5 times, now is {}, please check it",
                dataId, providerInfoListeners.size());
        }
    }
603514
public void notifyStateChangeToUnavailable() {
        final List<ConsumerStateListener> onprepear = consumerConfig.getOnAvailable();
        if (onprepear != null) {
            AsyncRuntime.getAsyncThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    // 状态变化通知监听器
                    for (ConsumerStateListener listener : onprepear) {
                        try {
                            listener.onUnavailable(consumerBootstrap.getProxyIns());
                        } catch (Exception e) {
                            LOGGER.error("Failed to notify consumer state listener when state change to unavailable");
                        }
                    }
                }
            });
        }
    }
55688
protected SofaResponse doSendMsg(ProviderInfo providerInfo, ClientTransport transport,
                                     SofaRequest request) throws SofaRpcException {
        RpcInternalContext context = RpcInternalContext.getContext();
        // 添加调用的服务端远程地址
        RpcInternalContext.getContext().setRemoteAddress(providerInfo.getHost(), providerInfo.getPort());
        try {
            checkProviderVersion(providerInfo, request); // 根据服务端版本特殊处理
            String invokeType = request.getInvokeType();
            int timeout = resolveTimeout(request, consumerConfig, providerInfo);

            SofaResponse response = null;
            // 同步调用
            if (RpcConstants.INVOKER_TYPE_SYNC.equals(invokeType)) {
                long start = RpcRuntimeContext.now();
                try {
                    response = transport.syncSend(request, timeout);
                } finally {
                    if (RpcInternalContext.isAttachmentEnable()) {
                        long elapsed = RpcRuntimeContext.now() - start;
                        context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE, elapsed);
                    }
                }
            }
            // 单向调用
            else if (RpcConstants.INVOKER_TYPE_ONEWAY.equals(invokeType)) {
                long start = RpcRuntimeContext.now();
                try {
                    transport.oneWaySend(request, timeout);
                    response = buildEmptyResponse(request);
                } finally {
                    if (RpcInternalContext.isAttachmentEnable()) {
                        long elapsed = RpcRuntimeContext.now() - start;
                        context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE, elapsed);
                    }
                }
            }
            // Callback调用
            else if (RpcConstants.INVOKER_TYPE_CALLBACK.equals(invokeType)) {
                // 调用级别回调监听器
                SofaResponseCallback sofaResponseCallback = request.getSofaResponseCallback();
                if (sofaResponseCallback == null) {
                    SofaResponseCallback methodResponseCallback = consumerConfig
                        .getMethodOnreturn(request.getMethodName());
                    if (methodResponseCallback != null) { // 方法的Callback
                        request.setSofaResponseCallback(methodResponseCallback);
                    }
                }
                // 记录发送开始时间
                context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_SEND_TIME, RpcRuntimeContext.now());
                // 开始调用
                transport.asyncSend(request, timeout);
                response = buildEmptyResponse(request);
            }
            // Future调用
            else if (RpcConstants.INVOKER_TYPE_FUTURE.equals(invokeType)) {
                // 记录发送开始时间
                context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_SEND_TIME, RpcRuntimeContext.now());
                // 开始调用
                ResponseFuture future = transport.asyncSend(request, timeout);
                // 放入线程上下文
                RpcInternalContext.getContext().setFuture(future);
                response = buildEmptyResponse(request);
            } else {
                throw new SofaRpcException(RpcErrorType.CLIENT_UNDECLARED_ERROR, "Unknown invoke type:" + invokeType);
            }
            return response;
        } catch (SofaRpcException e) {
            throw e;
        } catch (Throwable e) { // 客户端其它异常
            throw new SofaRpcException(RpcErrorType.CLIENT_UNDECLARED_ERROR, e);
        }
    }
1289987
function InitOralProcess(client, req) {
    return new Promise(function (resolve, reject) {
        // 通过client对象调用想要访问的接口，需要传入请求对象以及响应回调函数
        client.InitOralProcess(req, function (err, response) {
            if (err) {
                reject(err)
                return;
            }
            resolve(response)
        });
    })
}
317682
function (url, options) {
    // 首先建立连接
    options = options || {};
    options.autoReconnect = true;

    const { timestamp = true, updatedTime, createdTime } = options;

    const extendUpdate = timestamp ? extend.update(updatedTime) : extend.no();
    const extendCreate = timestamp ? extend.create(createdTime) : extend.no();

    const connect = mongo.connect(url, options);

    this.collections = () => {
      return connect.then((db) => {
        return db.collections();
      });
    };
    this.collection = (collectionName) => {
      return connect.then((db) => {
        return db.collection(collectionName);
      });
    };
    this.count = (collectionName, query, options) => {
      return this.collection(collectionName).then((collection) => {
        return collection.count(query, options);
      });
    };
    this.create = this.insert = (collectionName, data) => {
      return this.collection(collectionName).then((collection) => {
        return collection.insert(extendCreate(data));
      });
    };
    this.find = (collectionName, filter, condition, cursor) => {
      return this.collection(collectionName).then((collection) => {
        if (!cursor) {
          return collection.find(filter, condition).toArray();
        } else {
          return collection.find(filter, condition);
        }
      });
    };
    this.findOne = (collectionName, filter, condition) => {
      return this.collection(collectionName).then((collection) => {
        return collection.findOne(filter, condition);
      });
    };
    this.update = (collectionName, filter, data, options) => {
      return this.collection(collectionName).then((collection) => {
        return collection.update(filter, extendUpdate(data), Object.assign({}, { upsert: false }, options));
      });
    };
    this.updateOne = (collectionName, filter, data, options) => {
      return this.collection(collectionName).then((collection) => {
        return collection.updateOne(filter, extendUpdate(data), Object.assign({}, { upsert: true }, options));
      });
    };
    this.remove = (collectionName, filter, options) => {
      return this.collection(collectionName).then((collection) => {
        return collection.deleteMany(filter, options);
      });
    };
    this.aggregate = (collectionName, pipeline, options) => {
      return this.collection(collectionName).then((collection) => {
        return new Promise((rec, rej) => {
          collection.aggregate(pipeline, (err, res) => {
            if (err) {
              rej(err);
            } else {
              rec(res);
            }
          });
        });
      });
    };
    return this;
  }
103528
function initApp(options,app) {    
    app.set('trust proxy', 1);

    //在中间件之前使用中间件
    if(options.beforeMid) {
        options.beforeMid(app,middlewares);
    }

    //session中间件
    app.use(session(options.session));
    //cookies解析中间件
    app.use(cookieParser());
    //日志中间件
    app.use(morgan('combined'));
    //faviocn中间件
    app.use(favicon(options.public +path.sep+'favicon.ico'));
    //spm调试中间件
    if (env === 'development') {
        app.use(serveSPM(options.client, {
            log: console.log
        }));
        app.use(express.static(options.public));
    } else if (env === 'test') {
        //静态目录
        app.use(express.static(options.public));
    }

    //声明小部件目录
    hbs.registerPartials(options.partials);

    //设置handlebars视图引擎
    app.set('view engine', options.tempExt);
    app.engine(options.tempExt, hbs.__express);
    app.set('views', options.views);

    //body 序列化
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
        extended: false,
        limit:options.bodyLimit||'1000kb'
    }));

    return app;
}
592820
function TransmitOralProcessWithInit(client, req) {
    return new Promise(function (resolve, reject) {
        // 通过client对象调用想要访问的接口，需要传入请求对象以及响应回调函数
        client.TransmitOralProcessWithInit(req, function (err, response) {
            if (err) {
                reject(err)
                return;
            }
            // 请求正常返回，打印response对象
            resolve(response)
        });
    })
}
1284414
private function loadContainer(): void
    {
        $loaderClass = $this->config->getValue('SERVICE_LOADER');
        $this->container = new Container();
        $serviceLoader = new $loaderClass();
        $serviceLoader->loadContainerService($this->container);
        // 错误处理器
        $this->loadErrorHandler($this->getService('errorHandler'));
        $this->loadRouteErrorHandler($this->getService('routeErrorHandler'));
        // 路由服务
        $this->loadRouteHandler($this->getService('routeHandler'));
    }
1138223
public function api()
    {
        //处理消息
        $this->wechat->server->setMessageHandler(function ($m) {
            $this->m = $m;
            Log::info($m);

            if ($m->Event != 'unsubscribe' && $m->Event != 'LOCATION' && $m->Event != 'VIEW' && $m->Event != 'TEMPLATESENDJOBFINISH') {
                //存上行消息
                $msg = new Message();
                $msg->from_user_name = $m->FromUserName;
                $msg->to_user_name = $m->ToUserName;
                $msg->create_time = $m->CreateTime;
                $msg->msg_type = $m->MsgType;
//                $msg->msg_id = isset($m->MsgId) ? $m->MsgId : 0;
                $msg->content = isset($m->Content) ? $m->Content : '';
                $msg->pic_url = isset($m->PicUrl) ? $m->PicUrl : '';
//                $msg->location_x = isset($m->Location_X) ? $m->Location_X : '';
//                $msg->location_x = isset($m->Location_Y) ? $m->Location_Y : '';
//                $msg->scale = isset($m->Scale) ? $m->Scale : '';
                $msg->label = isset($m->Label) ? $m->Label : '';
                $msg->title = isset($m->Title) ? $m->Title : '';
                $msg->description = isset($m->Description) ? $m->Description : '';
                $msg->url = isset($m->Url) ? $m->Url : '';
                $msg->media_id = isset($m->MediaId) ? $m->MediaId : '';
                $msg->thumb_media_id = $m->ThumbMediaId;
                $msg->event = $m->Event;
                $msg->event_key = $m->EventKey;
                $msg->save();
            }

            //从上行消息中提取关键词
            $key = '';
            switch ($m->MsgType) {
                case 'text':
                    $key = $m->Content;

                    break;
                case 'event':
                    switch ($m->Event) {
                        case 'CLICK':
                            $key = $m->EventKey;
                            break;
                        case 'subscribe'://关注事件
                            UserSns::where('openid', $m->FromUserName)->update(['status' => 0]);
                            break;
                        case 'unsubscribe'://取消关注事件
                            UserSns::where('openid', $m->FromUserName)->update(['status' => 1]);
                            break;
                        case 'SCAN':
                    }
                    break;
            }
            $this->key = $key;
            Log::info($this->key);

//            //帮用户生成本站用户数据
//            if (!$this->reg()) {
//                return 'whops';
//            }

            //判断关注默认回复的关键词
            if ($m->Event == 'subscribe' && empty($m->EventKey)) {
                $this->key = $this->keyFollow;
            }

            //事件key会抽风夹带类似这种的 last_trade_no_4009012001201605306519754434
            if (strpos($m->EventKey, 'last_trade_no') === 0) {
                $this->key = $this->keyFollow;
            }

            //根据关键词处理回复
            $res = FALSE;
            if (!empty($this->key)) {
                $this->r = $this->returnReply();
            } else {
                $this->r = '';
            }

            //入库消息.取关和地理位置不记录

            return $this->r;

        });

        return $this->wechat->server->serve();

    }
992500
public static void compareProviders(List<ProviderInfo> oldList, List<ProviderInfo> newList,
                                        List<ProviderInfo> add, List<ProviderInfo> remove) {
        // 比较老列表和当前列表
        if (CommonUtils.isEmpty(oldList)) {
            // 空变成非空
            if (CommonUtils.isNotEmpty(newList)) {
                add.addAll(newList);
            }
            // 空到空，忽略
        } else {
            // 非空变成空
            if (CommonUtils.isEmpty(newList)) {
                remove.addAll(oldList);
            } else {
                // 非空变成非空，比较
                if (CommonUtils.isNotEmpty(oldList)) {
                    List<ProviderInfo> tmpList = new ArrayList<ProviderInfo>(newList);
                    // 遍历老的
                    for (ProviderInfo oldProvider : oldList) {
                        if (tmpList.contains(oldProvider)) {
                            tmpList.remove(oldProvider);
                        } else {
                            // 新的没有，老的有，删掉
                            remove.add(oldProvider);
                        }
                    }
                    add.addAll(tmpList);
                }
            }
        }
    }