Example usage for javax.servlet ServletContext getAttribute

List of usage examples for javax.servlet ServletContext getAttribute

Introduction

In this page you can find the example usage for javax.servlet ServletContext getAttribute.

Prototype

public Object getAttribute(String name);

Source Link

Document

Returns the servlet container attribute with the given name, or null if there is no attribute by that name.

Usage

From source file:org.apache.wiki.WikiEngine.java

/**
 *  Gets a WikiEngine related to the servlet. Works just like getInstance( ServletConfig )
 *
 *  @param context The ServletContext of the webapp servlet/JSP calling this method.
 *  @param props  A set of properties, or null, if we are to load JSPWiki's default
 *                jspwiki.properties (this is the usual case).
 *
 *  @return One fully functional, properly behaving WikiEngine.
 *  @throws InternalWikiException If the WikiEngine instantiation fails.
 *///from   w  w w  .j  a  v a2 s  .  c  om

// FIXME: Potential make-things-easier thingy here: no need to fetch the wikiengine anymore
//        Wiki.jsp.jspInit() [really old code]; it's probably even faster to fetch it
//        using this method every time than go to pageContext.getAttribute().

public static synchronized WikiEngine getInstance(ServletContext context, Properties props)
        throws InternalWikiException {
    WikiEngine engine = (WikiEngine) context.getAttribute(ATTR_WIKIENGINE);

    if (engine == null) {
        String appid = Integer.toString(context.hashCode()); //FIXME: Kludge, use real type.

        context.log(" Assigning new engine to " + appid);
        try {
            if (props == null) {
                props = PropertyReader.loadWebAppProps(context);
            }

            engine = new WikiEngine(context, appid, props);
            context.setAttribute(ATTR_WIKIENGINE, engine);
        } catch (Exception e) {
            context.log("ERROR: Failed to create a Wiki engine: " + e.getMessage());
            log.error("ERROR: Failed to create a Wiki engine, stacktrace follows ", e);
            throw new InternalWikiException("No wiki engine, check logs.");
        }

    }

    return engine;
}

From source file:gov.nih.nci.cananolab.restful.sample.SampleBO.java

private void calculateDataAvailabilityScore(SampleBean sampleBean, Set<DataAvailabilityBean> dataAvailability,
        HttpServletRequest request) {// w w w.j  a  va  2  s . c  o  m

    ServletContext appContext = request.getSession().getServletContext();

    SortedSet<String> minchar = (SortedSet<String>) appContext.getAttribute("MINChar");
    Map<String, String> attributes = (Map<String, String>) appContext.getAttribute("caNano2MINChar");
    sampleBean.calculateDataAvailabilityScore(dataAvailability, minchar, attributes);
}

From source file:org.red5.server.war.RootContextLoaderServlet.java

/**
 * Clearing the in-memory configuration parameters, we will receive
 * notification that the servlet context is about to be shut down
 *//*from  w ww .  j av a2s . c  o  m*/
@Override
public void contextDestroyed(ServletContextEvent sce) {
    synchronized (instance) {
        logger.info("Webapp shutdown");
        // XXX Paul: grabbed this from
        // http://opensource.atlassian.com/confluence/spring/display/DISC/Memory+leak+-+classloader+won%27t+let+go
        // in hopes that we can clear all the issues with J2EE containers
        // during shutdown
        try {
            ServletContext ctx = sce.getServletContext();
            // if the ctx being destroyed is root then kill the timer
            if (ctx.getContextPath().equals("/ROOT")) {
                timer.cancel();
            } else {
                // remove from registered list
                registeredContexts.remove(ctx);
            }
            // prepare spring for shutdown
            Introspector.flushCaches();
            // dereg any drivers
            for (Enumeration e = DriverManager.getDrivers(); e.hasMoreElements();) {
                Driver driver = (Driver) e.nextElement();
                if (driver.getClass().getClassLoader() == getClass().getClassLoader()) {
                    DriverManager.deregisterDriver(driver);
                }
            }
            // shutdown jmx
            JMXAgent.shutdown();
            // shutdown spring
            Object attr = ctx.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
            if (attr != null) {
                // get web application context from the servlet context
                ConfigurableWebApplicationContext applicationContext = (ConfigurableWebApplicationContext) attr;
                ConfigurableBeanFactory factory = applicationContext.getBeanFactory();
                // for (String scope : factory.getRegisteredScopeNames()) {
                // logger.debug("Registered scope: " + scope);
                // }
                try {
                    for (String singleton : factory.getSingletonNames()) {
                        logger.debug("Registered singleton: " + singleton);
                        factory.destroyScopedBean(singleton);
                    }
                } catch (RuntimeException e) {
                }
                factory.destroySingletons();

                ctx.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
                applicationContext.close();
            }
            instance.getContextLoader().closeWebApplicationContext(ctx);
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            // http://jakarta.apache.org/commons/logging/guide.html#Classloader_and_Memory_Management
            // http://wiki.apache.org/jakarta-commons/Logging/UndeployMemoryLeak?action=print
            LogFactory.release(Thread.currentThread().getContextClassLoader());
        }
    }
}

