private static V8Object hash(V8 v8) { return register(v8, new V8Object(v8)); }
public V8Function function(final JavaCallback callback) { return register(v8, new V8Function(v8, callback)); }
public V8Object hash(final Map<String, Object> hash) { return register(v8, V8ObjectUtils.toV8Object(v8, hash)); }
public V8Array array() { return register(v8, new V8Array(v8)); }
public V8Array array(final List<? extends Object> value) { return register(v8, V8ObjectUtils.toV8Array(v8, value)); }
private <T> Optional<T> get(final String name, final Function<String, T> provider) { return Try.apply(() -> Optional.of(register(v8, provider.apply(name)))) .orElse(Optional.empty()); }
private List<AssetProblem> problems(final V8Array array) { ImmutableList.Builder<AssetProblem> result = ImmutableList.builder(); for (int i = 0; i < array.length(); i++) { result.add(problem(register(v8, array.getObject(i)))); } return result.build(); }
private static Object load(Class<?> loader, V8 v8, final String path) throws Exception { return register(v8, v8.executeScript(readFile(loader, path), path, 0)); }
private List<AssetProblem> problems(final Object value) { if (value instanceof V8Array) { return problems((V8Array) value); } V8Object hash = (V8Object) value; if (hash.contains("errors")) { return problems(register(v8, hash.getArray("errors"))); } if (hash.contains("message")) { return ImmutableList.of(problem(hash)); } return Collections.emptyList(); }
public String execute(final String path, final Object... args) throws Exception { V8Function fn = register(v8, (V8Function) load(path)); V8Array arguments = array(Arrays.asList(args)); Object value = null; try { value = register(v8, fn.call(v8, arguments)); if (value instanceof String) { return value.toString(); } List<AssetProblem> problems = problems(value); if (problems.size() > 0) { throw new AssetException(id, problems); } return ((V8Object) value).getString("output"); } finally { releaseNow(value); releaseNow(arguments); releaseNow(fn); } }