Java Code Examples for cn.hutool.core.io.FileUtil#exist()

The following examples show how to use cn.hutool.core.io.FileUtil#exist() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ExecutorJobHandler.java    From datax-web with MIT License 6 votes vote down vote up
private String generateTemJsonFile(String jobJson) {
    String tmpFilePath;
    String dataXHomePath = SystemUtils.getDataXHomePath();
    if (StringUtils.isNotEmpty(dataXHomePath)) {
        jsonPath = dataXHomePath + DEFAULT_JSON;
    }
    if (!FileUtil.exist(jsonPath)) {
        FileUtil.mkdir(jsonPath);
    }
    tmpFilePath = jsonPath + "jobTmp-" + IdUtil.simpleUUID() + ".conf";
    // 根据json写入到临时本地文件
    try (PrintWriter writer = new PrintWriter(tmpFilePath, "UTF-8")) {
        writer.println(jobJson);
    } catch (FileNotFoundException | UnsupportedEncodingException e) {
        JobLogger.log("JSON 临时文件写入异常:" + e.getMessage());
    }
    return tmpFilePath;
}
 
Example 2
Source File: ScriptProcessBuilder.java    From Jpom with MIT License 6 votes vote down vote up
public static void addWatcher(ScriptModel scriptModel, String args, Session session) {
    File file = scriptModel.getFile(true);
    ScriptProcessBuilder scriptProcessBuilder = FILE_SCRIPT_PROCESS_BUILDER_CONCURRENT_HASH_MAP.computeIfAbsent(file, file1 -> {
        ScriptProcessBuilder scriptProcessBuilder1 = new ScriptProcessBuilder(scriptModel, args);
        ThreadUtil.execute(scriptProcessBuilder1);
        return scriptProcessBuilder1;
    });
    if (scriptProcessBuilder.sessions.add(session)) {
        if (FileUtil.exist(scriptProcessBuilder.logFile)) {
            // 读取之前的信息并发送
            FileUtil.readLines(scriptProcessBuilder.logFile, CharsetUtil.CHARSET_UTF_8, (LineHandler) line -> {
                try {
                    SocketSessionUtil.send(session, line);
                } catch (IOException e) {
                    DefaultSystemLog.getLog().error("发送消息失败", e);
                }
            });
        }
    }
}
 
Example 3
Source File: ScriptModel.java    From Jpom with MIT License 5 votes vote down vote up
public void readFileContext() {
    File file = getFile(true);
    if (FileUtil.exist(file)) {
        //
        String context = FileUtil.readString(file, JpomApplication.getCharset());
        setContext(context);
    }
}
 
Example 4
Source File: AutoImportLocalNode.java    From Jpom with MIT License 5 votes vote down vote up
private static void findPid(String pid) {
    File file = ConfigBean.getInstance().getApplicationJpomInfo(Type.Agent);
    if (!file.exists() || file.isDirectory()) {
        return;
    }
    // 比较进程id
    String json = FileUtil.readString(file, CharsetUtil.CHARSET_UTF_8);
    JpomManifest jpomManifest = JSONObject.parseObject(json, JpomManifest.class);
    if (!pid.equals(String.valueOf(jpomManifest.getPid()))) {
        return;
    }
    // 判断自动授权文件是否存在
    String path = ConfigBean.getInstance().getAgentAutoAuthorizeFile(jpomManifest.getDataPath());
    if (!FileUtil.exist(path)) {
        return;
    }
    json = FileUtil.readString(path, CharsetUtil.CHARSET_UTF_8);
    AgentAutoUser autoUser = JSONObject.parseObject(json, AgentAutoUser.class);
    // 判断授权信息
    //
    NodeModel nodeModel = new NodeModel();
    nodeModel.setUrl(StrUtil.format("127.0.0.1:{}", jpomManifest.getPort()));
    nodeModel.setName("本机");
    nodeModel.setId("localhost");
    //
    nodeModel.setLoginPwd(autoUser.getAgentPwd());
    nodeModel.setLoginName(autoUser.getAgentName());
    //
    nodeModel.setOpenStatus(true);
    nodeService.addItem(nodeModel);
    DefaultSystemLog.getLog().info("自动添加本机节点成功:" + nodeModel.getId());
}
 
Example 5
Source File: DocumentBrowser.java    From book118-downloader with MIT License 5 votes vote down vote up
List<String> readTaskList() {
    List<String> aTaskDocumentId = new ArrayList<>();
    if (FileUtil.exist(TASK_LIST_FILE)) {
        FileReader fileReader = new FileReader(TASK_LIST_FILE);
        aTaskDocumentId = fileReader.readLines().stream()
                .map(StrUtil::trim).filter(StrUtil::isNotBlank).collect(Collectors.toList());
    }
    return aTaskDocumentId;
}
 
Example 6
Source File: DocumentBrowser.java    From book118-downloader with MIT License 5 votes vote down vote up
void writeTaskList(List<String> pLists) {
    if (!FileUtil.exist(DES_PATH)) {
        FileUtil.mkdir(DES_PATH);
    }
    FileWriter fileWriter = new FileWriter(TASK_LIST_FILE);
    fileWriter.appendLines(pLists);
}
 
