org.apache.logging.log4j.Logger.error()

Here are the examples of the java api org.apache.logging.log4j.Logger.error() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

5313 Examples 7

19 Source : AbstractClientRunnable.java
with Apache License 2.0
from zonghaishang

private void runJavaAndHessian() {
    while (running) {
        long beginTime = getCurrentTime();
        if (beginTime >= endTime) {
            running = false;
            break;
        }
        try {
            Object result = doInvoke();
            long currentTime = getCurrentTime();
            // warm up ??
            if (beginTime <= startTime) {
                continue;
            }
            long consumeTime = currentTime - beginTime;
            sumResponseTimeSpread(consumeTime);
            int offset = Integer.parseInt(String.valueOf(beginTime - startTime)) / 1000000;
            if (offset >= maxRange) {
                LOGGER.error("benchmark range exceeds maxRange,range is: " + offset + ",maxRange is: " + maxRange);
                continue;
            }
            if (result != null) {
                tps[offset] = tps[offset] + 1;
                responseTimes[offset] = responseTimes[offset] + consumeTime;
            } else {
                LOGGER.error("server return result is null");
                errorTPS[offset] = errorTPS[offset] + 1;
                errorResponseTimes[offset] = errorResponseTimes[offset] + consumeTime;
            }
        } catch (Exception e) {
            LOGGER.error("failed to trigger doInvoke", e);
            long currentTime = getCurrentTime();
            // warm up ??
            if (beginTime <= startTime) {
                continue;
            }
            long consumeTime = currentTime - beginTime;
            sumResponseTimeSpread(consumeTime);
            int offset = Integer.parseInt(String.valueOf(beginTime - startTime)) / 1000000;
            if (offset >= maxRange) {
                LOGGER.error("benchmark range exceeds maxRange,range is: " + offset + ",maxRange is: " + maxRange);
                continue;
            }
            errorTPS[offset] = errorTPS[offset] + 1;
            errorResponseTimes[offset] = errorResponseTimes[offset] + consumeTime;
        }
    }
}

19 Source : AbstractServerInfos.java
with Apache License 2.0
from zifangsky

/**
 * 组装需要额外校验的License参数
 * @author zifangsky
 * @date 2018/4/23 14:23
 * @since 1.0.0
 * @return demo.LicenseCheckModel
 */
public LicenseCheckModel getServerInfos() {
    LicenseCheckModel result = new LicenseCheckModel();
    try {
        result.setIpAddress(this.getIpAddress());
        result.setMacAddress(this.getMacAddress());
        result.setCpuSerial(this.getCPUSerial());
        result.setMainBoardSerial(this.getMainBoardSerial());
    } catch (Exception e) {
        logger.error("获取服务器硬件信息失败", e);
    }
    return result;
}

19 Source : LicenseVerify.java
with Apache License 2.0
from zifangsky

/**
 * 安装License证书
 * @author zifangsky
 * @date 2018/4/20 16:26
 * @since 1.0.0
 */
public synchronized LicenseContent install(LicenseVerifyParam param) {
    LicenseContent result = null;
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // 1. 安装证书
    try {
        LicenseManager licenseManager = LicenseManagerHolder.getInstance(initLicenseParam(param));
        licenseManager.uninstall();
        result = licenseManager.install(new File(param.getLicensePath()));
        logger.info(MessageFormat.format("证书安装成功,证书有效期:{0} - {1}", format.format(result.getNotBefore()), format.format(result.getNotAfter())));
    } catch (Exception e) {
        logger.error("证书安装失败!", e);
    }
    return result;
}

19 Source : LicenseVerify.java
with Apache License 2.0
from zifangsky

/**
 * 校验License证书
 * @author zifangsky
 * @date 2018/4/20 16:26
 * @since 1.0.0
 * @return boolean
 */
public boolean verify() {
    LicenseManager licenseManager = LicenseManagerHolder.getInstance(null);
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // 2. 校验证书
    try {
        LicenseContent licenseContent = licenseManager.verify();
        // System.out.println(licenseContent.getSubject());
        logger.info(MessageFormat.format("证书校验通过,证书有效期:{0} - {1}", format.format(licenseContent.getNotBefore()), format.format(licenseContent.getNotAfter())));
        return true;
    } catch (Exception e) {
        logger.error("证书校验失败!", e);
        return false;
    }
}

19 Source : VersionChecker.java
with MIT License
from ZekerZhayard

/**
 * FML can't check the build number and if can't match minor version, game won't crash or prompt players prompts
 */
public static boolean checkForgeVersion(Function<String, Boolean> function, String currentFMLVersion) {
    try {
        VersionRange version = VersionRange.createFromVersionSpec("[" + REQUIRED_FORGE_VERSION + ",)");
        if (!version.containsVersion(new DefaultArtifactVersion(currentFMLVersion))) {
            return function.apply("You are using an unsupported Forge version, you can download the newer version from https://files.minecraftforge.net/maven/net/minecraftforge/forge/index_" + REQUIRED_MINECRAFT_VERSION + ".html.\n" + "The game will continue, and run without OptiFine and OptiForge.\n" + "(You installed: " + currentFMLVersion + ", required: " + REQUIRED_FORGE_VERSION + " or newer)");
        }
    } catch (Exception e) {
        LOGGER.error("An unexpected issue occurred when checking Forge version: ", e);
    }
    return true;
}

19 Source : AuthController.java
with GNU General Public License v3.0
from zcbin

@RequestMapping(value = "/unauth")
public JSONObject unauth() {
    LOGGER.error("not logged in yet");
    return ResponseUtil.unlogin();
}

19 Source : AuthController.java
with GNU General Public License v3.0
from zcbin

/**
 * 无权限
 *
 * @return
 */
@RequestMapping(value = "/unauthorized")
public JSONObject unauthorized() {
    LOGGER.error("no permission");
    return ResponseUtil.unauthz();
}

19 Source : Main.java
with MIT License
from zalopay-oss

public static void main(String[] args) throws IOException {
    env = System.getenv("env");
    if (StringUtils.isBlank(env)) {
        LOGGER.error("Missing env");
        System.exit(1);
    }
    System.setProperty("env", env);
    initSystemProperty();
    initVertx();
}

19 Source : ChunkIoMainThreadTaskUtils.java
with MIT License
from YatopiaMC

public static void drainQueue() {
    Runnable command;
    while ((command = mainThreadQueue.poll()) != null) {
        try {
            command.run();
        } catch (Throwable t) {
            LOGGER.error("Error while executing main thread task", t);
        }
    }
}

19 Source : C2MECachedRegionStorage.java
with MIT License
from YatopiaMC

private void scheduleWrite(ChunkPos pos, CompoundTag chunkData) {
    writeFutures.put(pos, regionLocks.acquireLock(new RegionPos(pos)).toCompletableFuture().thenCombineAsync(getRegionFile(pos), (lockToken, regionFile) -> {
        try (final DataOutputStream dataOutputStream = regionFile.getChunkOutputStream(pos)) {
            NbtIo.write(chunkData, dataOutputStream);
        } catch (Throwable t) {
            LOGGER.error("Failed to store chunk {}", pos, t);
        } finally {
            lockToken.releaseLock();
        }
        return null;
    }, IOExecutor).exceptionally(t -> null).thenAccept(unused -> {
    }));
}

19 Source : AsyncSerializationManager.java
with MIT License
from YatopiaMC

public static Scope getScope(ChunkPos pos) {
    final Scope scope = scopeHolder.get().peek();
    if (pos == null)
        return scope;
    if (scope != null) {
        if (scope.pos.equals(pos))
            return scope;
        LOGGER.error("Scope position mismatch! Expected: {} but got {}. This will impact stability. Incompatible mods?", scope.pos, pos, new Throwable());
    }
    return null;
}

19 Source : CommandLineUtils.java
with MIT License
from yale8848

