Example usage for java.util SortedMap containsKey

List of usage examples for java.util SortedMap containsKey

Introduction

In this page you can find the example usage for java.util SortedMap containsKey.

Prototype

boolean containsKey(Object key);

Source Link

Document

Returns true if this map contains a mapping for the specified key.

Usage

From source file:org.kuali.coeus.common.budget.impl.calculator.BudgetCalculationServiceImpl.java

@Deprecated
@Override// w ww  .  j  a  v a 2s.c o m
public void calculateBudgetSummaryTotals(Budget budget) {
    calculateBudgetTotals(budget);

    //Categorize all Object Codes per their Category Type
    SortedMap<BudgetCategoryType, List<CostElement>> objectCodeListByBudgetCategoryType = categorizeObjectCodesByCategory(
            budget);

    SortedMap<CostElement, List<BudgetPersonnelDetails>> objectCodeUniquePersonnelList = new TreeMap<>();

    SortedMap<String, List<ScaleTwoDecimal>> objectCodePersonnelSalaryTotals = new TreeMap<>();
    SortedMap<String, List<ScaleTwoDecimal>> objectCodePersonnelFringeTotals = new TreeMap<>();

    //Temp collections for maintaining Sub Section Totals
    SortedSet<String> objectCodePersonnelSalaryTotalsByPeriod = new TreeSet<>();
    SortedSet<String> objectCodePersonnelFringeTotalsByPeriod = new TreeSet<>();

    SortedMap<RateType, List<ScaleTwoDecimal>> personnelCalculatedExpenseTotals = new TreeMap<>();
    SortedMap<RateType, List<ScaleTwoDecimal>> nonPersonnelCalculatedExpenseTotals = new TreeMap<>();

    List<ScaleTwoDecimal> periodSummarySalaryTotals = new ArrayList<>();
    for (int i = 0; i < budget.getBudgetPeriods().size(); i++) {
        periodSummarySalaryTotals.add(i, ScaleTwoDecimal.ZERO);
    }
    List<ScaleTwoDecimal> periodSummaryFringeTotals = new ArrayList<>();
    for (int i = 0; i < budget.getBudgetPeriods().size(); i++) {
        periodSummaryFringeTotals.add(i, ScaleTwoDecimal.ZERO);
    }
    SortedMap<String, List<ScaleTwoDecimal>> subTotalsBySubSection = new TreeMap<>();
    subTotalsBySubSection.put("personnelSalaryTotals", periodSummarySalaryTotals);
    subTotalsBySubSection.put("personnelFringeTotals", periodSummaryFringeTotals);

    //Loop thru the Personnel Object Codes - to calculate Salary, Fringe Totals etc.. per person
    BudgetCategoryType personnelCategory = getPersonnelCategoryType();
    List<CostElement> personnelObjectCodes = objectCodeListByBudgetCategoryType.get(personnelCategory);

    if (CollectionUtils.isNotEmpty(personnelObjectCodes)) {
        for (CostElement personnelCostElement : personnelObjectCodes) {
            if (!objectCodeUniquePersonnelList.containsKey(personnelCostElement)) {
                objectCodeUniquePersonnelList.put(personnelCostElement,
                        new ArrayList<BudgetPersonnelDetails>());
            }

            for (BudgetPeriod budgetPeriod : budget.getBudgetPeriods()) {
                budgetPeriod.setBudget(budget);
                QueryList<BudgetLineItem> lineItemQueryList = new QueryList<>();
                lineItemQueryList.addAll(budgetPeriod.getBudgetLineItems());
                Equals objectCodeEquals = new Equals("costElement", personnelCostElement.getCostElement());
                QueryList<BudgetLineItem> filteredLineItems = lineItemQueryList.filter(objectCodeEquals);
                QueryList<BudgetPersonnelDetails> personnelQueryList = new QueryList<>();

                //Loop thru the matching Line Items to gather personnel info
                for (BudgetLineItem matchingLineItem : filteredLineItems) {
                    personnelQueryList.addAll(matchingLineItem.getBudgetPersonnelDetailsList());
                }

                for (BudgetLineItem matchingLineItem : filteredLineItems) {
                    for (BudgetPersonnelDetails budgetPersonnelDetails : matchingLineItem
                            .getBudgetPersonnelDetailsList()) {
                        Equals personIdEquals = new Equals("personId", budgetPersonnelDetails.getPersonId());
                        QueryList personOccurrencesForSameObjectCode = personnelQueryList
                                .filter(personIdEquals);

                        //Calculate the Salary Totals for each Person
                        ScaleTwoDecimal personSalaryTotalsForCurrentPeriod = personOccurrencesForSameObjectCode
                                .sumObjects("salaryRequested");

                        if (!objectCodePersonnelSalaryTotals.containsKey(matchingLineItem.getCostElement() + ","
                                + budgetPersonnelDetails.getPersonId())) {
                            objectCodeUniquePersonnelList.get(matchingLineItem.getCostElementBO())
                                    .add(budgetPersonnelDetails);
                            // set up for all periods and put into map
                            List<ScaleTwoDecimal> periodTotals = new ArrayList<>();
                            for (int i = 0; i < budget.getBudgetPeriods().size(); i++) {
                                periodTotals.add(i, ScaleTwoDecimal.ZERO);
                            }
                            objectCodePersonnelSalaryTotals.put(matchingLineItem.getCostElement() + ","
                                    + budgetPersonnelDetails.getPersonId(), periodTotals);
                        }
                        //Setting the total lines here - so that they'll be set just once for a unique person within an Object Code
                        objectCodePersonnelSalaryTotals
                                .get(matchingLineItem.getCostElement() + ","
                                        + budgetPersonnelDetails.getPersonId())
                                .set(budgetPeriod.getBudgetPeriod() - 1, personSalaryTotalsForCurrentPeriod);
                        if (objectCodePersonnelSalaryTotalsByPeriod
                                .add(budgetPeriod.getBudgetPeriod().toString() + ","
                                        + matchingLineItem.getCostElement() + ","
                                        + budgetPersonnelDetails.getPersonId())) {
                            subTotalsBySubSection.get("personnelSalaryTotals").set(
                                    budgetPeriod.getBudgetPeriod() - 1,
                                    ((subTotalsBySubSection.get("personnelSalaryTotals")
                                            .get(budgetPeriod.getBudgetPeriod() - 1)))
                                                    .add(personSalaryTotalsForCurrentPeriod));
                        }

                        //Calculate the Fringe Totals for each Person
                        if (!objectCodePersonnelFringeTotals.containsKey(matchingLineItem.getCostElement() + ","
                                + budgetPersonnelDetails.getPersonId())) {
                            // set up for all periods and put into map
                            List<ScaleTwoDecimal> periodFringeTotals = new ArrayList<>();
                            for (int i = 0; i < budget.getBudgetPeriods().size(); i++) {
                                periodFringeTotals.add(i, ScaleTwoDecimal.ZERO);
                            }
                            objectCodePersonnelFringeTotals.put(matchingLineItem.getCostElement() + ","
                                    + budgetPersonnelDetails.getPersonId(), periodFringeTotals);
                        }
                        ScaleTwoDecimal personFringeTotalsForCurrentPeriod = ScaleTwoDecimal.ZERO;
                        //Calculate the Fringe Totals for that Person (cumulative fringe for all occurrences of the person)
                        for (Object person : personOccurrencesForSameObjectCode) {
                            BudgetPersonnelDetails personOccurrence = (BudgetPersonnelDetails) person;
                            for (BudgetPersonnelCalculatedAmount calcExpenseAmount : personOccurrence
                                    .getBudgetPersonnelCalculatedAmounts()) {
                                calcExpenseAmount.refreshReferenceObject("rateClass");
                                //Check for Employee Benefits RateClassType
                                if (calcExpenseAmount.getRateClass().getRateClassTypeCode()
                                        .equalsIgnoreCase("E")) {
                                    personFringeTotalsForCurrentPeriod = personFringeTotalsForCurrentPeriod
                                            .add(calcExpenseAmount.getCalculatedCost());
                                }
                            }
                        }
                        objectCodePersonnelFringeTotals
                                .get(matchingLineItem.getCostElement() + ","
                                        + budgetPersonnelDetails.getPersonId())
                                .set(budgetPeriod.getBudgetPeriod() - 1, personFringeTotalsForCurrentPeriod);

                        if (objectCodePersonnelFringeTotalsByPeriod
                                .add(budgetPeriod.getBudgetPeriod().toString() + ","
                                        + matchingLineItem.getCostElement() + ","
                                        + budgetPersonnelDetails.getPersonId())) {
                            subTotalsBySubSection.get("personnelFringeTotals").set(
                                    budgetPeriod.getBudgetPeriod() - 1,
                                    ((subTotalsBySubSection.get("personnelFringeTotals")
                                            .get(budgetPeriod.getBudgetPeriod() - 1)))
                                                    .add(personFringeTotalsForCurrentPeriod));
                        }
                    }

                    //Need to handle the Summary Items - if any
                    if (CollectionUtils.isEmpty(matchingLineItem.getBudgetPersonnelDetailsList())) {
                        //Include Summary Item Salary (Line Item Cost)
                        if (!objectCodePersonnelSalaryTotals.containsKey(matchingLineItem.getCostElement())) {
                            // set up for all periods and put into map
                            List<ScaleTwoDecimal> periodTotals = new ArrayList<>();
                            for (int i = 0; i < budget.getBudgetPeriods().size(); i++) {
                                periodTotals.add(i, ScaleTwoDecimal.ZERO);
                            }
                            objectCodePersonnelSalaryTotals.put(matchingLineItem.getCostElement(),
                                    periodTotals);
                        }
                        objectCodePersonnelSalaryTotals.get(matchingLineItem.getCostElement()).set(
                                budgetPeriod.getBudgetPeriod() - 1,
                                (objectCodePersonnelSalaryTotals.get(matchingLineItem.getCostElement())
                                        .get(budgetPeriod.getBudgetPeriod() - 1))
                                                .add(matchingLineItem.getLineItemCost()));

                        //Include Summary Item Fringe Amt
                        ScaleTwoDecimal summaryFringeTotalsForCurrentPeriod = ScaleTwoDecimal.ZERO;
                        if (!objectCodePersonnelFringeTotals.containsKey(matchingLineItem.getCostElement())) {
                            // set up for all periods and put into map
                            List<ScaleTwoDecimal> periodFringeTotals = new ArrayList<>();
                            for (int i = 0; i < budget.getBudgetPeriods().size(); i++) {
                                periodFringeTotals.add(i, ScaleTwoDecimal.ZERO);
                            }
                            objectCodePersonnelFringeTotals.put(matchingLineItem.getCostElement(),
                                    periodFringeTotals);
                        }

                        for (BudgetLineItemCalculatedAmount lineItemCalculatedAmount : matchingLineItem
                                .getBudgetLineItemCalculatedAmounts()) {
                            lineItemCalculatedAmount.refreshReferenceObject("rateClass");
                            //Check for Employee Benefits RateClassType
                            if (lineItemCalculatedAmount.getRateClass().getRateClassTypeCode()
                                    .equalsIgnoreCase("E")) {
                                summaryFringeTotalsForCurrentPeriod = summaryFringeTotalsForCurrentPeriod
                                        .add(lineItemCalculatedAmount.getCalculatedCost());
                            }
                        }
                        objectCodePersonnelFringeTotals.get(matchingLineItem.getCostElement()).set(
                                budgetPeriod.getBudgetPeriod() - 1,
                                (objectCodePersonnelFringeTotals.get(matchingLineItem.getCostElement())
                                        .get(budgetPeriod.getBudgetPeriod() - 1))
                                                .add(summaryFringeTotalsForCurrentPeriod));

                        subTotalsBySubSection.get("personnelSalaryTotals").set(
                                budgetPeriod.getBudgetPeriod() - 1,
                                ((subTotalsBySubSection.get("personnelSalaryTotals")
                                        .get(budgetPeriod.getBudgetPeriod() - 1)))
                                                .add((objectCodePersonnelSalaryTotals
                                                        .get(matchingLineItem.getCostElement())
                                                        .get(budgetPeriod.getBudgetPeriod() - 1))));
                        subTotalsBySubSection.get("personnelFringeTotals").set(
                                budgetPeriod.getBudgetPeriod() - 1,
                                ((subTotalsBySubSection.get("personnelFringeTotals")
                                        .get(budgetPeriod.getBudgetPeriod() - 1)))
                                                .add((objectCodePersonnelFringeTotals
                                                        .get(matchingLineItem.getCostElement())
                                                        .get(budgetPeriod.getBudgetPeriod() - 1))));
                    }
                }

            } //Budget Period Looping Ends here
        } //Personnel Object Code Looping Ends here
    }

    budget.setBudgetSummaryTotals(subTotalsBySubSection);
    personnelCalculatedExpenseTotals = calculateExpenseTotals(budget, true);
    nonPersonnelCalculatedExpenseTotals = calculateExpenseTotals(budget, false);

    budget.setObjectCodeListByBudgetCategoryType(objectCodeListByBudgetCategoryType);
    budget.setObjectCodePersonnelList(objectCodeUniquePersonnelList);
    budget.setObjectCodePersonnelSalaryTotals(objectCodePersonnelSalaryTotals);
    budget.setObjectCodePersonnelFringeTotals(objectCodePersonnelFringeTotals);
    budget.setPersonnelCalculatedExpenseTotals(personnelCalculatedExpenseTotals);
    budget.setNonPersonnelCalculatedExpenseTotals(nonPersonnelCalculatedExpenseTotals);
    calculateNonPersonnelSummaryTotals(budget);
    populateBudgetPeriodSummaryCalcAmounts(budget);
}

From source file:org.kuali.kfs.module.cam.batch.service.impl.AssetDepreciationServiceImpl.java

/**
 * This method stores in a collection of business objects the depreciation transaction that later on will be passed to the
 * processGeneralLedgerPendingEntry method in order to store the records in gl pending entry table
 *
 * @param assetPayment asset payment//from  www.j  a v  a  2  s  .  com
 * @param transactionType which can be [C]redit or [D]ebit
 * @param plantCOA plant fund char of account code
 * @param plantAccount plant fund char of account code
 * @param financialObject char of account object code linked to the payment
 * @param depreciationTransactionSummary
 * @return none
 */
protected void populateDepreciationTransaction(AssetPaymentInfo assetPayment, String transactionType,
        String plantCOA, String plantAccount, ObjectCode deprObjectCode,
        SortedMap<String, AssetDepreciationTransaction> depreciationTransactionSummary) {
    LOG.debug(
            "populateDepreciationTransaction(AssetDepreciationTransaction depreciationTransaction, AssetPayment assetPayment, String transactionType, KualiDecimal transactionAmount, String plantCOA, String plantAccount, String accumulatedDepreciationFinancialObjectCode, String depreciationExpenseFinancialObjectCode, ObjectCode financialObject, SortedMap<String, AssetDepreciationTransaction> depreciationTransactionSummary) -  started");
    LOG.debug(CamsConstants.Depreciation.DEPRECIATION_BATCH
            + "populateDepreciationTransaction(): populating AssetDepreciationTransaction pojo - Asset#:"
            + assetPayment.getCapitalAssetNumber());
    AssetDepreciationTransaction depreciationTransaction = new AssetDepreciationTransaction();
    depreciationTransaction.setCapitalAssetNumber(assetPayment.getCapitalAssetNumber());
    depreciationTransaction.setChartOfAccountsCode(plantCOA);
    depreciationTransaction.setAccountNumber(plantAccount);
    depreciationTransaction.setSubAccountNumber(assetPayment.getSubAccountNumber());
    depreciationTransaction.setFinancialObjectCode(deprObjectCode.getFinancialObjectCode());
    depreciationTransaction.setFinancialSubObjectCode(assetPayment.getFinancialSubObjectCode());
    depreciationTransaction.setFinancialObjectTypeCode(deprObjectCode.getFinancialObjectTypeCode());
    depreciationTransaction.setTransactionType(transactionType);
    depreciationTransaction.setProjectCode(assetPayment.getProjectCode());
    depreciationTransaction.setTransactionAmount(assetPayment.getTransactionAmount());
    depreciationTransaction.setTransactionLedgerEntryDescription(
            CamsConstants.Depreciation.TRANSACTION_DESCRIPTION + assetPayment.getCapitalAssetNumber());

    String sKey = depreciationTransaction.getKey();

    // Grouping the asset transactions by asset#, accounts, sub account, object, transaction type (C/D), etc. in order to
    // only have one credit and one credit by group.
    if (depreciationTransactionSummary.containsKey(sKey)) {
        depreciationTransaction = depreciationTransactionSummary.get(sKey);
        depreciationTransaction.setTransactionAmount(
                depreciationTransaction.getTransactionAmount().add(assetPayment.getTransactionAmount()));
    } else {
        depreciationTransactionSummary.put(sKey, depreciationTransaction);
    }
    LOG.debug(
            "populateDepreciationTransaction(AssetDepreciationTransaction depreciationTransaction, AssetPayment assetPayment, String transactionType, KualiDecimal transactionAmount, String plantCOA, String plantAccount, String accumulatedDepreciationFinancialObjectCode, String depreciationExpenseFinancialObjectCode, ObjectCode financialObject, SortedMap<String, AssetDepreciationTransaction> depreciationTransactionSummary) -  ended");
}

From source file:org.torproject.ernie.web.ExoneraTorServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    /* Start writing response. */
    PrintWriter out = response.getWriter();
    writeHeader(out);/* w  ww .ja v a  2 s. co m*/

    /* Look up first and last consensus in the database. */
    long firstValidAfter = -1L, lastValidAfter = -1L;
    try {
        Connection conn = this.ds.getConnection();
        Statement statement = conn.createStatement();
        String query = "SELECT MIN(validafter) AS first, " + "MAX(validafter) AS last FROM consensus";
        ResultSet rs = statement.executeQuery(query);
        if (rs.next()) {
            firstValidAfter = rs.getTimestamp(1).getTime();
            lastValidAfter = rs.getTimestamp(2).getTime();
        }
        rs.close();
        statement.close();
        conn.close();
    } catch (SQLException e) {
        /* Looks like we don't have any consensuses. */
    }
    if (firstValidAfter < 0L || lastValidAfter < 0L) {
        out.println("<p><font color=\"red\"><b>Warning: </b></font>This "
                + "server doesn't have any relay lists available. If this " + "problem persists, please "
                + "<a href=\"mailto:tor-assistants@freehaven.net\">let us " + "know</a>!</p>\n");
        writeFooter(out);
        return;
    }

    out.println("<a name=\"relay\"></a><h3>Was there a Tor relay running " + "on this IP address?</h3>");

    /* Parse IP parameter. */
    Pattern ipAddressPattern = Pattern
            .compile("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
                    + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
    String ipParameter = request.getParameter("ip");
    String relayIP = "", ipWarning = "";
    if (ipParameter != null && ipParameter.length() > 0) {
        Matcher ipParameterMatcher = ipAddressPattern.matcher(ipParameter);
        if (ipParameterMatcher.matches()) {
            String[] ipParts = ipParameter.split("\\.");
            relayIP = Integer.parseInt(ipParts[0]) + "." + Integer.parseInt(ipParts[1]) + "."
                    + Integer.parseInt(ipParts[2]) + "." + Integer.parseInt(ipParts[3]);
        } else {
            ipWarning = "\""
                    + (ipParameter.length() > 20 ? ipParameter.substring(0, 20) + "[...]" : ipParameter)
                    + "\" is not a valid IP address.";
        }
    }

    /* Parse timestamp parameter. */
    String timestampParameter = request.getParameter("timestamp");
    long timestamp = 0L;
    String timestampStr = "", timestampWarning = "";
    SimpleDateFormat shortDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    shortDateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    if (timestampParameter != null && timestampParameter.length() > 0) {
        try {
            timestamp = shortDateTimeFormat.parse(timestampParameter).getTime();
            timestampStr = shortDateTimeFormat.format(timestamp);
            if (timestamp < firstValidAfter || timestamp > lastValidAfter) {
                timestampWarning = "Please pick a value between \""
                        + shortDateTimeFormat.format(firstValidAfter) + "\" and \""
                        + shortDateTimeFormat.format(lastValidAfter) + "\".";
            }
        } catch (ParseException e) {
            /* We have no way to handle this exception, other than leaving
               timestampStr at "". */
            timestampWarning = "\""
                    + (timestampParameter.length() > 20 ? timestampParameter.substring(0, 20) + "[...]"
                            : timestampParameter)
                    + "\" is not a valid timestamp.";
        }
    }

    /* If either IP address or timestamp is provided, the other one must
     * be provided, too. */
    if (relayIP.length() < 1 && timestampStr.length() > 0 && ipWarning.length() < 1) {
        ipWarning = "Please provide an IP address.";
    }
    if (relayIP.length() > 0 && timestampStr.length() < 1 && timestampWarning.length() < 1) {
        timestampWarning = "Please provide a timestamp.";
    }

    /* Parse target IP parameter. */
    String targetIP = "", targetPort = "", target = "";
    String[] targetIPParts = null;
    String targetAddrParameter = request.getParameter("targetaddr");
    String targetAddrWarning = "";
    if (targetAddrParameter != null && targetAddrParameter.length() > 0) {
        Matcher targetAddrParameterMatcher = ipAddressPattern.matcher(targetAddrParameter);
        if (targetAddrParameterMatcher.matches()) {
            String[] targetAddrParts = targetAddrParameter.split("\\.");
            targetIP = Integer.parseInt(targetAddrParts[0]) + "." + Integer.parseInt(targetAddrParts[1]) + "."
                    + Integer.parseInt(targetAddrParts[2]) + "." + Integer.parseInt(targetAddrParts[3]);
            target = targetIP;
            targetIPParts = targetIP.split("\\.");
        } else {
            targetAddrWarning = "\""
                    + (targetAddrParameter.length() > 20 ? timestampParameter.substring(0, 20) + "[...]"
                            : timestampParameter)
                    + "\" is not a valid IP address.";
        }
    }

    /* Parse target port parameter. */
    String targetPortParameter = request.getParameter("targetport");
    String targetPortWarning = "";
    if (targetPortParameter != null && targetPortParameter.length() > 0) {
        Pattern targetPortPattern = Pattern.compile("\\d+");
        if (targetPortParameter.length() < 5 && targetPortPattern.matcher(targetPortParameter).matches()
                && !targetPortParameter.equals("0") && Integer.parseInt(targetPortParameter) < 65536) {
            targetPort = targetPortParameter;
            if (target != null) {
                target += ":" + targetPort;
            } else {
                target = targetPort;
            }
        } else {
            targetPortWarning = "\""
                    + (targetPortParameter.length() > 8 ? targetPortParameter.substring(0, 8) + "[...]"
                            : targetPortParameter)
                    + "\" is not a valid TCP port.";
        }
    }

    /* If target port is provided, a target address must be provided,
     * too. */
    if (targetPort.length() > 0 && targetIP.length() < 1 && targetAddrWarning.length() < 1) {
        targetAddrWarning = "Please provide an IP address.";
    }

    /* Write form with IP address and timestamp. */
    out.println("        <form action=\"exonerator.html#relay\">\n"
            + "          <input type=\"hidden\" name=\"targetaddr\" "
            + (targetIP.length() > 0 ? " value=\"" + targetIP + "\"" : "") + ">\n"
            + "          <input type=\"hidden\" name=\"targetPort\""
            + (targetPort.length() > 0 ? " value=\"" + targetPort + "\"" : "") + ">\n" + "          <table>\n"
            + "            <tr>\n" + "              <td align=\"right\">IP address in question:" + "</td>\n"
            + "              <td><input type=\"text\" name=\"ip\""
            + (relayIP.length() > 0 ? " value=\"" + relayIP + "\"" : "") + ">"
            + (ipWarning.length() > 0 ? "<br><font color=\"red\">" + ipWarning + "</font>" : "") + "</td>\n"
            + "              <td><i>(Ex.: 1.2.3.4)</i></td>\n" + "            </tr>\n" + "            <tr>\n"
            + "              <td align=\"right\">Timestamp, in UTC:</td>\n"
            + "              <td><input type=\"text\" name=\"timestamp\""
            + (timestampStr.length() > 0 ? " value=\"" + timestampStr + "\"" : "") + ">"
            + (timestampWarning.length() > 0 ? "<br><font color=\"red\">" + timestampWarning + "</font>" : "")
            + "</td>\n" + "              <td><i>(Ex.: 2010-01-01 12:00)</i></td>\n" + "            </tr>\n"
            + "            <tr>\n" + "              <td></td>\n" + "              <td>\n"
            + "                <input type=\"submit\">\n" + "                <input type=\"reset\">\n"
            + "              </td>\n" + "              <td></td>\n" + "            </tr>\n"
            + "          </table>\n" + "        </form>\n");

    if (relayIP.length() < 1 || timestampStr.length() < 1) {
        writeFooter(out);
        return;
    }

    /* Look up relevant consensuses. */
    long timestampTooOld = timestamp - 15L * 60L * 60L * 1000L;
    long timestampFrom = timestamp - 3L * 60L * 60L * 1000L;
    long timestampTooNew = timestamp + 12L * 60L * 60L * 1000L;
    out.printf(
            "<p>Looking up IP address %s in the relay lists published " + "between %s and %s. "
                    + "Clients could have used any of these relay lists to "
                    + "select relays for their paths and build circuits using them. "
                    + "You may follow the links to relay lists and relay descriptors "
                    + "to grep for the lines printed below and confirm that results " + "are correct.<br>",
            relayIP, shortDateTimeFormat.format(timestampFrom), timestampStr);
    SimpleDateFormat validAfterTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    validAfterTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    String fromValidAfter = validAfterTimeFormat.format(timestampTooOld);
    String toValidAfter = validAfterTimeFormat.format(timestampTooNew);
    SortedMap<Long, String> tooOldConsensuses = new TreeMap<Long, String>();
    SortedMap<Long, String> relevantConsensuses = new TreeMap<Long, String>();
    SortedMap<Long, String> tooNewConsensuses = new TreeMap<Long, String>();
    try {
        Connection conn = this.ds.getConnection();
        Statement statement = conn.createStatement();
        String query = "SELECT validafter, rawdesc FROM consensus " + "WHERE validafter >= '" + fromValidAfter
                + "' AND validafter <= '" + toValidAfter + "'";
        ResultSet rs = statement.executeQuery(query);
        while (rs.next()) {
            long consensusTime = rs.getTimestamp(1).getTime();
            String rawConsensusString = new String(rs.getBytes(2), "US-ASCII");
            if (consensusTime < timestampFrom) {
                tooOldConsensuses.put(consensusTime, rawConsensusString);
            } else if (consensusTime > timestamp) {
                tooNewConsensuses.put(consensusTime, rawConsensusString);
            } else {
                relevantConsensuses.put(consensusTime, rawConsensusString);
            }
        }
        rs.close();
        statement.close();
        conn.close();
    } catch (SQLException e) {
        /* Looks like we don't have any consensuses in the requested
           interval. */
    }
    SortedMap<Long, String> allConsensuses = new TreeMap<Long, String>();
    allConsensuses.putAll(tooOldConsensuses);
    allConsensuses.putAll(relevantConsensuses);
    allConsensuses.putAll(tooNewConsensuses);
    if (allConsensuses.isEmpty()) {
        out.println("        <p>No relay lists found!</p>\n" + "        <p>Result is INDECISIVE!</p>\n"
                + "        <p>We cannot make any statement whether there was "
                + "a Tor relay running on IP address " + relayIP + " at " + timestampStr + "! We "
                + "did not find any relevant relay lists preceding the given "
                + "time. If you think this is an error on our side, please "
                + "<a href=\"mailto:tor-assistants@freehaven.net\">contact " + "us</a>!</p>\n");
        writeFooter(out);
        return;
    }

    /* Parse consensuses to find descriptors belonging to the IP
       address. */
    SortedSet<Long> positiveConsensusesNoTarget = new TreeSet<Long>();
    Set<String> addressesInSameNetwork = new HashSet<String>();
    SortedMap<String, Set<Long>> relevantDescriptors = new TreeMap<String, Set<Long>>();
    SimpleDateFormat validAfterUrlFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    validAfterUrlFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    for (Map.Entry<Long, String> e : allConsensuses.entrySet()) {
        long consensus = e.getKey();
        if (relevantConsensuses.containsKey(consensus)) {
            long validAfterTime = -1L;
            String validAfterDatetime = validAfterTimeFormat.format(consensus);
            String validAfterString = validAfterUrlFormat.format(consensus);
            out.println("        <br><tt>valid-after <b>" + "<a href=\"consensus?valid-after="
                    + validAfterString + "\" target=\"_blank\">" + validAfterDatetime + "</b></a></tt><br>");
        }
        String rawConsensusString = e.getValue();
        BufferedReader br = new BufferedReader(new StringReader(rawConsensusString));
        String line = null;
        while ((line = br.readLine()) != null) {
            if (!line.startsWith("r ")) {
                continue;
            }
            String[] parts = line.split(" ");
            String address = parts[6];
            if (address.equals(relayIP)) {
                String hex = String.format("%040x", new BigInteger(1, Base64.decodeBase64(parts[3] + "==")));
                if (!relevantDescriptors.containsKey(hex)) {
                    relevantDescriptors.put(hex, new HashSet<Long>());
                }
                relevantDescriptors.get(hex).add(consensus);
                positiveConsensusesNoTarget.add(consensus);
                if (relevantConsensuses.containsKey(consensus)) {
                    out.println("    <tt>r " + parts[1] + " " + parts[2] + " " + "<a href=\"serverdesc?desc-id="
                            + hex + "\" " + "target=\"_blank\">" + parts[3] + "</a> " + parts[4] + " "
                            + parts[5] + " <b>" + parts[6] + "</b> " + parts[7] + " " + parts[8] + "</tt><br>");
                }
            } else {
                if (relayIP.startsWith(address.substring(0, address.lastIndexOf(".")))) {
                    addressesInSameNetwork.add(address);
                }
            }
        }
        br.close();
    }
    if (relevantDescriptors.isEmpty()) {
        out.printf(
                "        <p>None found!</p>\n" + "        <p>Result is NEGATIVE with moderate certainty!</p>\n"
                        + "        <p>We did not find IP " + "address " + relayIP
                        + " in any of the relay lists that were "
                        + "published between %s and %s.\n\nA possible "
                        + "reason for false negatives is that the relay is using a "
                        + "different IP address when generating a descriptor than for "
                        + "exiting to the Internet. We hope to provide better checks "
                        + "for this case in the future.</p>\n",
                shortDateTimeFormat.format(timestampTooOld), shortDateTimeFormat.format(timestampTooNew));
        if (!addressesInSameNetwork.isEmpty()) {
            out.println("        <p>The following other IP addresses of Tor "
                    + "relays were found in the mentioned relay lists that "
                    + "are in the same /24 network and that could be related to " + "IP address " + relayIP
                    + ":</p>\n");
            for (String s : addressesInSameNetwork) {
                out.println("        <p>" + s + "</p>\n");
            }
        }
        writeFooter(out);
        return;
    }

    /* Print out result. */
    Set<Long> matches = positiveConsensusesNoTarget;
    if (matches.contains(relevantConsensuses.lastKey())) {
        out.println("        <p>Result is POSITIVE with high certainty!" + "</p>\n"
                + "        <p>We found one or more relays on IP address " + relayIP
                + " in the most recent relay list preceding " + timestampStr
                + " that clients were likely to know.</p>\n");
    } else {
        boolean inOtherRelevantConsensus = false, inTooOldConsensuses = false, inTooNewConsensuses = false;
        for (long match : matches) {
            if (relevantConsensuses.containsKey(match)) {
                inOtherRelevantConsensus = true;
            } else if (tooOldConsensuses.containsKey(match)) {
                inTooOldConsensuses = true;
            } else if (tooNewConsensuses.containsKey(match)) {
                inTooNewConsensuses = true;
            }
        }
        if (inOtherRelevantConsensus) {
            out.println("        <p>Result is POSITIVE " + "with moderate certainty!</p>\n");
            out.println("<p>We found one or more relays on IP address " + relayIP
                    + ", but not in the relay list immediately " + "preceding " + timestampStr
                    + ". A possible reason for the "
                    + "relay being missing in the last relay list preceding the "
                    + "given time might be that some of the directory "
                    + "authorities had difficulties connecting to the relay. "
                    + "However, clients might still have used the relay.</p>\n");
        } else {
            out.println("        <p>Result is NEGATIVE " + "with high certainty!</p>\n");
            out.println("        <p>We did not find any relay on IP address " + relayIP
                    + " in the relay lists 3 hours preceding " + timestampStr + ".</p>\n");
            if (inTooOldConsensuses || inTooNewConsensuses) {
                if (inTooOldConsensuses && !inTooNewConsensuses) {
                    out.println("        <p>Note that we found a matching relay "
                            + "in relay lists that were published between 5 and 3 " + "hours before "
                            + timestampStr + ".</p>\n");
                } else if (!inTooOldConsensuses && inTooNewConsensuses) {
                    out.println("        <p>Note that we found a matching relay "
                            + "in relay lists that were published up to 2 hours " + "after " + timestampStr
                            + ".</p>\n");
                } else {
                    out.println("        <p>Note that we found a matching relay "
                            + "in relay lists that were published between 5 and 3 "
                            + "hours before and in relay lists that were published " + "up to 2 hours after "
                            + timestampStr + ".</p>\n");
                }
                out.println("<p>Make sure that the timestamp you provided is "
                        + "in the correct timezone: UTC (or GMT).</p>");
            }
            writeFooter(out);
            return;
        }
    }

    /* Second part: target */
    out.println("<br><a name=\"exit\"></a><h3>Was this relay configured "
            + "to permit exiting to a given target?</h3>");

    out.println("        <form action=\"exonerator.html#exit\">\n"
            + "              <input type=\"hidden\" name=\"timestamp\"\n" + "                         value=\""
            + timestampStr + "\">\n" + "              <input type=\"hidden\" name=\"ip\" " + "value=\""
            + relayIP + "\">\n" + "          <table>\n" + "            <tr>\n"
            + "              <td align=\"right\">Target address:</td>\n"
            + "              <td><input type=\"text\" name=\"targetaddr\""
            + (targetIP.length() > 0 ? " value=\"" + targetIP + "\"" : "") + "\">"
            + (targetAddrWarning.length() > 0 ? "<br><font color=\"red\">" + targetAddrWarning + "</font>" : "")
            + "</td>\n" + "              <td><i>(Ex.: 4.3.2.1)</i></td>\n" + "            </tr>\n"
            + "            <tr>\n" + "              <td align=\"right\">Target port:</td>\n"
            + "              <td><input type=\"text\" name=\"targetport\""
            + (targetPort.length() > 0 ? " value=\"" + targetPort + "\"" : "") + ">"
            + (targetPortWarning.length() > 0 ? "<br><font color=\"red\">" + targetPortWarning + "</font>" : "")
            + "</td>\n" + "              <td><i>(Ex.: 80)</i></td>\n" + "            </tr>\n"
            + "            <tr>\n" + "              <td></td>\n" + "              <td>\n"
            + "                <input type=\"submit\">\n" + "                <input type=\"reset\">\n"
            + "              </td>\n" + "              <td></td>\n" + "            </tr>\n"
            + "          </table>\n" + "        </form>\n");

    if (targetIP.length() < 1) {
        writeFooter(out);
        return;
    }

    /* Parse router descriptors to check exit policies. */
    out.println("<p>Searching the relay descriptors published by the " + "relay on IP address " + relayIP
            + " to find out whether this " + "relay permitted exiting to " + target + ". You may follow the "
            + "links above to the relay descriptors and grep them for the "
            + "lines printed below to confirm that results are correct.</p>");
    SortedSet<Long> positiveConsensuses = new TreeSet<Long>();
    Set<String> missingDescriptors = new HashSet<String>();
    Set<String> descriptors = relevantDescriptors.keySet();
    for (String descriptor : descriptors) {
        byte[] rawDescriptor = null;
        try {
            Connection conn = this.ds.getConnection();
            Statement statement = conn.createStatement();
            String query = "SELECT rawdesc FROM descriptor " + "WHERE descriptor = '" + descriptor + "'";
            ResultSet rs = statement.executeQuery(query);
            if (rs.next()) {
                rawDescriptor = rs.getBytes(1);
            }
            rs.close();
            statement.close();
            conn.close();
        } catch (SQLException e) {
            /* Consider this descriptors as 'missing'. */
            continue;
        }
        if (rawDescriptor != null && rawDescriptor.length > 0) {
            missingDescriptors.remove(descriptor);
            String rawDescriptorString = new String(rawDescriptor, "US-ASCII");
            try {
                BufferedReader br = new BufferedReader(new StringReader(rawDescriptorString));
                String line = null, routerLine = null, publishedLine = null;
                StringBuilder acceptRejectLines = new StringBuilder();
                boolean foundMatch = false;
                while ((line = br.readLine()) != null) {
                    if (line.startsWith("router ")) {
                        routerLine = line;
                    } else if (line.startsWith("published ")) {
                        publishedLine = line;
                    } else if (line.startsWith("reject ") || line.startsWith("accept ")) {
                        if (foundMatch) {
                            out.println("<tt> " + line + "</tt><br>");
                            continue;
                        }
                        boolean ruleAccept = line.split(" ")[0].equals("accept");
                        String ruleAddress = line.split(" ")[1].split(":")[0];
                        if (!ruleAddress.equals("*")) {
                            if (!ruleAddress.contains("/") && !ruleAddress.equals(targetIP)) {
                                /* IP address does not match. */
                                acceptRejectLines.append("<tt> " + line + "</tt><br>\n");
                                continue;
                            }
                            String[] ruleIPParts = ruleAddress.split("/")[0].split("\\.");
                            int ruleNetwork = ruleAddress.contains("/")
                                    ? Integer.parseInt(ruleAddress.split("/")[1])
                                    : 32;
                            for (int i = 0; i < 4; i++) {
                                if (ruleNetwork == 0) {
                                    break;
                                } else if (ruleNetwork >= 8) {
                                    if (ruleIPParts[i].equals(targetIPParts[i])) {
                                        ruleNetwork -= 8;
                                    } else {
                                        break;
                                    }
                                } else {
                                    int mask = 255 ^ 255 >>> ruleNetwork;
                                    if ((Integer.parseInt(ruleIPParts[i])
                                            & mask) == (Integer.parseInt(targetIPParts[i]) & mask)) {
                                        ruleNetwork = 0;
                                    }
                                    break;
                                }
                            }
                            if (ruleNetwork > 0) {
                                /* IP address does not match. */
                                acceptRejectLines.append("<tt> " + line + "</tt><br>\n");
                                continue;
                            }
                        }
                        String rulePort = line.split(" ")[1].split(":")[1];
                        if (targetPort.length() < 1 && !ruleAccept && !rulePort.equals("*")) {
                            /* With no port given, we only consider reject :* rules as
                               matching. */
                            acceptRejectLines.append("<tt> " + line + "</tt><br>\n");
                            continue;
                        }
                        if (targetPort.length() > 0 && !rulePort.equals("*") && rulePort.contains("-")) {
                            int fromPort = Integer.parseInt(rulePort.split("-")[0]);
                            int toPort = Integer.parseInt(rulePort.split("-")[1]);
                            int targetPortInt = Integer.parseInt(targetPort);
                            if (targetPortInt < fromPort || targetPortInt > toPort) {
                                /* Port not contained in interval. */
                                continue;
                            }
                        }
                        if (targetPort.length() > 0) {
                            if (!rulePort.equals("*") && !rulePort.contains("-")
                                    && !targetPort.equals(rulePort)) {
                                /* Ports do not match. */
                                acceptRejectLines.append("<tt> " + line + "</tt><br>\n");
                                continue;
                            }
                        }
                        boolean relevantMatch = false;
                        for (long match : relevantDescriptors.get(descriptor)) {
                            if (relevantConsensuses.containsKey(match)) {
                                relevantMatch = true;
                            }
                        }
                        if (relevantMatch) {
                            String[] routerParts = routerLine.split(" ");
                            out.println("<br><tt>" + routerParts[0] + " " + routerParts[1] + " <b>"
                                    + routerParts[2] + "</b> " + routerParts[3] + " " + routerParts[4] + " "
                                    + routerParts[5] + "</tt><br>");
                            String[] publishedParts = publishedLine.split(" ");
                            out.println("<tt>" + publishedParts[0] + " <b>" + publishedParts[1] + " "
                                    + publishedParts[2] + "</b></tt><br>");
                            out.println(acceptRejectLines.toString());
                            out.println("<tt><b>" + line + "</b></tt><br>");
                            foundMatch = true;
                        }
                        if (ruleAccept) {
                            positiveConsensuses.addAll(relevantDescriptors.get(descriptor));
                        }
                    }
                }
                br.close();
            } catch (IOException e) {
                /* Could not read descriptor string. */
                continue;
            }
        }
    }

    /* Print out result. */
    matches = positiveConsensuses;
    if (matches.contains(relevantConsensuses.lastKey())) {
        out.println("        <p>Result is POSITIVE with high certainty!</p>" + "\n"
                + "        <p>We found one or more relays on IP address " + relayIP + " permitting exit to "
                + target + " in the most recent relay list preceding " + timestampStr
                + " that clients were likely to know.</p>\n");
        writeFooter(out);
        return;
    }
    boolean resultIndecisive = target.length() > 0 && !missingDescriptors.isEmpty();
    if (resultIndecisive) {
        out.println("        <p>Result is INDECISIVE!</p>\n"
                + "        <p>At least one referenced descriptor could not be "
                + "found. This is a rare case, but one that (apparently) "
                + "happens. We cannot make any good statement about exit "
                + "relays without these descriptors. The following descriptors " + "are missing:</p>");
        for (String desc : missingDescriptors)
            out.println("        <p>" + desc + "</p>\n");
    }
    boolean inOtherRelevantConsensus = false, inTooOldConsensuses = false, inTooNewConsensuses = false;
    for (long match : matches) {
        if (relevantConsensuses.containsKey(match)) {
            inOtherRelevantConsensus = true;
        } else if (tooOldConsensuses.containsKey(match)) {
            inTooOldConsensuses = true;
        } else if (tooNewConsensuses.containsKey(match)) {
            inTooNewConsensuses = true;
        }
    }
    if (inOtherRelevantConsensus) {
        if (!resultIndecisive) {
            out.println("        <p>Result is POSITIVE " + "with moderate certainty!</p>\n");
        }
        out.println("<p>We found one or more relays on IP address " + relayIP + " permitting exit to " + target
                + ", but not in " + "the relay list immediately preceding " + timestampStr
                + ". A possible reason for the relay being missing in the last "
                + "relay list preceding the given time might be that some of "
                + "the directory authorities had difficulties connecting to "
                + "the relay. However, clients might still have used the " + "relay.</p>\n");
    } else {
        if (!resultIndecisive) {
            out.println("        <p>Result is NEGATIVE " + "with high certainty!</p>\n");
        }
        out.println("        <p>We did not find any relay on IP address " + relayIP + " permitting exit to "
                + target + " in the relay list 3 hours preceding " + timestampStr + ".</p>\n");
        if (inTooOldConsensuses || inTooNewConsensuses) {
            if (inTooOldConsensuses && !inTooNewConsensuses) {
                out.println("        <p>Note that we found a matching relay in "
                        + "relay lists that were published between 5 and 3 " + "hours before " + timestampStr
                        + ".</p>\n");
            } else if (!inTooOldConsensuses && inTooNewConsensuses) {
                out.println("        <p>Note that we found a matching relay in "
                        + "relay lists that were published up to 2 hours after " + timestampStr + ".</p>\n");
            } else {
                out.println("        <p>Note that we found a matching relay in "
                        + "relay lists that were published between 5 and 3 "
                        + "hours before and in relay lists that were published up " + "to 2 hours after "
                        + timestampStr + ".</p>\n");
            }
            out.println("<p>Make sure that the timestamp you provided is "
                    + "in the correct timezone: UTC (or GMT).</p>");
        }
    }
    if (target != null) {
        if (positiveConsensuses.isEmpty() && !positiveConsensusesNoTarget.isEmpty()) {
            out.println("        <p>Note that although the found relay(s) did " + "not permit exiting to "
                    + target + ", there have been one " + "or more relays running at the given time.</p>");
        }
    }

    /* Finish writing response. */
    writeFooter(out);
}

