Example usage for javax.script SimpleScriptContext SimpleScriptContext

List of usage examples for javax.script SimpleScriptContext SimpleScriptContext

Introduction

In this page you can find the example usage for javax.script SimpleScriptContext SimpleScriptContext.

Prototype

public SimpleScriptContext() 

Source Link

Document

Create a SimpleScriptContext .

Usage

From source file:org.opennms.features.topology.plugins.topo.graphml.GraphMLEdgeStatusProvider.java

private GraphMLEdgeStatus computeEdgeStatus(final List<StatusScript> scripts, final GraphMLEdge edge) {
    return scripts.stream().flatMap(script -> {
        final SimpleBindings bindings = createBindings(edge);
        final StringWriter writer = new StringWriter();
        final ScriptContext context = new SimpleScriptContext();
        context.setWriter(writer);/*from  w  ww  .  j  a  v a  2 s.co m*/
        context.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
        try {
            LOG.debug("Executing script: {}", script);
            final GraphMLEdgeStatus status = script.eval(context);
            if (status != null) {
                return Stream.of(status);
            } else {
                return Stream.empty();
            }
        } catch (final ScriptException e) {
            LOG.error("Failed to execute script: {}", e);
            return Stream.empty();
        } finally {
            LOG.info(writer.toString());
        }
    }).reduce(GraphMLEdgeStatus::merge).orElse(null);
}

From source file:org.freeplane.plugin.script.GenericScript.java

private SimpleScriptContext createScriptContext(final NodeModel node) {
    final SimpleScriptContext context = new SimpleScriptContext();
    final OutputStreamWriter outWriter = new OutputStreamWriter(outStream);
    context.setWriter(outWriter);//from  www  .  j  av a  2s.  c  o m
    context.setErrorWriter(outWriter);
    context.setBindings(createBinding(node), javax.script.ScriptContext.ENGINE_SCOPE);
    return context;
}

From source file:com.hypersocket.upgrade.UpgradeServiceImpl.java

private void executeScript(Map<String, Object> beans, URL script) throws ScriptException, IOException {
    if (log.isInfoEnabled()) {
        log.info("Executing script " + script);
    }/*from  ww w  .j  a  v a  2 s .  c  om*/

    if (script.getPath().endsWith(".js")) {
        ScriptContext context = new SimpleScriptContext();
        ScriptEngine engine = buildEngine(beans, script, context);
        InputStream openStream = script.openStream();
        if (openStream == null) {
            throw new FileNotFoundException("Could not locate resource " + script);
        }
        Reader in = new InputStreamReader(openStream);
        try {
            engine.eval(in, context);
        } finally {
            in.close();
        }
    } else if (script.getPath().endsWith(".class")) {
        String path = script.getPath();
        int idx = path.indexOf("upgrade/");
        path = path.substring(idx);
        idx = path.lastIndexOf(".");
        path = path.substring(0, idx).replace("/", ".");
        try {
            @SuppressWarnings("unchecked")
            Class<? extends Runnable> clazz = (Class<? extends Runnable>) getClass().getClassLoader()
                    .loadClass(path);
            Runnable r = clazz.newInstance();
            springContext.getAutowireCapableBeanFactory().autowireBean(r);
            r.run();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else {

        BufferedReader r = new BufferedReader(new InputStreamReader(script.openStream()));
        try {
            String statement = "";
            String line;
            boolean ignoreErrors = false;
            while ((line = r.readLine()) != null) {
                line = line.trim();
                if (line.startsWith("EXIT IF FRESH")) {
                    if (isFreshInstall()) {
                        break;
                    }
                    continue;
                }

                if (!line.startsWith("/*") && !line.startsWith("//")) {
                    if (line.endsWith(";")) {
                        line = line.substring(0, line.length() - 1);
                        statement += line;
                        sessionFactory.getCurrentSession().createSQLQuery(statement).executeUpdate();
                        statement = "";
                    } else {
                        statement += line + "\n";
                    }
                }
            }

            if (StringUtils.isNotBlank(statement)) {
                try {
                    sessionFactory.getCurrentSession().createSQLQuery(statement).executeUpdate();
                } catch (Throwable e) {
                    if (!ignoreErrors) {
                        throw e;
                    }
                }
            }
        } finally {
            r.close();
        }
    }

}

From source file:org.jahia.services.content.rules.RulesNotificationService.java

private void sendMail(String template, Object user, String toMail, String fromMail, String ccList,
        String bcclist, Locale locale, KnowledgeHelper drools)
        throws RepositoryException, ScriptException, IOException {
    if (!notificationService.isEnabled()) {
        return;/*from  w w w  . ja v a  2  s  . c  o  m*/
    }
    if (StringUtils.isEmpty(toMail)) {
        logger.warn("A mail couldn't be sent because to: has no recipient");
        return;
    }

    // Resolve template :
    String extension = StringUtils.substringAfterLast(template, ".");
    ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension);
    ScriptContext scriptContext = new SimpleScriptContext();
    final Bindings bindings = new SimpleBindings();
    bindings.put("currentUser", user);
    bindings.put("contextPath", Jahia.getContextPath());
    bindings.put("currentLocale", locale);
    final Object object = drools.getMatch().getTuple().getHandle().getObject();
    JCRNodeWrapper node = null;
    if (object instanceof AbstractNodeFact) {
        node = ((AbstractNodeFact) object).getNode();
        bindings.put("currentNode", node);
        final int siteURLPortOverride = SettingsBean.getInstance().getSiteURLPortOverride();
        bindings.put("servername",
                "http" + (siteURLPortOverride == 443 ? "s" : "") + "://" + node.getResolveSite().getServerName()
                        + ((siteURLPortOverride != 0 && siteURLPortOverride != 80 && siteURLPortOverride != 443)
                                ? ":" + siteURLPortOverride
                                : ""));
    }
    InputStream scriptInputStream = JahiaContextLoaderListener.getServletContext()
            .getResourceAsStream(template);
    if (scriptInputStream == null && node != null) {
        RulesListener rulesListener = RulesListener.getInstance(node.getSession().getWorkspace().getName());
        String packageName = drools.getRule().getPackageName();
        JahiaTemplateManagerService jahiaTemplateManagerService = ServicesRegistry.getInstance()
                .getJahiaTemplateManagerService();
        for (Map.Entry<String, String> entry : rulesListener.getModulePackageNameMap().entrySet()) {
            if (packageName.equals(entry.getValue())) {
                JahiaTemplatesPackage templatePackage = jahiaTemplateManagerService
                        .getTemplatePackage(entry.getKey());
                Resource resource = templatePackage.getResource(template);
                if (resource != null) {
                    scriptInputStream = resource.getInputStream();
                    break;
                }
            }
        }
    }
    if (scriptInputStream != null) {
        String resourceBundleName = StringUtils.substringBeforeLast(Patterns.SLASH
                .matcher(StringUtils.substringAfter(Patterns.WEB_INF.matcher(template).replaceAll(""), "/"))
                .replaceAll("."), ".");
        String subject = "";
        try {
            ResourceBundle resourceBundle = ResourceBundles.get(resourceBundleName, locale);
            bindings.put("bundle", resourceBundle);
            subject = resourceBundle.getString("subject");
        } catch (MissingResourceException e) {
            if (node != null) {
                final Value[] values = node.getResolveSite().getProperty("j:installedModules").getValues();
                for (Value value : values) {
                    try {
                        ResourceBundle resourceBundle = ResourceBundles
                                .get(ServicesRegistry.getInstance().getJahiaTemplateManagerService()
                                        .getTemplatePackageById(value.getString()).getName(), locale);
                        subject = resourceBundle.getString(
                                drools.getRule().getName().toLowerCase().replaceAll(" ", ".") + ".subject");
                        bindings.put("bundle", resourceBundle);
                    } catch (MissingResourceException ee) {
                        // Do nothing
                    }
                }
            }
        }
        Reader scriptContent = null;
        try {
            scriptContent = new InputStreamReader(scriptInputStream);
            scriptContext.setWriter(new StringWriter());
            // The following binding is necessary for Javascript, which doesn't offer a console by default.
            bindings.put("out", new PrintWriter(scriptContext.getWriter()));
            scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
            scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE),
                    ScriptContext.GLOBAL_SCOPE);
            scriptEngine.eval(scriptContent, scriptContext);
            StringWriter writer = (StringWriter) scriptContext.getWriter();
            String body = writer.toString();
            notificationService.sendMessage(fromMail, toMail, ccList, bcclist, subject, null, body);
        } finally {
            if (scriptContent != null) {
                IOUtils.closeQuietly(scriptContent);
            }
        }
    }
}