public int getIntValue(String key, int defaultV) {
    if (cmd != null && cmd.hasOption(key)) {
        String v = cmd.getOptionValue(key);
        try {
            return Integer.valueOf(v);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
    }
    return defaultV;
}

19 Source : CommandLineUtils.java
with MIT License
from yale8848

// Posix style parameters : -a av -b bv
public CommandLineUtils posixParse() {
    try {
        parser = new PosixParser();
        cmd = parser.parse(options, args);
    } catch (final ParseException e) {
        LOGGER.error(e.getMessage());
    }
    return this;
}

19 Source : CommandLineUtils.java
with MIT License
from yale8848

// GNU style parameters : --a=av --b=bv
public CommandLineUtils gnuParse() {
    try {
        parser = new GnuParser();
        cmd = parser.parse(options, args);
    } catch (final ParseException e) {
        LOGGER.error(e.getMessage());
    }
    return this;
}

19 Source : CommandLineUtils.java
with MIT License
from yale8848

// array parameters : [-a,av,-b,bv]
public CommandLineUtils basicParse() {
    try {
        parser = new BasicParser();
        cmd = parser.parse(options, args);
    } catch (final ParseException e) {
        LOGGER.error(e.getMessage());
    }
    return this;
}

19 Source : Modules.java
with GNU General Public License v3.0
from XYROC

public static void load() {
    int size = MODULES.size();
    if (size <= 0)
        return;
    if (size == 1)
        LOGGER.info("There is one module present");
    else
        LOGGER.info("There are {} modules present", size);
    int successful = 0, failed = 0;
    moduleLoop: for (Clreplaced<? extends Module> moduleClreplaced : MODULES) {
        for (String modId : MOD_REQUIREMENTS.get(moduleClreplaced)) {
            if (!ModList.get().isLoaded(modId))
                continue moduleLoop;
        }
        try {
            Module module = moduleClreplaced.newInstance();
            LOGGER.info("Loading module {}", module.name);
            if (module.load())
                successful++;
            else {
                LOGGER.error("The module {} failed to load.", module.name);
                failed++;
            }
        } catch (Exception e) {
            LOGGER.error("An error occurred while trying to load {}", moduleClreplaced.toString());
        }
        LOGGER.info("Successfully loaded {} , {} failed.", successful + (size > 1 ? " Modules" : " Module"), failed);
    }
    LOGGER.info("Successfully loaded {} , {} failed.", successful + (size > 1 ? " Modules" : " Module"), failed);
}

19 Source : XMemcachedUtil.java
with GNU General Public License v3.0
from xuxueli

/**
 * 删除
 * @param key
 */
public static boolean delete(String key) {
    try {
        return getInstance().delete(key);
    } catch (TimeoutException e) {
        logger.error("", e);
    } catch (InterruptedException e) {
        logger.error("", e);
    } catch (MemcachedException e) {
        logger.error("", e);
    }
    return false;
}

19 Source : XMemcachedUtil.java
with GNU General Public License v3.0
from xuxueli

/**
 * 查询		和Cas匹配使用,可查询缓存Cas版本
 * @param key
 * @return
 */
public static GetsResponse<Object> gets(String key) {
    try {
        GetsResponse<Object> response = getInstance().gets(key);
        return response;
    } catch (TimeoutException e) {
        logger.error("", e);
    } catch (InterruptedException e) {
        logger.error("", e);
    } catch (MemcachedException e) {
        logger.error("", e);
    }
    return null;
}

19 Source : XMemcachedUtil.java
with GNU General Public License v3.0
from xuxueli

/**
 * Cas	原子性Set
 * @param key
 * @param value
 * @param expTime
 * @param cas
 */
public static boolean cas(String key, Object value, int expTime, long cas) {
    try {
        return getInstance().cas(key, expTime, value, cas);
    } catch (TimeoutException e) {
        logger.error("", e);
    } catch (InterruptedException e) {
        logger.error("", e);
    } catch (MemcachedException e) {
        logger.error("", e);
    }
    return false;
}

19 Source : XMemcachedUtil.java
with GNU General Public License v3.0
from xuxueli

/**
 * 存储
 * @param key		:存储的key名称
 * @param value		:实际存储的数据
 * @param expTime	:expire时间 (单位秒,超过这个时间,memcached将这个数据替换出,0表示永久存储(默认是一个月))
 */
public static void set(String key, Object value, int expTime) {
    try {
        getInstance().set(key, expTime, value);
    } catch (TimeoutException e) {
        logger.error("", e);
    } catch (InterruptedException e) {
        logger.error("", e);
    } catch (MemcachedException e) {
        logger.error("", e);
    }
}

19 Source : XMemcachedUtil.java
with GNU General Public License v3.0
from xuxueli

/**
 * 查询
 * @param key
 * @return
 */
public static Object get(String key) {
    try {
        Object value = getInstance().get(key);
        return value;
    } catch (TimeoutException e) {
        logger.error("", e);
    } catch (InterruptedException e) {
        logger.error("", e);
    } catch (MemcachedException e) {
        logger.error("", e);
    }
    return null;
}

19 Source : XMemcachedUtil.java
with GNU General Public License v3.0
from xuxueli

/**
 * 存储 (默认7200秒)
 * @param key		:存储的key名称
 * @param value		:实际存储的数据
 */
public static void set(String key, Object value) {
    try {
        getInstance().set(key, DEFAULT_EXPIRE_TIME, value);
    } catch (TimeoutException e) {
        logger.error("", e);
    } catch (InterruptedException e) {
        logger.error("", e);
    } catch (MemcachedException e) {
        logger.error("", e);
    }
}

19 Source : XMemcachedUtil.java
with GNU General Public License v3.0
from xuxueli

/**
 * 递增
 * @param key
 */
public static void incr(String key) {
    try {
        getInstance().incr(key, 1);
    } catch (TimeoutException e) {
        logger.error("", e);
    } catch (InterruptedException e) {
        logger.error("", e);
    } catch (MemcachedException e) {
        logger.error("", e);
    }
}

19 Source : JedisUtil.java
with GNU General Public License v3.0
from xuxueli

// ------------------------ serialize and unserialize ------------------------
/**
 * 将对象-->byte[] (由于jedis中不支持直接存储object所以转换成byte[]存入)
 *
 * @param object
 * @return
 */
private static byte[] serialize(Object object) {
    ObjectOutputStream oos = null;
    ByteArrayOutputStream baos = null;
    try {
        // 序列化
        baos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(baos);
        oos.writeObject(object);
        byte[] bytes = baos.toByteArray();
        return bytes;
    } catch (Exception e) {
        logger.error("{}", e);
    } finally {
        try {
            oos.close();
            baos.close();
        } catch (IOException e) {
            logger.error("{}", e);
        }
    }
    return null;
}

19 Source : JedisUtil.java
with GNU General Public License v3.0
from xuxueli

/**
 * 将byte[] -->Object
 *
 * @param bytes
 * @return
 */
private static Object unserialize(byte[] bytes) {
    ByteArrayInputStream bais = null;
    try {
        // 反序列化
        bais = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(bais);
        return ois.readObject();
    } catch (Exception e) {
        logger.error("{}", e);
    } finally {
        try {
            bais.close();
        } catch (IOException e) {
            logger.error("{}", e);
        }
    }
    return null;
}

19 Source : JacksonUtil.java
with GNU General Public License v3.0
from xuxueli

/**
 * bean、array、List、Map --> json
 *
 * @param obj
 * @return
 * @throws Exception
 */
public static String writeValuereplacedtring(Object obj) {
    try {
        return getInstance().writeValuereplacedtring(obj);
    } catch (JsonGenerationException e) {
        logger.error("", e);
    } catch (JsonMappingException e) {
        logger.error("", e);
    } catch (IOException e) {
        logger.error("", e);
    }
    return null;
}

19 Source : JacksonUtil.java
with GNU General Public License v3.0
from xuxueli

public static void main(String[] args) {
    try {
        Map<String, String> map = new HashMap<String, String>();
        map.put("aaa", "111");
        map.put("bbb", "222");
        String json = writeValuereplacedtring(map);
        logger.error(json);
        logger.error(readValue(json, Map.clreplaced).toString());
    } catch (Exception e) {
        logger.error("", e);
    }
}

19 Source : JacksonUtil.java
with GNU General Public License v3.0
from xuxueli

/**
 * string --> bean、Map、List(array)
 *
 * @param jsonStr
 * @param clazz
 * @return
 * @throws Exception
 */
public static <T> T readValue(String jsonStr, Clreplaced<T> clazz) {
    try {
        return getInstance().readValue(jsonStr, clazz);
    } catch (JsonParseException e) {
        logger.error("", e);
    } catch (JsonMappingException e) {
        logger.error("", e);
    } catch (IOException e) {
        logger.error("", e);
    }
    return null;
}

19 Source : JacksonUtil.java
with GNU General Public License v3.0
from xuxueli

public static <T> T readValueRefer(String jsonStr, Clreplaced<T> clazz) {
    try {
        return getInstance().readValue(jsonStr, new TypeReference<T>() {
        });
    } catch (JsonParseException e) {
        logger.error("", e);
    } catch (JsonMappingException e) {
        logger.error("", e);
    } catch (IOException e) {
        logger.error("", e);
    }
    return null;
}

19 Source : Monitor.java
with Apache License 2.0
from Xlinlin

/**
 * 监控流程:
 *  ①向词库服务器发送Head请求
 *  ②从响应中获取Last-Modify、ETags字段值,判断是否变化
 *  ③如果未变化,休眠1min,返回第①步
 * 	④如果有变化,重新加载词典
 *  ⑤休眠1min,返回第①步
 */
public void run() {
    // 超时设置
    RequestConfig rc = RequestConfig.custom().setConnectionRequestTimeout(10 * 1000).setConnectTimeout(10 * 1000).setSocketTimeout(15 * 1000).build();
    HttpHead head = new HttpHead(location);
    head.setConfig(rc);
    // 设置请求头
    if (last_modified != null) {
        head.setHeader("If-Modified-Since", last_modified);
    }
    if (eTags != null) {
        head.setHeader("If-None-Match", eTags);
    }
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(head);
        // 返回200 才做操作
        if (response.getStatusLine().getStatusCode() == 200) {
            if (((response.getLastHeader("Last-Modified") != null) && !response.getLastHeader("Last-Modified").getValue().equalsIgnoreCase(last_modified)) || ((response.getLastHeader("ETag") != null) && !response.getLastHeader("ETag").getValue().equalsIgnoreCase(eTags))) {
                // 远程词库有更新,需要重新加载词典,并修改last_modified,eTags
                Dictionary.getSingleton().reLoadMainDict();
                last_modified = response.getLastHeader("Last-Modified") == null ? null : response.getLastHeader("Last-Modified").getValue();
                eTags = response.getLastHeader("ETag") == null ? null : response.getLastHeader("ETag").getValue();
            }
        } else if (response.getStatusLine().getStatusCode() == 304) {
        // 没有修改,不做操作
        // noop
        } else {
            logger.info("remote_ext_dict {} return bad code {}", location, response.getStatusLine().getStatusCode());
        }
    } catch (Exception e) {
        logger.error("remote_ext_dict {} error!", e, location);
    } finally {
        try {
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
}

19 Source : Dictionary.java
with Apache License 2.0
from Xlinlin

private void loadSurnameDict() {
    _SurnameDict = new DictSegment((char) 0);
    Path file = PathUtils.get(getDictRoot(), Dictionary.PATH_DIC_SURNAME);
    InputStream is = null;
    try {
        is = new FileInputStream(file.toFile());
    } catch (FileNotFoundException e) {
        logger.error("ik-replacedyzer", e);
    }
    if (is == null) {
        throw new RuntimeException("Surname Dictionary not found!!!");
    }
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512);
        String theWord;
        do {
            theWord = br.readLine();
            if (theWord != null && !"".equals(theWord.trim())) {
                _SurnameDict.fillSegment(theWord.trim().toCharArray());
            }
        } while (theWord != null);
    } catch (IOException e) {
        logger.error("ik-replacedyzer", e);
    } finally {
        try {
            if (is != null) {
                is.close();
                is = null;
            }
        } catch (IOException e) {
            logger.error("ik-replacedyzer", e);
        }
    }
}