Example 7
Source File: DocumentBrowser.java    From book118-downloader with MIT License 5 votes vote down vote up
private int readDownloadedPage(String sDocumentId) {
    int nPage = 1;
    String filePath = String.format(FILE_DOWNLOAD_PAGE, sDocumentId);
    if (FileUtil.exist(filePath)) {
        FileReader fileReader = new FileReader(filePath);
        String sPage = fileReader.readString();
        nPage = Integer.valueOf(sPage);
    }
    return nPage;
}
 
Example 8
Source File: ExecutorJobHandler.java    From datax-web with MIT License 4 votes vote down vote up
@Override
public ReturnT<String> execute(TriggerParam trigger) {

    int exitValue = -1;
    Thread errThread = null;
    String tmpFilePath;
    LogStatistics logStatistics = null;
    //Generate JSON temporary file
    tmpFilePath = generateTemJsonFile(trigger.getJobJson());

    try {
        String[] cmdarrayFinal = buildDataXExecutorCmd(trigger, tmpFilePath,dataXPyPath);
        final Process process = Runtime.getRuntime().exec(cmdarrayFinal);
        String prcsId = ProcessUtil.getProcessId(process);
        JobLogger.log("------------------DataX process id: " + prcsId);
        jobTmpFiles.put(prcsId, tmpFilePath);
        //update datax process id
        HandleProcessCallbackParam prcs = new HandleProcessCallbackParam(trigger.getLogId(), trigger.getLogDateTime(), prcsId);
        ProcessCallbackThread.pushCallBack(prcs);
        // log-thread
        Thread futureThread = null;
        FutureTask<LogStatistics> futureTask = new FutureTask<>(() -> analysisStatisticsLog(new BufferedInputStream(process.getInputStream())));
        futureThread = new Thread(futureTask);
        futureThread.start();

        errThread = new Thread(() -> {
            try {
                analysisStatisticsLog(new BufferedInputStream(process.getErrorStream()));
            } catch (IOException e) {
                JobLogger.log(e);
            }
        });

        logStatistics = futureTask.get();
        errThread.start();
        // process-wait
        exitValue = process.waitFor();      // exit code: 0=success, 1=error
        // log-thread join
        errThread.join();
    } catch (Exception e) {
        JobLogger.log(e);
    } finally {
        if (errThread != null && errThread.isAlive()) {
            errThread.interrupt();
        }
        //  删除临时文件
        if (FileUtil.exist(tmpFilePath)) {
            FileUtil.del(new File(tmpFilePath));
        }
    }
    if (exitValue == 0) {
        return new ReturnT<>(200, logStatistics.toString());
    } else {
        return new ReturnT<>(IJobHandler.FAIL.getCode(), "command exit value(" + exitValue + ") is failed");
    }
}
 
Example 9
Source File: CertModel.java    From Jpom with MIT License 4 votes vote down vote up
/**
 * 解析证书
 *
 * @param key  zip里面文件
 * @param file 证书文件
 * @return 处理后的json
 */
public static JSONObject decodeCert(String file, String key) {
    if (file == null) {
        return null;
    }
    if (!FileUtil.exist(file)) {
        return null;
    }
    InputStream inputStream = null;
    try {
        inputStream = ResourceUtil.getStream(key);
        PrivateKey privateKey = PemUtil.readPemPrivateKey(inputStream);
        IoUtil.close(inputStream);
        inputStream = ResourceUtil.getStream(file);
        PublicKey publicKey = PemUtil.readPemPublicKey(inputStream);
        IoUtil.close(inputStream);
        RSA rsa = new RSA(privateKey, publicKey);
        String encryptStr = rsa.encryptBase64(KEY, KeyType.PublicKey);
        String decryptStr = rsa.decryptStr(encryptStr, KeyType.PrivateKey);
        if (!KEY.equals(decryptStr)) {
            throw new JpomRuntimeException("证书和私钥证书不匹配");
        }
    } finally {
        IoUtil.close(inputStream);
    }
    try {
        inputStream = ResourceUtil.getStream(file);
        // 创建证书对象
        X509Certificate oCert = (X509Certificate) KeyUtil.readX509Certificate(inputStream);
        //到期时间
        Date expirationTime = oCert.getNotAfter();
        //生效日期
        Date effectiveTime = oCert.getNotBefore();
        //域名
        String name = oCert.getSubjectDN().getName();
        int i = name.indexOf("=");
        String domain = name.substring(i + 1);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("expirationTime", expirationTime.getTime());
        jsonObject.put("effectiveTime", effectiveTime.getTime());
        jsonObject.put("domain", domain);
        jsonObject.put("pemPath", file);
        jsonObject.put("keyPath", key);
        return jsonObject;
    } catch (Exception e) {
        DefaultSystemLog.getLog().error(e.getMessage(), e);
    } finally {
        IoUtil.close(inputStream);
    }
    return null;
}