Java源码示例:com.twosigma.beakerx.jvm.object.SimpleEvaluationObject
示例1
@Test
public void returnFromFunction() throws Exception {
//given
String code = "" +
"val a = 2.2\n" +
"val b = 14\n" +
"\n" +
"val f = {x: Double -> a*x + b}\n" +
"\n" +
"println(f(2.0))\n" +
"f(2.0)";
SimpleEvaluationObject seo = KernelTest.createSeo(code);
//when
TryResult evaluate = evaluator.evaluate(seo, code);
//then
assertThat((Double) evaluate.result()).isEqualTo(18.4);
}
示例2
@Test
public void javaImports_shouldBeAdjustedForScala() throws Exception {
//given
Map<String, Object> paramMap = new HashMap<>();
// This import tests both "static" removal and "object" escaping.
List<String> imports = Arrays.asList(
"import static com.twosigma.beakerx.scala.evaluator.object.ImportTestHelper.staticMethod");
paramMap.put(IMPORTS, imports);
EvaluatorParameters kernelParameters = new EvaluatorParameters(paramMap);
//when
scalaEvaluator.updateEvaluatorParameters(kernelParameters);
String code = "val x = staticMethod()";
SimpleEvaluationObject seo = KernelTest.createSeo(code);
TryResult evaluate = scalaEvaluator.evaluate(seo, code);
//then
assertThat(evaluate.result()).isNull();
}
示例3
@Override
public MagicCommandOutcomeItem execute(MagicCommandExecutionParam param) {
String command = param.getCommand();
String[] split = splitPath(command);
if (split.length < 4) {
return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, WRONG_FORMAT_MSG + CLASSPATH_ADD_DYNAMIC);
}
String codeToExecute = command.substring(command.indexOf(DYNAMIC) + DYNAMIC.length()).trim();
SimpleEvaluationObject seo = createSimpleEvaluationObject(codeToExecute, kernel, param.getCode().getMessage(), param.getExecutionCount());
TryResult either = kernel.executeCode(codeToExecute, seo);
if (either.isResult()) {
try {
return addJars(either.result());
} catch (Exception e) {
return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, "There occurs problem during execution of " + CLASSPATH_ADD_DYNAMIC + " : " + e.getMessage());
}
} else {
return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, "There occurs problem during execution of " + CLASSPATH_ADD_DYNAMIC + " : " + either.error());
}
}
示例4
@Test
public void javaImports_shouldBeAdjustedForKotlin() throws Exception {
//given
Map<String, Object> paramMap = new HashMap<>();
// This import tests both "static" removal and "object" escaping.
List<String> imports = asList(
"import static com.twosigma.beakerx.kotlin.evaluator.object.ImportTestHelper.staticMethod");
paramMap.put(IMPORTS, imports);
EvaluatorParameters kernelParameters = new EvaluatorParameters(paramMap);
//when
evaluator.updateEvaluatorParameters(kernelParameters);
String code = "val x = staticMethod()";
SimpleEvaluationObject seo = KernelTest.createSeo(code);
TryResult evaluate = evaluator.evaluate(seo, code);
//then
assertThat(evaluate.result()).isNull();
}
示例5
static void runCommEvent(Message message, CommActions action, Widget.ActionPerformed handlerAction) {
if (message.getContent() != null) {
Serializable data = message.getContent().get("data");
if (data != null && data instanceof LinkedHashMap) {
Object contentObject = ((LinkedHashMap) data).get("content");
if (contentObject instanceof LinkedHashMap) {
HashMap content = (LinkedHashMap) contentObject;
if (handlerAction != null) {
final SimpleEvaluationObject seo = initOutput(message);
handlerAction.executeAction(content, message);
seo.clrOutputHandler();
}
}
}
}
}
示例6
@Test
public void shouldAddPlotToOutputContainerTest() throws Exception {
//given
String code =
"import com.twosigma.beakerx.groovy.evaluator.ResourceLoaderTest;\n" +
"import com.twosigma.beakerx.jvm.object.OutputContainer;\n" +
"import com.twosigma.beakerx.chart.xychart.SimpleTimePlot;\n" +
"List<Map<?, ?>> rates = ResourceLoaderTest.readAsList(\"tableRowsTest.csv\");\n" +
"plot2 = new SimpleTimePlot(rates, [\"m3\", \"y1\"], showLegend:false, initWidth: 300, initHeight: 400)\n" +
"new OutputContainer() << plot2";
//when
SimpleEvaluationObject evaluationObject = PlainCode.createSimpleEvaluationObject(code, groovyKernel, HEADER_MESSAGE, 1);
TryResult seo = evaluator.evaluate(evaluationObject, code);
//then
assertThat(seo.result()).isNotNull();
verifyPlot(groovyKernel.getPublishedMessages());
}
示例7
@Test
public void evaluatePlot_shouldCreatePlotObject() throws Exception {
//given
String code = "import com.twosigma.beakerx.chart.xychart.Plot;\n" +
"val plot = new Plot();\n" +
"plot.setTitle(\"test title\");";
SimpleEvaluationObject seo = KernelTest.createSeo(code);
//when
TryResult evaluate = scalaEvaluator.evaluate(seo, code);
//then
assertThat(evaluate.result() instanceof Plot).isTrue();
assertThat(((Plot) evaluate.result()).getTitle()).isEqualTo("test title");
}
示例8
private TryResult addImplicits(Message parent, String codeToExecute) {
SimpleEvaluationObject seo = createSimpleEvaluationObject(
codeToExecute,
kernel,
new Message(new Header(JupyterMessages.COMM_MSG, parent.getHeader().getSession())),
1);
return kernel.executeCode(codeToExecute, seo);
}
示例9
public static Message getParentHeader() {
SimpleEvaluationObject simpleEvaluationObject = getSimpleEvaluationObject();
if (simpleEvaluationObject != null && simpleEvaluationObject.getJupyterMessage() != null) {
return simpleEvaluationObject.getJupyterMessage();
}
return null;
}
示例10
@Test
public void allowOnlyComment() {
//given
String code =
"/*\n" +
"*/";
SimpleEvaluationObject seo = KernelTest.createSeo(code);
//when
TryResult evaluate = scalaEvaluator.evaluate(seo, code);
//then
assertThat(evaluate.result()).isNull();
}
示例11
public static List<MessageHolder> createMessage(SimpleEvaluationObject seo) {
logger.debug("Creating message response message from: " + seo);
Message message = seo.getJupyterMessage();
List<MessageHolder> ret = new ArrayList<>();
if (isConsoleOutputMessage(seo)) {
ret.addAll(createConsoleResult(seo, message));
} else if (isError(seo.getStatus())) {
ret.addAll(createError(seo, message));
} else if (isFinish(seo.getStatus()) && seo.isShowResult()) {
ret.addAll(createFinish(seo, message));
} else {
logger.debug("Unhandled status of SimpleEvaluationObject : " + seo.getStatus());
}
return ret;
}
示例12
private static List<MessageHolder> createConsoleResult(SimpleEvaluationObject seo, Message message) {
List<MessageHolder> result = new ArrayList<>();
while (!seo.getConsoleOutput().isEmpty()) {
ConsoleOutput co = seo.getConsoleOutput().poll(); //FIFO : peek to see, poll -- removes the data
result.add(new MessageHolder(SocketEnum.IOPUB_SOCKET, buildOutputMessage(message, co.getText(), co.isError())));
}
return result;
}
示例13
private static MessageHolder createErrorResult(SimpleEvaluationObject seo, Message message) {
String[] errorMessage = seo.getPayload().toString().split("\n");
errorMessage = clearText(errorMessage);
if (errorMessage != null && errorMessage.length > 0) {
logger.debug("Execution result ERROR: " + seo.getPayload().toString());
}
Message reply = initMessage(ERROR, message);
Hashtable<String, Serializable> map4 = new Hashtable<String, Serializable>(2);
String ename = "";
String evalue = "";
if (errorMessage != null && errorMessage[0] != null && !errorMessage[0].isEmpty()) {
String[] temp = errorMessage[0].split(":");
if (temp != null) {
if (temp.length == 1) {
ename = temp[0];
evalue = temp[0];
} else if (temp.length > 1) {
ename = temp[0];
evalue = temp[1];
}
}
}
map4.put("ename", ename);
map4.put("evalue", evalue);
map4.put("traceback", TracebackPrinter.print(errorMessage));
map4.put(ERROR_MESSAGE, seo.getPayload().toString());
reply.setContent(map4);
return new MessageHolder(SocketEnum.IOPUB_SOCKET, reply);
}
示例14
private MagicCommandOutcomeItem createSparkBasedOnUserSparkConfiguration(MagicCommandExecutionParam param, SparkRunner sparkRunner) {
SimpleEvaluationObject seo = createSEO(param);
TryResult either = kernel.executeCode(param.getCommandCodeBlock(), seo);
if (either.isResult()) {
Optional<SparkSessionBuilder> builderFromUser = getBuilderFromUser(either.result());
if (builderFromUser.isPresent()) {
SparkSessionBuilder builder = builderFromUser.get();
return sparkRunner.run(builder, param.getCode().getMessage());
} else {
return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, CONFIGURATION_MUST_BE_PROVIDED);
}
} else {
return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, "There occurs problem during execution of " + ENABLE_SPARK_SUPPORT + " : " + either.error());
}
}
示例15
private MagicCommandOutcomeItem createSparkBasedOnEmptyConfiguration(MagicCommandExecutionParam param, List<SparkOptionCommand> options) {
SimpleEvaluationObject seo = createSEO(param);
InternalVariable.setValue(seo);
SparkSessionBuilder config = this.sparkSessionBuilderFactory.newInstance(new SparkConf());
createAndDisplaySparkUI(options, config, param.getCode().getMessage());
return new MagicCommandOutput(MagicCommandOutput.Status.OK);
}
示例16
@Test
public void evaluatePlot_shouldCreatePlotObject() throws Exception {
//given
Map<String, Object> paramMap = new HashMap<>();
paramMap.put(IMPORTS, asList("import com.twosigma.beakerx.chart.xychart.*"));
evaluator.updateEvaluatorParameters(new EvaluatorParameters(paramMap));
String code = "val plot = Plot()\n" +
"plot.setTitle(\"test title\");\n" +
"plot.display();";
SimpleEvaluationObject seo = KernelTest.createSeo(code);
//when
TryResult evaluate = evaluator.evaluate(seo, code);
//then
assertThat(evaluate.result()).isNull();
}
示例17
@Test
public void executePlot() throws Exception {
//given
String code = "" +
"import com.twosigma.beakerx.chart.xychart.*\n" +
"val plot = Plot()";
SimpleEvaluationObject seo = KernelTest.createSeo(code);
//when
TryResult evaluate = evaluator.evaluate(seo, code);
//then
assertThat(evaluate.result()).isNull();
}
示例18
@Override
public void executeFrame(Code code, KernelFunctionality kernel, Message message, int executionCount) {
MagicCommandOutcomeItem execute = execute(code, executionCount, false);
execute.sendMagicCommandOutcome(kernel, message, executionCount);
TryResult result = execute.getResult();
SimpleEvaluationObject seo = execute.getSimpleEvaluationObject();
handleResult(seo, result);
}
示例19
@Test
public void insertsShouldReturnOutputCellHIDDEN() throws Exception {
//given
SimpleEvaluationObject seo = KernelTest.createSeo(SQLForColorTable.CREATE);
//when
TryResult evaluate = sqlEvaluator.evaluate(seo, seo.getExpression());
//then
verifyInsertResult(evaluate);
}
示例20
@Test
public void unitObjectShouldBeRepresentedAsHIDDEN() {
//given
String code = "()";
SimpleEvaluationObject seo = KernelTest.createSeo(code);
//when
TryResult evaluate = scalaEvaluator.evaluate(seo, code);
//then
assertThat(((MIMEContainer) evaluate.result())).isEqualTo(MIMEContainer.HIDDEN);
}
示例21
private int getBestNumber(String codeToExecute, boolean showResult, Message message) {
for (int value = 0; value < 10; ) {
Double numberOfExecution = Math.pow(10, value);
CompletableFuture<Boolean> keepLooking = new CompletableFuture<>();
Long startTime = System.nanoTime();
IntStream.range(0, numberOfExecution.intValue()).forEach(indexOfExecution -> {
SimpleEvaluationObject simpleEvaluationObject = createSimpleEvaluationObject(
codeToExecute, kernel, new Message(new Header(message.type(), message.getHeader().getSession())), 0);
if (!showResult) {
simpleEvaluationObject.noResult();
}
kernel.executeCode(codeToExecute, simpleEvaluationObject);
if (numberOfExecution.intValue() - 1 == indexOfExecution) {
if (TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime) > 0.2) {
keepLooking.complete(false);
} else {
keepLooking.complete(true);
}
}
});
try {
if (keepLooking.get()) {
value++;
} else {
return numberOfExecution.intValue();
}
} catch (ExecutionException | InterruptedException e) {
throw new IllegalStateException("Cannot create best number of execution.");
}
}
throw new IllegalStateException("Cannot create best number of execution.");
}
示例22
@Override
public void update(SimpleEvaluationObject seo ) {
if (seo != null) {
List<MessageHolder> message = MessageCreator.createMessage(seo);
message.forEach(job -> {
if (SocketEnum.IOPUB_SOCKET.equals(job.getSocketType())) {
kernel.publish(singletonList(job.getMessage()));
} else if (SocketEnum.SHELL_SOCKET.equals(job.getSocketType())) {
kernel.send(job.getMessage());
}
});
}
}
示例23
public static void runCompiledCodeAndPublish(Message message, ExecuteCompiledCode handler, Object... params) {
final SimpleEvaluationObject seo = initOutput(message);
InternalVariable.setValue(seo);
KernelManager.get().publish(singletonList(MessageCreator.buildClearOutput(message, true)));
try {
Object result = handler.executeCode(params);
if (result != null) {
List<MIMEContainer> resultString = MIMEContainerFactory.createMIMEContainers(result);
KernelManager.get().publish(singletonList(MessageCreator.buildDisplayData(message, resultString)));
}
} catch (Exception e) {
printError(message, seo, e);
}
seo.clrOutputHandler();
}
示例24
private static void printError(Message message, SimpleEvaluationObject seo, Exception e) {
if (message != null) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
seo.error(sw.toString());
} else {
logger.info("Execution result ERROR: \n" + e);
}
}
示例25
@Test
public void shouldDivide16By2() throws Exception {
//given
String code = codeForDivide16By2();
SimpleEvaluationObject seo = KernelTest.createSeo(code);
//when
TryResult result = evaluator().evaluate(seo, code);
//then
assertThat(result.result().toString()).isEqualTo("8");
}
示例26
@Test
public void shouldCreateErrorResultWithArithmeticExceptionWhenDivisionByZero() throws Exception {
//given
String code = codeForDivisionByZero();
SimpleEvaluationObject seo = KernelTest.createSeo(code);
//when
TryResult either = evaluator().evaluate(seo, code);
//then
assertThat(either.error()).contains(textAssertionForDivisionByZero());
}
示例27
@Test
public void returnPrintln() throws Exception {
//given
String code = codeForPrintln();
SimpleEvaluationObject seo = KernelTest.createSeo(code);
//when
TryResult result = evaluator().evaluate(seo, code);
//then
verifyReturnPrintlnStatement(result);
}
示例28
@Test
public void unableToResolveClass() throws Exception {
String code = "new IntSlider()";
SimpleEvaluationObject seo = KernelTest.createSeo(code);
//when
TryResult evaluate = groovyEvaluator.evaluate(seo, code);
//then
assertThat(evaluate.isError()).isTrue();
System.out.println(evaluate.error());
assertThat(evaluate.error()).contains("unable to resolve class IntSlider");
}
示例29
public KernelTest(String id, CommRepository commRepository) {
this.id = id;
this.commRepository = commRepository;
this.beakerXJson = new BeakerXJsonMock();
initMagicCommands();
SimpleEvaluationObject value = new SimpleEvaluationObject("ok", new SeoConfigurationFactoryMock(this, commMsg()));
InternalVariable.setValue(value);
KernelManager.register(this);
}
示例30
public KernelTest(String id, Evaluator evaluator) {
this.id = id;
this.evaluator = evaluator;
this.commRepository = new BeakerXCommRepositoryMock();
this.beakerXJson = new BeakerXJsonMock();
initMagicCommands();
SimpleEvaluationObject value = new SimpleEvaluationObject("ok", new SeoConfigurationFactoryMock(this, commMsg()));
InternalVariable.setValue(value);
KernelManager.register(this);
this.magicKernels = new HashMap<>();
}