From source file:com.aionemu.commons.scripting.AionScriptEngineManager.java

public void executeScript(ScriptEngine engine, File file) throws FileNotFoundException, ScriptException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

    if (VERBOSE_LOADING) {
        log.info("Loading Script: " + file.getAbsolutePath());
    }/*from  w w w. ja v a 2  s  .  c  o  m*/

    if (PURGE_ERROR_LOG) {
        String name = file.getAbsolutePath() + ".error.log";
        File errorLog = new File(name);
        if (errorLog.isFile()) {
            errorLog.delete();
        }
    }

    if (engine instanceof Compilable && ATTEMPT_COMPILATION) {
        ScriptContext context = new SimpleScriptContext();
        context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'),
                ScriptContext.ENGINE_SCOPE);
        context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE);

        setCurrentLoadingScript(file);
        ScriptContext ctx = engine.getContext();
        try {
            engine.setContext(context);
            if (USE_COMPILED_CACHE) {
                CompiledScript cs = _cache.loadCompiledScript(engine, file);
                cs.eval(context);
            } else {
                Compilable eng = (Compilable) engine;
                CompiledScript cs = eng.compile(reader);
                cs.eval(context);
            }
        } finally {
            engine.setContext(ctx);
            setCurrentLoadingScript(null);
            context.removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE);
            context.removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE);
            context.removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE);
        }
    } else {
        ScriptContext context = new SimpleScriptContext();
        context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'),
                ScriptContext.ENGINE_SCOPE);
        context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE);
        setCurrentLoadingScript(file);
        try {
            engine.eval(reader, context);
        } finally {
            setCurrentLoadingScript(null);
            engine.getContext().removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE);
            engine.getContext().removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE);
            engine.getContext().removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE);
        }

    }
}

From source file:com.l2jfree.gameserver.scripting.L2ScriptEngineManager.java

public void executeScript(ScriptEngine engine, File file) throws FileNotFoundException, ScriptException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

    if (VERBOSE_LOADING) {
        _log.info("Loading Script: " + file.getAbsolutePath());
    }/* w ww.  j a  va  2s  .  c om*/

    if (PURGE_ERROR_LOG) {
        String name = file.getAbsolutePath() + ".error.log";
        File errorLog = new File(name);
        if (errorLog.isFile()) {
            errorLog.delete();
        }
    }

    if (engine instanceof Compilable && ATTEMPT_COMPILATION) {
        ScriptContext context = new SimpleScriptContext();
        context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'),
                ScriptContext.ENGINE_SCOPE);
        context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE);

        setCurrentLoadingScript(file);
        ScriptContext ctx = engine.getContext();
        try {
            engine.setContext(context);
            if (USE_COMPILED_CACHE) {
                CompiledScript cs = _cache.loadCompiledScript(engine, file);
                cs.eval(context);
            } else {
                Compilable eng = (Compilable) engine;
                CompiledScript cs = eng.compile(reader);
                cs.eval(context);
            }
        } finally {
            engine.setContext(ctx);
            setCurrentLoadingScript(null);
            context.removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE);
            context.removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE);
            context.removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE);
        }
    } else {
        ScriptContext context = new SimpleScriptContext();
        context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'),
                ScriptContext.ENGINE_SCOPE);
        context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE);
        setCurrentLoadingScript(file);
        try {
            engine.eval(reader, context);
        } finally {
            setCurrentLoadingScript(null);
            engine.getContext().removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE);
            engine.getContext().removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE);
            engine.getContext().removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE);
        }

    }
}

From source file:org.jahia.services.mail.MailServiceImpl.java

