Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
erdostw committed Nov 16, 2023
1 parent 36d6dc1 commit acf9fab
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 3 deletions.
46 changes: 46 additions & 0 deletions java-src/io/github/erdos/stencil/impl/LifecycleLock.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package io.github.erdos.stencil.impl;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Supplier;

public final class LifecycleLock implements AutoCloseable {

private final ReentrantReadWriteLock lock;
private final AtomicBoolean alive;
private final Runnable cleanup;

public LifecycleLock(Runnable cleanup) {
this.lock = new ReentrantReadWriteLock();
this.alive = new AtomicBoolean(true);
this.cleanup = Objects.requireNonNull(cleanup);
}

public <T> T run(Supplier<T> supplier) {
lock.readLock().lock();
try {
if (alive.get()) {
return supplier.get();
} else {
throw new IllegalStateException("Component has already been closed.");
}
} finally {
lock.readLock().unlock();
}
}

@Override
public void close() throws Exception {
if (alive.get()) {
lock.writeLock().lock();
try {
if (alive.getAndSet(false)) {
cleanup.run();
}
} finally {
lock.writeLock().unlock();
}
}
}
}
6 changes: 4 additions & 2 deletions src/stencil/process.clj
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
(render [_ fragments function data]
;; TODO: use lifecycle lock here
(let [data (into {} (.getData data))
function (fn [name & args] (.call function) (into-array Object args))
function (fn [name args] (.call function name (into-array Object args)))
writers-map (model/template-model->writers-map @model data function (update-vals fragments datafy))
writer (partial render-writers-map writers-map)]
(reify EvaluatedDocument
Expand All @@ -55,7 +55,9 @@
(close [_]
(reset! model nil)
(FileHelper/forceDelete zip-dir))
(getVariables [_] variables))))
(getVariables [_] variables)
clojure.core.protocols/Datafiable
(datafy [_] @model))))

;; Called from Java API
(defn prepare-fragment [^File fragment-file, ^PrepareOptions options]
Expand Down
2 changes: 1 addition & 1 deletion test/stencil/model_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

(deftest test-load-template-model
(let [model (datafy (api/prepare "test-resources/multipart/main.docx"))]

(println (type model) (type (datafy model)))
(is (contains? model :main))
(is (contains? model :content-types))

Expand Down

0 comments on commit acf9fab

Please sign in to comment.