v8RuntimeMap;
+ private boolean isolateCreated;
private JavetClassLoader javetClassLoader;
- private boolean libLoaded;
private JavetException lastException;
- private boolean isolateCreated;
+ private boolean libraryLoaded;
private IV8Native v8Native;
private V8Host(JSRuntimeType jsRuntimeType) {
Objects.requireNonNull(jsRuntimeType);
javetClassLoader = null;
lastException = null;
- libLoaded = false;
+ libraryLoaded = false;
flags = new V8Flags();
logger = new JavetDefaultLogger(getClass().getName());
v8RuntimeMap = new ConcurrentHashMap<>();
@@ -73,6 +77,13 @@ private V8Host(JSRuntimeType jsRuntimeType) {
v8Notifier = new V8Notifier(v8RuntimeMap);
}
+ /**
+ * Gets instance by JS runtime type.
+ *
+ * @param jsRuntimeType the JS runtime type
+ * @return the instance
+ * @since 0.7.0
+ */
public static V8Host getInstance(JSRuntimeType jsRuntimeType) {
Objects.requireNonNull(jsRuntimeType);
if (jsRuntimeType.isV8()) {
@@ -83,50 +94,58 @@ public static V8Host getInstance(JSRuntimeType jsRuntimeType) {
return null;
}
+ /**
+ * Gets memory usage threshold ratio.
+ *
+ * @return the memory usage threshold ratio
+ * @since 0.8.3
+ */
+ public static double getMemoryUsageThresholdRatio() {
+ return memoryUsageThresholdRatio;
+ }
+
/**
* Gets Node instance.
*
* Note: Node runtime library is loaded by a custom class loader.
*
* @return the Node instance
+ * @since 0.8.0
*/
public static V8Host getNodeInstance() {
- if (nodeInstance == null) {
- synchronized (nodeLock) {
- if (nodeInstance == null) {
- nodeInstance = new V8Host(JSRuntimeType.Node);
- }
- }
- }
- return nodeInstance;
+ return NodeInstanceHolder.INSTANCE;
}
/**
* Gets V8 instance.
*
- * Note: V8 runtime library is loaded by the default class loader.
+ * Note: V8 runtime library is loaded by a custom class loader.
*
* @return the V8 instance
+ * @since 0.8.0
*/
public static V8Host getV8Instance() {
- return v8Instance;
+ return V8InstanceHolder.INSTANCE;
}
- public static double getMemoryUsageThresholdRatio() {
- return memoryUsageThresholdRatio;
+ /**
+ * Determines whether the JNI library is reloadable or not.
+ *
+ * @return true: reloadable, false: not reloadable, default: false
+ * @since 0.9.1
+ */
+ public static boolean isLibraryReloadable() {
+ return libraryReloadable;
}
/**
- * Sets memory usage threshold ratio.
- *
- * This manageable usage threshold attribute is designed for monitoring
- * the increasing trend of memory usage with low overhead.
+ * Sets whether the JNI library is reloadable or not.
*
- * @param memoryUsageThresholdRatio the memory usage threshold ratio
+ * @param libraryReloadable true: reloadable, false: not reloadable
+ * @since 0.9.1
*/
- public static void setMemoryUsageThresholdRatio(double memoryUsageThresholdRatio) {
- assert 0 <= memoryUsageThresholdRatio && memoryUsageThresholdRatio < 1;
- V8Host.memoryUsageThresholdRatio = memoryUsageThresholdRatio;
+ public static void setLibraryReloadable(boolean libraryReloadable) {
+ V8Host.libraryReloadable = libraryReloadable;
}
private static void setMemoryUsageThreshold() {
@@ -146,6 +165,23 @@ private static void setMemoryUsageThreshold() {
}
}
+ /**
+ * Sets memory usage threshold ratio.
+ *
+ * This manageable usage threshold attribute is designed for monitoring
+ * the increasing trend of memory usage with low overhead.
+ *
+ * @param memoryUsageThresholdRatio the memory usage threshold ratio
+ * @since 0.8.3
+ */
+ public static void setMemoryUsageThresholdRatio(double memoryUsageThresholdRatio) {
+ assert 0 <= memoryUsageThresholdRatio && memoryUsageThresholdRatio < 1;
+ V8Host.memoryUsageThresholdRatio = memoryUsageThresholdRatio;
+ }
+
+ /**
+ * Clear internal statistic for internal test purpose.
+ */
public void clearInternalStatistic() {
v8Native.clearInternalStatistic();
}
@@ -161,49 +197,62 @@ public void close() throws JavetException {
disableGCNotification();
}
- @SuppressWarnings("UnusedReturnValue")
- public V8Host disableGCNotification() {
- v8Notifier.unregisterListener();
- return this;
- }
-
- public V8Host enableGCNotification() {
- setMemoryUsageThreshold();
- // Javet {@link V8Notifier} listens to this notification to notify {@link V8Runtime} to perform GC.
- v8Notifier.registerListeners();
- return this;
- }
-
- public V8Flags getFlags() {
- return flags;
- }
-
- public long[] getInternalStatistic() {
- return v8Native.getInternalStatistic();
- }
-
- public String getJavetVersion() {
- return JavetLibLoader.LIB_VERSION;
- }
-
- public IJavetLogger getLogger() {
- return logger;
- }
-
- IV8Native getV8Native() {
- return v8Native;
+ /**
+ * Close V8 runtime.
+ *
+ * @param v8Runtime the V8 runtime
+ * @since 0.7.0
+ */
+ public void closeV8Runtime(V8Runtime v8Runtime) {
+ if (!libraryLoaded) {
+ return;
+ }
+ if (v8Runtime != null) {
+ final long handle = v8Runtime.getHandle();
+ if (handle > INVALID_HANDLE && v8RuntimeMap.containsKey(handle)) {
+ v8Native.closeV8Runtime(handle);
+ v8RuntimeMap.remove(handle);
+ }
+ }
}
+ /**
+ * Create V8 runtime.
+ *
+ * @param the type parameter
+ * @return the V8 runtime
+ * @throws JavetException the javet exception
+ * @since 0.7.0
+ */
public R createV8Runtime() throws JavetException {
return createV8Runtime(GLOBAL_THIS);
}
+ /**
+ * Create V8 runtime.
+ *
+ * @param the type parameter
+ * @param globalName the global name
+ * @return the V8 runtime
+ * @throws JavetException the javet exception
+ * @since 0.7.0
+ */
public R createV8Runtime(String globalName) throws JavetException {
return createV8Runtime(false, globalName);
}
+ /**
+ * Create V8 runtime.
+ *
+ * @param the type parameter
+ * @param pooled the pooled
+ * @param globalName the global name
+ * @return the V8 runtime
+ * @throws JavetException the javet exception
+ * @since 0.7.0
+ */
public R createV8Runtime(boolean pooled, String globalName) throws JavetException {
- if (!libLoaded) {
+ if (!libraryLoaded) {
if (lastException == null) {
throw new JavetException(
JavetError.LibraryNotLoaded,
@@ -226,77 +275,164 @@ public R createV8Runtime(boolean pooled, String globalName
return (R) v8Runtime;
}
- public void closeV8Runtime(V8Runtime v8Runtime) {
- if (!libLoaded) {
- return;
- }
- if (v8Runtime != null) {
- final long handle = v8Runtime.getHandle();
- if (handle > INVALID_HANDLE && v8RuntimeMap.containsKey(handle)) {
- v8Native.closeV8Runtime(v8Runtime.getHandle());
- v8RuntimeMap.remove(handle);
- }
- }
+ /**
+ * Disable GC notification.
+ *
+ * @return the self
+ * @since 0.8.3
+ */
+ @SuppressWarnings("UnusedReturnValue")
+ public V8Host disableGCNotification() {
+ v8Notifier.unregisterListener();
+ return this;
}
- public JSRuntimeType getJSRuntimeType() {
- return jsRuntimeType;
+ /**
+ * Enable GC notification.
+ *
+ * @return the self
+ * @since 0.8.3
+ */
+ public V8Host enableGCNotification() {
+ setMemoryUsageThreshold();
+ // Javet {@link V8Notifier} listens to this notification to notify {@link V8Runtime} to perform GC.
+ v8Notifier.registerListeners();
+ return this;
}
- private void loadLibrary() {
- if (!libLoaded) {
- if (jsRuntimeType.isNode()) {
- try {
- javetClassLoader = new JavetClassLoader(getClass().getClassLoader(), jsRuntimeType);
- javetClassLoader.load();
- v8Native = javetClassLoader.getNative();
- libLoaded = true;
- } catch (JavetException e) {
- logger.logError(e, "Failed to load Javet lib with error {0}.", e.getMessage());
- lastException = e;
- }
- } else {
- try {
- JavetLibLoader javetLibLoader = new JavetLibLoader(jsRuntimeType);
- javetLibLoader.load();
- v8Native = new V8Native();
- libLoaded = true;
- } catch (JavetException e) {
- logger.logError(e, "Failed to load Javet lib with error {0}.", e.getMessage());
- lastException = e;
- }
- }
- }
+ /**
+ * Gets flags.
+ *
+ * @return the flags
+ * @since 0.7.0
+ */
+ public V8Flags getFlags() {
+ return flags;
}
- private void unloadLibrary() {
- if (jsRuntimeType.isNode() && libLoaded) {
- javetClassLoader = null;
- System.gc();
- System.runFinalization();
- libLoaded = false;
- }
+ /**
+ * Get internal statistic internal for test purpose.
+ *
+ * @return the long [ ]
+ * @since 0.8.3
+ */
+ public long[] getInternalStatistic() {
+ return v8Native.getInternalStatistic();
+ }
+
+ /**
+ * Gets JS runtime type.
+ *
+ * @return the JS runtime type
+ * @since 0.8.0
+ */
+ public JSRuntimeType getJSRuntimeType() {
+ return jsRuntimeType;
}
+ /**
+ * Gets javet version.
+ *
+ * @return the javet version
+ * @since 0.7.1
+ */
+ public String getJavetVersion() {
+ return JavetLibLoader.LIB_VERSION;
+ }
+
+ /**
+ * Gets last exception.
+ *
+ * @return the last exception
+ * @since 0.7.0
+ */
public JavetException getLastException() {
return lastException;
}
- public int getV8RuntimeCount() {
- return v8RuntimeMap.size();
+ /**
+ * Gets logger.
+ *
+ * @return the logger
+ * @since 0.7.3
+ */
+ public IJavetLogger getLogger() {
+ return logger;
+ }
+
+ /**
+ * Gets V8 native.
+ *
+ * @return the V8 native
+ * @since 0.8.0
+ */
+ IV8Native getV8Native() {
+ return v8Native;
}
- public boolean isLibLoaded() {
- return libLoaded;
+ /**
+ * Gets V8 runtime count.
+ *
+ * @return the V8 runtime count
+ * @since 0.8.0
+ */
+ public int getV8RuntimeCount() {
+ return v8RuntimeMap.size();
}
+ /**
+ * Is isolate created.
+ *
+ * @return true: created, false: not created
+ * @since 0.8.0
+ */
public boolean isIsolateCreated() {
return isolateCreated;
}
+ /**
+ * Is library loaded.
+ *
+ * @return true: loaded, false: not loaded
+ * @since 0.8.0
+ */
+ public boolean isLibraryLoaded() {
+ return libraryLoaded;
+ }
+
+ /**
+ * Load library.
+ *
+ * Note: setLibraryReloadable(true) must be called, otherwise, JVM will crash.
+ *
+ * @return true: library is loaded, false: library is not loaded
+ * @since 0.9.1
+ */
+ public synchronized boolean loadLibrary() {
+ if (!libraryLoaded) {
+ try {
+ javetClassLoader = new JavetClassLoader(getClass().getClassLoader(), jsRuntimeType);
+ javetClassLoader.load();
+ v8Native = javetClassLoader.getNative();
+ libraryLoaded = true;
+ isolateCreated = false;
+ } catch (JavetException e) {
+ logger.logError(e, "Failed to load Javet lib with error {0}.", e.getMessage());
+ lastException = e;
+ }
+ }
+ return libraryLoaded;
+ }
+
+ /**
+ * Sets flags.
+ *
+ * @return true: flags are set, false: flags are not set
+ * @since 0.7.0
+ */
@SuppressWarnings("UnusedReturnValue")
public boolean setFlags() {
- if (libLoaded && !isolateCreated) {
+ if (libraryLoaded && !isolateCreated) {
List flags = new ArrayList<>();
if (this.flags.isAllowNativesSyntax()) {
flags.add(FLAG_ALLOW_NATIVES_SYNTAX);
@@ -318,4 +454,33 @@ public boolean setFlags() {
}
return false;
}
+
+ /**
+ * Unload library.
+ *
+ * Note: setLibraryReloadable(true) must be called, otherwise, JVM will crash.
+ *
+ * @return true: library is unloaded, false: library is loaded
+ * @since 0.9.1
+ */
+ public synchronized boolean unloadLibrary() {
+ if (libraryLoaded && v8RuntimeMap.isEmpty()) {
+ isolateCreated = false;
+ v8Native = null;
+ javetClassLoader = null;
+ System.gc();
+ System.runFinalization();
+ libraryLoaded = false;
+ lastException = null;
+ }
+ return !libraryLoaded;
+ }
+
+ private static class NodeInstanceHolder {
+ private static V8Host INSTANCE = new V8Host(JSRuntimeType.Node);
+ }
+
+ private static class V8InstanceHolder {
+ private static V8Host INSTANCE = new V8Host(JSRuntimeType.V8);
+ }
}
diff --git a/src/main/java/com/caoccao/javet/interop/V8Inspector.java b/src/main/java/com/caoccao/javet/interop/V8Inspector.java
index cc4ed715e..61b80a06c 100644
--- a/src/main/java/com/caoccao/javet/interop/V8Inspector.java
+++ b/src/main/java/com/caoccao/javet/interop/V8Inspector.java
@@ -26,11 +26,11 @@
import java.util.Objects;
public final class V8Inspector {
- private IJavetLogger logger;
- private final String name;
private final List listeners;
+ private final String name;
private final IV8Native v8Native;
private final V8Runtime v8Runtime;
+ private IJavetLogger logger;
V8Inspector(V8Runtime v8Runtime, String name, IV8Native v8Native) {
logger = v8Runtime.getLogger();
@@ -61,11 +61,6 @@ public IJavetLogger getLogger() {
return logger;
}
- public void setLogger(IJavetLogger logger) {
- Objects.requireNonNull(logger);
- this.logger = logger;
- }
-
public String getName() {
return name;
}
@@ -120,4 +115,9 @@ public void sendRequest(String message) throws JavetException {
}
v8Native.v8InspectorSend(v8Runtime.getHandle(), message);
}
+
+ public void setLogger(IJavetLogger logger) {
+ Objects.requireNonNull(logger);
+ this.logger = logger;
+ }
}
diff --git a/src/main/java/com/caoccao/javet/interop/V8Native.java b/src/main/java/com/caoccao/javet/interop/V8Native.java
index 3df5f51ae..5839fd5ad 100644
--- a/src/main/java/com/caoccao/javet/interop/V8Native.java
+++ b/src/main/java/com/caoccao/javet/interop/V8Native.java
@@ -117,10 +117,10 @@ public native Object execute(
public native Object getOwnPropertyNames(long v8RuntimeHandle, long v8ValueHandle, int v8ValueType);
@Override
- public native Object getPropertyNames(long v8RuntimeHandle, long v8ValueHandle, int v8ValueType);
+ public native Object getProperty(long v8RuntimeHandle, long v8ValueHandle, int v8ValueType, Object key);
@Override
- public native Object getProperty(long v8RuntimeHandle, long v8ValueHandle, int v8ValueType, Object key);
+ public native Object getPropertyNames(long v8RuntimeHandle, long v8ValueHandle, int v8ValueType);
@Override
public native int getSize(long v8RuntimeHandle, long v8ValueHandle, int v8ValueType);
diff --git a/src/main/java/com/caoccao/javet/interop/V8Runtime.java b/src/main/java/com/caoccao/javet/interop/V8Runtime.java
index 842ef7d74..8bd71b9c3 100644
--- a/src/main/java/com/caoccao/javet/interop/V8Runtime.java
+++ b/src/main/java/com/caoccao/javet/interop/V8Runtime.java
@@ -45,10 +45,10 @@
@SuppressWarnings("unchecked")
public class V8Runtime implements IJavetClosable, IV8Creatable, IV8Convertible {
- protected static final long INVALID_HANDLE = 0L;
- protected static final String PROPERTY_DATA_VIEW = "DataView";
protected static final IJavetConverter DEFAULT_CONVERTER = new JavetObjectConverter();
protected static final String DEFAULT_MESSAGE_FORMAT_JAVET_INSPECTOR = "Javet Inspector {0}";
+ protected static final long INVALID_HANDLE = 0L;
+ protected static final String PROPERTY_DATA_VIEW = "DataView";
protected static final int V8_VALUE_BOOLEAN_FALSE_INDEX = 0;
protected static final int V8_VALUE_BOOLEAN_TRUE_INDEX = 1;
protected static final int V8_VALUE_NUMBER_LOWER_BOUND = -128; // Inclusive
@@ -71,13 +71,13 @@ public class V8Runtime implements IJavetClosable, IV8Creatable, IV8Convertible {
protected String globalName;
protected long handle;
protected IJavetLogger logger;
- protected Map v8ModuleMap;
protected boolean pooled;
protected IJavetPromiseRejectCallback promiseRejectCallback;
protected Map referenceMap;
protected V8Host v8Host;
- protected IV8Native v8Native;
protected V8Inspector v8Inspector;
+ protected Map v8ModuleMap;
+ protected IV8Native v8Native;
V8Runtime(V8Host v8Host, long handle, boolean pooled, IV8Native v8Native, String globalName) {
assert handle != 0;
@@ -102,14 +102,14 @@ public void add(IV8ValueSet iV8ValueKeySet, V8Value value) throws JavetException
v8Native.add(handle, iV8ValueKeySet.getHandle(), iV8ValueKeySet.getType().getId(), value);
}
- public void addV8Module(IV8Module iV8Module) {
- v8ModuleMap.put(iV8Module.getResourceName(), iV8Module);
- }
-
public void addReference(IV8ValueReference iV8ValueReference) {
referenceMap.put(iV8ValueReference.getHandle(), iV8ValueReference);
}
+ public void addV8Module(IV8Module iV8Module) {
+ v8ModuleMap.put(iV8Module.getResourceName(), iV8Module);
+ }
+
public void allowEval(boolean allow) {
v8Native.allowCodeGenerationFromStrings(handle, allow);
}
@@ -153,6 +153,7 @@ public void close(boolean forceClose) throws JavetException {
removeAllReferences();
v8Host.closeV8Runtime(this);
handle = INVALID_HANDLE;
+ v8Native = null;
}
}
@@ -202,11 +203,6 @@ public V8ValueBoolean createV8ValueBoolean(boolean booleanValue) throws JavetExc
cachedV8ValueBooleans[V8_VALUE_BOOLEAN_FALSE_INDEX];
}
- @Override
- public V8ValueDouble createV8ValueDouble(double doubleValue) throws JavetException {
- return decorateV8Value(new V8ValueDouble(doubleValue));
- }
-
@Override
public V8ValueDataView createV8ValueDataView(V8ValueArrayBuffer v8ValueArrayBuffer) throws JavetException {
Objects.requireNonNull(v8ValueArrayBuffer);
@@ -215,6 +211,11 @@ public V8ValueDataView createV8ValueDataView(V8ValueArrayBuffer v8ValueArrayBuff
}
}
+ @Override
+ public V8ValueDouble createV8ValueDouble(double doubleValue) throws JavetException {
+ return decorateV8Value(new V8ValueDouble(doubleValue));
+ }
+
@Override
public V8ValueFunction createV8ValueFunction(JavetCallbackContext javetCallbackContext) throws JavetException {
Objects.requireNonNull(javetCallbackContext);
@@ -341,19 +342,6 @@ public IJavetConverter getConverter() {
return converter;
}
- public void setConverter(IJavetConverter converter) {
- Objects.requireNonNull(converter);
- this.converter = converter;
- }
-
- public String getGlobalName() {
- return globalName;
- }
-
- public void setGlobalName(String globalName) {
- this.globalName = globalName;
- }
-
public IV8Executor getExecutor(File scriptFile) throws JavetException {
return getExecutor(scriptFile.toPath());
}
@@ -366,17 +354,8 @@ public IV8Executor getExecutor(String scriptString) {
return new V8StringExecutor(this, scriptString);
}
- @SuppressWarnings("RedundantThrows")
- public int getIdentityHash(IV8ValueReference iV8ValueReference) throws JavetException {
- return v8Native.getIdentityHash(handle, iV8ValueReference.getHandle(), iV8ValueReference.getType().getId());
- }
-
- public IJavetLogger getLogger() {
- return logger;
- }
-
- public void setLogger(IJavetLogger logger) {
- this.logger = logger;
+ public String getGlobalName() {
+ return globalName;
}
public V8ValueGlobalObject getGlobalObject() throws JavetException {
@@ -387,6 +366,11 @@ public long getHandle() {
return handle;
}
+ @SuppressWarnings("RedundantThrows")
+ public int getIdentityHash(IV8ValueReference iV8ValueReference) throws JavetException {
+ return v8Native.getIdentityHash(handle, iV8ValueReference.getHandle(), iV8ValueReference.getType().getId());
+ }
+
public IV8ValueArray getInternalProperties(IV8ValueFunction iV8ValueFunction) throws JavetException {
return decorateV8Value((V8ValueArray) v8Native.getInternalProperties(
handle, iV8ValueFunction.getHandle(), iV8ValueFunction.getType().getId()));
@@ -397,15 +381,15 @@ public JSFunctionType getJSFunctionType(IV8ValueFunction iV8ValueFunction) {
handle, iV8ValueFunction.getHandle(), iV8ValueFunction.getType().getId()));
}
+ public JSRuntimeType getJSRuntimeType() {
+ return JSRuntimeType.V8;
+ }
+
public JSScopeType getJSScopeType(IV8ValueFunction iV8ValueFunction) {
return JSScopeType.parse(v8Native.getJSScopeType(
handle, iV8ValueFunction.getHandle(), iV8ValueFunction.getType().getId()));
}
- public JSRuntimeType getJSRuntimeType() {
- return JSRuntimeType.V8;
- }
-
public int getLength(IV8ValueArray iV8ValueArray) throws JavetException {
return v8Native.getLength(handle, iV8ValueArray.getHandle(), iV8ValueArray.getType().getId());
}
@@ -414,6 +398,10 @@ public int getLength(IV8ValueTypedArray iV8ValueTypedArray) throws JavetExceptio
return v8Native.getLength(handle, iV8ValueTypedArray.getHandle(), iV8ValueTypedArray.getType().getId());
}
+ public IJavetLogger getLogger() {
+ return logger;
+ }
+
public IV8ValueArray getOwnPropertyNames(
IV8ValueObject iV8ValueObject) throws JavetException {
return decorateV8Value((V8ValueArray) v8Native.getOwnPropertyNames(
@@ -424,11 +412,6 @@ public IJavetPromiseRejectCallback getPromiseRejectCallback() {
return promiseRejectCallback;
}
- public void setPromiseRejectCallback(IJavetPromiseRejectCallback promiseRejectCallback) {
- Objects.requireNonNull(promiseRejectCallback);
- this.promiseRejectCallback = promiseRejectCallback;
- }
-
public T getProperty(
IV8ValueObject iV8ValueObject, V8Value key) throws JavetException {
decorateV8Value(key);
@@ -492,6 +475,19 @@ public boolean hasOwnProperty(IV8ValueObject iV8ValueObject, V8Value key) throws
return v8Native.hasOwnProperty(handle, iV8ValueObject.getHandle(), iV8ValueObject.getType().getId(), key);
}
+ /**
+ * Idle notification deadline.
+ *
+ * Note: This API is the recommended one that notifies V8 to perform GC.
+ *
+ * @param deadlineInMillis the deadline in millis
+ */
+ public void idleNotificationDeadline(long deadlineInMillis) {
+ if (handle != INVALID_HANDLE && deadlineInMillis > 0) {
+ v8Native.idleNotificationDeadline(handle, deadlineInMillis);
+ }
+ }
+
protected void initializeV8ValueCache() {
try {
cachedV8ValueNull = decorateV8Value(new V8ValueNull());
@@ -530,23 +526,6 @@ public boolean isGCScheduled() {
return gcScheduled;
}
- public void setGCScheduled(boolean gcScheduled) {
- this.gcScheduled = gcScheduled;
- }
-
- /**
- * Idle notification deadline.
- *
- * Note: This API is the recommended one that notifies V8 to perform GC.
- *
- * @param deadlineInMillis the deadline in millis
- */
- public void idleNotificationDeadline(long deadlineInMillis) {
- if (handle != INVALID_HANDLE && deadlineInMillis > 0) {
- v8Native.idleNotificationDeadline(handle, deadlineInMillis);
- }
- }
-
public boolean isInUse() {
return v8Native.isInUse(handle);
}
@@ -630,6 +609,17 @@ public T promiseThen(
functionRejectedHandle == null ? 0L : functionRejectedHandle.getHandle()));
}
+ protected void receivePromiseRejectCallback(int event, V8ValuePromise promise, V8Value value) {
+ try {
+ decorateV8Values(promise, value);
+ promiseRejectCallback.callback(JavetPromiseRejectEvent.parse(event), promise, value);
+ } catch (Throwable t) {
+ logger.logError(t, "Failed to process promise reject callback {0}.", event);
+ } finally {
+ JavetResourceUtils.safeClose(promise, value);
+ }
+ }
+
protected void removeAllReferences() throws JavetException {
removeReferences();
removeCallbackContexts();
@@ -755,17 +745,6 @@ public V8Runtime resetIsolate() throws JavetException {
return this;
}
- protected void receivePromiseRejectCallback(int event, V8ValuePromise promise, V8Value value) {
- try {
- decorateV8Values(promise, value);
- promiseRejectCallback.callback(JavetPromiseRejectEvent.parse(event), promise, value);
- } catch (Throwable t) {
- logger.logError(t, "Failed to process promise reject callback {0}.", event);
- } finally {
- JavetResourceUtils.safeClose(promise, value);
- }
- }
-
public boolean sameValue(IV8ValueObject iV8ValueObject1, IV8ValueObject iV8ValueObject2) {
return v8Native.sameValue(handle, iV8ValueObject1.getHandle(), iV8ValueObject2.getHandle());
}
@@ -797,6 +776,28 @@ public boolean setAccessor(
return isAccessorSet;
}
+ public void setConverter(IJavetConverter converter) {
+ Objects.requireNonNull(converter);
+ this.converter = converter;
+ }
+
+ public void setGCScheduled(boolean gcScheduled) {
+ this.gcScheduled = gcScheduled;
+ }
+
+ public void setGlobalName(String globalName) {
+ this.globalName = globalName;
+ }
+
+ public void setLogger(IJavetLogger logger) {
+ this.logger = logger;
+ }
+
+ public void setPromiseRejectCallback(IJavetPromiseRejectCallback promiseRejectCallback) {
+ Objects.requireNonNull(promiseRejectCallback);
+ this.promiseRejectCallback = promiseRejectCallback;
+ }
+
public boolean setProperty(IV8ValueObject iV8ValueObject, V8Value key, V8Value value) throws JavetException {
decorateV8Values(key, value);
return v8Native.setProperty(handle, iV8ValueObject.getHandle(), iV8ValueObject.getType().getId(), key, value);
diff --git a/src/main/java/com/caoccao/javet/interop/V8ScriptOrigin.java b/src/main/java/com/caoccao/javet/interop/V8ScriptOrigin.java
index 0630f71a4..4a15cdb50 100644
--- a/src/main/java/com/caoccao/javet/interop/V8ScriptOrigin.java
+++ b/src/main/java/com/caoccao/javet/interop/V8ScriptOrigin.java
@@ -19,12 +19,12 @@
public final class V8ScriptOrigin {
- private String resourceName;
- private int resourceLineOffset;
+ private boolean module;
private int resourceColumnOffset;
+ private int resourceLineOffset;
+ private String resourceName;
private int scriptId;
private boolean wasm;
- private boolean module;
public V8ScriptOrigin(
String resourceName,
@@ -65,26 +65,33 @@ public V8ScriptOrigin(
scriptId, false, false);
}
+ public int getResourceColumnOffset() {
+ return resourceColumnOffset;
+ }
+
+ public int getResourceLineOffset() {
+ return resourceLineOffset;
+ }
+
public String getResourceName() {
return resourceName;
}
- public V8ScriptOrigin setResourceName(String resourceName) {
- this.resourceName = resourceName;
- return this;
+ public int getScriptId() {
+ return scriptId;
}
- public int getResourceLineOffset() {
- return resourceLineOffset;
+ public boolean isModule() {
+ return module;
}
- public V8ScriptOrigin setResourceLineOffset(int resourceLineOffset) {
- this.resourceLineOffset = resourceLineOffset;
- return this;
+ public boolean isWasm() {
+ return wasm;
}
- public int getResourceColumnOffset() {
- return resourceColumnOffset;
+ public V8ScriptOrigin setModule(boolean module) {
+ this.module = module;
+ return this;
}
public V8ScriptOrigin setResourceColumnOffset(int resourceColumnOffset) {
@@ -92,30 +99,23 @@ public V8ScriptOrigin setResourceColumnOffset(int resourceColumnOffset) {
return this;
}
- public int getScriptId() {
- return scriptId;
+ public V8ScriptOrigin setResourceLineOffset(int resourceLineOffset) {
+ this.resourceLineOffset = resourceLineOffset;
+ return this;
}
- public V8ScriptOrigin setScriptId(int scriptId) {
- this.scriptId = scriptId;
+ public V8ScriptOrigin setResourceName(String resourceName) {
+ this.resourceName = resourceName;
return this;
}
- public boolean isWasm() {
- return wasm;
+ public V8ScriptOrigin setScriptId(int scriptId) {
+ this.scriptId = scriptId;
+ return this;
}
public V8ScriptOrigin setWasm(boolean wasm) {
this.wasm = wasm;
return this;
}
-
- public boolean isModule() {
- return module;
- }
-
- public V8ScriptOrigin setModule(boolean module) {
- this.module = module;
- return this;
- }
}
diff --git a/src/main/java/com/caoccao/javet/interop/engine/IJavetEngine.java b/src/main/java/com/caoccao/javet/interop/engine/IJavetEngine.java
index ae32144cb..d36edf99e 100644
--- a/src/main/java/com/caoccao/javet/interop/engine/IJavetEngine.java
+++ b/src/main/java/com/caoccao/javet/interop/engine/IJavetEngine.java
@@ -26,14 +26,14 @@
public interface IJavetEngine extends IJavetClosable {
JavetEngineConfig getConfig();
- R getV8Runtime() throws JavetException;
-
@CheckReturnValue
IJavetEngineGuard getGuard();
@CheckReturnValue
IJavetEngineGuard getGuard(long timeoutMillis);
+ R getV8Runtime() throws JavetException;
+
boolean isActive();
void resetContext() throws JavetException;
diff --git a/src/main/java/com/caoccao/javet/interop/engine/JavetEngine.java b/src/main/java/com/caoccao/javet/interop/engine/JavetEngine.java
index 069865b91..fbe4eed53 100644
--- a/src/main/java/com/caoccao/javet/interop/engine/JavetEngine.java
+++ b/src/main/java/com/caoccao/javet/interop/engine/JavetEngine.java
@@ -56,11 +56,6 @@ protected void close(boolean forceClose) throws JavetException {
}
}
- @Override
- public void sendGCNotification() {
- v8Runtime.lowMemoryNotification();
- }
-
@Override
public JavetEngineConfig getConfig() {
return iJavetEnginePool.getConfig();
@@ -78,6 +73,15 @@ public IJavetEngineGuard getGuard(long timeoutMillis) {
return new JavetEngineGuard(this, v8Runtime, timeoutMillis);
}
+ /**
+ * Gets utc now. It's designed for mocking the time in test scenario.
+ *
+ * @return the utc now
+ */
+ protected ZonedDateTime getUTCNow() {
+ return JavetDateTimeUtils.getUTCNow();
+ }
+
protected JavetEngineUsage getUsage() {
return usage;
}
@@ -88,13 +92,9 @@ public R getV8Runtime() throws JavetException {
return v8Runtime;
}
- /**
- * Gets utc now. It's designed for mocking the time in test scenario.
- *
- * @return the utc now
- */
- protected ZonedDateTime getUTCNow() {
- return JavetDateTimeUtils.getUTCNow();
+ @Override
+ public boolean isActive() {
+ return active;
}
@Override
@@ -109,13 +109,9 @@ public void resetIsolate() throws JavetException {
usage.reset();
}
- protected void touchLastActiveZonedDateTime() {
- usage.setLastActiveZonedDatetime(getUTCNow());
- }
-
@Override
- public boolean isActive() {
- return active;
+ public void sendGCNotification() {
+ v8Runtime.lowMemoryNotification();
}
protected void setActive(boolean active) {
@@ -123,4 +119,8 @@ protected void setActive(boolean active) {
touchLastActiveZonedDateTime();
}
+ protected void touchLastActiveZonedDateTime() {
+ usage.setLastActiveZonedDatetime(getUTCNow());
+ }
+
}
diff --git a/src/main/java/com/caoccao/javet/interop/engine/JavetEngineConfig.java b/src/main/java/com/caoccao/javet/interop/engine/JavetEngineConfig.java
index d15ffe518..e2f394e4b 100644
--- a/src/main/java/com/caoccao/javet/interop/engine/JavetEngineConfig.java
+++ b/src/main/java/com/caoccao/javet/interop/engine/JavetEngineConfig.java
@@ -29,7 +29,6 @@ public final class JavetEngineConfig {
public static final int DEFAULT_ENGINE_GUARD_TIMEOUT_MILLIS = 30000;
public static final int DEFAULT_ENGINE_GUARD_CHECK_INTERVAL_MILLIS = 1000;
public static final JSRuntimeType DEFAULT_JS_RUNTIME_TYPE = JSRuntimeType.V8;
- public static final int DEFAULT_MAX_ENGINE_USED_COUNT = 100;
public static final int DEFAULT_POOL_MIN_SIZE = 1;
public static final int DEFAULT_POOL_IDLE_TIMEOUT_SECONDS = 60;
public static final int DEFAULT_POOL_DAEMON_CHECK_INTERVAL_MILLIS = 1000;
@@ -37,125 +36,114 @@ public final class JavetEngineConfig {
public static final String DEFAULT_GLOBAL_NAME = "window";
public static final int DEFAULT_POOL_SHUTDOWN_TIMEOUT_SECONDS = 5;
public static IJavetLogger DEFAULT_JAVET_LOGGER = new JavetDefaultLogger(JavetEnginePool.class.getName());
- private IJavetLogger javetLogger;
- private String globalName;
private boolean allowEval;
private boolean autoSendGCNotification;
private int defaultEngineGuardTimeoutMillis;
private int engineGuardCheckIntervalMillis;
+ private ExecutorService executorService;
private boolean gcBeforeEngineClose;
+ private String globalName;
+ private IJavetLogger javetLogger;
private JSRuntimeType jsRuntimeType;
- private int maxEngineUsedCount;
private int poolDaemonCheckIntervalMillis;
+ private int poolIdleTimeoutSeconds;
private int poolMaxSize;
private int poolMinSize;
- private int poolIdleTimeoutSeconds;
private int poolShutdownTimeoutSeconds;
private int resetEngineTimeoutSeconds;
- private ExecutorService executorService;
public JavetEngineConfig() {
reset();
}
- @SuppressWarnings("UnusedReturnValue")
- public JavetEngineConfig reset() {
- javetLogger = DEFAULT_JAVET_LOGGER;
- globalName = DEFAULT_GLOBAL_NAME;
- allowEval = false;
- autoSendGCNotification = true;
- defaultEngineGuardTimeoutMillis = DEFAULT_ENGINE_GUARD_TIMEOUT_MILLIS;
- engineGuardCheckIntervalMillis = DEFAULT_ENGINE_GUARD_CHECK_INTERVAL_MILLIS;
- gcBeforeEngineClose = false;
- jsRuntimeType = DEFAULT_JS_RUNTIME_TYPE;
- maxEngineUsedCount = DEFAULT_MAX_ENGINE_USED_COUNT;
- final int cpuCount = JavetOSUtils.getCPUCount();
- poolMinSize = Math.max(DEFAULT_POOL_MIN_SIZE, cpuCount >> 1);
- poolMaxSize = Math.max(DEFAULT_POOL_MIN_SIZE, cpuCount);
- poolIdleTimeoutSeconds = DEFAULT_POOL_IDLE_TIMEOUT_SECONDS;
- poolShutdownTimeoutSeconds = DEFAULT_POOL_SHUTDOWN_TIMEOUT_SECONDS;
- poolDaemonCheckIntervalMillis = DEFAULT_POOL_DAEMON_CHECK_INTERVAL_MILLIS;
- resetEngineTimeoutSeconds = DEFAULT_RESET_ENGINE_TIMEOUT_SECONDS;
- return this;
- }
-
- public boolean isGcBeforeEngineClose() {
- return gcBeforeEngineClose;
+ public int getDefaultEngineGuardTimeoutMillis() {
+ return defaultEngineGuardTimeoutMillis;
}
- public JavetEngineConfig setGcBeforeEngineClose(boolean gcBeforeEngineClose) {
- this.gcBeforeEngineClose = gcBeforeEngineClose;
- return this;
+ public int getEngineGuardCheckIntervalMillis() {
+ return engineGuardCheckIntervalMillis;
}
- public boolean isAllowEval() {
- return allowEval;
+ public ExecutorService getExecutorService() {
+ return executorService;
}
- public JavetEngineConfig setAllowEval(boolean allowEval) {
- this.allowEval = allowEval;
- return this;
+ public String getGlobalName() {
+ return globalName;
}
- public boolean isAutoSendGCNotification() {
- return autoSendGCNotification;
+ public JSRuntimeType getJSRuntimeType() {
+ return jsRuntimeType;
}
- public JavetEngineConfig setAutoSendGCNotification(boolean autoSendGCNotification) {
- this.autoSendGCNotification = autoSendGCNotification;
- return this;
+ public IJavetLogger getJavetLogger() {
+ return javetLogger;
}
- public ExecutorService getExecutorService() {
- return executorService;
+ public int getPoolDaemonCheckIntervalMillis() {
+ return poolDaemonCheckIntervalMillis;
}
- @SuppressWarnings("UnusedReturnValue")
- JavetEngineConfig setExecutorService(ExecutorService executorService) {
- this.executorService = executorService;
- return this;
+ public int getPoolIdleTimeoutSeconds() {
+ return poolIdleTimeoutSeconds;
}
- public JSRuntimeType getJSRuntimeType() {
- return jsRuntimeType;
+ public int getPoolMaxSize() {
+ return poolMaxSize;
}
- public JavetEngineConfig setJSRuntimeType(JSRuntimeType jsRuntimeType) {
- Objects.requireNonNull(jsRuntimeType);
- this.jsRuntimeType = jsRuntimeType;
- return this;
+ public int getPoolMinSize() {
+ return poolMinSize;
}
public int getPoolShutdownTimeoutSeconds() {
return poolShutdownTimeoutSeconds;
}
- public JavetEngineConfig setPoolShutdownTimeoutSeconds(int poolShutdownTimeoutSeconds) {
- this.poolShutdownTimeoutSeconds = poolShutdownTimeoutSeconds;
- return this;
+ public int getResetEngineTimeoutSeconds() {
+ return resetEngineTimeoutSeconds;
}
- public int getEngineGuardCheckIntervalMillis() {
- return engineGuardCheckIntervalMillis;
+ public boolean isAllowEval() {
+ return allowEval;
}
- @SuppressWarnings("UnusedReturnValue")
- public JavetEngineConfig setEngineGuardCheckIntervalMillis(int engineGuardCheckIntervalMillis) {
- this.engineGuardCheckIntervalMillis = engineGuardCheckIntervalMillis;
- return this;
+ public boolean isAutoSendGCNotification() {
+ return autoSendGCNotification;
}
- public String getGlobalName() {
- return globalName;
+ public boolean isGcBeforeEngineClose() {
+ return gcBeforeEngineClose;
}
- public JavetEngineConfig setGlobalName(String globalName) {
- this.globalName = globalName;
+ @SuppressWarnings("UnusedReturnValue")
+ public JavetEngineConfig reset() {
+ javetLogger = DEFAULT_JAVET_LOGGER;
+ globalName = DEFAULT_GLOBAL_NAME;
+ allowEval = false;
+ autoSendGCNotification = true;
+ defaultEngineGuardTimeoutMillis = DEFAULT_ENGINE_GUARD_TIMEOUT_MILLIS;
+ engineGuardCheckIntervalMillis = DEFAULT_ENGINE_GUARD_CHECK_INTERVAL_MILLIS;
+ gcBeforeEngineClose = false;
+ jsRuntimeType = DEFAULT_JS_RUNTIME_TYPE;
+ final int cpuCount = JavetOSUtils.getCPUCount();
+ poolMinSize = Math.max(DEFAULT_POOL_MIN_SIZE, cpuCount >> 1);
+ poolMaxSize = Math.max(DEFAULT_POOL_MIN_SIZE, cpuCount);
+ poolIdleTimeoutSeconds = DEFAULT_POOL_IDLE_TIMEOUT_SECONDS;
+ poolShutdownTimeoutSeconds = DEFAULT_POOL_SHUTDOWN_TIMEOUT_SECONDS;
+ poolDaemonCheckIntervalMillis = DEFAULT_POOL_DAEMON_CHECK_INTERVAL_MILLIS;
+ resetEngineTimeoutSeconds = DEFAULT_RESET_ENGINE_TIMEOUT_SECONDS;
return this;
}
- public int getDefaultEngineGuardTimeoutMillis() {
- return defaultEngineGuardTimeoutMillis;
+ public JavetEngineConfig setAllowEval(boolean allowEval) {
+ this.allowEval = allowEval;
+ return this;
+ }
+
+ public JavetEngineConfig setAutoSendGCNotification(boolean autoSendGCNotification) {
+ this.autoSendGCNotification = autoSendGCNotification;
+ return this;
}
public JavetEngineConfig setDefaultEngineGuardTimeoutMillis(int defaultEngineGuardTimeoutMillis) {
@@ -163,26 +151,32 @@ public JavetEngineConfig setDefaultEngineGuardTimeoutMillis(int defaultEngineGua
return this;
}
- public int getResetEngineTimeoutSeconds() {
- return resetEngineTimeoutSeconds;
+ @SuppressWarnings("UnusedReturnValue")
+ public JavetEngineConfig setEngineGuardCheckIntervalMillis(int engineGuardCheckIntervalMillis) {
+ this.engineGuardCheckIntervalMillis = engineGuardCheckIntervalMillis;
+ return this;
}
- public JavetEngineConfig setResetEngineTimeoutSeconds(int resetEngineTimeoutSeconds) {
- this.resetEngineTimeoutSeconds = resetEngineTimeoutSeconds;
+ @SuppressWarnings("UnusedReturnValue")
+ JavetEngineConfig setExecutorService(ExecutorService executorService) {
+ this.executorService = executorService;
return this;
}
- public int getMaxEngineUsedCount() {
- return maxEngineUsedCount;
+ public JavetEngineConfig setGcBeforeEngineClose(boolean gcBeforeEngineClose) {
+ this.gcBeforeEngineClose = gcBeforeEngineClose;
+ return this;
}
- public JavetEngineConfig setMaxEngineUsedCount(int maxEngineUsedCount) {
- this.maxEngineUsedCount = maxEngineUsedCount;
+ public JavetEngineConfig setGlobalName(String globalName) {
+ this.globalName = globalName;
return this;
}
- public IJavetLogger getJavetLogger() {
- return javetLogger;
+ public JavetEngineConfig setJSRuntimeType(JSRuntimeType jsRuntimeType) {
+ Objects.requireNonNull(jsRuntimeType);
+ this.jsRuntimeType = jsRuntimeType;
+ return this;
}
public JavetEngineConfig setJavetLogger(IJavetLogger javetLogger) {
@@ -191,17 +185,20 @@ public JavetEngineConfig setJavetLogger(IJavetLogger javetLogger) {
return this;
}
- public int getPoolMaxSize() {
- return poolMaxSize;
+ @SuppressWarnings("UnusedReturnValue")
+ public JavetEngineConfig setPoolDaemonCheckIntervalMillis(int poolDaemonCheckIntervalMillis) {
+ this.poolDaemonCheckIntervalMillis = poolDaemonCheckIntervalMillis;
+ return this;
}
- public JavetEngineConfig setPoolMaxSize(int poolMaxSize) {
- this.poolMaxSize = poolMaxSize;
+ public JavetEngineConfig setPoolIdleTimeoutSeconds(int poolIdleTimeoutSeconds) {
+ this.poolIdleTimeoutSeconds = poolIdleTimeoutSeconds;
return this;
}
- public int getPoolMinSize() {
- return poolMinSize;
+ public JavetEngineConfig setPoolMaxSize(int poolMaxSize) {
+ this.poolMaxSize = poolMaxSize;
+ return this;
}
public JavetEngineConfig setPoolMinSize(int poolMinSize) {
@@ -209,22 +206,13 @@ public JavetEngineConfig setPoolMinSize(int poolMinSize) {
return this;
}
- public int getPoolIdleTimeoutSeconds() {
- return poolIdleTimeoutSeconds;
- }
-
- public JavetEngineConfig setPoolIdleTimeoutSeconds(int poolIdleTimeoutSeconds) {
- this.poolIdleTimeoutSeconds = poolIdleTimeoutSeconds;
+ public JavetEngineConfig setPoolShutdownTimeoutSeconds(int poolShutdownTimeoutSeconds) {
+ this.poolShutdownTimeoutSeconds = poolShutdownTimeoutSeconds;
return this;
}
- public int getPoolDaemonCheckIntervalMillis() {
- return poolDaemonCheckIntervalMillis;
- }
-
- @SuppressWarnings("UnusedReturnValue")
- public JavetEngineConfig setPoolDaemonCheckIntervalMillis(int poolDaemonCheckIntervalMillis) {
- this.poolDaemonCheckIntervalMillis = poolDaemonCheckIntervalMillis;
+ public JavetEngineConfig setResetEngineTimeoutSeconds(int resetEngineTimeoutSeconds) {
+ this.resetEngineTimeoutSeconds = resetEngineTimeoutSeconds;
return this;
}
}
diff --git a/src/main/java/com/caoccao/javet/interop/engine/JavetEngineGuard.java b/src/main/java/com/caoccao/javet/interop/engine/JavetEngineGuard.java
index 6636b7203..fcd7a487f 100644
--- a/src/main/java/com/caoccao/javet/interop/engine/JavetEngineGuard.java
+++ b/src/main/java/com/caoccao/javet/interop/engine/JavetEngineGuard.java
@@ -78,19 +78,14 @@ public long getTimeoutMillis() {
return timeoutMillis;
}
- @Override
- public void setTimeoutMillis(long timeoutSeconds) {
- this.timeoutMillis = timeoutSeconds;
+ protected ZonedDateTime getUTCNow() {
+ return JavetDateTimeUtils.getUTCNow();
}
public boolean isQuitting() {
return quitting;
}
- protected ZonedDateTime getUTCNow() {
- return JavetDateTimeUtils.getUTCNow();
- }
-
@Override
public void run() {
JavetEngineConfig config = iJavetEngine.getConfig();
@@ -125,4 +120,9 @@ public void run() {
}
quitting = true;
}
+
+ @Override
+ public void setTimeoutMillis(long timeoutSeconds) {
+ this.timeoutMillis = timeoutSeconds;
+ }
}
diff --git a/src/main/java/com/caoccao/javet/interop/engine/JavetEnginePool.java b/src/main/java/com/caoccao/javet/interop/engine/JavetEnginePool.java
index 06f4d1a23..07d6f8787 100644
--- a/src/main/java/com/caoccao/javet/interop/engine/JavetEnginePool.java
+++ b/src/main/java/com/caoccao/javet/interop/engine/JavetEnginePool.java
@@ -32,12 +32,12 @@
public class JavetEnginePool implements IJavetEnginePool, Runnable {
protected static final String JAVET_DAEMON_THREAD_NAME = "Javet Daemon";
+ protected final ConcurrentLinkedQueue> activeEngineList;
protected final Object externalLock;
+ protected final ConcurrentLinkedQueue> idleEngineList;
+ protected boolean active;
protected JavetEngineConfig config;
- protected ConcurrentLinkedQueue> activeEngineList;
protected Thread daemonThread;
- protected ConcurrentLinkedQueue> idleEngineList;
- protected boolean active;
protected boolean quitting;
public JavetEnginePool() {
@@ -55,6 +55,11 @@ public JavetEnginePool(JavetEngineConfig config) {
startDaemon();
}
+ @Override
+ public void close() throws JavetException {
+ stopDaemon();
+ }
+
protected JavetEngine createEngine() throws JavetException {
V8Host v8Host = V8Host.getInstance(config.getJSRuntimeType());
@SuppressWarnings("ConstantConditions")
@@ -64,11 +69,6 @@ protected JavetEngine createEngine() throws JavetException {
return new JavetEngine<>(this, v8Runtime);
}
- @Override
- public void close() throws JavetException {
- stopDaemon();
- }
-
@Override
public int getActiveEngineCount() {
return activeEngineList.size();
@@ -150,24 +150,7 @@ public void run() {
if (engine.isActive()) {
activeEngineList.add(engine);
} else {
- boolean autoSendGCNotification = config.isAutoSendGCNotification();
- if (config.getMaxEngineUsedCount() > 0) {
- JavetEngineUsage usage = engine.getUsage();
- ZonedDateTime resetEngineZonedDateTime = usage.getLastActiveZonedDatetime()
- .plus(config.getResetEngineTimeoutSeconds(), ChronoUnit.SECONDS);
- if (usage.getEngineUsedCount() >= config.getMaxEngineUsedCount() ||
- resetEngineZonedDateTime.isBefore(getUTCNow())) {
- try {
- logger.debug("JavetEnginePool reset engine begins.");
- engine.resetContext();
- autoSendGCNotification = false;
- logger.debug("JavetEnginePool reset engine ends.");
- } catch (Exception e) {
- logger.logError(e, "Failed to reset idle engine.");
- }
- }
- }
- if (autoSendGCNotification) {
+ if (config.isAutoSendGCNotification()) {
engine.sendGCNotification();
}
idleEngineList.add(engine);
@@ -175,6 +158,7 @@ public void run() {
}
final int idleEngineCount = getIdleEngineCount();
for (int i = config.getPoolMinSize(); i < idleEngineCount; ++i) {
+ final int immediateIdleEngineCount = getIdleEngineCount();
JavetEngine engine = idleEngineList.poll();
if (engine == null) {
break;
@@ -182,13 +166,26 @@ public void run() {
JavetEngineUsage usage = engine.getUsage();
ZonedDateTime expirationZonedDateTime = usage.getLastActiveZonedDatetime()
.plus(config.getPoolIdleTimeoutSeconds(), ChronoUnit.SECONDS);
- if (getIdleEngineCount() > config.getPoolMaxSize() || expirationZonedDateTime.isBefore(getUTCNow())) {
+ if (immediateIdleEngineCount > config.getPoolMaxSize() || expirationZonedDateTime.isBefore(getUTCNow())) {
try {
engine.close(true);
} catch (Throwable t) {
logger.logError(t, "Failed to release idle engine.");
}
} else {
+ if (config.getResetEngineTimeoutSeconds() > 0) {
+ ZonedDateTime resetEngineZonedDateTime = usage.getLastActiveZonedDatetime()
+ .plus(config.getResetEngineTimeoutSeconds(), ChronoUnit.SECONDS);
+ if (resetEngineZonedDateTime.isBefore(getUTCNow())) {
+ try {
+ logger.debug("JavetEnginePool reset engine begins.");
+ engine.resetContext();
+ logger.debug("JavetEnginePool reset engine ends.");
+ } catch (Exception e) {
+ logger.logError(e, "Failed to reset idle engine.");
+ }
+ }
+ }
idleEngineList.add(engine);
}
}
diff --git a/src/main/java/com/caoccao/javet/interop/engine/JavetEngineUsage.java b/src/main/java/com/caoccao/javet/interop/engine/JavetEngineUsage.java
index fc21b23f2..e24827d9e 100644
--- a/src/main/java/com/caoccao/javet/interop/engine/JavetEngineUsage.java
+++ b/src/main/java/com/caoccao/javet/interop/engine/JavetEngineUsage.java
@@ -27,18 +27,14 @@ public JavetEngineUsage() {
reset();
}
- public ZonedDateTime getLastActiveZonedDatetime() {
- return lastActiveZonedDatetime;
- }
-
- public void setLastActiveZonedDatetime(ZonedDateTime lastActiveZonedDatetime) {
- this.lastActiveZonedDatetime = lastActiveZonedDatetime;
- }
-
public int getEngineUsedCount() {
return engineUsedCount;
}
+ public ZonedDateTime getLastActiveZonedDatetime() {
+ return lastActiveZonedDatetime;
+ }
+
public void increaseUsedCount() {
++engineUsedCount;
}
@@ -46,4 +42,8 @@ public void increaseUsedCount() {
protected void reset() {
engineUsedCount = 0;
}
+
+ public void setLastActiveZonedDatetime(ZonedDateTime lastActiveZonedDatetime) {
+ this.lastActiveZonedDatetime = lastActiveZonedDatetime;
+ }
}
diff --git a/src/main/java/com/caoccao/javet/interop/executors/IV8Executor.java b/src/main/java/com/caoccao/javet/interop/executors/IV8Executor.java
index 143073989..b883b57a3 100644
--- a/src/main/java/com/caoccao/javet/interop/executors/IV8Executor.java
+++ b/src/main/java/com/caoccao/javet/interop/executors/IV8Executor.java
@@ -63,6 +63,21 @@ default String getResourceName() {
return getV8ScriptOrigin().getResourceName();
}
+ String getScriptString() throws JavetException;
+
+ V8Runtime getV8Runtime();
+
+ V8ScriptOrigin getV8ScriptOrigin();
+
+ default boolean isModule() {
+ return getV8ScriptOrigin().isModule();
+ }
+
+ default IV8Executor setModule(boolean module) {
+ getV8ScriptOrigin().setModule(module);
+ return this;
+ }
+
default IV8Executor setResourceName(String resourceName) throws JavetException {
getV8ScriptOrigin().setResourceName(resourceName);
V8Runtime v8Runtime = getV8Runtime();
@@ -77,21 +92,6 @@ default IV8Executor setResourceName(String resourceName) throws JavetException {
return this;
}
- default boolean isModule() {
- return getV8ScriptOrigin().isModule();
- }
-
- default IV8Executor setModule(boolean module) {
- getV8ScriptOrigin().setModule(module);
- return this;
- }
-
- String getScriptString() throws JavetException;
-
- V8Runtime getV8Runtime();
-
- V8ScriptOrigin getV8ScriptOrigin();
-
@Override
default T toObject(V v8Value) throws JavetException {
return getV8Runtime().toObject(v8Value);
diff --git a/src/main/java/com/caoccao/javet/interop/executors/V8PathExecutor.java b/src/main/java/com/caoccao/javet/interop/executors/V8PathExecutor.java
index 5e13535ba..907ff8e59 100644
--- a/src/main/java/com/caoccao/javet/interop/executors/V8PathExecutor.java
+++ b/src/main/java/com/caoccao/javet/interop/executors/V8PathExecutor.java
@@ -36,6 +36,10 @@ public V8PathExecutor(V8Runtime v8Runtime, Path scriptPath) throws JavetExceptio
setResourceName(scriptPath.toFile().getAbsolutePath());
}
+ public Path getScriptPath() {
+ return scriptPath;
+ }
+
@Override
public String getScriptString() throws JavetException {
if (scriptString == null) {
@@ -50,8 +54,4 @@ public String getScriptString() throws JavetException {
}
return scriptString;
}
-
- public Path getScriptPath() {
- return scriptPath;
- }
}
diff --git a/src/main/java/com/caoccao/javet/interop/executors/V8StringExecutor.java b/src/main/java/com/caoccao/javet/interop/executors/V8StringExecutor.java
index 90ace05e0..92ac60f05 100644
--- a/src/main/java/com/caoccao/javet/interop/executors/V8StringExecutor.java
+++ b/src/main/java/com/caoccao/javet/interop/executors/V8StringExecutor.java
@@ -48,14 +48,14 @@ public V8Module compileV8Module(boolean resultRequired) throws JavetException {
return v8Runtime.compileV8Module(getScriptString(), v8ScriptOrigin, resultRequired);
}
- @Override
- public String getScriptString() throws JavetException {
- return scriptString;
- }
-
@Override
@CheckReturnValue
public T execute(boolean resultRequired) throws JavetException {
return v8Runtime.execute(getScriptString(), v8ScriptOrigin, resultRequired);
}
+
+ @Override
+ public String getScriptString() throws JavetException {
+ return scriptString;
+ }
}
diff --git a/src/main/java/com/caoccao/javet/node/modules/NodeModuleProcess.java b/src/main/java/com/caoccao/javet/node/modules/NodeModuleProcess.java
index 8c12443c7..ffb331a63 100644
--- a/src/main/java/com/caoccao/javet/node/modules/NodeModuleProcess.java
+++ b/src/main/java/com/caoccao/javet/node/modules/NodeModuleProcess.java
@@ -40,11 +40,11 @@ public Path getWorkingDirectory() throws JavetException {
return new File(moduleObject.invokeString(FUNCTION_CWD)).toPath();
}
- public void setWorkingDirectory(Path path) throws JavetException {
- moduleObject.invokeVoid(FUNCTION_CHDIR, new V8ValueString(path.toAbsolutePath().toString()));
- }
-
public void on(String eventName, V8ValueFunction v8ValueFunction) throws JavetException {
moduleObject.invokeVoid(FUNCTION_ON, new V8ValueString(eventName), v8ValueFunction);
}
+
+ public void setWorkingDirectory(Path path) throws JavetException {
+ moduleObject.invokeVoid(FUNCTION_CHDIR, new V8ValueString(path.toAbsolutePath().toString()));
+ }
}
diff --git a/src/main/java/com/caoccao/javet/utils/JavetCallbackContext.java b/src/main/java/com/caoccao/javet/utils/JavetCallbackContext.java
index cfaf4249c..f3e16a4d3 100644
--- a/src/main/java/com/caoccao/javet/utils/JavetCallbackContext.java
+++ b/src/main/java/com/caoccao/javet/utils/JavetCallbackContext.java
@@ -28,9 +28,9 @@ public final class JavetCallbackContext {
"Javet callback context handle is invalid";
private final Method callbackMethod;
private final Object callbackReceiver;
- private long handle;
private final boolean returnResult;
private final boolean thisObjectRequired;
+ private long handle;
public JavetCallbackContext(
Object callbackReceiver,
@@ -53,28 +53,28 @@ public JavetCallbackContext(
this.thisObjectRequired = thisObjectRequired;
}
- public boolean isThisObjectRequired() {
- return thisObjectRequired;
+ public Method getCallbackMethod() {
+ return callbackMethod;
}
public Object getCallbackReceiver() {
return callbackReceiver;
}
- public Method getCallbackMethod() {
- return callbackMethod;
- }
-
public long getHandle() {
return handle;
}
+ public boolean isReturnResult() {
+ return returnResult;
+ }
+
+ public boolean isThisObjectRequired() {
+ return thisObjectRequired;
+ }
+
public void setHandle(long handle) {
assert handle > 0L : ERROR_JAVET_CALLBACK_CONTEXT_HANDLE_IS_INVALID;
this.handle = handle;
}
-
- public boolean isReturnResult() {
- return returnResult;
- }
}
diff --git a/src/main/java/com/caoccao/javet/utils/JavetDateTimeUtils.java b/src/main/java/com/caoccao/javet/utils/JavetDateTimeUtils.java
index f28c61bd0..6ff72e2d0 100644
--- a/src/main/java/com/caoccao/javet/utils/JavetDateTimeUtils.java
+++ b/src/main/java/com/caoccao/javet/utils/JavetDateTimeUtils.java
@@ -26,21 +26,21 @@
*/
public final class JavetDateTimeUtils {
+ /**
+ * The constant ZONE_ID_UTC.
+ */
public static final ZoneId ZONE_ID_UTC = ZoneId.of("UTC");
private JavetDateTimeUtils() {
}
/**
- * From JS timestamp to zoned date time.
- *
- * Note: the ZoneId needs to be system default because that's what V8 sees.
+ * Gets utc now.
*
- * @param jsTimestamp the JS timestamp
- * @return the zoned date time
+ * @return the utc now
*/
- public static ZonedDateTime toZonedDateTime(long jsTimestamp) {
- return toZonedDateTime(jsTimestamp, ZoneId.systemDefault());
+ public static ZonedDateTime getUTCNow() {
+ return ZonedDateTime.now(ZONE_ID_UTC);
}
/**
@@ -54,7 +54,15 @@ public static ZonedDateTime toZonedDateTime(long jsTimestamp, ZoneId zoneId) {
return ZonedDateTime.ofInstant(Instant.ofEpochMilli(jsTimestamp), zoneId);
}
- public static ZonedDateTime getUTCNow() {
- return ZonedDateTime.now(ZONE_ID_UTC);
+ /**
+ * From JS timestamp to zoned date time.
+ *
+ * Note: the ZoneId needs to be system default because that's what V8 sees.
+ *
+ * @param jsTimestamp the JS timestamp
+ * @return the zoned date time
+ */
+ public static ZonedDateTime toZonedDateTime(long jsTimestamp) {
+ return toZonedDateTime(jsTimestamp, ZoneId.systemDefault());
}
}
diff --git a/src/main/java/com/caoccao/javet/utils/JavetDefaultLogger.java b/src/main/java/com/caoccao/javet/utils/JavetDefaultLogger.java
index 393bf29a1..145737f62 100644
--- a/src/main/java/com/caoccao/javet/utils/JavetDefaultLogger.java
+++ b/src/main/java/com/caoccao/javet/utils/JavetDefaultLogger.java
@@ -35,14 +35,6 @@ public JavetDefaultLogger(String name) {
this.name = name;
}
- public String getName() {
- return name;
- }
-
- public Logger getLogger() {
- return logger;
- }
-
@Override
public void debug(String message) {
logger.log(Level.FINE, message);
@@ -65,6 +57,14 @@ public void error(String message, Throwable cause) {
}
}
+ public Logger getLogger() {
+ return logger;
+ }
+
+ public String getName() {
+ return name;
+ }
+
@Override
public void info(String message) {
logger.info(message);
diff --git a/src/main/java/com/caoccao/javet/utils/JavetOSUtils.java b/src/main/java/com/caoccao/javet/utils/JavetOSUtils.java
index 1d0b0c24e..ce4893c75 100644
--- a/src/main/java/com/caoccao/javet/utils/JavetOSUtils.java
+++ b/src/main/java/com/caoccao/javet/utils/JavetOSUtils.java
@@ -25,7 +25,8 @@ public final class JavetOSUtils {
public static final String TEMP_DIRECTORY = System.getProperty("java.io.tmpdir");
public static final String WORKING_DIRECTORY = System.getProperty("user.dir");
- private JavetOSUtils() {}
+ private JavetOSUtils() {
+ }
public static int getCPUCount() {
return Runtime.getRuntime().availableProcessors();
diff --git a/src/main/java/com/caoccao/javet/utils/SimpleFreeMarkerFormat.java b/src/main/java/com/caoccao/javet/utils/SimpleFreeMarkerFormat.java
index f8acb2124..09c1bc060 100644
--- a/src/main/java/com/caoccao/javet/utils/SimpleFreeMarkerFormat.java
+++ b/src/main/java/com/caoccao/javet/utils/SimpleFreeMarkerFormat.java
@@ -23,8 +23,8 @@ public final class SimpleFreeMarkerFormat {
public static final String STRING_NULL = "";
private static final char CHAR_DOLLAR = '$';
- private static final char CHAR_VARIABLE_OPEN = '{';
private static final char CHAR_VARIABLE_CLOSE = '}';
+ private static final char CHAR_VARIABLE_OPEN = '{';
public static String format(final String format, final Map parameters) {
if (format == null || format.length() == 0 || parameters == null || parameters.isEmpty()) {
diff --git a/src/main/java/com/caoccao/javet/utils/receivers/JavetCallbackReceiver.java b/src/main/java/com/caoccao/javet/utils/receivers/JavetCallbackReceiver.java
index 8743a8d93..6a89146c3 100644
--- a/src/main/java/com/caoccao/javet/utils/receivers/JavetCallbackReceiver.java
+++ b/src/main/java/com/caoccao/javet/utils/receivers/JavetCallbackReceiver.java
@@ -49,11 +49,6 @@ public JavetCallbackReceiver(V8Runtime v8Runtime) {
this.v8Runtime = v8Runtime;
}
- @Override
- public V8Runtime getV8Runtime() {
- return v8Runtime;
- }
-
/**
* Echo the given V8 value.
*
@@ -121,4 +116,9 @@ public String echoString(V8Value... args) {
}
return String.join(COMMA, stringList);
}
+
+ @Override
+ public V8Runtime getV8Runtime() {
+ return v8Runtime;
+ }
}
diff --git a/src/main/java/com/caoccao/javet/values/IV8Value.java b/src/main/java/com/caoccao/javet/values/IV8Value.java
index b7dfd9e98..71fa65c8b 100644
--- a/src/main/java/com/caoccao/javet/values/IV8Value.java
+++ b/src/main/java/com/caoccao/javet/values/IV8Value.java
@@ -28,13 +28,6 @@
* The interface V8 value.
*/
public interface IV8Value extends IJavetClosable, IV8Cloneable {
- /**
- * Gets V8 runtime.
- *
- * @return the V8 runtime
- */
- V8Runtime getV8Runtime();
-
/**
* Equals.
*
@@ -46,6 +39,13 @@ public interface IV8Value extends IJavetClosable, IV8Cloneable {
*/
boolean equals(V8Value v8Value) throws JavetException;
+ /**
+ * Gets V8 runtime.
+ *
+ * @return the V8 runtime
+ */
+ V8Runtime getV8Runtime();
+
/**
* Is null.
*
diff --git a/src/main/java/com/caoccao/javet/values/V8Value.java b/src/main/java/com/caoccao/javet/values/V8Value.java
index d01d15c9e..c31583f1c 100644
--- a/src/main/java/com/caoccao/javet/values/V8Value.java
+++ b/src/main/java/com/caoccao/javet/values/V8Value.java
@@ -43,14 +43,13 @@ protected void checkV8Runtime() throws JavetException {
@Override
public abstract boolean equals(V8Value v8Value) throws JavetException;
- @Override
- @CheckReturnValue
- public abstract T toClone() throws JavetException;
-
public V8Runtime getV8Runtime() {
return v8Runtime;
}
+ @Override
+ public abstract boolean sameValue(V8Value v8Value) throws JavetException;
+
public void setV8Runtime(V8Runtime v8Runtime) throws JavetException {
Objects.requireNonNull(v8Runtime);
if (this.v8Runtime != null) {
@@ -60,8 +59,9 @@ public void setV8Runtime(V8Runtime v8Runtime) throws JavetException {
}
@Override
- public abstract boolean sameValue(V8Value v8Value) throws JavetException;
+ public abstract boolean strictEquals(V8Value v8Value) throws JavetException;
@Override
- public abstract boolean strictEquals(V8Value v8Value) throws JavetException;
+ @CheckReturnValue
+ public abstract T toClone() throws JavetException;
}
diff --git a/src/main/java/com/caoccao/javet/values/reference/IV8Module.java b/src/main/java/com/caoccao/javet/values/reference/IV8Module.java
index 07a671329..fe42fa58c 100644
--- a/src/main/java/com/caoccao/javet/values/reference/IV8Module.java
+++ b/src/main/java/com/caoccao/javet/values/reference/IV8Module.java
@@ -58,8 +58,6 @@ default T execute(boolean resultRequired) throws JavetExcept
String getResourceName();
- void setResourceName(String resourceName);
-
/**
* Gets script id.
*
@@ -74,6 +72,8 @@ default T execute(boolean resultRequired) throws JavetExcept
boolean instantiate() throws JavetException;
+ void setResourceName(String resourceName);
+
@Override
default T toObject(V v8Value) throws JavetException {
return getV8Runtime().toObject(v8Value);
diff --git a/src/main/java/com/caoccao/javet/values/reference/IV8ValueObject.java b/src/main/java/com/caoccao/javet/values/reference/IV8ValueObject.java
index 00bbda07b..5bbba3de9 100644
--- a/src/main/java/com/caoccao/javet/values/reference/IV8ValueObject.java
+++ b/src/main/java/com/caoccao/javet/values/reference/IV8ValueObject.java
@@ -560,6 +560,18 @@ default Boolean invokeBoolean(String functionName, Object... objects) throws Jav
return invokePrimitive(functionName, objects);
}
+ /**
+ * Invoke double double.
+ *
+ * @param functionName the function name
+ * @param objects the objects
+ * @return the double
+ * @throws JavetException the javet exception
+ */
+ default Double invokeDouble(String functionName, Object... objects) throws JavetException {
+ return invokePrimitive(functionName, objects);
+ }
+
/**
* Invoke extended and return V8 value which must be consumed,
* otherwise memory leak may occur.
@@ -588,18 +600,6 @@ default Boolean invokeBoolean(String functionName, Object... objects) throws Jav
@CheckReturnValue
T invokeExtended(String functionName, boolean returnResult, V8Value... v8Values) throws JavetException;
- /**
- * Invoke double double.
- *
- * @param functionName the function name
- * @param objects the objects
- * @return the double
- * @throws JavetException the javet exception
- */
- default Double invokeDouble(String functionName, Object... objects) throws JavetException {
- return invokePrimitive(functionName, objects);
- }
-
/**
* Invoke float float.
*
diff --git a/src/main/java/com/caoccao/javet/values/reference/V8Module.java b/src/main/java/com/caoccao/javet/values/reference/V8Module.java
index e38f9cc96..4872b2e1b 100644
--- a/src/main/java/com/caoccao/javet/values/reference/V8Module.java
+++ b/src/main/java/com/caoccao/javet/values/reference/V8Module.java
@@ -66,11 +66,6 @@ public String getResourceName() {
return resourceName;
}
- public void setResourceName(String resourceName) {
- Objects.requireNonNull(resourceName);
- this.resourceName = resourceName;
- }
-
@Override
public int getScriptId() throws JavetException {
checkV8Runtime();
@@ -94,6 +89,11 @@ public boolean instantiate() throws JavetException {
return v8Runtime.moduleInstantiate(this);
}
+ public void setResourceName(String resourceName) {
+ Objects.requireNonNull(resourceName);
+ this.resourceName = resourceName;
+ }
+
@Override
@CheckReturnValue
public V8Module toClone() throws JavetException {
diff --git a/src/main/java/com/caoccao/javet/values/reference/V8Script.java b/src/main/java/com/caoccao/javet/values/reference/V8Script.java
index 72f5c5b35..2441d219b 100644
--- a/src/main/java/com/caoccao/javet/values/reference/V8Script.java
+++ b/src/main/java/com/caoccao/javet/values/reference/V8Script.java
@@ -18,9 +18,9 @@
package com.caoccao.javet.values.reference;
import com.caoccao.javet.annotations.CheckReturnValue;
+import com.caoccao.javet.enums.V8ValueReferenceType;
import com.caoccao.javet.exceptions.JavetException;
import com.caoccao.javet.values.V8Value;
-import com.caoccao.javet.enums.V8ValueReferenceType;
import java.util.Objects;
@@ -44,16 +44,16 @@ public String getResourceName() {
return resourceName;
}
- public void setResourceName(String resourceName) {
- Objects.requireNonNull(resourceName);
- this.resourceName = resourceName;
- }
-
@Override
public V8ValueReferenceType getType() {
return V8ValueReferenceType.Script;
}
+ public void setResourceName(String resourceName) {
+ Objects.requireNonNull(resourceName);
+ this.resourceName = resourceName;
+ }
+
@Override
public V8Script toClone() throws JavetException {
return this;
diff --git a/src/main/java/com/caoccao/javet/values/reference/V8ValueArray.java b/src/main/java/com/caoccao/javet/values/reference/V8ValueArray.java
index c6734e8ae..c986ad73b 100644
--- a/src/main/java/com/caoccao/javet/values/reference/V8ValueArray.java
+++ b/src/main/java/com/caoccao/javet/values/reference/V8ValueArray.java
@@ -29,8 +29,8 @@
import java.util.Objects;
public class V8ValueArray extends V8ValueObject implements IV8ValueArray {
- protected static final String FUNCTION_NEXT = "next";
protected static final String FUNCTION_KEYS = "keys";
+ protected static final String FUNCTION_NEXT = "next";
protected static final String FUNCTION_POP = "pop";
protected static final String FUNCTION_PUSH = "push";
protected static final String PROPERTY_DONE = "done";
diff --git a/src/main/java/com/caoccao/javet/values/reference/V8ValueArrayBuffer.java b/src/main/java/com/caoccao/javet/values/reference/V8ValueArrayBuffer.java
index 516eedcac..c85b548c5 100644
--- a/src/main/java/com/caoccao/javet/values/reference/V8ValueArrayBuffer.java
+++ b/src/main/java/com/caoccao/javet/values/reference/V8ValueArrayBuffer.java
@@ -17,19 +17,18 @@
package com.caoccao.javet.values.reference;
-import com.caoccao.javet.exceptions.JavetException;
import com.caoccao.javet.enums.V8ValueReferenceType;
+import com.caoccao.javet.exceptions.JavetException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Objects;
public class V8ValueArrayBuffer extends V8ValueObject {
- protected static final String PROPERTY_BYTE_LENGTH = "byteLength";
protected static final int BYTE_LENGTH_1 = 1;
protected static final int BYTE_LENGTH_2 = 2;
protected static final int BYTE_LENGTH_3 = 3;
-
+ protected static final String PROPERTY_BYTE_LENGTH = "byteLength";
protected ByteBuffer byteBuffer;
protected ByteOrder byteOrder;
@@ -39,28 +38,6 @@ public class V8ValueArrayBuffer extends V8ValueObject {
byteOrder = ByteOrder.nativeOrder();
}
- public ByteOrder getByteOrder() {
- return byteOrder;
- }
-
- public void setByteOrder(ByteOrder byteOrder) {
- Objects.requireNonNull(byteOrder);
- this.byteOrder = byteOrder;
- }
-
- public ByteBuffer getByteBuffer() {
- return byteBuffer;
- }
-
- public int getByteLength() throws JavetException {
- return getInteger(PROPERTY_BYTE_LENGTH);
- }
-
- @Override
- public V8ValueReferenceType getType() {
- return V8ValueReferenceType.ArrayBuffer;
- }
-
public boolean fromBytes(byte[] bytes) {
if (bytes != null && bytes.length > 0 && bytes.length == byteBuffer.capacity()) {
byteBuffer.put(bytes);
@@ -109,6 +86,28 @@ public boolean fromShorts(short[] shorts) {
return false;
}
+ public ByteBuffer getByteBuffer() {
+ return byteBuffer;
+ }
+
+ public int getByteLength() throws JavetException {
+ return getInteger(PROPERTY_BYTE_LENGTH);
+ }
+
+ public ByteOrder getByteOrder() {
+ return byteOrder;
+ }
+
+ @Override
+ public V8ValueReferenceType getType() {
+ return V8ValueReferenceType.ArrayBuffer;
+ }
+
+ public void setByteOrder(ByteOrder byteOrder) {
+ Objects.requireNonNull(byteOrder);
+ this.byteOrder = byteOrder;
+ }
+
public byte[] toBytes() {
byte[] bytes = new byte[byteBuffer.capacity()];
byteBuffer.get(bytes);
diff --git a/src/main/java/com/caoccao/javet/values/reference/V8ValueDataView.java b/src/main/java/com/caoccao/javet/values/reference/V8ValueDataView.java
index 4876cfb18..d50c10505 100644
--- a/src/main/java/com/caoccao/javet/values/reference/V8ValueDataView.java
+++ b/src/main/java/com/caoccao/javet/values/reference/V8ValueDataView.java
@@ -21,30 +21,30 @@
import com.caoccao.javet.exceptions.JavetException;
public class V8ValueDataView extends V8ValueObject {
- /**
- * The constant PROPERTY_BYTE_LENGTH.
- */
- protected static final String PROPERTY_BYTE_LENGTH = "byteLength";
- /**
- * The constant PROPERTY_BUFFER.
- */
- protected static final String PROPERTY_BUFFER = "buffer";
- /**
- * The constant PROPERTY_BYTE_OFFSET.
- */
- protected static final String PROPERTY_BYTE_OFFSET = "byteOffset";
protected static final String FUNCTION_GET_BIG_INT_64 = "getBigInt64";
protected static final String FUNCTION_GET_FLOAT_32 = "getFloat32";
protected static final String FUNCTION_GET_FLOAT_64 = "getFloat64";
- protected static final String FUNCTION_GET_INT_8 = "getInt8";
protected static final String FUNCTION_GET_INT_16 = "getInt16";
protected static final String FUNCTION_GET_INT_32 = "getInt32";
+ protected static final String FUNCTION_GET_INT_8 = "getInt8";
protected static final String FUNCTION_SET_BIG_INT_64 = "setBigInt64";
protected static final String FUNCTION_SET_FLOAT_32 = "setFloat32";
protected static final String FUNCTION_SET_FLOAT_64 = "setFloat64";
- protected static final String FUNCTION_SET_INT_8 = "setInt8";
protected static final String FUNCTION_SET_INT_16 = "setInt16";
protected static final String FUNCTION_SET_INT_32 = "setInt32";
+ protected static final String FUNCTION_SET_INT_8 = "setInt8";
+ /**
+ * The constant PROPERTY_BUFFER.
+ */
+ protected static final String PROPERTY_BUFFER = "buffer";
+ /**
+ * The constant PROPERTY_BYTE_LENGTH.
+ */
+ protected static final String PROPERTY_BYTE_LENGTH = "byteLength";
+ /**
+ * The constant PROPERTY_BYTE_OFFSET.
+ */
+ protected static final String PROPERTY_BYTE_OFFSET = "byteOffset";
V8ValueDataView(long handle) {
super(handle);
@@ -135,14 +135,6 @@ public void setFloat64(int byteOffset, double value, boolean littleEndian) throw
invokeVoid(FUNCTION_SET_FLOAT_64, byteOffset, value, littleEndian);
}
- public void setInt32(int byteOffset, int value) throws JavetException {
- setInt32(byteOffset, value, true);
- }
-
- public void setInt32(int byteOffset, int value, boolean littleEndian) throws JavetException {
- invokeVoid(FUNCTION_SET_INT_32, byteOffset, value, littleEndian);
- }
-
public void setInt16(int byteOffset, short value) throws JavetException {
setInt16(byteOffset, value, true);
}
@@ -151,6 +143,14 @@ public void setInt16(int byteOffset, short value, boolean littleEndian) throws J
invokeVoid(FUNCTION_SET_INT_16, byteOffset, value, littleEndian);
}
+ public void setInt32(int byteOffset, int value) throws JavetException {
+ setInt32(byteOffset, value, true);
+ }
+
+ public void setInt32(int byteOffset, int value, boolean littleEndian) throws JavetException {
+ invokeVoid(FUNCTION_SET_INT_32, byteOffset, value, littleEndian);
+ }
+
public void setInt8(int byteOffset, byte value) throws JavetException {
invokeVoid(FUNCTION_SET_INT_8, byteOffset, value);
}
diff --git a/src/main/java/com/caoccao/javet/values/reference/V8ValueError.java b/src/main/java/com/caoccao/javet/values/reference/V8ValueError.java
index 7393ac70a..031c1a7d8 100644
--- a/src/main/java/com/caoccao/javet/values/reference/V8ValueError.java
+++ b/src/main/java/com/caoccao/javet/values/reference/V8ValueError.java
@@ -17,22 +17,17 @@
package com.caoccao.javet.values.reference;
-import com.caoccao.javet.exceptions.JavetException;
import com.caoccao.javet.enums.V8ValueReferenceType;
+import com.caoccao.javet.exceptions.JavetException;
public class V8ValueError extends V8ValueObject {
- protected static final String STACK = "stack";
protected static final String MESSAGE = "message";
+ protected static final String STACK = "stack";
V8ValueError(long handle) {
super(handle);
}
- @Override
- public V8ValueReferenceType getType() {
- return V8ValueReferenceType.Error;
- }
-
public String getMessage() throws JavetException {
return getPropertyString(MESSAGE);
}
@@ -40,4 +35,9 @@ public String getMessage() throws JavetException {
public String getStack() throws JavetException {
return getPropertyString(STACK);
}
+
+ @Override
+ public V8ValueReferenceType getType() {
+ return V8ValueReferenceType.Error;
+ }
}
diff --git a/src/main/java/com/caoccao/javet/values/reference/V8ValueFunction.java b/src/main/java/com/caoccao/javet/values/reference/V8ValueFunction.java
index 101eff76c..c09118e7b 100644
--- a/src/main/java/com/caoccao/javet/values/reference/V8ValueFunction.java
+++ b/src/main/java/com/caoccao/javet/values/reference/V8ValueFunction.java
@@ -37,42 +37,37 @@ public class V8ValueFunction extends V8ValueObject implements IV8ValueFunction {
@Override
@CheckReturnValue
- public T callExtended(IV8ValueObject receiver, boolean returnResult, Object... objects)
- throws JavetException {
+ public T callAsConstructor(Object... objects) throws JavetException {
checkV8Runtime();
try (V8VirtualValueList virtualValueList = new V8VirtualValueList(v8Runtime, objects)) {
- return v8Runtime.call(this, receiver, returnResult, virtualValueList.get());
+ return v8Runtime.callAsConstructor(this, virtualValueList.get());
}
}
@Override
@CheckReturnValue
- public T callExtended(IV8ValueObject receiver, boolean returnResult, V8Value... v8Values) throws JavetException {
+ public T callAsConstructor(V8Value... v8Values) throws JavetException {
checkV8Runtime();
v8Runtime.decorateV8Values(v8Values);
- return v8Runtime.call(this, receiver, returnResult, v8Values);
+ return v8Runtime.callAsConstructor(this, v8Values);
}
@Override
@CheckReturnValue
- public T callAsConstructor(Object... objects) throws JavetException {
+ public T callExtended(IV8ValueObject receiver, boolean returnResult, Object... objects)
+ throws JavetException {
checkV8Runtime();
try (V8VirtualValueList virtualValueList = new V8VirtualValueList(v8Runtime, objects)) {
- return v8Runtime.callAsConstructor(this, virtualValueList.get());
+ return v8Runtime.call(this, receiver, returnResult, virtualValueList.get());
}
}
@Override
@CheckReturnValue
- public T callAsConstructor(V8Value... v8Values) throws JavetException {
+ public T callExtended(IV8ValueObject receiver, boolean returnResult, V8Value... v8Values) throws JavetException {
checkV8Runtime();
v8Runtime.decorateV8Values(v8Values);
- return v8Runtime.callAsConstructor(this, v8Values);
- }
-
- @Override
- public V8ValueReferenceType getType() {
- return V8ValueReferenceType.Function;
+ return v8Runtime.call(this, receiver, returnResult, v8Values);
}
@Override
@@ -106,6 +101,11 @@ public String getSourceCode() throws JavetException {
return null;
}
+ @Override
+ public V8ValueReferenceType getType() {
+ return V8ValueReferenceType.Function;
+ }
+
@Override
public boolean setSourceCode(String sourceCodeString) throws JavetException {
checkV8Runtime();
diff --git a/src/main/java/com/caoccao/javet/values/reference/V8ValueIterator.java b/src/main/java/com/caoccao/javet/values/reference/V8ValueIterator.java
index ef5d70434..c6befc8f3 100644
--- a/src/main/java/com/caoccao/javet/values/reference/V8ValueIterator.java
+++ b/src/main/java/com/caoccao/javet/values/reference/V8ValueIterator.java
@@ -18,9 +18,9 @@
package com.caoccao.javet.values.reference;
import com.caoccao.javet.annotations.CheckReturnValue;
+import com.caoccao.javet.enums.V8ValueReferenceType;
import com.caoccao.javet.exceptions.JavetException;
import com.caoccao.javet.values.V8Value;
-import com.caoccao.javet.enums.V8ValueReferenceType;
public class V8ValueIterator extends V8ValueObject implements IV8ValueIterator {
protected static final String FUNCTION_NEXT = "next";
@@ -31,11 +31,6 @@ public class V8ValueIterator extends V8ValueObject implements
super(handle);
}
- @Override
- public V8ValueReferenceType getType() {
- return V8ValueReferenceType.Iterator;
- }
-
@Override
@CheckReturnValue
public T getNext() {
@@ -47,4 +42,9 @@ public T getNext() {
}
return null;
}
+
+ @Override
+ public V8ValueReferenceType getType() {
+ return V8ValueReferenceType.Iterator;
+ }
}
diff --git a/src/main/java/com/caoccao/javet/values/reference/V8ValueMap.java b/src/main/java/com/caoccao/javet/values/reference/V8ValueMap.java
index dd63bcfb1..b384e1bcf 100644
--- a/src/main/java/com/caoccao/javet/values/reference/V8ValueMap.java
+++ b/src/main/java/com/caoccao/javet/values/reference/V8ValueMap.java
@@ -30,9 +30,9 @@
@SuppressWarnings("unchecked")
public class V8ValueMap extends V8ValueObject implements IV8ValueMap {
+ protected static final String FUNCTION_ENTRIES = "entries";
protected static final String FUNCTION_KEYS = "keys";
protected static final String FUNCTION_VALUES = "values";
- protected static final String FUNCTION_ENTRIES = "entries";
V8ValueMap(long handle) {
super(handle);
diff --git a/src/main/java/com/caoccao/javet/values/reference/V8ValueObject.java b/src/main/java/com/caoccao/javet/values/reference/V8ValueObject.java
index 8a9345a39..fc235258d 100644
--- a/src/main/java/com/caoccao/javet/values/reference/V8ValueObject.java
+++ b/src/main/java/com/caoccao/javet/values/reference/V8ValueObject.java
@@ -46,8 +46,8 @@ public class V8ValueObject extends V8ValueReference implements IV8ValueObject {
protected static final String FUNCTION_GET = "get";
protected static final String FUNCTION_HAS = "has";
protected static final String FUNCTION_SET = "set";
- protected static final String METHOD_PREFIX_IS = "is";
protected static final String METHOD_PREFIX_GET = "get";
+ protected static final String METHOD_PREFIX_IS = "is";
protected static final String METHOD_PREFIX_SET = "set";
protected V8ValueObject(long handle) {
@@ -292,18 +292,18 @@ public IV8ValueArray getOwnPropertyNames() throws JavetException {
@Override
@CheckReturnValue
- public IV8ValueArray getPropertyNames() throws JavetException {
+ public T getProperty(Object key) throws JavetException {
checkV8Runtime();
- return v8Runtime.getPropertyNames(this);
+ try (V8VirtualValue virtualKey = new V8VirtualValue(v8Runtime, key)) {
+ return v8Runtime.getProperty(this, virtualKey.get());
+ }
}
@Override
@CheckReturnValue
- public T getProperty(Object key) throws JavetException {
+ public IV8ValueArray getPropertyNames() throws JavetException {
checkV8Runtime();
- try (V8VirtualValue virtualKey = new V8VirtualValue(v8Runtime, key)) {
- return v8Runtime.getProperty(this, virtualKey.get());
- }
+ return v8Runtime.getPropertyNames(this);
}
@Override
@@ -395,22 +395,22 @@ public boolean strictEquals(V8Value v8Value) throws JavetException {
}
@Override
- public String toProtoString() {
+ public String toJsonString() {
try {
checkV8Runtime();
- return v8Runtime.toProtoString(this);
+ try (V8ValueBuiltInJson v8ValueBuiltInJson = v8Runtime.getGlobalObject().getJson()) {
+ return v8ValueBuiltInJson.stringify(this);
+ }
} catch (JavetException e) {
return e.getMessage();
}
}
@Override
- public String toJsonString() {
+ public String toProtoString() {
try {
checkV8Runtime();
- try (V8ValueBuiltInJson v8ValueBuiltInJson = v8Runtime.getGlobalObject().getJson()) {
- return v8ValueBuiltInJson.stringify(this);
- }
+ return v8Runtime.toProtoString(this);
} catch (JavetException e) {
return e.getMessage();
}
diff --git a/src/main/java/com/caoccao/javet/values/reference/V8ValuePromise.java b/src/main/java/com/caoccao/javet/values/reference/V8ValuePromise.java
index 81dc79b45..98c5cd223 100644
--- a/src/main/java/com/caoccao/javet/values/reference/V8ValuePromise.java
+++ b/src/main/java/com/caoccao/javet/values/reference/V8ValuePromise.java
@@ -18,9 +18,9 @@
package com.caoccao.javet.values.reference;
import com.caoccao.javet.annotations.CheckReturnValue;
+import com.caoccao.javet.enums.V8ValueReferenceType;
import com.caoccao.javet.exceptions.JavetException;
import com.caoccao.javet.values.V8Value;
-import com.caoccao.javet.enums.V8ValueReferenceType;
public class V8ValuePromise extends V8ValueObject implements IV8ValuePromise {
@@ -68,7 +68,7 @@ public void markAsHandled() throws JavetException {
@Override
@CheckReturnValue
public V8ValuePromise then(IV8ValueFunction functionFulfilled, IV8ValueFunction functionRejected)
- throws JavetException{
+ throws JavetException {
checkV8Runtime();
return v8Runtime.promiseThen(this, functionFulfilled, functionRejected);
}
diff --git a/src/main/java/com/caoccao/javet/values/reference/V8ValueReference.java b/src/main/java/com/caoccao/javet/values/reference/V8ValueReference.java
index f61b30648..d90ee6635 100644
--- a/src/main/java/com/caoccao/javet/values/reference/V8ValueReference.java
+++ b/src/main/java/com/caoccao/javet/values/reference/V8ValueReference.java
@@ -88,14 +88,14 @@ public boolean equals(V8Value v8Value) throws JavetException {
return v8Runtime.equals(this, v8ValueReference);
}
- @Override
- public abstract V8ValueReferenceType getType();
-
@Override
public long getHandle() {
return handle;
}
+ @Override
+ public abstract V8ValueReferenceType getType();
+
@Override
public boolean isWeak() {
return weak;
diff --git a/src/main/java/com/caoccao/javet/values/reference/V8ValueSet.java b/src/main/java/com/caoccao/javet/values/reference/V8ValueSet.java
index b18bdf348..d5c5fb600 100644
--- a/src/main/java/com/caoccao/javet/values/reference/V8ValueSet.java
+++ b/src/main/java/com/caoccao/javet/values/reference/V8ValueSet.java
@@ -89,11 +89,6 @@ public IV8ValueIterator getEntries() throws JavetException {
return invoke(FUNCTION_ENTRIES);
}
- @Override
- public V8ValueReferenceType getType() {
- return V8ValueReferenceType.Set;
- }
-
@Override
@CheckReturnValue
public IV8ValueIterator getKeys() throws JavetException {
@@ -107,4 +102,9 @@ public int getSize() throws JavetException {
return v8Runtime.getSize(this);
}
+ @Override
+ public V8ValueReferenceType getType() {
+ return V8ValueReferenceType.Set;
+ }
+
}
diff --git a/src/main/java/com/caoccao/javet/values/reference/V8ValueSymbol.java b/src/main/java/com/caoccao/javet/values/reference/V8ValueSymbol.java
index ec7226960..d3afda98b 100644
--- a/src/main/java/com/caoccao/javet/values/reference/V8ValueSymbol.java
+++ b/src/main/java/com/caoccao/javet/values/reference/V8ValueSymbol.java
@@ -17,8 +17,8 @@
package com.caoccao.javet.values.reference;
-import com.caoccao.javet.exceptions.JavetException;
import com.caoccao.javet.enums.V8ValueReferenceType;
+import com.caoccao.javet.exceptions.JavetException;
import java.text.MessageFormat;
@@ -31,15 +31,15 @@ public class V8ValueSymbol extends V8ValueObject {
super(handle);
}
+ public String getDescription() throws JavetException {
+ return getPropertyString(PROPERTY_DESCRIPTION);
+ }
+
@Override
public V8ValueReferenceType getType() {
return V8ValueReferenceType.Symbol;
}
- public String getDescription() throws JavetException {
- return getPropertyString(PROPERTY_DESCRIPTION);
- }
-
@Override
public String toString() {
try {
diff --git a/src/main/java/com/caoccao/javet/values/reference/V8ValueTypedArray.java b/src/main/java/com/caoccao/javet/values/reference/V8ValueTypedArray.java
index 533dd8cd4..86ebe4ff1 100644
--- a/src/main/java/com/caoccao/javet/values/reference/V8ValueTypedArray.java
+++ b/src/main/java/com/caoccao/javet/values/reference/V8ValueTypedArray.java
@@ -18,8 +18,8 @@
package com.caoccao.javet.values.reference;
import com.caoccao.javet.annotations.CheckReturnValue;
-import com.caoccao.javet.exceptions.JavetException;
import com.caoccao.javet.enums.V8ValueReferenceType;
+import com.caoccao.javet.exceptions.JavetException;
import java.util.Objects;
@@ -110,77 +110,6 @@ public class V8ValueTypedArray extends V8ValueObject implements IV8ValueTypedArr
setType(V8ValueReferenceType.parse(type));
}
- @Override
- @CheckReturnValue
- public V8ValueArrayBuffer getBuffer() throws JavetException {
- return get(PROPERTY_BUFFER);
- }
-
- @Override
- public int getByteLength() throws JavetException {
- return getInteger(PROPERTY_BYTE_LENGTH);
- }
-
- @Override
- public int getByteOffset() throws JavetException {
- return getInteger(PROPERTY_BYTE_OFFSET);
- }
-
- @Override
- public int getLength() throws JavetException {
- checkV8Runtime();
- return v8Runtime.getLength(this);
- }
-
- @Override
- public int getSizeInBytes() {
- return sizeInBytes;
- }
-
- @Override
- public V8ValueReferenceType getType() {
- return type;
- }
-
- /**
- * Sets type.
- *
- * @param type the type
- */
- protected void setType(V8ValueReferenceType type) {
- switch (type) {
- case Int8Array:
- case Uint8Array:
- case Uint8ClampedArray:
- sizeInBytes = ONE_BYTE_PER_VALUE;
- break;
- case Int16Array:
- case Uint16Array:
- sizeInBytes = TWO_BYTES_PER_VALUE;
- break;
- case Int32Array:
- case Uint32Array:
- case Float32Array:
- sizeInBytes = FOUR_BYTES_PER_VALUE;
- break;
- case Float64Array:
- case BigInt64Array:
- case BigUint64Array:
- sizeInBytes = EIGHT_BYTES_PER_VALUE;
- break;
- default:
- type = V8ValueReferenceType.Invalid;
- sizeInBytes = ZERO_BYTE_PER_VALUE;
- break;
- }
- this.type = type;
- }
-
- @Override
- public boolean isValid() {
- return type != V8ValueReferenceType.Invalid;
- }
-
/**
* From byte array.
*
@@ -288,6 +217,77 @@ public boolean fromShorts(short[] shorts) throws JavetException {
return false;
}
+ @Override
+ @CheckReturnValue
+ public V8ValueArrayBuffer getBuffer() throws JavetException {
+ return get(PROPERTY_BUFFER);
+ }
+
+ @Override
+ public int getByteLength() throws JavetException {
+ return getInteger(PROPERTY_BYTE_LENGTH);
+ }
+
+ @Override
+ public int getByteOffset() throws JavetException {
+ return getInteger(PROPERTY_BYTE_OFFSET);
+ }
+
+ @Override
+ public int getLength() throws JavetException {
+ checkV8Runtime();
+ return v8Runtime.getLength(this);
+ }
+
+ @Override
+ public int getSizeInBytes() {
+ return sizeInBytes;
+ }
+
+ @Override
+ public V8ValueReferenceType getType() {
+ return type;
+ }
+
+ @Override
+ public boolean isValid() {
+ return type != V8ValueReferenceType.Invalid;
+ }
+
+ /**
+ * Sets type.
+ *
+ * @param type the type
+ */
+ protected void setType(V8ValueReferenceType type) {
+ switch (type) {
+ case Int8Array:
+ case Uint8Array:
+ case Uint8ClampedArray:
+ sizeInBytes = ONE_BYTE_PER_VALUE;
+ break;
+ case Int16Array:
+ case Uint16Array:
+ sizeInBytes = TWO_BYTES_PER_VALUE;
+ break;
+ case Int32Array:
+ case Uint32Array:
+ case Float32Array:
+ sizeInBytes = FOUR_BYTES_PER_VALUE;
+ break;
+ case Float64Array:
+ case BigInt64Array:
+ case BigUint64Array:
+ sizeInBytes = EIGHT_BYTES_PER_VALUE;
+ break;
+ default:
+ type = V8ValueReferenceType.Invalid;
+ sizeInBytes = ZERO_BYTE_PER_VALUE;
+ break;
+ }
+ this.type = type;
+ }
+
/**
* To byte array.
*
@@ -306,30 +306,30 @@ public byte[] toBytes() throws JavetException {
}
/**
- * To float array.
+ * To double array.
*
- * @return the float array
+ * @return the double array
* @throws JavetException the javet exception
*/
- public float[] toFloats() throws JavetException {
- if (getType() == V8ValueReferenceType.Float32Array) {
+ public double[] toDoubles() throws JavetException {
+ if (getType() == V8ValueReferenceType.Float64Array) {
try (V8ValueArrayBuffer v8ValueArrayBuffer = getBuffer()) {
- return v8ValueArrayBuffer.toFloats();
+ return v8ValueArrayBuffer.toDoubles();
}
}
return null;
}
/**
- * To double array.
+ * To float array.
*
- * @return the double array
+ * @return the float array
* @throws JavetException the javet exception
*/
- public double[] toDoubles() throws JavetException {
- if (getType() == V8ValueReferenceType.Float64Array) {
+ public float[] toFloats() throws JavetException {
+ if (getType() == V8ValueReferenceType.Float32Array) {
try (V8ValueArrayBuffer v8ValueArrayBuffer = getBuffer()) {
- return v8ValueArrayBuffer.toDoubles();
+ return v8ValueArrayBuffer.toFloats();
}
}
return null;
diff --git a/src/main/java/com/caoccao/javet/values/reference/builtin/V8ValueBuiltInPromise.java b/src/main/java/com/caoccao/javet/values/reference/builtin/V8ValueBuiltInPromise.java
index 4074dcb3a..d9acafc13 100644
--- a/src/main/java/com/caoccao/javet/values/reference/builtin/V8ValueBuiltInPromise.java
+++ b/src/main/java/com/caoccao/javet/values/reference/builtin/V8ValueBuiltInPromise.java
@@ -45,11 +45,6 @@ public V8ValuePromise all(V8Value v8Value) throws JavetException {
return invoke(FUNCTION_ALL, v8Value);
}
- public void allVoid(V8Value v8Value) throws JavetException {
- Objects.requireNonNull(v8Value);
- invokeVoid(FUNCTION_ALL, v8Value);
- }
-
@CheckReturnValue
public V8ValuePromise allSettled(V8Value v8Value) throws JavetException {
Objects.requireNonNull(v8Value);
@@ -61,6 +56,11 @@ public void allSettledVoid(V8Value v8Value) throws JavetException {
invokeVoid(FUNCTION_ALL_SETTLED, v8Value);
}
+ public void allVoid(V8Value v8Value) throws JavetException {
+ Objects.requireNonNull(v8Value);
+ invokeVoid(FUNCTION_ALL, v8Value);
+ }
+
@CheckReturnValue
public V8ValuePromise any(V8Value v8Value) throws JavetException {
Objects.requireNonNull(v8Value);
@@ -83,20 +83,15 @@ public void raceVoid(V8Value v8Value) throws JavetException {
invokeVoid(FUNCTION_RACE, v8Value);
}
- public void rejectVoid(V8Value v8Value) throws JavetException {
- Objects.requireNonNull(v8Value);
- invokeVoid(FUNCTION_REJECT, v8Value);
- }
-
@CheckReturnValue
public V8ValuePromise reject(V8Value v8Value) throws JavetException {
Objects.requireNonNull(v8Value);
return invoke(FUNCTION_REJECT, v8Value);
}
- public void resolveVoid(V8Value v8Value) throws JavetException {
+ public void rejectVoid(V8Value v8Value) throws JavetException {
Objects.requireNonNull(v8Value);
- invokeVoid(FUNCTION_RESOLVE, v8Value);
+ invokeVoid(FUNCTION_REJECT, v8Value);
}
@CheckReturnValue
@@ -105,6 +100,11 @@ public V8ValuePromise resolve(V8Value v8Value) throws JavetException {
return invoke(FUNCTION_RESOLVE, v8Value);
}
+ public void resolveVoid(V8Value v8Value) throws JavetException {
+ Objects.requireNonNull(v8Value);
+ invokeVoid(FUNCTION_RESOLVE, v8Value);
+ }
+
@Override
public V8ValueBuiltInPromise toClone() throws JavetException {
return this;
diff --git a/src/main/java/com/caoccao/javet/values/virtual/V8VirtualValueList.java b/src/main/java/com/caoccao/javet/values/virtual/V8VirtualValueList.java
index 009cbc8e2..5a4ad84c5 100644
--- a/src/main/java/com/caoccao/javet/values/virtual/V8VirtualValueList.java
+++ b/src/main/java/com/caoccao/javet/values/virtual/V8VirtualValueList.java
@@ -20,7 +20,6 @@
import com.caoccao.javet.exceptions.JavetException;
import com.caoccao.javet.interfaces.IJavetClosable;
import com.caoccao.javet.interop.V8Runtime;
-import com.caoccao.javet.interop.converters.IJavetConverter;
import com.caoccao.javet.utils.JavetResourceUtils;
import com.caoccao.javet.values.V8Value;
diff --git a/src/test/java/com/caoccao/javet/BaseTestJavet.java b/src/test/java/com/caoccao/javet/BaseTestJavet.java
index b2c52ccd2..0fd2a2bd1 100644
--- a/src/test/java/com/caoccao/javet/BaseTestJavet.java
+++ b/src/test/java/com/caoccao/javet/BaseTestJavet.java
@@ -17,8 +17,8 @@
package com.caoccao.javet;
-import com.caoccao.javet.interfaces.IJavetLogger;
import com.caoccao.javet.enums.JSRuntimeType;
+import com.caoccao.javet.interfaces.IJavetLogger;
import com.caoccao.javet.interop.JavetLibLoader;
import com.caoccao.javet.interop.V8Flags;
import com.caoccao.javet.interop.V8Host;
diff --git a/src/test/java/com/caoccao/javet/BaseTestJavetPool.java b/src/test/java/com/caoccao/javet/BaseTestJavetPool.java
index aab5fa586..b04790592 100644
--- a/src/test/java/com/caoccao/javet/BaseTestJavetPool.java
+++ b/src/test/java/com/caoccao/javet/BaseTestJavetPool.java
@@ -18,15 +18,23 @@
package com.caoccao.javet;
import com.caoccao.javet.exceptions.JavetException;
-import com.caoccao.javet.interop.V8Host;
import com.caoccao.javet.interop.engine.IJavetEnginePool;
import com.caoccao.javet.interop.engine.JavetEnginePool;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
public abstract class BaseTestJavetPool extends BaseTestJavet {
protected IJavetEnginePool javetEnginePool;
+ @AfterEach
+ public void afterEach() throws JavetException {
+ javetEnginePool.close();
+ v8Host.clearInternalStatistic();
+ assertEquals(0, v8Host.getNodeInstance().getV8RuntimeCount());
+ }
+
@BeforeEach
public void beforeEach() {
javetEnginePool = new JavetEnginePool();
@@ -34,11 +42,4 @@ public void beforeEach() {
javetEnginePool.getConfig().setJSRuntimeType(v8Host.getJSRuntimeType());
}
- @AfterEach
- public void afterEach() throws JavetException {
- javetEnginePool.close();
- V8Host.getNodeInstance().clearInternalStatistic();
- V8Host.getV8Instance().clearInternalStatistic();
- }
-
}
diff --git a/src/test/java/com/caoccao/javet/BaseTestJavetRuntime.java b/src/test/java/com/caoccao/javet/BaseTestJavetRuntime.java
index fb18a2173..0dfedf4a5 100644
--- a/src/test/java/com/caoccao/javet/BaseTestJavetRuntime.java
+++ b/src/test/java/com/caoccao/javet/BaseTestJavetRuntime.java
@@ -38,7 +38,7 @@ public void afterEach() throws JavetException {
NodeRuntime nodeRuntime = (NodeRuntime) v8Runtime;
assertEquals(nodeRuntime.getNodeModuleCount(), nodeRuntime.getReferenceCount(),
"Reference count should be the node module count after test case is ended.");
- }else {
+ } else {
assertEquals(0, v8Runtime.getReferenceCount(),
"Reference count should be 0 after test case is ended.");
}
@@ -52,6 +52,7 @@ public void afterEach() throws JavetException {
Arrays.copyOfRange(counters, 7, 13));
}
v8Host.clearInternalStatistic();
+ assertEquals(0, v8Host.getV8RuntimeCount());
}
@BeforeEach
diff --git a/src/test/java/com/caoccao/javet/interception/logging/TestJavetStandardConsoleInterceptor.java b/src/test/java/com/caoccao/javet/interception/logging/TestJavetStandardConsoleInterceptor.java
index 0e51257e4..472609bc9 100644
--- a/src/test/java/com/caoccao/javet/interception/logging/TestJavetStandardConsoleInterceptor.java
+++ b/src/test/java/com/caoccao/javet/interception/logging/TestJavetStandardConsoleInterceptor.java
@@ -56,6 +56,6 @@ public void test() throws IOException, JavetException {
byteArrayOutputStream.toString(StandardCharsets.UTF_8.name()).trim());
}
}
- v8Runtime.requestGarbageCollectionForTesting(true);
+ v8Runtime.lowMemoryNotification();
}
}
diff --git a/src/test/java/com/caoccao/javet/interop/TestJavetLibLoader.java b/src/test/java/com/caoccao/javet/interop/TestJavetLibLoader.java
index d70ba0f27..1c7061f09 100644
--- a/src/test/java/com/caoccao/javet/interop/TestJavetLibLoader.java
+++ b/src/test/java/com/caoccao/javet/interop/TestJavetLibLoader.java
@@ -18,20 +18,71 @@
package com.caoccao.javet.interop;
import com.caoccao.javet.enums.JSRuntimeType;
+import com.caoccao.javet.exceptions.JavetError;
import com.caoccao.javet.exceptions.JavetException;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.*;
+
public class TestJavetLibLoader {
+ @AfterAll
+ public static void afterAll() {
+ V8Host.setLibraryReloadable(false);
+ }
+
+ @BeforeAll
+ public static void beforeAll() {
+ V8Host.setLibraryReloadable(true);
+ }
+
@Test
- public void testLoadAndUnload() {
+ public void testCustomClassLoader() {
+ testCustomClassLoader(JSRuntimeType.Node);
+ testCustomClassLoader(JSRuntimeType.V8);
+ }
+
+ protected void testCustomClassLoader(JSRuntimeType jsRuntimeType) {
try {
- JavetClassLoader javetClassLoader = new JavetClassLoader(getClass().getClassLoader(), JSRuntimeType.Node);
- javetClassLoader.load();
- javetClassLoader = null;
- System.gc();
- System.runFinalization();
+ for (int i = 0; i < 2; ++i) {
+ JavetClassLoader javetClassLoader = new JavetClassLoader(getClass().getClassLoader(), jsRuntimeType);
+ javetClassLoader.load();
+ javetClassLoader.getNative();
+ javetClassLoader = null;
+ System.gc();
+ System.runFinalization();
+ }
} catch (JavetException e) {
// This is expected.
}
}
+
+ @Test
+ public void testLoadAndUnload() throws JavetException {
+ testLoadAndUnload(JSRuntimeType.Node);
+ testLoadAndUnload(JSRuntimeType.V8);
+ }
+
+ protected void testLoadAndUnload(JSRuntimeType jsRuntimeType) throws JavetException {
+ V8Host v8Host = V8Host.getInstance(jsRuntimeType);
+ assertTrue(v8Host.isLibraryLoaded());
+ try (V8Runtime v8Runtime = v8Host.createV8Runtime()) {
+ assertEquals(2, v8Runtime.getExecutor("1 + 1").executeInteger());
+ }
+ assertEquals(0, v8Host.getV8RuntimeCount());
+ assertTrue(v8Host.unloadLibrary());
+ assertFalse(v8Host.isLibraryLoaded());
+ try {
+ v8Host.createV8Runtime();
+ } catch (JavetException e) {
+ assertEquals(JavetError.LibraryNotLoaded, e.getError());
+ }
+ assertTrue(v8Host.loadLibrary());
+ assertTrue(v8Host.isLibraryLoaded());
+ try (V8Runtime v8Runtime = v8Host.createV8Runtime()) {
+ assertEquals(2, v8Runtime.getExecutor("1 + 1").executeInteger());
+ }
+ assertEquals(0, v8Host.getV8RuntimeCount());
+ }
}
diff --git a/src/test/java/com/caoccao/javet/interop/TestNodeRuntime.java b/src/test/java/com/caoccao/javet/interop/TestNodeRuntime.java
index 8f7253842..d8d93ef80 100644
--- a/src/test/java/com/caoccao/javet/interop/TestNodeRuntime.java
+++ b/src/test/java/com/caoccao/javet/interop/TestNodeRuntime.java
@@ -34,8 +34,8 @@
import static org.junit.jupiter.api.Assertions.*;
public class TestNodeRuntime extends BaseTestJavet {
- protected NodeRuntime nodeRuntime;
protected NodeModuleProcess nodeModuleProcess;
+ protected NodeRuntime nodeRuntime;
public TestNodeRuntime() {
super(JSRuntimeType.Node);
@@ -103,6 +103,13 @@ public void testModuleProcess() throws JavetException {
assertEquals(path1.toAbsolutePath().toString(), path4.toAbsolutePath().toString());
}
+ @Test
+ public void testModuleVM() throws JavetException {
+ internalTest(
+ "test-node-module-vm.js",
+ "[{\"a\":\"x\",\"b\":3},\"undefined\",\"undefined\"]");
+ }
+
@Test
public void testSqlite3() throws JavetException {
File sqlite3File = getScriptFile("../node_modules/sqlite3/sqlite3.js");
@@ -123,11 +130,4 @@ public void testTimers() throws JavetException {
"setTimeout() has been executed after await().");
}
}
-
- @Test
- public void testModuleVM() throws JavetException {
- internalTest(
- "test-node-module-vm.js",
- "[{\"a\":\"x\",\"b\":3},\"undefined\",\"undefined\"]");
- }
}
diff --git a/src/test/java/com/caoccao/javet/interop/TestV8Host.java b/src/test/java/com/caoccao/javet/interop/TestV8Host.java
index fcab97eee..ae5b7be80 100644
--- a/src/test/java/com/caoccao/javet/interop/TestV8Host.java
+++ b/src/test/java/com/caoccao/javet/interop/TestV8Host.java
@@ -39,16 +39,16 @@ public void testBothNodeAndV8() throws JavetException {
}
@Test
- public void testCreateV8RuntimeWithoutGlobalName() throws JavetException {
- try (V8Runtime v8Runtime = v8Host.createV8Runtime()) {
+ public void testCreateV8RuntimeWithGlobalName() throws JavetException {
+ try (V8Runtime v8Runtime = v8Host.createV8Runtime("window")) {
assertNotNull(v8Runtime);
assertTrue(v8Host.isIsolateCreated());
}
}
@Test
- public void testCreateV8RuntimeWithGlobalName() throws JavetException {
- try (V8Runtime v8Runtime = v8Host.createV8Runtime("window")) {
+ public void testCreateV8RuntimeWithoutGlobalName() throws JavetException {
+ try (V8Runtime v8Runtime = v8Host.createV8Runtime()) {
assertNotNull(v8Runtime);
assertTrue(v8Host.isIsolateCreated());
}
diff --git a/src/test/java/com/caoccao/javet/interop/TestV8Inspector.java b/src/test/java/com/caoccao/javet/interop/TestV8Inspector.java
index 209ea88ef..c5d3a9215 100644
--- a/src/test/java/com/caoccao/javet/interop/TestV8Inspector.java
+++ b/src/test/java/com/caoccao/javet/interop/TestV8Inspector.java
@@ -96,6 +96,7 @@ class MockV8InspectorListener implements IV8InspectorListener {
private List notifications;
private List requests;
private List responses;
+
public MockV8InspectorListener() {
contextGroupIds = new ArrayList<>();
notifications = new ArrayList<>();
diff --git a/src/test/java/com/caoccao/javet/interop/converters/TestJavetCustomConverter.java b/src/test/java/com/caoccao/javet/interop/converters/TestJavetCustomConverter.java
index c48940d13..660efc6d3 100644
--- a/src/test/java/com/caoccao/javet/interop/converters/TestJavetCustomConverter.java
+++ b/src/test/java/com/caoccao/javet/interop/converters/TestJavetCustomConverter.java
@@ -118,14 +118,14 @@ public String getName() {
return name;
}
- public void setName(String name) {
- this.name = name;
- }
-
public String getValue() {
return value;
}
+ public void setName(String name) {
+ this.name = name;
+ }
+
public void setValue(String value) {
this.value = value;
}
diff --git a/src/test/java/com/caoccao/javet/interop/converters/TestJavetObjectConverter.java b/src/test/java/com/caoccao/javet/interop/converters/TestJavetObjectConverter.java
index 4c12765df..1fa4f3527 100644
--- a/src/test/java/com/caoccao/javet/interop/converters/TestJavetObjectConverter.java
+++ b/src/test/java/com/caoccao/javet/interop/converters/TestJavetObjectConverter.java
@@ -193,24 +193,6 @@ public void testTypedArrayFloatArray() throws JavetException {
}
}
- @Test
- public void testTypedArrayLongArray() throws JavetException {
- IJavetConverter converter = new JavetObjectConverter();
- long[] longs = new long[]{1L, 2L, 3L};
- try (V8ValueTypedArray v8ValueTypedArray = converter.toV8Value(v8Runtime, longs)) {
- assertEquals(longs.length, v8ValueTypedArray.getLength());
- assertEquals(longs.length * v8ValueTypedArray.getSizeInBytes(), v8ValueTypedArray.getByteLength());
- assertEquals(0, v8ValueTypedArray.getByteOffset());
- assertArrayEquals(longs, v8ValueTypedArray.toLongs());
- }
- try (V8ValueTypedArray v8ValueTypedArray =
- v8Runtime.createV8ValueTypedArray(V8ValueReferenceType.BigInt64Array, longs.length)) {
- assertTrue(v8ValueTypedArray.fromLongs(longs));
- long[] newLongs = (long[]) converter.toObject(v8ValueTypedArray);
- assertArrayEquals(longs, newLongs);
- }
- }
-
@Test
public void testTypedArrayIntegerArray() throws JavetException {
IJavetConverter converter = new JavetObjectConverter();
@@ -229,6 +211,24 @@ public void testTypedArrayIntegerArray() throws JavetException {
}
}
+ @Test
+ public void testTypedArrayLongArray() throws JavetException {
+ IJavetConverter converter = new JavetObjectConverter();
+ long[] longs = new long[]{1L, 2L, 3L};
+ try (V8ValueTypedArray v8ValueTypedArray = converter.toV8Value(v8Runtime, longs)) {
+ assertEquals(longs.length, v8ValueTypedArray.getLength());
+ assertEquals(longs.length * v8ValueTypedArray.getSizeInBytes(), v8ValueTypedArray.getByteLength());
+ assertEquals(0, v8ValueTypedArray.getByteOffset());
+ assertArrayEquals(longs, v8ValueTypedArray.toLongs());
+ }
+ try (V8ValueTypedArray v8ValueTypedArray =
+ v8Runtime.createV8ValueTypedArray(V8ValueReferenceType.BigInt64Array, longs.length)) {
+ assertTrue(v8ValueTypedArray.fromLongs(longs));
+ long[] newLongs = (long[]) converter.toObject(v8ValueTypedArray);
+ assertArrayEquals(longs, newLongs);
+ }
+ }
+
@Test
public void testTypedArrayShortArray() throws JavetException {
IJavetConverter converter = new JavetObjectConverter();
diff --git a/src/test/java/com/caoccao/javet/interop/engine/TestJavetEngineGuard.java b/src/test/java/com/caoccao/javet/interop/engine/TestJavetEngineGuard.java
index d6a99ca8f..235e9b9b2 100644
--- a/src/test/java/com/caoccao/javet/interop/engine/TestJavetEngineGuard.java
+++ b/src/test/java/com/caoccao/javet/interop/engine/TestJavetEngineGuard.java
@@ -30,21 +30,6 @@
import static org.junit.jupiter.api.Assertions.*;
public class TestJavetEngineGuard extends BaseTestJavetPool {
- @Test
- public void testWithoutTermination() throws JavetException {
- final long timeoutMillis = 10000;
- ZonedDateTime startZonedDateTime = JavetDateTimeUtils.getUTCNow();
- try (IJavetEngine iJavetEngine = javetEnginePool.getEngine()) {
- try (IJavetEngineGuard iJavetEngineGuard = iJavetEngine.getGuard(timeoutMillis)) {
- V8Runtime v8Runtime = iJavetEngine.getV8Runtime();
- assertEquals(2, v8Runtime.getExecutor("1 + 1").executeInteger());
- }
- }
- ZonedDateTime endZonedDateTime = JavetDateTimeUtils.getUTCNow();
- Duration duration = Duration.between(startZonedDateTime, endZonedDateTime);
- assertTrue(duration.toMillis() < timeoutMillis);
- }
-
@Test
public void testTermination() throws JavetException {
// Get an engine from the pool as usual.
@@ -52,6 +37,7 @@ public void testTermination() throws JavetException {
V8Runtime v8Runtime = iJavetEngine.getV8Runtime();
// Get a guard from the engine and apply try-with-resource pattern.
try (IJavetEngineGuard iJavetEngineGuard = iJavetEngine.getGuard(1)) {
+ iJavetEngineGuard.enableInDebugMode();
v8Runtime.getExecutor("while (true) {}").executeVoid();
// That infinite loop will be terminated in 10 seconds by the guard.
} catch (JavetTerminatedException e) {
@@ -62,4 +48,19 @@ public void testTermination() throws JavetException {
"The V8 runtime is not dead and still be able to execute code afterwards.");
}
}
+
+ @Test
+ public void testWithoutTermination() throws JavetException {
+ final long timeoutMillis = 10000;
+ ZonedDateTime startZonedDateTime = JavetDateTimeUtils.getUTCNow();
+ try (IJavetEngine iJavetEngine = javetEnginePool.getEngine()) {
+ try (IJavetEngineGuard iJavetEngineGuard = iJavetEngine.getGuard(timeoutMillis)) {
+ V8Runtime v8Runtime = iJavetEngine.getV8Runtime();
+ assertEquals(2, v8Runtime.getExecutor("1 + 1").executeInteger());
+ }
+ }
+ ZonedDateTime endZonedDateTime = JavetDateTimeUtils.getUTCNow();
+ Duration duration = Duration.between(startZonedDateTime, endZonedDateTime);
+ assertTrue(duration.toMillis() < timeoutMillis);
+ }
}
diff --git a/src/test/java/com/caoccao/javet/interop/engine/TestJavetEnginePool.java b/src/test/java/com/caoccao/javet/interop/engine/TestJavetEnginePool.java
index bc89fe170..4c86de0a3 100644
--- a/src/test/java/com/caoccao/javet/interop/engine/TestJavetEnginePool.java
+++ b/src/test/java/com/caoccao/javet/interop/engine/TestJavetEnginePool.java
@@ -35,8 +35,8 @@
public class TestJavetEnginePool extends BaseTestJavet {
public static final int TEST_POOL_DAEMON_CHECK_INTERVAL_MILLIS = 1;
public static final int TEST_MAX_TIMEOUT = 1000;
- private JavetEnginePool javetEnginePool;
private JavetEngineConfig javetEngineConfig;
+ private JavetEnginePool javetEnginePool;
@AfterEach
private void afterEach() throws JavetException {
@@ -44,6 +44,7 @@ private void afterEach() throws JavetException {
assertEquals(0, javetEnginePool.getActiveEngineCount());
assertEquals(0, javetEnginePool.getIdleEngineCount());
assertFalse(javetEnginePool.isActive());
+ assertEquals(0, v8Host.getV8RuntimeCount());
}
@BeforeEach
@@ -52,27 +53,7 @@ private void beforeEach() {
assertTrue(javetEnginePool.isActive());
javetEngineConfig = javetEnginePool.getConfig();
javetEngineConfig.setPoolDaemonCheckIntervalMillis(TEST_POOL_DAEMON_CHECK_INTERVAL_MILLIS);
- }
-
- @Test
- public void testSingleThreadedExecution() throws Exception {
- assertEquals(0, javetEnginePool.getIdleEngineCount());
- assertEquals(0, javetEnginePool.getActiveEngineCount());
- try (IJavetEngine engine = javetEnginePool.getEngine()) {
- assertEquals(0, javetEnginePool.getIdleEngineCount());
- assertEquals(1, javetEnginePool.getActiveEngineCount());
- V8Runtime v8Runtime = engine.getV8Runtime();
- assertTrue(v8Runtime.isPooled());
- assertEquals(2, v8Runtime.getExecutor("1 + 1").executeInteger());
- v8Runtime.close(); // close() doesn't take effect because the V8 runtime is managed by pool
- assertEquals(4, v8Runtime.getExecutor("2 + 2").executeInteger());
- assertThrows(JavetExecutionException.class, () -> {
- v8Runtime.getExecutor("eval('1');").executeVoid();
- }, "By default, the engine pool should disallow eval().");
- }
- runAndWait(TEST_MAX_TIMEOUT, () -> javetEnginePool.getIdleEngineCount() == 1);
- assertEquals(1, javetEnginePool.getIdleEngineCount());
- assertEquals(0, javetEnginePool.getActiveEngineCount());
+ javetEngineConfig.setJSRuntimeType(v8Host.getJSRuntimeType());
}
@Test
@@ -166,4 +147,25 @@ public void testMultiThreadedExecutionExceedsMaxSize() throws Exception {
assertEquals(0, failureCount.get());
runAndWait(TEST_MAX_TIMEOUT, () -> 0 == javetEnginePool.getActiveEngineCount());
}
+
+ @Test
+ public void testSingleThreadedExecution() throws Exception {
+ assertEquals(0, javetEnginePool.getIdleEngineCount());
+ assertEquals(0, javetEnginePool.getActiveEngineCount());
+ try (IJavetEngine engine = javetEnginePool.getEngine()) {
+ assertEquals(0, javetEnginePool.getIdleEngineCount());
+ assertEquals(1, javetEnginePool.getActiveEngineCount());
+ V8Runtime v8Runtime = engine.getV8Runtime();
+ assertTrue(v8Runtime.isPooled());
+ assertEquals(2, v8Runtime.getExecutor("1 + 1").executeInteger());
+ v8Runtime.close(); // close() doesn't take effect because the V8 runtime is managed by pool
+ assertEquals(4, v8Runtime.getExecutor("2 + 2").executeInteger());
+ assertThrows(JavetExecutionException.class, () -> {
+ v8Runtime.getExecutor("eval('1');").executeVoid();
+ }, "By default, the engine pool should disallow eval().");
+ }
+ runAndWait(TEST_MAX_TIMEOUT, () -> javetEnginePool.getIdleEngineCount() == 1);
+ assertEquals(1, javetEnginePool.getIdleEngineCount());
+ assertEquals(0, javetEnginePool.getActiveEngineCount());
+ }
}
diff --git a/src/test/java/com/caoccao/javet/interop/engine/TestPerformance.java b/src/test/java/com/caoccao/javet/interop/engine/TestPerformance.java
index 158d33e53..7b63746cc 100644
--- a/src/test/java/com/caoccao/javet/interop/engine/TestPerformance.java
+++ b/src/test/java/com/caoccao/javet/interop/engine/TestPerformance.java
@@ -73,47 +73,6 @@ public void testAdHocContextAnd1Thread() throws Exception {
updateDoc(prefix + "Ad-hoc Context with 1 Thread", tps);
}
- @Test
- @Tag("performance")
- public void testAdHocIsolateAnd1Thread() throws Exception {
- final int iterations = jsRuntimeType.isNode() ? 200 : 10000;
- String codeString = "1 + 1";
- final long startTime = System.currentTimeMillis();
- try (IJavetEngine javetEngine = javetEnginePool.getEngine()) {
- V8Runtime v8Runtime = javetEngine.getV8Runtime();
- IV8Executor v8Executor = v8Runtime.getExecutor(codeString);
- for (int i = 0; i < iterations; i++) {
- javetEngine.resetIsolate();
- assertEquals(2, v8Executor.executeInteger());
- }
- }
- final long stopTime = System.currentTimeMillis();
- final long tps = iterations * 1000 / (stopTime - startTime);
- logger.logInfo(prefix + "Ad-hoc Isolate with 1 Thread: {0}", tps);
- updateDoc(prefix + "Ad-hoc Isolate with 1 Thread", tps);
- }
-
- @Test
- @Tag("performance")
- public void testSingleContextAnd1Thread() throws Exception {
- final int iterations = 2000000;
- String codeString = "1 + 1";
- final long startTime = System.currentTimeMillis();
- try (IJavetEngine javetEngine = javetEnginePool.getEngine()) {
- V8Runtime v8Runtime = javetEngine.getV8Runtime();
- try (V8Locker v8Locker = v8Runtime.getV8Locker()) {
- IV8Executor v8Executor = v8Runtime.getExecutor(codeString);
- for (int i = 0; i < iterations; i++) {
- assertEquals(2, v8Executor.executeInteger());
- }
- }
- }
- final long stopTime = System.currentTimeMillis();
- final long tps = iterations * 1000 / (stopTime - startTime);
- logger.logInfo(prefix + "Single Context with 1 Thread: {0}", tps);
- updateDoc(prefix + "Single Context with 1 Thread", tps);
- }
-
@Test
@Tag("performance")
public void testAdHocContextAnd8Threads() throws Exception {
@@ -148,6 +107,26 @@ public void testAdHocContextAnd8Threads() throws Exception {
updateDoc(prefix + "Ad-hoc Context with 8 Threads", tps);
}
+ @Test
+ @Tag("performance")
+ public void testAdHocIsolateAnd1Thread() throws Exception {
+ final int iterations = jsRuntimeType.isNode() ? 200 : 10000;
+ String codeString = "1 + 1";
+ final long startTime = System.currentTimeMillis();
+ try (IJavetEngine javetEngine = javetEnginePool.getEngine()) {
+ V8Runtime v8Runtime = javetEngine.getV8Runtime();
+ IV8Executor v8Executor = v8Runtime.getExecutor(codeString);
+ for (int i = 0; i < iterations; i++) {
+ javetEngine.resetIsolate();
+ assertEquals(2, v8Executor.executeInteger());
+ }
+ }
+ final long stopTime = System.currentTimeMillis();
+ final long tps = iterations * 1000 / (stopTime - startTime);
+ logger.logInfo(prefix + "Ad-hoc Isolate with 1 Thread: {0}", tps);
+ updateDoc(prefix + "Ad-hoc Isolate with 1 Thread", tps);
+ }
+
@Test
@Tag("performance")
public void testAdHocIsolateAnd8Threads() throws Exception {
@@ -182,6 +161,27 @@ public void testAdHocIsolateAnd8Threads() throws Exception {
updateDoc(prefix + "Ad-hoc Isolate with 8 Threads", tps);
}
+ @Test
+ @Tag("performance")
+ public void testSingleContextAnd1Thread() throws Exception {
+ final int iterations = 2000000;
+ String codeString = "1 + 1";
+ final long startTime = System.currentTimeMillis();
+ try (IJavetEngine javetEngine = javetEnginePool.getEngine()) {
+ V8Runtime v8Runtime = javetEngine.getV8Runtime();
+ try (V8Locker v8Locker = v8Runtime.getV8Locker()) {
+ IV8Executor v8Executor = v8Runtime.getExecutor(codeString);
+ for (int i = 0; i < iterations; i++) {
+ assertEquals(2, v8Executor.executeInteger());
+ }
+ }
+ }
+ final long stopTime = System.currentTimeMillis();
+ final long tps = iterations * 1000 / (stopTime - startTime);
+ logger.logInfo(prefix + "Single Context with 1 Thread: {0}", tps);
+ updateDoc(prefix + "Single Context with 1 Thread", tps);
+ }
+
@Test
@Tag("performance")
public void testSingleContextAnd8Threads() throws Exception {
diff --git a/src/test/java/com/caoccao/javet/mock/MockAnnotationBasedCallbackReceiver.java b/src/test/java/com/caoccao/javet/mock/MockAnnotationBasedCallbackReceiver.java
index a37947e7a..944e43134 100644
--- a/src/test/java/com/caoccao/javet/mock/MockAnnotationBasedCallbackReceiver.java
+++ b/src/test/java/com/caoccao/javet/mock/MockAnnotationBasedCallbackReceiver.java
@@ -32,8 +32,8 @@
public class MockAnnotationBasedCallbackReceiver {
private AtomicInteger count;
- private V8Runtime v8Runtime;
private String stringValue;
+ private V8Runtime v8Runtime;
public MockAnnotationBasedCallbackReceiver() {
count = new AtomicInteger(0);
@@ -47,36 +47,6 @@ public static String staticEcho(String str) {
return str;
}
- @V8Property
- public Integer getIntegerValue() {
- count.incrementAndGet();
- return 123;
- }
-
- @V8Property
- public String getStringValue() {
- count.incrementAndGet();
- return stringValue;
- }
-
- @V8Property(thisObjectRequired = true)
- public String getStringValueWithThis(V8ValueObject thisObject) throws JavetException {
- count.incrementAndGet();
- return thisObject.getString("stringValue");
- }
-
- @V8Property
- public void setStringValue(String stringValue) {
- count.incrementAndGet();
- this.stringValue = stringValue;
- }
-
- @V8Property(thisObjectRequired = true)
- public void setStringValueWithThis(V8ValueObject thisObject, String stringValue) throws JavetException {
- count.incrementAndGet();
- thisObject.set("stringValue", stringValue);
- }
-
@V8Function
public Integer contextScope(V8ValueFunction v8ValueFunction) throws JavetException {
assertTrue(v8ValueFunction.getJSFunctionType().isUserDefined());
@@ -96,13 +66,6 @@ public String echo(String str) {
return str;
}
- // Instance method with different name and same signature.
- @V8Function(name = "add")
- public Integer mathAdd(Integer a, Integer b) {
- count.incrementAndGet();
- return a + b;
- }
-
// Instance method with converter for non-primitive objects.
@V8Function(name = "generateArrayWithConverter")
public Object[] generateArrayWithConverter() throws JavetException {
@@ -121,6 +84,35 @@ public V8ValueArray generateArrayWithoutConverter() throws JavetException {
return v8ValueArray;
}
+ public int getCount() {
+ return count.get();
+ }
+
+ @V8Property
+ public Integer getIntegerValue() {
+ count.incrementAndGet();
+ return 123;
+ }
+
+ @V8Property
+ public String getStringValue() {
+ count.incrementAndGet();
+ return stringValue;
+ }
+
+ @V8Property(thisObjectRequired = true)
+ public String getStringValueWithThis(V8ValueObject thisObject) throws JavetException {
+ count.incrementAndGet();
+ return thisObject.getString("stringValue");
+ }
+
+ // Instance method with different name and same signature.
+ @V8Function(name = "add")
+ public Integer mathAdd(Integer a, Integer b) {
+ count.incrementAndGet();
+ return a + b;
+ }
+
// Instance method with primitive type byte
@V8Function(name = "primitiveAddByte")
public byte primitiveAddByte(byte a, byte b) {
@@ -163,13 +155,6 @@ public short primitiveAddShort(short a, short b) {
return Integer.valueOf(a + b).shortValue();
}
- // Instance method with primitive type boolean
- @V8Function(name = "primitiveRevertBoolean")
- public boolean primitiveRevertBoolean(boolean b) {
- count.incrementAndGet();
- return !b;
- }
-
// Instance method with primitive type char
@V8Function(name = "primitiveIncreaseChar")
public char primitiveIncreaseChar(char c) {
@@ -177,14 +162,29 @@ public char primitiveIncreaseChar(char c) {
return (char) ((int) c + 1);
}
+ // Instance method with primitive type boolean
+ @V8Function(name = "primitiveRevertBoolean")
+ public boolean primitiveRevertBoolean(boolean b) {
+ count.incrementAndGet();
+ return !b;
+ }
+
@V8Function(thisObjectRequired = true)
public V8ValueObject self(V8ValueObject thisObject) {
count.incrementAndGet();
return thisObject;
}
- public int getCount() {
- return count.get();
+ @V8Property
+ public void setStringValue(String stringValue) {
+ count.incrementAndGet();
+ this.stringValue = stringValue;
+ }
+
+ @V8Property(thisObjectRequired = true)
+ public void setStringValueWithThis(V8ValueObject thisObject, String stringValue) throws JavetException {
+ count.incrementAndGet();
+ thisObject.set("stringValue", stringValue);
}
// Declare the V8RuntimeSetter for dependency injection.
diff --git a/src/test/java/com/caoccao/javet/mock/MockCallbackReceiver.java b/src/test/java/com/caoccao/javet/mock/MockCallbackReceiver.java
index c0037e4f1..1b94269b0 100644
--- a/src/test/java/com/caoccao/javet/mock/MockCallbackReceiver.java
+++ b/src/test/java/com/caoccao/javet/mock/MockCallbackReceiver.java
@@ -40,14 +40,6 @@ public MockCallbackReceiver(V8Runtime v8Runtime) {
value = null;
}
- public boolean isCalled() {
- return called;
- }
-
- public void setCalled(boolean called) {
- this.called = called;
- }
-
public void blank() {
called = true;
}
@@ -58,9 +50,9 @@ public V8Value echo(V8Value arg) throws JavetException {
return super.echo(arg);
}
- public V8Value echoThis(V8Value thisObject) throws JavetException {
+ public V8ValueArray echo(V8Value... args) throws JavetException {
called = true;
- return v8Runtime.createV8ValueString(((V8ValueObject) thisObject).toJsonString());
+ return super.echo(args);
}
@Override
@@ -81,9 +73,9 @@ public String echoString(V8Value... args) {
return super.echoString(args);
}
- public V8ValueArray echo(V8Value... args) throws JavetException {
+ public V8Value echoThis(V8Value thisObject) throws JavetException {
called = true;
- return super.echo(args);
+ return v8Runtime.createV8ValueString(((V8ValueObject) thisObject).toJsonString());
}
public V8ValueString echoThis(V8Value thisObject, V8Value arg) throws JavetException {
@@ -134,9 +126,21 @@ public String getValue() {
return value;
}
- public void setValue(String value) {
+ public boolean isCalled() {
+ return called;
+ }
+
+ public String joinIntegerArrayWithThis(
+ V8ValueObject thisObject,
+ String s, Integer... integers) {
called = true;
- this.value = value;
+ List lines = new ArrayList<>();
+ lines.add(thisObject.toJsonString());
+ lines.add(s);
+ for (Integer integer : integers) {
+ lines.add(integer.toString());
+ }
+ return String.join(",", lines);
}
public String joinWithThis(
@@ -155,19 +159,6 @@ public String joinWithThis(
return String.join(",", lines);
}
- public String joinIntegerArrayWithThis(
- V8ValueObject thisObject,
- String s, Integer... integers) {
- called = true;
- List lines = new ArrayList<>();
- lines.add(thisObject.toJsonString());
- lines.add(s);
- for (Integer integer : integers) {
- lines.add(integer.toString());
- }
- return String.join(",", lines);
- }
-
public String joinWithoutThis(
Boolean b, Double d, Integer i, Long l, String s, ZonedDateTime z, V8ValueString v) {
called = true;
@@ -181,4 +172,13 @@ public String joinWithoutThis(
lines.add(v.getValue());
return String.join(",", lines);
}
+
+ public void setCalled(boolean called) {
+ this.called = called;
+ }
+
+ public void setValue(String value) {
+ called = true;
+ this.value = value;
+ }
}
diff --git a/src/test/java/com/caoccao/javet/tutorial/DecimalJavetInNodeJSMode.java b/src/test/java/com/caoccao/javet/tutorial/DecimalJavetInNodeJSMode.java
index 338bc8e7f..e5f2eaf07 100644
--- a/src/test/java/com/caoccao/javet/tutorial/DecimalJavetInNodeJSMode.java
+++ b/src/test/java/com/caoccao/javet/tutorial/DecimalJavetInNodeJSMode.java
@@ -17,10 +17,10 @@
package com.caoccao.javet.tutorial;
+import com.caoccao.javet.enums.JSRuntimeType;
import com.caoccao.javet.exceptions.JavetException;
import com.caoccao.javet.interfaces.IJavetClosable;
import com.caoccao.javet.interfaces.IJavetLogger;
-import com.caoccao.javet.enums.JSRuntimeType;
import com.caoccao.javet.interop.NodeRuntime;
import com.caoccao.javet.interop.engine.IJavetEngine;
import com.caoccao.javet.interop.engine.IJavetEnginePool;
@@ -32,8 +32,8 @@
import java.nio.file.Path;
public class DecimalJavetInNodeJSMode implements IJavetClosable {
- private IJavetEnginePool iJavetEnginePool;
private IJavetEngine iJavetEngine;
+ private IJavetEnginePool iJavetEnginePool;
public DecimalJavetInNodeJSMode() throws JavetException {
iJavetEnginePool = new JavetEnginePool<>();
@@ -52,6 +52,20 @@ public static void main(String[] args) throws JavetException {
}
}
+ @Override
+ public void close() throws JavetException {
+ if (iJavetEngine != null) {
+ iJavetEngine.close();
+ }
+ if (iJavetEnginePool != null) {
+ iJavetEnginePool.close();
+ }
+ }
+
+ public IJavetLogger getLogger() {
+ return iJavetEnginePool.getConfig().getJavetLogger();
+ }
+
public void test() throws JavetException {
NodeRuntime nodeRuntime = iJavetEngine.getV8Runtime();
Path workingDirectory = new File(JavetOSUtils.WORKING_DIRECTORY, "scripts/node/test-node").toPath();
@@ -63,18 +77,4 @@ public void test() throws JavetException {
"const b = new Decimal(2.34);" +
"a.add(b).toString();").executeString());
}
-
- public IJavetLogger getLogger() {
- return iJavetEnginePool.getConfig().getJavetLogger();
- }
-
- @Override
- public void close() throws JavetException {
- if (iJavetEngine != null) {
- iJavetEngine.close();
- }
- if (iJavetEnginePool != null) {
- iJavetEnginePool.close();
- }
- }
}
diff --git a/src/test/java/com/caoccao/javet/tutorial/DecimalJavetInV8Mode.java b/src/test/java/com/caoccao/javet/tutorial/DecimalJavetInV8Mode.java
index 4e3650a6f..e0c1f22d2 100644
--- a/src/test/java/com/caoccao/javet/tutorial/DecimalJavetInV8Mode.java
+++ b/src/test/java/com/caoccao/javet/tutorial/DecimalJavetInV8Mode.java
@@ -33,8 +33,8 @@
import java.math.BigDecimal;
public class DecimalJavetInV8Mode implements IJavetClosable {
- private IJavetEnginePool iJavetEnginePool;
private IJavetEngine iJavetEngine;
+ private IJavetEnginePool iJavetEnginePool;
public DecimalJavetInV8Mode() throws JavetException {
iJavetEnginePool = new JavetEnginePool<>();
@@ -54,6 +54,20 @@ public static void main(String[] args) throws JavetException {
}
}
+ @Override
+ public void close() throws JavetException {
+ if (iJavetEngine != null) {
+ iJavetEngine.close();
+ }
+ if (iJavetEnginePool != null) {
+ iJavetEnginePool.close();
+ }
+ }
+
+ public IJavetLogger getLogger() {
+ return iJavetEnginePool.getConfig().getJavetLogger();
+ }
+
public void loadJS() throws JavetException {
File decimalJSFile = new File(
JavetOSUtils.WORKING_DIRECTORY,
@@ -89,18 +103,4 @@ public void test() throws JavetException {
}
}
}
-
- public IJavetLogger getLogger() {
- return iJavetEnginePool.getConfig().getJavetLogger();
- }
-
- @Override
- public void close() throws JavetException {
- if (iJavetEngine != null) {
- iJavetEngine.close();
- }
- if (iJavetEnginePool != null) {
- iJavetEnginePool.close();
- }
- }
}
diff --git a/src/test/java/com/caoccao/javet/tutorial/HelloJavet.java b/src/test/java/com/caoccao/javet/tutorial/HelloJavet.java
index 333120a34..a3c767bca 100644
--- a/src/test/java/com/caoccao/javet/tutorial/HelloJavet.java
+++ b/src/test/java/com/caoccao/javet/tutorial/HelloJavet.java
@@ -35,24 +35,6 @@ public static void main(String[] args) throws JavetException {
helloJavet.playWithPoolAndConsole();
}
- public void printHelloJavet() throws JavetException {
- // Step 1: Create a V8 runtime from V8 host in try-with-resource.
- try (V8Runtime v8Runtime = V8Host.getV8Instance().createV8Runtime()) {
- // Step 2: Execute a string as JavaScript code and print the result to console.
- System.out.println(v8Runtime.getExecutor("'Hello Javet'").executeString()); // Hello Javet
- // Step 3: Resource is recycled automatically at the end of the try-with-resource block.
- }
- }
-
- public void printOnePlusOne() throws JavetException {
- // Step 1: Create a Node runtime from V8 host in try-with-resource.
- try (NodeRuntime nodeRuntime = V8Host.getNodeInstance().createV8Runtime()) {
- // Step 2: Execute a string as JavaScript code and print the result to console.
- System.out.println("1 + 1 = " + nodeRuntime.getExecutor("1 + 1").executeInteger()); // 2
- // Step 3: Resource is recycled automatically at the end of the try-with-resource block.
- }
- }
-
public void playWithPoolAndConsole() throws JavetException {
// Create a Javet engine pool.
try (IJavetEnginePool javetEnginePool = new JavetEnginePool<>()) {
@@ -75,4 +57,22 @@ public void playWithPoolAndConsole() throws JavetException {
}
}
}
+
+ public void printHelloJavet() throws JavetException {
+ // Step 1: Create a V8 runtime from V8 host in try-with-resource.
+ try (V8Runtime v8Runtime = V8Host.getV8Instance().createV8Runtime()) {
+ // Step 2: Execute a string as JavaScript code and print the result to console.
+ System.out.println(v8Runtime.getExecutor("'Hello Javet'").executeString()); // Hello Javet
+ // Step 3: Resource is recycled automatically at the end of the try-with-resource block.
+ }
+ }
+
+ public void printOnePlusOne() throws JavetException {
+ // Step 1: Create a Node runtime from V8 host in try-with-resource.
+ try (NodeRuntime nodeRuntime = V8Host.getNodeInstance().createV8Runtime()) {
+ // Step 2: Execute a string as JavaScript code and print the result to console.
+ System.out.println("1 + 1 = " + nodeRuntime.getExecutor("1 + 1").executeInteger()); // 2
+ // Step 3: Resource is recycled automatically at the end of the try-with-resource block.
+ }
+ }
}
diff --git a/src/test/java/com/caoccao/javet/tutorial/TestES6.java b/src/test/java/com/caoccao/javet/tutorial/TestES6.java
index bd7a5115c..3d72de810 100644
--- a/src/test/java/com/caoccao/javet/tutorial/TestES6.java
+++ b/src/test/java/com/caoccao/javet/tutorial/TestES6.java
@@ -20,7 +20,6 @@
import com.caoccao.javet.BaseTestJavetRuntime;
import com.caoccao.javet.exceptions.JavetException;
import com.caoccao.javet.utils.JavetOSUtils;
-import com.caoccao.javet.values.V8Value;
import com.caoccao.javet.values.reference.V8ValueArray;
import org.junit.jupiter.api.Test;
diff --git a/src/test/java/com/caoccao/javet/tutorial/TestInterception.java b/src/test/java/com/caoccao/javet/tutorial/TestInterception.java
index 897a1ca4b..08060df02 100644
--- a/src/test/java/com/caoccao/javet/tutorial/TestInterception.java
+++ b/src/test/java/com/caoccao/javet/tutorial/TestInterception.java
@@ -74,14 +74,15 @@ public static void main(String[] args) throws JavetException {
}
}
- @V8Property
- public String getName() {
- return name;
+ @V8Function
+ public int add(int delta) {
+ value += delta;
+ return value;
}
@V8Property
- public void setName(String name) {
- this.name = name;
+ public String getName() {
+ return name;
}
@V8Property
@@ -89,19 +90,18 @@ public int getValue() {
return value;
}
- @V8Property
- public void setValue(int value) {
- this.value = value;
- }
-
@V8Function
public int increaseAndGet() {
return ++value;
}
- @V8Function
- public int add(int delta) {
- value += delta;
- return value;
+ @V8Property
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @V8Property
+ public void setValue(int value) {
+ this.value = value;
}
}
diff --git a/src/test/java/com/caoccao/javet/tutorial/cdt/CDTConfig.java b/src/test/java/com/caoccao/javet/tutorial/cdt/CDTConfig.java
index 3a9095097..7220995ac 100644
--- a/src/test/java/com/caoccao/javet/tutorial/cdt/CDTConfig.java
+++ b/src/test/java/com/caoccao/javet/tutorial/cdt/CDTConfig.java
@@ -37,20 +37,20 @@ public static int getPort() {
return port;
}
+ public static V8Runtime getV8Runtime() {
+ return v8Runtime;
+ }
+
+ public static String getWebSocketUrl() {
+ return webSocketUrl;
+ }
+
public static void setPort(int port) {
CDTConfig.port = port;
webSocketUrl = "ws://127.0.0.1:" + Integer.toString(port) + PATH_JAVET;
}
- public static V8Runtime getV8Runtime() {
- return v8Runtime;
- }
-
public static void setV8Runtime(V8Runtime v8Runtime) {
CDTConfig.v8Runtime = v8Runtime;
}
-
- public static String getWebSocketUrl() {
- return webSocketUrl;
- }
}
diff --git a/src/test/java/com/caoccao/javet/utils/TestSimpleFreeMarkerFormat.java b/src/test/java/com/caoccao/javet/utils/TestSimpleFreeMarkerFormat.java
index d9c7e712e..cfb717cd8 100644
--- a/src/test/java/com/caoccao/javet/utils/TestSimpleFreeMarkerFormat.java
+++ b/src/test/java/com/caoccao/javet/utils/TestSimpleFreeMarkerFormat.java
@@ -26,47 +26,47 @@
public class TestSimpleFreeMarkerFormat {
@Test
public void testInvalid() {
- assertEquals( "abc",
+ assertEquals("abc",
SimpleFreeMarkerFormat.format("abc", null),
"Parameters being null should pass.");
- assertEquals( "abc",
+ assertEquals("abc",
SimpleFreeMarkerFormat.format("abc", new HashMap<>()),
"Parameters being empty should pass.");
- assertEquals( "abc${",
+ assertEquals("abc${",
SimpleFreeMarkerFormat.format("abc${", SimpleMap.of("d", "x")),
"Open variable should pass.");
- assertEquals( "abc${def",
+ assertEquals("abc${def",
SimpleFreeMarkerFormat.format("abc${def", SimpleMap.of("d", "x")),
"Open variable should pass.");
- assertEquals( "abc$${d}",
+ assertEquals("abc$${d}",
SimpleFreeMarkerFormat.format("abc$${d}", SimpleMap.of("d", "x")),
"Double dollar should pass.");
- assertEquals( "abcdef",
+ assertEquals("abcdef",
SimpleFreeMarkerFormat.format("abc${e}def", SimpleMap.of("d", "x")),
"Unknown variable should pass.");
- assertEquals( "abcdef",
+ assertEquals("abcdef",
SimpleFreeMarkerFormat.format("abc${}def", SimpleMap.of("d", "x")),
"Empty variable should pass.");
- assertEquals( "ab{def.$ghi}c",
+ assertEquals("ab{def.$ghi}c",
SimpleFreeMarkerFormat.format("ab{def.$ghi}c", SimpleMap.of("ghi", "x")),
"Dollar should pass.");
}
@Test
public void testValid() {
- assertEquals( "abcx",
+ assertEquals("abcx",
SimpleFreeMarkerFormat.format("abc${d}", SimpleMap.of("d", "x")),
"Variable at the end should pass.");
- assertEquals( "xabc",
+ assertEquals("xabc",
SimpleFreeMarkerFormat.format("${d}abc", SimpleMap.of("d", "x")),
"Variable at the beginning should pass.");
- assertEquals( "abxc",
+ assertEquals("abxc",
SimpleFreeMarkerFormat.format("ab${d}c", SimpleMap.of("d", "x")),
"Variable in the middle should pass.");
- assertEquals( "abxc",
+ assertEquals("abxc",
SimpleFreeMarkerFormat.format("ab${def.${ghi}c", SimpleMap.of("def.${ghi", "x")),
"Variable with dollar should pass.");
- assertEquals( "abxc",
+ assertEquals("abxc",
SimpleFreeMarkerFormat.format("ab${{}c", SimpleMap.of("{", "x")),
"Single open should pass.");
}
diff --git a/src/test/java/com/caoccao/javet/values/primitive/TestV8ValueDouble.java b/src/test/java/com/caoccao/javet/values/primitive/TestV8ValueDouble.java
index 34b36ea72..c75ababde 100644
--- a/src/test/java/com/caoccao/javet/values/primitive/TestV8ValueDouble.java
+++ b/src/test/java/com/caoccao/javet/values/primitive/TestV8ValueDouble.java
@@ -22,7 +22,6 @@
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
-import static org.junit.jupiter.api.Assertions.assertFalse;
public class TestV8ValueDouble extends BaseTestJavetRuntime {
public static final double DELTA = 0.001;
diff --git a/src/test/java/com/caoccao/javet/values/primitive/TestV8ValueInteger.java b/src/test/java/com/caoccao/javet/values/primitive/TestV8ValueInteger.java
index 6f88ffffd..5a3153677 100644
--- a/src/test/java/com/caoccao/javet/values/primitive/TestV8ValueInteger.java
+++ b/src/test/java/com/caoccao/javet/values/primitive/TestV8ValueInteger.java
@@ -22,7 +22,6 @@
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
-import static org.junit.jupiter.api.Assertions.assertFalse;
public class TestV8ValueInteger extends BaseTestJavetRuntime {
@Test
diff --git a/src/test/java/com/caoccao/javet/values/primitive/TestV8ValueString.java b/src/test/java/com/caoccao/javet/values/primitive/TestV8ValueString.java
index 66628908b..9ca0d8506 100644
--- a/src/test/java/com/caoccao/javet/values/primitive/TestV8ValueString.java
+++ b/src/test/java/com/caoccao/javet/values/primitive/TestV8ValueString.java
@@ -22,7 +22,6 @@
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
-import static org.junit.jupiter.api.Assertions.assertFalse;
public class TestV8ValueString extends BaseTestJavetRuntime {
@Test
diff --git a/src/test/java/com/caoccao/javet/values/reference/TestV8Module.java b/src/test/java/com/caoccao/javet/values/reference/TestV8Module.java
index 489d0c8e4..aa2826222 100644
--- a/src/test/java/com/caoccao/javet/values/reference/TestV8Module.java
+++ b/src/test/java/com/caoccao/javet/values/reference/TestV8Module.java
@@ -50,45 +50,6 @@ public void testExecute() throws JavetException {
}
}
- @Test
- public void testImportValidModuleAndExecute() throws JavetException {
- String codeString = "export function test() { return { a: 1 }; };";
- IV8Executor iV8Executor = v8Runtime.getExecutor(codeString).setResourceName("./test.js");
- try (V8Module v8Module = iV8Executor.compileV8Module()) {
- if (v8Runtime.getJSRuntimeType().isNode()) {
- v8Runtime.getExecutor("const process = require('process');\n" +
- "var globalReason = null;\n" +
- "process.on('unhandledRejection', (reason, promise) => {\n" +
- " globalReason = reason;\n" +
- "});").executeVoid();
- }
- try (V8ValuePromise v8ValuePromise = v8Module.execute()) {
- assertTrue(v8ValuePromise.isFulfilled());
- assertTrue(v8ValuePromise.getResult().isUndefined());
- }
- // Import in module is supported.
- codeString = "import { test } from './test.js'; test();";
- iV8Executor = v8Runtime.getExecutor(codeString).setResourceName("./a.js").setModule(true);
- try (V8ValueObject v8ValueObject = iV8Executor.execute()) {
- assertNotNull(v8ValueObject);
- V8ValuePromise v8ValuePromise = (V8ValuePromise) v8ValueObject;
- assertTrue(v8ValuePromise.isFulfilled());
- assertTrue(v8ValuePromise.getResult().isUndefined());
- if (v8Runtime.getJSRuntimeType().isV8()) {
- assertFalse(v8Runtime.containsV8Module("./a.js"));
- }
- }
- // V8: Dynamic import is not supported.
- // Node: UnhandledPromiseRejectionWarning: TypeError: Invalid host defined options.
- codeString = "const p = import('./test.js'); p;";
- iV8Executor = v8Runtime.getExecutor(codeString).setResourceName("./a.js").setModule(false);
- try (V8ValuePromise v8ValuePromise = iV8Executor.execute()) {
- assertNotNull(v8ValuePromise);
- assertTrue(v8ValuePromise.isRejected());
- }
- }
- }
-
@Test
public void testImportInvalidModuleInModule() throws JavetException {
String codeString1 = "export function test1() {\n" +
@@ -136,6 +97,45 @@ public void testImportInvalidModuleInModule() throws JavetException {
}
}
+ @Test
+ public void testImportValidModuleAndExecute() throws JavetException {
+ String codeString = "export function test() { return { a: 1 }; };";
+ IV8Executor iV8Executor = v8Runtime.getExecutor(codeString).setResourceName("./test.js");
+ try (V8Module v8Module = iV8Executor.compileV8Module()) {
+ if (v8Runtime.getJSRuntimeType().isNode()) {
+ v8Runtime.getExecutor("const process = require('process');\n" +
+ "var globalReason = null;\n" +
+ "process.on('unhandledRejection', (reason, promise) => {\n" +
+ " globalReason = reason;\n" +
+ "});").executeVoid();
+ }
+ try (V8ValuePromise v8ValuePromise = v8Module.execute()) {
+ assertTrue(v8ValuePromise.isFulfilled());
+ assertTrue(v8ValuePromise.getResult().isUndefined());
+ }
+ // Import in module is supported.
+ codeString = "import { test } from './test.js'; test();";
+ iV8Executor = v8Runtime.getExecutor(codeString).setResourceName("./a.js").setModule(true);
+ try (V8ValueObject v8ValueObject = iV8Executor.execute()) {
+ assertNotNull(v8ValueObject);
+ V8ValuePromise v8ValuePromise = (V8ValuePromise) v8ValueObject;
+ assertTrue(v8ValuePromise.isFulfilled());
+ assertTrue(v8ValuePromise.getResult().isUndefined());
+ if (v8Runtime.getJSRuntimeType().isV8()) {
+ assertFalse(v8Runtime.containsV8Module("./a.js"));
+ }
+ }
+ // V8: Dynamic import is not supported.
+ // Node: UnhandledPromiseRejectionWarning: TypeError: Invalid host defined options.
+ codeString = "const p = import('./test.js'); p;";
+ iV8Executor = v8Runtime.getExecutor(codeString).setResourceName("./a.js").setModule(false);
+ try (V8ValuePromise v8ValuePromise = iV8Executor.execute()) {
+ assertNotNull(v8ValuePromise);
+ assertTrue(v8ValuePromise.isRejected());
+ }
+ }
+ }
+
@Test
public void testImportValidModuleInModule() throws JavetException {
String codeString1 = "export function test1() {\n" +
diff --git a/src/test/java/com/caoccao/javet/values/reference/TestV8ValueArguments.java b/src/test/java/com/caoccao/javet/values/reference/TestV8ValueArguments.java
index 23e79b10d..5182bb476 100644
--- a/src/test/java/com/caoccao/javet/values/reference/TestV8ValueArguments.java
+++ b/src/test/java/com/caoccao/javet/values/reference/TestV8ValueArguments.java
@@ -17,8 +17,8 @@
package com.caoccao.javet.values.reference;
-import com.caoccao.javet.exceptions.JavetException;
import com.caoccao.javet.BaseTestJavetRuntime;
+import com.caoccao.javet.exceptions.JavetException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
diff --git a/src/test/java/com/caoccao/javet/values/reference/TestV8ValueArray.java b/src/test/java/com/caoccao/javet/values/reference/TestV8ValueArray.java
index 2834b77db..1cb1f6ded 100644
--- a/src/test/java/com/caoccao/javet/values/reference/TestV8ValueArray.java
+++ b/src/test/java/com/caoccao/javet/values/reference/TestV8ValueArray.java
@@ -42,31 +42,6 @@ public void testForEach() throws JavetException {
}
}
- @Test
- public void testGetAndSet() throws JavetException {
- try (V8ValueArray v8ValueArray = v8Runtime.getExecutor("const a = new Array(); a;").execute()) {
- v8ValueArray.set(0, "x");
- v8ValueArray.set(1, "y");
- v8ValueArray.set(2, "z");
- v8ValueArray.set("a", 1);
- v8ValueArray.set("b", "2");
- assertEquals(3, v8ValueArray.getLength());
- assertEquals("x", v8ValueArray.getString(0));
- assertEquals("y", v8ValueArray.getString(1));
- assertEquals("z", v8ValueArray.getString(2));
- assertEquals(1, v8ValueArray.getInteger("a"));
- assertEquals("2", v8ValueArray.getString("b"));
- assertEquals("x,y,z", v8ValueArray.toString());
- assertEquals("[object Array]", v8ValueArray.toProtoString());
- assertEquals("[\"x\",\"y\",\"z\"]", v8ValueArray.toJsonString());
- List keys = v8ValueArray.getKeys();
- assertEquals(3, keys.size());
- assertEquals(0, keys.get(0));
- assertEquals(1, keys.get(1));
- assertEquals(2, keys.get(2));
- }
- }
-
@Test
public void testGet() throws JavetException {
try (V8ValueArray v8ValueArray = v8Runtime.getExecutor(
@@ -103,6 +78,31 @@ public void testGet() throws JavetException {
}
}
+ @Test
+ public void testGetAndSet() throws JavetException {
+ try (V8ValueArray v8ValueArray = v8Runtime.getExecutor("const a = new Array(); a;").execute()) {
+ v8ValueArray.set(0, "x");
+ v8ValueArray.set(1, "y");
+ v8ValueArray.set(2, "z");
+ v8ValueArray.set("a", 1);
+ v8ValueArray.set("b", "2");
+ assertEquals(3, v8ValueArray.getLength());
+ assertEquals("x", v8ValueArray.getString(0));
+ assertEquals("y", v8ValueArray.getString(1));
+ assertEquals("z", v8ValueArray.getString(2));
+ assertEquals(1, v8ValueArray.getInteger("a"));
+ assertEquals("2", v8ValueArray.getString("b"));
+ assertEquals("x,y,z", v8ValueArray.toString());
+ assertEquals("[object Array]", v8ValueArray.toProtoString());
+ assertEquals("[\"x\",\"y\",\"z\"]", v8ValueArray.toJsonString());
+ List keys = v8ValueArray.getKeys();
+ assertEquals(3, keys.size());
+ assertEquals(0, keys.get(0));
+ assertEquals(1, keys.get(1));
+ assertEquals(2, keys.get(2));
+ }
+ }
+
@Test
public void testNestedArray() throws JavetException {
try (V8ValueArray outerArray = v8Runtime.getExecutor("[1,2,3]").execute()) {
diff --git a/src/test/java/com/caoccao/javet/values/reference/TestV8ValueError.java b/src/test/java/com/caoccao/javet/values/reference/TestV8ValueError.java
index 47c4236f5..91c5bd7ef 100644
--- a/src/test/java/com/caoccao/javet/values/reference/TestV8ValueError.java
+++ b/src/test/java/com/caoccao/javet/values/reference/TestV8ValueError.java
@@ -17,8 +17,8 @@
package com.caoccao.javet.values.reference;
-import com.caoccao.javet.exceptions.JavetException;
import com.caoccao.javet.BaseTestJavetRuntime;
+import com.caoccao.javet.exceptions.JavetException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
diff --git a/src/test/java/com/caoccao/javet/values/reference/TestV8ValueFunction.java b/src/test/java/com/caoccao/javet/values/reference/TestV8ValueFunction.java
index 397c8e179..a500b1fe5 100644
--- a/src/test/java/com/caoccao/javet/values/reference/TestV8ValueFunction.java
+++ b/src/test/java/com/caoccao/javet/values/reference/TestV8ValueFunction.java
@@ -112,7 +112,7 @@ public void testAnnotationBasedFunctions() throws JavetException {
assertEquals(String.valueOf((char) 1), v8Runtime.getExecutor("a.primitiveIncreaseChar(undefined)").executeString());
v8Runtime.getGlobalObject().delete("a");
}
- v8Runtime.requestGarbageCollectionForTesting(true);
+ v8Runtime.lowMemoryNotification();
}
@Test
@@ -137,7 +137,7 @@ public void testAnnotationBasedFunctionsAndProperties() throws JavetException {
assertEquals(4, mockAnnotationBasedCallbackReceiver.getCount());
v8Runtime.getGlobalObject().delete("a");
}
- v8Runtime.requestGarbageCollectionForTesting(true);
+ v8Runtime.lowMemoryNotification();
}
@Test
@@ -158,7 +158,7 @@ public void testAnonymousFunction() throws JavetException {
assertEquals(2, v8Runtime.getExecutor("b(1);").executeInteger());
v8Runtime.getGlobalObject().delete("a");
v8Runtime.getGlobalObject().delete("b");
- v8Runtime.requestGarbageCollectionForTesting(true);
+ v8Runtime.lowMemoryNotification();
}
@Test
@@ -174,28 +174,48 @@ public void testArrayPush() throws JavetException {
assertEquals(1, v8ValueArray.getLength());
assertEquals("x", v8ValueArray.toString());
}
- v8Runtime.requestGarbageCollectionForTesting(true);
+ v8Runtime.lowMemoryNotification();
}
@Test
- public void testCallbackBlankWithoutThis() throws JavetException, NoSuchMethodException {
+ public void testCallObject() throws JavetException {
+ String prefixString = "const x = 1; ";
+ String functionName = "function a";
+ String suffixString = " const y = 2;";
+ String codeString = "(b) { return [1,2,3].concat(b); }";
+ v8Runtime.getExecutor(prefixString + functionName + codeString + suffixString).executeVoid();
+ try (V8ValueFunction v8ValueFunction = v8Runtime.getGlobalObject().get("a")) {
+ assertTrue(v8ValueFunction.getJSFunctionType().isUserDefined());
+ assertEquals(functionName + codeString, v8ValueFunction.toString());
+ assertEquals(codeString, v8ValueFunction.getSourceCode());
+ List result = v8ValueFunction.callObject(null, (Object) (new Integer[]{4, 5, 6}));
+ assertArrayEquals(
+ new Integer[]{1, 2, 3, 4, 5, 6},
+ result.toArray(new Integer[0]),
+ "callObject() should work transparently without resource leak");
+ }
+ }
+
+ @Test
+ public void testCallbackBlankWithThis() throws JavetException, NoSuchMethodException {
MockCallbackReceiver mockCallbackReceiver = new MockCallbackReceiver(v8Runtime);
JavetCallbackContext javetCallbackContext = new JavetCallbackContext(
- mockCallbackReceiver, mockCallbackReceiver.getMethod("blank"));
+ mockCallbackReceiver, mockCallbackReceiver.getMethod("echoThis", true), true);
V8ValueObject globalObject = v8Runtime.getGlobalObject();
V8ValueFunction v8ValueFunction = v8Runtime.createV8ValueFunction(javetCallbackContext);
try (V8ValueObject a = v8Runtime.createV8ValueObject()) {
globalObject.set("a", a);
- a.set("blank", v8ValueFunction);
+ a.set("x", "1");
+ a.set("echoThis", v8ValueFunction);
assertFalse(mockCallbackReceiver.isCalled());
- v8Runtime.getExecutor("a.blank();").executeVoid();
+ assertEquals("{\"x\":\"1\"}", v8Runtime.getExecutor("a.echoThis();").executeString());
assertTrue(mockCallbackReceiver.isCalled());
v8ValueFunction.setWeak();
- a.delete("blank");
+ a.delete("echoThis");
globalObject.delete("a");
}
assertEquals(1, v8Runtime.getReferenceCount());
- v8Runtime.requestGarbageCollectionForTesting(true);
+ v8Runtime.lowMemoryNotification();
assertEquals(0, v8Runtime.getReferenceCount());
try {
v8ValueFunction.close();
@@ -205,25 +225,24 @@ public void testCallbackBlankWithoutThis() throws JavetException, NoSuchMethodEx
}
@Test
- public void testCallbackBlankWithThis() throws JavetException, NoSuchMethodException {
+ public void testCallbackBlankWithoutThis() throws JavetException, NoSuchMethodException {
MockCallbackReceiver mockCallbackReceiver = new MockCallbackReceiver(v8Runtime);
JavetCallbackContext javetCallbackContext = new JavetCallbackContext(
- mockCallbackReceiver, mockCallbackReceiver.getMethod("echoThis", true), true);
+ mockCallbackReceiver, mockCallbackReceiver.getMethod("blank"));
V8ValueObject globalObject = v8Runtime.getGlobalObject();
V8ValueFunction v8ValueFunction = v8Runtime.createV8ValueFunction(javetCallbackContext);
try (V8ValueObject a = v8Runtime.createV8ValueObject()) {
globalObject.set("a", a);
- a.set("x", "1");
- a.set("echoThis", v8ValueFunction);
+ a.set("blank", v8ValueFunction);
assertFalse(mockCallbackReceiver.isCalled());
- assertEquals("{\"x\":\"1\"}", v8Runtime.getExecutor("a.echoThis();").executeString());
+ v8Runtime.getExecutor("a.blank();").executeVoid();
assertTrue(mockCallbackReceiver.isCalled());
v8ValueFunction.setWeak();
- a.delete("echoThis");
+ a.delete("blank");
globalObject.delete("a");
}
assertEquals(1, v8Runtime.getReferenceCount());
- v8Runtime.requestGarbageCollectionForTesting(true);
+ v8Runtime.lowMemoryNotification();
assertEquals(0, v8Runtime.getReferenceCount());
try {
v8ValueFunction.close();
@@ -232,6 +251,35 @@ public void testCallbackBlankWithThis() throws JavetException, NoSuchMethodExcep
}
}
+ @Test
+ public void testCallbackEchoLILOWithThis() throws JavetException, NoSuchMethodException {
+ assertEquals(0, v8Runtime.getReferenceCount());
+ MockCallbackReceiver mockCallbackReceiver = new MockCallbackReceiver(v8Runtime);
+ JavetCallbackContext javetCallbackContext = new JavetCallbackContext(
+ mockCallbackReceiver, mockCallbackReceiver.getMethodVarargs("echoThis", true), true);
+ V8ValueObject globalObject = v8Runtime.getGlobalObject();
+ try (V8ValueFunction v8ValueFunction = v8Runtime.createV8ValueFunction(javetCallbackContext)) {
+ assertEquals(1, v8Runtime.getReferenceCount());
+ globalObject.set("x", "1");
+ globalObject.set("echoThis", v8ValueFunction);
+ assertFalse(mockCallbackReceiver.isCalled());
+ try (V8ValueArray v8ValueArray = v8Runtime.getExecutor("var a = echoThis(1, '2', 3n); a;").execute()) {
+ assertEquals(2, v8Runtime.getReferenceCount());
+ assertEquals(4, v8ValueArray.getLength());
+ try (V8ValueObject v8ValueObject = v8ValueArray.get(0)) {
+ assertEquals("1", v8ValueObject.getString("x"));
+ }
+ assertEquals(1, v8ValueArray.getInteger(1));
+ assertEquals("2", v8ValueArray.getString(2));
+ assertEquals(3L, v8ValueArray.getLong(3));
+ }
+ assertTrue(globalObject.hasOwnProperty("a"));
+ assertTrue(mockCallbackReceiver.isCalled());
+ globalObject.delete("echoThis");
+ }
+ v8Runtime.lowMemoryNotification();
+ }
+
@Test
public void testCallbackEchoLILOWithoutThis() throws JavetException, NoSuchMethodException {
assertEquals(0, v8Runtime.getReferenceCount());
@@ -253,36 +301,32 @@ public void testCallbackEchoLILOWithoutThis() throws JavetException, NoSuchMetho
assertTrue(mockCallbackReceiver.isCalled());
globalObject.delete("echo");
}
- v8Runtime.requestGarbageCollectionForTesting(true);
+ v8Runtime.lowMemoryNotification();
}
@Test
- public void testCallbackEchoLILOWithThis() throws JavetException, NoSuchMethodException {
+ public void testCallbackEchoStringWithThis() throws JavetException, NoSuchMethodException {
assertEquals(0, v8Runtime.getReferenceCount());
MockCallbackReceiver mockCallbackReceiver = new MockCallbackReceiver(v8Runtime);
JavetCallbackContext javetCallbackContext = new JavetCallbackContext(
- mockCallbackReceiver, mockCallbackReceiver.getMethodVarargs("echoThis", true), true);
+ mockCallbackReceiver, mockCallbackReceiver.getMethod("echoThisString", V8Value.class, String.class), true);
V8ValueObject globalObject = v8Runtime.getGlobalObject();
try (V8ValueFunction v8ValueFunction = v8Runtime.createV8ValueFunction(javetCallbackContext)) {
assertEquals(1, v8Runtime.getReferenceCount());
- globalObject.set("x", "1");
- globalObject.set("echoThis", v8ValueFunction);
+ try (V8ValueObject a = v8Runtime.createV8ValueObject()) {
+ a.set("x", "1");
+ a.set("echoThisString", v8ValueFunction);
+ globalObject.set("a", a);
+ }
assertFalse(mockCallbackReceiver.isCalled());
- try (V8ValueArray v8ValueArray = v8Runtime.getExecutor("var a = echoThis(1, '2', 3n); a;").execute()) {
- assertEquals(2, v8Runtime.getReferenceCount());
- assertEquals(4, v8ValueArray.getLength());
- try (V8ValueObject v8ValueObject = v8ValueArray.get(0)) {
- assertEquals("1", v8ValueObject.getString("x"));
- }
- assertEquals(1, v8ValueArray.getInteger(1));
- assertEquals("2", v8ValueArray.getString(2));
- assertEquals(3L, v8ValueArray.getLong(3));
+ try (V8ValueString v8ValueString = v8Runtime.getExecutor(
+ "const x = a.echoThisString('123'); x;").execute()) {
+ assertEquals("[{\"x\":\"1\"},\"123\"]", v8ValueString.getValue());
}
- assertTrue(globalObject.hasOwnProperty("a"));
- assertTrue(mockCallbackReceiver.isCalled());
- globalObject.delete("echoThis");
+ globalObject.delete("a");
}
- v8Runtime.requestGarbageCollectionForTesting(true);
+ assertTrue(mockCallbackReceiver.isCalled());
+ v8Runtime.lowMemoryNotification();
}
@Test
@@ -307,32 +351,31 @@ public void testCallbackEchoStringWithoutThis() throws JavetException, NoSuchMet
assertEquals("abc,def", v8Runtime.getExecutor("echoString('abc', 'def')").executeString());
assertEquals("", v8Runtime.getExecutor("echoString()").executeString());
globalObject.delete("echoString");
- v8Runtime.requestGarbageCollectionForTesting(true);
+ v8Runtime.lowMemoryNotification();
}
@Test
- public void testCallbackEchoStringWithThis() throws JavetException, NoSuchMethodException {
+ public void testCallbackEchoVIVOWithThis() throws JavetException, NoSuchMethodException {
assertEquals(0, v8Runtime.getReferenceCount());
MockCallbackReceiver mockCallbackReceiver = new MockCallbackReceiver(v8Runtime);
JavetCallbackContext javetCallbackContext = new JavetCallbackContext(
- mockCallbackReceiver, mockCallbackReceiver.getMethod("echoThisString", V8Value.class, String.class), true);
+ mockCallbackReceiver, mockCallbackReceiver.getMethod("echoThis", V8Value.class, V8Value.class), true);
V8ValueObject globalObject = v8Runtime.getGlobalObject();
try (V8ValueFunction v8ValueFunction = v8Runtime.createV8ValueFunction(javetCallbackContext)) {
assertEquals(1, v8Runtime.getReferenceCount());
try (V8ValueObject a = v8Runtime.createV8ValueObject()) {
a.set("x", "1");
- a.set("echoThisString", v8ValueFunction);
+ a.set("echoThis", v8ValueFunction);
globalObject.set("a", a);
}
assertFalse(mockCallbackReceiver.isCalled());
- try (V8ValueString v8ValueString = v8Runtime.getExecutor(
- "const x = a.echoThisString('123'); x;").execute()) {
+ try (V8ValueString v8ValueString = v8Runtime.getExecutor("const x = a.echoThis('123'); x;").execute()) {
assertEquals("[{\"x\":\"1\"},\"123\"]", v8ValueString.getValue());
}
globalObject.delete("a");
}
assertTrue(mockCallbackReceiver.isCalled());
- v8Runtime.requestGarbageCollectionForTesting(true);
+ v8Runtime.lowMemoryNotification();
}
@Test
@@ -353,31 +396,7 @@ public void testCallbackEchoVIVOWithoutThis() throws JavetException, NoSuchMetho
}
assertTrue(mockCallbackReceiver.isCalled());
assertTrue(globalObject.get("a").isUndefined());
- v8Runtime.requestGarbageCollectionForTesting(true);
- }
-
- @Test
- public void testCallbackEchoVIVOWithThis() throws JavetException, NoSuchMethodException {
- assertEquals(0, v8Runtime.getReferenceCount());
- MockCallbackReceiver mockCallbackReceiver = new MockCallbackReceiver(v8Runtime);
- JavetCallbackContext javetCallbackContext = new JavetCallbackContext(
- mockCallbackReceiver, mockCallbackReceiver.getMethod("echoThis", V8Value.class, V8Value.class), true);
- V8ValueObject globalObject = v8Runtime.getGlobalObject();
- try (V8ValueFunction v8ValueFunction = v8Runtime.createV8ValueFunction(javetCallbackContext)) {
- assertEquals(1, v8Runtime.getReferenceCount());
- try (V8ValueObject a = v8Runtime.createV8ValueObject()) {
- a.set("x", "1");
- a.set("echoThis", v8ValueFunction);
- globalObject.set("a", a);
- }
- assertFalse(mockCallbackReceiver.isCalled());
- try (V8ValueString v8ValueString = v8Runtime.getExecutor("const x = a.echoThis('123'); x;").execute()) {
- assertEquals("[{\"x\":\"1\"},\"123\"]", v8ValueString.getValue());
- }
- globalObject.delete("a");
- }
- assertTrue(mockCallbackReceiver.isCalled());
- v8Runtime.requestGarbageCollectionForTesting(true);
+ v8Runtime.lowMemoryNotification();
}
@Test
@@ -403,18 +422,17 @@ public void testCallbackError() throws JavetException, NoSuchMethodException {
}
globalObject.delete("testError");
mockCallbackReceiver.setCalled(false);
- v8Runtime.requestGarbageCollectionForTesting(true);
+ v8Runtime.lowMemoryNotification();
}
@Test
- public void testCallbackJoinWithThis() throws JavetException, NoSuchMethodException {
+ public void testCallbackJoinIntegerArrayWithThis() throws JavetException, NoSuchMethodException {
assertEquals(0, v8Runtime.getReferenceCount());
MockCallbackReceiver mockCallbackReceiver = new MockCallbackReceiver(v8Runtime);
JavetCallbackContext javetCallbackContext = new JavetCallbackContext(
mockCallbackReceiver,
- mockCallbackReceiver.getMethod("joinWithThis",
- V8ValueObject.class, Boolean.class, Double.class, Integer.class, Long.class,
- String.class, ZonedDateTime.class, V8ValueString.class),
+ mockCallbackReceiver.getMethod(
+ "joinIntegerArrayWithThis", V8ValueObject.class, String.class, Integer[].class),
true);
V8ValueObject globalObject = v8Runtime.getGlobalObject();
try (V8ValueFunction v8ValueFunction = v8Runtime.createV8ValueFunction(javetCallbackContext)) {
@@ -422,26 +440,27 @@ public void testCallbackJoinWithThis() throws JavetException, NoSuchMethodExcept
try (V8ValueObject x = v8Runtime.createV8ValueObject()) {
globalObject.set("x", x);
x.set("p", "q");
- x.set("joinWithThis", v8ValueFunction);
+ x.set("joinIntegerArrayWithThis", v8ValueFunction);
}
assertFalse(mockCallbackReceiver.isCalled());
String resultString = v8Runtime.getExecutor(
- "const a = x.joinWithThis(true, 1.23, 2, 3n, '4', new Date(1611710223719), '6'); a;").executeString();
- assertEquals("{\"p\":\"q\"},true,1.23,2,3,4,2021-01-27T01:17:03.719Z[UTC],6", resultString);
+ "const a = x.joinIntegerArrayWithThis('x', 1, 2, 3); a;").executeString();
+ assertEquals("{\"p\":\"q\"},x,1,2,3", resultString);
globalObject.delete("x");
}
assertTrue(mockCallbackReceiver.isCalled());
- v8Runtime.requestGarbageCollectionForTesting(true);
+ v8Runtime.lowMemoryNotification();
}
@Test
- public void testCallbackJoinIntegerArrayWithThis() throws JavetException, NoSuchMethodException {
+ public void testCallbackJoinWithThis() throws JavetException, NoSuchMethodException {
assertEquals(0, v8Runtime.getReferenceCount());
MockCallbackReceiver mockCallbackReceiver = new MockCallbackReceiver(v8Runtime);
JavetCallbackContext javetCallbackContext = new JavetCallbackContext(
mockCallbackReceiver,
- mockCallbackReceiver.getMethod(
- "joinIntegerArrayWithThis", V8ValueObject.class, String.class, Integer[].class),
+ mockCallbackReceiver.getMethod("joinWithThis",
+ V8ValueObject.class, Boolean.class, Double.class, Integer.class, Long.class,
+ String.class, ZonedDateTime.class, V8ValueString.class),
true);
V8ValueObject globalObject = v8Runtime.getGlobalObject();
try (V8ValueFunction v8ValueFunction = v8Runtime.createV8ValueFunction(javetCallbackContext)) {
@@ -449,16 +468,16 @@ public void testCallbackJoinIntegerArrayWithThis() throws JavetException, NoSuch
try (V8ValueObject x = v8Runtime.createV8ValueObject()) {
globalObject.set("x", x);
x.set("p", "q");
- x.set("joinIntegerArrayWithThis", v8ValueFunction);
+ x.set("joinWithThis", v8ValueFunction);
}
assertFalse(mockCallbackReceiver.isCalled());
String resultString = v8Runtime.getExecutor(
- "const a = x.joinIntegerArrayWithThis('x', 1, 2, 3); a;").executeString();
- assertEquals("{\"p\":\"q\"},x,1,2,3", resultString);
+ "const a = x.joinWithThis(true, 1.23, 2, 3n, '4', new Date(1611710223719), '6'); a;").executeString();
+ assertEquals("{\"p\":\"q\"},true,1.23,2,3,4,2021-01-27T01:17:03.719Z[UTC],6", resultString);
globalObject.delete("x");
}
assertTrue(mockCallbackReceiver.isCalled());
- v8Runtime.requestGarbageCollectionForTesting(true);
+ v8Runtime.lowMemoryNotification();
}
@Test
@@ -481,26 +500,7 @@ public void testCallbackJoinWithoutThis() throws JavetException, NoSuchMethodExc
globalObject.delete("joinWithoutThis");
}
assertTrue(mockCallbackReceiver.isCalled());
- v8Runtime.requestGarbageCollectionForTesting(true);
- }
-
- @Test
- public void testCallObject() throws JavetException {
- String prefixString = "const x = 1; ";
- String functionName = "function a";
- String suffixString = " const y = 2;";
- String codeString = "(b) { return [1,2,3].concat(b); }";
- v8Runtime.getExecutor(prefixString + functionName + codeString + suffixString).executeVoid();
- try (V8ValueFunction v8ValueFunction = v8Runtime.getGlobalObject().get("a")) {
- assertTrue(v8ValueFunction.getJSFunctionType().isUserDefined());
- assertEquals(functionName + codeString, v8ValueFunction.toString());
- assertEquals(codeString, v8ValueFunction.getSourceCode());
- List result = v8ValueFunction.callObject(null, (Object) (new Integer[]{4, 5, 6}));
- assertArrayEquals(
- new Integer[]{1, 2, 3, 4, 5, 6},
- result.toArray(new Integer[0]),
- "callObject() should work transparently without resource leak");
- }
+ v8Runtime.lowMemoryNotification();
}
@Test
@@ -529,7 +529,7 @@ public void testContextScope() throws JavetException {
e.printStackTrace();
fail(e.getScriptingError().toString());
}
- v8Runtime.requestGarbageCollectionForTesting(true);
+ v8Runtime.lowMemoryNotification();
}
/**
@@ -611,7 +611,7 @@ public void testPropertyGetter() throws NoSuchMethodException, JavetException {
assertTrue(mockCallbackReceiver.isCalled());
globalObject.delete("a");
}
- v8Runtime.requestGarbageCollectionForTesting(true);
+ v8Runtime.lowMemoryNotification();
}
@Test
@@ -646,6 +646,6 @@ public void testPropertyGetterAndSetter() throws NoSuchMethodException, JavetExc
assertTrue(mockCallbackReceiver.isCalled());
globalObject.delete("a");
}
- v8Runtime.requestGarbageCollectionForTesting(true);
+ v8Runtime.lowMemoryNotification();
}
}
diff --git a/src/test/java/com/caoccao/javet/values/reference/TestV8ValueObject.java b/src/test/java/com/caoccao/javet/values/reference/TestV8ValueObject.java
index dd8ea772f..4cb0f991c 100644
--- a/src/test/java/com/caoccao/javet/values/reference/TestV8ValueObject.java
+++ b/src/test/java/com/caoccao/javet/values/reference/TestV8ValueObject.java
@@ -65,7 +65,7 @@ public void testAnnotationBasedProperties() throws JavetException {
assertEquals(10, mockAnnotationBasedCallbackReceiver.getCount());
v8Runtime.getGlobalObject().delete("a");
}
- v8Runtime.requestGarbageCollectionForTesting(true);
+ v8Runtime.lowMemoryNotification();
}
@Test
@@ -90,29 +90,6 @@ public void testClearWeak() throws JavetException {
}
}
- @Test
- public void testForEach() throws JavetException {
- try (V8ValueObject v8ValueObject = v8Runtime.getExecutor(
- "const a = {'A0': 0, 'A1': 1, 'A2': 2}; a;").execute()) {
- AtomicInteger count = new AtomicInteger(0);
- assertEquals(3, v8ValueObject.forEach((V8ValueString key) -> {
- assertEquals("A" + Integer.toString(count.getAndIncrement()), key.getValue());
- }));
- count.set(0);
- assertEquals(3, v8ValueObject.forEach((V8ValueString key, V8ValueInteger value) -> {
- assertEquals("A" + Integer.toString(count.get()), key.getValue());
- assertEquals(count.getAndIncrement(), value.getValue());
- }));
- assertEquals(3, v8ValueObject.forEach((int index, V8ValueString key) -> {
- assertEquals("A" + Integer.toString(index), key.getValue());
- }));
- assertEquals(3, v8ValueObject.forEach((int index, V8ValueString key, V8ValueInteger value) -> {
- assertEquals("A" + Integer.toString(index), key.getValue());
- assertEquals(index, value.getValue());
- }));
- }
- }
-
@Test
public void testEquals() throws JavetException {
try (V8ValueObject v8ValueObject1 = v8Runtime.getExecutor(
@@ -136,29 +113,33 @@ public void testEquals() throws JavetException {
}
@Test
- public void testGetOwnPropertyNames() throws JavetException {
+ public void testForEach() throws JavetException {
try (V8ValueObject v8ValueObject = v8Runtime.getExecutor(
- "let x = {'a': 1, 'b': '2', 'c': 3n, d: 1, e: null, g: {h: 1}, '中文': '測試'}; x;").execute()) {
- try (IV8ValueArray iV8ValueArray = v8ValueObject.getOwnPropertyNames()) {
- assertNotNull(iV8ValueArray);
- assertEquals(7, iV8ValueArray.getLength());
- // Order is preserved since ES2015.
- assertEquals("a", iV8ValueArray.getPropertyString(0));
- assertEquals("b", iV8ValueArray.getPropertyString(1));
- assertEquals("c", iV8ValueArray.getPropertyString(2));
- assertEquals("d", iV8ValueArray.getPropertyString(3));
- assertEquals("e", iV8ValueArray.getPropertyString(4));
- assertEquals("g", iV8ValueArray.getPropertyString(5));
- assertEquals("中文", iV8ValueArray.getPropertyString(6));
- }
+ "const a = {'A0': 0, 'A1': 1, 'A2': 2}; a;").execute()) {
+ AtomicInteger count = new AtomicInteger(0);
+ assertEquals(3, v8ValueObject.forEach((V8ValueString key) -> {
+ assertEquals("A" + Integer.toString(count.getAndIncrement()), key.getValue());
+ }));
+ count.set(0);
+ assertEquals(3, v8ValueObject.forEach((V8ValueString key, V8ValueInteger value) -> {
+ assertEquals("A" + Integer.toString(count.get()), key.getValue());
+ assertEquals(count.getAndIncrement(), value.getValue());
+ }));
+ assertEquals(3, v8ValueObject.forEach((int index, V8ValueString key) -> {
+ assertEquals("A" + Integer.toString(index), key.getValue());
+ }));
+ assertEquals(3, v8ValueObject.forEach((int index, V8ValueString key, V8ValueInteger value) -> {
+ assertEquals("A" + Integer.toString(index), key.getValue());
+ assertEquals(index, value.getValue());
+ }));
}
}
@Test
- public void testGetPropertyNames() throws JavetException {
+ public void testGetOwnPropertyNames() throws JavetException {
try (V8ValueObject v8ValueObject = v8Runtime.getExecutor(
"let x = {'a': 1, 'b': '2', 'c': 3n, d: 1, e: null, g: {h: 1}, '中文': '測試'}; x;").execute()) {
- try (IV8ValueArray iV8ValueArray = v8ValueObject.getPropertyNames()) {
+ try (IV8ValueArray iV8ValueArray = v8ValueObject.getOwnPropertyNames()) {
assertNotNull(iV8ValueArray);
assertEquals(7, iV8ValueArray.getLength());
// Order is preserved since ES2015.
@@ -173,24 +154,6 @@ public void testGetPropertyNames() throws JavetException {
}
}
- @Test
- public void testGetSetDelete() throws JavetException {
- try (V8ValueObject v8ValueObject = v8Runtime.getExecutor("const a = {}; a;").execute()) {
- assertTrue(v8ValueObject.set("a", 1));
- assertTrue(v8ValueObject.set("b", "2"));
- assertTrue(v8ValueObject.set("c", new String[]{"x", "y"}));
- assertEquals(1, v8ValueObject.getInteger("a"));
- assertEquals("2", v8ValueObject.getString("b"));
- assertArrayEquals(
- new String[]{"x", "y"},
- ((List) v8Runtime.toObject(v8ValueObject.get("c"), true)).toArray(new String[0]));
- assertTrue(v8ValueObject.delete("x"));
- assertTrue(v8ValueObject.delete("b"));
- V8Value v8Value = v8ValueObject.getUndefined("b");
- assertNotNull(v8Value);
- }
- }
-
@Test
public void testGetProperty() throws JavetException {
try (V8ValueObject v8ValueObject = v8Runtime.getExecutor(
@@ -230,6 +193,43 @@ public void testGetProperty() throws JavetException {
}
}
+ @Test
+ public void testGetPropertyNames() throws JavetException {
+ try (V8ValueObject v8ValueObject = v8Runtime.getExecutor(
+ "let x = {'a': 1, 'b': '2', 'c': 3n, d: 1, e: null, g: {h: 1}, '中文': '測試'}; x;").execute()) {
+ try (IV8ValueArray iV8ValueArray = v8ValueObject.getPropertyNames()) {
+ assertNotNull(iV8ValueArray);
+ assertEquals(7, iV8ValueArray.getLength());
+ // Order is preserved since ES2015.
+ assertEquals("a", iV8ValueArray.getPropertyString(0));
+ assertEquals("b", iV8ValueArray.getPropertyString(1));
+ assertEquals("c", iV8ValueArray.getPropertyString(2));
+ assertEquals("d", iV8ValueArray.getPropertyString(3));
+ assertEquals("e", iV8ValueArray.getPropertyString(4));
+ assertEquals("g", iV8ValueArray.getPropertyString(5));
+ assertEquals("中文", iV8ValueArray.getPropertyString(6));
+ }
+ }
+ }
+
+ @Test
+ public void testGetSetDelete() throws JavetException {
+ try (V8ValueObject v8ValueObject = v8Runtime.getExecutor("const a = {}; a;").execute()) {
+ assertTrue(v8ValueObject.set("a", 1));
+ assertTrue(v8ValueObject.set("b", "2"));
+ assertTrue(v8ValueObject.set("c", new String[]{"x", "y"}));
+ assertEquals(1, v8ValueObject.getInteger("a"));
+ assertEquals("2", v8ValueObject.getString("b"));
+ assertArrayEquals(
+ new String[]{"x", "y"},
+ ((List) v8Runtime.toObject(v8ValueObject.get("c"), true)).toArray(new String[0]));
+ assertTrue(v8ValueObject.delete("x"));
+ assertTrue(v8ValueObject.delete("b"));
+ V8Value v8Value = v8ValueObject.getUndefined("b");
+ assertNotNull(v8Value);
+ }
+ }
+
@Test
public void testHarmonyScoping() throws JavetException {
v8Runtime.getExecutor("let a = 1;").executeVoid();
@@ -315,29 +315,6 @@ public void testSetProperty() throws JavetException {
}
}
- @Test
- public void testToClone() throws JavetException {
- try (V8ValueObject v8ValueObject = v8Runtime.getExecutor("const x = {}; x;").execute()) {
- v8ValueObject.setProperty("a", "1");
- assertEquals("{\"a\":\"1\"}", v8ValueObject.toJsonString());
- try (V8ValueObject clonedV8ValueObject = v8ValueObject.toClone()) {
- assertEquals("{\"a\":\"1\"}", clonedV8ValueObject.toJsonString());
- assertNotEquals(v8ValueObject.getHandle(), clonedV8ValueObject.getHandle());
- assertEquals(v8Runtime, clonedV8ValueObject.getV8Runtime());
- }
- }
- }
-
- @Test
- public void testToJsonString() throws JavetException {
- try (V8ValueObject v8ValueObject = v8Runtime.getExecutor("const x = {}; x;").execute()) {
- v8ValueObject.setProperty("a", "1");
- v8ValueObject.setProperty("b", 2);
- v8ValueObject.setProperty("c", 1.23);
- assertEquals("{\"a\":\"1\",\"b\":2,\"c\":1.23}", v8ValueObject.toJsonString());
- }
- }
-
@Test
public void testSetWeakDirectDescendant() throws JavetException {
V8ValueObject a = v8Runtime.createV8ValueObject();
@@ -354,7 +331,7 @@ public void testSetWeakDirectDescendant() throws JavetException {
assertEquals(1, v8Runtime.getReferenceCount());
a.setWeak();
globalObject.delete("a");
- v8Runtime.requestGarbageCollectionForTesting(true);
+ v8Runtime.lowMemoryNotification();
assertEquals(0, v8Runtime.getReferenceCount());
assertEquals(0L, a.getHandle());
assertTrue(globalObject.get("a").isUndefined());
@@ -371,6 +348,29 @@ public void testSetWeakIndirectDescendant() throws JavetException {
}
assertEquals(1, v8Runtime.getReferenceCount());
globalObject.delete("a");
- v8Runtime.requestGarbageCollectionForTesting(true);
+ v8Runtime.lowMemoryNotification();
+ }
+
+ @Test
+ public void testToClone() throws JavetException {
+ try (V8ValueObject v8ValueObject = v8Runtime.getExecutor("const x = {}; x;").execute()) {
+ v8ValueObject.setProperty("a", "1");
+ assertEquals("{\"a\":\"1\"}", v8ValueObject.toJsonString());
+ try (V8ValueObject clonedV8ValueObject = v8ValueObject.toClone()) {
+ assertEquals("{\"a\":\"1\"}", clonedV8ValueObject.toJsonString());
+ assertNotEquals(v8ValueObject.getHandle(), clonedV8ValueObject.getHandle());
+ assertEquals(v8Runtime, clonedV8ValueObject.getV8Runtime());
+ }
+ }
+ }
+
+ @Test
+ public void testToJsonString() throws JavetException {
+ try (V8ValueObject v8ValueObject = v8Runtime.getExecutor("const x = {}; x;").execute()) {
+ v8ValueObject.setProperty("a", "1");
+ v8ValueObject.setProperty("b", 2);
+ v8ValueObject.setProperty("c", 1.23);
+ assertEquals("{\"a\":\"1\",\"b\":2,\"c\":1.23}", v8ValueObject.toJsonString());
+ }
}
}
diff --git a/src/test/java/com/caoccao/javet/values/reference/TestV8ValueProxy.java b/src/test/java/com/caoccao/javet/values/reference/TestV8ValueProxy.java
index eca88a7dc..e61cc8470 100644
--- a/src/test/java/com/caoccao/javet/values/reference/TestV8ValueProxy.java
+++ b/src/test/java/com/caoccao/javet/values/reference/TestV8ValueProxy.java
@@ -17,8 +17,8 @@
package com.caoccao.javet.values.reference;
-import com.caoccao.javet.exceptions.JavetException;
import com.caoccao.javet.BaseTestJavetRuntime;
+import com.caoccao.javet.exceptions.JavetException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
diff --git a/src/test/java/com/caoccao/javet/values/reference/TestV8ValueRegExp.java b/src/test/java/com/caoccao/javet/values/reference/TestV8ValueRegExp.java
index 53b1ef2af..3a42ae212 100644
--- a/src/test/java/com/caoccao/javet/values/reference/TestV8ValueRegExp.java
+++ b/src/test/java/com/caoccao/javet/values/reference/TestV8ValueRegExp.java
@@ -21,7 +21,6 @@
import com.caoccao.javet.exceptions.JavetException;
import org.junit.jupiter.api.Test;
-import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class TestV8ValueRegExp extends BaseTestJavetRuntime {
diff --git a/src/test/java/com/caoccao/javet/values/reference/TestV8ValueSymbol.java b/src/test/java/com/caoccao/javet/values/reference/TestV8ValueSymbol.java
index 0f02d9c02..679c8df72 100644
--- a/src/test/java/com/caoccao/javet/values/reference/TestV8ValueSymbol.java
+++ b/src/test/java/com/caoccao/javet/values/reference/TestV8ValueSymbol.java
@@ -17,12 +17,12 @@
package com.caoccao.javet.values.reference;
-import com.caoccao.javet.exceptions.JavetException;
import com.caoccao.javet.BaseTestJavetRuntime;
-import com.caoccao.javet.exceptions.JavetExecutionException;
+import com.caoccao.javet.exceptions.JavetException;
import org.junit.jupiter.api.Test;
-import static org.junit.jupiter.api.Assertions.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
public class TestV8ValueSymbol extends BaseTestJavetRuntime {
@Test
diff --git a/src/test/java/com/caoccao/javet/values/reference/TestV8ValueWeakMap.java b/src/test/java/com/caoccao/javet/values/reference/TestV8ValueWeakMap.java
index 13e7e4745..9fb4b657f 100644
--- a/src/test/java/com/caoccao/javet/values/reference/TestV8ValueWeakMap.java
+++ b/src/test/java/com/caoccao/javet/values/reference/TestV8ValueWeakMap.java
@@ -34,7 +34,7 @@ public void testSetGetHasAndDelete() throws JavetException {
v8ValueObject.set("x", "1");
v8ValueWeakMap.set(v8ValueObject, "2");
assertTrue(v8ValueWeakMap.has(v8ValueObject));
- assertEquals("2", ((V8ValueString)v8ValueWeakMap.get(v8ValueObject)).getValue());
+ assertEquals("2", ((V8ValueString) v8ValueWeakMap.get(v8ValueObject)).getValue());
v8ValueWeakMap.delete(v8ValueObject);
assertFalse(v8ValueWeakMap.has(v8ValueObject));
}
diff --git a/src/test/java/com/caoccao/javet/values/reference/TestV8ValueWeakSet.java b/src/test/java/com/caoccao/javet/values/reference/TestV8ValueWeakSet.java
index 2ccf38e58..27bb1dc3d 100644
--- a/src/test/java/com/caoccao/javet/values/reference/TestV8ValueWeakSet.java
+++ b/src/test/java/com/caoccao/javet/values/reference/TestV8ValueWeakSet.java
@@ -19,9 +19,6 @@
import com.caoccao.javet.BaseTestJavetRuntime;
import com.caoccao.javet.exceptions.JavetException;
-import com.caoccao.javet.values.V8Value;
-import com.caoccao.javet.values.primitive.V8ValueInteger;
-import com.caoccao.javet.values.primitive.V8ValueString;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;