From source file:com.google.gwt.emultest.java.util.TreeMapTest.java

public void testSubMap_entrySet() {
    K[] keys = getSortedKeys();/*  www . j  ava  2 s.c  o  m*/
    V[] values = getSortedValues();
    NavigableMap<K, V> map = createNavigableMap();
    map.put(keys[0], values[0]);
    map.put(keys[1], values[1]);
    map.put(keys[2], values[2]);
    map.put(keys[3], values[3]);

    SortedMap<K, V> subMap = map.subMap(keys[1], keys[3]);
    Set<Entry<K, V>> entries = subMap.entrySet();
    assertEquals(2, subMap.size());
    assertEquals(subMap.size(), entries.size());
    assertFalse(entries.contains(new SimpleEntry<K, V>(keys[0], values[0])));
    assertTrue(entries.contains(new SimpleEntry<K, V>(keys[1], values[1])));
    assertTrue(entries.contains(new SimpleEntry<K, V>(keys[2], values[2])));
    assertFalse(entries.contains(new SimpleEntry<K, V>(keys[3], values[3])));

    entries.remove(new SimpleEntry<K, V>(keys[1], values[1]));
    assertEquals(3, map.size());
    assertEquals(subMap.size(), entries.size());
    assertFalse(entries.contains(new SimpleEntry<K, V>(keys[1], values[1])));
    assertFalse(subMap.containsKey(keys[1]));
    assertFalse(subMap.containsValue(values[1]));

    entries.clear();
    assertEquals(2, map.size());
    assertEquals(subMap.size(), entries.size());
    assertTrue(entries.isEmpty());
    assertTrue(subMap.isEmpty());

    subMap.put(keys[2], values[2]);
    assertEquals(1, subMap.size());
    assertEquals(subMap.size(), entries.size());

    subMap.put(keys[1], values[1]);
    Iterator<Entry<K, V>> it = entries.iterator();
    while (it.hasNext()) {
        Map.Entry<K, V> entry = it.next();
        subMap.containsKey(entry.getKey());
        subMap.containsValue(entry.getValue());
        it.remove();
    }
    try {
        it.next();
        fail("should throw NoSuchElementException");
    } catch (NoSuchElementException expected) {
    }
    assertEquals(2, map.size());
    assertEquals(0, subMap.size());
    assertEquals(subMap.size(), entries.size());

    map = createNavigableMap();
    Set<Entry<K, V>> entrySet = map.entrySet();
    map.put(keys[0], values[0]);
    map.put(keys[1], values[1]);
    map.put(keys[2], values[2]);
    assertEquals(map.size(), entrySet.size());
    _assertEquals(entrySet, map.entrySet());
    map.clear();
    assertEquals(map.size(), entrySet.size());
    _assertEquals(entrySet, map.entrySet());
    map.put(keys[0], values[0]);
    assertEquals(map.size(), entrySet.size());
    _assertEquals(entrySet, map.entrySet());
    entrySet.clear();
    assertEquals(map.size(), entrySet.size());
    _assertEquals(entrySet, map.entrySet());
}

From source file:org.kuali.coeus.common.budget.impl.calculator.BudgetCalculationServiceImpl.java

