Skip to content

Commit

Permalink
refactor EvaluatedDocument
Browse files Browse the repository at this point in the history
  • Loading branch information
erdos committed Nov 15, 2023
1 parent 0e552a9 commit 4d865fb
Show file tree
Hide file tree
Showing 5 changed files with 16 additions and 55 deletions.
13 changes: 3 additions & 10 deletions java-src/io/github/erdos/stencil/EvaluatedDocument.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,14 @@

import java.io.*;
import java.util.concurrent.ExecutorService;
import java.util.function.Consumer;

/**
* An evaluated document ready to be converted to the final output format.
*/
@SuppressWarnings("unused")
public interface EvaluatedDocument {

TemplateDocumentFormats getFormat();

Consumer<OutputStream> getWriter();
void write(OutputStream target);

/**
* Writes output of this document to a file
Expand All @@ -24,14 +21,10 @@ default void writeToFile(File output) throws IOException {
throw new IllegalArgumentException("Output file already exists: " + output);
}
try (FileOutputStream fos = new FileOutputStream(output)) {
writeToStream(fos);
write(fos);
}
}

default void writeToStream(OutputStream outputStream) {
getWriter().accept(outputStream);
}

/**
* Creates a blocking input stream that can be used to render generated document.
*
Expand Down Expand Up @@ -59,7 +52,7 @@ default InputStream toInputStream(ExecutorService executorService) {
throw new IllegalStateException("The supplied executor must submit jobs to new threads!");
} else {
try {
writeToStream(outputStream);
write(outputStream);
} catch (Throwable e) {
inputStreamErrors.fail(e);
throw e;
Expand Down
4 changes: 2 additions & 2 deletions java-src/io/github/erdos/stencil/TemplateVariables.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ private TemplateVariables(Set<String> variables, Set<String> fragmentNames) {
root = r;
}

private Node reduce(Node originalNode, String path) {
private static Node reduce(Node originalNode, String path) {
if (path.isEmpty())
return LEAF;
else if (originalNode == null)
Expand Down Expand Up @@ -151,7 +151,7 @@ private List<SchemaError> validate(Object data, Node schema) {
return validateImpl("", data, schema).collect(toList());
}

private Stream<SchemaError> validateImpl(String path, Object data, Node schema) {
private static Stream<SchemaError> validateImpl(String path, Object data, Node schema) {
return schema.accept(new NodeVisitor<Stream<SchemaError>>() {
@Override
public Stream<SchemaError> visitArray(Node wrapped) {
Expand Down
44 changes: 5 additions & 39 deletions java-src/io/github/erdos/stencil/impl/NativeEvaluator.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,26 @@
import clojure.lang.AFunction;
import clojure.lang.IFn;
import clojure.lang.PersistentHashMap;
import io.github.erdos.stencil.*;
import io.github.erdos.stencil.EvaluatedDocument;
import io.github.erdos.stencil.PreparedFragment;
import io.github.erdos.stencil.PreparedTemplate;
import io.github.erdos.stencil.TemplateData;
import io.github.erdos.stencil.exceptions.EvalException;
import io.github.erdos.stencil.functions.FunctionEvaluator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;

import static io.github.erdos.stencil.impl.Logging.debugStopWatch;
import static java.util.Collections.emptyList;

/**
* Default implementation that calls the engine written in Clojure.
*/
public final class NativeEvaluator {

private final static Logger LOGGER = LoggerFactory.getLogger(NativeEvaluator.class);

private final FunctionEvaluator functions = new FunctionEvaluator();


Expand All @@ -46,24 +41,16 @@ public EvaluatedDocument render(PreparedTemplate template, Map<String, PreparedF
throw new IllegalArgumentException("Template data is missing!");
}

final Consumer<Supplier<String>> stopwatch = debugStopWatch(LOGGER);
stopwatch.accept(() -> "Starting document rendering for template " + template.getTemplateFile());

final IFn fn = ClojureHelper.findFunction("eval-template");
final Object argsMap = makeArgsMap(template.getSecretObject(), fragments, data.getData());

final Map result;
try {
result = (Map) fn.invoke(argsMap);
return (EvaluatedDocument) fn.invoke(argsMap);
} catch (EvalException e) {
throw e;
} catch (Exception e) {
throw new EvalException("Unexpected error", e);
}

final Consumer<OutputStream> stream = resultWriter(result);

return build(stream, template.getTemplateFormat());
}


Expand All @@ -75,27 +62,6 @@ public FunctionEvaluator getFunctionEvaluator() {
return functions;
}

private static EvaluatedDocument build(Consumer<OutputStream> writer, TemplateDocumentFormats format) {
return new EvaluatedDocument() {

@Override
public TemplateDocumentFormats getFormat() {
return format;
}

@Override
public Consumer<OutputStream> getWriter() {
return writer;
}
};
}

@SuppressWarnings("unchecked")
private static Consumer<OutputStream> resultWriter(Map result) {
IFn writer = (IFn) ClojureHelper.Keywords.WRITER.getOrThrow(result);
return writer::invoke;
}

@SuppressWarnings("unchecked")
private Object makeArgsMap(Object template, Map<String, PreparedFragment> fragments, Object data) {
final Map result = new HashMap();
Expand Down
2 changes: 1 addition & 1 deletion src/stencil/api.clj
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
(.toInputStream result clojure.lang.Agent/soloExecutor)

(instance? java.io.OutputStream (:output opts))
(.writeToStream result (:output opts))
(.write result (:output opts))

(:output opts)
(let [f (io/file (:output opts))]
Expand Down
8 changes: 5 additions & 3 deletions src/stencil/process.clj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"These functions are called from Java."
(:import [java.io File]
[java.util.zip ZipEntry ZipOutputStream]
[io.github.erdos.stencil PrepareOptions PreparedFragment PreparedTemplate TemplateVariables]
[io.github.erdos.stencil EvaluatedDocument PrepareOptions PreparedFragment PreparedTemplate TemplateVariables]
[io.github.erdos.stencil.impl FileHelper ZipHelper])
(:require [clojure.java.io :as io]
[stencil.log :as log]
Expand Down Expand Up @@ -77,5 +77,7 @@
(defn eval-template [{:keys [template data function fragments]}]
(assert (:source-folder template))
(let [data (into {} data)
writers-map (model/template-model->writers-map template data function fragments)]
{:writer (partial render-writers-map writers-map)}))
writers-map (model/template-model->writers-map template data function fragments)
writer (partial render-writers-map writers-map)]
(reify EvaluatedDocument
(write [_ target-stream] (writer target-stream)))))

0 comments on commit 4d865fb

Please sign in to comment.