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: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 w w w  .ja v 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:net.jawr.web.bundle.processor.BundleProcessor.java

/**
 * Process the Jawr Servlets// w w w .  j  av  a2s  . c o m
 * 
 * @param destDirPath
 *            the destination directory path
 * @param jawrServletDefinitions
 *            the destination directory
 * @throws Exception
 *             if an exception occurs.
 */
protected void processJawrServlets(String destDirPath, List<ServletDefinition> jawrServletDefinitions,
        boolean keepUrlMapping) throws Exception {

    String appRootDir = "";
    String jsServletMapping = "";
    String cssServletMapping = "";
    String binaryServletMapping = "";

    for (Iterator<ServletDefinition> iterator = jawrServletDefinitions.iterator(); iterator.hasNext();) {

        ServletDefinition servletDef = (ServletDefinition) iterator.next();
        ServletConfig servletConfig = servletDef.getServletConfig();

        // Force the production mode, and remove config listener parameters
        Map<?, ?> initParameters = ((MockServletConfig) servletConfig).getInitParameters();
        initParameters.remove("jawr.config.reload.interval");

        String jawrServletMapping = servletConfig.getInitParameter(JawrConstant.SERVLET_MAPPING_PROPERTY_NAME);
        String servletMapping = servletConfig
                .getInitParameter(JawrConstant.SPRING_SERVLET_MAPPING_PROPERTY_NAME);
        if (servletMapping == null) {
            servletMapping = jawrServletMapping;
        }

        ResourceBundlesHandler bundleHandler = null;
        BinaryResourcesHandler binaryRsHandler = null;

        // Retrieve the bundle Handler
        ServletContext servletContext = servletConfig.getServletContext();
        String type = servletConfig.getInitParameter(TYPE_INIT_PARAMETER);
        if (type == null || type.equals(JawrConstant.JS_TYPE)) {
            bundleHandler = (ResourceBundlesHandler) servletContext
                    .getAttribute(JawrConstant.JS_CONTEXT_ATTRIBUTE);
            String contextPathOverride = bundleHandler.getConfig().getContextPathOverride();
            if (StringUtils.isNotEmpty(contextPathOverride)) {
                int idx = contextPathOverride.indexOf("//");
                if (idx != -1) {
                    idx = contextPathOverride.indexOf("/", idx + 2);
                    if (idx != -1) {
                        appRootDir = PathNormalizer.asPath(contextPathOverride.substring(idx));
                    }
                }
            }

            if (jawrServletMapping != null) {
                jsServletMapping = PathNormalizer.asPath(jawrServletMapping);
            }

        } else if (type.equals(JawrConstant.CSS_TYPE)) {
            bundleHandler = (ResourceBundlesHandler) servletContext
                    .getAttribute(JawrConstant.CSS_CONTEXT_ATTRIBUTE);
            if (jawrServletMapping != null) {
                cssServletMapping = PathNormalizer.asPath(jawrServletMapping);
            }
        } else if (type.equals(JawrConstant.BINARY_TYPE)) {
            binaryRsHandler = (BinaryResourcesHandler) servletContext
                    .getAttribute(JawrConstant.BINARY_CONTEXT_ATTRIBUTE);
            if (jawrServletMapping != null) {
                binaryServletMapping = PathNormalizer.asPath(jawrServletMapping);
            }
        }

        if (bundleHandler != null) {
            createBundles(servletDef.getServlet(), bundleHandler, destDirPath, servletMapping, keepUrlMapping);
        } else if (binaryRsHandler != null) {
            createBinaryBundle(servletDef.getServlet(), binaryRsHandler, destDirPath, servletConfig,
                    keepUrlMapping);
        }
    }

    // Create the apache rewrite config file.
    createApacheRewriteConfigFile(destDirPath, appRootDir, jsServletMapping, cssServletMapping,
            binaryServletMapping);

}

From source file:org.apache.catalina.loader.WebappLoader.java

/**
 * Configure associated class loader permissions.
 *//*from  w w w  .  j  a  v  a  2s.c om*/
