Example usage for org.apache.shiro.subject.support SubjectThreadState SubjectThreadState

List of usage examples for org.apache.shiro.subject.support SubjectThreadState SubjectThreadState

Introduction

In this page you can find the example usage for org.apache.shiro.subject.support SubjectThreadState SubjectThreadState.

Prototype

public SubjectThreadState(Subject subject) 

Source Link

Document

Creates a new SubjectThreadState that will bind and unbind the specified Subject to the thread

Usage

From source file:cn.hxh.springside.test.utils.ShiroTestUtils.java

License:Apache License

/**
 * ?Subject?./*from w w  w.  java 2s .c  o m*/
 */
public static void bindSubject(Subject subject) {
    clearSubject();
    threadState = new SubjectThreadState(subject);
    threadState.bind();
}

From source file:com.ablesky.asdeploy.test.ShiroTestUtils.java

License:Apache License

/**
 * ?Subject?.//from   www . java  2 s .c om
 */
protected static void bindSubject(Subject subject) {
    clearSubject();
    threadState = new SubjectThreadState(subject);
    threadState.bind();
}

From source file:com.freedomotic.app.Freedomotic.java

License:Open Source License

/**
 *
 * @throws FreedomoticException//  w  w w .  ja v a2  s .  c o  m
 */
public void start() throws FreedomoticException {
    // Relocate base data folder according to configuration (if specified in the config file)
    // Do not move it in AppConfigImpl otherwise unit tests will become dependent to the presence of the data folder
    String defaultPath = Info.PATHS.PATH_DATA_FOLDER.getAbsolutePath();
    Info.relocateDataPath(new File(config.getStringProperty("KEY_DATA_PATH", defaultPath)));

    // init localization
    i18n.setDefaultLocale(config.getStringProperty("KEY_ENABLE_I18N", "no"));

    // init auth* framework
    auth.initBaseRealm();
    auth.load();
    if (auth.isInited()) {
        PrincipalCollection principals = new SimplePrincipalCollection("system", UserRealm.USER_REALM_NAME);
        Subject SysSubject = new Subject.Builder().principals(principals).buildSubject();
        SysSubject.getSession().setTimeout(-1);
        ThreadState threadState = new SubjectThreadState(SysSubject);
        threadState.bind();
        LOG.info("Booting as user:" + auth.getSubject().getPrincipal() + ". Session will last:"
                + auth.getSubject().getSession().getTimeout());
    }

    String resourcesPath = new File(Info.PATHS.PATH_WORKDIR
            + config.getStringProperty("KEY_RESOURCES_PATH", "/build/classes/it/freedom/resources/")).getPath();
    LOG.info("\nOS: " + System.getProperty("os.name") + "\n" + i18n.msg("architecture") + ": "
            + System.getProperty("os.arch") + "\n" + "OS Version: " + System.getProperty("os.version") + "\n"
            + i18n.msg("user") + ": " + System.getProperty("user.name") + "\n" + "Java Home: "
            + System.getProperty("java.home") + "\n" + "Java Library Path: {"
            + System.getProperty("java.library.path") + "}\n" + "Program path: "
            + System.getProperty("user.dir") + "\n" + "Java Version: " + System.getProperty("java.version")
            + "\n" + "Resources Path: " + resourcesPath);

    //check if topology manager is initiated
    if (topologyManager == null) {
        throw new IllegalStateException("Topology manager has not started");
    }

    if (synchManager == null) {
        throw new IllegalStateException("Synch manager has not started");
    }

    // register listener
    this.listener = new BusMessagesListener(this, busService);
    // this class is a BusConsumer too
    // listen for exit signal (an event) and call onExit method if received
    listener.consumeEventFrom("app.event.system.exit");

    // Stop on initialization error.
    final BootStatus currentStatus = BootStatus.getCurrentStatus();
    if (!BootStatus.STARTED.equals(currentStatus)) {

        kill(currentStatus.getCode());
    }

    /**
     * ******************************************************************
     * Starting the logger and popup it in the browser
     * *****************************************************************
     */
    if (!config.getStringProperty("KEY_SAVE_LOG_TO_FILE", "OFF").trim().equalsIgnoreCase("OFF")) {
        try {
            PatternLayout layout = new PatternLayout("%d{HH:mm:ss.SSS} %-5p [%t] (%F:%L) %m%n");
            RollingFileAppender rollingFileAppender = new RollingFileAppender(layout,
                    Info.PATHS.PATH_WORKDIR + "/log/freedomotic.log");
            rollingFileAppender.setMaxBackupIndex(5);
            rollingFileAppender.setMaxFileSize("500KB");
            org.apache.log4j.Logger proxyLogger = org.apache.log4j.Logger.getRootLogger();
            proxyLogger.setLevel(
                    org.apache.log4j.Level.toLevel(config.getStringProperty("KEY_SAVE_LOG_TO_FILE", "OFF")));
            proxyLogger.setAdditivity(false);
            proxyLogger.addAppender(rollingFileAppender);

            if ((config.getBooleanProperty("KEY_LOGGER_POPUP", true) == true)
                    && (java.awt.Desktop.getDesktop().isSupported(Desktop.Action.BROWSE))) {
                java.awt.Desktop.getDesktop()
                        .browse(new File(Info.PATHS.PATH_WORKDIR + "/log/freedomotic.log").toURI());
            }
        } catch (IOException ex) {
            LOG.error(ex.getMessage());
        }
    }

    /**
     * ******************************************************************
     * Create data backup folder (FEATURE DISABLED!!!)
     * *****************************************************************
     */
    //        if (getConfig().getBooleanProperty("KEY_BACKUP_DATA_BEFORE_START", true) == true) {
    //            try {
    //                CopyFile.copy(new File(Info.getDatafilePath()), new File(Info.getApplicationPath() + "/backup"));
    //            } catch (Exception ex) {
    //                logger.warning("unable to saveAll a backup copy of application data " + getStackTraceInfo(ex));
    //            }
    //        }
    /**
     * ******************************************************************
     * Shows the freedomotic website if stated in the config file
     * *****************************************************************
     */
    if (config.getBooleanProperty("KEY_SHOW_WEBSITE_ON_STARTUP", false)) {
        try {
            java.awt.Desktop.getDesktop().browse(new URI("www.freedomotic.com"));
        } catch (URISyntaxException ex) {
            LOG.error(ex.getMessage());
        } catch (IOException ex) {
            LOG.error(ex.getMessage());
        }
    }

    /**
     * ******************************************************************
     * Dynamically load all plugins
     * *****************************************************************
     */
    try {
        pluginsManager.loadAllPlugins();
    } catch (PluginLoadingException ex) {
        LOG.warn("Error while loading all plugins. Impossible to load " + ex.getPluginName(), ex);
    }

    /**
     * ******************************************************************
     * Dynamically load jar files in /plugin/providers folder for plugins
     * *****************************************************************
     */
    try {
        ClassPathUpdater.add(Info.PATHS.PATH_PROVIDERS_FOLDER);
    } catch (IOException | IllegalAccessException | NoSuchMethodException | InvocationTargetException ex) {
        LOG.error(ex.getMessage());
    }

    /**
     * ******************************************************************
     * Cache online plugins
     * *****************************************************************
     */
    if (config.getBooleanProperty("CACHE_MARKETPLACE_ON_STARTUP", false)) {
        try {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            LOG.info("Starting marketplace service");

                            MarketPlaceService mps = MarketPlaceService.getInstance();
                            onlinePluginCategories = mps.getCategoryList();
                        }
                    }).start();
                }
            });
        } catch (Exception e) {
            LOG.warn("Unable to cache plugins package from marketplace");
        }
    }

    // Bootstrap Things in the environments
    // This should be done after loading all Things plugins otherwise
    // its java class will not be recognized by the system
    environmentRepository.initFromDefaultFolder();
    // for (EnvironmentLogic env : environmentRepository.findAll()) {
    // Load all the Things in this environment
    //    File thingsFolder = env.getObjectFolder();
    //    List<EnvObjectLogic> loadedThings = thingsRepository.loadAll(thingsFolder);
    //    for (EnvObjectLogic thing : loadedThings) {
    //        thing.setEnvironment(env);
    // Actvates the Thing. Important, otherwise it will be not visible in the environment
    //        thingsRepository.create(thing);
    //    }
    // }

    // Loads the entire Reactions system (Trigger + Commands + Reactions)
    triggerRepository.loadTriggers(new File(Info.PATHS.PATH_DATA_FOLDER + "/trg/"));
    commandRepository.loadCommands(new File(Info.PATHS.PATH_DATA_FOLDER + "/cmd/"));
    reactionRepository.loadReactions(new File(Info.PATHS.PATH_DATA_FOLDER + "/rea/"));

    // Starting plugins
    for (Client plugin : clientStorage.getClients()) {
        String startupTime = plugin.getConfiguration().getStringProperty("startup-time", "undefined");

        if (startupTime.equalsIgnoreCase("on load")) {
            plugin.start();

            PluginHasChanged event = new PluginHasChanged(this, plugin.getName(), PluginActions.DESCRIPTION);
            busService.send(event);
        }
    }

    double MB = 1024 * 1024;
    Runtime runtime = Runtime.getRuntime();
    LOG.info("Used Memory:" + ((runtime.totalMemory() - runtime.freeMemory()) / MB));
    LOG.info("Freedomotic startup completed");
}

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

