All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.kilmajster.blog.controller.FileBasedBlogController Maven / Gradle / Ivy

There is a newer version: 0.3
Show newest version
package io.github.kilmajster.blog.controller;

import static java.util.Objects.requireNonNull;
import static org.springframework.util.StringUtils.split;

import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;


import org.commonmark.Extension;
import org.commonmark.ext.gfm.strikethrough.Strikethrough;
import org.commonmark.ext.gfm.strikethrough.StrikethroughExtension;
import org.commonmark.ext.gfm.tables.TablesExtension;
import org.commonmark.node.*;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import io.github.kilmajster.blog.config.MinimalBlog;
import io.github.kilmajster.blog.data.Post;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequestMapping("${blog.baseUrl}")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class FileBasedBlogController {

  private final MinimalBlog minimalBlog;

  @GetMapping
  @SneakyThrows
  public String mainPage(ModelMap modelMap) {
    // TODO replace this and rename minimalBlog to minimalBlogConfig
    modelMap.addAttribute("blog", minimalBlog);

    final List posts = getPosts();
    modelMap.addAttribute("posts", posts);

    final Set dates = posts.stream().map(Post::getDate).map(s -> s.replace("-", " / ")).collect(Collectors.toSet());
    modelMap.addAttribute("dates", dates);

    modelMap.addAttribute("elsewheres", minimalBlog.getElsewhere());

    return "blog";
  }

  private List getPosts() throws Exception {
    File blogResourcesRootDir = new DefaultResourceLoader().getResource(minimalBlog.getResourcesRootDir()).getFile();
    List posts = new ArrayList<>();
    Stream.of(requireNonNull(blogResourcesRootDir.list((current, name) -> new File(current, name).isDirectory())))
        .forEach(postsDirectoryName -> Stream.of(postsDirectoryName)
            .filter(Pattern.compile("^(19|20)\\d\\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$").asPredicate())
            .forEach(dateString -> {
              try {
                String dateFilename = minimalBlog.getResourcesRootDir() + "/" + dateString;
                File dateAsDir = new DefaultResourceLoader().getResource(dateFilename).getFile();
                Stream.of(requireNonNull(dateAsDir.list((current, name) -> new File(current, name).isFile())))
                    .filter(Pattern.compile("[^\"]+\\.(html|md)").asPredicate())
                    .forEach(postFileName -> {
                      log.info("Blog post file found - " + minimalBlog.getResourcesRootDir() + "/" + dateString + "/" + postFileName);
                      String postContent = "";
                      try {
                        if (postFileName.endsWith("html")) {
                          postContent = new String(
                              Files.readAllBytes(new DefaultResourceLoader().getResource(
                                  minimalBlog.getResourcesRootDir() + "/" + dateString + "/" + postFileName).getFile().toPath()));
                        } else if (postFileName.endsWith("md")) {
                          String markdown = new String(
                              Files.readAllBytes(new DefaultResourceLoader().getResource(
                                  minimalBlog.getResourcesRootDir() + "/" + dateString + "/" + postFileName).getFile().toPath()));

                          List extensions = Arrays.asList(
                              TablesExtension.create(),
                              StrikethroughExtension.create());

                          Parser parser = Parser.builder()
                              .extensions(extensions)
                              .build();

                          HtmlRenderer renderer = HtmlRenderer.builder()
                              .extensions(extensions)
                              .build();

                          Node document = parser.parse(markdown);
                          postContent = renderer.render(document);

                        } else {
                          throw new RuntimeException();
                        }
                      } catch (Exception e) {
                        e.printStackTrace();
                      }

                      String postTitle = requireNonNull(split(postFileName, "."))[0].replace("-", " ");
                      postTitle = postTitle.substring(0, 1).toUpperCase() + postTitle.substring(1);

                      posts.add(Post.builder()
                          .date(dateString)
                          .title(postTitle)
                          .content(postContent).build());
                    });
              } catch (Exception e) {
                e.printStackTrace();
              }
            }));
    return posts;
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy