/** * Convenience method that simplifies retrieval of a thread-bound Subject. If there is no * Subject bound to the thread, this method returns <tt>null</tt>. It is merely a convenient wrapper * for the following: * <p/> * <code>return (Subject)get( SUBJECT_KEY );</code> * <p/> * This method only returns the bound value if it exists - it does not remove it * from the thread. To remove it, one must call {@link #unbindSubject() unbindSubject()} instead. * * @return the Subject object bound to the thread, or <tt>null</tt> if there isn't one bound. * @since 0.2 */ public static Subject getSubject() { return (Subject) get(SUBJECT_KEY); }
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpservletRequest = (HttpServletRequest) servletRequest; URL requestURL = URI.create(httpservletRequest.getRequestURL().toString()).toURL(); String currentResourceURI = ((Request) httpservletRequest).getHttpURI().getPathQuery(); ThreadContext.put("currentResourceURI", currentResourceURI); ThreadContext.put("currentURLProtocol", requestURL.getProtocol()); ThreadContext.put("currentURLHost", requestURL.getHost()); ThreadContext.put("currentURLPort", requestURL.getPort()); filterChain.doFilter(servletRequest, servletResponse); ThreadContext.remove(); }
/** * Returns the object for the specified <code>key</code> that is bound to * the current thread. * * @param key the key that identifies the value to return * @return the object keyed by <code>key</code> or <code>null</code> if * no value exists for the specified <code>key</code> */ public static Object get(Object key) { if (log.isTraceEnabled()) { String msg = "get() - in thread [" + Thread.currentThread().getName() + "]"; log.trace(msg); } Object value = getValue(key); if ((value != null) && log.isTraceEnabled()) { String msg = "Retrieved value of type [" + value.getClass().getName() + "] for key [" + key + "] " + "bound to thread [" + Thread.currentThread().getName() + "]"; log.trace(msg); } return value; }
URI createdResourceURI = URI.create(resourceLocationUri); IResourceStore.IResourceId resourceId = RestUtilities.extractResourceId(createdResourceURI); Principal userPrincipal = SecurityUtilities.getPrincipal(ThreadContext.getSubject()); URI userURI = UserUtilities.getUserURI(userStore, userPrincipal); ResourceDescriptor resourceDescriptor = (ResourceDescriptor) descriptorStore.readDescriptor(resourceId.getId(), resourceId.getVersion() - 1); resourceDescriptor.setLastModifiedOn(new Date(System.currentTimeMillis())); resourceDescriptor.setLastModifiedBy(UserUtilities.getUserURI(userStore, SecurityUtilities.getPrincipal(ThreadContext.getSubject()))); resourceDescriptor.setResource(createNewVersionOfResource(resourceDescriptor.getResource(), resourceId.getVersion())); descriptorStore.updateDescriptor(resourceId.getId(), resourceId.getVersion() - 1, resourceDescriptor); String currentResourceURI = (String) ThreadContext.get("currentResourceURI"); IDescriptorStore descriptorStore = getDescriptorStore(currentResourceURI); IResourceStore.IResourceId resourceId = RestUtilities.extractResourceId(URI.create(currentResourceURI));
private Permissions getPermissions(String id) throws IResourceStore.ResourceStoreException, IResourceStore.ResourceNotFoundException { Permissions permissions = permissionStore.readPermissions(id); if (!RuntimeUtilities.isNullOrEmpty(ThreadContext.getSubject())) { PermissionUtilities.keepOwnPermissionsOnly(userStore, groupStore, permissions); } return permissions; }
/** * Convenience method that simplifies removal of the application's SecurityManager instance from the thread. * <p/> * The implementation just helps reduce casting and remembering of the ThreadContext key name, i.e it is * merely a conveient wrapper for the following: * <p/> * <code>return (SecurityManager)remove( SECURITY_MANAGER_KEY );</code> * <p/> * If you wish to just retrieve the object from the thread without removing it (so it can be retrieved later * during thread execution), use the {@link #getSecurityManager() getSecurityManager()} method instead. * * @return the application's SecurityManager instance previously bound to the thread, or <tt>null</tt> if there * was none bound. * @since 0.9 */ public static SecurityManager unbindSecurityManager() { return (SecurityManager) remove(SECURITY_MANAGER_KEY); }
@Override public <T> Future<T> submitCallable(final Callable<T> callable, final IFinishedExecution<T> callback, final Map<Object, Object> threadBindings) { return getExecutorService().submit(() -> { try { if (threadBindings != null) { ThreadContext.setResources(threadBindings); } final T result = callable.call(); callback.onComplete(result); return result; } catch (Throwable t) { log.error(t.getLocalizedMessage(), t); callback.onFailure(t); return null; } finally { ThreadContext.remove(); } }); }
/** * Convenience method that simplifies binding a Subject to the ThreadContext. * <p/> * <p>The method's existence is to help reduce casting in your own code and to simplify remembering of * ThreadContext key names. The implementation is simple in that, if the Subject is not <tt>null</tt>, * it binds it to the thread, i.e.: * <p/> * <pre> * if (subject != null) { * put( SUBJECT_KEY, subject ); * }</pre> * * @param subject the Subject object to bind to the thread. If the argument is null, nothing will be done. * @since 0.2 */ public static void bind(Subject subject) { if (subject != null) { put(SUBJECT_KEY, subject); } }
private void undeploy(Deployment.Environment environment, String botId, Integer version) { Callable<Void> undeployBot = () -> { try { botFactory.undeployBot(environment, botId, version); deploymentStore.setDeploymentInfo(environment.toString(), botId, version, DeploymentStatus.undeployed); } catch (ServiceException e) { throwError(botId, version, e, "Error while undeploying bot! (botId=%s , version=%s)"); } catch (IllegalAccessException e) { return throwErrorForbidden(botId, version, e); } catch (Exception e) { log.error(e.getLocalizedMessage(), e); throw new InternalServerErrorException(e.getLocalizedMessage(), e); } return null; }; SystemRuntime.getRuntime().submitCallable(undeployBot, ThreadContext.getResources()); }
@Override public UserIdentity login(String username, Object credentials, ServletRequest request) { try { Credential credential = Credential.getCredential((String) credentials); User user = lookupUser(username, credential); if (user != null) { UserIdentity userIdentity = createUserIdentity(username, credential); AbstractLoginService.UserPrincipal principal = (AbstractLoginService.UserPrincipal) userIdentity.getUserPrincipal(); if (principal.authenticate(credentials)) { bindUserDataToThread(user); ThreadContext.bind(userIdentity.getSubject()); return userIdentity; } } } catch (IResourceStore.ResourceStoreException e) { log.error("Could not process login.", e); } catch (IResourceStore.ResourceNotFoundException e) { //no user entity found for the given username } return null; }
public static void keepOwnPermissionsOnly(IUserStore userstore, IGroupStore groupStore, Permissions permissions) throws IResourceStore.ResourceStoreException, IResourceStore.ResourceNotFoundException { Subject subject = ThreadContext.getSubject(); if (subject != null) { String username = SecurityUtilities.getPrincipal(subject).getName(); URI currentUser = URI.create(IRestUserStore.resourceURI + userstore.searchUser(username)); AuthorizedSubjects authorizedSubjects; for (IAuthorization.Type type : IAuthorization.Type.values()) { authorizedSubjects = permissions.getPermissions().get(type); if (authorizedSubjects != null) { List<AuthorizedUser> authorizedUsers = PermissionUtilities.mergeAuthorizedSubjects(groupStore, authorizedSubjects); authorizedSubjects.getUsers().clear(); authorizedSubjects.getUsers().addAll(authorizedUsers); PermissionUtilities.filterAuthorizedSubjectsByUser(currentUser, authorizedSubjects.getUsers()); if ((authorizedSubjects.getUsers() == null || authorizedSubjects.getUsers().isEmpty()) && (authorizedSubjects.getGroups() == null || authorizedSubjects.getGroups().isEmpty())) { permissions.getPermissions().remove(type); } } } } }
/** * Convenience method that simplifies removal of a thread-local Subject from the thread. * <p/> * The implementation just helps reduce casting and remembering of the ThreadContext key name, i.e it is * merely a conveient wrapper for the following: * <p/> * <code>return (Subject)remove( SUBJECT_KEY );</code> * <p/> * If you wish to just retrieve the object from the thread without removing it (so it can be retrieved later during * thread execution), you should use the {@link #getSubject() getSubject()} method for that purpose. * * @return the Subject object previously bound to the thread, or <tt>null</tt> if there was none bound. * @since 0.2 */ public static Subject unbindSubject() { return (Subject) remove(SUBJECT_KEY); }
/** * Convenience method that simplifies binding the application's SecurityManager instance to the ThreadContext. * <p/> * <p>The method's existence is to help reduce casting in code and to simplify remembering of * ThreadContext key names. The implementation is simple in that, if the SecurityManager is not <tt>null</tt>, * it binds it to the thread, i.e.: * <p/> * <pre> * if (securityManager != null) { * put( SECURITY_MANAGER_KEY, securityManager); * }</pre> * * @param securityManager the application's SecurityManager instance to bind to the thread. If the argument is * null, nothing will be done. * @since 0.9 */ public static void bind(SecurityManager securityManager) { if (securityManager != null) { put(SECURITY_MANAGER_KEY, securityManager); } }
private void deploy(final Deployment.Environment environment, final String botId, final Integer version, final Boolean autoDeploy) { Callable<Void> deployBot = () -> { try { if (EnumSet.of(Status.NOT_FOUND, Status.ERROR).contains(checkDeploymentStatus(environment, botId, version))) { botFactory.deployBot(environment, botId, version, status -> { if (status == Status.READY && autoDeploy) { deploymentStore.setDeploymentInfo(environment.toString(), botId, version, DeploymentStatus.deployed); } }); } } catch (ServiceException e) { throwError(botId, version, e, "Error while deploying bot! (botId=%s , version=%s)"); } catch (IllegalAccessException e) { throwErrorForbidden(botId, version, e); } catch (Exception e) { log.error(e.getLocalizedMessage(), e); throw new InternalServerErrorException(e.getLocalizedMessage(), e); } return null; }; SystemRuntime.getRuntime().submitCallable(deployBot, ThreadContext.getResources()); }
@Override public Permissions readFilteredPermissions(String resourceId) throws IResourceStore.ResourceStoreException, IResourceStore.ResourceNotFoundException { Permissions permissions = readPermissions(resourceId); Principal principal = SecurityUtilities.getPrincipal(ThreadContext.getSubject()); URI userURI = UserUtilities.getUserURI(userStore, principal); if (!isUserAdministrator(permissions, userURI)) { PermissionUtilities.keepOwnPermissionsOnly(userStore, groupStore, permissions); } return permissions; }
/** * Convenience method that simplifies retrieval of the application's SecurityManager instance from the current * thread. If there is no SecurityManager bound to the thread (probably because framework code did not bind it * to the thread), this method returns <tt>null</tt>. * <p/> * It is merely a convenient wrapper for the following: * <p/> * <code>return (SecurityManager)get( SECURITY_MANAGER_KEY );</code> * <p/> * This method only returns the bound value if it exists - it does not remove it * from the thread. To remove it, one must call {@link #unbindSecurityManager() unbindSecurityManager()} instead. * * @return the Subject object bound to the thread, or <tt>null</tt> if there isn't one bound. * @since 0.9 */ public static SecurityManager getSecurityManager() { return (SecurityManager) get(SECURITY_MANAGER_KEY); }
/** * Binds <tt>value</tt> for the given <code>key</code> to the current thread. * <p/> * <p>A <tt>null</tt> <tt>value</tt> has the same effect as if <tt>remove</tt> was called for the given * <tt>key</tt>, i.e.: * <p/> * <pre> * if ( value == null ) { * remove( key ); * }</pre> * * @param key The key with which to identify the <code>value</code>. * @param value The value to bind to the thread. * @throws IllegalArgumentException if the <code>key</code> argument is <tt>null</tt>. */ public static void put(Object key, Object value) { if (key == null) { throw new IllegalArgumentException("key cannot be null"); } if (value == null) { remove(key); return; } resources.get().put(key, value); if (log.isTraceEnabled()) { String msg = "Bound value of type [" + value.getClass().getName() + "] for key [" + key + "] to thread " + "[" + Thread.currentThread().getName() + "]"; log.trace(msg); } }
private void bindUserDataToThread(User user) throws IResourceStore.ResourceStoreException, IResourceStore.ResourceNotFoundException { String username = user.getUsername(); ThreadContext.put("currentuser:userid", userStore.searchUser(username)); ThreadContext.put("currentuser:displayname", user.getDisplayName()); ThreadContext.put("currentuser:username", username); }
public void executeTestCase(final String id, final TestCase testCase) { SystemRuntime.getRuntime().submitCallable((Callable<Void>) () -> { try { testCaseStore.setTestCaseState(id, TestCaseState.IN_PROGRESS); if (!isBotDeployed(testCase.getBotId(), testCase.getBotVersion())) { deployBot(testCase.getBotId(), testCase.getBotVersion()); } ConversationMemorySnapshot actual = runTestCase(testCase.getBotId(), testCase); testCase.setActual(actual); testCase.setLastRun(new Date(System.currentTimeMillis())); testCase.setTestCaseState(testCase.getExpected().equals(testCase.getActual()) ? TestCaseState.SUCCESS : TestCaseState.FAILED); testCaseStore.storeTestCase(id, testCase); } catch (Exception e) { testCaseStore.setTestCaseState(id, TestCaseState.ERROR); throw e; } return null; }, ThreadContext.getResources()); }
permissionStore.createPermissions(respondedResourceId.getId(), PermissionUtilities.createDefaultPermissions(respondedResourceURI)); } else { Principal userPrincipal = SecurityUtilities.getPrincipal(ThreadContext.getSubject()); URI userURI = UserUtilities.getUserURI(userStore, userPrincipal); if (methodName.equals(METHOD_NAME_START_CONVERSATION)) {