protected SortedMap<RateType, List<ScaleTwoDecimal>> calculateExpenseTotals(Budget budget,
        boolean personnelFlag) {
    SortedMap<RateType, List<ScaleTwoDecimal>> calculatedExpenseTotals = new TreeMap<>();

    List<ScaleTwoDecimal> calculatedDirectCostSummaryTotals = new ArrayList<>();
    for (int i = 0; i < budget.getBudgetPeriods().size(); i++) {
        calculatedDirectCostSummaryTotals.add(i, ScaleTwoDecimal.ZERO);
    }/*from  w w w.j av  a  2 s.com*/
    final String totalsMapKey;
    if (personnelFlag) {
        totalsMapKey = "personnelCalculatedExpenseSummaryTotals";
    } else {
        totalsMapKey = "nonPersonnelCalculatedExpenseSummaryTotals";
    }
    budget.getBudgetSummaryTotals().put(totalsMapKey, calculatedDirectCostSummaryTotals);

    for (BudgetPeriod budgetPeriod : budget.getBudgetPeriods()) {
        for (BudgetLineItem budgetLineItem : budgetPeriod.getBudgetLineItems()) {
            if ((personnelFlag && StringUtils.equals(
                    budgetLineItem.getCostElementBO().getBudgetCategory().getBudgetCategoryTypeCode(), "P"))
                    || (!personnelFlag && !StringUtils.equals(
                            budgetLineItem.getCostElementBO().getBudgetCategory().getBudgetCategoryTypeCode(),
                            "P"))) {
                // get calculated expenses                        
                QueryList<BudgetLineItemCalculatedAmount> lineItemCalcAmtQueryList = new QueryList<>();
                lineItemCalcAmtQueryList.addAll(budgetLineItem.getBudgetLineItemCalculatedAmounts());
                List<RateType> rateTypes = new ArrayList<>();

                for (Object item : budgetLineItem.getBudgetLineItemCalculatedAmounts()) {
                    BudgetLineItemCalculatedAmount budgetLineItemCalculatedAmount = (BudgetLineItemCalculatedAmount) item;
                    RateType rateType = createRateType(budgetLineItemCalculatedAmount);
                    RateClass rateClass = null;
                    if (rateType != null) {
                        rateType.refreshReferenceObject("rateClass");
                        rateClass = rateType.getRateClass();
                    }

                    if (((personnelFlag && rateClass != null
                            && !StringUtils.equals(rateClass.getRateClassTypeCode(), "E")) || !personnelFlag)
                            && !rateTypes.contains(rateType)) {
                        rateTypes.add(rateType);
                        Equals equalsRC = new Equals("rateClassCode",
                                budgetLineItemCalculatedAmount.getRateClassCode());
                        Equals equalsRT = new Equals("rateTypeCode",
                                budgetLineItemCalculatedAmount.getRateTypeCode());
                        And RCandRT = new And(equalsRC, equalsRT);
                        ScaleTwoDecimal rateTypeTotalInThisPeriod = lineItemCalcAmtQueryList
                                .sumObjects(CALCULATED_COST, RCandRT);
                        if (!calculatedExpenseTotals.containsKey(rateType)) {
                            List<ScaleTwoDecimal> rateTypePeriodTotals = new ArrayList<>();
                            for (int i = 0; i < budget.getBudgetPeriods().size(); i++) {
                                rateTypePeriodTotals.add(i, ScaleTwoDecimal.ZERO);
                            }
                            calculatedExpenseTotals.put(rateType, rateTypePeriodTotals);
                        }
                        calculatedExpenseTotals.get(rateType).set(budgetPeriod.getBudgetPeriod() - 1,
                                (calculatedExpenseTotals.get(rateType).get(budgetPeriod.getBudgetPeriod() - 1))
                                        .add(rateTypeTotalInThisPeriod));

                        if (!StringUtils.equals(rateClass.getRateClassTypeCode(),
                                RateClassType.OVERHEAD.getRateClassType())) {
                            budget.getBudgetSummaryTotals().get(totalsMapKey).set(
                                    budgetPeriod.getBudgetPeriod() - 1,
                                    ((budget.getBudgetSummaryTotals().get(totalsMapKey)
                                            .get(budgetPeriod.getBudgetPeriod() - 1)))
                                                    .add(rateTypeTotalInThisPeriod));
                        }

                        budgetPeriod
                                .setExpenseTotal(budgetPeriod.getExpenseTotal().add(rateTypeTotalInThisPeriod));
                    }
                }
            }

        }
    }

    return calculatedExpenseTotals;
}

From source file:com.google.gwt.emultest.java.util.TreeMapTest.java

public void testHeadMapLjava_lang_ObjectZL() {
    K[] keys = getSortedKeys();/* ww  w  .  java 2s.  c  o  m*/
    V[] values = getSortedValues();
    NavigableMap<K, V> map = createNavigableMap();
    for (int i = 0; i < keys.length; i++) {
        map.put(keys[i], values[i]);
    }

    // normal case
    SortedMap<K, V> subMap = map.headMap(keys[2], true);
    assertEquals(3, subMap.size());
    subMap = map.headMap(keys[3], true);
    assertEquals(4, subMap.size());
    for (int i = 0; i < 4; i++) {
        assertEquals(values[i], subMap.get(keys[i]));
    }
    subMap = map.headMap(keys[2], false);
    assertEquals(2, subMap.size());
    assertNull(subMap.get(keys[3]));

    // Exceptions
    assertEquals(0, map.headMap(keys[0], false).size());

    try {
        map.headMap(null, true);
        assertTrue("expected exception", useNullKey());
    } catch (NullPointerException e) {
        assertFalse("unexpected NPE", useNullKey());
    }

    try {
        map.headMap(null, false);
        assertTrue("expected exception", useNullKey());
    } catch (NullPointerException e) {
        assertFalse("unexpected NPE", useNullKey());
    }

    subMap = map.headMap(keys[2]);
    assertEquals(2, subMap.size());
    try {
        subMap.put(keys[2], values[2]);
        fail("should throw IllegalArgumentException");
    } catch (IllegalArgumentException expected) {
    }
    assertEquals(keys.length, map.size());
    subMap = map.headMap(keys[2], true);
    assertEquals(3, subMap.size());
    subMap.remove(keys[1]);
    assertFalse(subMap.containsKey(keys[1]));
    assertFalse(subMap.containsValue(values[1]));
    assertFalse(map.containsKey(keys[1]));
    assertFalse(map.containsValue(values[1]));
    assertEquals(2, subMap.size());
    assertEquals(keys.length - 1, map.size());

    subMap.put(keys[1], values[1]);

    try {
        subMap.subMap(keys[1], keys[3]);
        fail("should throw IllegalArgumentException");
    } catch (IllegalArgumentException expected) {
    }
    try {
        subMap.subMap(keys[3], keys[1]);
        fail("should throw IllegalArgumentException");
    } catch (IllegalArgumentException expected) {
    }

    if (useNullKey() && useNullValue()) {
        map.put(null, null);

        subMap = map.headMap(null, true);
        assertEquals(1, subMap.size());
        assertTrue(subMap.containsValue(null));
        assertNull(subMap.get(null));

        subMap = map.subMap(null, false, keys[2], true);
        assertEquals(3, subMap.size());

        Set<K> keySet = subMap.keySet();
        assertEquals(3, keySet.size());

        Set<Map.Entry<K, V>> entrySet = subMap.entrySet();
        assertEquals(3, entrySet.size());

        Collection<V> valueCollection = subMap.values();
        assertEquals(3, valueCollection.size());

        map.remove(null);
    }

    // head map of head map
    NavigableMap<K, V> headMap = map.headMap(keys[3], true);
    assertEquals(4, headMap.size());
    headMap = headMap.headMap(keys[3], false);
    assertEquals(3, headMap.size());
    headMap = headMap.headMap(keys[2], false);
    assertEquals(2, headMap.size());
    headMap = headMap.tailMap(keys[0], false);
    assertEquals(1, headMap.size());
    headMap = headMap.tailMap(keys[1], false);
    assertEquals(0, headMap.size());
}

From source file:org.kuali.kra.budget.calculator.BudgetCalculationServiceImpl.java

protected SortedMap<RateType, List<BudgetDecimal>> calculateExpenseTotals(Budget budget,
        boolean personnelFlag) {
    SortedMap<RateType, List<BudgetDecimal>> calculatedExpenseTotals = new TreeMap<RateType, List<BudgetDecimal>>();

    List<BudgetDecimal> calculatedDirectCostSummaryTotals = new ArrayList<BudgetDecimal>();
    for (int i = 0; i < budget.getBudgetPeriods().size(); i++) {
        calculatedDirectCostSummaryTotals.add(i, BudgetDecimal.ZERO);
    }// w  w  w  . j av  a 2  s. co m
    String totalsMapKey = null;
    if (personnelFlag) {
        totalsMapKey = "personnelCalculatedExpenseSummaryTotals";
    } else {
        totalsMapKey = "nonPersonnelCalculatedExpenseSummaryTotals";
    }
    budget.getBudgetSummaryTotals().put(totalsMapKey, calculatedDirectCostSummaryTotals);

    for (BudgetPeriod budgetPeriod : budget.getBudgetPeriods()) {
        for (BudgetLineItem budgetLineItem : budgetPeriod.getBudgetLineItems()) {
            if ((personnelFlag && StringUtils.equals(
                    budgetLineItem.getCostElementBO().getBudgetCategory().getBudgetCategoryTypeCode(), "P"))
                    || (!personnelFlag && !StringUtils.equals(
                            budgetLineItem.getCostElementBO().getBudgetCategory().getBudgetCategoryTypeCode(),
                            "P"))) {
                // get calculated expenses                        
                QueryList lineItemCalcAmtQueryList = new QueryList();
                lineItemCalcAmtQueryList.addAll(budgetLineItem.getBudgetLineItemCalculatedAmounts());
                List<RateType> rateTypes = new ArrayList<RateType>();

                for (Object item : budgetLineItem.getBudgetLineItemCalculatedAmounts()) {
                    BudgetLineItemCalculatedAmount budgetLineItemCalculatedAmount = (BudgetLineItemCalculatedAmount) item;
                    //                        if (budgetLineItemCalculatedAmount.getRateType() == null) {
                    //                            budgetLineItemCalculatedAmount.refreshReferenceObject("rateType");
                    //                        }
                    //                        if (budgetLineItemCalculatedAmount.getRateType() != null && budgetLineItemCalculatedAmount.getRateType().getRateClass() == null) {
                    //                            budgetLineItemCalculatedAmount.getRateType().refreshReferenceObject("rateClass");
                    //                        }
                    RateType rateType = createRateType(budgetLineItemCalculatedAmount);
                    RateClass rateClass = null;
                    if (rateType != null) {
                        rateType.refreshReferenceObject("rateClass");
                        rateClass = rateType.getRateClass();
                    }

                    if (((personnelFlag && rateClass != null
                            && !StringUtils.equals(rateClass.getRateClassType(), "E")) || !personnelFlag)
                            && !rateTypes.contains(rateType)) {
                        rateTypes.add(rateType);
                        Equals equalsRC = new Equals("rateClassCode",
                                budgetLineItemCalculatedAmount.getRateClassCode());
                        Equals equalsRT = new Equals("rateTypeCode",
                                budgetLineItemCalculatedAmount.getRateTypeCode());
                        And RCandRT = new And(equalsRC, equalsRT);
                        BudgetDecimal rateTypeTotalInThisPeriod = lineItemCalcAmtQueryList
                                .sumObjects("calculatedCost", RCandRT);
                        if (!calculatedExpenseTotals.containsKey(rateType)) {
                            List<BudgetDecimal> rateTypePeriodTotals = new ArrayList<BudgetDecimal>();
                            for (int i = 0; i < budget.getBudgetPeriods().size(); i++) {
                                rateTypePeriodTotals.add(i, BudgetDecimal.ZERO);
                            }
                            calculatedExpenseTotals.put(rateType, rateTypePeriodTotals);
                        }
                        calculatedExpenseTotals.get(rateType).set(budgetPeriod.getBudgetPeriod() - 1,
                                ((BudgetDecimal) calculatedExpenseTotals.get(rateType)
                                        .get(budgetPeriod.getBudgetPeriod() - 1))
                                                .add(rateTypeTotalInThisPeriod));

                        if (!StringUtils.equals(rateClass.getRateClassType(), "O")) {
                            budget.getBudgetSummaryTotals().get(totalsMapKey).set(
                                    budgetPeriod.getBudgetPeriod() - 1,
                                    ((BudgetDecimal) (budget.getBudgetSummaryTotals().get(totalsMapKey)
                                            .get(budgetPeriod.getBudgetPeriod() - 1)))
                                                    .add(rateTypeTotalInThisPeriod));
                        }

                        budgetPeriod
                                .setExpenseTotal(budgetPeriod.getExpenseTotal().add(rateTypeTotalInThisPeriod));
                    }
                }
            }

        }
    }

    return calculatedExpenseTotals;
}