private void setPermissions() {

    if (System.getSecurityManager() == null)
        return;
    if (!(container instanceof Context))
        return;

    // Tell the class loader the root of the context
    ServletContext servletContext = ((Context) container).getServletContext();

    // Assigning permissions for the work directory
    File workDir = (File) servletContext.getAttribute(Globals.WORK_DIR_ATTR);
    if (workDir != null) {
        try {
            String workDirPath = workDir.getCanonicalPath();
            classLoader.addPermission(new FilePermission(workDirPath, "read,write"));
            classLoader
                    .addPermission(new FilePermission(workDirPath + File.separator + "-", "read,write,delete"));
        } catch (IOException e) {
            // Ignore
        }
    }

    try {

        URL rootURL = servletContext.getResource("/");
        classLoader.addPermission(rootURL);

        String contextRoot = servletContext.getRealPath("/");
        if (contextRoot != null) {
            try {
                contextRoot = (new File(contextRoot)).getCanonicalPath();
                classLoader.addPermission(contextRoot);
            } catch (IOException e) {
                // Ignore
            }
        }

        URL classesURL = servletContext.getResource("/WEB-INF/classes/");
        classLoader.addPermission(classesURL);
        URL libURL = servletContext.getResource("/WEB-INF/lib/");
        classLoader.addPermission(libURL);

        if (contextRoot != null) {

            if (libURL != null) {
                File rootDir = new File(contextRoot);
                File libDir = new File(rootDir, "WEB-INF/lib/");
                try {
                    String path = libDir.getCanonicalPath();
                    classLoader.addPermission(path);
                } catch (IOException e) {
                }
            }

        } else {

            if (workDir != null) {
                if (libURL != null) {
                    File libDir = new File(workDir, "WEB-INF/lib/");
                    try {
                        String path = libDir.getCanonicalPath();
                        classLoader.addPermission(path);
                    } catch (IOException e) {
                    }
                }
                if (classesURL != null) {
                    File classesDir = new File(workDir, "WEB-INF/classes/");
                    try {
                        String path = classesDir.getCanonicalPath();
                        classLoader.addPermission(path);
                    } catch (IOException e) {
                    }
                }
            }

        }

    } catch (MalformedURLException e) {
    }

}

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

private void configureCache(ServletContext context) {
    LOG.info("configureCache");
    CacheContext cacheContext = new CacheContext();
    // Give the cache manager its own connection pool... this can speed up the web-tier
    // when background processing is occurring
    ConnectionPool commonCP = (ConnectionPool) context.getAttribute(Constants.CONNECTION_POOL);
    if (commonCP != null) {
        if (!this.has(CONNECTION_POOL_MAX_CACHE_CONNECTIONS)) {
            cacheContext.setConnectionPool(commonCP);
        } else {//from ww w  .  j  a  va  2 s  .  c  om
            ConnectionPool cacheCP = new ConnectionPool();
            cacheCP.setDebug(commonCP.getDebug());
            cacheCP.setTestConnections(commonCP.getTestConnections());
            cacheCP.setAllowShrinking(commonCP.getAllowShrinking());
            cacheCP.setMaxConnections(this.get(CONNECTION_POOL_MAX_CACHE_CONNECTIONS));
            cacheCP.setMaxIdleTime(commonCP.getMaxIdleTime());
            cacheCP.setMaxDeadTime(commonCP.getMaxDeadTime());
            cacheContext.setConnectionPool(cacheCP);
        }
    }
    if (cacheContext.getConnectionPool() != null) {
        // The cacheContext is ready to be finalized
        ConnectionElement ce = new ConnectionElement();
        ce.setDriver(this.get(CONNECTION_DRIVER));
        ce.setUrl(this.get(CONNECTION_URL));
        ce.setUsername(this.get(CONNECTION_USER));
        ce.setPassword(this.get(CONNECTION_PASSWORD));
        cacheContext.setConnectionElement(ce);
        cacheContext.setApplicationPrefs(this);
        cacheContext.setKey((Key) context.getAttribute(TEAM_KEY));
        Caches.addCaches(cacheContext);
    }
}

From source file:jeeves.monitor.MonitorManager.java

