Example usage for org.springframework.security.core.context SecurityContextHolder MODE_GLOBAL

List of usage examples for org.springframework.security.core.context SecurityContextHolder MODE_GLOBAL

Introduction

In this page you can find the example usage for org.springframework.security.core.context SecurityContextHolder MODE_GLOBAL.

Prototype

String MODE_GLOBAL

To view the source code for org.springframework.security.core.context SecurityContextHolder MODE_GLOBAL.

Click Source Link

Usage

From source file:org.key2gym.client.Main.java

/**
 * The main method which performs all the task described in the class
 * description.// w w w.  ja v  a 2 s  .  c  o  m
 * 
 * @param args an array of arguments
 */
public static void main(String[] args) {

    /*
     * Configures the logger using 'etc/logging.properties' or the default
     * logging properties file.
     */
    try (InputStream input = new FileInputStream(PATH_LOGGING_PROPERTIES)) {
        PropertyConfigurator.configure(input);
    } catch (IOException ex) {
        try (InputStream input = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream(RESOURCE_DEFAULT_LOGGING_PROPERTIES)) {
            PropertyConfigurator.configure(input);

            /*
             * Notify that the default logging properties file has been
             * used.
             */
            logger.info("Could not load the logging properties file");
        } catch (IOException ex2) {
            throw new RuntimeException("Failed to initialize logging system", ex2);
        }
    }

    logger.info("Starting...");

    /*
     * Loads the built-in default properties file.
     */
    try (InputStream input = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(RESOURCE_DEFAULT_CLIENT_PROPERTIES)) {
        Properties defaultProperties = null;
        defaultProperties = new Properties();
        defaultProperties.load(input);
        properties.putAll(defaultProperties);
    } catch (IOException ex) {
        throw new RuntimeException("Failed to load the default client properties file", ex);
    }

    /*
     * Loads the local client properties file.
     */
    try (FileInputStream input = new FileInputStream(PATH_APPLICATION_PROPERTIES)) {
        Properties localProperties = null;
        localProperties = new Properties();
        localProperties.load(input);
        properties.putAll(localProperties);
    } catch (IOException ex) {
        if (logger.isEnabledFor(Level.DEBUG)) {
            logger.debug("Failed to load the client properties file", ex);
        } else {
            logger.info("Could not load the local client properties file");
        }

        /*
         * It's okay to start without the local properties file.
         */
    }

    logger.debug("Effective properties: " + properties);

    if (properties.containsKey(PROPERTY_LOCALE_COUNTRY) && properties.containsKey(PROPERTY_LOCALE_LANGUAGE)) {

        /*
         * Changes the application's locale.
         */
        Locale.setDefault(new Locale(properties.getProperty(PROPERTY_LOCALE_LANGUAGE),
                properties.getProperty(PROPERTY_LOCALE_COUNTRY)));

    } else {
        logger.debug("Using the default locale");
    }

    /*
     * Changes the application's L&F.
     */
    String ui = properties.getProperty(PROPERTY_UI);
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if (ui.equalsIgnoreCase(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
            | UnsupportedLookAndFeelException ex) {
        logger.error("Failed to change the L&F:", ex);
    }

    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);

    // Loads the client application context
    context = new ClassPathXmlApplicationContext("META-INF/client.xml");

    logger.info("Started!");
    launchAndWaitMainFrame();
    logger.info("Shutting down!");

    context.close();
}

From source file:org.opennms.poller.remote.Main.java

private void getAuthenticationInfo() throws InvocationTargetException, InterruptedException {
    if (m_uri == null) {
        throw new IllegalArgumentException("no URI specified!");
    } else if (m_uri.getScheme() == null) {
        throw new IllegalArgumentException("no URI scheme specified!");
    }//w ww  .  ja va 2s .c  o m

    // Make sure that the URI is a valid value
    SpringExportSchemes.valueOf(m_uri.getScheme());

    if (SpringExportSchemes.rmi.toString().equals(m_uri.getScheme())) {
        // RMI doesn't have authentication
        return;
    }

    if (m_username == null) {
        // Display a screen where the username and password are entered
        final AuthenticationGui gui = createGui();
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                gui.createAndShowGui();
            }
        });

        /*
         * This call pauses on a {@link CountDownLatch} that is
         * signaled when the user hits the 'OK' button on the GroovyGui
         * screen.
         */
        AuthenticationBean auth = gui.getAuthenticationBean();

        m_username = auth.getUsername();
        m_password = auth.getPassword();
    }

    if (m_username != null) {
        SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
        SecurityContextHolder.getContext()
                .setAuthentication(new UsernamePasswordAuthenticationToken(m_username, m_password));
    }
}