From source file:com.google.gwt.emultest.java.util.TreeMapTest.java

/**
 * Test method for 'java.util.Map.put(Object, Object)'. This test shows some
 * bad behavior of the TreeMap class before JDK 7. A mapping with null key can
 * be put in but several methods are are unusable afterward.
 *
 * A SortedMap with natural ordering (no comparator) is supposed to throw a
 * null pointer exception if a null keys are "not supported". For a natural
 * ordered TreeMap before JDK 7, a null pointer exception is not thrown. But,
 * the map is left in a state where any other key based methods result in a
 * null pointer exception.//from  w  ww .j  a  v a2 s .co m
 *
 * @see java.util.Map#put(Object, Object)
 */
public void testPut_nullKey() {
    K[] keys = getSortedKeys();
    V[] values = getSortedValues();
    SortedMap<K, V> sortedMap = createNavigableMap();

    if (useNullKey()) {
        assertNull(sortedMap.put(null, values[0]));
        assertTrue(sortedMap.containsValue(values[0]));

        // the map methods the continue to function
        sortedMap.containsValue(null);
        sortedMap.containsValue(values[0]);
        sortedMap.entrySet();
        sortedMap.equals(createMap());
        sortedMap.hashCode();
        sortedMap.isEmpty();
        sortedMap.keySet();
        sortedMap.putAll(createMap());
        sortedMap.size();
        sortedMap.values();

        // all of the sorted map methods still function
        sortedMap.comparator();
        sortedMap.firstKey();
        sortedMap.lastKey();
        sortedMap.subMap(getLessThanMinimumKey(), getGreaterThanMaximumKey());
        sortedMap.headMap(getLessThanMinimumKey());
        sortedMap.tailMap(getLessThanMinimumKey());
    } else if (TestUtils.getJdkVersion() > 6) {
        // nulls are rejected immediately and don't poison the map anymore
        try {
            assertNull(sortedMap.put(null, values[0]));
            fail("should have thrown");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            assertNull(sortedMap.put(null, values[1]));
            fail("expected exception adding second null");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            sortedMap.containsKey(null);
            fail("expected exception on containsKey(null)");
        } catch (NullPointerException e) {
            // expected outcome
        }
        sortedMap.containsKey(keys[0]);
        try {
            sortedMap.get(null);
            fail("expected exception on get(null)");
        } catch (NullPointerException e) {
            // expected outcome
        }
        sortedMap.get(keys[0]);
        try {
            sortedMap.remove(null);
        } catch (NullPointerException e) {
            // expected
        }
        sortedMap.remove(keys[0]);
    } else {
        // before JDK 7, nulls poisoned the map
        try {
            assertNull(sortedMap.put(null, values[0]));
            // note: first null added is not required to throw NPE since no
            // comparisons are needed
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            assertNull(sortedMap.put(null, values[1]));
            fail("expected exception adding second null");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            sortedMap.containsKey(null);
            fail("expected exception on containsKey(null)");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            sortedMap.containsKey(keys[0]);
            fail("expected exception on contains(key)");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            sortedMap.get(null);
            fail("expected exception on get(null)");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            sortedMap.get(keys[0]);
            fail("expected exception on get(key)");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            sortedMap.remove(null);
            fail("expected exception on remove(null)");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            sortedMap.remove(keys[0]);
            fail("expected exception on remove(key)");
        } catch (NullPointerException e) {
            // expected outcome
        }
    }
}

From source file:org.torproject.ernie.db.ConsensusHealthChecker.java