@Override
public void sendMessageWithTemplate(String template, Map<String, Object> boundObjects, String toMail,
        String fromMail, String ccList, String bcclist, Locale locale, String templatePackageName)
        throws RepositoryException, ScriptException {
    // Resolve template :
    ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(StringUtils.substringAfterLast(template, "."));
    ScriptContext scriptContext = new SimpleScriptContext();

    //try if it is multilingual 
    String suffix = StringUtils.substringAfterLast(template, ".");
    String languageMailConfTemplate = template.substring(0, template.length() - (suffix.length() + 1)) + "_"
            + locale.toString() + "." + suffix;
    JahiaTemplatesPackage templatePackage = templateManagerService.getTemplatePackage(templatePackageName);
    Resource templateRealPath = templatePackage.getResource(languageMailConfTemplate);
    if (templateRealPath == null) {
        templateRealPath = templatePackage.getResource(template);
    }/* w ww  . ja  va2s.  c  o m*/
    InputStream scriptInputStream = null;
    try {
        scriptInputStream = templateRealPath.getInputStream();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    if (scriptInputStream != null) {
        ResourceBundle resourceBundle;
        if (templatePackageName == null) {
            String resourceBundleName = StringUtils.substringBeforeLast(Patterns.SLASH
                    .matcher(StringUtils.substringAfter(Patterns.WEB_INF.matcher(template).replaceAll(""), "/"))
                    .replaceAll("."), ".");
            resourceBundle = ResourceBundles.get(resourceBundleName, locale);
        } else {
            resourceBundle = ResourceBundles.get(ServicesRegistry.getInstance().getJahiaTemplateManagerService()
                    .getTemplatePackage(templatePackageName), locale);
        }
        final Bindings bindings = new SimpleBindings();
        bindings.put("bundle", resourceBundle);
        bindings.putAll(boundObjects);
        Reader scriptContent = null;
        // Subject
        String subject;
        try {
            String subjectTemplatePath = StringUtils.substringBeforeLast(template, ".") + ".subject."
                    + StringUtils.substringAfterLast(template, ".");
            InputStream stream = templatePackage.getResource(subjectTemplatePath).getInputStream();
            scriptContent = templateCharset != null ? new InputStreamReader(stream, templateCharset)
                    : new InputStreamReader(stream);
            scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
            scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE),
                    ScriptContext.GLOBAL_SCOPE);
            scriptContext.setWriter(new StringWriter());
            scriptEngine.eval(scriptContent, scriptContext);
            subject = scriptContext.getWriter().toString().trim();
        } catch (Exception e) {
            logger.warn("Not able to render mail subject using "
                    + StringUtils.substringBeforeLast(template, ".") + ".subject."
                    + StringUtils.substringAfterLast(template, ".")
                    + " template file - set org.jahia.services.mail.MailService in debug for more information");
            if (logger.isDebugEnabled()) {
                logger.debug("generating the mail subject throw an exception : ", e);
            }
            subject = resourceBundle.getString(
                    StringUtils.substringBeforeLast(StringUtils.substringAfterLast(template, "/"), ".")
                            + ".subject");
        } finally {
            IOUtils.closeQuietly(scriptContent);
        }
        try {
            try {
                scriptContent = templateCharset != null
                        ? new InputStreamReader(scriptInputStream, templateCharset)
                        : new InputStreamReader(scriptInputStream);
            } catch (UnsupportedEncodingException e) {
                throw new IllegalArgumentException(e);
            }
            scriptContext.setWriter(new StringWriter());
            scriptContext.setErrorWriter(new StringWriter());
            // The following binding is necessary for JavaScript, which
            // doesn't offer a console by default.
            bindings.put("out", new PrintWriter(scriptContext.getWriter()));
            scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
            scriptEngine.eval(scriptContent, scriptContext);
            StringWriter writer = (StringWriter) scriptContext.getWriter();
            String body = writer.toString();

            sendMessage(fromMail, toMail, ccList, bcclist, subject, null, body);
        } finally {
            IOUtils.closeQuietly(scriptContent);
        }
    } else {
        logger.warn("Cannot send mail, template [" + template + "] from module [" + templatePackageName
                + "] not found");
    }
}

From source file:com.xpn.xwiki.test.MockitoOldcore.java

