cn.hutool.core.util.CharsetUtil Java Examples

The following examples show how to use cn.hutool.core.util.CharsetUtil. 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: ResourceServerConfiguration.java    From spring-security with Apache License 2.0 8 votes vote down vote up
@Bean
public AuthenticationEntryPoint authenticationEntryPoint(){
    return (HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) ->{
        Map<String, Object> map = new HashMap<>();
        map.put("code", 401);
        map.put("msg", "非法访问资源,访问此资源需要完全身份验证");
        map.put("path", request.getServletPath());
        map.put("timestamp", System.currentTimeMillis());
        response.setContentType("application/json");
        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(response.getOutputStream(), map);
        } catch (Exception e) {
            throw new ServletException();
        }
    };
}
 
Example #2
Source File: LoginAuthFailedHandler.java    From mall4j with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@SneakyThrows
public void onAuthenticationFailure(HttpServletRequest request,
                                    HttpServletResponse response, AuthenticationException exception) {

    if (!(exception instanceof BaseYamiAuth2Exception)) {
        return;
    }

    BaseYamiAuth2Exception auth2Exception = (BaseYamiAuth2Exception) exception;

    response.setCharacterEncoding(CharsetUtil.UTF_8);
    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
    response.setStatus(auth2Exception.getHttpErrorCode());
    PrintWriter printWriter = response.getWriter();
    printWriter.append(auth2Exception.getMessage());
}
 
Example #3
Source File: FileTailWatcherRun.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 读取文件内容
 *
 * @throws IOException IO
 */
private void read() throws IOException {
    final long currentLength = randomFile.length();
    final long position = randomFile.getFilePointer();
    if (0 == currentLength || currentLength == position) {
        // 内容长度不变时忽略此次
        return;
    } else if (currentLength < position) {
        // 如果内容变短,说明文件做了删改,回到内容末尾
        randomFile.seek(currentLength);
        return;
    }
    String tmp;
    while ((tmp = randomFile.readLine()) != null) {
        tmp = CharsetUtil.convert(tmp, CharsetUtil.CHARSET_ISO_8859_1, charset);
        limitQueue.offer(tmp);
        lineHandler.handle(tmp);
    }
    // 记录当前读到的位置
    this.randomFile.seek(currentLength);
}
 
Example #4
Source File: GenUtil.java    From albedo with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * XML文件转换为对象
 *
 * @param fileName
 * @param clazz
 * @return
 */
@SuppressWarnings("unchecked")
public static <T> T fileToObject(String fileName, Class<?> clazz) {
	String pathName = getTemplatePath() + fileName;
	logger.debug("file to object: {} ", pathName);

	PathMatchingResourcePatternResolver resourceLoader = new PathMatchingResourcePatternResolver();
	String content = null;
	try {
		content = IoUtil.read(resourceLoader.getResources(pathName)[0].getInputStream(), CharsetUtil.CHARSET_UTF_8);
		return (T) JaxbMapper.fromXml(content, clazz);
	} catch (IOException e) {
		logger.warn("error convert: {}", e.getMessage());
	}
	return null;
}
 
Example #5
Source File: AuthUtils.java    From smaker with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 从header 请求中的clientId/clientsecect
 *
 * @param header header中的参数
 * @throws RuntimeException if the Basic header is not present or is not valid
 *                          Base64
 */
public static String[] extractAndDecodeHeader(String header)
	throws IOException {

	byte[] base64Token = header.substring(6).getBytes("UTF-8");
	byte[] decoded;
	try {
		decoded = Base64.decode(base64Token);
	} catch (IllegalArgumentException e) {
		throw new RuntimeException(
			"Failed to decode basic authentication token");
	}

	String token = new String(decoded, CharsetUtil.UTF_8);

	int delim = token.indexOf(":");

	if (delim == -1) {
		throw new RuntimeException("Invalid basic authentication token");
	}
	return new String[]{token.substring(0, delim), token.substring(delim + 1)};
}
 
