Java Code Examples for cn.hutool.core.io.IoUtil#read()

The following examples show how to use cn.hutool.core.io.IoUtil#read() . 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: SshService.java    From Jpom with MIT License 6 votes vote down vote up
private String exec(Session session, Charset charset, String command) throws IOException, JSchException {
    ChannelExec channel = null;
    try {
        channel = (ChannelExec) JschUtil.createChannel(session, ChannelType.EXEC);
        channel.setCommand(command);
        InputStream inputStream = channel.getInputStream();
        InputStream errStream = channel.getErrStream();
        channel.connect();
        // 读取结果
        String result = IoUtil.read(inputStream, charset);
        //
        String error = IoUtil.read(errStream, charset);
        return result + error;
    } finally {
        JschUtil.close(channel);
    }
}
 
Example 2
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 3
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 4
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 5
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 6
Source File: SystemConfigController.java    From Jpom with MIT License 5 votes vote down vote up
@RequestMapping(value = "getConfig.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String config() throws IOException {
    String content = IoUtil.read(ExtConfigBean.getResource().getInputStream(), CharsetUtil.CHARSET_UTF_8);
    JSONObject json = new JSONObject();
    json.put("content", content);
    return JsonMessage.getString(200, "ok", json);
}
 
Example 7
Source File: IndexControl.java    From Jpom with MIT License 5 votes vote down vote up
@RequestMapping(value = "menus_data.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public String menusData() {
    NodeModel nodeModel = tryGetNode();
    UserModel userModel = getUserModel();
    // 菜单
    InputStream inputStream;
    String secondary;
    if (nodeModel == null) {
        inputStream = ResourceUtil.getStream("classpath:/menus/index.json");
        secondary = "";
    } else {
        inputStream = ResourceUtil.getStream("classpath:/menus/node-index.json");
        secondary = "node/";
    }

    String json = IoUtil.read(inputStream, CharsetUtil.CHARSET_UTF_8);
    JSONArray jsonArray = JSONArray.parseArray(json);
    List<Object> collect1 = jsonArray.stream().filter(o -> {
        JSONObject jsonObject = (JSONObject) o;
        if (!testMenus(jsonObject, userModel, secondary)) {
            return false;
        }
        JSONArray childs = jsonObject.getJSONArray("childs");
        if (childs != null) {
            List<Object> collect = childs.stream().filter(o1 -> {
                JSONObject jsonObject1 = (JSONObject) o1;
                return testMenus(jsonObject1, userModel, secondary);
            }).collect(Collectors.toList());
            if (collect.isEmpty()) {
                return false;
            }
            jsonObject.put("childs", collect);
        }
        return true;
    }).collect(Collectors.toList());
    return JsonMessage.getString(200, "", collect1);
}
 