public void init(ServletContext context, String baseUrl) {

    String webappName = "";

    if (StringUtils.isNotEmpty(baseUrl)) {
        webappName = baseUrl.substring(1);
    }/* w w  w  . ja v a  2s  .com*/

    if (context != null) {
        HealthCheckRegistry tmpHealthCheckRegistry = lookUpHealthCheckRegistry(context, HEALTH_CHECK_REGISTRY);
        HealthCheckRegistry criticalTmpHealthCheckRegistry = lookUpHealthCheckRegistry(context,
                CRITICAL_HEALTH_CHECK_REGISTRY);
        HealthCheckRegistry warningTmpHealthCheckRegistry = lookUpHealthCheckRegistry(context,
                WARNING_HEALTH_CHECK_REGISTRY);
        HealthCheckRegistry expensiveTmpHealthCheckRegistry = lookUpHealthCheckRegistry(context,
                EXPENSIVE_HEALTH_CHECK_REGISTRY);

        healthCheckRegistry = tmpHealthCheckRegistry;
        criticalHealthCheckRegistry = criticalTmpHealthCheckRegistry;
        warningHealthCheckRegistry = warningTmpHealthCheckRegistry;
        expensiveHealthCheckRegistry = expensiveTmpHealthCheckRegistry;

        MetricsRegistry tmpMetricsRegistry = (MetricsRegistry) context.getAttribute(METRICS_REGISTRY);
        if (tmpMetricsRegistry == null) {
            tmpMetricsRegistry = new MetricsRegistry();
        }

        metricsRegistry = tmpMetricsRegistry;
        context.setAttribute(METRICS_REGISTRY, tmpMetricsRegistry);

        jmxReporter = new GeonetworkJmxReporter(metricsRegistry, webappName);
        jmxReporter.start();
    } else {
        healthCheckRegistry = new HealthCheckRegistry();
        criticalHealthCheckRegistry = new HealthCheckRegistry();
        warningHealthCheckRegistry = new HealthCheckRegistry();
        expensiveHealthCheckRegistry = new HealthCheckRegistry();
        metricsRegistry = new MetricsRegistry();

        jmxReporter = new GeonetworkJmxReporter(metricsRegistry, webappName);
        jmxReporter.start();

    }

    LogManager.getRootLogger().addAppender(new InstrumentedAppender(metricsRegistry));
}

From source file:com.rapid.server.RapidServletContextListener.java

@Override
public void contextDestroyed(ServletContextEvent event) {

    _logger.info("Shutting down...");

    // interrupt the page monitor if we have one
    if (_monitor != null)
        _monitor.interrupt();//from w  w  w . ja v a  2  s  .c om

    // get the servletContext
    ServletContext servletContext = event.getServletContext();

    // get all of the applications
    Applications applications = (Applications) servletContext.getAttribute("applications");
    // if we got some
    if (applications != null) {
        // loop the application ids
        for (String id : applications.getIds()) {
            // get the application
            Versions versions = applications.getVersions(id);
            // loop the versions of each app
            for (String version : versions.keySet()) {
                // get the application
                Application application = applications.get(id, version);
                // have it close any sensitive resources 
                application.close(servletContext);
            }
        }
    }

    // sleep for 2 seconds to allow any database connection cleanup to complete
    try {
        Thread.sleep(2000);
    } catch (Exception ex) {
    }

    // This manually deregisters JDBC drivers, which prevents Tomcat from complaining about memory leaks from this class
    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        Driver driver = drivers.nextElement();
        try {
            DriverManager.deregisterDriver(driver);
            _logger.info(String.format("Deregistering jdbc driver: %s", driver));
        } catch (SQLException e) {
            _logger.error(String.format("Error deregistering driver %s", driver), e);
        }
    }

    // Thanks to http://stackoverflow.com/questions/11872316/tomcat-guice-jdbc-memory-leak
    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
    for (Thread t : threadArray) {
        if (t.getName().contains("Abandoned connection cleanup thread")) {
            synchronized (t) {
                try {
                    _logger.info("Forcing stop of Abandoned connection cleanup thread");
                    t.stop(); //don't complain, it works
                } catch (Exception ex) {
                    _logger.info("Error forcing stop of Abandoned connection cleanup thread", ex);
                }
            }
        }
    }

    // sleep for 1 second to allow any database connection cleanup to complete
    try {
        Thread.sleep(1000);
    } catch (Exception ex) {
    }

    // last log
    _logger.info("Logger shutdown");
    // shutdown logger
    if (_logger != null)
        LogManager.shutdown();

}

From source file:com.inverse2.ajaxtoaster.AjaxToasterServlet.java

public ServicePool getServicePool() {
    ServletContext context = getServletContext();
    ServicePool pool = null;//w ww  .  java2s  .c om

    pool = (ServicePool) context.getAttribute(ATTRIB_SERVICE_POOL);

    return (pool);
}

From source file:com.portfolio.security.LTIv2Servlet.java

protected void doRegister(HttpServletResponse response, Map<String, Object> payload, ServletContext application,
        String toolProxyPath, StringBuffer outTrace) {
    String launch_url = (String) payload.get("launch_url");
    response.setContentType("text/html");

    outTraceFormattedMessage(outTrace, "doRegister() - launch_url: " + launch_url);
    outTraceFormattedMessage(outTrace, "payload: " + payload);

    String key = null;/*from w  w w.  ja  v a  2  s. c  o  m*/
    String passwd = null;
    if (BasicLTIConstants.LTI_MESSAGE_TYPE_TOOLPROXYREGISTRATIONREQUEST
            .equals(payload.get(BasicLTIConstants.LTI_MESSAGE_TYPE))) {
        key = (String) payload.get(LTI2Constants.REG_KEY);
        passwd = (String) payload.get(LTI2Constants.REG_PASSWORD);
    } else if (BasicLTIConstants.LTI_MESSAGE_TYPE_TOOLPROXY_RE_REGISTRATIONREQUEST
            .equals(payload.get(BasicLTIConstants.LTI_MESSAGE_TYPE))) {
        key = (String) payload.get(LTIServletUtils.OAUTH_CONSUMER_KEY);
        final String configPrefix = "basiclti.provider." + key + ".";
        passwd = (String) application.getAttribute(configPrefix + "secret");

    } else {
        //TODO BOOM
        outTraceFormattedMessage(outTrace, "BOOM");
    }

    String returnUrl = (String) payload.get(BasicLTIConstants.LAUNCH_PRESENTATION_RETURN_URL);
    String tcProfileUrl = (String) payload.get(LTI2Constants.TC_PROFILE_URL);

    //Lookup tc profile
    if (tcProfileUrl != null && !"".equals(tcProfileUrl)) {
        InputStream is = null;
        try {
            URL url = new URL(tcProfileUrl);
            is = url.openStream();
            JSONParser parser = new JSONParser();
            JSONObject obj = (JSONObject) parser.parse(new InputStreamReader(is));
            //             is.close();
            outTraceFormattedMessage(outTrace, obj.toJSONString());
            JSONArray services = (JSONArray) obj.get("service_offered");
            String regUrl = null;
            for (int i = 0; i < services.size(); i++) {
                JSONObject service = (JSONObject) services.get(i);
                JSONArray formats = (JSONArray) service.get("format");
                if (formats.contains("application/vnd.ims.lti.v2.toolproxy+json")) {
                    regUrl = (String) service.get("endpoint");
                    outTraceFormattedMessage(outTrace, "RegEndpoint: " + regUrl);
                }
            }
            if (regUrl == null) {
                //TODO BOOM
                throw new RuntimeException("Need an endpoint");
            }

            JSONObject toolProxy = getToolProxy(toolProxyPath);
            //TODO do some replacement on stock values that need specifics from us here

            // Tweak the stock profile
            toolProxy.put("tool_consumer_profile", tcProfileUrl);
            //LTI2Constants.
            //            BasicLTIConstants.

            //            // Re-register
            JSONObject toolProfile = (JSONObject) toolProxy.get("tool_profile");
            JSONArray messages = (JSONArray) toolProfile.get("message");
            JSONObject message = (JSONObject) messages.get(0);
            message.put("path", launch_url);
            String baseUrl = (String) payload.get("base_url");

            JSONObject pi = (JSONObject) toolProfile.get("product_instance");
            JSONObject pInfo = (JSONObject) pi.get("product_info");
            JSONObject pFamily = (JSONObject) pInfo.get("product_family");
            JSONObject vendor = (JSONObject) pFamily.get("vendor");
            vendor.put("website", baseUrl);
            //            vendor.put("timestamp", new Date().toString());
            //            $tp_profile->tool_profile->product_instance->product_info->product_family->vendor->website = $cur_base;
            //            $tp_profile->tool_profile->product_instance->product_info->product_family->vendor->timestamp = "2013-07-13T09:08:16-04:00";
            //
            //            // I want this *not* to be unique per instance
            //            $tp_profile->tool_profile->product_instance->guid = "urn:sakaiproject:unit-test";
            //
            //            $tp_profile->tool_profile->product_instance->service_provider->guid = "http://www.sakaiproject.org/";
            //
            //            // Launch Request
            //            $tp_profile->tool_profile->resource_handler[0]->message[0]->path = "tool.php";
            //            $tp_profile->tool_profile->resource_handler[0]->resource_type->code = "sakai-api-test-01";

            //            $tp_profile->tool_profile->base_url_choice[0]->secure_base_url = $cur_base;
            //            $tp_profile->tool_profile->base_url_choice[0]->default_base_url = $cur_base;
            JSONObject choice = (JSONObject) ((JSONArray) toolProfile.get("base_url_choice")).get(0);
            choice.put("secure_base_url", baseUrl);
            choice.put("default_base_url", baseUrl);

            JSONObject secContract = (JSONObject) toolProxy.get("security_contract");
            secContract.put("shared_secret", passwd);
            JSONArray toolServices = (JSONArray) secContract.get("tool_service");
            JSONObject service = (JSONObject) toolServices.get(0);
            service.put("service", regUrl);

            outTraceFormattedMessage(outTrace, "ToolProxyJSON: " + toolProxy.toJSONString());

            /// From the Implementation Guid Version 2.0 Final (http://www.imsglobal.org/lti/ltiv2p0/ltiIMGv2p0.html)
            /// Section 10.1
            /// Get data
            JSONObject dataService = getData(tcProfileUrl);

            /// find endpoint with format: application/vnd.ims.lti.v2.toolproxy+json WITH POST action
            JSONArray offered = (JSONArray) dataService.get("service_offered");
            String registerAddress = "";
            for (int i = 0; i < offered.size(); ++i) {
                JSONObject offer = (JSONObject) offered.get(i);
                JSONArray offerFormat = (JSONArray) offer.get("format");
                String format = (String) offerFormat.get(0);
                JSONArray offerAction = (JSONArray) offer.get("action");
                String action = (String) offerAction.get(0);
                if ("application/vnd.ims.lti.v2.toolproxy+json".equals(format) && "POST".equals(action)) {
                    registerAddress = (String) offer.get("endpoint");
                    break;
                }
            }

            /// FIXME: Sakai return server name as "localhost", could be my configuration
            String[] serverAddr = tcProfileUrl.split("/");
            String addr = serverAddr[2];
            registerAddress = registerAddress.substring(registerAddress.indexOf("/", 8));
            registerAddress = "http://" + addr + registerAddress;

            /// Send POST to specified URL as signed request with given values
            int responseCode = postData(registerAddress, toolProxy.toJSONString(), key, passwd);
            if (responseCode != HttpServletResponse.SC_CREATED) {
                //TODO BOOM!
                throw new RuntimeException("Bad response code.  Got " + responseCode + " but expected "
                        + HttpServletResponse.SC_CREATED);
            }

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    String output = "<a href='" + returnUrl + "'>Continue to launch presentation url</a>";

    try {
        PrintWriter out = response.getWriter();
        out.println(output);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.impalaframework.web.servlet.wrapper.request.PartitionedRequestWrapper.java

public HttpServletRequest getWrappedRequest(HttpServletRequest request, ServletContext servletContext,
        RequestModuleMapping moduleMapping, String applicationId) {

    if (request instanceof ModuleHttpServletRequest) {
        if (((ModuleHttpServletRequest) request).isReuse()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Returning existing mapped request instance for request with URI "
                        + request.getRequestURI());
            }/*  www.java  2 s  .c  o m*/
            return request;
        }
    }

    final HttpSessionWrapper sessionWrapper;
    if (enableModuleSessionProtection || enablePartitionedServletContext) {
        PartitionedHttpSessionWrapper httpSessionWrapper = new PartitionedHttpSessionWrapper();
        httpSessionWrapper.setServletContext(servletContext);
        httpSessionWrapper.setWebAttributeQualifier(webAttributeQualifier);
        httpSessionWrapper.setEnableModuleSessionProtection(enableModuleSessionProtection);
        httpSessionWrapper.setEnablePartitionedServletContext(enablePartitionedServletContext);
        sessionWrapper = httpSessionWrapper;
    } else {

        IdentityHttpSessionWrapper httpSessionWrapper = new IdentityHttpSessionWrapper();
        sessionWrapper = httpSessionWrapper;
    }

    final String moduleName = moduleMapping.getModuleName();
    final String wrappedServletContextAttributeName = webAttributeQualifier
            .getQualifiedAttributeName("wrapped_servlet_context", applicationId, moduleName);
    final ServletContext wrappedServletContext = (ServletContext) servletContext
            .getAttribute(wrappedServletContextAttributeName);

    final MappedHttpServletRequest mappedRequest = new MappedHttpServletRequest(
            (wrappedServletContext != null ? wrappedServletContext : servletContext), request, sessionWrapper,
            moduleMapping, applicationId);

    String baseAttributeName = webAttributeQualifier.getQualifierPrefix(applicationId, moduleName);
    request.setAttribute(WebAttributeQualifier.MODULE_QUALIFIER_PREFIX, baseAttributeName);

    return mappedRequest;
}