Example #6
Source File: PasswordDecoderFilter.java    From albedo with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
	// 不是登录请求,直接向下执行
	if (!StrUtil.containsAnyIgnoreCase(request.getRequestURI(), applicationProperties.getAdminPath(SecurityConstants.AUTHENTICATE_URL))) {
		filterChain.doFilter(request, response);
		return;
	}

	String queryParam = request.getQueryString();
	Map<String, String> paramMap = HttpUtil.decodeParamMap(queryParam, CharsetUtil.CHARSET_UTF_8);

	String password = request.getParameter(PASSWORD);
	if (StrUtil.isNotBlank(password)) {
		try {
			password = decryptAes(password, applicationProperties.getSecurity().getEncodeKey());
		} catch (Exception e) {
			log.error("密码解密失败:{}", password);
			throw e;
		}
		paramMap.put(PASSWORD, password.trim());
	}
	ParameterRequestWrapper requestWrapper = new ParameterRequestWrapper(request, paramMap);
	filterChain.doFilter(requestWrapper, response);
}
 
Example #7
Source File: JsonFileUtil.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 读取json 文件,同步
 *
 * @param path 路径
 * @return JSON
 * @throws FileNotFoundException 文件异常
 */
public static JSON readJson(String path) throws FileNotFoundException {
    File file = new File(path);
    if (!file.exists()) {
        throw new FileNotFoundException("没有找到对应配置文件:" + path);
    }
    READ_LOCK.lock();
    // 防止多线程操作文件异常
    try {
        String json = FileUtil.readString(file, CharsetUtil.UTF_8);
        if (StrUtil.isEmpty(json)) {
            return new JSONObject();
        }
        try {
            return (JSON) JSON.parse(json);
        } catch (Exception e) {
            throw new JpomRuntimeException("数据文件内容错误,请检查文件是否被非法修改:" + path, e);
        }
    } finally {
        READ_LOCK.unlock();
    }
}
 
Example #8
Source File: LoginAuthSuccessHandler.java    From mall4j with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Called when a user has been successfully authenticated.
 * 调用spring security oauth API 生成 oAuth2AccessToken
 *
 * @param request        the request which caused the successful authentication
 * @param response       the response
 * @param authentication the <tt>Authentication</tt> object which was created during
 */
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {

    try {

        TokenRequest tokenRequest = new TokenRequest(null, null, null, null);

        // 简化
        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(new BaseClientDetails());
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);


        OAuth2AccessToken oAuth2AccessToken = yamiTokenServices.createAccessToken(oAuth2Authentication);
        log.info("获取token 成功:{}", oAuth2AccessToken.getValue());

        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(oAuth2AccessToken));
    } catch (IOException e) {
        throw new BadCredentialsException(
                "Failed to decode basic authentication token");
    }

}
 
Example #9
Source File: FileUtils.java    From v-mock with MIT License 6 votes vote down vote up
/**
 * 下载文件名重新编码
 *
 * @param request  请求对象
 * @param fileName 文件名
 * @return 编码后的文件名
 */
public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
    final String agent = request.getHeader("USER-AGENT");
    String filename = fileName;
    if (agent.contains(MSIE)) {
        // IE浏览器
        filename = URLEncoder.encode(filename, CharsetUtil.UTF_8);
        filename = filename.replace("+", " ");
    } else if (agent.contains(FIREFOX)) {
        // 火狐浏览器
        filename = new String(fileName.getBytes(), CharsetUtil.ISO_8859_1);
    } else {
        // 其它浏览器
        filename = URLEncoder.encode(filename, CharsetUtil.UTF_8);
    }
    return filename;
}
 
Example #10
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 #11
Source File: ScriptProcessBuilder.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 响应
 *
 * @param line 信息
 */
private void handle(String line) {
    // 写入文件
    List<String> fileLine = new ArrayList<>();
    fileLine.add(line);
    FileUtil.appendLines(fileLine, logFile, CharsetUtil.CHARSET_UTF_8);
    Iterator<Session> iterator = sessions.iterator();
    while (iterator.hasNext()) {
        Session session = iterator.next();
        try {
            SocketSessionUtil.send(session, line);
        } catch (IOException e) {
            DefaultSystemLog.getLog().error("发送消息失败", e);
            iterator.remove();
        }
    }
}
 