19 Source : Dictionary.java
with Apache License 2.0
from Xlinlin

/**
 * 加载量词词典
 */
private void loadQuantifierDict() {
    // 建立一个量词典实例
    _QuantifierDict = new DictSegment((char) 0);
    // 读取量词词典文件
    Path file = PathUtils.get(getDictRoot(), Dictionary.PATH_DIC_QUANTIFIER);
    InputStream is = null;
    try {
        is = new FileInputStream(file.toFile());
    } catch (FileNotFoundException e) {
        logger.error("ik-replacedyzer", e);
    }
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512);
        String theWord = null;
        do {
            theWord = br.readLine();
            if (theWord != null && !"".equals(theWord.trim())) {
                _QuantifierDict.fillSegment(theWord.trim().toCharArray());
            }
        } while (theWord != null);
    } catch (IOException ioe) {
        logger.error("Quantifier Dictionary loading exception.");
    } finally {
        try {
            if (is != null) {
                is.close();
                is = null;
            }
        } catch (IOException e) {
            logger.error("ik-replacedyzer", e);
        }
    }
}

19 Source : Dictionary.java
with Apache License 2.0
from Xlinlin

/**
 * 加载用户扩展的停止词词典
 */
private void loadStopWordDict() {
    // 建立主词典实例
    _StopWords = new DictSegment((char) 0);
    // 读取主词典文件
    Path file = PathUtils.get(getDictRoot(), Dictionary.PATH_DIC_STOP);
    InputStream is = null;
    try {
        is = new FileInputStream(file.toFile());
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage(), e);
    }
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512);
        String theWord = null;
        do {
            theWord = br.readLine();
            if (theWord != null && !"".equals(theWord.trim())) {
                _StopWords.fillSegment(theWord.trim().toCharArray());
            }
        } while (theWord != null);
    } catch (IOException e) {
        logger.error("ik-replacedyzer", e);
    } finally {
        try {
            if (is != null) {
                is.close();
                is = null;
            }
        } catch (IOException e) {
            logger.error("ik-replacedyzer", e);
        }
    }
    // 加载扩展停止词典
    List<String> extStopWordDictFiles = getExtStopWordDictionarys();
    if (extStopWordDictFiles != null) {
        is = null;
        for (String extStopWordDictName : extStopWordDictFiles) {
            logger.info("[Dict Loading] " + extStopWordDictName);
            // 读取扩展词典文件
            file = PathUtils.get(getDictRoot(), extStopWordDictName);
            try {
                is = new FileInputStream(file.toFile());
            } catch (FileNotFoundException e) {
                logger.error("ik-replacedyzer", e);
            }
            // 如果找不到扩展的字典,则忽略
            if (is == null) {
                continue;
            }
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512);
                String theWord = null;
                do {
                    theWord = br.readLine();
                    if (theWord != null && !"".equals(theWord.trim())) {
                        // 加载扩展停止词典数据到内存中
                        _StopWords.fillSegment(theWord.trim().toCharArray());
                    }
                } while (theWord != null);
            } catch (IOException e) {
                logger.error("ik-replacedyzer", e);
            } finally {
                try {
                    if (is != null) {
                        is.close();
                        is = null;
                    }
                } catch (IOException e) {
                    logger.error("ik-replacedyzer", e);
                }
            }
        }
    }
    // 加载远程停用词典
    List<String> remoteExtStopWordDictFiles = getRemoteExtStopWordDictionarys();
    for (String location : remoteExtStopWordDictFiles) {
        logger.info("[Dict Loading] " + location);
        List<String> lists = getRemoteWords(location);
        // 如果找不到扩展的字典,则忽略
        if (lists == null) {
            logger.error("[Dict Loading] " + location + "加载失败");
            continue;
        }
        for (String theWord : lists) {
            if (theWord != null && !"".equals(theWord.trim())) {
                // 加载远程词典数据到主内存中
                logger.info(theWord);
                _StopWords.fillSegment(theWord.trim().toLowerCase().toCharArray());
            }
        }
    }
}