Example 8
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 9
Source File: XssHttpRequestWrapper.java    From kvf-admin with MIT License 5 votes vote down vote up
@Override
public ServletInputStream getInputStream() throws IOException {
    // 非json类型,直接返回
    if (!MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(super.getHeader(HttpHeaders.CONTENT_TYPE))) {
        return super.getInputStream();
    }

    // 为空,直接返回
    String json = IoUtil.read(super.getInputStream(), "utf-8");
    if (StrUtil.isBlank(json)) {
        return super.getInputStream();
    }

    // xss过滤
    json = xssEncode(json);
    final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
    return new ServletInputStream() {
        @Override
        public boolean isFinished() {
            return true;
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setReadListener(ReadListener readListener) {
        }

        @Override
        public int read() throws IOException {
            return bis.read();
        }
    };
}
 
Example 10
Source File: AdminController.java    From stone with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Markdown 导入
 *
 * @param file    file
 * @param request request
 *
 * @return JsonResult
 */
@PostMapping(value = "/tools/markdownImport")
@ResponseBody
public JsonResult markdownImport(@RequestParam("file") MultipartFile file,
                                 HttpServletRequest request,
                                 HttpSession session) throws IOException {
    final User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY);
    final String markdown = IoUtil.read(file.getInputStream(), "UTF-8");
    final String content = MarkdownUtils.renderMarkdown(markdown);
    final Map<String, List<String>> frontMatters = MarkdownUtils.getFrontMatter(markdown);
    final Post post = new Post();
    List<String> elementValue = null;
    final List<Tag> tags = new ArrayList<>();
    final List<Category> categories = new ArrayList<>();
    Tag tag = null;
    Category category = null;
    if (frontMatters.size() > 0) {
        for (String key : frontMatters.keySet()) {
            elementValue = frontMatters.get(key);
            for (String ele : elementValue) {
                if ("title".equals(key)) {
                    post.setPostTitle(ele);
                } else if ("date".equals(key)) {
                    post.setPostDate(DateUtil.parse(ele));
                } else if ("updated".equals(key)) {
                    post.setPostUpdate(DateUtil.parse(ele));
                } else if ("tags".equals(key)) {
                    tag = tagService.findTagByTagName(ele);
                    if (null == tag) {
                        tag = new Tag();
                        tag.setTagName(ele);
                        tag.setTagUrl(ele);
                        tag = tagService.save(tag);
                    }
                    tags.add(tag);
                } else if ("categories".equals(key)) {
                    category = categoryService.findByCateName(ele);
                    if (null == category) {
                        category = new Category();
                        category.setCateName(ele);
                        category.setCateUrl(ele);
                        category.setCateDesc(ele);
                        category = categoryService.save(category);
                    }
                    categories.add(category);
                }
            }
        }
    } else {
        post.setPostDate(new Date());
        post.setPostUpdate(new Date());
        post.setPostTitle(file.getOriginalFilename());
    }
    post.setPostContentMd(markdown);
    post.setPostContent(content);
    post.setPostType(PostTypeEnum.POST_TYPE_POST.getDesc());
    post.setAllowComment(AllowCommentEnum.ALLOW.getCode());
    post.setUser(user);
    post.setTags(tags);
    post.setCategories(categories);
    post.setPostUrl(StrUtil.removeSuffix(file.getOriginalFilename(), ".md"));
    int postSummary = 50;
    if (StrUtil.isNotEmpty(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()))) {
        postSummary = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()));
    }
    final String summaryText = StrUtil.cleanBlank(HtmlUtil.cleanHtmlTag(post.getPostContent()));
    if (summaryText.length() > postSummary) {
        final String summary = summaryText.substring(0, postSummary);
        post.setPostSummary(summary);
    } else {
        post.setPostSummary(summaryText);
    }
    if (null == post.getPostDate()) {
        post.setPostDate(new Date());
    }
    if (null == post.getPostUpdate()) {
        post.setPostUpdate(new Date());
    }
    postService.save(post);
    return new JsonResult(ResultCodeEnum.SUCCESS.getCode());
}
 
Example 11
Source File: AdminController.java    From blog-sharon with Apache License 2.0 4 votes vote down vote up
/**
 * Markdown 导入
 *
 * @param file    file
 * @param request request
 * @return JsonResult
 */
@PostMapping(value = "/tools/markdownImport")
@ResponseBody
public JsonResult markdownImport(@RequestParam("file") MultipartFile file,
                                 HttpServletRequest request,
                                 HttpSession session) throws IOException {
    User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY);
    String markdown = IoUtil.read(file.getInputStream(), "UTF-8");
    String content = MarkdownUtils.renderMarkdown(markdown);
    Map<String, List<String>> frontMatters = MarkdownUtils.getFrontMatter(markdown);
    Post post = new Post();
    List<String> elementValue = null;
    List<Tag> tags = new ArrayList<>();
    List<Category> categories = new ArrayList<>();
    Tag tag = null;
    Category category = null;
    if (frontMatters.size() > 0) {
        for (String key : frontMatters.keySet()) {
            elementValue = frontMatters.get(key);
            for (String ele : elementValue) {
                if ("title".equals(key)) {
                    post.setPostTitle(ele);
                } else if ("date".equals(key)) {
                    post.setPostDate(DateUtil.parse(ele));
                } else if ("updated".equals(key)) {
                    post.setPostUpdate(DateUtil.parse(ele));
                } else if ("tags".equals(key)) {
                    tag = tagService.findTagByTagName(ele);
                    if (null == tag) {
                        tag = new Tag();
                        tag.setTagName(ele);
                        tag.setTagUrl(ele);
                        tag = tagService.save(tag);
                    }
                    tags.add(tag);
                } else if ("categories".equals(key)) {
                    category = categoryService.findByCateName(ele);
                    if (null == category) {
                        category = new Category();
                        category.setCateName(ele);
                        category.setCateUrl(ele);
                        category.setCateDesc(ele);
                        category = categoryService.save(category);
                    }
                    categories.add(category);
                }
            }
        }
    } else {
        post.setPostDate(new Date());
        post.setPostUpdate(new Date());
        post.setPostTitle(file.getOriginalFilename());
    }
    post.setPostContentMd(markdown);
    post.setPostContent(content);
    post.setPostType(PostTypeEnum.POST_TYPE_POST.getDesc());
    post.setAllowComment(AllowCommentEnum.ALLOW.getCode());
    post.setUser(user);
    post.setTags(tags);
    post.setCategories(categories);
    post.setPostUrl(StrUtil.removeSuffix(file.getOriginalFilename(), ".md"));
    int postSummary = 50;
    if (StrUtil.isNotEmpty(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()))) {
        postSummary = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.POST_SUMMARY.getProp()));
    }
    String summaryText = StrUtil.cleanBlank(HtmlUtil.cleanHtmlTag(post.getPostContent()));
    if (summaryText.length() > postSummary) {
        String summary = summaryText.substring(0, postSummary);
        post.setPostSummary(summary);
    } else {
        post.setPostSummary(summaryText);
    }
    if (null == post.getPostDate()) {
        post.setPostDate(new Date());
    }
    if (null == post.getPostUpdate()) {
        post.setPostUpdate(new Date());
    }
    postService.save(post);
    return new JsonResult(ResultCodeEnum.SUCCESS.getCode());
}
 