public void before(Class<?> testClass) throws Exception {
    // Statically store the component manager in {@link Utils} to be able to access it without
    // the context.
    Utils.setComponentManager(getMocker());

    this.context = new XWikiContext();

    getXWikiContext().setWikiId("xwiki");
    getXWikiContext().setMainXWiki("xwiki");

    this.spyXWiki = spy(new XWiki());
    getXWikiContext().setWiki(this.spyXWiki);

    this.mockHibernateStore = mock(XWikiHibernateStore.class);
    this.mockVersioningStore = mock(XWikiVersioningStoreInterface.class);
    this.mockRightService = mock(XWikiRightService.class);
    this.mockGroupService = mock(XWikiGroupService.class);

    doReturn(this.mockHibernateStore).when(this.spyXWiki).getStore();
    doReturn(this.mockHibernateStore).when(this.spyXWiki).getHibernateStore();
    doReturn(this.mockVersioningStore).when(this.spyXWiki).getVersioningStore();
    doReturn(this.mockRightService).when(this.spyXWiki).getRightService();
    doReturn(this.mockGroupService).when(this.spyXWiki).getGroupService(getXWikiContext());

    // We need to initialize the Component Manager so that the components can be looked up
    getXWikiContext().put(ComponentManager.class.getName(), getMocker());

    if (testClass.getAnnotation(AllComponents.class) != null) {
        // If @AllComponents is enabled force mocking AuthorizationManager and ContextualAuthorizationManager if not
        // already mocked
        this.mockAuthorizationManager = getMocker().registerMockComponent(AuthorizationManager.class, false);
        this.mockContextualAuthorizationManager = getMocker()
                .registerMockComponent(ContextualAuthorizationManager.class, false);
    } else {//from ww  w  .j a  v a2 s  . c  om
        // Make sure an AuthorizationManager and a ContextualAuthorizationManager is available
        if (!getMocker().hasComponent(AuthorizationManager.class)) {
            this.mockAuthorizationManager = getMocker().registerMockComponent(AuthorizationManager.class);
        }
        if (!getMocker().hasComponent(ContextualAuthorizationManager.class)) {
            this.mockContextualAuthorizationManager = getMocker()
                    .registerMockComponent(ContextualAuthorizationManager.class);
        }
    }

    // Make sure a default ConfigurationSource is available
    if (!getMocker().hasComponent(ConfigurationSource.class)) {
        this.configurationSource = getMocker().registerMemoryConfigurationSource();
    }

    // Make sure a "xwikicfg" ConfigurationSource is available
    if (!getMocker().hasComponent(ConfigurationSource.class, XWikiCfgConfigurationSource.ROLEHINT)) {
        this.xwikicfgConfigurationSource = new MockConfigurationSource();
        getMocker().registerComponent(
                MockConfigurationSource.getDescriptor(XWikiCfgConfigurationSource.ROLEHINT),
                this.xwikicfgConfigurationSource);
    }
    // Make sure a "wiki" ConfigurationSource is available
    if (!getMocker().hasComponent(ConfigurationSource.class, "wiki")) {
        this.wikiConfigurationSource = new MockConfigurationSource();
        getMocker().registerComponent(MockConfigurationSource.getDescriptor("wiki"),
                this.wikiConfigurationSource);
    }

    // Make sure a "space" ConfigurationSource is available
    if (!getMocker().hasComponent(ConfigurationSource.class, "space")) {
        this.spaceConfigurationSource = new MockConfigurationSource();
        getMocker().registerComponent(MockConfigurationSource.getDescriptor("space"),
                this.spaceConfigurationSource);
    }

    // Since the oldcore module draws the Servlet Environment in its dependencies we need to ensure it's set up
    // correctly with a Servlet Context.
    if (getMocker().hasComponent(Environment.class)
            && getMocker().getInstance(Environment.class) instanceof ServletEnvironment) {
        ServletEnvironment environment = getMocker().getInstance(Environment.class);

        ServletContext servletContextMock = mock(ServletContext.class);
        environment.setServletContext(servletContextMock);
        when(servletContextMock.getAttribute("javax.servlet.context.tempdir"))
                .thenReturn(new File(System.getProperty("java.io.tmpdir")));

        File testDirectory = new File("target/test-" + new Date().getTime());
        this.temporaryDirectory = new File(testDirectory, "temporary-dir");
        this.permanentDirectory = new File(testDirectory, "permanent-dir");
        environment.setTemporaryDirectory(this.temporaryDirectory);
        environment.setPermanentDirectory(this.permanentDirectory);
    }

    // Initialize the Execution Context
    if (this.componentManager.hasComponent(ExecutionContextManager.class)) {
        ExecutionContextManager ecm = this.componentManager.getInstance(ExecutionContextManager.class);
        ExecutionContext ec = new ExecutionContext();
        ecm.initialize(ec);
    }

    // Bridge with old XWiki Context, required for old code.
    Execution execution;
    if (this.componentManager.hasComponent(Execution.class)) {
        execution = this.componentManager.getInstance(Execution.class);
    } else {
        execution = this.componentManager.registerMockComponent(Execution.class);
    }
    ExecutionContext econtext;
    if (MockUtil.isMock(execution)) {
        econtext = new ExecutionContext();
        when(execution.getContext()).thenReturn(econtext);
    } else {
        econtext = execution.getContext();
    }

    // Set a few standard things in the ExecutionContext
    econtext.setProperty(XWikiContext.EXECUTIONCONTEXT_KEY, this.context);
    this.scriptContext = (ScriptContext) econtext
            .getProperty(ScriptExecutionContextInitializer.SCRIPT_CONTEXT_ID);
    if (this.scriptContext == null) {
        this.scriptContext = new SimpleScriptContext();
        econtext.setProperty(ScriptExecutionContextInitializer.SCRIPT_CONTEXT_ID, this.scriptContext);
    }

    if (!this.componentManager.hasComponent(ScriptContextManager.class)) {
        ScriptContextManager scriptContextManager = this.componentManager
                .registerMockComponent(ScriptContextManager.class);
        when(scriptContextManager.getCurrentScriptContext()).thenReturn(this.scriptContext);
        when(scriptContextManager.getScriptContext()).thenReturn(this.scriptContext);
    }

    // Initialize XWikiContext provider
    if (!this.componentManager.hasComponent(XWikiContext.TYPE_PROVIDER)) {
        Provider<XWikiContext> xcontextProvider = this.componentManager
                .registerMockComponent(XWikiContext.TYPE_PROVIDER);
        when(xcontextProvider.get()).thenReturn(this.context);
    } else {
        Provider<XWikiContext> xcontextProvider = this.componentManager.getInstance(XWikiContext.TYPE_PROVIDER);
        if (MockUtil.isMock(xcontextProvider)) {
            when(xcontextProvider.get()).thenReturn(this.context);
        }
    }

    // Initialize readonly XWikiContext provider
    if (!this.componentManager.hasComponent(XWikiContext.TYPE_PROVIDER, "readonly")) {
        Provider<XWikiContext> xcontextProvider = this.componentManager
                .registerMockComponent(XWikiContext.TYPE_PROVIDER, "readonly");
        when(xcontextProvider.get()).thenReturn(this.context);
    } else {
        Provider<XWikiContext> xcontextProvider = this.componentManager.getInstance(XWikiContext.TYPE_PROVIDER);
        if (MockUtil.isMock(xcontextProvider)) {
            when(xcontextProvider.get()).thenReturn(this.context);
        }
    }

    // Initialize stub context provider
    if (this.componentManager.hasComponent(XWikiStubContextProvider.class)) {
        XWikiStubContextProvider stubContextProvider = this.componentManager
                .getInstance(XWikiStubContextProvider.class);
        if (!MockUtil.isMock(stubContextProvider)) {
            stubContextProvider.initialize(this.context);
        }
    }

    // Make sure to have a mocked CoreConfiguration (even if one already exist)
    if (!this.componentManager.hasComponent(CoreConfiguration.class)) {
        CoreConfiguration coreConfigurationMock = this.componentManager
                .registerMockComponent(CoreConfiguration.class);
        when(coreConfigurationMock.getDefaultDocumentSyntax()).thenReturn(Syntax.XWIKI_2_1);
    } else {
        CoreConfiguration coreConfiguration = this.componentManager
                .registerMockComponent(CoreConfiguration.class, false);
        if (MockUtil.isMock(coreConfiguration)) {
            when(coreConfiguration.getDefaultDocumentSyntax()).thenReturn(Syntax.XWIKI_2_1);
        }
    }

    // Set a context ComponentManager if none exist
    if (!this.componentManager.hasComponent(ComponentManager.class, "context")) {
        DefaultComponentDescriptor<ComponentManager> componentManagerDescriptor = new DefaultComponentDescriptor<>();
        componentManagerDescriptor.setRoleHint("context");
        componentManagerDescriptor.setRoleType(ComponentManager.class);
        this.componentManager.registerComponent(componentManagerDescriptor, this.componentManager);
    }

    // XWiki

    doAnswer(new Answer<XWikiDocument>() {
        @Override
        public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
            XWikiDocument doc = invocation.getArgument(0);
            String revision = invocation.getArgument(1);

            if (StringUtils.equals(revision, doc.getVersion())) {
                return doc;
            }

            // TODO: implement version store mocking
            return new XWikiDocument(doc.getDocumentReference());
        }
    }).when(getSpyXWiki()).getDocument(anyXWikiDocument(), any(), anyXWikiContext());
    doAnswer(new Answer<XWikiDocument>() {
        @Override
        public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
            DocumentReference target = invocation.getArgument(0);

            if (target.getLocale() == null) {
                target = new DocumentReference(target, Locale.ROOT);
            }

            XWikiDocument document = documents.get(target);

            if (document == null) {
                document = new XWikiDocument(target, target.getLocale());
                document.setSyntax(Syntax.PLAIN_1_0);
                document.setOriginalDocument(document.clone());
            }

            return document;
        }
    }).when(getSpyXWiki()).getDocument(any(DocumentReference.class), anyXWikiContext());
    doAnswer(new Answer<XWikiDocument>() {
        @Override
        public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
            XWikiDocument target = invocation.getArgument(0);

            return getSpyXWiki().getDocument(target.getDocumentReferenceWithLocale(),
                    invocation.getArgument(1));
        }
    }).when(getSpyXWiki()).getDocument(anyXWikiDocument(), any(XWikiContext.class));
    doAnswer(new Answer<Boolean>() {
        @Override
        public Boolean answer(InvocationOnMock invocation) throws Throwable {
            DocumentReference target = (DocumentReference) invocation.getArguments()[0];

            if (target.getLocale() == null) {
                target = new DocumentReference(target, Locale.ROOT);
            }

            return documents.containsKey(target);
        }
    }).when(getSpyXWiki()).exists(any(DocumentReference.class), anyXWikiContext());
    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            XWikiDocument document = invocation.getArgument(0);
            String comment = invocation.getArgument(1);
            boolean minorEdit = invocation.getArgument(2);

            boolean isNew = document.isNew();

            document.setComment(StringUtils.defaultString(comment));
            document.setMinorEdit(minorEdit);

            if (document.isContentDirty() || document.isMetaDataDirty()) {
                document.setDate(new Date());
                if (document.isContentDirty()) {
                    document.setContentUpdateDate(new Date());
                    document.setContentAuthorReference(document.getAuthorReference());
                }
                document.incrementVersion();

                document.setContentDirty(false);
                document.setMetaDataDirty(false);
            }
            document.setNew(false);
            document.setStore(getMockStore());

            XWikiDocument previousDocument = documents.get(document.getDocumentReferenceWithLocale());

            if (previousDocument != null && previousDocument != document) {
                for (XWikiAttachment attachment : document.getAttachmentList()) {
                    if (!attachment.isContentDirty()) {
                        attachment.setAttachment_content(previousDocument
                                .getAttachment(attachment.getFilename()).getAttachment_content());
                    }
                }
            }

            XWikiDocument originalDocument = document.getOriginalDocument();
            if (originalDocument == null) {
                originalDocument = spyXWiki.getDocument(document.getDocumentReferenceWithLocale(), context);
                document.setOriginalDocument(originalDocument);
            }

            XWikiDocument savedDocument = document.clone();

            documents.put(document.getDocumentReferenceWithLocale(), savedDocument);

            if (isNew) {
                if (notifyDocumentCreatedEvent) {
                    getObservationManager().notify(new DocumentCreatedEvent(document.getDocumentReference()),
                            document, getXWikiContext());
                }
            } else {
                if (notifyDocumentUpdatedEvent) {
                    getObservationManager().notify(new DocumentUpdatedEvent(document.getDocumentReference()),
                            document, getXWikiContext());
                }
            }

            // Set the document as it's original document
            savedDocument.setOriginalDocument(savedDocument.clone());

            return null;
        }
    }).when(getSpyXWiki()).saveDocument(anyXWikiDocument(), any(String.class), anyBoolean(), anyXWikiContext());
    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            XWikiDocument document = invocation.getArgument(0);

            documents.remove(document.getDocumentReferenceWithLocale());

            if (notifyDocumentDeletedEvent) {
                getObservationManager().notify(new DocumentDeletedEvent(document.getDocumentReference()),
                        document, getXWikiContext());
            }

            return null;
        }
    }).when(getSpyXWiki()).deleteDocument(anyXWikiDocument(), any(Boolean.class), anyXWikiContext());
    doAnswer(new Answer<BaseClass>() {
        @Override
        public BaseClass answer(InvocationOnMock invocation) throws Throwable {
            return getSpyXWiki()
                    .getDocument((DocumentReference) invocation.getArguments()[0], invocation.getArgument(1))
                    .getXClass();
        }
    }).when(getSpyXWiki()).getXClass(any(DocumentReference.class), anyXWikiContext());
    doAnswer(new Answer<String>() {
        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            return getXWikiContext().getLanguage();
        }
    }).when(getSpyXWiki()).getLanguagePreference(anyXWikiContext());

    getXWikiContext().setLocale(Locale.ENGLISH);

    // XWikiStoreInterface

    when(getMockStore().getTranslationList(anyXWikiDocument(), anyXWikiContext()))
            .then(new Answer<List<String>>() {
                @Override
                public List<String> answer(InvocationOnMock invocation) throws Throwable {
                    XWikiDocument document = invocation.getArgument(0);

                    List<String> translations = new ArrayList<String>();

                    for (XWikiDocument storedDocument : documents.values()) {
                        Locale storedLocale = storedDocument.getLocale();
                        if (!storedLocale.equals(Locale.ROOT) && storedDocument.getDocumentReference()
                                .equals(document.getDocumentReference())) {
                            translations.add(storedLocale.toString());
                        }
                    }

                    return translations;
                }
            });
    when(getMockStore().loadXWikiDoc(anyXWikiDocument(), anyXWikiContext())).then(new Answer<XWikiDocument>() {
        @Override
        public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
            // The store is based on the contex for the wiki
            DocumentReference reference = invocation.<XWikiDocument>getArgument(0).getDocumentReference();
            XWikiContext xcontext = invocation.getArgument(1);
            if (!xcontext.getWikiReference().equals(reference.getWikiReference())) {
                reference = reference.setWikiReference(xcontext.getWikiReference());
            }

            return getSpyXWiki().getDocument(reference, xcontext);
        }
    });
    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            // The store is based on the contex for the wiki
            DocumentReference reference = invocation.<XWikiDocument>getArgument(0)
                    .getDocumentReferenceWithLocale();
            XWikiContext xcontext = invocation.getArgument(1);
            if (!xcontext.getWikiReference().equals(reference.getWikiReference())) {
                reference = reference.setWikiReference(xcontext.getWikiReference());
            }

            documents.remove(reference);

            return null;
        }
    }).when(getMockStore()).deleteXWikiDoc(anyXWikiDocument(), anyXWikiContext());

    // Users

    doAnswer(new Answer<BaseClass>() {
        @Override
        public BaseClass answer(InvocationOnMock invocation) throws Throwable {
            XWikiContext xcontext = invocation.getArgument(0);

            XWikiDocument userDocument = getSpyXWiki().getDocument(
                    new DocumentReference(USER_CLASS, new WikiReference(xcontext.getWikiId())), xcontext);

            final BaseClass userClass = userDocument.getXClass();

            if (userDocument.isNew()) {
                userClass.addTextField("first_name", "First Name", 30);
                userClass.addTextField("last_name", "Last Name", 30);
                userClass.addEmailField("email", "e-Mail", 30);
                userClass.addPasswordField("password", "Password", 10);
                userClass.addBooleanField("active", "Active", "active");
                userClass.addTextAreaField("comment", "Comment", 40, 5);
                userClass.addTextField("avatar", "Avatar", 30);
                userClass.addTextField("phone", "Phone", 30);
                userClass.addTextAreaField("address", "Address", 40, 3);

                getSpyXWiki().saveDocument(userDocument, xcontext);
            }

            return userClass;
        }
    }).when(getSpyXWiki()).getUserClass(anyXWikiContext());
    doAnswer(new Answer<BaseClass>() {
        @Override
        public BaseClass answer(InvocationOnMock invocation) throws Throwable {
            XWikiContext xcontext = invocation.getArgument(0);

            XWikiDocument groupDocument = getSpyXWiki().getDocument(
                    new DocumentReference(GROUP_CLASS, new WikiReference(xcontext.getWikiId())), xcontext);

            final BaseClass groupClass = groupDocument.getXClass();

            if (groupDocument.isNew()) {
                groupClass.addTextField("member", "Member", 30);

                getSpyXWiki().saveDocument(groupDocument, xcontext);
            }

            return groupClass;
        }
    }).when(getSpyXWiki()).getGroupClass(anyXWikiContext());

    // Query Manager
    // If there's already a Query Manager registered, use it instead.
    // This allows, for example, using @ComponentList to use the real Query Manager, in integration tests.
    if (!this.componentManager.hasComponent(QueryManager.class)) {
        mockQueryManager();
    }
    when(getMockStore().getQueryManager()).then(new Answer<QueryManager>() {

        @Override
        public QueryManager answer(InvocationOnMock invocation) throws Throwable {
            return getQueryManager();
        }
    });

    // WikiDescriptorManager
    // If there's already a WikiDescriptorManager registered, use it instead.
    // This allows, for example, using @ComponentList to use the real WikiDescriptorManager, in integration tests.
    if (!this.componentManager.hasComponent(WikiDescriptorManager.class)) {
        this.wikiDescriptorManager = getMocker().registerMockComponent(WikiDescriptorManager.class);
        when(this.wikiDescriptorManager.getMainWikiId()).then(new Answer<String>() {
            @Override
            public String answer(InvocationOnMock invocation) throws Throwable {
                return getXWikiContext().getMainXWiki();
            }
        });
        when(this.wikiDescriptorManager.getCurrentWikiId()).then(new Answer<String>() {
            @Override
            public String answer(InvocationOnMock invocation) throws Throwable {
                return getXWikiContext().getWikiId();
            }
        });
    }
}

From source file:com.xpn.xwiki.test.MockitoOldcoreRule.java

protected void before(Class<?> testClass) throws Exception {
    // Statically store the component manager in {@link Utils} to be able to access it without
    // the context.
    Utils.setComponentManager(getMocker());

    this.context = new XWikiContext();

    getXWikiContext().setWikiId("xwiki");
    getXWikiContext().setMainXWiki("xwiki");

    this.spyXWiki = spy(new XWiki());
    getXWikiContext().setWiki(this.spyXWiki);

    this.mockHibernateStore = mock(XWikiHibernateStore.class);
    this.mockVersioningStore = mock(XWikiVersioningStoreInterface.class);
    this.mockRightService = mock(XWikiRightService.class);
    this.mockGroupService = mock(XWikiGroupService.class);

    doReturn(this.mockHibernateStore).when(this.spyXWiki).getStore();
    doReturn(this.mockHibernateStore).when(this.spyXWiki).getHibernateStore();
    doReturn(this.mockVersioningStore).when(this.spyXWiki).getVersioningStore();
    doReturn(this.mockRightService).when(this.spyXWiki).getRightService();
    doReturn(this.mockGroupService).when(this.spyXWiki).getGroupService(getXWikiContext());

    // We need to initialize the Component Manager so that the components can be looked up
    getXWikiContext().put(ComponentManager.class.getName(), getMocker());

    if (testClass.getAnnotation(AllComponents.class) != null) {
        // If @AllComponents is enabled force mocking AuthorizationManager and ContextualAuthorizationManager if not
        // already mocked
        this.mockAuthorizationManager = getMocker().registerMockComponent(AuthorizationManager.class, false);
        this.mockContextualAuthorizationManager = getMocker()
                .registerMockComponent(ContextualAuthorizationManager.class, false);
    } else {//from   www  . j av a  2  s  .  c o m
        // Make sure an AuthorizationManager and a ContextualAuthorizationManager is available
        if (!getMocker().hasComponent(AuthorizationManager.class)) {
            this.mockAuthorizationManager = getMocker().registerMockComponent(AuthorizationManager.class);
        }
        if (!getMocker().hasComponent(ContextualAuthorizationManager.class)) {
            this.mockContextualAuthorizationManager = getMocker()
                    .registerMockComponent(ContextualAuthorizationManager.class);
        }
    }

    // Make sure a default ConfigurationSource is available
    if (!getMocker().hasComponent(ConfigurationSource.class)) {
        this.configurationSource = getMocker().registerMemoryConfigurationSource();
    }

    // Make sure a "xwikicfg" ConfigurationSource is available
    if (!getMocker().hasComponent(ConfigurationSource.class, XWikiCfgConfigurationSource.ROLEHINT)) {
        this.xwikicfgConfigurationSource = new MockConfigurationSource();
        getMocker().registerComponent(
                MockConfigurationSource.getDescriptor(XWikiCfgConfigurationSource.ROLEHINT),
                this.xwikicfgConfigurationSource);
    }
    // Make sure a "wiki" ConfigurationSource is available
    if (!getMocker().hasComponent(ConfigurationSource.class, "wiki")) {
        this.wikiConfigurationSource = new MockConfigurationSource();
        getMocker().registerComponent(MockConfigurationSource.getDescriptor("wiki"),
                this.wikiConfigurationSource);
    }

    // Make sure a "space" ConfigurationSource is available
    if (!getMocker().hasComponent(ConfigurationSource.class, "space")) {
        this.spaceConfigurationSource = new MockConfigurationSource();
        getMocker().registerComponent(MockConfigurationSource.getDescriptor("space"),
                this.spaceConfigurationSource);
    }

    // Since the oldcore module draws the Servlet Environment in its dependencies we need to ensure it's set up
    // correctly with a Servlet Context.
    if (getMocker().hasComponent(Environment.class)
            && getMocker().getInstance(Environment.class) instanceof ServletEnvironment) {
        ServletEnvironment environment = getMocker().getInstance(Environment.class);

        ServletContext servletContextMock = mock(ServletContext.class);
        environment.setServletContext(servletContextMock);
        when(servletContextMock.getAttribute("javax.servlet.context.tempdir"))
                .thenReturn(new File(System.getProperty("java.io.tmpdir")));

        File testDirectory = new File("target/test-" + new Date().getTime());
        this.temporaryDirectory = new File(testDirectory, "temporary-dir");
        this.permanentDirectory = new File(testDirectory, "permanent-dir");
        environment.setTemporaryDirectory(this.temporaryDirectory);
        environment.setPermanentDirectory(this.permanentDirectory);
    }

    // Initialize the Execution Context
    if (this.componentManager.hasComponent(ExecutionContextManager.class)) {
        ExecutionContextManager ecm = this.componentManager.getInstance(ExecutionContextManager.class);
        ExecutionContext ec = new ExecutionContext();
        ecm.initialize(ec);
    }

    // Bridge with old XWiki Context, required for old code.
    Execution execution;
    if (this.componentManager.hasComponent(Execution.class)) {
        execution = this.componentManager.getInstance(Execution.class);
    } else {
        execution = this.componentManager.registerMockComponent(Execution.class);
    }
    ExecutionContext econtext;
    if (MockUtil.isMock(execution)) {
        econtext = new ExecutionContext();
        when(execution.getContext()).thenReturn(econtext);
    } else {
        econtext = execution.getContext();
    }

    // Set a few standard things in the ExecutionContext
    econtext.setProperty(XWikiContext.EXECUTIONCONTEXT_KEY, this.context);
    this.scriptContext = (ScriptContext) econtext
            .getProperty(ScriptExecutionContextInitializer.SCRIPT_CONTEXT_ID);
    if (this.scriptContext == null) {
        this.scriptContext = new SimpleScriptContext();
        econtext.setProperty(ScriptExecutionContextInitializer.SCRIPT_CONTEXT_ID, this.scriptContext);
    }

    if (!this.componentManager.hasComponent(ScriptContextManager.class)) {
        ScriptContextManager scriptContextManager = this.componentManager
                .registerMockComponent(ScriptContextManager.class);
        when(scriptContextManager.getCurrentScriptContext()).thenReturn(this.scriptContext);
        when(scriptContextManager.getScriptContext()).thenReturn(this.scriptContext);
    }

    // Initialize XWikiContext provider
    if (!this.componentManager.hasComponent(XWikiContext.TYPE_PROVIDER)) {
        Provider<XWikiContext> xcontextProvider = this.componentManager
                .registerMockComponent(XWikiContext.TYPE_PROVIDER);
        when(xcontextProvider.get()).thenReturn(this.context);
    } else {
        Provider<XWikiContext> xcontextProvider = this.componentManager.getInstance(XWikiContext.TYPE_PROVIDER);
        if (MockUtil.isMock(xcontextProvider)) {
            when(xcontextProvider.get()).thenReturn(this.context);
        }
    }

    // Initialize readonly XWikiContext provider
    if (!this.componentManager.hasComponent(XWikiContext.TYPE_PROVIDER, "readonly")) {
        Provider<XWikiContext> xcontextProvider = this.componentManager
                .registerMockComponent(XWikiContext.TYPE_PROVIDER, "readonly");
        when(xcontextProvider.get()).thenReturn(this.context);
    } else {
        Provider<XWikiContext> xcontextProvider = this.componentManager.getInstance(XWikiContext.TYPE_PROVIDER);
        if (MockUtil.isMock(xcontextProvider)) {
            when(xcontextProvider.get()).thenReturn(this.context);
        }
    }

    // Initialize stub context provider
    if (this.componentManager.hasComponent(XWikiStubContextProvider.class)) {
        XWikiStubContextProvider stubContextProvider = this.componentManager
                .getInstance(XWikiStubContextProvider.class);
        if (!MockUtil.isMock(stubContextProvider)) {
            stubContextProvider.initialize(this.context);
        }
    }

    // Make sure to have a mocked CoreConfiguration (even if one already exist)
    if (!this.componentManager.hasComponent(CoreConfiguration.class)) {
        CoreConfiguration coreConfigurationMock = this.componentManager
                .registerMockComponent(CoreConfiguration.class);
        when(coreConfigurationMock.getDefaultDocumentSyntax()).thenReturn(Syntax.XWIKI_2_1);
    } else {
        CoreConfiguration coreConfiguration = this.componentManager
                .registerMockComponent(CoreConfiguration.class, false);
        if (MockUtil.isMock(coreConfiguration)) {
            when(coreConfiguration.getDefaultDocumentSyntax()).thenReturn(Syntax.XWIKI_2_1);
        }
    }

    // Set a context ComponentManager if none exist
    if (!this.componentManager.hasComponent(ComponentManager.class, "context")) {
        DefaultComponentDescriptor<ComponentManager> componentManagerDescriptor = new DefaultComponentDescriptor<>();
        componentManagerDescriptor.setRoleHint("context");
        componentManagerDescriptor.setRoleType(ComponentManager.class);
        this.componentManager.registerComponent(componentManagerDescriptor, this.componentManager);
    }

    // XWiki

    doAnswer(new Answer<XWikiDocument>() {
        @Override
        public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
            XWikiDocument doc = invocation.getArgument(0);
            String revision = invocation.getArgument(1);

            if (StringUtils.equals(revision, doc.getVersion())) {
                return doc;
            }

            // TODO: implement version store mocking
            return new XWikiDocument(doc.getDocumentReference());
        }
    }).when(getSpyXWiki()).getDocument(anyXWikiDocument(), any(), anyXWikiContext());
    doAnswer(new Answer<XWikiDocument>() {
        @Override
        public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
            DocumentReference target = invocation.getArgument(0);

            if (target.getLocale() == null) {
                target = new DocumentReference(target, Locale.ROOT);
            }

            XWikiDocument document = documents.get(target);

            if (document == null) {
                document = new XWikiDocument(target, target.getLocale());
                document.setSyntax(Syntax.PLAIN_1_0);
                document.setOriginalDocument(document.clone());
            }

            return document;
        }
    }).when(getSpyXWiki()).getDocument(any(DocumentReference.class), anyXWikiContext());
    doAnswer(new Answer<XWikiDocument>() {
        @Override
        public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
            XWikiDocument target = invocation.getArgument(0);

            return getSpyXWiki().getDocument(target.getDocumentReferenceWithLocale(),
                    invocation.getArgument(1));
        }
    }).when(getSpyXWiki()).getDocument(anyXWikiDocument(), any(XWikiContext.class));
    doAnswer(new Answer<Boolean>() {
        @Override
        public Boolean answer(InvocationOnMock invocation) throws Throwable {
            DocumentReference target = (DocumentReference) invocation.getArguments()[0];

            if (target.getLocale() == null) {
                target = new DocumentReference(target, Locale.ROOT);
            }

            return documents.containsKey(target);
        }
    }).when(getSpyXWiki()).exists(any(DocumentReference.class), anyXWikiContext());
    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            XWikiDocument document = invocation.getArgument(0);
            String comment = invocation.getArgument(1);
            boolean minorEdit = invocation.getArgument(2);

            boolean isNew = document.isNew();

            document.setComment(StringUtils.defaultString(comment));
            document.setMinorEdit(minorEdit);

            if (document.isContentDirty() || document.isMetaDataDirty()) {
                document.setDate(new Date());
                if (document.isContentDirty()) {
                    document.setContentUpdateDate(new Date());
                    document.setContentAuthorReference(document.getAuthorReference());
                }
                document.incrementVersion();

                document.setContentDirty(false);
                document.setMetaDataDirty(false);
            }
            document.setNew(false);
            document.setStore(getMockStore());

            XWikiDocument previousDocument = documents.get(document.getDocumentReferenceWithLocale());

            if (previousDocument != null && previousDocument != document) {
                for (XWikiAttachment attachment : document.getAttachmentList()) {
                    if (!attachment.isContentDirty()) {
                        attachment.setAttachment_content(previousDocument
                                .getAttachment(attachment.getFilename()).getAttachment_content());
                    }
                }
            }

            XWikiDocument originalDocument = document.getOriginalDocument();
            if (originalDocument == null) {
                originalDocument = spyXWiki.getDocument(document.getDocumentReferenceWithLocale(), context);
                document.setOriginalDocument(originalDocument);
            }

            XWikiDocument savedDocument = document.clone();

            documents.put(document.getDocumentReferenceWithLocale(), savedDocument);

            if (isNew) {
                if (notifyDocumentCreatedEvent) {
                    getObservationManager().notify(new DocumentCreatedEvent(document.getDocumentReference()),
                            document, getXWikiContext());
                }
            } else {
                if (notifyDocumentUpdatedEvent) {
                    getObservationManager().notify(new DocumentUpdatedEvent(document.getDocumentReference()),
                            document, getXWikiContext());
                }
            }

            // Set the document as it's original document
            savedDocument.setOriginalDocument(savedDocument.clone());

            return null;
        }
    }).when(getSpyXWiki()).saveDocument(anyXWikiDocument(), any(String.class), anyBoolean(), anyXWikiContext());
    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            XWikiDocument document = invocation.getArgument(0);

            documents.remove(document.getDocumentReferenceWithLocale());

            if (notifyDocumentDeletedEvent) {
                getObservationManager().notify(new DocumentDeletedEvent(document.getDocumentReference()),
                        document, getXWikiContext());
            }

            return null;
        }
    }).when(getSpyXWiki()).deleteDocument(anyXWikiDocument(), any(Boolean.class), anyXWikiContext());
    doAnswer(new Answer<BaseClass>() {
        @Override
        public BaseClass answer(InvocationOnMock invocation) throws Throwable {
            return getSpyXWiki()
                    .getDocument((DocumentReference) invocation.getArguments()[0], invocation.getArgument(1))
                    .getXClass();
        }
    }).when(getSpyXWiki()).getXClass(any(DocumentReference.class), anyXWikiContext());
    doAnswer(new Answer<String>() {
        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            return getXWikiContext().getLanguage();
        }
    }).when(getSpyXWiki()).getLanguagePreference(anyXWikiContext());

    getXWikiContext().setLocale(Locale.ENGLISH);

    // XWikiStoreInterface

    when(getMockStore().getTranslationList(anyXWikiDocument(), anyXWikiContext()))
            .then(new Answer<List<String>>() {
                @Override
                public List<String> answer(InvocationOnMock invocation) throws Throwable {
                    XWikiDocument document = invocation.getArgument(0);

                    List<String> translations = new ArrayList<String>();

                    for (XWikiDocument storedDocument : documents.values()) {
                        Locale storedLocale = storedDocument.getLocale();
                        if (!storedLocale.equals(Locale.ROOT) && storedDocument.getDocumentReference()
                                .equals(document.getDocumentReference())) {
                            translations.add(storedLocale.toString());
                        }
                    }

                    return translations;
                }
            });
    when(getMockStore().loadXWikiDoc(anyXWikiDocument(), anyXWikiContext())).then(new Answer<XWikiDocument>() {
        @Override
        public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
            // The store is based on the contex for the wiki
            DocumentReference reference = invocation.<XWikiDocument>getArgument(0).getDocumentReference();
            XWikiContext xcontext = invocation.getArgument(1);
            if (!xcontext.getWikiReference().equals(reference.getWikiReference())) {
                reference = reference.setWikiReference(xcontext.getWikiReference());
            }

            return getSpyXWiki().getDocument(reference, xcontext);
        }
    });
    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            // The store is based on the contex for the wiki
            DocumentReference reference = invocation.<XWikiDocument>getArgument(0)
                    .getDocumentReferenceWithLocale();
            XWikiContext xcontext = invocation.getArgument(1);
            if (!xcontext.getWikiReference().equals(reference.getWikiReference())) {
                reference = reference.setWikiReference(xcontext.getWikiReference());
            }

            documents.remove(reference);

            return null;
        }
    }).when(getMockStore()).deleteXWikiDoc(anyXWikiDocument(), anyXWikiContext());

    // Users

    doAnswer(new Answer<BaseClass>() {
        @Override
        public BaseClass answer(InvocationOnMock invocation) throws Throwable {
            XWikiContext xcontext = invocation.getArgument(0);

            XWikiDocument userDocument = getSpyXWiki().getDocument(
                    new DocumentReference(USER_CLASS, new WikiReference(xcontext.getWikiId())), xcontext);

            final BaseClass userClass = userDocument.getXClass();

            if (userDocument.isNew()) {
                userClass.addTextField("first_name", "First Name", 30);
                userClass.addTextField("last_name", "Last Name", 30);
                userClass.addEmailField("email", "e-Mail", 30);
                userClass.addPasswordField("password", "Password", 10);
                userClass.addBooleanField("active", "Active", "active");
                userClass.addTextAreaField("comment", "Comment", 40, 5);
                userClass.addTextField("avatar", "Avatar", 30);
                userClass.addTextField("phone", "Phone", 30);
                userClass.addTextAreaField("address", "Address", 40, 3);

                getSpyXWiki().saveDocument(userDocument, xcontext);
            }

            return userClass;
        }
    }).when(getSpyXWiki()).getUserClass(anyXWikiContext());
    doAnswer(new Answer<BaseClass>() {
        @Override
        public BaseClass answer(InvocationOnMock invocation) throws Throwable {
            XWikiContext xcontext = invocation.getArgument(0);

            XWikiDocument groupDocument = getSpyXWiki().getDocument(
                    new DocumentReference(GROUP_CLASS, new WikiReference(xcontext.getWikiId())), xcontext);

            final BaseClass groupClass = groupDocument.getXClass();

            if (groupDocument.isNew()) {
                groupClass.addTextField("member", "Member", 30);

                getSpyXWiki().saveDocument(groupDocument, xcontext);
            }

            return groupClass;
        }
    }).when(getSpyXWiki()).getGroupClass(anyXWikiContext());

    // Query Manager
    // If there's already a Query Manager registered, use it instead.
    // This allows, for example, using @ComponentList to use the real Query Manager, in integration tests.
    if (!this.componentManager.hasComponent(QueryManager.class)) {
        mockQueryManager();
    }
    when(getMockStore().getQueryManager()).then(new Answer<QueryManager>() {

        @Override
        public QueryManager answer(InvocationOnMock invocation) throws Throwable {
            return getQueryManager();
        }
    });

    // WikiDescriptorManager
    // If there's already a WikiDescriptorManager registered, use it instead.
    // This allows, for example, using @ComponentList to use the real WikiDescriptorManager, in integration tests.
    if (!this.componentManager.hasComponent(WikiDescriptorManager.class)) {
        this.wikiDescriptorManager = getMocker().registerMockComponent(WikiDescriptorManager.class);
        when(this.wikiDescriptorManager.getMainWikiId()).then(new Answer<String>() {
            @Override
            public String answer(InvocationOnMock invocation) throws Throwable {
                return getXWikiContext().getMainXWiki();
            }
        });
        when(this.wikiDescriptorManager.getCurrentWikiId()).then(new Answer<String>() {
            @Override
            public String answer(InvocationOnMock invocation) throws Throwable {
                return getXWikiContext().getWikiId();
            }
        });
    }
}

