List of usage examples for java.util SortedMap get
V get(Object key);
From source file:org.omnaest.utils.table.TableTest.java
@SuppressWarnings({ "unchecked", "cast" }) @Test//from w w w . j a v a2s .c o m public void testIndexOfArbitraryKeyExtractorWithValueExtractor() { Table<String> table = this.filledTable(100, 5); KeyExtractor<Integer, RowDataReader<String>> keyExtractor = new KeyExtractor<Integer, RowDataReader<String>>() { private static final long serialVersionUID = -7714884390309847394L; @Override public Integer extractKey(RowDataReader<String> rowDataReader) { String[] elements = rowDataReader.getElements(); String[] tokens = elements[1].split(":"); return Integer.valueOf(tokens[0]); } }; ValueExtractor<Integer, Set<String[]>> valueExtractor = new ValueExtractor<Integer, Set<String[]>>() { @Override public Integer extractValue(Set<String[]> elementsSet) { final String[] elements = IterableUtils.firstElement(elementsSet); final String[] tokens = elements[1].split(":"); return Integer.valueOf(tokens[1]); } }; SortedMap<Integer, Integer> sortedMap = table.index().of(keyExtractor, valueExtractor, (Comparator<Integer>) ComparatorUtils.reversedComparator(ComparatorUtils.NATURAL_COMPARATOR)); { assertNotNull(sortedMap); assertEquals(table.rowSize(), sortedMap.size()); assertTrue(sortedMap.containsKey(0)); } table.removeRow(0); { assertFalse(sortedMap.containsKey(0)); assertTrue(sortedMap.containsKey(1)); assertFalse(sortedMap.containsKey(101)); table.setElement(0, 1, "101:88"); assertTrue(sortedMap.containsKey(101)); Integer columnIndex = sortedMap.get(101); assertEquals(88, columnIndex.intValue()); } }
From source file:com.github.fauu.natrank.service.RankingServiceImpl.java
private void calculateTeamRatingsAndRankChanges(List<Match> matches) throws DataAccessException { teamRatingRepository.deleteAll();/*w w w. java2 s. com*/ teamRankRepository.deleteAll(); List<TeamRating> ratings = new LinkedList<>(); List<TeamRank> ranks = new LinkedList<>(); Map<Integer, RankedTeam> rankedTeamsByTeamId = new HashMap(); List<Team> teams = teamRepository.findAll(); SortedMap<Integer, Integer> initialRatings = new TreeMap<>(); for (int passNo = 0; passNo < 2; passNo++) { if (passNo == 1) { ratings.clear(); for (Team team : teams) { team.getRatings().clear(); } } for (Match match : matches) { List<Team> matchTeams = new ArrayList<>(); matchTeams.add(match.getTeam1()); matchTeams.add(match.getTeam2()); for (Team team : matchTeams) { if (team.getRatings().size() == 0) { team.setHomeAdvantageCoefficient(INITIAL_HOME_ADVANTAGE_COEFFICIENT); TeamRating rating = new TeamRating(); rating.setDate(match.getDate()); rating.setTeam(team); rating.setChange(0); rating.setProvisional(true); if (!initialRatings.containsKey(team.getId())) { for (int year : DEFAULT_RATINGS_UPTO_YEAR.keySet()) { if (match.getDate().getYear() < year) { initialRatings.put(team.getId(), DEFAULT_RATINGS_UPTO_YEAR.get(year)); break; } } } rating.setValue(initialRatings.get(team.getId())); team.getRatings().add(rating); } } List<Integer> matchTeamRatings = new ArrayList<>(); matchTeamRatings.add(matchTeams.get(0).getCurrentRating().getValue()); matchTeamRatings.add(matchTeams.get(1).getCurrentRating().getValue()); List<Integer> matchTeamRatingsAdjusted = new ArrayList<>(matchTeamRatings); Team winnerTeam = match.getWinnerTeam(); double marginOfVictoryCoefficient; double matchResultCoefficient = 0; if (winnerTeam != null) { marginOfVictoryCoefficient = Math.sqrt(Math.abs(match.getTeam1Goals() - match.getTeam2Goals())); if (winnerTeam == matchTeams.get(0)) { matchResultCoefficient = 1; matchTeamRatingsAdjusted.set(0, matchTeamRatingsAdjusted.get(0) + (int) Math.round(matchTeams.get(0).getHomeAdvantageCoefficient())); } else if (winnerTeam == matchTeams.get(1)) { matchResultCoefficient = 0; matchTeamRatingsAdjusted.set(1, matchTeamRatingsAdjusted.get(1) + (int) Math.round(matchTeams.get(1).getHomeAdvantageCoefficient())); } } else { marginOfVictoryCoefficient = 1; matchResultCoefficient = 0.5; } double exponent = (-1 * (matchTeamRatingsAdjusted.get(0) - matchTeamRatingsAdjusted.get(1))) / 444.0; double expectedMatchResultCoefficient = 1 / (Math.pow(10, exponent) + 1); double team1RatingChange = match.getType().getWeight() * marginOfVictoryCoefficient * (matchResultCoefficient - expectedMatchResultCoefficient); long team1RatingChangeRounded = Math.round(team1RatingChange); List<Integer> matchTeamRatingChanges = new ArrayList<>(); matchTeamRatingChanges.add((int) team1RatingChangeRounded); matchTeamRatingChanges.add(-1 * (int) team1RatingChangeRounded); for (int i = 0; i < 2; i++) { Team currentTeam = matchTeams.get(i); int ratingChangeModifier = 1; if (passNo == 0 && currentTeam.getRatings().size() - 1 < NUM_TRIAL_MATCHES) { ratingChangeModifier = TRIAL_RATING_MODIFIER; } int currentTeamOldRating = matchTeamRatings.get(i); matchTeamRatings.set(i, currentTeamOldRating + ratingChangeModifier * matchTeamRatingChanges.get(i)); TeamRating newRating = new TeamRating(); newRating.setDate(match.getDate()); newRating.setTeam(matchTeams.get(i)); newRating.setMatch(match); newRating.setValue(matchTeamRatings.get(i)); newRating.setChange(matchTeamRatingChanges.get(i)); if (passNo == 1 && currentTeam.getRatings().size() < NUM_TRIAL_MATCHES) { newRating.setProvisional(true); } matchTeams.get(i).setHomeAdvantageCoefficient(matchTeams.get(i).getHomeAdvantageCoefficient() + 0.075 * matchTeamRatingChanges.get(i)); if (i == 0) { match.setTeam1Rating(newRating.getValue()); match.setTeam1RatingChange(newRating.getChange()); } else if (i == 1) { match.setTeam2Rating(newRating.getValue()); match.setTeam2RatingChange(newRating.getChange()); } ratings.add(newRating); currentTeam.getRatings().add(newRating); if (passNo == 1 && (currentTeam.getRatings().size() - 1) >= NUM_TRIAL_MATCHES) { List<RankedTeam> rankedTeamsToProcess = new LinkedList<>(); boolean isFirstEntryOfCurrentTeam = false; if (!rankedTeamsByTeamId.containsKey(currentTeam.getId())) { RankedTeam newRankedTeam = new RankedTeam(); newRankedTeam.setTeam(currentTeam); newRankedTeam.setRating(currentTeam.getCurrentRating().getValue()); newRankedTeam.setRank(rankedTeamsByTeamId.size() + 1); rankedTeamsByTeamId.put(currentTeam.getId(), newRankedTeam); currentTeamOldRating = 0; isFirstEntryOfCurrentTeam = true; } int currentTeamCurrentRating = currentTeam.getCurrentRating().getValue(); int currentTeamRatingChange = currentTeamCurrentRating - currentTeamOldRating; if (currentTeamRatingChange != 0) { int currentTeamHighRating = currentTeamRatingChange >= 0 ? currentTeamCurrentRating : currentTeamOldRating; int currentTeamLowRating = currentTeamRatingChange < 0 ? currentTeamCurrentRating : currentTeamOldRating; int currentTeamRank = rankedTeamsByTeamId.get(currentTeam.getId()).getRank(); for (Map.Entry<Integer, RankedTeam> rankedTeamEntry : rankedTeamsByTeamId.entrySet()) { if (rankedTeamEntry.getKey().equals(currentTeam.getId())) { rankedTeamEntry.getValue().setRating(currentTeamCurrentRating); } int entryTeamRating = rankedTeamEntry.getValue().getRating(); int entryTeamRank = rankedTeamEntry.getValue().getRank(); if ((currentTeamHighRating >= entryTeamRating) && (currentTeamLowRating <= entryTeamRating) && !((currentTeamRatingChange > 0) && (entryTeamRating == currentTeamLowRating) && (entryTeamRank > currentTeamRank)) && !((currentTeamRatingChange < 0) && (entryTeamRating == currentTeamHighRating) && (entryTeamRank < currentTeamRank))) { rankedTeamsToProcess.add(rankedTeamEntry.getValue()); } } if (isFirstEntryOfCurrentTeam || rankedTeamsToProcess.size() > 1) { int otherTeamsRankChange = currentTeamRatingChange > 0 ? 1 : -1; int currentTeamRankChange = -1 * otherTeamsRankChange * (rankedTeamsToProcess.size() - 1); for (RankedTeam rankedTeam : rankedTeamsToProcess) { int rankChange = rankedTeam.getTeam() == currentTeam ? currentTeamRankChange : otherTeamsRankChange; rankedTeam.setRank(rankedTeam.getRank() + rankChange); TeamRank newTeamRankEntry = new TeamRank(); newTeamRankEntry.setDate(match.getDate()); newTeamRankEntry.setTeam(rankedTeam.getTeam()); newTeamRankEntry.setValue(rankedTeam.getRank()); if (!(rankedTeam.getTeam() == currentTeam) || !isFirstEntryOfCurrentTeam) { newTeamRankEntry.setChange(-1 * rankChange); } if (rankedTeam.getTeam() == match.getTeam1()) { match.setTeam1Rank(newTeamRankEntry.getValue()); match.setTeam1RankChange(newTeamRankEntry.getChange()); } else if (rankedTeam.getTeam() == match.getTeam2()) { match.setTeam2Rank(newTeamRankEntry.getValue()); match.setTeam2RankChange(newTeamRankEntry.getChange()); } ranks.add(newTeamRankEntry); } } else { if (i == 0) { match.setTeam1Rank(rankedTeamsByTeamId.get(currentTeam.getId()).getRank()); match.setTeam1RankChange(0); } else if (i == 1) { match.setTeam2Rank(rankedTeamsByTeamId.get(currentTeam.getId()).getRank()); match.setTeam2RankChange(0); } } } } if (passNo == 0 && (matchTeams.get(i).getRatings().size() - 1 < NUM_TRIAL_MATCHES)) { initialRatings.put(matchTeams.get(i).getId(), newRating.getValue()); } } } } matchRepository.save(matches); teamRatingRepository.save(ratings); teamRankRepository.save(ranks); }
From source file:org.talend.dataprep.schema.xls.XlsSchemaParser.java
/** * We store (cell types per row) per column. * * @param sheet key is the column number, value is a Map with key row number and value Type * @return A Map<colId, Map<rowId, type>> *//*from w w w. j a va 2 s .com*/ private SortedMap<Integer, SortedMap<Integer, String>> collectSheetTypeMatrix(Sheet sheet, FormulaEvaluator formulaEvaluator) { int firstRowNum = sheet.getFirstRowNum(); int lastRowNum = sheet.getLastRowNum(); LOGGER.debug("firstRowNum: {}, lastRowNum: {}", firstRowNum, lastRowNum); SortedMap<Integer, SortedMap<Integer, String>> cellsTypeMatrix = new TreeMap<>(); // we start analysing rows for (int rowCounter = firstRowNum; rowCounter <= lastRowNum; rowCounter++) { int cellCounter = 0; Row row = sheet.getRow(rowCounter); if (row == null) { continue; } Iterator<Cell> cellIterator = row.cellIterator(); String currentType; while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); int xlsType = Cell.CELL_TYPE_STRING; try { xlsType = cell.getCellType() == Cell.CELL_TYPE_FORMULA ? // formulaEvaluator.evaluate(cell).getCellType() : cell.getCellType(); } catch (Exception e) { // ignore formula error evaluation get as a String with the formula } switch (xlsType) { case Cell.CELL_TYPE_BOOLEAN: currentType = BOOLEAN.getName(); break; case Cell.CELL_TYPE_NUMERIC: currentType = getTypeFromNumericCell(cell); break; case Cell.CELL_TYPE_BLANK: currentType = BLANK; break; case Cell.CELL_TYPE_FORMULA: case Cell.CELL_TYPE_STRING: currentType = STRING.getName(); break; case Cell.CELL_TYPE_ERROR: // we cannot really do anything with an error default: currentType = ANY.getName(); } SortedMap<Integer, String> cellInfo = cellsTypeMatrix.get(cellCounter); if (cellInfo == null) { cellInfo = new TreeMap<>(); } cellInfo.put(rowCounter, currentType); cellsTypeMatrix.put(cellCounter, cellInfo); cellCounter++; } } LOGGER.trace("cellsTypeMatrix: {}", cellsTypeMatrix); return cellsTypeMatrix; }
From source file:org.apache.hadoop.hbase.master.TestCatalogJanitor.java
/** * Make sure parent with specified end key gets cleaned up even if daughter is cleaned up before it. * * @param rootDir the test case name, used as the HBase testing utility root * @param lastEndKey the end key of the split parent * @throws IOException//from www . j av a 2s. com * @throws InterruptedException */ private void parentWithSpecifiedEndKeyCleanedEvenIfDaughterGoneFirst(final String rootDir, final byte[] lastEndKey) throws IOException, InterruptedException { HBaseTestingUtility htu = new HBaseTestingUtility(); setRootDirAndCleanIt(htu, rootDir); Server server = new MockServer(htu); MasterServices services = new MockMasterServices(server); CatalogJanitor janitor = new CatalogJanitor(server, services); final HTableDescriptor htd = createHTableDescriptor(); // Create regions: aaa->{lastEndKey}, aaa->ccc, aaa->bbb, bbb->ccc, etc. // Parent HRegionInfo parent = new HRegionInfo(htd.getTableName(), Bytes.toBytes("aaa"), lastEndKey); // Sleep a second else the encoded name on these regions comes out // same for all with same start key and made in same second. Thread.sleep(1001); // Daughter a HRegionInfo splita = new HRegionInfo(htd.getTableName(), Bytes.toBytes("aaa"), Bytes.toBytes("ccc")); Thread.sleep(1001); // Make daughters of daughter a; splitaa and splitab. HRegionInfo splitaa = new HRegionInfo(htd.getTableName(), Bytes.toBytes("aaa"), Bytes.toBytes("bbb")); HRegionInfo splitab = new HRegionInfo(htd.getTableName(), Bytes.toBytes("bbb"), Bytes.toBytes("ccc")); // Daughter b HRegionInfo splitb = new HRegionInfo(htd.getTableName(), Bytes.toBytes("ccc"), lastEndKey); Thread.sleep(1001); // Make Daughters of daughterb; splitba and splitbb. HRegionInfo splitba = new HRegionInfo(htd.getTableName(), Bytes.toBytes("ccc"), Bytes.toBytes("ddd")); HRegionInfo splitbb = new HRegionInfo(htd.getTableName(), Bytes.toBytes("ddd"), lastEndKey); // First test that our Comparator works right up in CatalogJanitor. // Just fo kicks. SortedMap<HRegionInfo, Result> regions = new TreeMap<HRegionInfo, Result>( new CatalogJanitor.SplitParentFirstComparator()); // Now make sure that this regions map sorts as we expect it to. regions.put(parent, createResult(parent, splita, splitb)); regions.put(splitb, createResult(splitb, splitba, splitbb)); regions.put(splita, createResult(splita, splitaa, splitab)); // Assert its properly sorted. int index = 0; for (Map.Entry<HRegionInfo, Result> e : regions.entrySet()) { if (index == 0) { assertTrue(e.getKey().getEncodedName().equals(parent.getEncodedName())); } else if (index == 1) { assertTrue(e.getKey().getEncodedName().equals(splita.getEncodedName())); } else if (index == 2) { assertTrue(e.getKey().getEncodedName().equals(splitb.getEncodedName())); } index++; } // Now play around with the cleanParent function. Create a ref from splita // up to the parent. Path splitaRef = createReferences(services, htd, parent, splita, Bytes.toBytes("ccc"), false); // Make sure actual super parent sticks around because splita has a ref. assertFalse(janitor.cleanParent(parent, regions.get(parent))); //splitba, and split bb, do not have dirs in fs. That means that if // we test splitb, it should get cleaned up. assertTrue(janitor.cleanParent(splitb, regions.get(splitb))); // Now remove ref from splita to parent... so parent can be let go and so // the daughter splita can be split (can't split if still references). // BUT make the timing such that the daughter gets cleaned up before we // can get a chance to let go of the parent. FileSystem fs = FileSystem.get(htu.getConfiguration()); assertTrue(fs.delete(splitaRef, true)); // Create the refs from daughters of splita. Path splitaaRef = createReferences(services, htd, splita, splitaa, Bytes.toBytes("bbb"), false); Path splitabRef = createReferences(services, htd, splita, splitab, Bytes.toBytes("bbb"), true); // Test splita. It should stick around because references from splitab, etc. assertFalse(janitor.cleanParent(splita, regions.get(splita))); // Now clean up parent daughter first. Remove references from its daughters. assertTrue(fs.delete(splitaaRef, true)); assertTrue(fs.delete(splitabRef, true)); assertTrue(janitor.cleanParent(splita, regions.get(splita))); // Super parent should get cleaned up now both splita and splitb are gone. assertTrue(janitor.cleanParent(parent, regions.get(parent))); services.stop("test finished"); janitor.join(); }
From source file:org.kuali.coeus.common.budget.impl.calculator.BudgetCalculationServiceImpl.java
/** * This method is to categorize line item calculated amounts based on rate type */// www . j ava 2s . com private SortedMap<RateType, QueryList<BudgetLineItemCalculatedAmount>> getBudgetSummaryUniqueRateTypeCalAmounts( List<BudgetLineItem> budgetLineItems, boolean personnelFlag, String personnelCategoryTypeCode) { SortedMap<RateType, QueryList<BudgetLineItemCalculatedAmount>> uniqueLineItemCalAmounts = new TreeMap<>(); for (BudgetLineItem budgetLineItem : budgetLineItems) { if ((personnelFlag && StringUtils.equals( budgetLineItem.getCostElementBO().getBudgetCategory().getBudgetCategoryTypeCode(), personnelCategoryTypeCode)) || (!personnelFlag && !StringUtils.equals( budgetLineItem.getCostElementBO().getBudgetCategory().getBudgetCategoryTypeCode(), personnelCategoryTypeCode))) { for (BudgetLineItemCalculatedAmount budgetLineItemCalculatedAmount : budgetLineItem .getBudgetLineItemCalculatedAmounts()) { RateType rateType = getRateType(budgetLineItemCalculatedAmount); if (!uniqueLineItemCalAmounts.containsKey(rateType)) { uniqueLineItemCalAmounts.put(rateType, new QueryList<>()); } uniqueLineItemCalAmounts.get(rateType).add(budgetLineItemCalculatedAmount); } } } return uniqueLineItemCalAmounts; }
From source file:org.apache.accumulo.tserver.TabletServer.java
public static Pair<Text, KeyExtent> verifyTabletInformation(AccumuloServerContext context, KeyExtent extent, TServerInstance instance, SortedMap<Key, Value> tabletsKeyValues, String clientAddress, ZooLock lock) throws AccumuloSecurityException, DistributedStoreException, AccumuloException { log.debug("verifying extent " + extent); if (extent.isRootTablet()) { return verifyRootTablet(extent, instance); }//from w w w . j a v a2 s. co m String tableToVerify = MetadataTable.ID; if (extent.isMeta()) tableToVerify = RootTable.ID; List<ColumnFQ> columnsToFetch = Arrays .asList(new ColumnFQ[] { TabletsSection.ServerColumnFamily.DIRECTORY_COLUMN, TabletsSection.TabletColumnFamily.PREV_ROW_COLUMN, TabletsSection.TabletColumnFamily.SPLIT_RATIO_COLUMN, TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN, TabletsSection.ServerColumnFamily.TIME_COLUMN }); ScannerImpl scanner = new ScannerImpl(context, tableToVerify, Authorizations.EMPTY); scanner.setRange(extent.toMetadataRange()); TreeMap<Key, Value> tkv = new TreeMap<Key, Value>(); for (Entry<Key, Value> entry : scanner) tkv.put(entry.getKey(), entry.getValue()); // only populate map after success if (tabletsKeyValues == null) { tabletsKeyValues = tkv; } else { tabletsKeyValues.clear(); tabletsKeyValues.putAll(tkv); } Text metadataEntry = extent.getMetadataEntry(); Value dir = checkTabletMetadata(extent, instance, tabletsKeyValues, metadataEntry); if (dir == null) return null; Value oldPrevEndRow = null; for (Entry<Key, Value> entry : tabletsKeyValues.entrySet()) { if (TabletsSection.TabletColumnFamily.OLD_PREV_ROW_COLUMN.hasColumns(entry.getKey())) { oldPrevEndRow = entry.getValue(); } } if (oldPrevEndRow != null) { SortedMap<Text, SortedMap<ColumnFQ, Value>> tabletEntries; tabletEntries = MetadataTableUtil.getTabletEntries(tabletsKeyValues, columnsToFetch); KeyExtent fke; try { fke = MasterMetadataUtil.fixSplit(context, metadataEntry, tabletEntries.get(metadataEntry), instance, lock); } catch (IOException e) { log.error("Error fixing split " + metadataEntry); throw new AccumuloException(e.toString()); } if (!fke.equals(extent)) { return new Pair<Text, KeyExtent>(null, fke); } // reread and reverify metadata entries now that metadata entries were fixed tabletsKeyValues.clear(); return verifyTabletInformation(context, fke, instance, tabletsKeyValues, clientAddress, lock); } return new Pair<Text, KeyExtent>(new Text(dir.get()), null); }
From source file:com.aurel.track.exchange.track.importer.ImporterDropdownParser.java
private void addLabelBean(SortedMap<String, List<ISerializableLabelBean>> dropDowns, Map<String, String> attributesMap, String name) { ISerializableLabelBean labelBean = null; if (name == ExchangeFieldNames.COSTCENTER) { labelBean = new TCostCenterBean().deserializeBean(attributesMap); }// w w w . j a va 2 s . c o m if (name == ExchangeFieldNames.ACCOUNT) { labelBean = new TAccountBean().deserializeBean(attributesMap); } if (name == ExchangeFieldNames.DEPARTMENT) { labelBean = new TDepartmentBean().deserializeBean(attributesMap); } if (name == ExchangeFieldNames.SYSTEMSTATE) { labelBean = new TSystemStateBean().deserializeBean(attributesMap); } if (name == ExchangeFieldNames.PROJECTTYPE) { labelBean = new TProjectTypeBean().deserializeBean(attributesMap); } if (name == ExchangeFieldNames.LIST) { labelBean = new TListBean().deserializeBean(attributesMap); } if (name == ExchangeFieldNames.OPTION) { labelBean = new TOptionBean().deserializeBean(attributesMap); } if (name == ExchangeFieldNames.FIELDCONFIG) { labelBean = new TFieldConfigBean().deserializeBean(attributesMap); } if (name == ExchangeFieldNames.OPTIONSETTINGS) { labelBean = new TOptionSettingsBean().deserializeBean(attributesMap); } if (name == ExchangeFieldNames.TEXTBOXSETTINGS) { labelBean = new TTextBoxSettingsBean().deserializeBean(attributesMap); } if (name == ExchangeFieldNames.GENERALSETTINGS) { labelBean = new TGeneralSettingsBean().deserializeBean(attributesMap); } if (name == ExchangeFieldNames.ROLE) { labelBean = new TRoleBean().deserializeBean(attributesMap); } if (name == ExchangeFieldNames.ACL) { labelBean = new TAccessControlListBean().deserializeBean(attributesMap); } if (name == ExchangeFieldNames.LINKED_ITEMS) { labelBean = new TWorkItemBean().deserializeBean(attributesMap); } if (labelBean == null) { LOGGER.warn("Deserialized labelBean is null for " + name); } else { List<ISerializableLabelBean> labelBeanList = dropDowns.get(name); if (labelBeanList == null) { labelBeanList = new ArrayList<ISerializableLabelBean>(); dropDowns.put(name, labelBeanList); } labelBeanList.add(labelBean); } }
From source file:richtercloud.reflection.form.builder.fieldhandler.MappingFieldHandler.java
/** * Figures out candidates which the longest common prefix in the * {@code fieldParameterizedType} chain of (nested) generic types ignoring * specifications of {@link AnyType}. Then determines the candidates with * the smallest number of {@link AnyType} specifications in the chain. If * there're multiple with the same number of {@link AnyType} chooses the * first it finds which might lead to random choices. * * @param fieldParameterizedType the chain of generic types (remember to * retrieve this information with {@link Field#getGenericType() } instead of * {@link Field#getType() } from fields) * @return the choice result as described above or {@code null} if no * candidate exists/*from www . j a v a 2 s .c o m*/ */ protected Type retrieveClassMappingBestMatch(ParameterizedType fieldParameterizedType) { //check in a row (walking a tree doesn't make sense because it's //agnostic of the position of the type SortedMap<Integer, List<ParameterizedType>> candidates = new TreeMap<>(); //TreeMap is a SortedMap for (Type mappingType : classMapping.keySet()) { if (!(mappingType instanceof ParameterizedType)) { continue; } ParameterizedType mappingParameterizedType = (ParameterizedType) mappingType; if (!mappingParameterizedType.getRawType().equals(fieldParameterizedType.getRawType())) { continue; } Type[] parameterizedTypeArguments = mappingParameterizedType.getActualTypeArguments(); Type[] fieldParameterizedTypeArguments = fieldParameterizedType.getActualTypeArguments(); for (int i = 0; i < Math.min(parameterizedTypeArguments.length, fieldParameterizedTypeArguments.length); i++) { if (fieldParameterizedTypeArguments[i].equals(AnyType.class)) { throw new IllegalArgumentException(String.format( "type %s must only be used to declare placeholders in class mapping, not in classes (was used in field type %s", AnyType.class, fieldParameterizedType)); } // only compare raw type to raw type in the chain Type fieldParameterizedTypeArgument = fieldParameterizedTypeArguments[i]; if (fieldParameterizedTypeArgument instanceof ParameterizedType) { fieldParameterizedTypeArgument = ((ParameterizedType) fieldParameterizedTypeArgument) .getRawType(); } Type parameterizedTypeArgument = parameterizedTypeArguments[i]; if (parameterizedTypeArgument instanceof ParameterizedType) { parameterizedTypeArgument = ((ParameterizedType) parameterizedTypeArgument).getRawType(); } //record AnyType matches as well boolean anyTypeMatch = AnyType.class.equals(parameterizedTypeArgument); //work around sucky debugger if (!parameterizedTypeArgument.equals(fieldParameterizedTypeArgument) && !anyTypeMatch) { break; } int matchCount = i + 1; List<ParameterizedType> candidateList = candidates.get(matchCount); if (candidateList == null) { candidateList = new LinkedList<>(); candidates.put(matchCount, candidateList); } candidateList.add(mappingParameterizedType); } } if (candidates.isEmpty()) { return null; //avoid NoSuchElementException } List<ParameterizedType> higestCandidatesList = candidates.get(candidates.lastKey()); int lowestAnyCount = Integer.MAX_VALUE; ParameterizedType lowestAnyCountCandidate = null; for (ParameterizedType highestCandidateCandidate : higestCandidatesList) { int highestCandidateCandidateAnyCount = retrieveAnyCountRecursively(highestCandidateCandidate); if (highestCandidateCandidateAnyCount < lowestAnyCount) { lowestAnyCount = highestCandidateCandidateAnyCount; lowestAnyCountCandidate = highestCandidateCandidate; } } return lowestAnyCountCandidate; }