Example usage for org.apache.shiro.web.env EnvironmentLoader ENVIRONMENT_ATTRIBUTE_KEY

List of usage examples for org.apache.shiro.web.env EnvironmentLoader ENVIRONMENT_ATTRIBUTE_KEY

Introduction

In this page you can find the example usage for org.apache.shiro.web.env EnvironmentLoader ENVIRONMENT_ATTRIBUTE_KEY.

Prototype

String ENVIRONMENT_ATTRIBUTE_KEY

To view the source code for org.apache.shiro.web.env EnvironmentLoader ENVIRONMENT_ATTRIBUTE_KEY.

Click Source Link

Usage

From source file:com.meltmedia.cadmium.servlets.guice.CadmiumListener.java

License:Apache License

private Module createModule() {
    return new AbstractModule() {
        @SuppressWarnings("unchecked")
        @Override//from w w  w  .  j a  v  a  2 s  .c o m
        protected void configure() {
            Properties configProperties = configManager.getDefaultProperties();

            org.apache.shiro.web.env.WebEnvironment shiroEnv = (org.apache.shiro.web.env.WebEnvironment) context
                    .getAttribute(EnvironmentLoader.ENVIRONMENT_ATTRIBUTE_KEY);
            if (shiroEnv != null && shiroEnv instanceof WebEnvironment) {
                WebEnvironment cadmiumShiroEnv = (WebEnvironment) shiroEnv;
                if (cadmiumShiroEnv.getPersistablePropertiesRealm() != null) {
                    log.debug("Binding shiro configurable realm: " + PersistablePropertiesRealm.class);
                    bind(PersistablePropertiesRealm.class)
                            .toInstance(cadmiumShiroEnv.getPersistablePropertiesRealm());
                    cadmiumShiroEnv.getPersistablePropertiesRealm()
                            .loadProperties(applicationContentRoot.getAbsoluteFile());
                }
            }

            bind(Reflections.class).toInstance(reflections);

            bind(Boolean.class).annotatedWith(com.meltmedia.cadmium.core.ISJBoss.class).toInstance(jboss);
            bind(Boolean.class).annotatedWith(com.meltmedia.cadmium.core.ISOLDJBoss.class).toInstance(oldJBoss);

            bind(com.meltmedia.cadmium.core.SiteDownService.class).toInstance(MaintenanceFilter.siteDown);
            bind(com.meltmedia.cadmium.core.ApiEndpointAccessController.class)
                    .toInstance(ApiEndpointAccessFilter.controller);

            bind(ScheduledExecutorService.class).toInstance(executor);
            bind(ExecutorService.class).toInstance(executor);
            bind(Executor.class).toInstance(executor);

            bind(FileServlet.class).in(Scopes.SINGLETON);
            bind(com.meltmedia.cadmium.core.ContentService.class).to(FileServlet.class);

            bind(MessageConverter.class);
            bind(MessageSender.class).to(JGroupsMessageSender.class);

            bind(DelayedGitServiceInitializer.class)
                    .annotatedWith(com.meltmedia.cadmium.core.ContentGitService.class)
                    .toInstance(new DelayedGitServiceInitializer());
            bind(DelayedGitServiceInitializer.class)
                    .annotatedWith(com.meltmedia.cadmium.core.ConfigurationGitService.class)
                    .toInstance(new DelayedGitServiceInitializer());

            members = Collections.synchronizedList(new ArrayList<ChannelMember>());
            bind(new TypeLiteral<List<ChannelMember>>() {
            }).annotatedWith(com.meltmedia.cadmium.core.ClusterMembers.class).toInstance(members);
            Multibinder<com.meltmedia.cadmium.core.CommandAction<?>> commandActionBinder = Multibinder
                    .newSetBinder(binder(), new TypeLiteral<com.meltmedia.cadmium.core.CommandAction<?>>() {
                    });

            @SuppressWarnings("rawtypes")
            Set<Class<? extends com.meltmedia.cadmium.core.CommandAction>> commandActionSet = reflections
                    .getSubTypesOf(com.meltmedia.cadmium.core.CommandAction.class);
            log.debug("Found {} CommandAction classes.", commandActionSet.size());

            for (@SuppressWarnings("rawtypes")
            Class<? extends com.meltmedia.cadmium.core.CommandAction> commandActionClass : commandActionSet) {
                commandActionBinder.addBinding()
                        .to((Class<? extends com.meltmedia.cadmium.core.CommandAction<?>>) commandActionClass);
            }

            bind(new TypeLiteral<CommandResponse<HistoryResponse>>() {
            }).to(HistoryResponseCommandAction.class).in(Scopes.SINGLETON);
            bind(new TypeLiteral<CommandResponse<LoggerConfigResponse>>() {
            }).to(LoggerConfigResponseCommandAction.class).in(Scopes.SINGLETON);

            bind(new TypeLiteral<Map<String, com.meltmedia.cadmium.core.CommandAction<?>>>() {
            }).annotatedWith(com.meltmedia.cadmium.core.CommandMap.class).toProvider(CommandMapProvider.class);
            bind(new TypeLiteral<Map<String, Class<?>>>() {
            }).annotatedWith(com.meltmedia.cadmium.core.CommandBodyMap.class)
                    .toProvider(CommandBodyMapProvider.class);

            bind(String.class).annotatedWith(com.meltmedia.cadmium.core.ContentDirectory.class)
                    .toInstance(contentDir);
            bind(String.class).annotatedWith(com.meltmedia.cadmium.core.SharedContentRoot.class)
                    .toInstance(sharedContentRoot.getAbsolutePath());
            bind(String.class).annotatedWith(com.meltmedia.cadmium.core.CurrentWarName.class)
                    .toInstance(warName);

            String environment = configProperties.getProperty("com.meltmedia.cadmium.environment",
                    "development");

            // Bind channel name
            bind(String.class).annotatedWith(MessagingChannelName.class)
                    .toInstance("CadmiumChannel-v2.0-" + vHostName + "-" + environment);
            bind(String.class).annotatedWith(VHost.class).toInstance(vHostName);

            bind(String.class).annotatedWith(com.meltmedia.cadmium.core.ApplicationContentRoot.class)
                    .toInstance(applicationContentRoot.getAbsoluteFile().getAbsolutePath());

            bind(HistoryManager.class);

            bind(ConfigManager.class).toInstance(configManager);

            // Bind Config file URL
            if (channelConfigUrl == null) {
                log.info("Using internal tcp.xml configuration file for JGroups.");
                URL propsUrl = JChannelProvider.class.getClassLoader().getResource("tcp.xml");
                bind(URL.class).annotatedWith(MessagingConfigurationUrl.class).toInstance(propsUrl);
            } else {
                try {
                    log.info("Using {} configuration file for JGroups.", channelConfigUrl);
                    bind(URL.class).annotatedWith(MessagingConfigurationUrl.class)
                            .toInstance(new URL(channelConfigUrl));
                } catch (MalformedURLException e) {
                    log.error("Failed to setup jgroups with the file specified [" + channelConfigUrl
                            + "]. Failing back to built in configuration!", e);
                }
            }

            // Bind JChannel provider
            bind(JChannel.class).toProvider(JChannelProvider.class).in(Scopes.SINGLETON);

            bind(MembershipListener.class).to(JGroupsMembershipTracker.class);
            bind(MembershipTracker.class).to(JGroupsMembershipTracker.class);
            bind(MessageListener.class).to(MessageReceiver.class);

            bind(LifecycleService.class);
            bind(new TypeLiteral<com.meltmedia.cadmium.core.CoordinatedWorker<com.meltmedia.cadmium.core.commands.ContentUpdateRequest>>() {
            }).annotatedWith(com.meltmedia.cadmium.core.ContentWorker.class).to(CoordinatedWorkerImpl.class);
            bind(new TypeLiteral<com.meltmedia.cadmium.core.CoordinatedWorker<com.meltmedia.cadmium.core.commands.ContentUpdateRequest>>() {
            }).annotatedWith(com.meltmedia.cadmium.core.ConfigurationWorker.class)
                    .to(ConfigCoordinatedWorkerImpl.class);

            bind(SiteConfigProcessor.class);
            bind(Api.class);
            bind(EventQueue.class);

            Multibinder<ConfigProcessor> configProcessorBinder = Multibinder.newSetBinder(binder(),
                    ConfigProcessor.class);

            Set<Class<? extends ConfigProcessor>> configProcessorSet = reflections
                    .getSubTypesOf(ConfigProcessor.class);

            log.debug("Found {} ConfigProcessor classes.", configProcessorSet.size());

            for (Class<? extends ConfigProcessor> configProcessorClass : configProcessorSet) {
                configProcessorBinder.addBinding().to(configProcessorClass);
                //bind(ConfigProcessor.class).to(configProcessorClass);
            }

            bind(Receiver.class).to(MultiClassReceiver.class).asEagerSingleton();

            Set<Class<?>> modules = reflections
                    .getTypesAnnotatedWith(com.meltmedia.cadmium.core.CadmiumModule.class);
            log.debug("Found {} Module classes.", modules.size());
            for (Class<?> module : modules) {
                if (Module.class.isAssignableFrom(module)) {
                    log.debug("Installing module {}", module.getName());
                    try {
                        install(((Class<? extends Module>) module).newInstance());
                    } catch (InstantiationException e) {
                        log.warn("Failed to instantiate " + module.getName(), e);
                    } catch (IllegalAccessException e) {
                        log.debug("Modules [" + module.getName() + "] constructor is not accessible.", e);
                    }
                }
            }

            //Discover configuration classes.
            install(new ConfigurationModule(reflections));

            // Bind Jersey Endpoints
            Set<Class<? extends Object>> jerseySet = reflections.getTypesAnnotatedWith(Path.class);

            log.debug("Found {} jersey services with the Path annotation.", jerseySet.size());

            for (Class<? extends Object> jerseyService : jerseySet) {
                log.debug("Binding jersey endpoint class {}", jerseyService.getName());
                bind(jerseyService).asEagerSingleton();
            }

            SchedulerService.bindScheduled(binder(), reflections);
            bind(SchedulerService.class);
        }
    };
}

From source file:net.scran24.user.server.services.InitListener.java

License:Apache License

public void contextInitialized(ServletContextEvent contextEvent) {
    ServletContext context = contextEvent.getServletContext();

    Map<String, String> configParams = new HashMap<String, String>();

    Enumeration<String> paramNames = context.getInitParameterNames();

    while (paramNames.hasMoreElements()) {
        String name = paramNames.nextElement();
        configParams.put(name, context.getInitParameter(name));
    }/*from  www. ja  va 2  s  .c om*/

    AbstractModule configModule;

    try {
        Constructor<?> ctor = Class.forName(context.getInitParameter("config-module"))
                .getConstructor(Map.class);
        configModule = (AbstractModule) ctor.newInstance(configParams);
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | NoSuchMethodException
            | SecurityException | IllegalArgumentException | InvocationTargetException e) {
        throw new RuntimeException(e);
    }

    Injector injector = Guice.createInjector(configModule);

    context.setAttribute("intake24.injector", injector);

    WebEnvironment shiroEnvironment = (WebEnvironment) context
            .getAttribute(EnvironmentLoader.ENVIRONMENT_ATTRIBUTE_KEY);
    RealmSecurityManager securityManager = (RealmSecurityManager) shiroEnvironment.getSecurityManager();

    ScranAuthRealm securityRealm = new ScranAuthRealm(injector.getInstance(DataStore.class));

    HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
    credentialsMatcher.setHashAlgorithmName(Sha256Hash.ALGORITHM_NAME);
    credentialsMatcher.setStoredCredentialsHexEncoded(false);
    credentialsMatcher.setHashIterations(1024);

    securityRealm.setCredentialsMatcher(credentialsMatcher);
    securityManager.setRealm(securityRealm);

}

From source file:org.openengsb.ui.common.OpenEngSBWicketApplication.java

License:Apache License

private void initWebEnvironment() {
    DefaultWebEnvironment environment = new DefaultWebEnvironment();
    SecurityManagerHolder manager = new SecurityManagerHolder();
    InjectorHolder.getInjector().inject(manager, SecurityManagerHolder.class);
    environment.setSecurityManager(manager.getWebSecurityManager());
    getServletContext().setAttribute(EnvironmentLoader.ENVIRONMENT_ATTRIBUTE_KEY, environment);
}

From source file:org.pac4j.demo.shiro.util.WebUtils.java

License:Apache License

public static <T extends Object> T getObject(final PageContext pageContext, final Class<T> clazz,
        final String name) {
    final IniWebEnvironment env = (IniWebEnvironment) pageContext.getServletContext()
            .getAttribute(EnvironmentLoader.ENVIRONMENT_ATTRIBUTE_KEY);
    if (env != null) {
        return env.getObject(name, clazz);
    }// ww w. j  a va2 s  . c  o  m
    return null;
}

From source file:org.panifex.security.shiro.env.ModularEnvironmentLoaderTest.java

License:Open Source License

@Test
public void testInitEnvironmentWithPreparedModularWebEnvironment() {
    // mocks//from   ww  w.  jav  a2s . c om
    ModularWebEnvironment webEnvironment = createMock(ModularWebEnvironment.class);

    // servlet context must not return an environment attribute because it contains
    // an already registered Shiro's environment
    expect(servletContextMock.getAttribute(EnvironmentLoader.ENVIRONMENT_ATTRIBUTE_KEY)).andReturn(null);

    servletContextMock.log(anyObject(String.class));

    // expect binding servlet context to modular web environment
    webEnvironment.setServletContext(servletContextMock);

    // expect lifecycle init
    LifecycleUtils.init(webEnvironment);

    // expect setting modular web environment to servlet context
    servletContextMock.setAttribute(EnvironmentLoader.ENVIRONMENT_ATTRIBUTE_KEY, webEnvironment);

    // prepare modular environment loader to test
    ModularEnvironmentLoader loader = new ModularEnvironmentLoader();
    loader.setEnvironment(webEnvironment);

    replayAll();
    loader.initEnvironment(servletContextMock);
    verifyAll();
}

From source file:org.panifex.security.shiro.SecurityFilterImpl.java

License:Open Source License

@Override
public void init() throws Exception {
    log.info("Initialize security filter");
    ServletContext servletContext = getServletContext();
    if (servletContext.getAttribute(EnvironmentLoader.ENVIRONMENT_ATTRIBUTE_KEY) == null) {
        loader.initEnvironment(getServletContext());
    }// ww w  .j a  va 2 s  . c om

    super.init();

    bindLoginUrlToAccessControlFilter();
    bindPasswordParamToFormAuthenticationFilter();
    bindRememberMeParamToFormAuthenticationFilter();
    bindSuccessUrlToAuthenticationFilter();
    bindUsernameParamToFormAuthenticationFilter();
}

From source file:org.panifex.security.shiro.SecurityFilterImplTest.java

License:Open Source License

@Test
public void testInitSecurityFilter() throws Exception {
    // expect initializing environment
    expect(environmentLoaderMock.initEnvironment(servletContextMock))
            .andReturn(createMock(WebEnvironment.class));

    expectSettingDefaultLoginUrl();/*from ww  w .j a  v  a2  s .  com*/
    expectSettingDefaultPasswordParam();
    expectSettingDefaultRememberMeParam();
    expectSettingDefaultSuccessUrl();
    expectSettingDefaultUsernameParam();

    expect(servletContextMock.getAttribute(EnvironmentLoader.ENVIRONMENT_ATTRIBUTE_KEY)).andReturn(null);

    // perform test
    replayAll();
    filter.init();
    verifyAll();
}