refactor: Remove stats service (#20)

* refactor: Remove stats service

* fix: remove call to get stat
pull/1580/head
Dominik František Bučík 2021-09-01 13:56:53 +02:00 committed by GitHub
parent 37aea39cf6
commit d17c11c035
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 49 additions and 677 deletions

View File

@ -21,14 +21,6 @@
<li><a href="about" data-toggle="collapse" data-target=".nav-collapse"><spring:message code="topbar.about"/></a></li>
</c:otherwise>
</c:choose>
<c:choose>
<c:when test="${pageName == 'Statistics'}">
<li class="active" data-toggle="collapse" data-target=".nav-collapse"><a href=""><spring:message code="topbar.statistics"/></a></li>
</c:when>
<c:otherwise>
<li><a href="stats" data-toggle="collapse" data-target=".nav-collapse"><spring:message code="topbar.statistics"/></a></li>
</c:otherwise>
</c:choose>
<c:choose>
<c:when test="${pageName == 'Contact'}">
<li class="active" data-toggle="collapse" data-target=".nav-collapse"><a href=""><spring:message code="topbar.contact"/></a></li>

View File

@ -39,46 +39,8 @@
</div>
<hr>
<!-- Example row of columns -->
<div class="row-fluid">
<div class="span12">
<h2><spring:message code="home.statistics.title"/></h2>
<p id="statsloader" class="muted"><spring:message code="home.statistics.loading"/></p>
<p id="stats">
<spring:message code="home.statistics.number_users" arguments="?"/>
<spring:message code="home.statistics.number_clients" arguments="?"/>
<spring:message code="home.statistics.number_approvals" arguments="?"/>
</p>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
// load stats dynamically to make main page render faster
$(document).ready(function() {
$('#stats').hide();
var base = $('base').attr('href');
if (base.substr(-1) !== '/') {
base += '/';
}
$.getJSON(base + 'api/stats/summary', function(data) {
var stats = data;
$('#userCount').html(stats.userCount);
$('#clientCount').html(stats.clientCount);
$('#approvalCount').html(stats.approvalCount);
$('#statsloader').hide();
$('#stats').show();
});
});
</script>
<o:footer />

View File

@ -1,28 +0,0 @@
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="o" tagdir="/WEB-INF/tags"%>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!-- TODO: highlight proper section of topbar; what is the right way to do this? -->
<spring:message code="statistics.title" var="title"/>
<o:header title="${title}"/>
<o:topbar pageName="Statistics"/>
<div class="container-fluid main">
<div class="row-fluid">
<o:sidebar/>
<div class="span10">
<div class="hero-unit">
<h2><spring:message code="statistics.title"/></h2>
<p>
<spring:message code="statistics.number_users" arguments='${statsSummary["userCount"]}'/>
<spring:message code="statistics.number_clients" arguments='${statsSummary["clientCount"]}'/>
<spring:message code="statistics.number_approvals" arguments='${statsSummary["approvalCount"]}'/>
</p>
</div>
</div>
</div>
</div>
<o:footer/>

View File

@ -200,10 +200,6 @@ var RegistrationTokenModel = Backbone.Model.extend({
urlRoot: 'api/tokens/registration'
});
var ClientStatsModel = Backbone.Model.extend({
urlRoot: 'api/stats/byclientid'
});
var ClientCollection = Backbone.Collection.extend({
initialize: function() {
@ -303,7 +299,6 @@ var ClientView = Backbone.View.extend({
});
this.updateMatched();
this.updateStats();
$(this.el).i18n();
@ -312,12 +307,6 @@ var ClientView = Backbone.View.extend({
return this;
},
updateStats: function(eventName) {
$('.count', this.el).html(this.countTemplate({
count: this.options.clientStat.get('approvedSiteCount')
}));
},
showRegistrationToken: function(e) {
e.preventDefault();
@ -471,8 +460,6 @@ var ClientListView = Backbone.View.extend({
tagName: 'span',
stats: {},
initialize: function(options) {
this.options = options;
this.filteredModel = this.model;
@ -542,10 +529,8 @@ var ClientListView = Backbone.View.extend({
// togglePlaceholder)
_.each(this.filteredModel.models, function(client, index) {
var clientStat = this.getStat(client.get('clientId'));
var view = new ClientView({
model: client,
clientStat: clientStat,
systemScopeList: this.options.systemScopeList,
whiteList: this.options.whiteListList.getByClientId(client.get('clientId'))
});
@ -569,15 +554,6 @@ var ClientListView = Backbone.View.extend({
return this.views[index];
},
getStat: function(index) {
if (!this.stats[index]) {
this.stats[index] = new ClientStatsModel({
id: index
});
}
return this.stats[index];
},
togglePlaceholder: function() {
// set up pagination
var numPages = Math.ceil(this.filteredModel.length / 10);
@ -637,17 +613,6 @@ var ClientListView = Backbone.View.extend({
} else {
if (!view.isRendered) {
view.render();
var clientStat = view.options.clientStat;
// load and display the stats
$.when(clientStat.fetchIfNeeded({
success: function(e) {
},
error: app.errorHandlerView.handleError()
})).done(function(e) {
view.updateStats();
});
}
$(view.el).show();
}

View File

@ -17,17 +17,13 @@
*******************************************************************************/
package org.mitre.oauth2.service.impl;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Strings;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
@ -42,7 +38,6 @@ import org.mitre.openid.connect.config.ConfigurationPropertiesBean;
import org.mitre.openid.connect.model.WhitelistedSite;
import org.mitre.openid.connect.service.ApprovedSiteService;
import org.mitre.openid.connect.service.BlacklistedSiteService;
import org.mitre.openid.connect.service.StatsService;
import org.mitre.openid.connect.service.WhitelistedSiteService;
import org.mitre.uma.model.ResourceSet;
import org.mitre.uma.service.ResourceSetService;
@ -57,13 +52,16 @@ import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import com.google.common.base.Strings;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
@Service
public class DefaultOAuth2ClientDetailsEntityService implements ClientDetailsEntityService {
@ -91,9 +89,6 @@ public class DefaultOAuth2ClientDetailsEntityService implements ClientDetailsEnt
@Autowired
private SystemScopeService scopeService;
@Autowired
private StatsService statsService;
@Autowired
private ResourceSetService resourceSetService;
@ -142,14 +137,8 @@ public class DefaultOAuth2ClientDetailsEntityService implements ClientDetailsEnt
// check the sector URI
checkSectorIdentifierUri(client);
ensureNoReservedScopes(client);
ClientDetailsEntity c = clientRepository.saveClient(client);
statsService.resetCache();
return c;
return clientRepository.saveClient(client);
}
/**
@ -379,9 +368,6 @@ public class DefaultOAuth2ClientDetailsEntityService implements ClientDetailsEnt
// take care of the client itself
clientRepository.deleteClient(client);
statsService.resetCache();
}
/**

View File

@ -20,18 +20,11 @@
*/
package org.mitre.oauth2.web;
import static org.mitre.openid.connect.request.ConnectRequestParameters.PROMPT;
import static org.mitre.openid.connect.request.ConnectRequestParameters.PROMPT_SEPARATOR;
import java.net.URISyntaxException;
import java.security.Principal;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
import com.google.gson.JsonObject;
import org.apache.http.client.utils.URIBuilder;
import org.mitre.oauth2.model.ClientDetailsEntity;
import org.mitre.oauth2.model.SystemScope;
@ -39,7 +32,6 @@ import org.mitre.oauth2.service.ClientDetailsEntityService;
import org.mitre.oauth2.service.SystemScopeService;
import org.mitre.openid.connect.model.UserInfo;
import org.mitre.openid.connect.service.ScopeClaimTranslationService;
import org.mitre.openid.connect.service.StatsService;
import org.mitre.openid.connect.service.UserInfoService;
import org.mitre.openid.connect.view.HttpCodeView;
import org.slf4j.Logger;
@ -55,11 +47,16 @@ import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
import com.google.gson.JsonObject;
import java.net.URISyntaxException;
import java.security.Principal;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.mitre.openid.connect.request.ConnectRequestParameters.PROMPT;
import static org.mitre.openid.connect.request.ConnectRequestParameters.PROMPT_SEPARATOR;
/**
* @author jricher
@ -82,9 +79,6 @@ public class OAuthConfirmationController {
@Autowired
private UserInfoService userInfoService;
@Autowired
private StatsService statsService;
@Autowired
private RedirectResolver redirectResolver;
@ -201,25 +195,12 @@ public class OAuthConfirmationController {
model.put("claims", claimsForScopes);
// client stats
Integer count = statsService.getCountForClientId(client.getClientId()).getApprovedSiteCount();
model.put("count", count);
// contacts
if (client.getContacts() != null) {
String contacts = Joiner.on(", ").join(client.getContacts());
model.put("contacts", contacts);
}
// if the client is over a week old and has more than one registration, don't give such a big warning
// instead, tag as "Generally Recognized As Safe" (gras)
Date lastWeek = new Date(System.currentTimeMillis() - (60 * 60 * 24 * 7 * 1000));
if (count > 1 && client.getCreatedAt() != null && client.getCreatedAt().before(lastWeek)) {
model.put("gras", true);
} else {
model.put("gras", false);
}
model.put("gras", true);
return "approve";
}

View File

@ -1,34 +0,0 @@
/*******************************************************************************
* Copyright 2018 The MIT Internet Trust Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.mitre.openid.connect.model;
/**
* @author jricher
*/
public class ClientStat {
private Integer approvedSiteCount;
public Integer getApprovedSiteCount() {
return approvedSiteCount;
}
public void setApprovedSiteCount(Integer count) {
this.approvedSiteCount = count;
}
}

View File

@ -1,56 +0,0 @@
/*******************************************************************************
* Copyright 2018 The MIT Internet Trust Consortium
*
* Portions copyright 2011-2013 The MITRE Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/**
*
*/
package org.mitre.openid.connect.service;
import java.util.Map;
import org.mitre.openid.connect.model.ClientStat;
/**
* @author jricher
*
*/
public interface StatsService {
/**
* Calculate summary statistics
* approvalCount: total approved sites
* userCount: unique users
* clientCount: unique clients
*
* @return
*/
Map<String, Integer> getSummaryStats();
/**
* Calculate the usage count for a single client
*
* @param clientId the id of the client to search on
* @return
*/
ClientStat getCountForClientId(String clientId);
/**
* Trigger the stats to be recalculated upon next update.
*/
void resetCache();
}

View File

@ -17,17 +17,13 @@
*******************************************************************************/
package org.mitre.openid.connect.service.impl;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Set;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import org.mitre.oauth2.model.OAuth2AccessTokenEntity;
import org.mitre.oauth2.repository.OAuth2TokenRepository;
import org.mitre.openid.connect.model.ApprovedSite;
import org.mitre.openid.connect.repository.ApprovedSiteRepository;
import org.mitre.openid.connect.service.ApprovedSiteService;
import org.mitre.openid.connect.service.StatsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@ -35,8 +31,10 @@ import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Set;
/**
* Implementation of the ApprovedSiteService
@ -58,9 +56,6 @@ public class DefaultApprovedSiteService implements ApprovedSiteService {
@Autowired
private OAuth2TokenRepository tokenRepository;
@Autowired
private StatsService statsService;
@Override
public Collection<ApprovedSite> getAll() {
return approvedSiteRepository.getAll();
@ -69,9 +64,7 @@ public class DefaultApprovedSiteService implements ApprovedSiteService {
@Override
@Transactional(value="defaultTransactionManager")
public ApprovedSite save(ApprovedSite approvedSite) {
ApprovedSite a = approvedSiteRepository.save(approvedSite);
statsService.resetCache();
return a;
return approvedSiteRepository.save(approvedSite);
}
@Override
@ -94,8 +87,6 @@ public class DefaultApprovedSiteService implements ApprovedSiteService {
}
approvedSiteRepository.remove(approvedSite);
statsService.resetCache();
}
@Override

View File

@ -1,111 +0,0 @@
/*******************************************************************************
* Copyright 2018 The MIT Internet Trust Consortium
*
* Portions copyright 2011-2013 The MITRE Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/**
*
*/
package org.mitre.openid.connect.service.impl;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.mitre.openid.connect.model.ApprovedSite;
import org.mitre.openid.connect.model.ClientStat;
import org.mitre.openid.connect.service.ApprovedSiteService;
import org.mitre.openid.connect.service.StatsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
/**
* @author jricher
*
*/
@Service
public class DefaultStatsService implements StatsService {
@Autowired
private ApprovedSiteService approvedSiteService;
// stats cache
private Supplier<Map<String, Integer>> summaryCache = createSummaryCache();
private Supplier<Map<String, Integer>> createSummaryCache() {
return Suppliers.memoizeWithExpiration(new Supplier<Map<String, Integer>>() {
@Override
public Map<String, Integer> get() {
return computeSummaryStats();
}
}, 10, TimeUnit.MINUTES);
}
@Override
public Map<String, Integer> getSummaryStats() {
return summaryCache.get();
}
// do the actual computation
private Map<String, Integer> computeSummaryStats() {
// get all approved sites
Collection<ApprovedSite> allSites = approvedSiteService.getAll();
// process to find number of unique users and sites
Set<String> userIds = new HashSet<>();
Set<String> clientIds = new HashSet<>();
for (ApprovedSite approvedSite : allSites) {
userIds.add(approvedSite.getUserId());
clientIds.add(approvedSite.getClientId());
}
Map<String, Integer> e = new HashMap<>();
e.put("approvalCount", allSites.size());
e.put("userCount", userIds.size());
e.put("clientCount", clientIds.size());
return e;
}
/* (non-Javadoc)
* @see org.mitre.openid.connect.service.StatsService#countForClientId(java.lang.String)
*/
@Override
public ClientStat getCountForClientId(String clientId) {
Collection<ApprovedSite> approvedSites = approvedSiteService.getByClientId(clientId);
ClientStat stat = new ClientStat();
stat.setApprovedSiteCount(approvedSites.size());
return stat;
}
/**
* Reset both stats caches on a trigger (before the timer runs out). Resets the timers.
*/
@Override
public void resetCache() {
summaryCache = createSummaryCache();
}
}

View File

@ -17,10 +17,6 @@
*******************************************************************************/
package org.mitre.openid.connect.web;
import java.util.Map;
import org.mitre.openid.connect.service.StatsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
@ -35,9 +31,6 @@ public class RootController {
public static final String API_URL = "api";
@Autowired
private StatsService statsService;
@RequestMapping({"", "home", "index"})
public String showHomePage(ModelMap m) {
return "home";
@ -48,14 +41,6 @@ public class RootController {
return "about";
}
@RequestMapping({"stats", "stats/"})
public String showStatsPage(ModelMap m) {
Map<String, Integer> summary = statsService.getSummaryStats();
m.put("statsSummary", summary);
return "stats";
}
@RequestMapping({"contact", "contact/"})
public String showContactPage(ModelMap m) {
return "contact";
@ -67,12 +52,4 @@ public class RootController {
return "manage";
}
public StatsService getStatsService() {
return statsService;
}
public void setStatsService(StatsService statsService) {
this.statsService = statsService;
}
}

View File

@ -1,78 +0,0 @@
/*******************************************************************************
* Copyright 2018 The MIT Internet Trust Consortium
*
* Portions copyright 2011-2013 The MITRE Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.mitre.openid.connect.web;
import java.util.Map;
import org.mitre.openid.connect.model.ClientStat;
import org.mitre.openid.connect.service.StatsService;
import org.mitre.openid.connect.view.JsonEntityView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/" + StatsAPI.URL)
public class StatsAPI {
public static final String URL = RootController.API_URL + "/stats";
// Logger for this class
private static final Logger logger = LoggerFactory.getLogger(StatsAPI.class);
@Autowired
private StatsService statsService;
@RequestMapping(value = "summary", produces = MediaType.APPLICATION_JSON_VALUE)
public String statsSummary(ModelMap m) {
Map<String, Integer> e = statsService.getSummaryStats();
m.put(JsonEntityView.ENTITY, e);
return JsonEntityView.VIEWNAME;
}
// @PreAuthorize("hasRole('ROLE_USER')")
// @RequestMapping(value = "byclientid", produces = MediaType.APPLICATION_JSON_VALUE)
// public String statsByClient(ModelMap m) {
// Map<Long, Integer> e = statsService.getByClientId();
//
// m.put(JsonEntityView.ENTITY, e);
//
// return JsonEntityView.VIEWNAME;
// }
//
@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping(value = "byclientid/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public String statsByClientId(@PathVariable("id") String clientId, ModelMap m) {
ClientStat e = statsService.getCountForClientId(clientId);
m.put(JsonEntityView.ENTITY, e);
return JsonEntityView.VIEWNAME;
}
}

View File

@ -30,13 +30,12 @@ import org.mitre.openid.connect.config.ConfigurationPropertiesBean;
import org.mitre.openid.connect.model.WhitelistedSite;
import org.mitre.openid.connect.service.ApprovedSiteService;
import org.mitre.openid.connect.service.BlacklistedSiteService;
import org.mitre.openid.connect.service.StatsService;
import org.mitre.openid.connect.service.WhitelistedSiteService;
import org.mitre.uma.model.ResourceSet;
import org.mitre.uma.service.ResourceSetService;
import org.mockito.AdditionalAnswers;
import org.mockito.InjectMocks;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
@ -83,9 +82,6 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
@Mock
private ResourceSetService resourceSetService;
@Mock
private StatsService statsService;
@Mock
private ConfigurationPropertiesBean config;
@ -94,7 +90,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
@Before
public void prepare() {
Mockito.reset(clientRepository, tokenRepository, approvedSiteService, whitelistedSiteService, blacklistedSiteService, scopeService, statsService);
Mockito.reset(clientRepository, tokenRepository, approvedSiteService, whitelistedSiteService, blacklistedSiteService, scopeService);
Mockito.when(clientRepository.saveClient(ArgumentMatchers.any(ClientDetailsEntity.class))).thenAnswer(new Answer<ClientDetailsEntity>() {
@Override

View File

@ -17,12 +17,8 @@
*******************************************************************************/
package org.mitre.openid.connect.service.impl;
import static org.mockito.Matchers.any;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -32,16 +28,16 @@ import org.mitre.oauth2.repository.OAuth2TokenRepository;
import org.mitre.openid.connect.model.ApprovedSite;
import org.mitre.openid.connect.repository.ApprovedSiteRepository;
import org.mitre.openid.connect.service.ApprovedSiteService;
import org.mitre.openid.connect.service.StatsService;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.test.annotation.Rollback;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import java.util.List;
import java.util.Set;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
@ -61,9 +57,6 @@ public class TestDefaultApprovedSiteService {
@Mock
private OAuth2TokenRepository tokenRepository;
@Mock
private StatsService statsService;
@InjectMocks
private ApprovedSiteService service = new DefaultApprovedSiteService();
@ -93,7 +86,7 @@ public class TestDefaultApprovedSiteService {
site3.setUserId("user2");
site3.setClientId(clientId);
Mockito.reset(repository, statsService);
Mockito.reset(repository);
}

View File

@ -1,164 +0,0 @@
/*******************************************************************************
* Copyright 2018 The MIT Internet Trust Consortium
*
* Portions copyright 2011-2013 The MITRE Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.mitre.openid.connect.service.impl;
import java.util.HashSet;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mitre.oauth2.model.ClientDetailsEntity;
import org.mitre.openid.connect.model.ApprovedSite;
import org.mitre.openid.connect.service.ApprovedSiteService;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import com.google.common.collect.Sets;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* @author wkim
*
*/
@RunWith(MockitoJUnitRunner.class)
public class TestDefaultStatsService {
// Test fixtures:
// Currently tests 4 approved sites with a total of 2 users and 3 clients for those sites.
// There is an extra client in the system to make sure the stats only count for approved sites.
private String userId1 = "batman";
private String userId2 = "alfred";
private String clientId1 = "bar";
private String clientId2 = "pawnshop";
private String clientId3 = "pizzastore";
private String clientId4 = "gasstation";
private ApprovedSite ap1 = Mockito.mock(ApprovedSite.class);
private ApprovedSite ap2 = Mockito.mock(ApprovedSite.class);
private ApprovedSite ap3 = Mockito.mock(ApprovedSite.class);
private ApprovedSite ap4 = Mockito.mock(ApprovedSite.class);
private ApprovedSite ap5 = Mockito.mock(ApprovedSite.class);
private ApprovedSite ap6 = Mockito.mock(ApprovedSite.class);
@Mock
private ApprovedSiteService approvedSiteService;
@InjectMocks
private DefaultStatsService service = new DefaultStatsService();
/**
* Prepares a collection of ApprovedSite mocks to be returned from the approvedSiteService
* and a collection of ClientDetailEntity mocks to be returned from the clientService.
*/
@Before
public void prepare() {
Mockito.reset(approvedSiteService);
Mockito.when(ap1.getUserId()).thenReturn(userId1);
Mockito.when(ap1.getClientId()).thenReturn(clientId1);
Mockito.when(ap2.getUserId()).thenReturn(userId1);
Mockito.when(ap2.getClientId()).thenReturn(clientId1);
Mockito.when(ap3.getUserId()).thenReturn(userId2);
Mockito.when(ap3.getClientId()).thenReturn(clientId2);
Mockito.when(ap4.getUserId()).thenReturn(userId2);
Mockito.when(ap4.getClientId()).thenReturn(clientId3);
Mockito.when(ap5.getUserId()).thenReturn(userId2);
Mockito.when(ap5.getClientId()).thenReturn(clientId1);
Mockito.when(ap6.getUserId()).thenReturn(userId1);
Mockito.when(ap6.getClientId()).thenReturn(clientId4);
Mockito.when(approvedSiteService.getAll()).thenReturn(Sets.newHashSet(ap1, ap2, ap3, ap4));
Mockito.when(approvedSiteService.getByClientId(clientId1)).thenReturn(Sets.newHashSet(ap1, ap2));
Mockito.when(approvedSiteService.getByClientId(clientId2)).thenReturn(Sets.newHashSet(ap3));
Mockito.when(approvedSiteService.getByClientId(clientId3)).thenReturn(Sets.newHashSet(ap4));
Mockito.when(approvedSiteService.getByClientId(clientId4)).thenReturn(Sets.newHashSet());
}
@Test
public void calculateSummaryStats_empty() {
Mockito.when(approvedSiteService.getAll()).thenReturn(new HashSet<ApprovedSite>());
Map<String, Integer> stats = service.getSummaryStats();
assertThat(stats.get("approvalCount"), is(0));
assertThat(stats.get("userCount"), is(0));
assertThat(stats.get("clientCount"), is(0));
}
@Test
public void calculateSummaryStats() {
Map<String, Integer> stats = service.getSummaryStats();
assertThat(stats.get("approvalCount"), is(4));
assertThat(stats.get("userCount"), is(2));
assertThat(stats.get("clientCount"), is(3));
}
@Test
public void countForClientId() {
// stats for ap1..ap4
assertThat(service.getCountForClientId(clientId1).getApprovedSiteCount(), is(2));
assertThat(service.getCountForClientId(clientId2).getApprovedSiteCount(), is(1));
assertThat(service.getCountForClientId(clientId3).getApprovedSiteCount(), is(1));
assertThat(service.getCountForClientId(clientId4).getApprovedSiteCount(), is(0));
}
@Test
public void cacheAndReset() {
Map<String, Integer> stats = service.getSummaryStats();
assertThat(stats.get("approvalCount"), is(4));
assertThat(stats.get("userCount"), is(2));
assertThat(stats.get("clientCount"), is(3));
Mockito.when(approvedSiteService.getAll()).thenReturn(Sets.newHashSet(ap1, ap2, ap3, ap4, ap5, ap6));
Map<String, Integer> stats2 = service.getSummaryStats();
// cache should remain the same due to memoized functions
assertThat(stats2.get("approvalCount"), is(4));
assertThat(stats2.get("userCount"), is(2));
assertThat(stats2.get("clientCount"), is(3));
// reset the cache and make sure the count goes up
service.resetCache();
Map<String, Integer> stats3 = service.getSummaryStats();
assertThat(stats3.get("approvalCount"), is(6));
assertThat(stats3.get("userCount"), is(2));
assertThat(stats3.get("clientCount"), is(4));
}
}