非开发环境全局处理error(warning)，exception,shutdown
347691
public function handle(){
    	if($this->plume('plume.env') === 'dev'){
            error_reporting(E_ALL);
    		return;
    	}
        // Report simple running errors
        error_reporting(E_ERROR | E_WARNING | E_PARSE);
        set_error_handler(array($this, 'error_function'));
        set_exception_handler(array($this, 'exception_function'));
        register_shutdown_function(array($this, 'shutdown_function'));
    }
279951
public function shutdown()
    {
        $exceptions = $this->client_holder->shutdown();

        if ($this->hasLogger()) {
            foreach ($exceptions as $exception) {
                printf(
                    "Exception caught during shutdown: %s\n",
                    (string) $exception
                );
            }

            $this->logger = null;
        }

        $this->client_poolers = [];
        $this->connection->close();
        $this->is_shutdown = true;
    }
1362905
public void start() throws IkasoaException {
		if (server == null) {
			log.debug("Server configuration : {}", configuration);
			// 不允许使用1024以内的端口.
			if (!ServerUtil.isSocketPort(serverPort))
				throw new IkasoaException(String.format(
						"Server initialize failed ! Port range must is 1025 ~ 65535 . Your port is : %d .",
						serverPort));
			try {
				initServer(getTransport());
			} catch (TTransportException e) {
				throw new IkasoaException("Server initialize failed !", e);
			}
		}
		// 如果服务没有启动,则自动启动服务.
		if (server != null) {
			if (server.isServing()) {
				log.info("Server already run .");
				return;
			}
			server.serve();
			log.info("Startup server ... (name : {} , port : {})", getServerName(), getServerPort());
		} else
			log.warn("Startup server failed !");
	}
549407
@Override
    protected void shutDown() throws Exception {
        long traceId = LoggerHelpers.traceEnterWithContext(log, this.objectId, "shutDown");
        try {
            log.info("Stopping REST server listening on port: {}", this.restServerConfig.getPort());
            final GrizzlyFuture<HttpServer> shutdown = httpServer.shutdown(30, TimeUnit.SECONDS);
            log.info("Awaiting termination of REST server");
            shutdown.get();
            log.info("REST server terminated");
        } finally {
            LoggerHelpers.traceLeave(log, this.objectId, "shutDown", traceId);
        }
    }
583021
public function stop()
    {
        $rpcServer = $this->getRpcServer();

        // 是否已启动
        if (! $rpcServer->isRunning()) {
            \output()->writeln('<error>The server is not running! cannot stop</error>', true, true);
        }

        // pid文件
        $serverStatus = $rpcServer->getServerSetting();
        $pidFile = $serverStatus['pfile'];

        \output()->writeln(sprintf('<info>Swoft %s is stopping ...</info>', input()->getFullScript()));

        $result = $rpcServer->stop();

        // 停止失败
        if (! $result) {
            \output()->writeln(sprintf('<error>Swoft %s stop fail</error>', input()->getFullScript()));
        }
        //删除pid文件
        @unlink($pidFile);

        \output()->writeln(sprintf('<success>Swoft %s stop success</success>', input()->getFullScript()));
    }
1256749
function callAndCatchPromiseError(fn, ...args) {
  // args 最后一个参数如果是如果是 function 则表示 next()
  // 如果执行时出错，调用 next(err)
  const next = args[args.length - 1];
  let p = null;
  try {
    p = fn.apply(null, args);
  } catch (err) {
    return next(err);
  }
  if (p && p.then && p.catch) {
    p.catch(err => next(err));
  }
}
853533
public function error($error,$errstr, $errfile=null, $errline=null, $errcontext=null){
        //错误捕获
        $e = new \ErrorException($errstr, $error, $error, $errfile, $errline);
        $this->dowith($e);

    }