From source file:com.concursive.connect.config.ApplicationPrefs.java

/**
 * Description of the Method//from  ww  w. ja  v  a2  s  .  c o m
 *
 * @param context Description of the Parameter
 */
public void configureConnectionPool(ServletContext context) {
    LOG.info("configureConnectionPool");
    //Define the ConnectionPool, else defaults from the ContextListener will be used
    ConnectionPool cp = (ConnectionPool) context.getAttribute(Constants.CONNECTION_POOL);
    if (cp != null) {
        // Apply any settings
        if (this.has(CONNECTION_POOL_DEBUG)) {
            cp.setDebug(this.get(CONNECTION_POOL_DEBUG));
        }
        if (this.has(CONNECTION_POOL_TEST_CONNECTIONS)) {
            cp.setTestConnections(this.get(CONNECTION_POOL_TEST_CONNECTIONS));
        }
        if (this.has(CONNECTION_POOL_ALLOW_SHRINKING)) {
            cp.setAllowShrinking(this.get(CONNECTION_POOL_ALLOW_SHRINKING));
        }
        if (this.has(CONNECTION_POOL_MAX_CONNECTIONS)) {
            cp.setMaxConnections(this.get(CONNECTION_POOL_MAX_CONNECTIONS));
        }
        if (this.has(CONNECTION_POOL_MAX_IDLE_TIME)) {
            cp.setMaxIdleTimeSeconds(this.get(CONNECTION_POOL_MAX_IDLE_TIME));
        }
        if (this.has(CONNECTION_POOL_MAX_DEAD_TIME)) {
            cp.setMaxDeadTimeSeconds(this.get(CONNECTION_POOL_MAX_DEAD_TIME));
        }
        // Clone it for RSS Feeds
        if (this.get(CONNECTION_POOL_MAX_RSS_CONNECTIONS) != null) {
            ConnectionPool rssCP = new ConnectionPool();
            rssCP.setDebug(cp.getDebug());
            rssCP.setTestConnections(cp.getTestConnections());
            rssCP.setAllowShrinking(cp.getAllowShrinking());
            rssCP.setMaxConnections(this.get(CONNECTION_POOL_MAX_RSS_CONNECTIONS));
            rssCP.setMaxIdleTime(cp.getMaxIdleTime());
            rssCP.setMaxDeadTime(cp.getMaxDeadTime());
            context.setAttribute(Constants.CONNECTION_POOL_RSS, rssCP);
        } else {
            context.setAttribute(Constants.CONNECTION_POOL_RSS, cp);
        }
        // Clone it for API Requests
        if (this.get(CONNECTION_POOL_MAX_API_CONNECTIONS) != null) {
            ConnectionPool apiCP = new ConnectionPool();
            apiCP.setDebug(cp.getDebug());
            apiCP.setTestConnections(cp.getTestConnections());
            apiCP.setAllowShrinking(cp.getAllowShrinking());
            apiCP.setMaxConnections(this.get(CONNECTION_POOL_MAX_API_CONNECTIONS));
            apiCP.setMaxIdleTime(cp.getMaxIdleTime());
            apiCP.setMaxDeadTime(cp.getMaxDeadTime());
            context.setAttribute(Constants.CONNECTION_POOL_API, apiCP);
        } else {
            context.setAttribute(Constants.CONNECTION_POOL_API, cp);
        }
    } else {
        LOG.error("ConnectionPool is null");
    }
}

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   w w  w. j  a  v  a  2 s. com*/
        // 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:jp.or.openid.eiwg.scim.servlet.ServiceProviderConfigs.java

