use of java.util.TreeMap in project buck by facebook.
the class FineGrainedJavaDependencySuggester method suggestRefactoring.
/**
* Suggests a refactoring by printing it to stdout (with warnings printed to stderr).
* @throws IllegalArgumentException
*/
void suggestRefactoring() {
final TargetNode<?, ?> suggestedNode = graph.get(suggestedTarget);
if (!(suggestedNode.getConstructorArg() instanceof JavaLibraryDescription.Arg)) {
console.printErrorText(String.format("'%s' does not correspond to a Java rule", suggestedTarget));
throw new IllegalArgumentException();
}
JavaLibraryDescription.Arg arg = (JavaLibraryDescription.Arg) suggestedNode.getConstructorArg();
JavaFileParser javaFileParser = javaDepsFinder.getJavaFileParser();
Multimap<String, String> providedSymbolToRequiredSymbols = HashMultimap.create();
Map<String, PathSourcePath> providedSymbolToSrc = new HashMap<>();
for (SourcePath src : arg.srcs) {
extractProvidedSymbolInfoFromSourceFile(src, javaFileParser, providedSymbolToRequiredSymbols, providedSymbolToSrc);
}
// Create a MutableDirectedGraph from the providedSymbolToRequiredSymbols.
MutableDirectedGraph<String> symbolsDependencies = new MutableDirectedGraph<>();
// dependencies.
for (String providedSymbol : providedSymbolToSrc.keySet()) {
// Add a node for the providedSymbol in case it has no edges.
symbolsDependencies.addNode(providedSymbol);
for (String requiredSymbol : providedSymbolToRequiredSymbols.get(providedSymbol)) {
if (providedSymbolToRequiredSymbols.containsKey(requiredSymbol) && !providedSymbol.equals(requiredSymbol)) {
symbolsDependencies.addEdge(providedSymbol, requiredSymbol);
}
}
}
// Determine the strongly connected components.
Set<Set<String>> stronglyConnectedComponents = symbolsDependencies.findStronglyConnectedComponents();
// Maps a providedSymbol to the component that contains it.
Map<String, NamedStronglyConnectedComponent> namedComponentsIndex = new TreeMap<>();
Set<NamedStronglyConnectedComponent> namedComponents = new TreeSet<>();
for (Set<String> stronglyConnectedComponent : stronglyConnectedComponents) {
// We just use the first provided symbol in the strongly connected component as the canonical
// name for the component. Maybe not the best name, but certainly not the worst.
String name = Iterables.getFirst(stronglyConnectedComponent, /* defaultValue */
null);
if (name == null) {
throw new IllegalStateException("A strongly connected component was created with zero nodes.");
}
NamedStronglyConnectedComponent namedComponent = new NamedStronglyConnectedComponent(name, stronglyConnectedComponent);
namedComponents.add(namedComponent);
for (String providedSymbol : stronglyConnectedComponent) {
namedComponentsIndex.put(providedSymbol, namedComponent);
}
}
// Visibility argument.
StringBuilder visibilityBuilder = new StringBuilder(" visibility = [\n");
SortedSet<String> visibilities = FluentIterable.from(suggestedNode.getVisibilityPatterns()).transform(VisibilityPattern::getRepresentation).toSortedSet(Ordering.natural());
for (String visibility : visibilities) {
visibilityBuilder.append(" '" + visibility + "',\n");
}
visibilityBuilder.append(" ],\n");
String visibilityArg = visibilityBuilder.toString();
// Print out the new version of the original rule.
console.getStdOut().printf("java_library(\n" + " name = '%s',\n" + " exported_deps = [\n", suggestedTarget.getShortName());
for (NamedStronglyConnectedComponent namedComponent : namedComponents) {
console.getStdOut().printf(" ':%s',\n", namedComponent.name);
}
console.getStdOut().print(" ],\n" + visibilityArg + ")\n");
// Print out a rule for each of the strongly connected components.
JavaDepsFinder.DependencyInfo dependencyInfo = javaDepsFinder.findDependencyInfoForGraph(graph);
for (NamedStronglyConnectedComponent namedComponent : namedComponents) {
String buildRuleDefinition = createBuildRuleDefinition(namedComponent, providedSymbolToSrc, providedSymbolToRequiredSymbols, namedComponentsIndex, dependencyInfo, symbolsDependencies, visibilityArg);
console.getStdOut().print(buildRuleDefinition);
}
}
use of java.util.TreeMap in project buck by facebook.
the class DDescriptionUtils method requireBuildRule.
/**
* Ensures that a DCompileBuildRule exists for the given target, creating a DCompileBuildRule
* if neccesary.
* @param baseParams build parameters for the rule
* @param buildRuleResolver BuildRuleResolver the rule should be in
* @param src the source file to be compiled
* @param compilerFlags flags to pass to the compiler
* @param compileTarget the target the rule should be for
* @param dBuckConfig the Buck configuration for D
* @return the build rule
*/
public static DCompileBuildRule requireBuildRule(BuildTarget compileTarget, BuildRuleParams baseParams, BuildRuleResolver buildRuleResolver, SourcePathRuleFinder ruleFinder, DBuckConfig dBuckConfig, ImmutableList<String> compilerFlags, String name, SourcePath src, DIncludes includes) throws NoSuchBuildTargetException {
Optional<BuildRule> existingRule = buildRuleResolver.getRuleOptional(compileTarget);
if (existingRule.isPresent()) {
return (DCompileBuildRule) existingRule.get();
} else {
Tool compiler = dBuckConfig.getDCompiler();
Map<BuildTarget, DIncludes> transitiveIncludes = new TreeMap<>();
transitiveIncludes.put(baseParams.getBuildTarget(), includes);
for (Map.Entry<BuildTarget, DLibrary> library : getTransitiveDLibraryRules(baseParams.getDeps()).entrySet()) {
transitiveIncludes.put(library.getKey(), library.getValue().getIncludes());
}
ImmutableSortedSet.Builder<BuildRule> depsBuilder = ImmutableSortedSet.naturalOrder();
depsBuilder.addAll(compiler.getDeps(ruleFinder));
depsBuilder.addAll(ruleFinder.filterBuildRuleInputs(src));
for (DIncludes dIncludes : transitiveIncludes.values()) {
depsBuilder.addAll(dIncludes.getDeps(ruleFinder));
}
ImmutableSortedSet<BuildRule> deps = depsBuilder.build();
return buildRuleResolver.addToIndex(new DCompileBuildRule(baseParams.withBuildTarget(compileTarget).copyReplacingDeclaredAndExtraDeps(Suppliers.ofInstance(deps), Suppliers.ofInstance(ImmutableSortedSet.of())), compiler, ImmutableList.<String>builder().addAll(dBuckConfig.getBaseCompilerFlags()).addAll(compilerFlags).build(), name, ImmutableSortedSet.of(src), ImmutableList.copyOf(transitiveIncludes.values())));
}
}
use of java.util.TreeMap in project head by mifos.
the class HolidayServiceFacadeWebTier method holidaysByYear.
@Override
public Map<String, List<OfficeHoliday>> holidaysByYear() {
List<HolidayBO> holidays = this.holidayDao.findAllHolidays();
Map<String, List<OfficeHoliday>> holidaysByYear = new TreeMap<String, List<OfficeHoliday>>();
for (HolidayBO holiday : holidays) {
HolidayDetails holidayDetail = new HolidayDetails(holiday.getHolidayName(), holiday.getHolidayFromDate(), holiday.getHolidayThruDate(), holiday.getRepaymentRuleType().getValue());
String holidayRepaymentRuleName = ApplicationContextProvider.getBean(MessageLookup.class).lookup(holiday.getRepaymentRuleType().getPropertiesKey());
holidayDetail.setRepaymentRuleName(holidayRepaymentRuleName);
int year = holiday.getThruDate().getYear();
List<OfficeHoliday> holidaysInYear = holidaysByYear.get(Integer.toString(year));
if (holidaysInYear == null) {
holidaysInYear = new LinkedList<OfficeHoliday>();
}
holidaysInYear.add(new OfficeHoliday(holidayDetail, this.holidayDao.applicableOffices(holiday.getId())));
holidaysByYear.put(Integer.toString(year), holidaysInYear);
}
sortValuesByFromDate(holidaysByYear);
return holidaysByYear;
}
use of java.util.TreeMap in project head by mifos.
the class WebTierAccountServiceFacade method applyGroupCharge.
@Override
public void applyGroupCharge(Map<Integer, String> idsAndValues, Short chargeId, boolean isPenaltyType) {
MifosUser user = (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
UserContext userContext = toUserContext(user);
TreeMap<Integer, String> idsAndValueAsTreeMap = new TreeMap<Integer, String>(idsAndValues);
try {
AccountBO parentAccount = ((LoanBO) legacyAccountDao.getAccount(new AccountBusinessService().getAccount(idsAndValueAsTreeMap.firstKey()).getAccountId())).getParentAccount();
BigDecimal parentAmount = ((LoanBO) parentAccount).getLoanAmount().getAmount();
BigDecimal membersAmount = BigDecimal.ZERO;
for (Map.Entry<Integer, String> entry : idsAndValues.entrySet()) {
LoanBO individual = loanDao.findById(entry.getKey());
Double chargeAmount = Double.valueOf(entry.getValue());
if (chargeAmount.equals(0.0)) {
continue;
}
membersAmount = membersAmount.add(individual.getLoanAmount().getAmount());
individual.updateDetails(userContext);
if (isPenaltyType && !chargeId.equals(Short.valueOf(AccountConstants.MISC_PENALTY))) {
PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue());
individual.addAccountPenalty(new AccountPenaltiesEntity(individual, penalty, chargeAmount));
} else {
individual.applyCharge(chargeId, chargeAmount);
}
}
boolean isRateCharge = false;
if (!chargeId.equals(Short.valueOf(AccountConstants.MISC_FEES)) && !chargeId.equals(Short.valueOf(AccountConstants.MISC_PENALTY))) {
if (isPenaltyType) {
PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue());
if (penalty instanceof RatePenaltyBO) {
isRateCharge = true;
}
} else {
FeeBO fee = feeDao.findById(chargeId);
if (fee.getFeeType().equals(RateAmountFlag.RATE)) {
isRateCharge = true;
}
}
}
Double chargeAmount = null;
if (!isRateCharge) {
chargeAmount = sumCharge(idsAndValues);
} else {
chargeAmount = Double.valueOf(idsAndValueAsTreeMap.firstEntry().getValue());
BigDecimal chargeAmountBig = new BigDecimal(chargeAmount);
membersAmount = membersAmount.multiply(chargeAmountBig);
int scale = Money.getInternalPrecision();
chargeAmountBig = membersAmount.divide(parentAmount, scale, RoundingMode.HALF_EVEN);
chargeAmount = chargeAmountBig.doubleValue();
}
parentAccount.updateDetails(userContext);
CustomerLevel customerLevel = null;
if (parentAccount.isCustomerAccount()) {
customerLevel = parentAccount.getCustomer().getLevel();
}
if (parentAccount.getPersonnel() != null) {
checkPermissionForApplyCharges(parentAccount.getType(), customerLevel, userContext, parentAccount.getOffice().getOfficeId(), parentAccount.getPersonnel().getPersonnelId());
} else {
checkPermissionForApplyCharges(parentAccount.getType(), customerLevel, userContext, parentAccount.getOffice().getOfficeId(), userContext.getId());
}
this.transactionHelper.startTransaction();
if (isPenaltyType && parentAccount instanceof LoanBO) {
PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue());
((LoanBO) parentAccount).addAccountPenalty(new AccountPenaltiesEntity(parentAccount, penalty, chargeAmount));
} else {
parentAccount.applyCharge(chargeId, chargeAmount);
}
this.transactionHelper.commitTransaction();
} catch (ServiceException e) {
this.transactionHelper.rollbackTransaction();
throw new MifosRuntimeException(e);
} catch (ApplicationException e) {
this.transactionHelper.rollbackTransaction();
throw new BusinessRuleException(e.getKey(), e);
}
}
use of java.util.TreeMap in project pinot by linkedin.
the class PinotZKChanger method printSegmentAssignment.
protected void printSegmentAssignment(Map<String, Map<String, String>> mapping) throws Exception {
StringWriter sw = new StringWriter();
objectMapper.writerWithDefaultPrettyPrinter().writeValue(sw, mapping);
LOGGER.info(sw.toString());
Map<String, List<String>> serverToSegmentMapping = new TreeMap<>();
for (String segment : mapping.keySet()) {
Map<String, String> serverToStateMap = mapping.get(segment);
for (String server : serverToStateMap.keySet()) {
if (!serverToSegmentMapping.containsKey(server)) {
serverToSegmentMapping.put(server, new ArrayList<String>());
}
serverToSegmentMapping.get(server).add(segment);
}
}
DescriptiveStatistics stats = new DescriptiveStatistics();
for (String server : serverToSegmentMapping.keySet()) {
List<String> list = serverToSegmentMapping.get(server);
LOGGER.info("server " + server + " has " + list.size() + " segments");
stats.addValue(list.size());
}
LOGGER.info("Segment Distrbution stat");
LOGGER.info(stats.toString());
}
Aggregations