/**
   * @param engineName the script engine name (eg "groovy", etc)
   * @return the Script engine to use to evaluate the script
   * @throws MacroExecutionException in case of an error in parsing the jars parameter
   */
  private ScriptEngine getScriptEngine(String engineName) throws MacroExecutionException {
    // Look for a script engine in the Execution Context since we want the same engine to be used
    // for all evals during the same execution lifetime.
    // We must use the same engine because that engine may create an internal ClassLoader in which
    // it loads new classes defined in the script and if we create a new engine then defined classes
    // will be lost.
    // However we also need to be able to execute several script Macros during a single execution
    // request
    // and for example the second macro could have jar parameters. In order to support this use case
    // we ensure in AbstractScriptMacro to reuse the same thread context ClassLoader during the
    // whole
    // request execution.
    ExecutionContext executionContext = this.execution.getContext();
    Map<String, ScriptEngine> scriptEngines =
        (Map<String, ScriptEngine>) executionContext.getProperty(EXECUTION_CONTEXT_ENGINE_KEY);
    if (scriptEngines == null) {
      scriptEngines = new HashMap<String, ScriptEngine>();
      executionContext.setProperty(EXECUTION_CONTEXT_ENGINE_KEY, scriptEngines);
    }
    ScriptEngine engine = scriptEngines.get(engineName);

    if (engine == null) {
      ScriptEngineManager sem = new ScriptEngineManager();
      engine = sem.getEngineByName(engineName);
      scriptEngines.put(engineName, engine);
    }

    return engine;
  }
  /**
   * Tests that the Execution Context and the XWiki Context share the same reference of the Velocity
   * Context after a call to {@link VelocityManager#getVelocityContext()}. There is old code that
   * accesses the Velocity Context from the XWiki Context.
   */
  @Test
  public void getVelocityContextUpdatesXContext() throws Exception {
    Execution execution = this.mocker.getInstance(Execution.class);
    ExecutionContext executionContext = new ExecutionContext();
    when(execution.getContext()).thenReturn(executionContext);

    ScriptContextManager scriptContextManager = this.mocker.getInstance(ScriptContextManager.class);
    ScriptContext scriptContext = new SimpleScriptContext();
    when(scriptContextManager.getScriptContext()).thenReturn(scriptContext);

    VelocityContext velocityContext = new VelocityContext();
    executionContext
        .newProperty("velocityContext")
        .initial(velocityContext)
        .inherited()
        .cloneValue()
        .declare();

    XWikiContext mockContext = mock(XWikiContext.class);
    Provider<XWikiContext> xcontextProvider = this.mocker.getInstance(XWikiContext.TYPE_PROVIDER);
    when(xcontextProvider.get()).thenReturn(mockContext);

    this.mocker.getComponentUnderTest().getVelocityContext();

    verify(mockContext).put("vcontext", velocityContext);
  }
  @Before
  public void configure() throws Exception {
    getMockery().setImposteriser(ClassImposteriser.INSTANCE);

    Utils.setComponentManager(getComponentManager());

    execution = getComponentManager().getInstance(Execution.class);
    final ExecutionContext context = new ExecutionContext();

    this.xwiki = getMockery().mock(XWiki.class);

    this.xwikiContext = new XWikiContext();
    this.xwikiContext.setDatabase("xwiki");
    this.xwikiContext.setWiki(this.xwiki);

    context.setProperty("xwikicontext", this.xwikiContext);

    this.componentDoc = getMockery().mock(XWikiDocument.class);

    getMockery()
        .checking(
            new Expectations() {
              {
                allowing(execution).getContext();
                will(returnValue(context));

                allowing(xwiki).getDocument(DOC_REF, xwikiContext);
                will(returnValue(componentDoc));
                allowing(componentDoc).getSyntax();
                will(returnValue(Syntax.XWIKI_2_0));
              }
            });

    this.builder = getComponentManager().getInstance(WikiComponentBuilder.class, "uiextension");
  }
 /** @return the XWikiContext */
 protected XWikiContext getXWikiContext() {
   ExecutionContext executionContext = this.execution.getContext();
   XWikiContext context =
       (XWikiContext) executionContext.getProperty(XWikiContext.EXECUTIONCONTEXT_KEY);
   // FIXME: Do we need this? Maybe when running an index Thread?
   // if (context == null) {
   // context = this.contextProvider.createStubContext();
   // executionContext.setProperty(XWikiContext.EXECUTIONCONTEXT_KEY, context);
   // }
   return context;
 }
 private void setUpBaseMocks() throws Exception {
   this.resolver =
       this.componentManager.registerMockComponent(
           DocumentReferenceResolver.TYPE_STRING, "explicit");
   this.execution = this.componentManager.registerMockComponent(Execution.class);
   this.xwikiContext = mock(XWikiContext.class);
   ExecutionContext executionContext = new ExecutionContext();
   executionContext.setProperty(XWikiContext.EXECUTIONCONTEXT_KEY, this.xwikiContext);
   when(this.execution.getContext()).thenReturn(executionContext);
   this.xwiki = mock(XWiki.class);
   when(this.xwikiContext.getWiki()).thenReturn(this.xwiki);
 }