License:Open Source License

/**
 *
 * @param userName//from  ww  w  .j a  v  a  2s.  co m
 * @return
 */
@Override
public boolean bindFakeUser(String userName) {
    if (baseRealm.accountExists(userName)) {
        PrincipalCollection principals = new SimplePrincipalCollection(userName, BASE_REALM_NAME);
        Subject subj = new Subject.Builder().principals(principals).buildSubject();
        ThreadState threadState = new SubjectThreadState(subj);
        threadState.bind();
        return true;
    }
    return false;
}

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

License:Open Source License

/**
 *
 * @param userName/*from  w  w  w  .  j  a v  a2s  .co  m*/
 * @return
 */
@Override
public boolean bindFakeUser(String userName) {
    if (baseRealm.accountExists(userName)) {
        PrincipalCollection principals = new SimplePrincipalCollection(userName, UserRealm.USER_REALM_NAME);
        Subject subj = new Subject.Builder().principals(principals).buildSubject();
        ThreadState threadState = new SubjectThreadState(subj);
        threadState.bind();
        return true;
    }
    return false;
}

From source file:com.gemstone.gemfire.internal.security.GeodeSecurityUtil.java

License:Apache License

/**
 * this binds the passed-in subject to the executing thread, normally, you
 * would do this://from w  w  w  .j  a  va2 s .co m
 *
 * ThreadState state = null;
 * try{
 *   state = GeodeSecurityUtil.bindSubject(subject);
 *   //do the rest of the work as this subject
 * }
 * finally{
 *   if(state!=null)
 *      state.clear();
 * }
 */