Example #12
Source File: JpomApplication.java    From Jpom with MIT License 6 votes vote down vote up
public JpomApplication(Type appType, Class<?> appClass, String[] args) throws Exception {
    super(appClass);
    //
    checkEvent(args);
    JpomApplication.appType = appType;
    JpomApplication.appClass = appClass;
    JpomApplication.args = args;

    addHttpMessageConverter(new StringHttpMessageConverter(CharsetUtil.CHARSET_UTF_8));

    //
    ObjectMapper build = createJackson();
    addHttpMessageConverter(new MappingJackson2HttpMessageConverter(build));

    // 参数拦截器
    addInterceptor(ParameterInterceptor.class);
    addInterceptor(PluginFeatureInterceptor.class);
    //
    addApplicationEventClient(new JpomApplicationEvent());
    // 添加初始化监听
    this.application().addInitializers(new PluginFactory());
}
 
Example #13
Source File: TestJavaTail.java    From Jpom with MIT License 6 votes vote down vote up
public static void test() throws IOException {

//        String path = FileDescriptorTest.class.getClassLoader().getResource("").getPath()+"test.txt";
        File file = new File("D:/ssss/a/tset.log");
        FileOutputStream fileOutputStream = new FileOutputStream(file, true);

        FileDescriptor descriptor = fileOutputStream.getFD();
        FileInputStream nfis = new FileInputStream(descriptor);
        String msg = IoUtil.read(nfis, CharsetUtil.CHARSET_UTF_8);
        System.out.println(msg);
        System.out.println("nfis>>>" + nfis.read());
        FileInputStream sfis = new FileInputStream(descriptor);
        System.out.println("sfis>>>" + sfis.read());
        System.out.println("nfis>>>" + nfis.read());
        nfis.close();
        try {
            System.out.println("sfis>>>" + sfis.read());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("nfis执行异常");
        }
        sfis.close();
    }
 
Example #14
Source File: TopTest.java    From Jpom with MIT License 6 votes vote down vote up
private static String execCommand(String[] command) {
    System.out.println(Arrays.toString(command));
    String result = "error";
    try {
        Process process = Runtime.getRuntime().exec(command);
        InputStream is;
        int wait = process.waitFor();
        if (wait == 0) {
            is = process.getInputStream();
        } else {
            is = process.getErrorStream();
        }
        result = IoUtil.read(is, CharsetUtil.GBK);
        is.close();
        process.destroy();
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
    return result;
}
 
Example #15
Source File: InitDb.java    From Jpom with MIT License 6 votes vote down vote up
@PreLoadMethod
private static void init() {
    Setting setting = new Setting();
    setting.set("url", DbConfig.getInstance().getDbUrl());
    setting.set("user", "jpom");
    setting.set("pass", "jpom");
    // 调试模式显示sql 信息
    if (JpomManifest.getInstance().isDebug()) {
        setting.set("showSql", "true");
        setting.set("sqlLevel", "INFO");
        setting.set("showParams", "true");
    }
    DefaultSystemLog.getLog().info("初始化数据中....");
    try {
        // 创建连接
        DSFactory dsFactory = DSFactory.create(setting);
        InputStream inputStream = ResourceUtil.getStream("classpath:/bin/h2-db-v1.sql");
        String sql = IoUtil.read(inputStream, CharsetUtil.CHARSET_UTF_8);
        Db.use(dsFactory.getDataSource()).execute(sql);
        DSFactory.setCurrentDSFactory(dsFactory);
    } catch (Exception e) {
        DefaultSystemLog.getLog().error("初始化数据库失败", e);
        System.exit(0);
    }
}
 
Example #16
Source File: NodeWelcomeController.java    From Jpom with MIT License 6 votes vote down vote up
@RequestMapping(value = "exportTop")
public void exportTop(String time) throws UnsupportedEncodingException {
    PageResult<SystemMonitorLog> monitorData = getList(time, getCycleMillis());
    if (monitorData.getTotal() <= 0) {
        //            NodeForward.requestDownload(node, getRequest(), getResponse(), NodeUrl.exportTop);
    } else {
        NodeModel node = getNode();
        StringBuilder buf = new StringBuilder();
        buf.append("监控时间").append(",占用cpu").append(",占用内存").append(",占用磁盘").append("\r\n");
        for (SystemMonitorLog log : monitorData) {
            long monitorTime = log.getMonitorTime();
            buf.append(DateUtil.date(monitorTime).toString()).append(",")
                    .append(log.getOccupyCpu()).append("%").append(",")
                    .append(log.getOccupyMemory()).append("%").append(",")
                    .append(log.getOccupyDisk()).append("%").append("\r\n");
        }
        String fileName = URLEncoder.encode("Jpom系统监控-" + node.getId(), "UTF-8");
        HttpServletResponse response = getResponse();
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), "GBK") + ".csv");
        response.setContentType("text/csv;charset=utf-8");
        ServletUtil.write(getResponse(), buf.toString(), CharsetUtil.UTF_8);
    }
}
 
