2121import lombok .AllArgsConstructor ;
2222import lombok .extern .slf4j .Slf4j ;
2323import org .apache .commons .collections4 .CollectionUtils ;
24+ import org .apache .commons .lang3 .BooleanUtils ;
2425import org .apache .commons .lang3 .StringUtils ;
2526import org .springframework .stereotype .Service ;
2627
2728import java .time .LocalDateTime ;
2829import java .time .ZoneId ;
2930import java .time .format .DateTimeFormatter ;
31+ import java .util .ArrayList ;
3032import java .util .Collections ;
33+ import java .util .Comparator ;
3134import java .util .Date ;
3235import java .util .List ;
3336import java .util .Map ;
@@ -66,7 +69,7 @@ public MetricResponse query(String projectKey, String environmentKey, String tog
6669 environmentKey , toggleKey ).get ();
6770 appendLatestVariations (accessCounters , latestTargeting , metricType );
6871
69- return new MetricResponse (accessEventPoints , accessCounters );
72+ return new MetricResponse (accessEventPoints , sortAccessCounters ( accessCounters ) );
7073 }
7174
7275 private Map <String , VariationHistory > buildVariationVersionMap (String projectKey , String environmentKey ,
@@ -243,11 +246,11 @@ protected void appendLatestVariations(List<VariationAccessCounter> accessCounter
243246 appendVariationIfInLatest (accessCounters , latestVariations );
244247 }
245248
249+
246250 private void setVariationDeletedIfNotInLatest (List <VariationAccessCounter > accessCounters ,
247251 List <String > namesOrValues ) {
248252 accessCounters .stream ()
249- .filter (accessCounter -> !namesOrValues .contains (accessCounter .getValue ()))
250- .forEach (accessCounter -> accessCounter .setDeleted (true ));
253+ .forEach (accessCounter -> accessCounter .setDeleted (!namesOrValues .contains (accessCounter .getValue ())));
251254 }
252255
253256 private void appendVariationIfInLatest (List <VariationAccessCounter > accessCounters , List <String > namesOrValues ) {
@@ -261,6 +264,21 @@ private void appendVariationIfInLatest(List<VariationAccessCounter> accessCounte
261264 });
262265 }
263266
267+ protected List <VariationAccessCounter > sortAccessCounters (List <VariationAccessCounter > accessCounters ) {
268+ Collections .sort (accessCounters , Comparator .comparingLong (VariationAccessCounter ::getCount ).reversed ());
269+
270+ List <VariationAccessCounter > deletedCounters = Lists .newArrayList ();
271+ new ArrayList <>(accessCounters ).forEach (accessCounter -> {
272+ if (BooleanUtils .isTrue (accessCounter .getDeleted ())) {
273+ deletedCounters .add (accessCounter );
274+ accessCounters .remove (accessCounter );
275+ }
276+ });
277+ accessCounters .addAll (deletedCounters );
278+ return accessCounters ;
279+ }
280+
281+
264282 private String queryEnvironmentServerSdkKey (String projectKey , String environmentKey ) {
265283 Environment environment = this .environmentRepository .findByProjectKeyAndKey (projectKey , environmentKey ).get ();
266284 return environment .getServerSdkKey ();
0 commit comments