Java tutorial
/* * Copyright 2015 Pawan Dubey pawandubey@outlook.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pawandubey.griffin; import com.pawandubey.griffin.cli.GriffinCommand; import com.pawandubey.griffin.cli.NewCommand; import com.pawandubey.griffin.cli.PreviewCommand; import com.pawandubey.griffin.cli.PublishCommand; import org.apache.commons.lang3.StringUtils; import org.kohsuke.args4j.*; import org.kohsuke.args4j.spi.BooleanOptionHandler; import org.kohsuke.args4j.spi.SubCommand; import org.kohsuke.args4j.spi.SubCommandHandler; import org.kohsuke.args4j.spi.SubCommands; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import static com.pawandubey.griffin.Configurator.LINE_SEPARATOR; import static com.pawandubey.griffin.Data.config; import static com.pawandubey.griffin.Data.fileQueue; /** * * @author Pawan Dubey pawandubey@outlook.com */ public class Griffin { private Parser parser; @Option(name = "--version", aliases = { "-v" }, handler = BooleanOptionHandler.class, usage = "print the current version") private boolean version = false; @Option(name = "--help", aliases = { "-h" }, handler = BooleanOptionHandler.class, usage = "print help message for the command") private boolean help = false; @Argument(usage = "Execute subcommands", metaVar = "<commands>", handler = SubCommandHandler.class) @SubCommands({ @SubCommand(name = "new", impl = NewCommand.class), @SubCommand(name = "publish", impl = PublishCommand.class), @SubCommand(name = "preview", impl = PreviewCommand.class) }) public GriffinCommand commands; /** * Creates a new instance of Griffin */ public Griffin() { } /** * Creates(scaffolds out) a new Griffin directory at the given path. * @throws IOException the exception */ public void draft() throws IOException { initializeConfigurationSettings(); } /** * Parses the content of the site in the 'content' directory and produces * the output. It parses incrementally i.e it only parses the content which * has changed since the last parsing event if the fastParse variable is * true. * * @param fastParse Do a fast incremental parse * @param rebuild Do force a full rebuild * @throws IOException the exception * @throws InterruptedException the exception */ public void publish(boolean fastParse, boolean rebuild) throws IOException, InterruptedException { long start = System.currentTimeMillis(); System.out.println("Rebuilding site from scratch..."); DirectoryCrawler crawler = new DirectoryCrawler(); crawler.readIntoQueue(Paths.get(DirectoryCrawler.SOURCE_DIRECTORY).normalize()); System.out.println("Parsing " + Data.fileQueue.size() + " objects..."); parser = new Parser(); parser.parse(fileQueue); parser.shutDownExecutors(); long end = System.currentTimeMillis(); System.out.println("Time (hardly) taken: " + (end - start) + " ms"); } /** * Creates the server and starts a preview at the given port * * @param port the port number for the server to run on. */ public void preview(Integer port) { Server server = new Server(port); server.startPreview(); server.openBrowser(); } private void printHelpMessage() { String title = this.getClass().getPackage().getImplementationTitle(); String ver = this.getClass().getPackage().getImplementationVersion(); String author = this.getClass().getPackage().getImplementationVendor(); String header = title + " version " + ver + " copyright " + author; String desc = "a simple and fast static site generator"; String usage = "usage: " + title + " [subcommand] [options..] [arguments...]"; String moreHelp = "run " + title + " <subcommand> " + "--help to see more help about individual subcommands"; StringBuilder sb = new StringBuilder(); sb.append(header).append(LINE_SEPARATOR); if (this.version) { System.out.println(sb.toString()); } else { sb.append(desc).append(LINE_SEPARATOR).append(usage).append(LINE_SEPARATOR).append(moreHelp) .append(LINE_SEPARATOR + LINE_SEPARATOR); System.out.println(sb.toString()); } } private void initializeConfigurationSettings() throws NumberFormatException, IOException { String title = null, author = null, date = null, slug = null, layout = "post", category = null, tags = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)); while (StringUtils.isEmpty(title)) { System.out.println("1. title :"); title = br.readLine(); } while (StringUtils.isEmpty(author)) { System.out.println("2. your name : (default is " + config.getSiteAuthor() + ",press Enter omit!)"); author = br.readLine(); if (StringUtils.isBlank(author)) { author = config.getSiteAuthor(); } } while (StringUtils.isEmpty(slug)) { System.out.println("3. url :"); slug = br.readLine(); } while (StringUtils.isEmpty(category)) { System.out.println("4. category : (" + config.getCategories() + ",pick one or create new !):"); category = br.readLine(); } while (StringUtils.isEmpty(tags)) { System.out.println("5. tag : eg: tag1,tag2"); tags = br.readLine(); } while (StringUtils.isEmpty(date)) { System.out.println( "6. write date : (format :" + config.getInputDateFormat() + ",press Enter user today.)"); date = br.readLine(); if (StringUtils.isEmpty(date)) { date = LocalDateTime.now().format(DateTimeFormatter.ofPattern(config.getInputDateFormat())); } } ; Path draftPath = Paths.get(config.getSourceDir()) .resolve(title.replaceAll("\\s+|;|\\)|\\(|&", "-") + ".markdown"); String content = postTemplate.replace("#title", title).replace("#date", date).replace("#category", category) .replace("#layout", layout).replace("#author", author).replace("#tags", formatTag(tags)) .replace("#slug", slug); try (BufferedWriter bw = Files.newBufferedWriter(draftPath, StandardCharsets.UTF_8)) { bw.write(content); } catch (IOException ex) { Logger.getLogger(Parser.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("draft path [" + draftPath + "]"); System.out.println("*******************************************************************"); System.out.println(content); System.out.println("*******************************************************************"); System.out.println("draft path [" + draftPath + "]"); } private String formatTag(String tag) { List<String> list = new ArrayList<>(); String[] items = tag.split(","); for (String item : items) { list.add("\"" + item.trim() + "\""); } return StringUtils.join(list, ","); } private static final String postTemplate = "title=\"#title\"\n" + "author=\"#author\"\n" + "date=\"#date\"\n" + "slug=\"#slug\"\n" + "layout=\"#layout\"\n" + "category=\"#category\"\n" + "tags=[#tags]\n" + "#####\n"; /** * @param args the command line arguments * @throws java.io.IOException the exception * @throws java.lang.InterruptedException the exception */ public static void main(String[] args) throws IOException, InterruptedException { try { Griffin griffin = new Griffin(); CmdLineParser parser = new CmdLineParser(griffin, ParserProperties.defaults().withUsageWidth(120)); parser.parseArgument(args); if (griffin.help || griffin.version || args.length == 0) { griffin.printHelpMessage(); parser.printUsage(System.out); } else { griffin.commands.execute(); } } catch (CmdLineException ex) { Logger.getLogger(Griffin.class.getName()).log(Level.SEVERE, null, ex); } } }