Example #17
Source File: SshInstallAgentController.java    From Jpom with MIT License 6 votes vote down vote up
private String getAuthorize(SshModel sshModel, NodeModel nodeModel, String path) {
    File saveFile = null;
    try {
        String tempFilePath = ServerConfigBean.getInstance().getUserTempPath().getAbsolutePath();
        //  获取远程的授权信息
        String normalize = FileUtil.normalize(StrUtil.format("{}/{}/{}", path, ConfigBean.DATA, ConfigBean.AUTHORIZE));
        saveFile = FileUtil.file(tempFilePath, IdUtil.fastSimpleUUID() + ConfigBean.AUTHORIZE);
        sshService.download(sshModel, normalize, saveFile);
        //
        String json = FileUtil.readString(saveFile, CharsetUtil.CHARSET_UTF_8);
        AgentAutoUser autoUser = JSONObject.parseObject(json, AgentAutoUser.class);
        nodeModel.setLoginPwd(autoUser.getAgentPwd());
        nodeModel.setLoginName(autoUser.getAgentName());
    } catch (Exception e) {
        DefaultSystemLog.getLog().error("拉取授权信息失败", e);
        return JsonMessage.getString(500, "获取授权信息失败", e);
    } finally {
        FileUtil.del(saveFile);
    }
    return null;
}
 
Example #18
Source File: NodeForward.java    From Jpom with MIT License 6 votes vote down vote up
/**
     * 添加agent 授权信息header
     *
     * @param httpRequest request
     * @param nodeModel   节点
     * @param userModel   用户
     */
    private static void addUser(HttpRequest httpRequest, NodeModel nodeModel, NodeUrl nodeUrl, UserModel userModel) {
        // 判断开启状态
        if (!nodeModel.isOpenStatus()) {
            throw new JpomRuntimeException(nodeModel.getName() + "节点未启用");
        }
        if (userModel != null) {
            httpRequest.header(ConfigBean.JPOM_SERVER_USER_NAME, URLEncoder.DEFAULT.encode(UserModel.getOptUserName(userModel), CharsetUtil.CHARSET_UTF_8));
//            httpRequest.header(ConfigBean.JPOM_SERVER_SYSTEM_USER_ROLE, userModel.getUserRole(nodeModel).name());
        }
        httpRequest.header(ConfigBean.JPOM_AGENT_AUTHORIZE, nodeModel.getAuthorize(true));
        //
        if (nodeUrl.getTimeOut() != -1 && nodeModel.getTimeOut() > 0) {
            //
            httpRequest.timeout(nodeModel.getTimeOut());
        }
    }
 
Example #19
Source File: SshService.java    From Jpom with MIT License 6 votes vote down vote up
public static Session getSession(SshModel sshModel) {
    if (sshModel.getConnectType() == SshModel.ConnectType.PASS) {
        return JschUtil.openSession(sshModel.getHost(), sshModel.getPort(), sshModel.getUser(), sshModel.getPassword());
    }
    if (sshModel.getConnectType() == SshModel.ConnectType.PUBKEY) {
        File tempPath = ServerConfigBean.getInstance().getTempPath();
        String sshFile = StrUtil.emptyToDefault(sshModel.getId(), IdUtil.fastSimpleUUID());
        File ssh = FileUtil.file(tempPath, "ssh", sshFile);
        FileUtil.writeString(sshModel.getPrivateKey(), ssh, CharsetUtil.UTF_8);
        byte[] pas = null;
        if (StrUtil.isNotEmpty(sshModel.getPassword())) {
            pas = sshModel.getPassword().getBytes();
        }
        return JschUtil.openSession(sshModel.getHost(), sshModel.getPort(), sshModel.getUser(), FileUtil.getAbsolutePath(ssh), pas);
    }
    throw new IllegalArgumentException("不支持的模式");
}
 
Example #20
Source File: FileTailWatcherRun.java    From Jpom with MIT License 5 votes vote down vote up
private void readLine() throws IOException {
    String line = randomFile.readLine();
    if (line != null) {
        line = CharsetUtil.convert(line, CharsetUtil.CHARSET_ISO_8859_1, charset);
        limitQueue.offerFirst(line);
    }
}
 
Example #21
Source File: ExtConfigBean.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 单例
 *
 * @return this
 */
public static ExtConfigBean getInstance() {
    if (extConfigBean == null) {
        extConfigBean = SpringUtil.getBean(ExtConfigBean.class);
        // 读取配置的编码格式
        if (StrUtil.isNotBlank(extConfigBean.logFileCharset)) {
            try {
                extConfigBean.logFileCharsets = CharsetUtil.charset(extConfigBean.logFileCharset);
            } catch (Exception ignored) {
            }
        }
    }
    return extConfigBean;
}
 
Example #22
Source File: JsonFileUtil.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 保存json 文件,同步
 *
 * @param path 路径
 * @param json 新的json内容
 */
public static void saveJson(String path, JSON json) {
    WRITE_LOCK.lock();
    try {
        // 输出格式化后的json 字符串
        String newsJson = JSON.toJSONString(json, true);
        FileUtil.writeString(newsJson, path, CharsetUtil.UTF_8);
    } finally {
        WRITE_LOCK.unlock();
    }
}
 
Example #23
Source File: FileTailWatcherRun.java    From Jpom with MIT License 5 votes vote down vote up
FileTailWatcherRun(File file, LineHandler lineHandler) throws IOException {
    this.lineHandler = lineHandler;
    this.randomFile = new RandomAccessFile(file, FileMode.r.name());
    Charset detSet = ExtConfigBean.getInstance().getLogFileCharset();
    if (detSet == null) {
        detSet = CharsetUtil.charset(new CharsetDetector().detectChineseCharset(file));
        detSet = (detSet == StandardCharsets.US_ASCII) ? CharsetUtil.CHARSET_UTF_8 : detSet;
    }
    this.charset = detSet;
    if (file.length() > 0) {
        // 开始读取
        this.startRead();
    }
}
 
