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

net.codestory.http.templating.Site Maven / Gradle / Ivy

Go to download

This is the simplest fastest full fledged http server we could come up with

There is a newer version: 2.105
Show newest version
/**
 * Copyright (C) 2013 [email protected]
 *
 * 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 net.codestory.http.templating;

import static java.nio.charset.StandardCharsets.*;
import static net.codestory.http.misc.MemoizingSupplier.*;

import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.function.*;
import java.util.stream.*;

import net.codestory.http.convert.*;
import net.codestory.http.io.*;
import net.codestory.http.misc.*;

import com.github.jknack.handlebars.*;

public class Site {
  private static Site INSTANCE = new Site();

  private Supplier> yaml;
  private Supplier> data;
  private Supplier>> pages;
  private Supplier>>> tags;
  private Supplier>>> categories;

  private Site() {
    yaml = memoize(() -> loadYamlConfig("_config.yml"));

    data = memoize(() -> Resources.list()
        .stream()
        .filter(path -> path.startsWith("_data/"))
        .collect(Collectors.toMap(path -> nameWithoutExtension(path), path -> readYaml(path))));

    pages = memoize(() -> Resources.list()
        .stream()
        .filter(path -> !path.startsWith("_"))
        .map(path -> Site.pathToMap(path))
        .collect(Collectors.>toList())
    );

    tags = memoize(() -> {
      Map>> tags = new TreeMap<>();
      for (Map page : getPages()) {
        for (String tag : tags(page)) {
          tags.computeIfAbsent(tag, key -> new ArrayList>()).add(page);
        }
      }
      return tags;
    });

    categories = memoize(() -> {
      Map>> sorted = getPages()
          .stream()
          .collect(Collectors.groupingBy(page -> Site.category(page), TreeMap::new, Collectors.toList()));
      return sorted;
    });
  }

  public static Site get() {
    return Env.INSTANCE.prodMode() ? INSTANCE : new Site();
  }

  private Map configYaml() {
    return yaml.get();
  }

  public Object get(String key) {
    return yaml.get().get(key);
  }

  public  T getAs(String key, Class type) {
    return TypeConvert.convertValue(get(key), type);
  }

  public Map getData() {
    return data.get();
  }

  public List> getPages() {
    return pages.get();
  }

  public Map>> getTags() {
    return tags.get();
  }

  public Map>> getCategories() {
    return categories.get();
  }

  private static Map pathToMap(String path) {
    try {
      return YamlFrontMatter.parse(Paths.get(path)).getVariables();
    } catch (IOException e) {
      throw new IllegalStateException("Unable to read file: " + path, e);
    }
  }

  private static Object readYaml(String path) {
    try {
      return YamlParser.INSTANCE.parse(Resources.read(Paths.get(path), UTF_8));
    } catch (IOException e) {
      throw new IllegalStateException("Unable to read file: " + path, e);
    }
  }

  private static String category(Map page) {
    return page.getOrDefault("category", "").toString().trim();
  }

  private static String[] tags(Map page) {
    return page.getOrDefault("tags", "").toString().trim().split("\\s*,\\s*");
  }

  @SuppressWarnings("unchecked")
  private Map loadYamlConfig(String configFile) {
    Path configPath = Paths.get(configFile);
    if (!Resources.exists(configPath)) {
      return new HashMap<>();
    }

    try {
      return YamlParser.INSTANCE.parseMap(Resources.read(configPath, UTF_8));
    } catch (IOException e) {
      throw new IllegalStateException("Unable to read " + configFile, e);
    }
  }

  private static String nameWithoutExtension(String path) {
    return Strings.substringBeforeLast(Paths.get(path).getFileName().toString(), ".");
  }

  static enum SiteValueResolver implements ValueResolver {
    INSTANCE;

    @Override
    public Object resolve(Object context, String name) {
      if (context instanceof Site) {
        return ((Site) context).configYaml().getOrDefault(name, UNRESOLVED);
      }
      return UNRESOLVED;
    }

    @Override
    public Set> propertySet(Object context) {
      if (context instanceof Site) {
        return ((Site) context).configYaml().entrySet();
      }
      return Collections.emptySet();
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy