com.twosigma.beakerx.mimetype.MIMEContainer Java Examples

The following examples show how to use com.twosigma.beakerx.mimetype.MIMEContainer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OutputContainerLayoutManager.java    From beakerx with Apache License 2.0 6 votes vote down vote up
private Optional<Widget> toWidget(Object item) {
  if (item == null) {
    return handleNull();
  }
  if (item instanceof WidgetItem) {
    return of(((WidgetItem) item).asWidget());
  }
  Widget widget = MIMEContainerFactory.getTableDisplay(item);
  if (widget != null) {
    return of(widget);
  }
  if (item instanceof MIMEContainer) {
    return of(createHTML(((MIMEContainer) item).getData().toString()));
  }

  return of(createHTMLPre(item.toString()));
}
 
Example #2
Source File: Graphics.java    From beakerx with Apache License 2.0 6 votes vote down vote up
public void fireOnKey(String key, GraphicsActionObject actionObject, Message message) {
  GraphicsActionListener listener = onKeyListeners.get(key);
  if (listener != null) {
    runCompiledCode(
            message,
            params -> {
              GraphicsActionListener listener1 = (GraphicsActionListener) params[0];
              GraphicsActionObject ao = (GraphicsActionObject) params[1];
              ao.setGraphics(this);
              listener1.execute(ao);
              return MIMEContainer.HIDDEN;
            },
            listener,
            actionObject);
  }
}
 
Example #3
Source File: JavaScriptMagicCommandTest.java    From beakerx with Apache License 2.0 6 votes vote down vote up
@Test
public void handleJavaScriptMagicCommand() throws Exception {
  //given
  String jsCode =
          "require.config({\n" +
                  "  paths: {\n" +
                  "      d3: '//cdnjs.cloudflare.com/ajax/libs/d3/3.4.8/d3.min'\n" +
                  "  }});";

  Code code = CodeFactory.create(JAVASCRIPT + System.lineSeparator() + jsCode, commMsg(), kernel);
  //when
  code.execute(this.kernel, 1);
  //MagicCommandOutcome result = executeMagicCommands(code, 1, kernel);
  //then
  Map data = (Map) kernel.getPublishedMessages().get(0).getContent().get("data");
  String toCompare = (String) data.get(MIMEContainer.MIME.APPLICATION_JAVASCRIPT);
  toCompare = toCompare.replaceAll("\\s+", "");
  jsCode = jsCode.replaceAll("\\s+", "");
  assertThat(toCompare.trim()).isEqualTo(jsCode);
}
 
Example #4
Source File: MIMEContainerFactoryTest.java    From beakerx with Apache License 2.0 6 votes vote down vote up
@Test
public void integerAsTextHtml() throws Exception {
  //given
  Displayers.register(Integer.class, new Displayer<Integer>() {
    @Override
    public Map<String, String> display(Integer value) {
      return new HashMap<String, String>() {{
        put(TEXT_HTML, "<div><h1>" + value + "</h1></div>");
      }};
    }
  });
  //when
  List<MIMEContainer> result = MIMEContainerFactory.createMIMEContainers(2);
  //then
  assertThat(result.get(0)).isEqualTo(new MIMEContainer(TEXT_HTML, "<div><h1>" + 2 + "</h1></div>"));
}
 
Example #5
Source File: BeakerxDefaultDisplayers.java    From beakerx with Apache License 2.0 6 votes vote down vote up
private static void registerImageDisplayer() {
  Displayers.register(RenderedImage.class, new Displayer<RenderedImage>() {
    @Override
    public Map<String, String> display(RenderedImage value) {
      return new HashMap<String, String>() {{
        try {
          byte[] data = Images.encode(value);
          String base64 = Base64.getEncoder().encodeToString(data);
          put(MIMEContainer.MIME.IMAGE_PNG, base64);
        }
        catch (IOException exc) {
          StringWriter sw = new StringWriter();
          exc.printStackTrace(new PrintWriter(sw));
          put(MIMEContainer.MIME.TEXT_HTML, "<div><pre>" + sw.toString() + "</pre></div>");
        }
      }};
    }
  });
}
 
Example #6
Source File: MIMEContainerFactory.java    From beakerx with Apache License 2.0 5 votes vote down vote up
public static List<MIMEContainer> getMimeContainerForNull() {
  if (Kernel.showNullExecutionResult) {
    return singletonList(Text("null"));
  }

  return HIDDEN_MIME;
}
 
Example #7
Source File: SymjaMMAEvaluator.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Set the mode for the output format possible values <code>input, output, tex, java, traditional</code>
 * 
 * @param symjaMMACodeRunner
 * @param trimmedInput
 * @return
 */
MIMEContainer metaCommand(final SymjaMMACodeRunner symjaMMACodeRunner, final String trimmedInput) {
	String command = trimmedInput.substring(1).toLowerCase(Locale.ENGLISH);
	if (command.equals("java")) {
		fUsedForm = SymjaMMAEvaluator.JAVAFORM;
		return new MarkdownNotebookOutput("Enabling output for JavaForm");
	} else if (command.equals("traditional")) {
		fUsedForm = SymjaMMAEvaluator.TRADITIONALFORM;
		return new MarkdownNotebookOutput("Enabling output for TraditionalForm");
	} else if (command.equals("output")) {
		fUsedForm = SymjaMMAEvaluator.OUTPUTFORM;
		return new MarkdownNotebookOutput("Enabling output for OutputForm");
		// } else if (command.equals("pretty")) {
		// symjammaEvaluator.fUsedForm = SymjaMMAEvaluator.PRETTYFORM;
		// return new MarkdownNotebookOutput("Enabling output for PrettyPrinterForm");
	} else if (command.equals("input")) {
		fUsedForm = SymjaMMAEvaluator.INPUTFORM;
		return new MarkdownNotebookOutput("Enabling output for InputForm");
	} else if (command.equals("tex")) {
		fUsedForm = SymjaMMAEvaluator.TEXFORM;
		return new MarkdownNotebookOutput("Enabling output for TeXForm");
	} else if (command.equals("timeoutoff")) {
		fSeconds = -1;
		return new MarkdownNotebookOutput("Disabling timeout for evaluation");
	} else if (command.equals("timeouton")) {
		fSeconds = 60;
		return new MarkdownNotebookOutput("Enabling timeout for evaluation to 60 seconds.");
	}
	return null;
}
 
Example #8
Source File: Clojure.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Override
protected void configureJvmRepr() {
  Displayers.register(LazySeq.class, new Displayer<LazySeq>() {
    @Override
    public Map<String, String> display(LazySeq value) {
      return new HashMap<String, String>() {{
        List<String> collect = stream(value.toArray()).map(Object::toString).collect(Collectors.toList());
        put(MIMEContainer.MIME.TEXT_PLAIN, new ArrayList<>(collect).toString());
      }};
    }
  });
  DisplayerDataMapper.register(converter);
}
 
Example #9
Source File: ScalaReprTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #10
Source File: SimpleLayoutManagerTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Test
public void outputContainerWithHtml() throws Exception {
  //given
  String code = "<h4>Title</h4>";
  OutputContainer outputContainer = new OutputContainer();
  outputContainer.leftShift(MIMEContainer.HTML(code));
  //when
  outputContainer.display();
  //then
  String value = findValueForProperty(kernel, Widget.VALUE, String.class);
  assertThat(value).isEqualTo(code);
}
 
Example #11
Source File: MIMEContainerFactoryTest.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Test
public void OutputCellHIDDENShouldReturnMIMEContainerHidden() throws Exception {
  //give
  //when
  List<MIMEContainer> result = MIMEContainerFactory.createMIMEContainers(OutputCell.HIDDEN);
  //then
  assertThat(result.get(0)).isEqualTo(MIMEContainer.HIDDEN);
}
 
Example #12
Source File: CompiledCodeRunner.java    From beakerx with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #13
Source File: MIMEDisplayMethodManager.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Override
public void display(List<MIMEContainer> mimeContainers) {
  HashMap<String, Serializable> content = new HashMap<>();
  HashMap<String, Object> data = new HashMap<>();
  mimeContainers.forEach(x -> data.put(x.getMime().asString(), x.getData()));
  content.put(DATA, data);
  content.put(METADATA, new HashMap<>());
  Message message = BxComm.messageMessage(DISPLAY_DATA, Buffer.EMPTY, content, getParentHeader());
  KernelManager.get().publish(singletonList(message));
}
 
Example #14
Source File: TableDisplay.java    From beakerx with Apache License 2.0 5 votes vote down vote up
private Object contextMenuClickHandlerCommon(Object... params) throws Exception {
  Object actionObject = params[0];
  ArrayList<Object> other = (ArrayList<Object>) params[1];
  if (actionObject instanceof ContextMenuAction) {
    ContextMenuAction action = (ContextMenuAction) actionObject;
    action.apply((Integer) other.get(0), (Integer) other.get(1), this);
  } else {
    Object ret = runClosure(params[0], other.toArray());
  }
  return MIMEContainer.HIDDEN;
}
 
Example #15
Source File: BeakerxDefaultDisplayers.java    From beakerx with Apache License 2.0 5 votes vote down vote up
private static void registerCodeCellDisplayer() {
  Displayers.register(CodeCell.class, new Displayer<CodeCell>() {
    @Override
    public Map<String, String> display(CodeCell value) {
      return new HashMap<String, String>() {{
        StringBuilder sb = new StringBuilder("Cell Type:" + (value).getCellType()).append(System.getProperty("line.separator"));
        sb.append("Execution Count:").append((value).getExecutionCount()).append(System.getProperty("line.separator"));
        sb.append("Metadata:").append((value).getMetadata()).append(System.getProperty("line.separator"));
        sb.append("Source:").append((value).getSource());
        put(MIMEContainer.MIME.TEXT_PLAIN, sb.toString());
      }};
    }
  });
}
 
Example #16
Source File: MIMEContainerFactory.java    From beakerx with Apache License 2.0 5 votes vote down vote up
private static List<MIMEContainer> createMIMEContainersFromObject(final Object data) {

    Object input = DisplayerDataMapper.convert(data);

    if (input instanceof DisplayableWidget) {
      ((DisplayableWidget) input).display();
      return HIDDEN_MIME;
    }

    TableDisplay table = getTableDisplay(input);
    if (table != null) {
      table.display();
      return HIDDEN_MIME;
    }

    if (input instanceof Collection) {
      return singletonList(MIMEContainer.Text(collectionToString((Collection<?>) input)));
    }

    if (input instanceof XYGraphics) {
      new Plot().add((XYGraphics) input).display();
      return HIDDEN_MIME;
    }
    if (input instanceof MIMEContainer) {
      return singletonList((MIMEContainer) input);
    }

    return Displayers.display(input).entrySet().stream().
            map(item -> new MIMEContainer(item.getKey(), item.getValue())).
            collect(Collectors.toList());
  }
 
Example #17
Source File: OutputContainerLayoutManager.java    From beakerx with Apache License 2.0 5 votes vote down vote up
private Optional<Widget> handleNull() {
  List<MIMEContainer> mimeContainerForNull = MIMEContainerFactory.getMimeContainerForNull();
  if (mimeContainerForNull.contains(MIMEContainer.HIDDEN)) {
    return empty();
  }
  return of(createHTMLPre(mimeContainerForNull.get(0).getData().toString()));
}
 
Example #18
Source File: Graphics.java    From beakerx with Apache License 2.0 5 votes vote down vote up
public void fireClick(GraphicsActionObject actionObject, Message message) {
  if (onClickListener != null) {
    runCompiledCode(
            message,
            params -> {
              GraphicsActionObject ao = (GraphicsActionObject) params[0];
              ao.setGraphics(this);
              onClickListener.execute(ao);
              return MIMEContainer.HIDDEN;
            },
            actionObject);
  }
}
 
Example #19
Source File: MessageCreator.java    From beakerx with Apache License 2.0 5 votes vote down vote up
private static boolean showResult(SimpleEvaluationObject seo) {
  boolean ret = true;
  if (seo != null && seo.getPayload() != null && seo.getPayload() instanceof MIMEContainer) {
    MIMEContainer input = (MIMEContainer) seo.getPayload();
    ret = !MIMEContainer.MIME.HIDDEN.equals(input.getMime().asString());
  } else if ((seo != null && !seo.getOutputdata().isEmpty())) {
    ret = true;
  }
  return ret;
}
 
Example #20
Source File: MessageCreator.java    From beakerx with Apache License 2.0 5 votes vote down vote up
public static Message buildMessage(Message message, List<MIMEContainer> mimes, int executionCount) {
  Message reply = initMessage(EXECUTE_RESULT, message);
  reply.setContent(new HashMap<>());
  reply.getContent().put("execution_count", executionCount);
  HashMap<String, Object> map3 = new HashMap<>();
  mimes.forEach(mimeItem -> map3.put(mimeItem.getMime().asString(), mimeItem.getData()));
  reply.getContent().put("data", map3);
  reply.getContent().put("metadata", new HashMap<>());
  return reply;
}
 
Example #21
Source File: MessageCreator.java    From beakerx with Apache License 2.0 5 votes vote down vote up
private static Message buildMessage(Message message, List<MIMEContainer> mimes, String outputdataResult, int executionCount) {
  if (!outputdataResult.isEmpty()) {
    List<MIMEContainer> collect = mimes.stream().map(x -> new MIMEContainer(x.getMime().asString(), x.getData() + outputdataResult)).collect(Collectors.toList());
    return buildMessage(message, collect, executionCount);
  }
  return buildMessage(message, mimes, executionCount);
}
 
Example #22
Source File: MessageCreator.java    From beakerx with Apache License 2.0 5 votes vote down vote up
public static Message buildDisplayData(Message message, List<MIMEContainer> mimes) {
  Message reply = initMessage(DISPLAY_DATA, message);
  reply.setContent(new HashMap<>());
  reply.getContent().put("metadata", new HashMap<>());
  HashMap<String, Object> map3 = new HashMap<>();
  mimes.forEach(mimeItem -> map3.put(mimeItem.getMime().asString(), mimeItem.getData()));
  reply.getContent().put("data", map3);
  return reply;
}
 
Example #23
Source File: MessageCreator.java    From beakerx with Apache License 2.0 5 votes vote down vote up
private static MessageHolder createFinishResult(SimpleEvaluationObject seo, Message message) {
  MessageHolder ret = null;
  List<MIMEContainer> mimes = MIMEContainerFactory.createMIMEContainers(seo.getPayload());
  if (!mimes.contains(MIMEContainer.HIDDEN)) {
    ret = new MessageHolder(SocketEnum.IOPUB_SOCKET,
            buildMessage(message, mimes, outputdataResult(seo.getOutputdata()), seo.getExecutionCount()));
  }
  return ret;
}
 
Example #24
Source File: HtmlMagicCommand.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Override
public MagicCommandOutcomeItem execute(MagicCommandExecutionParam param) {
  String commandCodeBlock = param.getCommandCodeBlock();
  if (commandCodeBlock == null) {
    return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, String.format(USAGE_ERROR_MSG, HTML));
  }
  MIMEContainer html = HTML("<html>" + commandCodeBlock + "</html>");
  return new MagicCommandResult(MagicCommandOutcomeItem.Status.OK, html);
}
 
Example #25
Source File: OutputCellTest.java    From beakerx with Apache License 2.0 4 votes vote down vote up
@Test
public void outputCellHasHiddenState() throws Exception {
  //then
  Assertions.assertThat(OutputCell.HIDDEN instanceof MIMEContainer).isEqualTo(true);
}
 
Example #26
Source File: MIMEDisplayMethodManager.java    From beakerx with Apache License 2.0 4 votes vote down vote up
public void display(List<MIMEContainer> mimeContainers) {
  this.displayMimeMethodStrategy.display(mimeContainers);
}
 
Example #27
Source File: ClasspathShowMagicCommand.java    From beakerx with Apache License 2.0 4 votes vote down vote up
@Override
public MagicCommandOutput execute(MagicCommandExecutionParam param) {
  MIMEContainer result = Text(kernel.getClasspath());
  return new MagicCommandOutput(MagicCommandOutput.Status.OK, result.getData().toString());
}
 
Example #28
Source File: Output.java    From beakerx with Apache License 2.0 4 votes vote down vote up
public void display(MIMEContainer mimeContainer) {
  HashMap<String, Serializable> content = new HashMap<>();
  content.put(mimeContainer.getMime().asString(), (Serializable) mimeContainer.getData());
  display(content);
}
 
Example #29
Source File: Output.java    From beakerx with Apache License 2.0 4 votes vote down vote up
public void display(List<MIMEContainer> mimeContainers) {
  mimeContainers.forEach(this::display);
}
 
Example #30
Source File: OutputManager.java    From beakerx with Apache License 2.0 4 votes vote down vote up
@Override
public void display(List<MIMEContainer> mimeContainers) {
  getOutput().display(mimeContainers);
}