Example usage for org.apache.shiro.subject Subject execute

List of usage examples for org.apache.shiro.subject Subject execute

Introduction

In this page you can find the example usage for org.apache.shiro.subject Subject execute.

Prototype

void execute(Runnable runnable);

Source Link

Document

Associates the specified Runnable with this Subject instance and then executes it on the currently running thread.

Usage

From source file:com.freedomotic.security.AuthImpl.java

License:Open Source License

private Runnable executePrivileged(String classname, Runnable action) {
    if (isInited()) {
        //LOG.info("Executing privileged for plugin: " + classname);
        PrincipalCollection plugPrincipals = new SimplePrincipalCollection(classname, pluginRealm.getName());
        Subject plugSubject = new Subject.Builder().principals(plugPrincipals).buildSubject();
        plugSubject.getSession().setTimeout(-1);
        plugSubject.execute(action);
    } else {//  www.  java 2 s. c o m
        action.run();
    }
    return null;
}

From source file:ddf.common.test.ServiceManagerProxy.java

License:Open Source License

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

    Subject subject = org.codice.ddf.security.common.Security.runAsAdmin(() -> Security.getSystemSubject());
    return subject.execute(() -> {
        try {//  ww w .j  av a  2s. c o m
            return method.invoke(serviceManager, args);
        } catch (Exception e) {
            LOGGER.error("Unable to run method {} as system subject", method.getName());
            return null;
        }
    });
}

From source file:info.novatec.inspectit.cmr.spring.exporter.SessionAwareSecureRemoteInvocationExecutor.java

License:Apache License

/**
 * {@inheritDoc}/*  w w  w . j a  va 2s. co m*/
 */
@Override
public Object invoke(final RemoteInvocation invocation, final Object targetObject)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    try {
        Subject.Builder builder = new Subject.Builder(securityManager);
        String host = (String) invocation.getAttribute(SecureRemoteInvocationFactory.HOST_KEY);
        if (host != null) {
            builder.host(host);
        }
        Serializable sessionId = invocation.getAttribute(SecureRemoteInvocationFactory.SESSION_ID_KEY);
        if (sessionId != null) {
            builder.sessionId(sessionId);
        }

        Subject subject = builder.buildSubject();

        return subject.execute(new Callable<Object>() {
            public Object call() throws Exception {
                // This is the part which is significantly modified to set the session id thread local manually.
                Object result = SessionAwareSecureRemoteInvocationExecutor.super.invoke(invocation,
                        targetObject);

                Object sessionId = null;
                Session session = SecurityUtils.getSubject().getSession(false);
                if (null != session) {
                    sessionId = session.getId();
                }
                sessionIdThreadLocal.set(sessionId);

                return result;
            }
        });
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        if ((cause instanceof NoSuchMethodException)) {
            throw ((NoSuchMethodException) cause); // NOPMD
        }
        if ((cause instanceof IllegalAccessException)) {
            throw ((IllegalAccessException) cause); // NOPMD
        }
        if ((cause instanceof InvocationTargetException)) {
            throw ((InvocationTargetException) cause); // NOPMD
        }
        throw new InvocationTargetException(cause); // NOPMD
    } catch (Throwable t) { // NOPMD
        throw new InvocationTargetException(t);
    }
}

From source file:io.bootique.shiro.ShiroModuleIT.java

License:Apache License

@Test
public void testFullStack_SecurityUtils() {
    Realm mockRealm = mockRealm();//w  ww  . j  av  a  2 s . c  om

    BQRuntime runtime = testFactory.app().module(b -> ShiroModule.extend(b).addRealm(mockRealm))
            .autoLoadModules().createRuntime();

    Subject subject = new Subject.Builder(runtime.getInstance(SecurityManager.class)).buildSubject();

    assertNull(ThreadContext.getSubject());

    // testing Shiro idiom of wrapping lambda in a subject...
    subject.execute(() -> {
        assertSame("Unexpected subject, thread state is disturbed", subject, SecurityUtils.getSubject());
    });
}

