@Override
	public Map<String, Object> assembleFrom(OAuth2AccessTokenEntity accessToken, UserInfo userInfo, Set<String> authScopes) {

		Map<String, Object> result = newLinkedHashMap();
		OAuth2Authentication authentication = accessToken.getAuthenticationHolder().getAuthentication();

		result.put(ACTIVE, true);

		if (accessToken.getPermissions() != null && !accessToken.getPermissions().isEmpty()) {

			Set<Object> permissions = Sets.newHashSet();

			for (Permission perm : accessToken.getPermissions()) {
				Map<String, Object> o = newLinkedHashMap();
				o.put("resource_set_id", perm.getResourceSet().getId().toString());
				Set<String> scopes = Sets.newHashSet(perm.getScopes());
				o.put("scopes", scopes);
				permissions.add(o);
			}

			result.put("permissions", permissions);

		} else {
			Set<String> scopes = Sets.intersection(authScopes, accessToken.getScope());

			result.put(SCOPE, Joiner.on(SCOPE_SEPARATOR).join(scopes));

		}

		if (accessToken.getExpiration() != null) {
			try {
				result.put(EXPIRES_AT, dateFormat.valueToString(accessToken.getExpiration()));
				result.put(EXP, accessToken.getExpiration().getTime() / 1000L);
			} catch (ParseException e) {
				logger.error("Parse exception in token introspection", e);
			}
		}

		if (userInfo != null) {
			// if we have a UserInfo, use that for the subject
			result.put(SUB, userInfo.getSub());
		} else {
			// otherwise, use the authentication's username
			result.put(SUB, authentication.getName());
		}

		if(authentication.getUserAuthentication() != null) {
			result.put(USER_ID, authentication.getUserAuthentication().getName());
		}

		result.put(CLIENT_ID, authentication.getOAuth2Request().getClientId());

		result.put(TOKEN_TYPE, accessToken.getTokenType());

		return result;
	}
@Test
	public void shouldAssembleExpectedResultForRefreshToken() throws ParseException {

		// given
		OAuth2RefreshTokenEntity refreshToken = refreshToken(new Date(123 * 1000L),
				oauth2AuthenticationWithUser(oauth2Request("clientId", scopes("foo", "bar")), "name"));

		UserInfo userInfo = userInfo("sub");

		Set<String> authScopes = scopes("foo", "bar", "baz");

		// when
		Map<String, Object> result = assembler.assembleFrom(refreshToken, userInfo, authScopes);


		// then
		Map<String, Object> expected = new ImmutableMap.Builder<String, Object>()
				.put("sub", "sub")
				.put("exp", 123L)
				.put("expires_at", dateFormat.valueToString(new Date(123 * 1000L)))
				.put("scope", "bar foo")
				.put("active", Boolean.TRUE)
				.put("user_id", "name")
				.put("client_id", "clientId")
				.build();
		assertThat(result, is(equalTo(expected)));
	}