List of usage examples for java.util List sort
@SuppressWarnings({ "unchecked", "rawtypes" }) default void sort(Comparator<? super E> c)
From source file:org.niord.core.message.MessageService.java
/** * Returns the message with the given IDs * * @param ids the message IDs/* w ww .j a v a 2s. c om*/ * @return the message with the given IDs */ private List<Message> getMessages(List<Integer> ids) { if (ids.isEmpty()) { return Collections.emptyList(); } List<Message> messages = em.createNamedQuery("Message.findByIds", Message.class).setParameter("ids", ids) .getResultList(); // Sort the result according to the order of the messages in the ID list messages.sort(Comparator.comparingInt(m -> ids.indexOf(m.getId()))); return messages; }
From source file:gist.ac.netcs.fwdtraffic.FwdTrafficComponent.java
public SortedMap<Device, List<FlowEntry>> getSortedFlows(DeviceService deviceService, FlowRuleService service) { SortedMap<Device, List<FlowEntry>> flows = new TreeMap<>(Comparators.ELEMENT_COMPARATOR); List<FlowEntry> rules; FlowEntry.FlowEntryState s = null;//w ww . java 2 s. c o m if (state != null && !state.equals("any")) { s = FlowEntry.FlowEntryState.valueOf(state.toUpperCase()); } Iterable<Device> devices = uri == null ? deviceService.getDevices() : Collections.singletonList(deviceService.getDevice(DeviceId.deviceId(uri))); for (Device d : devices) { if (s == null) { rules = newArrayList(service.getFlowEntries(d.id())); } else { rules = newArrayList(); for (FlowEntry f : service.getFlowEntries(d.id())) { if (f.state().equals(s)) { rules.add(f); } } } rules.sort(Comparators.FLOW_RULE_COMPARATOR); flows.put(d, rules); } return flows; }
From source file:it.unibo.alchemist.model.implementations.actions.ChangeBiomolConcentrationInEnv.java
@Override public void execute() { // declaring a variable for the node where this action is set, to have faster access final Node<Double> thisNode = getNode(); // get the environment surrounding final List<EnvironmentNode> environmentNodesSurrounding = getEnvironmentNodesSurrounding(); // if the node is an EnvironmentNode... if (thisNode instanceof EnvironmentNode) { // sort the env node randomly changeConcentrationInRandomNodes(environmentNodesSurrounding); } else {/*from w w w . jav a2 s .c om*/ // if getNode() instanceof CellNode, check if all nodes are at the same distance final boolean areAllEnvNodesAtTheSameDistance = environmentNodesSurrounding.stream() .mapToDouble(n -> env.getDistanceBetweenNodes(thisNode, n)).distinct().count() == 1; if (areAllEnvNodesAtTheSameDistance) { // if they are, check if they have all the same concentration of the biomolecule final boolean haveAllNodeTheSameConcentration = environmentNodesSurrounding.stream() .mapToDouble(n -> n.getConcentration(biomolecule)).distinct().count() == 1; if (haveAllNodeTheSameConcentration) { // if they have, pick up from the list randomly changeConcentrationInRandomNodes(environmentNodesSurrounding); } else { // else, sort the list by the concentration of the biomolecule environmentNodesSurrounding.sort((n1, n2) -> Double.compare(n1.getConcentration(biomolecule), n2.getConcentration(biomolecule))); changeConcentrationInSortedNodes(environmentNodesSurrounding); } } else { // else, sort the list by the distance from the node environmentNodesSurrounding .sort((n1, n2) -> Double.compare(env.getDistanceBetweenNodes(thisNode, n1), env.getDistanceBetweenNodes(thisNode, n2))); changeConcentrationInSortedNodes(environmentNodesSurrounding); } } }
From source file:org.cgiar.ccafs.marlo.action.impactpathway.ClusterActivitiesAction.java
@Override public void prepare() throws Exception { // Get the Users list that have the pmu role in this crp. loggedCrp = (GlobalUnit) this.getSession().get(APConstants.SESSION_CRP); loggedCrp = crpManager.getGlobalUnitById(loggedCrp.getId()); clRol = Long.parseLong((String) this.getSession().get(APConstants.CRP_CL_ROLE)); roleCl = roleManager.getRoleById(clRol); clusterofActivities = new ArrayList<>(); if (this.getRequest().getParameter(APConstants.TRANSACTION_ID) != null) { transaction = StringUtils.trim(this.getRequest().getParameter(APConstants.TRANSACTION_ID)); CrpProgram history = (CrpProgram) auditLogManager.getHistory(transaction); if (history != null) { crpProgramID = history.getId(); selectedProgram = history;/* w w w. j a va 2s.c o m*/ clusterofActivities.addAll(history.getCrpClusterOfActivities().stream() .filter(c -> c.isActive() && c.getPhase().equals(this.getActualPhase())) .collect(Collectors.toList())); this.setEditable(false); this.setCanEdit(false); programs = new ArrayList<>(); programs.add(history); List<HistoryDifference> differences = new ArrayList<>(); Map<String, String> specialList = new HashMap<>(); int i = 0; for (CrpClusterOfActivity crpClusterOfActivity : clusterofActivities) { differences.addAll(historyComparator.getDifferencesList(crpClusterOfActivity, transaction, specialList, "clusterofActivities[" + i + "]", "clusterofActivities", 1)); crpClusterOfActivity.setLeaders(crpClusterOfActivity.getCrpClusterActivityLeaders().stream() .filter(c -> c.isActive()).collect(Collectors.toList())); int j = 0; for (CrpClusterActivityLeader clusterActivityLeader : crpClusterOfActivity.getLeaders()) { differences.addAll(historyComparator.getDifferencesList(clusterActivityLeader, transaction, specialList, "clusterofActivities[" + i + "].leaders[" + j + "]", "clusterofActivities", 2)); j++; } crpClusterOfActivity.setKeyOutputs(crpClusterOfActivity.getCrpClusterKeyOutputs().stream() .filter(c -> c.isActive()).collect(Collectors.toList())); j = 0; int k = 0; for (CrpClusterKeyOutput crpClusterKeyOutput : crpClusterOfActivity.getKeyOutputs()) { differences.addAll(historyComparator.getDifferencesList(crpClusterKeyOutput, transaction, specialList, "clusterofActivities[" + i + "].keyOutputs[" + j + "]", "clusterofActivities", 2)); crpClusterKeyOutput .setKeyOutputOutcomes(crpClusterKeyOutput.getCrpClusterKeyOutputOutcomes().stream() .filter(c -> c.isActive()).collect(Collectors.toList())); for (CrpClusterKeyOutputOutcome crpClusterKeyOutputOutcome : crpClusterKeyOutput .getKeyOutputOutcomes()) { differences.addAll(historyComparator.getDifferencesList( crpClusterKeyOutputOutcome, transaction, specialList, "clusterofActivities[" + i + "].keyOutputs[" + j + "].keyOutputOutcomes[" + k + "]", "clusterofActivities", 3)); k++; } j++; } i++; } i = 0; this.setDifferences(differences); } else { programs = new ArrayList<>(); this.transaction = "-1"; } } else { List<CrpProgram> allPrograms = loggedCrp.getCrpPrograms().stream() .filter(c -> c.getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue() && c.isActive()) .collect(Collectors.toList()); allPrograms.sort((p1, p2) -> p1.getAcronym().compareTo(p2.getAcronym())); crpProgramID = -1; if (allPrograms != null) { this.programs = allPrograms; try { crpProgramID = Long.parseLong( StringUtils.trim(this.getRequest().getParameter(APConstants.CRP_PROGRAM_ID))); } catch (Exception e) { User user = userManager.getUser(this.getCurrentUser().getId()); List<CrpProgramLeader> userLeads = user.getCrpProgramLeaders().stream().filter(c -> c.isActive() && c.getCrpProgram().isActive() && c.getCrpProgram() != null && c.getCrpProgram().getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue()) .collect(Collectors.toList()); if (!userLeads.isEmpty()) { crpProgramID = userLeads.get(0).getCrpProgram().getId(); } else { if (!this.programs.isEmpty()) { crpProgramID = this.programs.get(0).getId(); } } } } else { programs = new ArrayList<>(); } if (crpProgramID != -1) { selectedProgram = crpProgramManager.getCrpProgramById(crpProgramID); clusterofActivities.addAll(selectedProgram.getCrpClusterOfActivities().stream() .filter(c -> c.isActive() && c.getPhase().equals(this.getActualPhase())) .collect(Collectors.toList())); for (CrpClusterOfActivity crpClusterOfActivity : clusterofActivities) { crpClusterOfActivity.setLeaders(crpClusterOfActivity.getCrpClusterActivityLeaders().stream() .filter(c -> c.isActive()).collect(Collectors.toList())); crpClusterOfActivity.setKeyOutputs(crpClusterOfActivity.getCrpClusterKeyOutputs().stream() .filter(c -> c.isActive()).collect(Collectors.toList())); for (CrpClusterKeyOutput crpClusterKeyOutput : crpClusterOfActivity.getKeyOutputs()) { crpClusterKeyOutput .setKeyOutputOutcomes(crpClusterKeyOutput.getCrpClusterKeyOutputOutcomes().stream() .filter(c -> c.isActive()).collect(Collectors.toList())); for (CrpClusterKeyOutputOutcome keyOuputOutcome : crpClusterKeyOutput .getKeyOutputOutcomes()) { keyOuputOutcome.setCrpProgramOutcome(crpProgramOutcomeManager .getCrpProgramOutcomeById(keyOuputOutcome.getCrpProgramOutcome().getId())); } } } } if (selectedProgram != null) { Path path = this.getAutoSaveFilePath(); if (path.toFile().exists()) { BufferedReader reader = null; reader = new BufferedReader(new FileReader(path.toFile())); Gson gson = new GsonBuilder().create(); JsonObject jReader = gson.fromJson(reader, JsonObject.class); reader.close(); try { AutoSaveReader autoSaveReader = new AutoSaveReader(); selectedProgram = (CrpProgram) autoSaveReader.readFromJson(jReader); clusterofActivities = selectedProgram.getClusterofActivities(); selectedProgram.setAcronym( crpProgramManager.getCrpProgramById(selectedProgram.getId()).getAcronym()); selectedProgram.setCrp(loggedCrp); if (clusterofActivities == null) { clusterofActivities = new ArrayList<>(); } for (CrpClusterOfActivity clusterOfActivity : clusterofActivities) { if (clusterOfActivity.getKeyOutputs() == null) { clusterOfActivity.setKeyOutputs(new ArrayList<>()); } if (clusterOfActivity.getLeaders() != null) { for (CrpClusterActivityLeader leaders : clusterOfActivity.getLeaders()) { if (leaders.getUser() != null && leaders.getUser().getId() != null) { leaders.setUser(userManager.getUser(leaders.getUser().getId())); } } } if (clusterOfActivity.getKeyOutputs() != null) { for (CrpClusterKeyOutput keyOuput : clusterOfActivity.getKeyOutputs()) { if (keyOuput.getKeyOutputOutcomes() != null) { for (CrpClusterKeyOutputOutcome keyOuputOutcome : keyOuput .getKeyOutputOutcomes()) { keyOuputOutcome.setCrpProgramOutcome( crpProgramOutcomeManager.getCrpProgramOutcomeById( keyOuputOutcome.getCrpProgramOutcome().getId())); } } } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } this.setDraft(true); } else { this.setDraft(false); } String params[] = { loggedCrp.getAcronym(), selectedProgram.getId().toString() }; this.setBasePermission(this.getText(Permission.IMPACT_PATHWAY_BASE_PERMISSION, params)); selectedProgram = crpProgramManager.getCrpProgramById(selectedProgram.getId()); outcomes = selectedProgram.getCrpProgramOutcomes().stream() .filter(c -> c.isActive() && c.getPhase().equals(this.getActualPhase())) .collect(Collectors.toList()); if (!selectedProgram.getSubmissions().stream() .filter(c -> ((c.isUnSubmit() == null || !c.isUnSubmit()) && c.getYear().intValue() == this.getActualPhase().getYear() && c.getCycle().equals(this.getActualPhase().getDescription()))) .collect(Collectors.toList()).isEmpty()) { if (!(this.canAccessSuperAdmin() || this.canAcessCrpAdmin())) { this.setCanEdit(false); this.setEditable(false); } List<Submission> submissions = selectedProgram.getSubmissions().stream() .filter(c -> c.getYear() == this.getActualPhase().getYear() && c.getCycle() != null && c.getCycle().equals(this.getActualPhase().getDescription())) .collect(Collectors.toList()); if (!submissions.isEmpty()) { this.setSubmission(submissions.get(0)); } } } if (this.isHttpPost()) { clusterofActivities.clear(); clusterofActivities = null; } } }
From source file:edu.usu.sdl.openstorefront.service.AttributeServiceImpl.java
private void sortArchitecture(List<Architecture> architectures) { if (architectures.isEmpty()) { return;/*from w ww . j a va 2 s .c om*/ } for (Architecture architecture : architectures) { sortArchitecture(architecture.getChildren()); } architectures.sort(new ArchitectureComparator<>()); }
From source file:com.yahoo.pulsar.broker.namespace.NamespaceService.java
public List<String> getListOfDestinations(String property, String cluster, String namespace) throws Exception { List<String> destinations = Lists.newArrayList(); // For every topic there will be a managed ledger created. try {/*from w w w.j av a 2 s. co m*/ String path = String.format("/managed-ledgers/%s/%s/%s/persistent", property, cluster, namespace); LOG.debug("Getting children from managed-ledgers now: {}", path); for (String destination : pulsar.getLocalZkCacheService().managedLedgerListCache().get(path)) { destinations.add(String.format("persistent://%s/%s/%s/%s", property, cluster, namespace, Codec.decode(destination))); } } catch (KeeperException.NoNodeException e) { // NoNode means there are no persistent topics for this namespace } destinations.sort(null); return destinations; }
From source file:com.navercorp.pinpoint.web.mapper.stat.AgentStatMapperV2Test.java
@Test public void mapperTest() throws Exception { // Given//from w ww.ja v a 2 s.c o m List<TestAgentStat> givenAgentStats = new ArrayList<>(); List<Put> puts = new ArrayList<>(); long initialTimestamp = System.currentTimeMillis(); int numBatch = RandomUtils.nextInt(1, MAX_NUM_TEST_VALUES); for (int i = 0; i < numBatch; i++) { int batchSize = RandomUtils.nextInt(1, MAX_NUM_TEST_VALUES); List<TestAgentStat> agentStatBatch = createAgentStats(initialTimestamp, COLLECT_INVERVAL, batchSize); givenAgentStats.addAll(agentStatBatch); puts.addAll(this.hbaseOperationFactory.createPuts(AGENT_ID, AGENT_STAT_TYPE, agentStatBatch, this.serializer)); initialTimestamp += batchSize * COLLECT_INVERVAL; } List<Cell> cellsToPut = new ArrayList<>(); for (Put put : puts) { List<Cell> cells = put.getFamilyCellMap().get(HbaseColumnFamily.AGENT_STAT_STATISTICS.getName()); cellsToPut.addAll(cells); } Result result = Result.create(cellsToPut); // When AgentStatMapperV2<TestAgentStat> mapper = new AgentStatMapperV2<>(this.hbaseOperationFactory, this.decoder, TEST_FILTER); List<TestAgentStat> mappedAgentStats = mapper.mapRow(result, 0); // Then givenAgentStats.sort(AgentStatMapperV2.REVERSE_TIMESTAMP_COMPARATOR); Assert.assertEquals(givenAgentStats, mappedAgentStats); }
From source file:de.themoep.simpleteampvp.games.SimpleTeamPvPGame.java
/** * Balance the teams//from w ww . j a v a 2s.c o m * @return <tt>true</tt> if game is in GameState.JOINING and players can be balanced */ public boolean balance() { if (getState() != GameState.JOINING) return false; plugin.getServer() .broadcastMessage(ChatColor.GREEN + "Ausbalancieren und Auffllen der Teams gestartet..."); Map<Player, String> beforeBalance = new HashMap<>(); List<Player> playersToJoin = new ArrayList<>(); for (Player player : plugin.getServer().getOnlinePlayers()) { if (player.hasPermission(SimpleTeamPvP.BYPASS_PERM) || player.getGameMode() == GameMode.CREATIVE || player.getGameMode() == GameMode.SPECTATOR) continue; TeamInfo team = getTeam(player); if (team == null) { if (config.getRandomRegion() == null || config.getRandomRegion().contains(player.getLocation())) playersToJoin.add(player); beforeBalance.put(player, ""); } else { beforeBalance.put(player, team.getName()); } } plugin.getLogger().log(Level.INFO, "Players to join: " + playersToJoin.size()); int totalPlayers = playersToJoin.size(); for (TeamInfo team : config.getTeams().values()) { totalPlayers += team.getSize(); } plugin.getLogger().log(Level.INFO, "Number of teams: " + config.getTeams().size()); double perfectSize = (double) totalPlayers / (double) config.getTeams().size(); plugin.getLogger().log(Level.INFO, "perfectSize: " + perfectSize); if (plugin.getServerTags() != null) { // Team key -> Tag Map<String, String> teamTags = new HashMap<>(); for (TeamInfo team : config.getTeams().values()) { Map<String, Integer> tags = new HashMap<>(); for (String playerName : team.getScoreboardTeam().getEntries()) { Player player = plugin.getServer().getPlayer(playerName); if (player == null) continue; String tag = "no server"; ServerInfo serverInfo = plugin.getServerTags().getPlayerServer(player); if (serverInfo != null) { tag = serverInfo.getTag(); } if (!tags.containsKey(tag)) { tags.put(tag, 0); } tags.put(tag, tags.get(tag) + 1); } String teamTag = "no server"; int tagCount = 0; for (Map.Entry<String, Integer> entry : tags.entrySet()) { if (entry.getValue() > tagCount) { tagCount = entry.getValue(); teamTag = entry.getKey(); } } teamTags.put(team.getName(), teamTag); } for (TeamInfo team : config.getTeams().values()) { // Filter out players that come from another server than the majority of the team // and remove them as long as the team is larger than the perfect size for (String playerName : team.getScoreboardTeam().getEntries()) { if (team.getSize() <= perfectSize + 0.5) break; Player player = plugin.getServer().getPlayer(playerName); if (player == null) continue; String tag = "no server"; ServerInfo serverInfo = plugin.getServerTags().getPlayerServer(player); if (serverInfo != null) { tag = serverInfo.getTag(); } if (tag.equals(teamTags.get(team.getName()))) continue; plugin.getLogger().log(Level.INFO, "[ST] Removed " + player.getName() + " from " + team.getName() + " (Step 1)"); team.removePlayer(player); playersToJoin.add(player); } // Team still larger than the perfect size? Remove last joined player Deque<String> teamMates = new ArrayDeque<>(team.getScoreboardTeam().getEntries()); while (team.getSize() > perfectSize + 0.5) { String name = teamMates.peekLast(); Player player = plugin.getServer().getPlayer(name); if (player == null) continue; team.removePlayer(player); plugin.getLogger().log(Level.INFO, "[ST] Removed " + player.getName() + " from " + team.getName() + " (Step 2)"); teamMates.pollLast(); playersToJoin.add(player); } } // Add rest of players to teams from their server Iterator<Player> playerIterator = playersToJoin.iterator(); while (playerIterator.hasNext()) { Player player = playerIterator.next(); ServerInfo serverInfo = plugin.getServerTags().getPlayerServer(player); if (serverInfo != null && teamTags.containsValue(serverInfo.getTag())) { for (TeamInfo team : config.getTeams().values()) { if (team.getSize() < perfectSize - 0.5 && teamTags.containsKey(team.getName()) && teamTags.get(team.getName()).equals(serverInfo.getTag())) { team.addPlayer(player); plugin.getLogger().log(Level.INFO, "[ST] Added " + player.getName() + " to " + team.getName()); playerIterator.remove(); break; } } } } plugin.getLogger().log(Level.INFO, "Players to join after servertags: " + playersToJoin.size()); } // Remove players from teams that have more than the perfect size for (TeamInfo team : config.getTeams().values()) { for (String playerName : team.getScoreboardTeam().getEntries()) { if (team.getSize() <= perfectSize + 0.5) break; Player player = plugin.getServer().getPlayer(playerName); if (player == null) continue; plugin.getLogger().log(Level.INFO, "Removed " + player.getName() + " from " + team.getName()); team.removePlayer(player); playersToJoin.add(player); } } Iterator<Player> playerIterator = playersToJoin.iterator(); for (TeamInfo team : config.getTeams().values()) { while (playerIterator.hasNext()) { if (team.getSize() >= perfectSize - 0.5) break; Player player = playerIterator.next(); team.addPlayer(player); plugin.getLogger().log(Level.INFO, "Added " + player.getName() + " to " + team.getName()); playerIterator.remove(); } } if (playerIterator.hasNext()) { plugin.getLogger().log(Level.INFO, "Adding " + playersToJoin.size() + " remaining players to teams according to their player count:"); List<TeamInfo> teams = new ArrayList<>(config.getTeams().values()); teams.sort((t1, t2) -> Integer.compare(t2.getSize(), t1.getSize())); for (TeamInfo team : teams) { while (playerIterator.hasNext()) { if (team.getSize() > perfectSize) break; Player player = playerIterator.next(); team.addPlayer(player); plugin.getLogger().log(Level.INFO, "Added remaining player " + player.getName() + " to " + team.getName()); playerIterator.remove(); } } } if (playerIterator.hasNext()) { plugin.getLogger().log(Level.INFO, "Adding " + playersToJoin.size() + " remaining players to totally random teams:"); Random r = new Random(); List<TeamInfo> teams = new ArrayList<>(config.getTeams().values()); while (playerIterator.hasNext()) { Player player = playerIterator.next(); TeamInfo team = teams.get(r.nextInt(teams.size())); team.addPlayer(player); plugin.getLogger().log(Level.INFO, "Added player " + player.getName() + " to " + team.getName() + " by random"); playerIterator.remove(); } } plugin.getLogger().log(Level.INFO, "All players joined! (" + playersToJoin.size() + ")"); for (Map.Entry<Player, String> entry : beforeBalance.entrySet()) { TeamInfo team = getTeam(entry.getKey()); if (team != null && !team.getName().equals(entry.getValue())) { Player player = null; for (Iterator<String> it = team.getScoreboardTeam().getEntries().iterator(); player == null && it.hasNext();) { player = plugin.getServer().getPlayer(it.next()); } if (player != null && team.getJoinRegion().contains(player.getLocation())) { entry.getKey().teleport(player); } else { entry.getKey().teleport(team.getJoinRegion().calculateMiddle().getLocation()); } } } plugin.getServer().broadcastMessage(ChatColor.GREEN + "Teams ausbalanciert und aufgefllt!"); state = GameState.WAITING; return true; }
From source file:de.whs.poodle.controllers.AboutController.java
private static List<Credit> createCredits() { License apache2 = new License("Apache 2.0", "https://www.apache.org/licenses/LICENSE-2.0.html"); List<Credit> credits = Arrays.asList( new Credit("jQuery", "https://jquery.com/", new License("MIT", "https://raw.githubusercontent.com/jquery/jquery/master/LICENSE.txt")), new Credit("jQuery UI", "https://jqueryui.com/", new License("MIT", "https://raw.githubusercontent.com/jquery/jquery-ui/master/LICENSE.txt")), new Credit("moment.js", "http://momentjs.com/", new License("MIT", "https://raw.githubusercontent.com/moment/moment/develop/LICENSE")), new Credit("JSoup", "http://jsoup.org/", new License("MIT", "http://jsoup.org/license")), new Credit("Bootstrap", "http://getbootstrap.com/", new License("MIT", "https://raw.githubusercontent.com/twbs/bootstrap/master/LICENSE")), new Credit("Bootstrap DateTimePicker", "https://github.com/Eonasdan/bootstrap-datetimepicker/", new License("MIT", "https://github.com/Eonasdan/bootstrap-datetimepicker/blob/master/LICENSE")), new Credit("DataTables", "https://datatables.net/", new License("MIT", "https://raw.githubusercontent.com/DataTables/DataTables/master/license.txt")), new Credit("PostgreSQL", "http://www.postgresql.org/", new License("PostgreSQL License", "http://www.postgresql.org/about/licence/")), new Credit("Spring", "https://spring.io/", apache2), new Credit("Spring Boot", "http://projects.spring.io/spring-boot/", apache2), new Credit("Thymeleaf", "http://www.thymeleaf.org/", apache2), new Credit("Jackson", "https://github.com/FasterXML/jackson", apache2), new Credit("Gradle", "http://gradle.org/", apache2), new Credit("MathJax", "http://www.mathjax.org/", apache2), new Credit("Apache Tomcat", "https://tomcat.apache.org/", apache2), new Credit("google-diff-match-patch", "https://code.google.com/p/google-diff-match-patch/", apache2),/* ww w. j a v a2s . com*/ new Credit("CKEditor", "http://ckeditor.com/", new License("GPL", "https://www.gnu.org/licenses/gpl-3.0.txt"))); // sort by name credits.sort((c1, c2) -> c1.getName().compareTo(c2.getName())); return credits; }
From source file:org.springframework.context.annotation.ConfigurationClassPostProcessor.java
/** * Build and validate a configuration model based on the registry of * {@link Configuration} classes./*from ww w .java2 s.com*/ */ public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) { List<BeanDefinitionHolder> configCandidates = new ArrayList<>(); String[] candidateNames = registry.getBeanDefinitionNames(); for (String beanName : candidateNames) { BeanDefinition beanDef = registry.getBeanDefinition(beanName); if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) || ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) { if (logger.isDebugEnabled()) { logger.debug("Bean definition has already been processed as a configuration class: " + beanDef); } } else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) { configCandidates.add(new BeanDefinitionHolder(beanDef, beanName)); } } // Return immediately if no @Configuration classes were found if (configCandidates.isEmpty()) { return; } // Sort by previously determined @Order value, if applicable configCandidates.sort((bd1, bd2) -> { int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition()); int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition()); return (i1 < i2) ? -1 : (i1 > i2) ? 1 : 0; }); // Detect any custom bean name generation strategy supplied through the enclosing application context SingletonBeanRegistry sbr = null; if (registry instanceof SingletonBeanRegistry) { sbr = (SingletonBeanRegistry) registry; if (!this.localBeanNameGeneratorSet) { BeanNameGenerator generator = (BeanNameGenerator) sbr .getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR); if (generator != null) { this.componentScanBeanNameGenerator = generator; this.importBeanNameGenerator = generator; } } } if (this.environment == null) { this.environment = new StandardEnvironment(); } // Parse each @Configuration class ConfigurationClassParser parser = new ConfigurationClassParser(this.metadataReaderFactory, this.problemReporter, this.environment, this.resourceLoader, this.componentScanBeanNameGenerator, registry); Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates); Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size()); do { parser.parse(candidates); parser.validate(); Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses()); configClasses.removeAll(alreadyParsed); // Read the model and create bean definitions based on its content if (this.reader == null) { this.reader = new ConfigurationClassBeanDefinitionReader(registry, this.sourceExtractor, this.resourceLoader, this.environment, this.importBeanNameGenerator, parser.getImportRegistry()); } this.reader.loadBeanDefinitions(configClasses); alreadyParsed.addAll(configClasses); candidates.clear(); if (registry.getBeanDefinitionCount() > candidateNames.length) { String[] newCandidateNames = registry.getBeanDefinitionNames(); Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames)); Set<String> alreadyParsedClasses = new HashSet<>(); for (ConfigurationClass configurationClass : alreadyParsed) { alreadyParsedClasses.add(configurationClass.getMetadata().getClassName()); } for (String candidateName : newCandidateNames) { if (!oldCandidateNames.contains(candidateName)) { BeanDefinition bd = registry.getBeanDefinition(candidateName); if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) && !alreadyParsedClasses.contains(bd.getBeanClassName())) { candidates.add(new BeanDefinitionHolder(bd, candidateName)); } } } candidateNames = newCandidateNames; } } while (!candidates.isEmpty()); // Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes if (sbr != null) { if (!sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) { sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry()); } } if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) { // Clear cache in externally provided MetadataReaderFactory; this is a no-op // for a shared cache since it'll be cleared by the ApplicationContext. ((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache(); } }