From source file:org.pentaho.di.repository.pur.PurRepositoryIT.java

protected void setUpUser() {
    StandaloneSession pentahoSession = new StandaloneSession(userInfo.getLogin());
    pentahoSession.setAuthenticated(userInfo.getLogin());
    pentahoSession.setAttribute(IPentahoSession.TENANT_ID_KEY, "/pentaho/" + EXP_TENANT);
    List<GrantedAuthority> authorities = new ArrayList<>(2);
    authorities.add(new SimpleGrantedAuthority("Authenticated"));
    authorities.add(new SimpleGrantedAuthority("acme_Authenticated"));
    final String password = "ignored"; //$NON-NLS-1$
    UserDetails userDetails = new User(userInfo.getLogin(), password, true, true, true, true, authorities);
    Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, password, authorities);
    // next line is copy of SecurityHelper.setPrincipal
    pentahoSession.setAttribute("SECURITY_PRINCIPAL", authentication);
    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
    PurRepositoryTestingUtils.setSession(pentahoSession, authentication);
    repositoryLifecyleManager.newTenant();
    repositoryLifecyleManager.newUser();
}

From source file:org.pentaho.di.ui.repository.pur.repositoryexplorer.model.UIEERepositoryDirectoryIT.java

private void setUpUser() {
    StandaloneSession pentahoSession = new StandaloneSession(userInfo.getLogin());
    pentahoSession.setAuthenticated(userInfo.getLogin());
    pentahoSession.setAttribute(IPentahoSession.TENANT_ID_KEY, "/pentaho/" + EXP_TENANT);
    List<GrantedAuthority> authorities = new ArrayList<>(2);
    authorities.add(new SimpleGrantedAuthority("Authenticated"));
    authorities.add(new SimpleGrantedAuthority("acme_Authenticated"));
    final String password = "ignored"; //$NON-NLS-1$
    UserDetails userDetails = new User(userInfo.getLogin(), password, true, true, true, true, authorities);
    Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, password, authorities);
    // next line is copy of SecurityHelper.setPrincipal
    pentahoSession.setAttribute("SECURITY_PRINCIPAL", authentication);
    PentahoSessionHolder.setSession(pentahoSession);
    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    repositoryLifecyleManager.newTenant();
    repositoryLifecyleManager.newUser();
}

From source file:org.pentaho.platform.plugin.services.metadata.MetadataRepositoryLifecycleManagerIT.java

@BeforeClass
public static void beforeClass() throws Exception {
    System.setProperty(SYSTEM_PROPERTY, "MODE_GLOBAL");
    PentahoSessionHolder.setStrategyName(PentahoSessionHolder.MODE_GLOBAL);
    FileUtils.deleteDirectory(new File("/tmp/jackrabbit-test-TRUNK"));
    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
}

From source file:org.pentaho.platform.repository2.unified.webservices.jaxws.DefaultUnifiedRepositoryJaxwsWebServiceIT.java

@Before
public void setUp() throws Exception {
    super.setUp();

    IRepositoryVersionManager mockRepositoryVersionManager = mock(IRepositoryVersionManager.class);
    when(mockRepositoryVersionManager.isVersioningEnabled(anyString())).thenReturn(true);
    when(mockRepositoryVersionManager.isVersionCommentEnabled(anyString())).thenReturn(false);
    JcrRepositoryFileUtils.setRepositoryVersionManager(mockRepositoryVersionManager);

    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);

    String address = "http://localhost:9000/repo";
    Endpoint.publish(address, new DefaultUnifiedRepositoryJaxwsWebService(repo));

    Service service = Service.create(new URL("http://localhost:9000/repo?wsdl"),
            new QName("http://www.pentaho.org/ws/1.0", "unifiedRepository"));

    IUnifiedRepositoryJaxwsWebService repoWebService = service.getPort(IUnifiedRepositoryJaxwsWebService.class);

    // accept cookies to maintain session on server
    ((BindingProvider) repoWebService).getRequestContext().put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);
    // support streaming binary data
    ((BindingProvider) repoWebService).getRequestContext().put(JAXWSProperties.HTTP_CLIENT_STREAMING_CHUNK_SIZE,
            8192);/*from ww w. j a va2s.c  o m*/
    SOAPBinding binding = (SOAPBinding) ((BindingProvider) repoWebService).getBinding();
    binding.setMTOMEnabled(true);

    repo = new UnifiedRepositoryToWebServiceAdapter(repoWebService);

}

From source file:org.pentaho.test.platform.web.http.api.DirectoryResourceIT.java