Example 12
Source File: BackupServiceImpl.java    From halo with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void importData(MultipartFile file) throws IOException {
    String jsonContent = IoUtil.read(file.getInputStream(), StandardCharsets.UTF_8);

    ObjectMapper mapper = JsonUtils.createDefaultJsonMapper();
    TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
    };
    HashMap<String, Object> data = mapper.readValue(jsonContent, typeRef);

    List<Attachment> attachments = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("attachments")), Attachment[].class));
    attachmentService.createInBatch(attachments);

    List<Category> categories = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("categories")), Category[].class));
    categoryService.createInBatch(categories);

    List<Tag> tags = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("tags")), Tag[].class));
    tagService.createInBatch(tags);

    List<CommentBlackList> commentBlackList = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("comment_black_list")), CommentBlackList[].class));
    commentBlackListService.createInBatch(commentBlackList);

    List<Journal> journals = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("journals")), Journal[].class));
    journalService.createInBatch(journals);

    List<JournalComment> journalComments = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("journal_comments")), JournalComment[].class));
    journalCommentService.createInBatch(journalComments);

    List<Link> links = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("links")), Link[].class));
    linkService.createInBatch(links);

    List<Log> logs = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("logs")), Log[].class));
    logService.createInBatch(logs);

    List<Menu> menus = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("menus")), Menu[].class));
    menuService.createInBatch(menus);

    List<Option> options = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("options")), Option[].class));
    optionService.createInBatch(options);

    eventPublisher.publishEvent(new OptionUpdatedEvent(this));

    List<Photo> photos = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("photos")), Photo[].class));
    photoService.createInBatch(photos);

    List<Post> posts = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("posts")), Post[].class));
    postService.createInBatch(posts);

    List<PostCategory> postCategories = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("post_categories")), PostCategory[].class));
    postCategoryService.createInBatch(postCategories);

    List<PostComment> postComments = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("post_comments")), PostComment[].class));
    postCommentService.createInBatch(postComments);

    List<PostMeta> postMetas = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("post_metas")), PostMeta[].class));
    postMetaService.createInBatch(postMetas);

    List<PostTag> postTags = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("post_tags")), PostTag[].class));
    postTagService.createInBatch(postTags);

    List<Sheet> sheets = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("sheets")), Sheet[].class));
    sheetService.createInBatch(sheets);

    List<SheetComment> sheetComments = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("sheet_comments")), SheetComment[].class));
    sheetCommentService.createInBatch(sheetComments);

    List<SheetMeta> sheetMetas = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("sheet_metas")), SheetMeta[].class));
    sheetMetaService.createInBatch(sheetMetas);

    List<ThemeSetting> themeSettings = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("theme_settings")), ThemeSetting[].class));
    themeSettingService.createInBatch(themeSettings);

    eventPublisher.publishEvent(new ThemeUpdatedEvent(this));
}
 
Example 13
Source File: ServletUtils.java    From yue-library with Apache License 2.0 3 votes vote down vote up
/**
 * 获取请求体<br>
 * 调用该方法后,getParam方法将失效
 * 
 * @param request {@link ServletRequest}
 * @return 获得请求体
 * @since 4.0.2
 */
public static String getBody(ServletRequest request) {
	try {
		return IoUtil.read(request.getReader());
	} catch (IOException e) {
		throw new IORuntimeException(e);
	}
}
 
Example 14
Source File: BackupServiceImpl.java    From halo with GNU General Public License v3.0 3 votes vote down vote up
@Override
public BasePostDetailDTO importMarkdown(MultipartFile file) throws IOException {

    // Read markdown content.
    String markdown = IoUtil.read(file.getInputStream(), StandardCharsets.UTF_8);

    // TODO sheet import

    return postService.importMarkdown(markdown, file.getOriginalFilename());
}