示例#6
0
  /**
   * Init provided {@link ExportURLFactory} and add rendered documents to ZIP stream.
   *
   * @param zos the ZIP output stream.
   * @param tempdir the directory where to copy attached files.
   * @param urlf the {@link com.xpn.xwiki.web.XWikiURLFactory} used to render the documents.
   * @param context the XWiki context.
   * @throws XWikiException error when render documents.
   * @throws IOException error when render documents.
   */
  private void renderDocuments(
      ZipOutputStream zos, File tempdir, ExportURLFactory urlf, XWikiContext context)
      throws XWikiException, IOException {
    ExecutionContextManager ecim = Utils.getComponent(ExecutionContextManager.class);
    Execution execution = Utils.getComponent(Execution.class);

    VelocityContext oldVelocityContext = (VelocityContext) context.get("vcontext");

    try {
      XWikiContext renderContext = (XWikiContext) context.clone();
      renderContext.put("action", "view");

      ExecutionContext ec = new ExecutionContext();

      // Bridge with old XWiki Context, required for old code.
      ec.setProperty("xwikicontext", renderContext);

      ecim.initialize(ec);

      // Push a clean new Execution Context since we don't want the main Execution Context to be
      // used for
      // rendering the HTML pages to export. It's cleaner to isolate it as we do. Note that the new
      // Execution Context automatically gets initialized with a new Velocity Context by
      // the VelocityRequestInitializer class.
      execution.pushContext(ec);

      VelocityManager velocityManager = Utils.getComponent(VelocityManager.class);

      // At this stage we have a clean Velocity Context
      VelocityContext vcontext = velocityManager.getVelocityContext();

      urlf.init(this.pages, tempdir, renderContext);
      renderContext.setURLFactory(urlf);

      for (String pageName : this.pages) {
        renderDocument(pageName, zos, renderContext, vcontext);
      }
    } catch (ExecutionContextException e) {
      throw new XWikiException(
          XWikiException.MODULE_XWIKI_EXPORT,
          XWikiException.ERROR_XWIKI_INIT_FAILED,
          "Failed to initialize Execution Context",
          e);
    } finally {
      // We must ensure that the new request we've used is removed so that the current
      // thread can continue to use its original Execution Context.
      execution.popContext();

      context.put("vcontext", oldVelocityContext);
    }
  }
 @Override
 public void initialize(ExecutionContext executionContext) throws ExecutionContextException {
   // We're storing an instance of the Script Context class in the Execution Context so that it can
   // be
   // shared between different script invocations during the lifetime of the Execution Context.
   executionContext.setProperty(SCRIPT_CONTEXT_ID, new SimpleScriptContext());
 }
  @Test
  public void verifyToString() throws Exception {
    Session session = Session.getDefaultInstance(new Properties());
    MimeMessage message = new MimeMessage(session);
    String batchId = UUID.randomUUID().toString();

    ExecutionContext context = new ExecutionContext();
    XWikiContext xContext = new XWikiContext();
    xContext.setWikiId("wiki");
    context.setProperty(XWikiContext.EXECUTIONCONTEXT_KEY, xContext);

    PrepareMailQueueItem item =
        new PrepareMailQueueItem(Arrays.asList(message), session, null, batchId, context);

    assertEquals(
        "batchId = ["
            + batchId
            + "], context = [[xwikicontext] = [{originalWiki=wiki, wiki=wiki}]]",
        item.toString());
  }
  @Before
  public void setUp() throws Exception {
    Utils.setComponentManager(this.componentManager);

    Execution execution = this.componentManager.getInstance(Execution.class);
    ExecutionContext context = new ExecutionContext();

    this.xwiki = mock(XWiki.class);

    this.xwikiContext = new XWikiContext();
    this.xwikiContext.setDatabase("somewiki");
    this.xwikiContext.setWiki(this.xwiki);

    context.setProperty("xwikicontext", this.xwikiContext);

    final DocumentReference configDocReference =
        new DocumentReference("somewiki", "IRC", "IRCConfiguration");
    this.configDoc = mock(XWikiDocument.class);

    when(execution.getContext()).thenReturn(context);
    when(xwiki.getDocument(configDocReference, xwikiContext)).thenReturn(configDoc);
    when(configDoc.getDocumentReference()).thenReturn(configDocReference);
  }
 protected void setContext(XWikiContext ctx) {
   executionContext.setProperty(XWikiContext.EXECUTIONCONTEXT_KEY, ctx);
 }
  @Before
  public void setUp() throws Exception {
    EntityReferenceSerializer<String> localSerializer =
        mocker.getInstance(EntityReferenceSerializer.TYPE_STRING, "local");
    EntityReferenceSerializer<String> serializer =
        mocker.getInstance(EntityReferenceSerializer.TYPE_STRING, "default");

    // No locale provided.
    documentReference = new DocumentReference("wiki", "space", "name");
    documentReferenceString = serializer.serialize(documentReference);
    documentReferenceLocalString = localSerializer.serialize(documentReference);

    language = "en";
    renderedContent = "content";
    title = "title";
    version = "1.1";
    hidden = false;
    date = new Date();
    creationDate = new Date();

    authorReference = new DocumentReference("wiki", "space", "author");
    authorString = serializer.serialize(authorReference);
    authorDisplay = "Au Thor";

    creatorReference = new DocumentReference("wiki", "space", "Creator");
    creatorString = serializer.serialize(creatorReference);
    creatorDisplay = "Crea Tor";

    // Mock

    mockContext = mock(XWikiContext.class);
    Execution mockExecution = mocker.getInstance(Execution.class);
    ExecutionContext mockExecutionContext = new ExecutionContext();
    mockExecutionContext.setProperty(XWikiContext.EXECUTIONCONTEXT_KEY, mockContext);

    when(mockExecution.getContext()).thenReturn(mockExecutionContext);

    mockXWiki = mock(XWiki.class);
    mockDocument = mock(XWikiDocument.class);

    when(mockContext.getWiki()).thenReturn(mockXWiki);
    when(mockXWiki.getDocument(documentReference, mockContext)).thenReturn(mockDocument);

    when(mockDocument.getRealLanguage()).thenReturn(language);
    when(mockDocument.getTranslatedDocument(any(String.class), eq(mockContext)))
        .thenReturn(mockDocument);

    mockDab = mocker.getInstance(DocumentAccessBridge.class);
    when(mockDab.getDocument(documentReference)).thenReturn(mockDocument);

    BlockRenderer mockPlainRenderer = mocker.getInstance(BlockRenderer.class, "plain/1.0");
    doAnswer(
            new Answer<Object>() {
              public Object answer(InvocationOnMock invocation) {
                Object[] args = invocation.getArguments();

                WikiPrinter printer = (WikiPrinter) args[1];
                printer.print(renderedContent);

                return null;
              }
            })
        .when(mockPlainRenderer)
        .render(any(Block.class), any(WikiPrinter.class));

    when(mockDocument.getRenderedTitle(any(Syntax.class), eq(mockContext))).thenReturn(title);

    when(mockDocument.getVersion()).thenReturn(version);

    when(mockDocument.getAuthorReference()).thenReturn(authorReference);
    when(mockXWiki.getUserName(authorString, null, false, mockContext)).thenReturn(authorDisplay);

    when(mockDocument.getCreatorReference()).thenReturn(creatorReference);
    when(mockXWiki.getUserName(creatorString, null, false, mockContext)).thenReturn(creatorDisplay);

    when(mockDocument.getCreationDate()).thenReturn(creationDate);
    when(mockDocument.getContentUpdateDate()).thenReturn(date);

    when(mockDocument.isHidden()).thenReturn(hidden);
  }