19 Source : Dictionary.java
with Apache License 2.0
from Xlinlin

/**
 * [简要描述]:初始化缓存和DB服务<br/>
 * [详细描述]:<br/>
 *
 * @author llxiao
 */
private void initRedisAndDB() {
    customeProps = new Properties();
    Path file = PathUtils.get(getDictRoot(), "customize.properties");
    // 默认60秒
    int period = 60;
    try {
        if (logger.isInfoEnabled()) {
            logger.info("------------------Starting load redis and DB!");
        }
        customeProps.load(new FileInputStream(file.toFile()));
        // 加载缓存
        redisServer = new RedisSever(customeProps);
        // 数据库加载
        dbServer = new DBServer(customeProps);
        if (logger.isInfoEnabled()) {
            logger.info("------------------Starting load redis and DB successfully!");
        }
        // 加载定时加载缓存和数据库中的热词
        loadDB = true;
        period = Integer.parseInt(customeProps.getProperty("ik.monitor.period"));
    } catch (FileNotFoundException e) {
        logger.error("Can't found customize.properties file!", e);
    } catch (IOException e) {
        logger.error("Loading customize.properties file IOException!", e);
    } catch (Exception e) {
        logger.error("Can't found customize.properties file!", e);
    }
    if (loadDB) {
        /* 20180306 使用Redis Pub/Subscribe功能 添加热数据加载 llxiao */
        String channels = customeProps.getProperty("redis.channels");
        // 初始化线程执行订阅操作
        exutorService = Executors.newFixedThreadPool(1, new RedisSubscribeThreadFactory());
        exutorService.execute(new RedisSubscribeThread(redisServer, channels));
        // 启用监控订阅线程
        pool.scheduleAtFixedRate(new RedisSubscribeMonitorThread(exutorService, redisServer, channels), 10, period, TimeUnit.SECONDS);
    /* 20180208 添加热数据加载 llxiao */
    // if (loadDB)
    // {
    // // 10 秒是初始延迟可以修改的 60是间隔时间 单位秒 定时刷新数据热词到IK
    // pool.scheduleAtFixedRate(new HotDictReloadThread(), 10, 3600 * 24,
    // TimeUnit.SECONDS);
    // }
    }
}

19 Source : Dictionary.java
with Apache License 2.0
from Xlinlin

/**
 * 加载用户配置的扩展词典到主词库表
 */
private void loadExtDict() {
    // 加载扩展词典配置
    List<String> extDictFiles = getExtDictionarys();
    if (extDictFiles != null) {
        InputStream is = null;
        for (String extDictName : extDictFiles) {
            // 读取扩展词典文件
            logger.info("[Dict Loading] " + extDictName);
            Path file = PathUtils.get(getDictRoot(), extDictName);
            try {
                is = new FileInputStream(file.toFile());
            } catch (FileNotFoundException e) {
                logger.error("ik-replacedyzer", e);
            }
            // 如果找不到扩展的字典,则忽略
            if (is == null) {
                continue;
            }
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512);
                String theWord = null;
                do {
                    theWord = br.readLine();
                    if (theWord != null && !"".equals(theWord.trim())) {
                        // 加载扩展词典数据到主内存词典中
                        _MainDict.fillSegment(theWord.trim().toCharArray());
                    }
                } while (theWord != null);
            } catch (IOException e) {
                logger.error("ik-replacedyzer", e);
            } finally {
                try {
                    if (is != null) {
                        is.close();
                        is = null;
                    }
                } catch (IOException e) {
                    logger.error("ik-replacedyzer", e);
                }
            }
        }
    }
}

