Search in sources :

Example 21 with TreeMap

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);
    }
}
Also used : JavaDepsFinder(com.facebook.buck.jvm.java.autodeps.JavaDepsFinder) SortedSet(java.util.SortedSet) TreeSet(java.util.TreeSet) Set(java.util.Set) HashMap(java.util.HashMap) JavaFileParser(com.facebook.buck.jvm.java.JavaFileParser) SourcePath(com.facebook.buck.rules.SourcePath) PathSourcePath(com.facebook.buck.rules.PathSourcePath) TreeSet(java.util.TreeSet) JavaLibraryDescription(com.facebook.buck.jvm.java.JavaLibraryDescription) PathSourcePath(com.facebook.buck.rules.PathSourcePath) TreeMap(java.util.TreeMap) MutableDirectedGraph(com.facebook.buck.graph.MutableDirectedGraph)

Example 22 with TreeMap

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())));
    }
}
Also used : TreeMap(java.util.TreeMap) BuildTarget(com.facebook.buck.model.BuildTarget) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) BuildRule(com.facebook.buck.rules.BuildRule) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) TreeMap(java.util.TreeMap) Tool(com.facebook.buck.rules.Tool)

Example 23 with TreeMap

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;
}
Also used : HolidayDetails(org.mifos.dto.domain.HolidayDetails) MessageLookup(org.mifos.application.master.MessageLookup) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) HolidayBO(org.mifos.application.holiday.business.HolidayBO) TreeMap(java.util.TreeMap) OfficeHoliday(org.mifos.dto.domain.OfficeHoliday)

Example 24 with TreeMap

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);
    }
}
Also used : AccountPenaltiesEntity(org.mifos.accounts.business.AccountPenaltiesEntity) RatePenaltyBO(org.mifos.accounts.penalties.business.RatePenaltyBO) CustomerLevel(org.mifos.customers.api.CustomerLevel) PenaltyBO(org.mifos.accounts.penalties.business.PenaltyBO) RatePenaltyBO(org.mifos.accounts.penalties.business.RatePenaltyBO) UserContext(org.mifos.security.util.UserContext) LoanBO(org.mifos.accounts.loan.business.LoanBO) MifosUser(org.mifos.security.MifosUser) TreeMap(java.util.TreeMap) BigDecimal(java.math.BigDecimal) AccountBO(org.mifos.accounts.business.AccountBO) BusinessRuleException(org.mifos.service.BusinessRuleException) AccountBusinessService(org.mifos.accounts.business.service.AccountBusinessService) ApplicationException(org.mifos.framework.exceptions.ApplicationException) ServiceException(org.mifos.framework.exceptions.ServiceException) FeeBO(org.mifos.accounts.fees.business.FeeBO) RateFeeBO(org.mifos.accounts.fees.business.RateFeeBO) Map(java.util.Map) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) MifosRuntimeException(org.mifos.core.MifosRuntimeException)

Example 25 with TreeMap

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());
}
Also used : DescriptiveStatistics(org.apache.commons.math.stat.descriptive.DescriptiveStatistics) StringWriter(java.io.StringWriter) ArrayList(java.util.ArrayList) List(java.util.List) TreeMap(java.util.TreeMap)

Aggregations

TreeMap (java.util.TreeMap)4328 Map (java.util.Map)1215 ArrayList (java.util.ArrayList)908 HashMap (java.util.HashMap)848 Test (org.junit.Test)610 List (java.util.List)530 Before (org.junit.Before)504 IOException (java.io.IOException)390 HashSet (java.util.HashSet)292 File (java.io.File)260 Set (java.util.Set)258 SortedMap (java.util.SortedMap)238 TreeSet (java.util.TreeSet)208 LinkedHashMap (java.util.LinkedHashMap)181 Key (org.apache.accumulo.core.data.Key)156 Value (org.apache.accumulo.core.data.Value)156 Iterator (java.util.Iterator)147 NavigableMap (java.util.NavigableMap)124 Collection (java.util.Collection)111 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)110