Example #24
Source File: SystemConfigController.java    From Jpom with MIT License 5 votes vote down vote up
@RequestMapping(value = "config.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
@SystemPermission
public String config(String nodeId) throws IOException {
    String content;
    if (StrUtil.isNotEmpty(nodeId)) {
        JSONObject jsonObject = NodeForward.requestData(getNode(), NodeUrl.SystemGetConfig, getRequest(), JSONObject.class);
        content = jsonObject.getString("content");
    } else {
        content = IoUtil.read(ExtConfigBean.getResource().getInputStream(), CharsetUtil.CHARSET_UTF_8);
    }
    setAttribute("content", content);
    return "system/config";
}
 
Example #25
Source File: TestSSh.java    From Jpom with MIT License 5 votes vote down vote up
/**
     * 执行一条命令
     */
    public static void execCmd(String command, Session session) throws Exception {
        Channel channel = JschUtil.createChannel(session, ChannelType.EXEC);
        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(System.err);


        System.out.println("执行");
//        IoUtil.readUtf8Lines(channel.getExtInputStream(), new LineHandler() {
//            @Override
//            public void handle(String line) {
//                System.out.println(line);
//            }
//        });
        InputStream inputStream = channel.getInputStream();
        channel.connect();
        IoUtil.readLines(inputStream, CharsetUtil.CHARSET_UTF_8, new LineHandler() {
            @Override
            public void handle(String line) {
                System.out.println(line);
            }
        });
        int exitStatus = channel.getExitStatus();
        System.out.println(exitStatus);
        channel.disconnect();
        session.disconnect();
    }
 
Example #26
Source File: GenUtil.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 生成到文件
 *
 * @param tpl
 * @param model
 * @param isReplaceFile
 * @return
 */
public static String generateToFile(TemplateVo tpl, Map<String, Object> model, boolean isReplaceFile) {
	// 获取生成文件 "c:\\temp\\"//
	String realFileName = FreeMarkers.renderString(tpl.getFileName(), model),
		fileName = StringUtil.getProjectPath(realFileName, getConfig().getCodeUiPath()) + File.separator
			+ FreeMarkers.renderString(tpl.getFilePath() + StringUtil.SLASH, model).replaceAll("//|/|\\.", "\\" + File.separator)
			+ realFileName;

	logger.debug(" fileName === " + fileName);
	boolean entityId = "entityId".equals(tpl.getName());
	if (entityId) {
		TableDto table = (TableDto) model.get("table");
		if (table.isNotCompositeId()) {
			return "因不满足联合主键条件已忽略" + fileName + "<br/>";
		}
	}

	// 获取生成文件内容
	String content = FreeMarkers.renderString(StringUtil.trimToEmpty(tpl.getContent()), model);
	logger.debug(" content === \r\n" + content);

	// 如果选择替换文件,则删除原文件
	if (isReplaceFile) {
		FileUtil.deleteFile(fileName);
	}

	// 创建并写入文件
	if (FileUtil.createFile(fileName)) {
		FileUtil.writeString(content, fileName, CharsetUtil.UTF_8);
		logger.debug(" file create === " + fileName);
		return "生成成功:" + fileName + "<br/>";
	} else {
		logger.debug(" file extents === " + fileName);
		return "文件已存在:" + fileName + "<br/>";
	}
}
 
Example #27
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 #28
Source File: BaseBuild.java    From Jpom with MIT License 5 votes vote down vote up
protected void log(String title, Throwable throwable, BuildModel.Status status) {
    DefaultSystemLog.getLog().error(title, throwable);
    FileUtil.appendLines(CollectionUtil.toList(title), this.logFile, CharsetUtil.CHARSET_UTF_8);
    String s = ExceptionUtil.stacktraceToString(throwable);
    FileUtil.appendLines(CollectionUtil.toList(s), this.logFile, CharsetUtil.CHARSET_UTF_8);
    updateStatus(status);
}
 
Example #29
Source File: MybatisUtil.java    From WePush with MIT License 5 votes vote down vote up
/**
 * 初始化数据库文件
 */
public static void initDbFile() throws SQLException {
    File configHomeDir = new File(SystemUtil.configHome);
    if (!configHomeDir.exists()) {
        configHomeDir.mkdirs();
    }
    // 不存在db文件时会自动创建一个
    String sql = FileUtil.readString(MainWindow.class.getResource("/db_init.sql"), CharsetUtil.UTF_8);
    executeSql(sql);
    needInit = true;
}
 
Example #30
Source File: ZIMuKuCommon.java    From SubTitleSearcher with Apache License 2.0 5 votes vote down vote up
/**
 * 获取页面列表
 * @param title
 * @return
 */
public static JSONArray getPageList(String title) {
	String result = httpGet(baseUrl+"/search?q="+URLUtil.encodeAll(title, CharsetUtil.CHARSET_UTF_8));
	//System.out.println(result);
	JSONArray resList = RegexUtil.getMatchList(result, "<p\\s+class=\"tt\\s+clearfix\"><a\\s+href=\"(/subs/[\\w]+\\.html)\"\\s+"
			+ "target=\"_blank\"><b>(.*?)</b></a></p>", Pattern.DOTALL);
	//System.out.println(resList);
	if(resList == null) {
		return new JSONArray();
	}
	
	return resList;
}