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


Java ThreadContext类代码示例

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


ThreadContext类属于org.apache.shiro.util包,在下文中一共展示了ThreadContext类的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: deleteBranch

import org.apache.shiro.util.ThreadContext; //导入依赖的package包/类
public void deleteBranch(String branch) {
  	String refName = GitUtils.branch2ref(branch);
  	ObjectId commitId = getObjectId(refName);
  	try {
	git().branchDelete().setForce(true).setBranchNames(branch).call();
} catch (Exception e) {
	Throwables.propagate(e);
}
  	
  	Subject subject = SecurityUtils.getSubject();
  	GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {

	@Override
	public void run() {
		ThreadContext.bind(subject);
		try {
			Project project = GitPlex.getInstance(ProjectManager.class).load(getId());
			GitPlex.getInstance(ListenerRegistry.class).post(
					new RefUpdated(project, refName, commitId, ObjectId.zeroId()));
		} finally {
			ThreadContext.unbindSubject();
		}
	}
  		
  	});
  }
 
开发者ID:jmfgdev,项目名称:gitplex-mit,代码行数:27,代码来源:Project.java

示例3: deleteTag

import org.apache.shiro.util.ThreadContext; //导入依赖的package包/类
public void deleteTag(String tag) {
  	String refName = GitUtils.tag2ref(tag);
  	ObjectId commitId = getRevCommit(refName).getId();
  	try {
	git().tagDelete().setTags(tag).call();
} catch (GitAPIException e) {
	throw new RuntimeException(e);
}
  	Subject subject = SecurityUtils.getSubject();
  	GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {

	@Override
	public void run() {
		ThreadContext.bind(subject);
		try {
			Project project = GitPlex.getInstance(ProjectManager.class).load(getId());
			GitPlex.getInstance(ListenerRegistry.class).post(
					new RefUpdated(project, refName, commitId, ObjectId.zeroId()));
		} finally {
			ThreadContext.unbindSubject();
		}
	}
  		
  	});
  }
 
开发者ID:jmfgdev,项目名称:gitplex-mit,代码行数:26,代码来源:Project.java

示例4: 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

示例5: login

import org.apache.shiro.util.ThreadContext; //导入依赖的package包/类
/**
 * @return null if security is not enabled, otherwise return a shiro subject
 */
public Subject login(Properties credentials) {
  if (!isIntegratedSecurity()) {
    return null;
  }

  if (credentials == null)
    return null;

  // this makes sure it starts with a clean user object
  ThreadContext.remove();

  Subject currentUser = SecurityUtils.getSubject();
  GeodeAuthenticationToken token = new GeodeAuthenticationToken(credentials);
  try {
    logger.info("Logging in " + token.getPrincipal());
    currentUser.login(token);
  } catch (ShiroException e) {
    logger.info(e.getMessage(), e);
    throw new AuthenticationFailedException(
        "Authentication error. Please check your credentials.", e);
  }

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

示例6: logout

import org.apache.shiro.util.ThreadContext; //导入依赖的package包/类
public void logout() {
  Subject currentUser = getSubject();
  if (currentUser == null) {
    return;
  }

  try {
    logger.info("Logging out " + currentUser.getPrincipal());
    currentUser.logout();
  } catch (ShiroException e) {
    logger.info(e.getMessage(), e);
    throw new GemFireSecurityException(e.getMessage(), e);
  }
  // clean out Shiro's thread local content
  ThreadContext.remove();
}
 
开发者ID:ampool,项目名称:monarch,代码行数:17,代码来源:IntegratedSecurityService.java

示例7: close

import org.apache.shiro.util.ThreadContext; //导入依赖的package包/类
public void close() {
  if (securityManager != null) {
    securityManager.close();
    securityManager = null;
  }

  if (postProcessor != null) {
    postProcessor.close();
    postProcessor = null;
  }
  ThreadContext.remove();
  SecurityUtils.setSecurityManager(null);
  isIntegratedSecurity = null;
  isClientAuthenticator = false;
  isPeerAuthenticator = false;
}
 
开发者ID:ampool,项目名称:monarch,代码行数:17,代码来源:IntegratedSecurityService.java

示例8: testFullStack_SecurityUtils

import org.apache.shiro.util.ThreadContext; //导入依赖的package包/类
@Test
public void testFullStack_SecurityUtils() {
    Realm mockRealm = mockRealm();

    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());
    });
}
 
开发者ID:bootique,项目名称:bootique-shiro,代码行数:19,代码来源:ShiroModuleIT.java

示例9: 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

示例10: doFilter

import org.apache.shiro.util.ThreadContext; //导入依赖的package包/类
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
	try {
		chain.doFilter(request, response);
	} finally {
		Map<Object, Object> resources = ThreadContext.getResources();
		if (resources != null) {
			for (Object key : resources.keySet()) {
				if (key != null && key instanceof String) {
					if (((String) key).startsWith(REMOVABLE_KEY_PREFIX)) {
						ThreadContext.remove(key);
					}
				}
			}
		}
	}
}
 
开发者ID:easycodebox,项目名称:easycode,代码行数:18,代码来源:ThreadContextFilter.java

示例11: SubjectThreadState

import org.apache.shiro.util.ThreadContext; //导入依赖的package包/类
/**
 * Creates a new {@code SubjectThreadState} that will bind and unbind the specified {@code Subject} to the
 * thread
 *
 * @param subject the {@code Subject} instance to bind and unbind from the {@link ThreadContext}.
 */
public SubjectThreadState(Subject subject) {
    if (subject == null) {
        throw new IllegalArgumentException("Subject argument cannot be null.");
    }
    this.subject = subject;

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

示例12: setAttribute

import org.apache.shiro.util.ThreadContext; //导入依赖的package包/类
@Override
public void setAttribute(SessionKey sessionKey, Object attributeKey, Object value) throws InvalidSessionException {
	try {
		super.setAttribute(sessionKey, attributeKey, value);
	} catch (UnknownSessionException e) {
		Subject subject = ThreadContext.getSubject();
		if ((value instanceof PrincipalCollection) && sessionDAO != null && subject != null
				&& (subject instanceof DelegatingSubject)) {
			try {
				SessionContext sessionContext = createSessionContext(((DelegatingSubject) subject).getHost());
				Session session = newSessionInstance(sessionContext);
				session.setAttribute(attributeKey, value);
				session.setTimeout(getGlobalSessionTimeout());
				((SimpleSession) session).setId(sessionKey.getSessionId());
				sessionDAO.create(session);
			} catch (Exception ex) {
				throw e;
			}
		} else {
			if (!(value instanceof SavedRequest)) {
				throw e;
			}
		}
	}
}
 
开发者ID:xuegongzi,项目名称:rabbitframework,代码行数:26,代码来源:SimpleSessionManager.java

示例13: doFilter

import org.apache.shiro.util.ThreadContext; //导入依赖的package包/类
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (isAuthenticated(request)) {
        logger.trace("Synchronize the Shiro subject bound to thread [" +
            Thread.currentThread().getId() +
            "] with the principal bound to request [" +
            request +
            "] ...");
        String message = new ContainerAuthenticationBridge().synchronizeShiroSubjectWithJEEPrincipal(request);
        if (message != null) {
            logger.info(message);
        }
    }
    try {
        chain.doFilter(request, response);
    } finally {
        logger.trace("Cleaning up the thread context (including the Shiro subject)");
        ThreadContext.remove();
    }
}
 
开发者ID:rvs-fluid-it,项目名称:shiro-jee-authc,代码行数:21,代码来源:ContainerAuthenticationFilter.java

示例14: 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

示例15: 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


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