@BeforeClass
public static void beforeClass() throws Exception {
    System.setProperty(SYSTEM_PROPERTY, "MODE_GLOBAL");
    PentahoSessionHolder.setStrategyName(PentahoSessionHolder.MODE_GLOBAL);

    FileUtils.deleteDirectory(new File("/tmp/jackrabbit-test-TRUNK"));
    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
}

From source file:org.pentaho.test.platform.web.http.api.DirectoryResourceIT.java

@AfterClass
public static void afterClass() {
    PentahoSessionHolder.setStrategyName(PentahoSessionHolder.MODE_GLOBAL);
    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
}

From source file:org.pentaho.test.platform.web.http.api.DirectoryResourceIT.java

@Before
public void beforeTest() throws PlatformInitializationException {
    mp = new MicroPlatform();
    // used by DefaultPentahoJackrabbitAccessControlHelper
    mp.defineInstance(IAuthorizationPolicy.class, authorizationPolicy);
    mp.defineInstance(ITenantManager.class, tenantManager);
    mp.define(ITenant.class, Tenant.class);
    mp.defineInstance("roleAuthorizationPolicyRoleBindingDaoTarget", roleBindingDaoTarget);
    mp.defineInstance(IRoleAuthorizationPolicyRoleBindingDao.class, roleBindingDaoTarget);
    mp.defineInstance("tenantedUserNameUtils", tenantedUserNameUtils);
    mp.defineInstance("tenantedRoleNameUtils", tenantedRoleNameUtils);
    mp.defineInstance("repositoryAdminUsername", repositoryAdminUsername);
    mp.define(IRoleAuthorizationPolicyRoleBindingDao.class, RoleAuthorizationPolicy.class, Scope.GLOBAL);
    mp.define(ITenantManager.class, RepositoryTenantManager.class, Scope.GLOBAL);
    mp.defineInstance("singleTenantAdminAuthorityName", new String("Administrator"));
    mp.defineInstance("RepositoryFileProxyFactory",
            new RepositoryFileProxyFactory(this.testJcrTemplate, this.repositoryFileDao));

    DefaultRepositoryVersionManager defaultRepositoryVersionManager = new DefaultRepositoryVersionManager();
    defaultRepositoryVersionManager.setPlatformMimeResolver(new NameBaseMimeResolver());
    mp.defineInstance(IRepositoryVersionManager.class, defaultRepositoryVersionManager);
    UserRoleDaoUserDetailsService userDetailsService = new UserRoleDaoUserDetailsService();
    userDetailsService.setUserRoleDao(userRoleDao);
    List<String> systemRoles = new ArrayList<String>();
    systemRoles.add("Admin");
    List<String> extraRoles = Arrays.asList(new String[] { "Authenticated", "Anonymous" });
    String adminRole = "Admin";

    userRoleListService = new UserRoleDaoUserRoleListService(userRoleDao, userDetailsService,
            tenantedUserNameUtils, systemRoles, extraRoles, adminRole);
    ((UserRoleDaoUserRoleListService) userRoleListService).setUserRoleDao(userRoleDao);
    ((UserRoleDaoUserRoleListService) userRoleListService).setUserDetailsService(userDetailsService);

    mp.defineInstance(IUserRoleListService.class, userRoleListService);
    mp.start();/*from www. ja  v a 2s .c o m*/
    logout();
    startupCalled = true;
    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
}

From source file:org.pentaho.test.platform.web.http.api.RepositoryResourceIT.java

@Before
public void beforeTest() throws Exception {
    repositoryBase.setUp();/*w  ww  . j a  va  2  s  .c  o  m*/
    repositoryBase.getMp().define(IPluginManager.class, DefaultPluginManager.class, Scope.GLOBAL);
    repositoryBase.getMp().defineInstance(IPluginResourceLoader.class, new PluginResourceLoader() {
        protected PluginClassLoader getOverrideClassloader() {
            return new PluginClassLoader(
                    new File(TestResourceLocation.TEST_RESOURCES + "/PluginResourceTest/system/test-plugin"),
                    this);
        }
    });
    repositoryBase.getMp().define(IPluginProvider.class, TestPlugin.class, Scope.GLOBAL);
    PentahoSystem.get(IPluginManager.class).reload();
    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);

    repositoryBase.loginAsRepositoryAdmin();

    mainTenant_1 = repositoryBase.createTenant(repositoryBase.getSystemTenant(), MAIN_TENANT_1);
    repositoryBase.createUser(mainTenant_1, "admin", "password",
            new String[] { repositoryBase.getTenantAdminRoleName() });

    repositoryBase.login("admin", mainTenant_1, new String[] { repositoryBase.getTenantAdminRoleName() });

    publicFolderPath = ClientRepositoryPaths.getPublicFolderPath().replaceAll("/", ":");
}