public static ThreadState bindSubject(Subject subject) {
    if (subject == null) {
        return null;
    }

    ThreadState threadState = new SubjectThreadState(subject);
    threadState.bind();
    return threadState;
}

From source file:com.github.mizool.technology.web.MockitoExtensions.java

License:Apache License

public Subject mockSubject() {
    SecurityManager securityManager = mock(SecurityManager.class);
    SecurityUtils.setSecurityManager(securityManager);

    Subject subject = mock(Subject.class);
    SubjectThreadState subjectThreadState = new SubjectThreadState(subject);
    subjectThreadState.bind();//from w  w  w  . j  a v  a  2  s .c om
    return subject;
}

From source file:com.sonicle.webtop.core.app.servlet.DocEditor.java

License:Open Source License

@Override
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    WebTopApp wta = WebTopApp.get(request);

    ThreadState threadState = new SubjectThreadState(wta.getAdminSubject());
    threadState.bind();/*from   ww  w  .ja va2s.c o  m*/
    try {
        processRequestAsAdmin(request, response);
    } catch (Throwable t) {
        logger.error("Error fulfilling request", t);
        throw t;
    } finally {
        threadState.clear();
    }
}

From source file:com.sonicle.webtop.core.app.servlet.PublicRequest.java

License:Open Source License

@Override
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    WebTopApp wta = WebTopApp.get(request);
    WebTopSession wts = SessionContext.getCurrent(true);

    try {// w  w w  .  j  a va  2 s .c o m
        String serviceId = ServletUtils.getStringParameter(request, "service", null);

        String relativePath = null;
        if (serviceId != null) { // Checks if service ID is valid
            wts.initPublicEnvironment(request, serviceId);

        } else { // Retrieves public service ID using its public name
            String[] urlParts = splitPath(request.getPathInfo());
            serviceId = wta.getServiceManager().getServiceIdByPublicName(urlParts[1]);
            if (serviceId == null)
                throw new WTRuntimeException("Public name not known [{0}]", urlParts[1]);
            wts.initPublicEnvironment(request, serviceId);
            relativePath = urlParts[2];
        }

        // Returns direct stream if pathInfo points to a real file
        Resource resource = getPublicFile(wta, serviceId, relativePath);
        if (resource != null) {
            writeFile(request, response, resource);

        } else {
            String action = ServletUtils.getStringParameter(request, "action", false);
            Boolean nowriter = ServletUtils.getBooleanParameter(request, "nowriter", false);

            // Retrieves instantiated service
            BasePublicService instance = wts.getPublicServiceById(serviceId);

            // Gets method and invokes it...
            MethodInfo meinfo = getMethod(instance.getClass(), serviceId, action, nowriter);
            ThreadState threadState = new SubjectThreadState(wta.getAdminSubject());
            threadState.bind();
            try {
                invokeMethod(instance, meinfo, serviceId, request, response);
            } finally {
                threadState.clear();
            }
        }

    } catch (Exception ex) {
        logger.warn("Error processing publicService request", ex);
        throw new ServletException(ex.getMessage());
    }
}

From source file:com.sonicle.webtop.core.app.WebTopApp.java

License:Open Source License

void boot() {
    isStartingUp = true;//  w  ww  .j a va 2  s .c  o m
    ThreadState threadState = new SubjectThreadState(adminSubject);
    try {
        threadState.bind();
        internalInit();
        instance = this;
    } finally {
        threadState.clear();
        isStartingUp = false;
    }

    new Timer("onAppReady").schedule(new TimerTask() {
        @Override
        public void run() {
            ThreadState threadState = new SubjectThreadState(adminSubject);
            try {
                LoggerUtils.initDC();
                threadState.bind();
                onAppReady();
            } catch (InterruptedException ex) {
                // Do nothing...
            } finally {
                threadState.clear();
            }
        }
    }, 5000);
}