From source file:it.freedomotic.security.AuthImpl.java

License:Open Source License

private void executePrivileged(String classname, Runnable action) {
    if (isInited()) {
        //LOG.info("Executing privileged for plugin: " + classname);
        PrincipalCollection plugPrincipals = new SimplePrincipalCollection(classname, pluginRealm.getName());
        Subject plugSubject = new Subject.Builder().principals(plugPrincipals).buildSubject();
        plugSubject.getSession().setTimeout(-1);
        plugSubject.execute(action);
    } else {//ww  w  . j  ava  2 s  . c o m
        action.run();
    }
}

From source file:org.atteo.moonshine.tests.ShiroRule.java

License:Apache License

@Override
public Statement apply(final Statement base, Description description) {
    return new Statement() {
        @Override/*from ww w  .  j  a va 2  s . c  o m*/
        public void evaluate() throws Throwable {
            Subject.Builder builder = new Subject.Builder();
            Subject subject = builder.buildSubject();
            subject.execute(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    try {
                        base.evaluate();
                    } catch (Exception | Error e) {
                        throw e;
                    } catch (Throwable e) {
                        throw new RuntimeException(e);
                    }
                    return null;
                }
            });
        }
    };
}

From source file:org.codice.ddf.commands.catalog.SubjectCommands.java

License:Open Source License

private Object runWithUserName() throws InvocationTargetException {
    try {//from   w w  w . jav  a2s .  com
        String password = session.readLine("Password for " + user + ": ", '*');
        Subject subject = security.getSubject(user, password, "127.0.0.1");

        if (subject == null) {
            printErrorMessage("Invalid username/password");
            return null;
        }

        return subject.execute(this::executeWithSubject);
    } catch (ExecutionException e) {
        LOGGER.info("Failed to run command: {}", e.getCause().getMessage(), e.getCause());
        throw new InvocationTargetException(e.getCause());
    } catch (IOException e) {
        LOGGER.info("Failed to run command", e);
        printErrorMessage("Failed to read password");
    }

    return null;
}

From source file:org.codice.ddf.itests.common.ServiceManagerProxy.java

License:Open Source License

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    // wait until the security manager is available otherwise the getSystemSubject command will fail
    with().pollInterval(1, SECONDS).await().atMost(AbstractIntegrationTest.GENERIC_TIMEOUT_SECONDS, SECONDS)
            .until(() -> serviceManager.getServiceReference(SecurityManager.class) != null);

    RetryPolicy retryPolicy = new RetryPolicy().withMaxRetries(10).withDelay(1, SECONDS).retryWhen(null);
    Subject subject = Failsafe.with(retryPolicy).get(() -> SECURITY.runAsAdmin(SECURITY::getSystemSubject));
    return subject.execute(() -> method.invoke(serviceManager, args));
}

From source file:org.codice.ddf.migration.commands.MigrationCommand.java

License:Open Source License

private Object runWithUserName() throws ExecutionException {
    try {/* ww w.  jav  a 2s .  c om*/
        final String password = session.readLine("Password for " + user + ": ", '*');
        final Subject subject = security.getSubject(user, password, "127.0.0.1");

        if (subject != null) {
            return subject.execute(this::executeWithSubject);
        }
        outputErrorMessage("Invalid username/password");
    } catch (IOException e) {
        LOGGER.info("Failed to read password", e);
        outputErrorMessage("Failed to read password");
    }
    return null;
}

From source file:org.obiba.mica.security.SubjectUtils.java

License:Open Source License

public static <V> V sudo(Callable<V> callable) {
    Subject sudo = new Subject.Builder()
            .principals(SecurityUtils.getSecurityManager()
                    .authenticate(new SudoAuthToken(SecurityUtils.getSubject())).getPrincipals())
            .authenticated(true).buildSubject();

    return sudo.execute(callable);
}