Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
/*
* The MIT License
*
* Copyright 2022 Karate Labs Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.intuit.karate.core;
import com.intuit.karate.FileUtils;
import com.intuit.karate.Json;
import com.intuit.karate.JsonUtils;
import com.intuit.karate.KarateException;
import com.intuit.karate.Logger;
import com.intuit.karate.Match;
import com.intuit.karate.MatchStep;
import com.intuit.karate.PerfContext;
import com.intuit.karate.StringUtils;
import com.intuit.karate.XmlUtils;
import com.intuit.karate.graal.JsEngine;
import com.intuit.karate.graal.JsFunction;
import com.intuit.karate.graal.JsLambda;
import com.intuit.karate.graal.JsList;
import com.intuit.karate.graal.JsMap;
import com.intuit.karate.graal.JsValue;
import com.intuit.karate.http.HttpClient;
import com.intuit.karate.http.HttpRequest;
import com.intuit.karate.http.HttpRequestBuilder;
import com.intuit.karate.http.ResourceType;
import com.intuit.karate.http.WebSocketClient;
import com.intuit.karate.http.WebSocketOptions;
import com.intuit.karate.shell.Command;
import java.io.File;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.graalvm.polyglot.Value;
import org.graalvm.polyglot.proxy.ProxyExecutable;
/**
*
* @author pthomas3
*/
public class ScenarioBridge implements PerfContext {
private final ScenarioEngine ENGINE;
protected ScenarioBridge(ScenarioEngine engine) {
ENGINE = engine;
}
public void abort() {
getEngine().setAborted(true);
}
public Object append(Value... vals) {
List list = new ArrayList();
JsList jsList = new JsList(list);
if (vals.length == 0) {
return jsList;
}
Value val = vals[0];
if (val.hasArrayElements()) {
list.addAll(val.as(List.class));
} else {
list.add(val.as(Object.class));
}
if (vals.length == 1) {
return jsList;
}
for (int i = 1; i < vals.length; i++) {
Value v = vals[i];
if (v.hasArrayElements()) {
list.addAll(v.as(List.class));
} else {
list.add(v.as(Object.class));
}
}
return jsList;
}
private Object appendToInternal(String varName, Value... vals) {
ScenarioEngine engine = getEngine();
Variable var = engine.vars.get(varName);
if (!var.isList()) {
return null;
}
List list = var.getValue();
for (Value v : vals) {
if (v.hasArrayElements()) {
list.addAll(v.as(List.class));
} else {
Object temp = v.as(Object.class);
list.add(temp);
}
}
engine.setVariable(varName, list);
return new JsList(list);
}
public Object appendTo(Value ref, Value... vals) {
if (ref.isString()) {
return appendToInternal(ref.asString(), vals);
}
List list;
if (ref.hasArrayElements()) {
list = new JsValue(ref).getAsList(); // make sure we unwrap the "original" list
} else {
list = new ArrayList();
}
for (Value v : vals) {
if (v.hasArrayElements()) {
list.addAll(v.as(List.class));
} else {
Object temp = v.as(Object.class);
list.add(temp);
}
}
return new JsList(list);
}
public Object call(String fileName) {
return call(false, fileName, null);
}
public Object call(String fileName, Value arg) {
return call(false, fileName, arg);
}
public Object call(boolean sharedScope, String fileName) {
return call(sharedScope, fileName, null);
}
public Object call(boolean sharedScope, String fileName, Value arg) {
ScenarioEngine engine = getEngine();
Variable called = new Variable(engine.fileReader.readFile(fileName));
Variable result = engine.call(called, arg == null ? null : new Variable(arg), sharedScope);
if (sharedScope) {
if (result.isMap()) {
engine.setVariables(result.getValue());
}
}
return JsValue.fromJava(result.getValue());
}
private static Object callSingleResult(ScenarioEngine engine, Object o) throws Exception {
if (o instanceof Exception) {
engine.logger.warn("callSingle() cached result is an exception");
throw (Exception) o;
}
// clone so that threads see the same data snapshot
// we also attach js functions
o = engine.JS.attachAll(o);
return JsValue.fromJava(o);
}
public Object callSingle(String fileName) throws Exception {
return callSingle(fileName, null);
}
public Object callSingle(String fileName, Value arg) throws Exception {
ScenarioEngine engine = getEngine();
final Map CACHE = engine.runtime.featureRuntime.suite.callSingleCache;
int minutes = engine.getConfig().getCallSingleCacheMinutes();
if ((minutes == 0) && CACHE.containsKey(fileName)) {
engine.logger.trace("callSingle cache hit: {}", fileName);
return callSingleResult(engine, CACHE.get(fileName));
}
long startTime = System.currentTimeMillis();
engine.logger.trace("callSingle waiting for lock: {}", fileName);
synchronized (CACHE) { // lock
if ((minutes == 0) && CACHE.containsKey(fileName)) { // retry
long endTime = System.currentTimeMillis() - startTime;
engine.logger.warn("this thread waited {} milliseconds for callSingle lock: {}", endTime, fileName);
return callSingleResult(engine, CACHE.get(fileName));
}
// this thread is the 'winner'
engine.logger.info(">> lock acquired, begin callSingle: {}", fileName);
Object result = null;
File cacheFile = null;
if (minutes > 0) {
String cleanedName = StringUtils.toIdString(fileName);
String cacheFileName = engine.getConfig().getCallSingleCacheDir() + File.separator + cleanedName + ".txt";
cacheFile = new File(cacheFileName);
long since = System.currentTimeMillis() - minutes * 60 * 1000;
if (cacheFile.exists()) {
long lastModified = cacheFile.lastModified();
if (lastModified > since) {
String json = FileUtils.toString(cacheFile);
result = JsonUtils.fromJson(json);
engine.logger.info("callSingleCache hit: {}", cacheFile);
} else {
engine.logger.info("callSingleCache stale, last modified {} - is before {} (minutes: {})",
lastModified, since, minutes);
}
} else {
engine.logger.info("callSingleCache file does not exist, will create: {}", cacheFile);
}
}
if (result == null) {
Variable called = new Variable(read(fileName));
Variable argVar;
if (arg == null || arg.isNull()) {
argVar = null;
} else {
argVar = new Variable(arg);
}
Variable resultVar;
try {
resultVar = engine.call(called, argVar, false);
} catch (Exception e) {
// don't retain any vestiges of graal-js
RuntimeException re = new RuntimeException(e.getMessage());
// we do this so that an exception is also "cached"
resultVar = new Variable(re); // will be thrown at end
engine.logger.warn("callSingle() will cache an exception");
}
if (minutes > 0) { // cacheFile will be not null
if (resultVar.isMapOrList()) {
String json = resultVar.getAsString();
FileUtils.writeToFile(cacheFile, json);
engine.logger.info("callSingleCache write: {}", cacheFile);
} else {
engine.logger.warn("callSingleCache write failed, not json-like: {}", resultVar);
}
}
result = resultVar.getValue();
}
CACHE.put(fileName, result);
engine.logger.info("<< lock released, cached callSingle: {}", fileName);
return callSingleResult(engine, result);
}
}
public Object callonce(String path) {
return callonce(false, path);
}
public Object callonce(boolean sharedScope, String path) {
String exp = "read('" + path + "')";
Variable v = getEngine().call(true, exp, sharedScope);
return JsValue.fromJava(v.getValue());
}
@Override
public void capturePerfEvent(String name, long startTime, long endTime) {
PerfEvent event = new PerfEvent(startTime, endTime, name, 200);
getEngine().capturePerfEvent(event);
}
public Object compareImage(Object baseline, Object latest, Value... optionsVal) {
if (optionsVal.length > 0 && !optionsVal[0].hasMembers()) {
throw new RuntimeException("invalid image comparison options: expected map");
}
Map options = new HashMap<>();
if (optionsVal.length > 0) {
for (String k : optionsVal[0].getMemberKeys()) {
options.put(k, optionsVal[0].getMember(k).as(Object.class));
}
}
Map params = new HashMap<>();
params.put("baseline", baseline);
params.put("latest", latest);
params.put("options", options);
return JsValue.fromJava(getEngine().compareImageInternal(params));
}
public void configure(String key, Value value) {
getEngine().configure(key, new Variable(value));
}
public Object consume(String type) {
return getEngine().consume(type);
}
public Object distinct(Value o) {
if (!o.hasArrayElements()) {
return JsList.EMPTY;
}
long count = o.getArraySize();
Set