19 Source : Dictionary.java
with Apache License 2.0
from Xlinlin

/**
 * 加载远程扩展词典到主词库表
 */
private void loadRemoteExtDict() {
    List<String> remoteExtDictFiles = getRemoteExtDictionarys();
    for (String location : remoteExtDictFiles) {
        logger.info("[Dict Loading] " + location);
        List<String> lists = getRemoteWords(location);
        // 如果找不到扩展的字典,则忽略
        if (lists == null) {
            logger.error("[Dict Loading] " + location + "加载失败");
            continue;
        }
        for (String theWord : lists) {
            if (theWord != null && !"".equals(theWord.trim())) {
                // 加载扩展词典数据到主内存词典中
                logger.info(theWord);
                _MainDict.fillSegment(theWord.trim().toLowerCase().toCharArray());
            }
        }
    }
}

19 Source : Dictionary.java
with Apache License 2.0
from Xlinlin

/**
 * 加载主词典及扩展词典
 */
private void loadMainDict() {
    // 建立一个主词典实例
    _MainDict = new DictSegment((char) 0);
    // 读取主词典文件
    Path file = PathUtils.get(getDictRoot(), Dictionary.PATH_DIC_MAIN);
    InputStream is = null;
    try {
        is = new FileInputStream(file.toFile());
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage(), e);
    }
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512);
        String theWord = null;
        do {
            theWord = br.readLine();
            if (theWord != null && !"".equals(theWord.trim())) {
                _MainDict.fillSegment(theWord.trim().toCharArray());
            }
        } while (theWord != null);
    } catch (IOException e) {
        logger.error("ik-replacedyzer", e);
    } finally {
        try {
            if (is != null) {
                is.close();
                is = null;
            }
        } catch (IOException e) {
            logger.error("ik-replacedyzer", e);
        }
    }
    // 加载扩展词典
    this.loadExtDict();
    // 加载远程自定义词库
    this.loadRemoteExtDict();
    // 从mysql加载词典
    this.loadMySQLExtDict();
}

19 Source : RedisSever.java
with Apache License 2.0
from Xlinlin

/**
 * 关闭/是否连接池资源,若是网络异常,则断开连接,如果是一般异常,将直接抛出异常
 *
 * @param jedis
 * @param conectionBroken
 */
public void closeResource(Jedis jedis, boolean conectionBroken) {
    try {
        // 直接调用close方法,新客户端方法里面已经实现连接池回收处理逻辑 --caohong
        if (null != jedis && null != pool) {
            jedis.close();
        }
    } catch (Exception e) {
        logger.error("return back jedis failed, will force close the jedis," + e.getMessage(), e);
    }
}

19 Source : RedisSever.java
with Apache License 2.0
from Xlinlin

/**
 * 判断jedis抛出的异常类型,网络异常或者一般异常
 *
 * @param exception
 * @return
 */
private boolean handleJedisException(Exception exception) {
    // 无实际使用了,因为资源回收已经不需要判断异常 --caohong
    if (exception instanceof JedisConnectionException) {
        logger.error("Redis connection lost. Exception is : ", exception);
    } else if (exception instanceof JedisDataException) {
        if (exception.getMessage() != null && exception.getMessage().indexOf("READONLY") != -1) {
            logger.error("Redis connection are read-only slave. Exception is : ", exception);
        } else {
            return false;
        }
    } else {
        logger.error("Jedis exception happen. Exception is : ", exception);
    }
    return true;
}

19 Source : Log4j2Impl.java
with Apache License 2.0
from xiaour

public void error(String s) {
    errorCount++;
    log.error(s);
}

19 Source : Log4j2Impl.java
with Apache License 2.0
from xiaour

public void error(String s, Throwable e) {
    errorCount++;
    log.error(s, e);
}

19 Source : MiscUtils.java
with Mozilla Public License 2.0
from Wurst-Imperium

public static boolean openLink(String url) {
    try {
        Desktop.getDesktop().browse(new URI(url));
        return true;
    } catch (Exception e) {
        logger.error("Failed to open link", e);
        return false;
    }
}

19 Source : RocksDBHolder.java
with Apache License 2.0
from wuba

public static boolean makeCheckPoint(int groupId, JavaOriTypeWrapper<String> dirPath, List<String> fileList) {
    String checkpointPath = kvPath + File.separator + groupId + File.separator + "checkpoint";
    try {
        rocksDBS[groupId].makeCheckPoint(checkpointPath);
        dirPath.setValue(checkpointPath);
        File file = new File(checkpointPath);
        if (file != null && file.list() != null) {
            fileList.addAll(Arrays.asList(file.list()));
        }
        return true;
    } catch (RocksDBException e) {
        logger.error("path {}", checkpointPath, e);
        return false;
    }
}

19 Source : RocksDBHolder.java
with Apache License 2.0
from wuba

public static boolean learnCheckPoint(int groupId, String checkPointPath, List<String> fileList) {
    try {
        return rocksDBS[groupId].recoverCheckpoint(checkPointPath, fileList);
    } catch (RocksDBException e) {
        logger.error(e.getMessage(), e);
        return false;
    }
}

19 Source : RocksDB.java
with Apache License 2.0
from wuba

public boolean recoverCheckpoint(String checkPointPath, List<String> fileList) throws RocksDBException {
    if (rocksDB != null) {
        logger.info("rocksdb close");
        rocksDB.close();
        rocksDB = null;
    }
    File file = new File(path);
    FileUtils.deleteDir(path + ".bak");
    if (!file.renameTo(new File(path + ".bak"))) {
        logger.error("rename file error");
        return false;
    }
    for (String s : fileList) {
        logger.info("checkpoint file {}", s);
    }
    File checkpoint = new File(checkPointPath);
    boolean b = checkpoint.renameTo(new File(path));
    if (!b) {
        logger.error("rename chaeckpoint error");
        return false;
    }
    init();
    return true;
}

19 Source : ServiceThread.java
with Apache License 2.0
from wuba

protected void waitForRunning(long interval) {
    if (hasNotified.compareAndSet(true, false)) {
        this.onWaitEnd();
        return;
    }
    // entry to wait
    waitPoint.reset();
    try {
        waitPoint.await(interval, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        log.error("Interrupted", e);
    } finally {
        hasNotified.set(false);
        this.onWaitEnd();
    }
}

19 Source : ServiceThread.java
with Apache License 2.0
from wuba

public void shutdown(final boolean interrupt) {
    this.stopped = true;
    log.info("shutdown thread {} interrupt {}.", this.getServiceName(), interrupt);
    if (hasNotified.compareAndSet(false, true)) {
        waitPoint.countDown();
    }
    try {
        if (interrupt) {
            this.thread.interrupt();
        }
        long beginTime = System.currentTimeMillis();
        if (!this.thread.isDaemon()) {
            this.thread.join(this.getJointime());
        }
        long eclipseTime = System.currentTimeMillis() - beginTime;
        log.info("join thread {} eclipse time(ms) {} join time {} ", this.getServiceName(), eclipseTime, this.getJointime());
    } catch (InterruptedException e) {
        log.error("Interrupted", e);
    }
}

19 Source : Notifier.java
with Apache License 2.0
from wuba

public int waitNotify() {
    this.serialLock.lock();
    try {
        while (!isCommitEnd) {
            this.serialLock.waitTime(1000);
        }
    } catch (Exception e) {
        logger.error("", e);
    } finally {
        this.serialLock.unLock();
    }
    return this.commitRet;
}

19 Source : ConfigManager.java
with Apache License 2.0
from wuba

public synchronized void persist() {
    String jsonString = this.encode(true);
    if (jsonString != null) {
        String fileName = this.configFilePath();
        try {
            MixAll.string2File(jsonString, fileName);
        } catch (IOException e) {
            logger.error("persist file Exception, " + fileName, e);
        }
    }
}

19 Source : ConfigManager.java
with Apache License 2.0
from wuba

private boolean loadBak() {
    String fileName = null;
    try {
        fileName = this.configFilePath();
        String jsonString = MixAll.file2String(fileName + ".bak");
        if (jsonString != null && jsonString.length() > 0) {
            this.decode(jsonString);
            logger.info("init " + fileName + " OK");
            return true;
        }
    } catch (Exception e) {
        logger.error("init " + fileName + " Failed", e);
        return false;
    }
    return true;
}

See More Examples