/**
 * GET?/*  w w w  . j  a  v a  2  s  .c  o m*/
 *
 * @param request 
 * @param response ?
 * @throws ServletException
 * @throws IOException
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ?
    ServletContext context = getServletContext();

    // ??
    Operation op = new Operation();
    boolean result = op.Authentication(context, request);

    if (!result) {
        // 
        errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
    } else {
        // [draft-ietf-scim-api-13 3.2.2.1. Query Endpoints]
        //  Queries MAY be performed against a SCIM resource object, a resource
        //  type endpoint, or a SCIM server root.

        // ServiceProviderConfigs ??????????

        // location?URL?
        String location = request.getScheme() + "://" + request.getServerName();
        int serverPort = request.getServerPort();
        if (serverPort != 80 && serverPort != 443) {
            location += ":" + Integer.toString(serverPort);
        }
        location += request.getContextPath();

        // ??
        @SuppressWarnings("unchecked")
        Map<String, Object> serviceProviderConfigsObject = (Map<String, Object>) context
                .getAttribute("ServiceProviderConfigs");

        try {
            ObjectMapper mapper = new ObjectMapper();
            StringWriter writer = new StringWriter();
            mapper.writeValue(writer, serviceProviderConfigsObject);
            String serviceProviderConfigs = writer.toString();
            serviceProviderConfigs = String.format(serviceProviderConfigs, location);

            response.setContentType("application/scim+json;charset=UTF-8");
            response.setHeader("Location", request.getRequestURL().toString());
            PrintWriter out = response.getWriter();
            out.println(serviceProviderConfigs);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:jp.terasoluna.fw.web.struts.plugins.ResetterPlugInTest.java

/**
 * testInitResources09()/*from  ww w  . j  av a 2 s.c  o  m*/
 * <br><br>
 * 
 * (??n)
 * <br>
 * _?FA
 * <br><br>
 * l?F(?) servlet:not null<br>
 *         (?) config:W?[(?)=""<br>
 *         (?) this.resourcePath:"ResetterPlugInTest-reset.xml","ResetterPlugInTest-reset2.xml","ResetterPlugInTest-reset3.xml"<br>
 *         (?) digesterRules:"ResetterPlugInTest-reset-rules.xml"<br>
 *         (?) ServletContext#getResource():?|<br>
 *         
 * <br>
 * l?F(?) RESETTER_RESOURCES:T?[ubgReLXg"RESETTER_RESOURCES"L?[ResetterResourcesCX^Xi[?B?iResetterResources?gmF?s?j<br>
 *         (?) digesterRules:?|<br>
 *         (?) O:?|<br>
 *         (?) ?O:?|<br>
 *         
 * <br>
 * this.resourcesPath?t@Cw?ARESETTER_RESOURCESL?[?A??T?[ubgReLXgmF?B
 * <br>
 * 
 * @throws Exception ?\bh?O
 */
public void testInitResources09() throws Exception {
    // W?[??
    ModuleConfig conf = new ModuleConfigImpl("");

    // reset.xmlpX?
    UTUtil.setPrivateField(plugin, "resourcesPath",
            RESET_FILE_NAME + "," + RESET_FILE_NAME2 + "," + RESET_FILE_NAME3);
    // reset-rules.xmlpX?
    UTUtil.setPrivateField(plugin, "digesterRules", RESET_RULES_FILE_NAME);

    // ANVT?[ubg??
    ResetterPlugIn_ActionServletStub01 servlet = new ResetterPlugIn_ActionServletStub01();

    // eXg?s
    plugin.initResources(servlet, conf);

    // mF
    // T?[ubgReLXg
    ServletContext ctx = servlet.getServletContext();
    assertEquals("jp.terasoluna.fw.web.struts.reset.ResetterResources",
            ((ResetterResources) ctx.getAttribute("RESETTER_RESOURCES")).getClass().getName());

    // XMLp?[X
    ResetterResources resource = (ResetterResources) ctx.getAttribute("RESETTER_RESOURCES");
    Map actionResets = (Map) UTUtil.getPrivateField(resource, "actionResets");

    // Pt@Cresett@C???
    ActionReset actionReset1_1 = (ActionReset) actionResets.get("/changePage");
    // fieldReset`FbN
    Map fieldResets1_1 = (Map) UTUtil.getPrivateField(actionReset1_1, "fieldResets");
    assertEquals(1, fieldResets1_1.size());
    FieldReset fieldReset1_1 = (FieldReset) fieldResets1_1.get("field1-1");
    assertEquals("field1-1", fieldReset1_1.getFieldName());
    assertFalse(fieldReset1_1.isSelect());

    ActionReset actionReset1_2 = (ActionReset) actionResets.get("/bbb/BBB");
    // fieldReset`FbN
    Map fieldResets1_2 = (Map) UTUtil.getPrivateField(actionReset1_2, "fieldResets");
    assertEquals(3, fieldResets1_2.size());
    FieldReset fieldReset1_2 = (FieldReset) fieldResets1_2.get("field1-1");
    assertEquals("field1-1", fieldReset1_2.getFieldName());
    assertFalse(fieldReset1_2.isSelect());
    FieldReset fieldReset1_3 = (FieldReset) fieldResets1_2.get("field1-2");
    assertEquals("field1-2", fieldReset1_3.getFieldName());
    assertTrue(fieldReset1_3.isSelect());
    FieldReset fieldReset1_4 = (FieldReset) fieldResets1_2.get("field1-3");
    assertEquals("field1-3", fieldReset1_4.getFieldName());
    assertTrue(fieldReset1_4.isSelect());

    ActionReset actionReset1_3 = (ActionReset) actionResets.get("/ccc/CCC");
    // fieldReset`FbN
    Map fieldResets1_3 = (Map) UTUtil.getPrivateField(actionReset1_3, "fieldResets");
    assertEquals(2, fieldResets1_3.size());
    FieldReset fieldReset1_5 = (FieldReset) fieldResets1_3.get("field1-1");
    assertEquals("field1-1", fieldReset1_5.getFieldName());
    assertFalse(fieldReset1_5.isSelect());
    FieldReset fieldReset1_6 = (FieldReset) fieldResets1_3.get("field1-2");
    assertEquals("field1-2", fieldReset1_6.getFieldName());
    assertFalse(fieldReset1_6.isSelect());

    // Qt@Cresett@C???
    ActionReset actionReset2_1 = (ActionReset) actionResets.get("/aaa/AAA2");
    // fieldReset`FbN
    Map fieldResets2_1 = (Map) UTUtil.getPrivateField(actionReset2_1, "fieldResets");
    assertEquals(1, fieldResets2_1.size());
    FieldReset fieldReset2_1 = (FieldReset) fieldResets2_1.get("field2-1");
    assertEquals("field2-1", fieldReset2_1.getFieldName());
    assertFalse(fieldReset2_1.isSelect());

    ActionReset actionReset2_2 = (ActionReset) actionResets.get("/bbb/BBB2");
    // fieldReset`FbN
    Map fieldResets2_2 = (Map) UTUtil.getPrivateField(actionReset2_2, "fieldResets");
    assertEquals(3, fieldResets2_2.size());
    FieldReset fieldReset2_2 = (FieldReset) fieldResets2_2.get("field2-1");
    assertEquals("field2-1", fieldReset2_2.getFieldName());
    assertFalse(fieldReset2_2.isSelect());
    FieldReset fieldReset2_3 = (FieldReset) fieldResets2_2.get("field2-2");
    assertEquals("field2-2", fieldReset2_3.getFieldName());
    assertTrue(fieldReset2_3.isSelect());
    FieldReset fieldReset2_4 = (FieldReset) fieldResets2_2.get("field2-3");
    assertEquals("field2-3", fieldReset2_4.getFieldName());
    assertTrue(fieldReset2_4.isSelect());

    ActionReset actionReset2_3 = (ActionReset) actionResets.get("/ccc/CCC2");
    // fieldReset`FbN
    Map fieldResets2_3 = (Map) UTUtil.getPrivateField(actionReset2_3, "fieldResets");
    assertEquals(2, fieldResets2_3.size());
    FieldReset fieldReset2_5 = (FieldReset) fieldResets2_3.get("field2-1");
    assertEquals("field2-1", fieldReset2_5.getFieldName());
    assertFalse(fieldReset2_5.isSelect());
    FieldReset fieldReset2_6 = (FieldReset) fieldResets2_3.get("field2-2");
    assertEquals("field2-2", fieldReset2_6.getFieldName());
    assertFalse(fieldReset2_6.isSelect());

    // Rt@Cresett@C???
    ActionReset actionReset3_1 = (ActionReset) actionResets.get("/aaa/AAA3");
    // fieldReset`FbN
    Map fieldResets3_1 = (Map) UTUtil.getPrivateField(actionReset3_1, "fieldResets");
    assertEquals(1, fieldResets3_1.size());
    FieldReset fieldReset3_1 = (FieldReset) fieldResets3_1.get("field3-1");
    assertEquals("field3-1", fieldReset3_1.getFieldName());
    assertFalse(fieldReset3_1.isSelect());

    ActionReset actionReset3_2 = (ActionReset) actionResets.get("/bbb/BBB3");
    // fieldReset`FbN
    Map fieldResets3_2 = (Map) UTUtil.getPrivateField(actionReset3_2, "fieldResets");
    assertEquals(3, fieldResets3_2.size());
    FieldReset fieldReset3_2 = (FieldReset) fieldResets3_2.get("field3-1");
    assertEquals("field3-1", fieldReset3_2.getFieldName());
    assertFalse(fieldReset3_2.isSelect());
    FieldReset fieldReset3_3 = (FieldReset) fieldResets3_2.get("field3-2");
    assertEquals("field3-2", fieldReset3_3.getFieldName());
    assertTrue(fieldReset3_3.isSelect());
    FieldReset fieldReset3_4 = (FieldReset) fieldResets3_2.get("field3-3");
    assertEquals("field3-3", fieldReset3_4.getFieldName());
    assertTrue(fieldReset3_4.isSelect());

    ActionReset actionReset3_3 = (ActionReset) actionResets.get("/ccc/CCC3");
    // fieldReset`FbN
    Map fieldResets3_3 = (Map) UTUtil.getPrivateField(actionReset3_3, "fieldResets");
    assertEquals(2, fieldResets3_3.size());
    FieldReset fieldReset3_5 = (FieldReset) fieldResets3_3.get("field3-1");
    assertEquals("field3-1", fieldReset3_5.getFieldName());
    assertFalse(fieldReset3_5.isSelect());
    FieldReset fieldReset3_6 = (FieldReset) fieldResets3_3.get("field3-2");
    assertEquals("field3-2", fieldReset3_6.getFieldName());
    assertFalse(fieldReset3_6.isSelect());

    // Qt@CRt@Cresett@C?dpX????A
    // ?t@C??
    ActionReset actionResetDuplicate = (ActionReset) actionResets.get("/duplicate");
    // fieldReset`FbN
    Map duplicate = (Map) UTUtil.getPrivateField(actionResetDuplicate, "fieldResets");
    assertEquals(1, duplicate.size());
    FieldReset fieldReset1 = (FieldReset) duplicate.get("duplicate1");
    assertNull(fieldReset1);
    FieldReset fieldReset2 = (FieldReset) duplicate.get("duplicate2");
    assertEquals("duplicate2", fieldReset2.getFieldName());
    assertFalse(fieldReset2.isSelect());
}

From source file:com.concursive.connect.web.modules.login.utils.UserUtils.java

public static void createLoggedInUser(User thisUser, Connection db, ApplicationPrefs prefs,
        ServletContext context) throws SQLException {
    // Apply limitations
    thisUser.setCurrentAccountSize(FileItemVersionList.queryOwnerSize(db, thisUser.getId()));
    // Use standard template engine
    thisUser.setTemplate("template0");
    // Set a default time zone for user
    if (thisUser.getTimeZone() == null) {
        thisUser.setTimeZone(prefs.get(ApplicationPrefs.TIMEZONE));
    }//from  ww w  .jav  a2  s .c om
    // Set a default currency
    if (thisUser.getCurrency() == null) {
        thisUser.setCurrency(prefs.get(ApplicationPrefs.CURRENCY));
    }
    // Set a default locale
    if (thisUser.getLanguage() == null) {
        thisUser.setLanguage(prefs.get(ApplicationPrefs.LANGUAGE));
    }
    // Show recently accessed projects
    thisUser.queryRecentlyAccessedProjects(db);
    // Make sure the user has a profile
    if (thisUser.getProfileProjectId() == -1) {
        // @todo find out how the user profile is not already generated!
        LOG.warn("Adding a user profile (should have already existed)");
        UserUtils.addUserProfile(db, thisUser, prefs);

        // processInsertHook
        boolean sslEnabled = "true".equals(prefs.get("SSL"));
        String url = ("http" + (sslEnabled ? "s" : "") + "://" + prefs.get(ApplicationPrefs.WEB_DOMAIN_NAME)
                + (!"80".equals(prefs.get(ApplicationPrefs.WEB_PORT))
                        && !"443".equals(prefs.get(ApplicationPrefs.WEB_PORT))
                                ? ":" + prefs.get(ApplicationPrefs.WEB_PORT)
                                : "")
                + prefs.get(ApplicationPrefs.WEB_CONTEXT));
        ObjectHookManager hookManager = (ObjectHookManager) context.getAttribute(Constants.OBJECT_HOOK_MANAGER);
        hookManager.process(ObjectHookAction.INSERT, null, thisUser.getProfileProject(), thisUser.getId(), url,
                url, null);

        // indexer
        Scheduler scheduler = (Scheduler) context.getAttribute(Constants.SCHEDULER);
        try {
            IndexEvent indexEvent = new IndexEvent(thisUser.getProfileProject(), IndexEvent.ADD);
            ((Vector) scheduler.getContext().get("IndexArray")).add(indexEvent);
            scheduler.triggerJob("indexer",
                    (String) scheduler.getContext().get(ScheduledJobs.CONTEXT_SCHEDULER_GROUP));
        } catch (Exception e) {
            LOG.error("createUser-scheduler-index-profile", e);
        }
    }
}

From source file:org.codehaus.groovy.grails.web.binding.GrailsDataBinder.java

private void bindWithRequestAndPropertyValues(ServletRequest request, MutablePropertyValues mpvs) {
    GrailsWebRequest webRequest = GrailsWebRequest.lookup((HttpServletRequest) request);
    if (webRequest != null) {
        final ApplicationContext applicationContext = webRequest.getApplicationContext();
        if (applicationContext != null) {
            ServletContext servletContext = webRequest.getServletContext();
            @SuppressWarnings("unchecked")
            Map<String, BindEventListener> bindEventListenerMap = (Map<String, BindEventListener>) servletContext
                    .getAttribute(BIND_EVENT_LISTENERS);
            if (bindEventListenerMap == null) {
                bindEventListenerMap = applicationContext.getBeansOfType(BindEventListener.class);
                if (!Environment.isDevelopmentMode()) {
                    servletContext.setAttribute(BIND_EVENT_LISTENERS, bindEventListenerMap);
                }//from w w w  .java 2s.c o  m
            }
            for (BindEventListener bindEventListener : bindEventListenerMap.values()) {
                bindEventListener.doBind(getTarget(), mpvs, getTypeConverter());
            }
        }
    }
    preProcessMutablePropertyValues(mpvs);

    if (request instanceof MultipartHttpServletRequest) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        bindMultipart(multipartRequest.getMultiFileMap(), mpvs);
    }
    doBind(mpvs);
}