当前位置: 首页>>代码示例>>Java>>正文


Java ThreadContext.bind方法代码示例

本文整理汇总了Java中org.apache.shiro.util.ThreadContext.bind方法的典型用法代码示例。如果您正苦于以下问题:Java ThreadContext.bind方法的具体用法?Java ThreadContext.bind怎么用?Java ThreadContext.bind使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.apache.shiro.util.ThreadContext的用法示例。


在下文中一共展示了ThreadContext.bind方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: newCheckStatusRunnable

import org.apache.shiro.util.ThreadContext; //导入方法依赖的package包/类
private Runnable newCheckStatusRunnable(Long requestId, Subject subject) {
	return new Runnable() {
		
		@Override
		public void run() {
			try {
		        ThreadContext.bind(subject);
				check(load(requestId));
			} catch (Exception e) {
				logger.error("Error checking pull request status", e);
			} finally {
				ThreadContext.unbindSubject();
			}
		}

	};		
}
 
开发者ID:jmfgdev,项目名称:gitplex-mit,代码行数:18,代码来源:DefaultPullRequestManager.java

示例2: start

import org.apache.shiro.util.ThreadContext; //导入方法依赖的package包/类
@Override
public void start() {
	jettyRunner.start();
	
	if (Bootstrap.command == null) {
		taskScheduler.start();
	}
	
	persistManager.start();
	
	List<ManualConfig> manualConfigs = dataManager.init();
	if (!manualConfigs.isEmpty()) {
		logger.warn("Please set up the server at " + guessServerUrl());
		initStage = new InitStage("Server Setup", manualConfigs);
		
		initStage.waitForFinish();
	}

	unitOfWork.begin();
	try {
		ThreadContext.bind(userManager.getRoot().asSubject());
		listenerRegistry.post(new SystemStarting());
	} finally {
		unitOfWork.end();
	}
}
 
开发者ID:jmfgdev,项目名称:gitplex-mit,代码行数:27,代码来源:GitPlex.java

示例3: filter

import org.apache.shiro.util.ThreadContext; //导入方法依赖的package包/类
@Override
public ContainerRequest filter(ContainerRequest request) {
    Subject subject = new Subject.Builder(_securityManager).buildSubject();
    ThreadContext.bind(subject);

    AuthenticationToken token = _tokenGenerator.createToken(request);
    if (token == null) {
        token = AnonymousToken.getInstance();
    }
    subject.login(token);

    // The user has been successfully logged in.  Update the container authentication.
    setJettyAuthentication(subject);

    return request;
}
 
开发者ID:bazaarvoice,项目名称:emodb,代码行数:17,代码来源:AuthenticationResourceFilter.java

示例4: preHandle

import org.apache.shiro.util.ThreadContext; //导入方法依赖的package包/类
@Override
protected boolean preHandle(final ServletRequest request, final ServletResponse response) throws Exception {
  Subject subject = SecurityUtils.getSubject();
  AnonymousManager manager = anonymousManager.get();
 
  if (subject.getPrincipal() == null && manager.isEnabled()) {
    request.setAttribute(ORIGINAL_SUBJECT, subject);
    subject = manager.buildSubject();
    ThreadContext.bind(subject);
    log.trace("Bound anonymous subject: {}", subject);
    
    // fire an event if we haven't already seen this ClientInfo since the server started
    if (request instanceof HttpServletRequest) {
      String userId = manager.getConfiguration().getUserId();
      ClientInfo clientInfo = new ClientInfo(userId, request.getRemoteAddr(),
          ((HttpServletRequest) request).getHeader(HttpHeaders.USER_AGENT));
      if(!cache.contains(clientInfo)) {
        log.trace("Tracking new anonymous access from: {}", clientInfo);
        eventManager.get().post(new AnonymousAccessEvent(clientInfo, new Date()));
        cache.add(clientInfo);
      }
    }
  }

  return true;
}
 
开发者ID:sonatype,项目名称:nexus-public,代码行数:27,代码来源:AnonymousFilter.java

示例5: createSession

import org.apache.shiro.util.ThreadContext; //导入方法依赖的package包/类
@POST
@Path("/sessions")
public Response createSession(@SuppressWarnings("TypeMayBeWeakened") @Context HttpServletRequest servletRequest,
    @FormParam("username") String username, @FormParam("password") String password) {
  try {
    Subject subject = SecurityUtils.getSubject();
    subject.login(new UsernamePasswordToken(username, password));
    ThreadContext.bind(subject);
    String sessionId = SecurityUtils.getSubject().getSession().getId().toString();

    userService.updateUserLastLogin(username);

    log.info("Successful session creation for user '{}' session ID is '{}'.", username, sessionId);
    return Response.created(
        UriBuilder.fromPath(JerseyConfiguration.WS_ROOT).path(SessionResource.class).build(sessionId))
        .build();

  } catch(AuthenticationException e) {
    log.info("Authentication failure of user '{}' at ip: '{}': {}", username, servletRequest.getRemoteAddr(),
        e.getMessage());
    // When a request contains credentials and they are invalid, the a 403 (Forbidden) should be returned.
    return Response.status(Response.Status.FORBIDDEN).cookie().build();
  }
}
 
开发者ID:obiba,项目名称:agate,代码行数:25,代码来源:SessionsResource.java

示例6: bind

import org.apache.shiro.util.ThreadContext; //导入方法依赖的package包/类
@Override
public void bind(final Session session) throws AuthException {
	if (session == null) {
		exceptionRegistry.throwRuntimeException(AuthException.class, 1000);
	} else {

		// check if there is a subject known
		final Subject subject = session.get("subject");

		// if not create one and bind it, ...
		if (subject == null) {
			session.bind("subject", getSubject());
		}
		// otherwise bind it now
		else {
			ThreadContext.bind(manager);
			ThreadContext.bind(subject);
		}
	}
}
 
开发者ID:pmeisen,项目名称:dis-timeintervaldataanalyzer,代码行数:21,代码来源:ShiroAuthManager.java

示例7: run

import org.apache.shiro.util.ThreadContext; //导入方法依赖的package包/类
private void run(Runnable runnable) {
	UnitOfWork unitOfWork = AppLoader.getInstance(UnitOfWork.class);
	unitOfWork.begin();
	try {
		Subject subject = (Subject) request.getHttpServletRequest().getAttribute(WebSocketFilter.SHIRO_SUBJECT);
        ThreadContext.bind(subject);

        runnable.run();
	} finally {
		ThreadContext.unbindSubject();
		unitOfWork.end();
	}
}
 
开发者ID:jmfgdev,项目名称:gitplex-mit,代码行数:14,代码来源:WebSocketProcessor.java

示例8: getSubject

import org.apache.shiro.util.ThreadContext; //导入方法依赖的package包/类
/**
 * It first looks the shiro subject in AccessControlContext since JMX will use multiple threads to
 * process operations from the same client, then it looks into Shiro's thead context.
 *
 * @return the shiro subject, null if security is not enabled
 */
public Subject getSubject() {
  if (!isIntegratedSecurity()) {
    return null;
  }

  Subject currentUser = null;

  // First try get the principal out of AccessControlContext instead of Shiro's Thread context
  // since threads can be shared between JMX clients.
  javax.security.auth.Subject jmxSubject =
      javax.security.auth.Subject.getSubject(AccessController.getContext());

  if (jmxSubject != null) {
    Set<ShiroPrincipal> principals = jmxSubject.getPrincipals(ShiroPrincipal.class);
    if (principals.size() > 0) {
      ShiroPrincipal principal = principals.iterator().next();
      currentUser = principal.getSubject();
      ThreadContext.bind(currentUser);
      return currentUser;
    }
  }

  // in other cases like rest call, client operations, we get it from the current thread
  currentUser = SecurityUtils.getSubject();

  if (currentUser == null || currentUser.getPrincipal() == null) {
    throw new GemFireSecurityException("Error: Anonymous User");
  }

  return currentUser;
}
 
开发者ID:ampool,项目名称:monarch,代码行数:38,代码来源:IntegratedSecurityService.java

示例9: bind

import org.apache.shiro.util.ThreadContext; //导入方法依赖的package包/类
/**
 * Binds a {@link Subject} and {@link org.apache.shiro.mgt.SecurityManager SecurityManager} to the
 * {@link ThreadContext} so they can be retrieved later by any
 * {@code SecurityUtils.}{@link org.apache.shiro.SecurityUtils#getSubject() getSubject()} calls that might occur
 * during the thread's execution.
 * <p/>
 * Prior to binding, the {@code ThreadContext}'s existing {@link ThreadContext#getResources() resources} are
 * retained so they can be restored later via the {@link #restore restore} call.
 */
public void bind() {
    SecurityManager securityManager = this.securityManager;
    if ( securityManager == null ) {
        //try just in case the constructor didn't find one at the time:
        securityManager = ThreadContext.getSecurityManager();
    }
    this.originalResources = ThreadContext.getResources();
    ThreadContext.remove();

    ThreadContext.bind(this.subject);
    if (securityManager != null) {
        ThreadContext.bind(securityManager);
    }
}
 
开发者ID:xuegongzi,项目名称:rabbitframework,代码行数:24,代码来源:SubjectThreadState.java

示例10: activateService

