0

I've created a custom Magic command with the intention of generating a spark query programatically. Here's the relevant part of my class that implements the MagicCommandFunctionality:

MagicCommandOutcomeItem execute(MagicCommandExecutionParam magicCommandExecutionParam) {    

    // get the string that was entered:
    String input = magicCommandExecutionParam.command.substring(MAGIC.length())

    // use the input to generate a query
    String generatedQuery =  Interpreter.interpret(input)

    MIMEContainer result = Text(generatedQuery);
    return new MagicCommandOutput(MagicCommandOutcomeItem.Status.OK, result.getData().toString());
}

This works splendidly. It returns the command that I generated. (As text)

My question is -- how do I coerce the notebook into evaluating that value in the cell? My guess is that a SimpleEvaluationObject and TryResult are involved, but I can't find any examples of their use

Rather than creating the MagicCommandOutput I probably want the Kernel to create one for me. I see that the KernelMagicCommand has an execute method that would do that. Anyone have any ideas?

johnxfly
  • 21
  • 6

1 Answers1

0

Okay, I found one way to do it. Here's my solution:
You can ask the current kernelManager for the kernel you're interested in,
then call PythonEntryPoint.evaluate. It seems to do the job!

@Override MagicCommandOutcomeItem execute(MagicCommandExecutionParam magicCommandExecutionParam) {

String input = magicCommandExecutionParam.command.substring(MAGIC.length() + 1)
// this is the Scala code I want to evaluate:
String codeToExecute = <your code here>

KernelFunctionality kernel = KernelManager.get()
PythonEntryPoint pep = kernel.getPythonEntryPoint(SCALA_KERNEL)
pep.evaluate(codeToExecute)
pep.getShellMsg()

List<Message> messages = new ArrayList<>()
//until there are messages on iopub channel available collect them into response
    while (true) {
        String iopubMsg = pep.getIopubMsg()
        if (iopubMsg == "null") break
        try {
            Message msg = parseMessage(iopubMsg) //(I didn't show this part)
            messages.add(msg)
            String commId = (String) msg.getContent().get("comm_id")
            if (commId != null) {
                kernel.addCommIdManagerMapping(commId, SCALA_KERNEL)
            }
        } catch (IOException e) {
            log.error("There was an error: ${e.getMessage()}")
            return new MagicKernelResponse(MagicCommandOutcomeItem.Status.ERROR, messages)
        }
    }
    return new MagicKernelResponse(MagicCommandOutcomeItem.Status.OK, messages)
}
johnxfly
  • 21
  • 6