1196718
public void start(CockroachQueue queue) throws Exception {
        this.thread = config.getThread();
        TaskResponseFilterBox filterBox = this.bulidResponseFilters();
        this.executerListeners.forEach(IExecutersListener::onStart);
        for (int i = 0; i < thread; i++) {
            TaskExecuter executer = new TaskExecuter(
                    queue,
                    this.bulidHttpClient(),
                    this.config.getStore().newInstance(),
                    new TaskErrorHandlerBox().add(this.config.getTaskErrorHandler().newInstance()),
                    this.config.getThreadSleep(),
                    this.config.isAutoClose(),
                    filterBox
            );
            logger.info("new thread:" + executer.getId());
            service.execute(executer);
            executerList.add(executer);
        }
        /**
         * 不可以再继续 提交新的任务 已经提交的任务不影响
         */
        service.shutdown();

        /**
         * 每 5 秒检测是否全部线程执行完毕
         */
        new Thread(() -> {
            try {
                while (true) {
                    TimeUnit.SECONDS.sleep(5);
                    if (service.isTerminated()) {
                        logger.info("任务已经全部执行完毕");
                        this.executerListeners.forEach(IExecutersListener::onEnd);
                        break;
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
642654
public static function shutdownHandler()
    {
        if ( ! ($error = error_get_last())) {
            return;
        }

        self::exceptionHandler(
            new \ErrorException($error['message'], 0, $error['type'], $error['file'], $error['line'])
        );
    }
1247202
public void init() throws WatchException{
		//获取目录或文件路径
		if(false ==Files.exists(this.path, LinkOption.NOFOLLOW_LINKS)) {
			final Path lastPathEle = FileUtil.getLastPathEle(this.path);
			if(null != lastPathEle) {
				final String lastPathEleStr = lastPathEle.toString();
				//带有点表示有扩展名，按照未创建的文件对待。Linux下.d的为目录，排除之
				if(StrUtil.contains(lastPathEleStr, StrUtil.C_DOT) && false ==StrUtil.endWithIgnoreCase(lastPathEleStr, ".d")) {
					this.filePath = this.path;
					this.path = this.filePath.getParent();
				}
			}
			
			//创建不存在的目录或父目录
			try {
				Files.createDirectories(this.path);
			} catch (IOException e) {
				throw new IORuntimeException(e);
			}
		}else if(Files.isRegularFile(this.path, LinkOption.NOFOLLOW_LINKS)){
			this.filePath = this.path;
			this.path = this.filePath.getParent();
		}
		
		//初始化监听
		try {
			watchService = FileSystems.getDefault().newWatchService();
		} catch (IOException e) {
			throw new WatchException(e);
		}
		
		isClosed = false;
	}
1058970
final void shutdown() {
        _enabled = false;
        _ignoredSegs.clear();
        
        if(_executor != null && !_executor.isShutdown()) {
            try {
                _executor.shutdown();
                _log.info("shutdown");
            } catch (Exception e) {
                _log.warn("shutdown abort", e);
            }
            
            try {
                _executor.awaitTermination(_shutdownTimeout, TimeUnit.SECONDS);
            } catch (Exception e) {
                _log.warn("shutdown abort", e);
            }
            
            if(_segTarget != null) {
                try {
                    _updateManager.endUpdate(_segTarget);
                } catch (Exception e) {
                    _log.warn("shutdown abort", e);
                }
            }
        }
        
        _executor = null;
        _state = State.DONE;
    }
906274
public void check() throws ThriftConnectionPoolException {
		if (connectTimeout <= 0) {
			throw new ThriftConnectionPoolException("连接超时时间必须大于0");
		}

		// 判断是否是单接口模式 如果是则只检测单接口
		if (getThriftServiceType() == ThriftServiceType.SINGLE_INTERFACE) {
			if (clientClass == null) {
				throw new ThriftConnectionPoolException("thrift客户端实现类未设置");
			}
			// 检测ping方法
			try {
				clientClass.getMethod("ping");
			} catch (NoSuchMethodException e) {
				throw new ThriftConnectionPoolException("Thrift客户端实现类必须带有ping()方法用于检测连接");
			}
		} else if (getThriftServiceType() == ThriftServiceType.MULTIPLEXED_INTERFACE) {
			if (clientClasses.size() == 0) {
				throw new ThriftConnectionPoolException("多服务thrift客户端实现类未设置");
			}
			// 检测所有接口
			List<String> toRemoveClasses = new ArrayList<>();
			Iterator<Entry<String, Class<? extends TServiceClient>>> iterator = clientClasses.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry<String, Class<? extends TServiceClient>> entry = iterator.next();
				Class<? extends TServiceClient> clazz = entry.getValue();
				try {
					clazz.getMethod("ping");
				} catch (NoSuchMethodException e) {
					toRemoveClasses.add(entry.getKey());
					logger.warn("接口：" + entry.getKey() + " 没有实现ping方法 无法创建对应的服务客户端");
				}
			}
			for (String toRemoveClass : toRemoveClasses) {
				clientClasses.remove(toRemoveClass);
			}
			Iterator<String> servicesNameIterator = clientClasses.keySet().iterator();
			while (servicesNameIterator.hasNext()) {
				logger.info("注册服务客户端：" + servicesNameIterator.next());
			}
		}

		if (maxConnectionPerServer <= 0) {
			throw new ThriftConnectionPoolException("每台服务器的最大连接数必须大于0");
		}

		if (minConnectionPerServer < 0) {
			throw new ThriftConnectionPoolException("每台服务器最小连接数不能小于0");
		}

		if (minConnectionPerServer > maxConnectionPerServer) {
			throw new ThriftConnectionPoolException("每台服务器的最小连接数不能超过最大连接数配置");
		}

		if (idleConnectionTestPeriodInSeconds <= 0) {
			throw new ThriftConnectionPoolException("检测时间周期必须大于0秒");
		}

		if (idleMaxAgeInSeconds <= 0) {
			throw new ThriftConnectionPoolException("未使用连接关闭时间必须大于0秒");
		}

		if (maxConnectionAgeInSeconds <= 0) {
			throw new ThriftConnectionPoolException("连接最大生存时间必须大于0秒");
		}

		if (acquireRetryAttempts < 0) {
			throw new ThriftConnectionPoolException("获取连接重试次数不能小于0");
		}

		if (acquireRetryDelayInMs < 0) {
			throw new ThriftConnectionPoolException("获取连接重试等待时间不能小于0毫秒");
		}

		if (connectionTimeoutInMs < 0) {
			throw new ThriftConnectionPoolException("获取连接等待时间不能小于0毫秒");
		}

		if (acquireIncrement <= 0) {
			throw new ThriftConnectionPoolException("每次创建原始连接的数量必须大于0个");
		}
	}
1266649
public static void main(String[] args) throws Exception {

		String datapath = "../data";
		
		
		String allfile = datapath + "/FNLPDATA/all.seg";	
		String testfile = datapath + "/FNLPDATA/test.seg";	
		String trainfile = datapath + "/FNLPDATA/train.seg";
		MyFiles.delete(testfile);
		MyFiles.delete(trainfile);
		MyFiles.delete(allfile);

		String dictfile = datapath + "/FNLPDATA/dict.seg";

		String segfile = datapath + "/FNLPDATA/temp.seg";
		//清理
		MyFiles.delete(dictfile);
		MyFiles.delete(segfile);
		

		FNLPCorpus corpus = new FNLPCorpus();
		//读自有数据
		corpus.readOurCorpus(datapath + "/ourdata",".txt","UTF8");
		//读分词文件
		corpus.readCWS(datapath + "/FNLPDATA/seg",".txt","UTF8");	
		//读分词+词性文件
		corpus.readPOS(datapath + "/FNLPDATA/pos",".txt","UTF8");	
		//读FNLP数据
		corpus.read(datapath + "/FNLPDATA/ctb7.dat", null);			
		corpus.read(datapath + "/FNLPDATA/WeiboFTB(v1.0)-train.dat", null);



		FNLP2BMES.w2BMES(corpus,segfile);		
		//FNLP2BMES.w2BMES(corpus,segfile_w); //?


		//词典转BMES
		//搜狗词典
		DICT dict = new DICT();
		String sougou = datapath + "/FNLPDATA/dict/SogouLabDic.dic.raw";

//		dict.readSougou(sougou,2,3,"sougou");
		//互动词典
		String hudong = datapath + "/FNLPDATA/dict/hudong.dic.all";
//		dict.readSougou(hudong,2,3,"");
		//添加其他词典
		dict.readDictionary(datapath + "/FNLPDATA/dict",".dic");

		//添加其他词典
//		dict.readDictionaryWithFrequency(datapath + "/FNLPDATA/dict",".dic.freq");




		//添加词性字典
		dict.readPOSDICT(datapath + "/FNLPDATA/词性字典", ".txt");
		dict.readPOSDICT(datapath + "/FNLPDATA/dict-sogou-input/txt", ".txt");

		dict.toBMES(dictfile,3);
		new File(dictfile).deleteOnExit();

		//合并训练文件
		
		
		
		List<File> files = MyFiles.getAllFiles(datapath + "/FNLPDATA/", ".seg");
		MyFiles.combine(trainfile,files.toArray(new File[files.size()]));
		
		//生成新字典		
		String dicfile = datapath + "/FNLPDATA/train.dict";
		DICT.BMES2DICT(trainfile,dicfile);

		//处理测试数据
		FNLPCorpus corpust = new FNLPCorpus();
		//读自有数据
		corpust.read(datapath + "/FNLPDATA/WeiboFTB(v1.0)-test.dat", null);	
		
		FNLP2BMES.w2BMES(corpust,testfile);		
		
		


		System.out.println(new Date().toString());
		System.out.println("Done!");




	}
292525
public void loadData() throws Exception{

		System.out.print("Loading training data ...");
		long beginTime = System.currentTimeMillis();

		Pipe pipe = createProcessor();


		trainSet = new InstanceSet(pipe, factory);
		labels = factory.DefaultLabelAlphabet();
		features = factory.DefaultFeatureAlphabet();
		features.setStopIncrement(false);
		labels.setStopIncrement(false);

		// 训练集
		trainSet.loadThruStagePipes(new SequenceReader(train, true));

		long endTime = System.currentTimeMillis();
		System.out.println(" done!");
		System.out.println("Time escape: " + (endTime - beginTime) / 1000 + "s");
		System.out.println();

		// 输出
		System.out.println("Training Number: " + trainSet.size());
		System.out.println("Label Number: " + labels.size()); // 标签个数
		System.out.println("Feature Number: " + features.size()); // 特征个数
		System.out.println();

		// 冻结特征集
		features.setStopIncrement(true);
		labels.setStopIncrement(true);


		// 读入测试数据
		if (testfile != null) {
			System.out.print("Loading test data ...");
			boolean hasTarget = true;;
			if (!hasTarget) {// 如果test data没有标注
				pipe = featurePipe;
			} 

			// 测试集
			testSet = new InstanceSet(pipe);
			testSet.loadThruStagePipes(new SequenceReader(testfile, hasTarget, "utf8"));
			System.out.println("Test Number: " + testSet.size()); // 样本个数
		}
	}
1180152
public static void main(String[] args) throws Exception {
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("table", "my_table_name");
        parameters.put("id", "my_id");
        parameters.put(":1", "first_param");

        final Pattern PATTERN = Pattern.compile("\\{([a-zA-Z0-9_\\.\\:]+)\\}|##\\((.+)\\)");

        String sql = "select form ##(:table) {name} where {id}='{1}'";

        StringBuilder sb = new StringBuilder(sql.length() + 200);
        Matcher matcher = PATTERN.matcher(sql);
        int start = 0;
        while (matcher.find(start)) {
            sb.append(sql.substring(start, matcher.start()));
            String group = matcher.group();
            String key = null;
            if (group.startsWith("{")) {
                key = matcher.group(1);
            } else if (group.startsWith("##(")) {
                key = matcher.group(2);
            }
            System.out.println(key);
            if (key == null || key.length() == 0) {
                continue;
            }
            Object value = parameters.get(key); // 针对{paramName}、{:1}两种情况
            if (value == null) {
                if (key.startsWith(":") || key.startsWith("$")) {
                    value = parameters.get(key.substring(1)); // 针对{:paramName}的情况
                } else {
                    char ch = key.charAt(0);
                    if (ch >= '0' && ch <= '9') {
                        value = parameters.get(":" + key); // 针对{1}两种情况
                    }
                }
            }
            if (value == null) {
                value = parameters.get(key); // 针对常量的情况
            }
            if (value != null) {
                sb.append(value);
            } else {
                sb.append(group);
            }
            start = matcher.end();
        }
        sb.append(sql.substring(start));
        System.out.println(sb);

    }
927956
public void shutdown() throws Exception {
        if (type == null) {
            return;
        }
        if (type instanceof Hub) {
            ((Hub) type).stop();
        }
        if (type instanceof SelfRegisteringRemote) {
            ((SelfRegisteringRemote) type).stopRemoteServer();
        }
        if (type instanceof SeleniumServer) {
            ((SeleniumServer) type).stop();
        }
        LOGGER.info("Selenium is shut down");
    }
97500
@Override
	protected void doStop() throws Exception {
		for (ThreadPoolExecutor pool: threadPools.values()){
			pool.shutdown();
		}

		for (ThreadPoolExecutor pool: threadPools.values()){
			shutdownAndAwaitTermination(pool, shutdownWaitSeconds);
		}

	}