From source file:org.jahia.osgi.FrameworkService.java

private void updateFileReferencesIfNeeded() {
    File script = new File(
            SettingsBean.getInstance().getJahiaVarDiskPath() + "/scripts/groovy/updateFileReferences.groovy");
    if (!script.isFile()) {
        return;//from  w  ww. ja  v a  2s .  co m
    }

    ScriptEngine scriptEngine;
    try {
        scriptEngine = ScriptEngineUtils.getInstance()
                .scriptEngine(FilenameUtils.getExtension(script.getName()));
    } catch (ScriptException e) {
        throw new JahiaRuntimeException(e);
    }
    if (scriptEngine == null) {
        throw new IllegalStateException("No script engine available");
    }

    ScriptContext scriptContext = new SimpleScriptContext();
    Bindings bindings = new SimpleBindings();
    bindings.put("log", logger);
    bindings.put("logger", logger);
    scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
    try (FileInputStream scriptInputStream = new FileInputStream(script);
            InputStreamReader scriptReader = new InputStreamReader(scriptInputStream, Charsets.UTF_8);
            StringWriter out = new StringWriter()) {
        scriptContext.setWriter(out);
        scriptEngine.eval(scriptReader, scriptContext);
    } catch (ScriptException | IOException e) {
        throw new JahiaRuntimeException(e);
    }
}