public void writeStatusWebsite() {

    /* If we don't have any consensus, we cannot write useful consensus
     * health information to the website. Do not overwrite existing page
     * with a warning, because we might just not have learned about a new
     * consensus in this execution. */
    if (this.mostRecentConsensus == null) {
        return;//w  w w .  j  a  va  2s. c  o m
    }

    /* Prepare parsing dates. */
    SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    StringBuilder knownFlagsResults = new StringBuilder();
    StringBuilder numRelaysVotesResults = new StringBuilder();
    StringBuilder consensusMethodsResults = new StringBuilder();
    StringBuilder versionsResults = new StringBuilder();
    StringBuilder paramsResults = new StringBuilder();
    StringBuilder authorityKeysResults = new StringBuilder();
    StringBuilder bandwidthScannersResults = new StringBuilder();
    StringBuilder authorityVersionsResults = new StringBuilder();
    SortedSet<String> allKnownFlags = new TreeSet<String>();
    SortedSet<String> allKnownVotes = new TreeSet<String>();
    SortedMap<String, String> consensusAssignedFlags = new TreeMap<String, String>();
    SortedMap<String, SortedSet<String>> votesAssignedFlags = new TreeMap<String, SortedSet<String>>();
    SortedMap<String, String> votesKnownFlags = new TreeMap<String, String>();
    SortedMap<String, SortedMap<String, Integer>> flagsAgree = new TreeMap<String, SortedMap<String, Integer>>();
    SortedMap<String, SortedMap<String, Integer>> flagsLost = new TreeMap<String, SortedMap<String, Integer>>();
    SortedMap<String, SortedMap<String, Integer>> flagsMissing = new TreeMap<String, SortedMap<String, Integer>>();

    /* Read consensus and parse all information that we want to compare to
     * votes. */
    String consensusConsensusMethod = null, consensusKnownFlags = null, consensusClientVersions = null,
            consensusServerVersions = null, consensusParams = null, rLineTemp = null, sLineTemp = null;
    int consensusTotalRelays = 0, consensusRunningRelays = 0;
    try {
        BufferedReader br = new BufferedReader(new StringReader(new String(this.mostRecentConsensus)));
        String line = null;
        while ((line = br.readLine()) != null) {
            if (line.startsWith("consensus-method ")) {
                consensusConsensusMethod = line;
            } else if (line.startsWith("client-versions ")) {
                consensusClientVersions = line;
            } else if (line.startsWith("server-versions ")) {
                consensusServerVersions = line;
            } else if (line.startsWith("known-flags ")) {
                consensusKnownFlags = line;
            } else if (line.startsWith("params ")) {
                consensusParams = line;
            } else if (line.startsWith("r ")) {
                rLineTemp = line;
            } else if (line.startsWith("s ")) {
                sLineTemp = line;
                consensusTotalRelays++;
                if (line.contains(" Running")) {
                    consensusRunningRelays++;
                }
                consensusAssignedFlags.put(
                        Hex.encodeHexString(Base64.decodeBase64(rLineTemp.split(" ")[2] + "=")).toUpperCase()
                                + " " + rLineTemp.split(" ")[1],
                        line);
            } else if (line.startsWith("v ") && sLineTemp.contains(" Authority")) {
                authorityVersionsResults
                        .append("          <tr>\n" + "            <td>" + rLineTemp.split(" ")[1] + "</td>\n"
                                + "            <td>" + line.substring(2) + "</td>\n" + "          </tr>\n");
            }
        }
        br.close();
    } catch (IOException e) {
        /* There should be no I/O taking place when reading a String. */
    }

    /* Read votes and parse all information to compare with the
     * consensus. */
    for (byte[] voteBytes : this.mostRecentVotes.values()) {
        String voteConsensusMethods = null, voteKnownFlags = null, voteClientVersions = null,
                voteServerVersions = null, voteParams = null, dirSource = null, voteDirKeyExpires = null;
        int voteTotalRelays = 0, voteRunningRelays = 0, voteContainsBandwidthWeights = 0;
        try {
            BufferedReader br = new BufferedReader(new StringReader(new String(voteBytes)));
            String line = null;
            while ((line = br.readLine()) != null) {
                if (line.startsWith("consensus-methods ")) {
                    voteConsensusMethods = line;
                } else if (line.startsWith("client-versions ")) {
                    voteClientVersions = line;
                } else if (line.startsWith("server-versions ")) {
                    voteServerVersions = line;
                } else if (line.startsWith("known-flags ")) {
                    voteKnownFlags = line;
                } else if (line.startsWith("params ")) {
                    voteParams = line;
                } else if (line.startsWith("dir-source ")) {
                    dirSource = line.split(" ")[1];
                    allKnownVotes.add(dirSource);
                } else if (line.startsWith("dir-key-expires ")) {
                    voteDirKeyExpires = line;
                } else if (line.startsWith("r ")) {
                    rLineTemp = line;
                } else if (line.startsWith("s ")) {
                    voteTotalRelays++;
                    if (line.contains(" Running")) {
                        voteRunningRelays++;
                    }
                    String relayKey = Hex.encodeHexString(Base64.decodeBase64(rLineTemp.split(" ")[2] + "="))
                            .toUpperCase() + " " + rLineTemp.split(" ")[1];
                    SortedSet<String> sLines = null;
                    if (votesAssignedFlags.containsKey(relayKey)) {
                        sLines = votesAssignedFlags.get(relayKey);
                    } else {
                        sLines = new TreeSet<String>();
                        votesAssignedFlags.put(relayKey, sLines);
                    }
                    sLines.add(dirSource + " " + line);
                } else if (line.startsWith("w ")) {
                    if (line.contains(" Measured")) {
                        voteContainsBandwidthWeights++;
                    }
                }
            }
            br.close();
        } catch (IOException e) {
            /* There should be no I/O taking place when reading a String. */
        }

        /* Write known flags. */
        knownFlagsResults.append("          <tr>\n" + "            <td>" + dirSource + "</td>\n"
                + "            <td>" + voteKnownFlags + "</td>\n" + "          </tr>\n");
        votesKnownFlags.put(dirSource, voteKnownFlags);
        for (String flag : voteKnownFlags.substring("known-flags ".length()).split(" ")) {
            allKnownFlags.add(flag);
        }

        /* Write number of relays voted about. */
        numRelaysVotesResults.append("          <tr>\n" + "            <td>" + dirSource + "</td>\n"
                + "            <td>" + voteTotalRelays + " total</td>\n" + "            <td>"
                + voteRunningRelays + " Running</td>\n" + "          </tr>\n");

        /* Write supported consensus methods. */
        if (!voteConsensusMethods.contains(consensusConsensusMethod.split(" ")[1])) {
            consensusMethodsResults.append("          <tr>\n" + "            <td><font color=\"red\">"
                    + dirSource + "</font></td>\n" + "            <td><font color=\"red\">"
                    + voteConsensusMethods + "</font></td>\n" + "          </tr>\n");
            this.logger.warning(dirSource + " does not support consensus " + "method "
                    + consensusConsensusMethod.split(" ")[1] + ": " + voteConsensusMethods);
        } else {
            consensusMethodsResults.append("          <tr>\n" + "            <td>" + dirSource + "</td>\n"
                    + "            <td>" + voteConsensusMethods + "</td>\n" + "          </tr>\n");
            this.logger.fine(dirSource + " supports consensus method " + consensusConsensusMethod.split(" ")[1]
                    + ": " + voteConsensusMethods);
        }

        /* Write recommended versions. */
        if (voteClientVersions == null) {
            /* Not a versioning authority. */
        } else if (!voteClientVersions.equals(consensusClientVersions)) {
            versionsResults.append("          <tr>\n" + "            <td><font color=\"red\">" + dirSource
                    + "</font></td>\n" + "            <td><font color=\"red\">" + voteClientVersions
                    + "</font></td>\n" + "          </tr>\n");
            this.logger.warning(dirSource + " recommends other client " + "versions than the consensus: "
                    + voteClientVersions);
        } else {
            versionsResults.append("          <tr>\n" + "            <td>" + dirSource + "</td>\n"
                    + "            <td>" + voteClientVersions + "</td>\n" + "          </tr>\n");
            this.logger.fine(dirSource + " recommends the same client " + "versions as the consensus: "
                    + voteClientVersions);
        }
        if (voteServerVersions == null) {
            /* Not a versioning authority. */
        } else if (!voteServerVersions.equals(consensusServerVersions)) {
            versionsResults.append(
                    "          <tr>\n" + "            <td></td>\n" + "            <td><font color=\"red\">"
                            + voteServerVersions + "</font></td>\n" + "          </tr>\n");
            this.logger.warning(dirSource + " recommends other server " + "versions than the consensus: "
                    + voteServerVersions);
        } else {
            versionsResults.append("          <tr>\n" + "            <td></td>\n" + "            <td>"
                    + voteServerVersions + "</td>\n" + "          </tr>\n");
            this.logger.fine(dirSource + " recommends the same server " + "versions as the consensus: "
                    + voteServerVersions);
        }

        /* Write consensus parameters. */
        boolean conflictOrInvalid = false;
        Set<String> validParameters = new HashSet<String>(
                Arrays.asList("circwindow,CircuitPriorityHalflifeMsec,refuseunknownexits".split(",")));
        if (voteParams == null) {
            /* Authority doesn't set consensus parameters. */
        } else {
            for (String param : voteParams.split(" ")) {
                if (!param.equals("params") && (!consensusParams.contains(param)
                        || !validParameters.contains(param.split("=")[0]))) {
                    conflictOrInvalid = true;
                    break;
                }
            }
        }
        if (conflictOrInvalid) {
            paramsResults.append("          <tr>\n" + "            <td><font color=\"red\">" + dirSource
                    + "</font></td>\n" + "            <td><font color=\"red\">" + voteParams + "</font></td>\n"
                    + "          </tr>\n");
            this.logger.warning(
                    dirSource + " sets conflicting or invalid " + "consensus parameters: " + voteParams);
        } else {
            paramsResults.append("          <tr>\n" + "            <td>" + dirSource + "</td>\n"
                    + "            <td>" + voteParams + "</td>\n" + "          </tr>\n");
            this.logger.fine(dirSource + " sets only non-conflicting and " + "valid consensus parameters: "
                    + voteParams);
        }

        /* Write authority key expiration date. */
        if (voteDirKeyExpires != null) {
            boolean expiresIn14Days = false;
            try {
                expiresIn14Days = (System.currentTimeMillis() + 14L * 24L * 60L * 60L * 1000L > dateTimeFormat
                        .parse(voteDirKeyExpires.substring("dir-key-expires ".length())).getTime());
            } catch (ParseException e) {
                /* Can't parse the timestamp? Whatever. */
            }
            if (expiresIn14Days) {
                authorityKeysResults.append("          <tr>\n" + "            <td><font color=\"red\">"
                        + dirSource + "</font></td>\n" + "            <td><font color=\"red\">"
                        + voteDirKeyExpires + "</font></td>\n" + "          </tr>\n");
                this.logger.warning(
                        dirSource + "'s certificate expires in the " + "next 14 days: " + voteDirKeyExpires);
            } else {
                authorityKeysResults.append("          <tr>\n" + "            <td>" + dirSource + "</td>\n"
                        + "            <td>" + voteDirKeyExpires + "</td>\n" + "          </tr>\n");
                this.logger.fine(dirSource + "'s certificate does not " + "expire in the next 14 days: "
                        + voteDirKeyExpires);
            }
        }

        /* Write results for bandwidth scanner status. */
        if (voteContainsBandwidthWeights > 0) {
            bandwidthScannersResults.append("          <tr>\n" + "            <td>" + dirSource + "</td>\n"
                    + "            <td>" + voteContainsBandwidthWeights + " Measured values in w lines</td>\n"
                    + "          </tr>\n");
        }
    }

    /* Check if we're missing a vote. TODO make this configurable */
    SortedSet<String> knownAuthorities = new TreeSet<String>(
            Arrays.asList(("dannenberg,dizum,gabelmoo,ides,maatuska,moria1," + "tor26,urras").split(",")));
    for (String dir : allKnownVotes) {
        knownAuthorities.remove(dir);
    }
    if (!knownAuthorities.isEmpty()) {
        StringBuilder sb = new StringBuilder();
        for (String dir : knownAuthorities) {
            sb.append(", " + dir);
        }
        this.logger.warning("We're missing votes from the following " + "directory authorities: "
                + sb.toString().substring(2));
    }

    try {

        /* Keep the past two consensus health statuses. */
        File file0 = new File("website/consensus-health.html");
        File file1 = new File("website/consensus-health-1.html");
        File file2 = new File("website/consensus-health-2.html");
        if (file2.exists()) {
            file2.delete();
        }
        if (file1.exists()) {
            file1.renameTo(file2);
        }
        if (file0.exists()) {
            file0.renameTo(file1);
        }

        /* Start writing web page. */
        BufferedWriter bw = new BufferedWriter(new FileWriter("website/consensus-health.html"));
        bw.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n" + "<html>\n"
                + "  <head>\n" + "    <title>Tor Metrics Portal: Consensus health</title>\n"
                + "    <meta http-equiv=\"content-type\" content=\"text/html; " + "charset=ISO-8859-1\">\n"
                + "    <link href=\"/css/stylesheet-ltr.css\" type=\"text/css\" " + "rel=\"stylesheet\">\n"
                + "    <link href=\"/images/favicon.ico\" " + "type=\"image/x-icon\" rel=\"shortcut icon\">\n"
                + "  </head>\n" + "  <body>\n" + "    <div class=\"center\">\n"
                + "      <table class=\"banner\" border=\"0\" "
                + "cellpadding=\"0\" cellspacing=\"0\" summary=\"\">\n" + "        <tr>\n"
                + "          <td class=\"banner-left\"><a "
                + "href=\"/index.html\"><img src=\"/images/top-left.png\" "
                + "alt=\"Click to go to home page\" width=\"193\" " + "height=\"79\"></a></td>\n"
                + "          <td class=\"banner-middle\">\n" + "            <a href=\"/\">Home</a>\n"
                + "            <a href=\"graphs.html\">Graphs</a>\n"
                + "            <a href=\"research.html\">Research</a>\n"
                + "            <a href=\"status.html\">Status</a>\n" + "            <br>\n"
                + "            <font size=\"2\">\n"
                + "              <a href=\"exonerator.html\">ExoneraTor</a>\n"
                + "              <a href=\"relay-search.html\">Relay Search</a>\n"
                + "              <a class=\"current\">Consensus Health</a>\n" + "            </font>\n"
                + "          </td>\n" + "          <td class=\"banner-right\"></td>\n" + "        </tr>\n"
                + "      </table>\n" + "      <div class=\"main-column\">\n"
                + "        <h2>Tor Metrics Portal: Consensus Health</h2>\n" + "        <br>\n"
                + "        <p>This page shows statistics about the current "
                + "consensus and votes to facilitate debugging of the " + "directory consensus process.</p>\n");

        /* Write valid-after time. */
        bw.write("        <br>\n" + "        <h3>Valid-after time</h3>\n" + "        <br>\n"
                + "        <p>Consensus was published ");
        boolean consensusIsStale = false;
        try {
            consensusIsStale = System.currentTimeMillis() - 3L * 60L * 60L * 1000L > dateTimeFormat
                    .parse(this.mostRecentValidAfterTime).getTime();
        } catch (ParseException e) {
            /* Can't parse the timestamp? Whatever. */
        }
        if (consensusIsStale) {
            bw.write("<font color=\"red\">" + this.mostRecentValidAfterTime + "</font>");
            this.logger.warning("The last consensus published at " + this.mostRecentValidAfterTime
                    + " is more than 3 hours " + "old.");
        } else {
            bw.write(this.mostRecentValidAfterTime);
            this.logger.fine("The last consensus published at " + this.mostRecentValidAfterTime
                    + " is less than 3 hours " + "old.");
        }
        bw.write(". <i>Note that it takes " + "15 to 30 minutes for the metrics portal to learn about "
                + "new consensus and votes and process them.</i></p>\n");

        /* Write known flags. */
        bw.write("        <br>\n" + "        <h3>Known flags</h3>\n" + "        <br>\n"
                + "        <table border=\"0\" cellpadding=\"4\" " + "cellspacing=\"0\" summary=\"\">\n"
                + "          <colgroup>\n" + "            <col width=\"160\">\n"
                + "            <col width=\"640\">\n" + "          </colgroup>\n");
        if (knownFlagsResults.length() < 1) {
            bw.write("          <tr><td>(No votes.)</td><td></td></tr>\n");
        } else {
            bw.write(knownFlagsResults.toString());
        }
        bw.write("          <tr>\n" + "            <td><font color=\"blue\">consensus</font>" + "</td>\n"
                + "            <td><font color=\"blue\">" + consensusKnownFlags + "</font></td>\n"
                + "          </tr>\n");
        bw.write("        </table>\n");

        /* Write number of relays voted about. */
        bw.write("        <br>\n" + "        <h3>Number of relays voted about</h3>\n" + "        <br>\n"
                + "        <table border=\"0\" cellpadding=\"4\" " + "cellspacing=\"0\" summary=\"\">\n"
                + "          <colgroup>\n" + "            <col width=\"160\">\n"
                + "            <col width=\"320\">\n" + "            <col width=\"320\">\n"
                + "          </colgroup>\n");
        if (numRelaysVotesResults.length() < 1) {
            bw.write("          <tr><td>(No votes.)</td><td></td><td></td></tr>\n");
        } else {
            bw.write(numRelaysVotesResults.toString());
        }
        bw.write("          <tr>\n" + "            <td><font color=\"blue\">consensus</font>" + "</td>\n"
                + "            <td><font color=\"blue\">" + consensusTotalRelays + " total</font></td>\n"
                + "            <td><font color=\"blue\">" + consensusRunningRelays + " Running</font></td>\n"
                + "          </tr>\n");
        bw.write("        </table>\n");

        /* Write consensus methods. */
        bw.write("        <br>\n" + "        <h3>Consensus methods</h3>\n" + "        <br>\n"
                + "        <table border=\"0\" cellpadding=\"4\" " + "cellspacing=\"0\" summary=\"\">\n"
                + "          <colgroup>\n" + "            <col width=\"160\">\n"
                + "            <col width=\"640\">\n" + "          </colgroup>\n");
        if (consensusMethodsResults.length() < 1) {
            bw.write("          <tr><td>(No votes.)</td><td></td></tr>\n");
        } else {
            bw.write(consensusMethodsResults.toString());
        }
        bw.write("          <tr>\n" + "            <td><font color=\"blue\">consensus</font>" + "</td>\n"
                + "            <td><font color=\"blue\">" + consensusConsensusMethod + "</font></td>\n"
                + "          </tr>\n");
        bw.write("        </table>\n");

        /* Write recommended versions. */
        bw.write("        <br>\n" + "        <h3>Recommended versions</h3>\n" + "        <br>\n"
                + "        <table border=\"0\" cellpadding=\"4\" " + "cellspacing=\"0\" summary=\"\">\n"
                + "          <colgroup>\n" + "            <col width=\"160\">\n"
                + "            <col width=\"640\">\n" + "          </colgroup>\n");
        if (versionsResults.length() < 1) {
            bw.write("          <tr><td>(No votes.)</td><td></td></tr>\n");
        } else {
            bw.write(versionsResults.toString());
        }
        bw.write("          <tr>\n" + "            <td><font color=\"blue\">consensus</font>" + "</td>\n"
                + "            <td><font color=\"blue\">" + consensusClientVersions + "</font></td>\n"
                + "          </tr>\n");
        bw.write("          <tr>\n" + "            <td></td>\n" + "            <td><font color=\"blue\">"
                + consensusServerVersions + "</font></td>\n" + "          </tr>\n");
        bw.write("        </table>\n");

        /* Write consensus parameters. */
        bw.write("        <br>\n" + "        <h3>Consensus parameters</h3>\n" + "        <br>\n"
                + "        <table border=\"0\" cellpadding=\"4\" " + "cellspacing=\"0\" summary=\"\">\n"
                + "          <colgroup>\n" + "            <col width=\"160\">\n"
                + "            <col width=\"640\">\n" + "          </colgroup>\n");
        if (paramsResults.length() < 1) {
            bw.write("          <tr><td>(No votes.)</td><td></td></tr>\n");
        } else {
            bw.write(paramsResults.toString());
        }
        bw.write("          <tr>\n" + "            <td><font color=\"blue\">consensus</font>" + "</td>\n"
                + "            <td><font color=\"blue\">" + consensusParams + "</font></td>\n"
                + "          </tr>\n");
        bw.write("        </table>\n");

        /* Write authority keys. */
        bw.write("        <br>\n" + "        <h3>Authority keys</h3>\n" + "        <br>\n"
                + "        <table border=\"0\" cellpadding=\"4\" " + "cellspacing=\"0\" summary=\"\">\n"
                + "          <colgroup>\n" + "            <col width=\"160\">\n"
                + "            <col width=\"640\">\n" + "          </colgroup>\n");
        if (authorityKeysResults.length() < 1) {
            bw.write("          <tr><td>(No votes.)</td><td></td></tr>\n");
        } else {
            bw.write(authorityKeysResults.toString());
        }
        bw.write("        </table>\n" + "        <br>\n"
                + "        <p><i>Note that expiration dates of legacy keys are "
                + "not included in votes and therefore not listed here!</i>" + "</p>\n");

        /* Write bandwidth scanner status. */
        bw.write("        <br>\n" + "        <h3>Bandwidth scanner status</h3>\n" + "        <br>\n"
                + "        <table border=\"0\" cellpadding=\"4\" " + "cellspacing=\"0\" summary=\"\">\n"
                + "          <colgroup>\n" + "            <col width=\"160\">\n"
                + "            <col width=\"640\">\n" + "          </colgroup>\n");
        if (bandwidthScannersResults.length() < 1) {
            bw.write("          <tr><td>(No votes.)</td><td></td></tr>\n");
        } else {
            bw.write(bandwidthScannersResults.toString());
        }
        bw.write("        </table>\n");

        /* Write authority versions. */
        bw.write("        <br>\n" + "        <h3>Authority versions</h3>\n" + "        <br>\n");
        if (authorityVersionsResults.length() < 1) {
            bw.write("          <p>(No relays with Authority flag found.)" + "</p>\n");
        } else {
            bw.write("        <table border=\"0\" cellpadding=\"4\" " + "cellspacing=\"0\" summary=\"\">\n"
                    + "          <colgroup>\n" + "            <col width=\"160\">\n"
                    + "            <col width=\"640\">\n" + "          </colgroup>\n");
            bw.write(authorityVersionsResults.toString());
            bw.write("        </table>\n" + "        <br>\n"
                    + "        <p><i>Note that this list of relays with the "
                    + "Authority flag may be different from the list of v3 "
                    + "directory authorities!</i></p>\n");
        }

        /* Write (huge) table with all flags. */
        bw.write("        <br>\n" + "        <h3>Relay flags</h3>\n" + "        <br>\n"
                + "        <p>The semantics of flags written in the table is " + "as follows:</p>\n"
                + "        <ul>\n" + "          <li><b>In vote and consensus:</b> Flag in vote "
                + "matches flag in consensus, or relay is not listed in "
                + "consensus (because it doesn't have the Running " + "flag)</li>\n"
                + "          <li><b><font color=\"red\">Only in "
                + "vote:</font></b> Flag in vote, but missing in the "
                + "consensus, because there was no majority for the flag or "
                + "the flag was invalidated (e.g., Named gets invalidated by " + "Unnamed)</li>\n"
                + "          <li><b><font color=\"gray\"><s>Only in "
                + "consensus:</s></font></b> Flag in consensus, but missing "
                + "in a vote of a directory authority voting on this " + "flag</li>\n"
                + "          <li><b><font color=\"blue\">In " + "consensus:</font></b> Flag in consensus</li>\n"
                + "        </ul>\n" + "        <br>\n"
                + "        <p>See also the summary below the table.</p>\n"
                + "        <table border=\"0\" cellpadding=\"4\" " + "cellspacing=\"0\" summary=\"\">\n"
                + "          <colgroup>\n" + "            <col width=\"120\">\n"
                + "            <col width=\"80\">\n");
        for (int i = 0; i < allKnownVotes.size(); i++) {
            bw.write("            <col width=\"" + (640 / allKnownVotes.size()) + "\">\n");
        }
        bw.write("          </colgroup>\n");
        int linesWritten = 0;
        for (Map.Entry<String, SortedSet<String>> e : votesAssignedFlags.entrySet()) {
            if (linesWritten++ % 10 == 0) {
                bw.write("          <tr><td><br><b>Fingerprint</b></td>" + "<td><br><b>Nickname</b></td>\n");
                for (String dir : allKnownVotes) {
                    String shortDirName = dir.length() > 6 ? dir.substring(0, 5) + "." : dir;
                    bw.write("<td><br><b>" + shortDirName + "</b></td>");
                }
                bw.write("<td><br><b>consensus</b></td></tr>\n");
            }
            String relayKey = e.getKey();
            SortedSet<String> votes = e.getValue();
            String fingerprint = relayKey.split(" ")[0].substring(0, 8);
            String nickname = relayKey.split(" ")[1];
            bw.write("          <tr>\n");
            if (consensusAssignedFlags.containsKey(relayKey)
                    && consensusAssignedFlags.get(relayKey).contains(" Named")
                    && !Character.isDigit(nickname.charAt(0))) {
                bw.write("            <td id=\"" + nickname + "\"><a href=\"relay.html?fingerprint="
                        + relayKey.split(" ")[0] + "\" target=\"_blank\">" + fingerprint + "</a></td>\n");
            } else {
                bw.write("            <td><a href=\"relay.html?fingerprint=" + fingerprint
                        + "\" target=\"_blank\">" + fingerprint + "</a></td>\n");
            }
            bw.write("            <td>" + nickname + "</td>\n");
            SortedSet<String> relevantFlags = new TreeSet<String>();
            for (String vote : votes) {
                String[] parts = vote.split(" ");
                for (int j = 2; j < parts.length; j++) {
                    relevantFlags.add(parts[j]);
                }
            }
            String consensusFlags = null;
            if (consensusAssignedFlags.containsKey(relayKey)) {
                consensusFlags = consensusAssignedFlags.get(relayKey);
                String[] parts = consensusFlags.split(" ");
                for (int j = 1; j < parts.length; j++) {
                    relevantFlags.add(parts[j]);
                }
            }
            for (String dir : allKnownVotes) {
                String flags = null;
                for (String vote : votes) {
                    if (vote.startsWith(dir)) {
                        flags = vote;
                        break;
                    }
                }
                if (flags != null) {
                    votes.remove(flags);
                    bw.write("            <td>");
                    int flagsWritten = 0;
                    for (String flag : relevantFlags) {
                        bw.write(flagsWritten++ > 0 ? "<br>" : "");
                        SortedMap<String, SortedMap<String, Integer>> sums = null;
                        if (flags.contains(" " + flag)) {
                            if (consensusFlags == null || consensusFlags.contains(" " + flag)) {
                                bw.write(flag);
                                sums = flagsAgree;
                            } else {
                                bw.write("<font color=\"red\">" + flag + "</font>");
                                sums = flagsLost;
                            }
                        } else if (consensusFlags != null && votesKnownFlags.get(dir).contains(" " + flag)
                                && consensusFlags.contains(" " + flag)) {
                            bw.write("<font color=\"gray\"><s>" + flag + "</s></font>");
                            sums = flagsMissing;
                        }
                        if (sums != null) {
                            SortedMap<String, Integer> sum = null;
                            if (sums.containsKey(dir)) {
                                sum = sums.get(dir);
                            } else {
                                sum = new TreeMap<String, Integer>();
                                sums.put(dir, sum);
                            }
                            sum.put(flag, sum.containsKey(flag) ? sum.get(flag) + 1 : 1);
                        }
                    }
                    bw.write("</td>\n");
                } else {
                    bw.write("            <td></td>\n");
                }
            }
            if (consensusFlags != null) {
                bw.write("            <td>");
                int flagsWritten = 0;
                for (String flag : relevantFlags) {
                    bw.write(flagsWritten++ > 0 ? "<br>" : "");
                    if (consensusFlags.contains(" " + flag)) {
                        bw.write("<font color=\"blue\">" + flag + "</font>");
                    }
                }
                bw.write("</td>\n");
            } else {
                bw.write("            <td></td>\n");
            }
            bw.write("          </tr>\n");
        }
        bw.write("        </table>\n");

        /* Write summary of overlap between votes and consensus. */
        bw.write("        <br>\n" + "        <h3>Overlap between votes and consensus</h3>\n" + "        <br>\n"
                + "        <p>The semantics of columns is similar to the " + "table above:</p>\n"
                + "        <ul>\n" + "          <li><b>In vote and consensus:</b> Flag in vote "
                + "matches flag in consensus, or relay is not listed in "
                + "consensus (because it doesn't have the Running " + "flag)</li>\n"
                + "          <li><b><font color=\"red\">Only in "
                + "vote:</font></b> Flag in vote, but missing in the "
                + "consensus, because there was no majority for the flag or "
                + "the flag was invalidated (e.g., Named gets invalidated by " + "Unnamed)</li>\n"
                + "          <li><b><font color=\"gray\"><s>Only in "
                + "consensus:</s></font></b> Flag in consensus, but missing "
                + "in a vote of a directory authority voting on this " + "flag</li>\n" + "        </ul>\n"
                + "        <br>\n" + "        <table border=\"0\" cellpadding=\"4\" "
                + "cellspacing=\"0\" summary=\"\">\n" + "          <colgroup>\n"
                + "            <col width=\"160\">\n" + "            <col width=\"210\">\n"
                + "            <col width=\"210\">\n" + "            <col width=\"210\">\n"
                + "          </colgroup>\n");
        bw.write("          <tr><td></td><td><b>Only in vote</b></td>" + "<td><b>In vote and consensus</b></td>"
                + "<td><b>Only in consensus</b></td>\n");
        for (String dir : allKnownVotes) {
            boolean firstFlagWritten = false;
            String[] flags = votesKnownFlags.get(dir).substring("known-flags ".length()).split(" ");
            for (String flag : flags) {
                bw.write("          <tr>\n");
                if (firstFlagWritten) {
                    bw.write("            <td></td>\n");
                } else {
                    bw.write("            <td>" + dir + "</td>\n");
                    firstFlagWritten = true;
                }
                if (flagsLost.containsKey(dir) && flagsLost.get(dir).containsKey(flag)) {
                    bw.write("            <td><font color=\"red\"> " + flagsLost.get(dir).get(flag) + " " + flag
                            + "</font></td>\n");
                } else {
                    bw.write("            <td></td>\n");
                }
                if (flagsAgree.containsKey(dir) && flagsAgree.get(dir).containsKey(flag)) {
                    bw.write("            <td>" + flagsAgree.get(dir).get(flag) + " " + flag + "</td>\n");
                } else {
                    bw.write("            <td></td>\n");
                }
                if (flagsMissing.containsKey(dir) && flagsMissing.get(dir).containsKey(flag)) {
                    bw.write("            <td><font color=\"gray\"><s>" + flagsMissing.get(dir).get(flag) + " "
                            + flag + "</s></font></td>\n");
                } else {
                    bw.write("            <td></td>\n");
                }
                bw.write("          </tr>\n");
            }
        }
        bw.write("        </table>\n");

        /* Finish writing. */
        bw.write("      </div>\n" + "    </div>\n" + "    <div class=\"bottom\" id=\"bottom\">\n"
                + "      <p>This material is supported in part by the "
                + "National Science Foundation under Grant No. "
                + "CNS-0959138. Any opinions, finding, and conclusions "
                + "or recommendations expressed in this material are "
                + "those of the author(s) and do not necessarily reflect "
                + "the views of the National Science Foundation.</p>\n"
                + "      <p>\"Tor\" and the \"Onion Logo\" are <a "
                + "href=\"https://www.torproject.org/docs/trademark-faq.html" + ".en\">"
                + "registered trademarks</a> of The Tor Project, " + "Inc.</p>\n"
                + "      <p>Data on this site is freely available under a "
                + "<a href=\"http://creativecommons.org/publicdomain/"
                + "zero/1.0/\">CC0 no copyright declaration</a>: To the "
                + "extent possible under law, the Tor Project has waived "
                + "all copyright and related or neighboring rights in "
                + "the data. Graphs are licensed under a <a "
                + "href=\"http://creativecommons.org/licenses/by/3.0/"
                + "us/\">Creative Commons Attribution 3.0 United States " + "License</a>.</p>\n"
                + "    </div>\n" + "  </body>\n" + "</html>");
        bw.close();

    } catch (IOException e) {
    }
}