import org.apache.shiro.util.ThreadContext; //导入方法依赖的package包/类
@Override
public void activateService()
        throws Exception
{
    configuration.refresh();
    ShiroIniConfiguration config = configuration.get();

    String iniResourcePath = config.iniResourcePath().get() == null
                             ? Shiro.DEFAULT_INI_RESOURCE_PATH
                             : config.iniResourcePath().get();

    setIni( Ini.fromResourcePath( iniResourcePath ) );
    securityManager = getInstance();

    if ( realmsRefs != null && realmsRefs.iterator().hasNext() ) {

        // Register Realms Services
        RealmSecurityManager realmSecurityManager = ( RealmSecurityManager ) securityManager;
        Collection<Realm> iniRealms = new ArrayList<>( realmSecurityManager.getRealms() );
        for ( ServiceReference<Realm> realmRef : realmsRefs ) {
            iniRealms.add( realmRef.get() );
            LOG.debug( "Realm Service '{}' registered!", realmRef.identity() );
        }
        realmSecurityManager.setRealms( iniRealms );

    }

    ThreadContext.bind( securityManager );
}
 
开发者ID:apache,项目名称:polygene-java,代码行数:30,代码来源:IniSecurityManagerService.java

示例11: setUp

import org.apache.shiro.util.ThreadContext; //导入方法依赖的package包/类
@Before
public void setUp() throws Exception {
  when(subject.getPrincipal()).thenReturn("admin");
  when(subject.associateWith(any(Runnable.class)))
      .thenAnswer(invoc -> new SubjectRunnable(subject, (Runnable) invoc.getArguments()[0]));
  ThreadContext.bind(subject);

  cacheRemovalListener = new CacheRemovalListener(database.getInstanceProvider(), assetDownloadCountEntityAdapter);
  underTest = new AssetDownloadCountStoreImpl(database.getInstanceProvider(), true, 10, 10,
      assetDownloadCountEntityAdapter, dataCleaner, cacheRemovalListener);
  underTest.start();
}
 
开发者ID:sonatype,项目名称:nexus-public,代码行数:13,代码来源:AssetDownloadCountStoreImplTest.java

示例12: setUp

import org.apache.shiro.util.ThreadContext; //导入方法依赖的package包/类
@Before
public void setUp() throws Exception {
  when(subject.getPrincipal()).thenReturn("admin");
  when(subject.associateWith(any(Runnable.class)))
      .thenAnswer(invoc -> new SubjectRunnable(subject, (Runnable) invoc.getArguments()[0]));
  ThreadContext.bind(subject);

  when(assetDownloadCountEntityAdapter.getMaxDeleteSize()).thenReturn(1000);

  underTest = new AssetDownloadHistoricDataCleaner(database.getInstanceProvider(), assetDownloadCountEntityAdapter,
      5000);
}
 
开发者ID:sonatype,项目名称:nexus-public,代码行数:13,代码来源:AssetDownloadHistoricDataCleanerTest.java

示例13: init

import org.apache.shiro.util.ThreadContext; //导入方法依赖的package包/类
/**
 * @see org.apache.wicket.Application#init()
 */
@Override
public void init() {
	super.init();

	String version = "0.0.17";
	System.setProperty("MyOpenTraderWebVersion", version);

	// Check the properties
	PropertiesFactory pf = PropertiesFactory.getInstance();
	ServletContext context = this.getServletContext();
	String configDir = pf.getConfigDir();

	// If the configDir is already set, use this one otherwise get the
	// context
	if (configDir == null) {
		configDir = context.getRealPath("/WEB-INF/conf");
		pf.setConfigDir(configDir);
	}

	System.out.println("*** STARTING NEW MYOPENTRADER WEB INSTANCE ***");
	System.out.println("Using Config directory: " + configDir);
	System.out.println("Using context path: " + context.getContextPath());
	System.out.println("**********");

	// Configure the log4j properties
	PropertyConfigurator.configure(pf.getConfigDir() + "/log4j.properties");

	// The following lines ensure that the context is set for SHIRO. If not,
	// the securityFactory will not get a subject
	WebEnvironment wm = WebUtils.getRequiredWebEnvironment(context);
	WebSecurityManager wsm = wm.getWebSecurityManager();
	ThreadContext.bind(wsm);

}
 
开发者ID:sgrotz,项目名称:myopentrader,代码行数:38,代码来源:MyOpenTraderWeb.java

示例14: set_notSet

import org.apache.shiro.util.ThreadContext; //导入方法依赖的package包/类
@Test
public void set_notSet() {
  ThreadContext.bind(subject("test"));

  UserIdMdcHelper.set();

  assertThat(UserIdMdcHelper.isSet(), is(true));
  assertThat(MDC.get(KEY), is("test"));
}
 
开发者ID:sonatype,项目名称:nexus-public,代码行数:10,代码来源:UserIdMdcHelperTest.java

示例15: set_notSet_withoutSubject

import org.apache.shiro.util.ThreadContext; //导入方法依赖的package包/类
@Test
public void set_notSet_withoutSubject() {
  ThreadContext.bind(mock(SecurityManager.class));

  UserIdMdcHelper.set();

  assertThat(UserIdMdcHelper.isSet(), is(false));
  assertThat(MDC.get(KEY), is(UNKNOWN));
}
 
开发者ID:sonatype,项目名称:nexus-public,代码行数:10,代码来源:UserIdMdcHelperTest.java


注:本文中的org.apache.shiro.util.ThreadContext.bind方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。