Example usage for java.util TreeMap put

List of usage examples for java.util TreeMap put

Introduction

In this page you can find the example usage for java.util TreeMap put.

Prototype

public V put(K key, V value) 

Source Link

Document

Associates the specified value with the specified key in this map.

Usage

From source file:com.alibaba.wasp.master.handler.TableEventHandler.java

public boolean reOpenAllEntityGroups(List<EntityGroupInfo> entityGroups) throws IOException {
    boolean done = false;
    LOG.info("Bucketing entityGroups by entityGroup server...");
    TreeMap<ServerName, List<EntityGroupInfo>> serverToEntityGroups = Maps.newTreeMap();
    NavigableMap<EntityGroupInfo, ServerName> egiHserverMapping = FMetaScanner
            .allTableEntityGroups(server.getConfiguration(), tableName, false);

    List<EntityGroupInfo> reEntityGroups = new ArrayList<EntityGroupInfo>();
    for (EntityGroupInfo egi : entityGroups) {
        ServerName egLocation = egiHserverMapping.get(egi);

        // Skip the offlined split parent EntityGroup
        if (null == egLocation) {
            LOG.info("Skip " + egi);
            continue;
        }//www  . ja  v  a 2  s.com
        if (!serverToEntityGroups.containsKey(egLocation)) {
            LinkedList<EntityGroupInfo> egiList = Lists.newLinkedList();
            serverToEntityGroups.put(egLocation, egiList);
        }
        reEntityGroups.add(egi);
        serverToEntityGroups.get(egLocation).add(egi);
    }

    LOG.info("Reopening " + reEntityGroups.size() + " entityGroups on " + serverToEntityGroups.size()
            + " fservers.");
    this.fMasterServices.getAssignmentManager().setEntityGroupsToReopen(reEntityGroups);
    BulkReOpen bulkReopen = new BulkReOpen(this.server, serverToEntityGroups,
            this.fMasterServices.getAssignmentManager());
    while (true) {
        try {
            if (bulkReopen.bulkReOpen()) {
                done = true;
                break;
            } else {
                LOG.warn("Timeout before reopening all entityGroups");
            }
        } catch (InterruptedException e) {
            LOG.warn("Reopen was interrupted");
            // Preserve the interrupt.
            Thread.currentThread().interrupt();
            break;
        }
    }
    return done;
}

From source file:com.erudika.para.i18n.LanguageUtils.java

/**
 * Returns a map of all translations for a given language.
 * Defaults to the default language which must be set.
 * @param appid appid name of the {@link com.erudika.para.core.App}
 * @param langCode the 2-letter language code
 * @return the language map/* w  ww .j a  v a  2 s. c o  m*/
 */
public Map<String, String> readLanguage(String appid, String langCode) {
    if (StringUtils.isBlank(langCode) || !allLocales.containsKey(langCode)) {
        return getDefaultLanguage();
    }
    if (search == null || dao == null) {
        return getDefaultLanguage();
    }

    Sysprop s = dao.read(appid, keyPrefix.concat(langCode));
    TreeMap<String, String> lang = new TreeMap<String, String>();

    if (s == null || s.getProperties().isEmpty()) {
        Map<String, Object> terms = new HashMap<String, Object>();
        terms.put("locale", langCode);
        terms.put("approved", true);
        List<Translation> tlist = search.findTerms(appid, Utils.type(Translation.class), terms, true);

        Sysprop saved = new Sysprop(keyPrefix.concat(langCode));
        lang.putAll(getDefaultLanguage()); // copy default langmap
        int approved = 0;

        for (Translation trans : tlist) {
            lang.put(trans.getThekey(), trans.getValue());
            saved.addProperty(trans.getThekey(), trans.getValue());
            approved++;
        }
        if (approved > 0) {
            updateTranslationProgressMap(appid, langCode, approved);
        }
        dao.create(appid, saved);
    } else {
        Map<String, Object> loaded = s.getProperties();
        for (String key : loaded.keySet()) {
            lang.put(key, loaded.get(key).toString());
        }
    }
    return lang;
}

From source file:com.nubits.nubot.trading.wrappers.PeatioWrapper.java

private ApiResponse getBalanceImpl(Currency currency, CurrencyPair pair) {
    ApiResponse apiResponse = new ApiResponse();
    PairBalance balance = null;/*from www. j  a  v  a  2  s. c om*/
    String url = apiBaseUrl;
    String method = API_GET_INFO;
    boolean isGet = true;
    TreeMap<String, String> query_args = new TreeMap<>();
    /*Params
     *
     */
    query_args.put("canonical_verb", "GET");
    query_args.put("canonical_uri", method);

    ApiResponse response = getQuery(url, method, query_args, true, isGet);
    if (response.isPositive()) {
        Amount NBTonOrder = null, NBTAvail = null, PEGonOrder = null, PEGAvail = null;
        JSONObject httpAnswerJson = (JSONObject) response.getResponseObject();
        JSONArray accounts = (JSONArray) httpAnswerJson.get("accounts");

        if (currency == null) { //Get all balances
            for (int i = 0; i < accounts.size(); i++) {
                JSONObject balanceObj = (JSONObject) accounts.get(i);
                String tempCurrency = balanceObj.get("currency").toString();

                String nbtCurrencyCode = pair.getOrderCurrency().getCode();
                String pegCurrencyCode = pair.getPaymentCurrency().getCode();

                if (tempCurrency.equalsIgnoreCase(nbtCurrencyCode)) {
                    NBTAvail = new Amount(Double.parseDouble(balanceObj.get("balance").toString()),
                            pair.getOrderCurrency());
                    NBTonOrder = new Amount(Double.parseDouble(balanceObj.get("locked").toString()),
                            pair.getOrderCurrency());
                }
                if (tempCurrency.equalsIgnoreCase(pegCurrencyCode)) {
                    PEGAvail = new Amount(Double.parseDouble(balanceObj.get("balance").toString()),
                            pair.getPaymentCurrency());
                    PEGonOrder = new Amount(Double.parseDouble(balanceObj.get("locked").toString()),
                            pair.getPaymentCurrency());
                }
            }
            if (NBTAvail != null && NBTonOrder != null && PEGAvail != null && PEGonOrder != null) {
                balance = new PairBalance(PEGAvail, NBTAvail, PEGonOrder, NBTonOrder);
                //Pack it into the ApiResponse
                apiResponse.setResponseObject(balance);
            } else {
                apiResponse.setError(errors.nullReturnError);
            }
        } else {//return available balance for the specific currency
            boolean found = false;
            Amount amount = null;
            for (int i = 0; i < accounts.size(); i++) {
                JSONObject balanceObj = (JSONObject) accounts.get(i);
                String tempCurrency = balanceObj.get("currency").toString();

                if (tempCurrency.equalsIgnoreCase(currency.getCode())) {
                    amount = new Amount((Double.parseDouble(balanceObj.get("balance").toString())), currency);

                    found = true;
                }
            }

            if (found) {
                apiResponse.setResponseObject(amount);
            } else {
                apiResponse.setError(new ApiError(21341,
                        "Can't find balance for" + " specified currency: " + currency.getCode()));
            }
        }
    } else {
        apiResponse = response;
    }

    return apiResponse;
}

From source file:com.netflix.ice.processor.BillingFileProcessor.java

private void sendOndemandCostAlert() {

    if (ondemandThreshold == null || StringUtils.isEmpty(fromEmail) || StringUtils.isEmpty(alertEmails)
            || endMilli < lastAlertMillis() + AwsUtils.hourMillis * 24)
        return;//from  ww w  .  ja v  a 2 s . c  o  m

    Map<Long, Map<Ec2InstanceReservationPrice.Key, Double>> ondemandCosts = getOndemandCosts(
            lastAlertMillis() + AwsUtils.hourMillis);
    Long maxHour = null;
    double maxTotal = ondemandThreshold;

    for (Long hour : ondemandCosts.keySet()) {
        double total = 0;
        for (Double value : ondemandCosts.get(hour).values())
            total += value;

        if (total > maxTotal) {
            maxHour = hour;
            maxTotal = total;
        }
    }

    if (maxHour != null) {
        NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);
        String subject = String.format("Alert: Ondemand cost per hour reached $%s at %s",
                numberFormat.format(maxTotal), AwsUtils.dateFormatter.print(maxHour));
        StringBuilder body = new StringBuilder();
        body.append(String.format("Total ondemand cost $%s at %s:<br><br>", numberFormat.format(maxTotal),
                AwsUtils.dateFormatter.print(maxHour)));
        TreeMap<Double, String> costs = Maps.newTreeMap();
        for (Map.Entry<Ec2InstanceReservationPrice.Key, Double> entry : ondemandCosts.get(maxHour).entrySet()) {
            costs.put(entry.getValue(), entry.getKey().region + " " + entry.getKey().usageType + ": ");
        }
        for (Double cost : costs.descendingKeySet()) {
            if (cost > 0)
                body.append(costs.get(cost)).append("$" + numberFormat.format(cost)).append("<br>");
        }
        body.append("<br>Please go to <a href=\"" + urlPrefix
                + "dashboard/reservation#usage_cost=cost&groupBy=UsageType&product=ec2_instance&operation=OndemandInstances\">Ice</a> for details.");
        SendEmailRequest request = new SendEmailRequest();
        request.withSource(fromEmail);
        List<String> emails = Lists.newArrayList(alertEmails.split(","));
        request.withDestination(new Destination(emails));
        request.withMessage(
                new Message(new Content(subject), new Body().withHtml(new Content(body.toString()))));

        AmazonSimpleEmailServiceClient emailService = AwsUtils.getAmazonSimpleEmailServiceClient();
        try {
            emailService.sendEmail(request);
            updateLastAlertMillis(endMilli);
            logger.info("updateLastAlertMillis " + endMilli);
        } catch (Exception e) {
            logger.error("Error in sending alert emails", e);
        }
    }
}

From source file:com.nubits.nubot.trading.wrappers.BitSparkWrapper.java

@Override
public ApiResponse getActiveOrders(CurrencyPair pair) {
    ApiResponse apiResponse = new ApiResponse();
    ArrayList<Order> orderList = new ArrayList<Order>();
    String url = API_BASE_URL;
    String method = API_ACTIVE_ORDERS;
    boolean isGet = true;
    TreeMap<String, String> query_args = new TreeMap<>();

    /*Params//from w w w .  ja v a 2  s .  c o m
     * pair, default all pairs
     */

    query_args.put("canonical_verb", "GET");
    query_args.put("canonical_uri", method);
    query_args.put("market", pair.toString());
    query_args.put("limit", "999"); //default is 10 , max is 1000

    ApiResponse response = getQuery(url, method, query_args, true, isGet);
    if (response.isPositive()) {
        JSONArray httpAnswerJson = (JSONArray) response.getResponseObject();
        for (Object anOrdersResponse : httpAnswerJson) {
            JSONObject orderResponse = (JSONObject) anOrdersResponse;
            Order tempOrder = parseOrder(orderResponse);
            if (!tempOrder.isCompleted()) //Do not add executed orders
            {
                orderList.add(tempOrder);
            }
        }
        apiResponse.setResponseObject(orderList);
    } else {
        apiResponse = response;
    }

    return apiResponse;
}

From source file:com.ichi2.libanki.Decks.java

/**
 * Select a new branch.// w  w w .ja  va  2s  .  c o  m
 */
public void select(long did) {
    try {
        String name = mDecks.get(did).getString("name");

        // current deck
        mCol.getConf().put("curDeck", Long.toString(did));
        // and active decks (current + all children)
        TreeMap<String, Long> actv = children(did); // Note: TreeMap is already sorted
        actv.put(name, did);
        JSONArray ja = new JSONArray();
        for (Long n : actv.values()) {
            ja.put(n);
        }
        mCol.getConf().put("activeDecks", ja);
        mChanged = true;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.sun.faces.generate.RenderKitSpecificationGenerator.java

/**
 *
 * @return a SortedMap, where the keys are component-family String
 * entries, and the values are {@link RendererBean} instances
 *//*from www.jav a2 s.  co  m*/

public static SortedMap getComponentFamilyRendererMap(String rkId) throws IllegalStateException {
    RenderKitBean renderKit = null;
    RendererBean[] renderers = null;
    RendererBean renderer = null;
    TreeMap result = null;
    ArrayList list = null;
    String componentFamily = null;

    if (null == (renderKit = fcb.getRenderKit(rkId))) {
        RenderKitBean[] kits = null;
        if (null == (kits = fcb.getRenderKits())) {
            throw new IllegalStateException("no RenderKits");
        }
        if (null == (renderKit = kits[0])) {
            throw new IllegalStateException("no RenderKits");
        }
    }

    if (null == (renderers = renderKit.getRenderers())) {
        throw new IllegalStateException("no Renderers");
    }

    result = new TreeMap();

    for (int i = 0, len = renderers.length; i < len; i++) {
        if (null == (renderer = renderers[i])) {
            throw new IllegalStateException("no Renderer");
        }
        // if this is the first time we've encountered this
        // componentFamily
        if (null == (list = (ArrayList) result.get(componentFamily = renderer.getComponentFamily()))) {
            // create a list for it
            list = new ArrayList();
            list.add(renderer);
            result.put(componentFamily, list);
        } else {
            list.add(renderer);
        }
    }
    return result;
}

From source file:com.sfs.whichdoctor.dao.OrganisationDAOImpl.java

/**
 * Load groups./*from  www  . j a  v a 2  s . c  o m*/
 *
 * @param guid the guid
 *
 * @return the collection< group bean>
 */
private Collection<GroupBean> loadGroups(final int guid) {

    // Create new SearchBean of type Organisation and default values
    SearchResultsBean results = new SearchResultsBean();
    SearchBean groupSearch = this.getSearchDAO().initiate("group", null);
    groupSearch.setLimit(0);

    GroupBean searchCriteria = (GroupBean) groupSearch.getSearchCriteria();
    searchCriteria.setObjectType("Organisations");
    ItemBean item = new ItemBean();
    item.setObject2GUID(guid);
    TreeMap<String, ItemBean> items = new TreeMap<String, ItemBean>();
    items.put("Organisation", item);
    searchCriteria.setItems(items);

    groupSearch.setSearchCriteria(searchCriteria);

    try {
        BuilderBean loadGroup = new BuilderBean();
        loadGroup.setParameter("ITEMS", true);
        loadGroup.setParameter("REFERENCEID", String.valueOf(guid));
        results = this.getSearchDAO().search(groupSearch, loadGroup);
    } catch (Exception e) {
        dataLogger.error("Error loading groups for organisation: " + e.getMessage());
    }

    ArrayList<GroupBean> groups = new ArrayList<GroupBean>();
    for (Object group : results.getSearchResults()) {
        groups.add((GroupBean) group);
    }
    return groups;
}

From source file:ai.susi.mind.SusiMind.java

/**
 * This is the core principle of creativity: being able to match a given input
 * with problem-solving knowledge./*from   w w w.jav a  2 s .com*/
 * This method finds ideas (with a query instantiated skills) for a given query.
 * The skills are selected using a scoring system and pattern matching with the query.
 * Not only the most recent user query is considered for skill selection but also
 * previously requested queries and their answers to be able to set new skill selections
 * in the context of the previous conversation.
 * @param query the user input
 * @param previous_argument the latest conversation with the same user
 * @param maxcount the maximum number of ideas to return
 * @return an ordered list of ideas, first idea should be considered first.
 */
public List<SusiIdea> creativity(String query, SusiThought latest_thought, int maxcount) {
    // tokenize query to have hint for idea collection
    final List<SusiIdea> ideas = new ArrayList<>();
    this.reader.tokenizeSentence(query).forEach(token -> {
        Set<SusiSkill> skill_for_category = this.skilltrigger.get(token.categorized);
        Set<SusiSkill> skill_for_original = token.original.equals(token.categorized) ? null
                : this.skilltrigger.get(token.original);
        Set<SusiSkill> r = new HashSet<>();
        if (skill_for_category != null)
            r.addAll(skill_for_category);
        if (skill_for_original != null)
            r.addAll(skill_for_original);
        r.forEach(skill -> ideas.add(new SusiIdea(skill).setIntent(token)));
    });

    for (SusiIdea idea : ideas)
        DAO.log("idea.phrase-1: score=" + idea.getSkill().getScore().score + " : "
                + idea.getSkill().getPhrases().toString() + " " + idea.getSkill().getActionsClone());

    // add catchall skills always (those are the 'bad ideas')
    Collection<SusiSkill> ca = this.skilltrigger.get(SusiSkill.CATCHALL_KEY);
    if (ca != null)
        ca.forEach(skill -> ideas.add(new SusiIdea(skill)));

    // create list of all ideas that might apply
    TreeMap<Long, List<SusiIdea>> scored = new TreeMap<>();
    AtomicLong count = new AtomicLong(0);
    ideas.forEach(idea -> {
        int score = idea.getSkill().getScore().score;
        long orderkey = Long.MAX_VALUE - ((long) score) * 1000L + count.incrementAndGet();
        List<SusiIdea> r = scored.get(orderkey);
        if (r == null) {
            r = new ArrayList<>();
            scored.put(orderkey, r);
        }
        r.add(idea);
    });

    // make a sorted list of all ideas
    ideas.clear();
    scored.values().forEach(r -> ideas.addAll(r));

    for (SusiIdea idea : ideas)
        DAO.log("idea.phrase-2: score=" + idea.getSkill().getScore().score + " : "
                + idea.getSkill().getPhrases().toString() + " " + idea.getSkill().getActionsClone());

    // test ideas and collect those which match up to maxcount
    List<SusiIdea> plausibleIdeas = new ArrayList<>(Math.min(10, maxcount));
    for (SusiIdea idea : ideas) {
        SusiSkill skill = idea.getSkill();
        Collection<Matcher> m = skill.matcher(query);
        if (m.isEmpty())
            continue;
        // TODO: evaluate leading SEE flow commands right here as well
        plausibleIdeas.add(idea);
        if (plausibleIdeas.size() >= maxcount)
            break;
    }

    for (SusiIdea idea : plausibleIdeas) {
        DAO.log("idea.phrase-3: score=" + idea.getSkill().getScore().score + " : "
                + idea.getSkill().getPhrases().toString() + " " + idea.getSkill().getActionsClone());
        DAO.log("idea.phrase-3:   log=" + idea.getSkill().getScore().log);
    }

    return plausibleIdeas;
}

From source file:org.posterita.businesslogic.performanceanalysis.CustomPOSReportManager.java

public static TabularReport generateTabularReportGroupByDate(Properties ctx, String title, String subtitle,
        int account_id, Timestamp fromDate, Timestamp toDate, String salesGroup, String priceQtyFilter)
        throws OperationException {
    boolean isTaxDue = (account_id == Constants.TAX_DUE.intValue());
    boolean isTaxCredit = (account_id == Constants.TAX_CREDIT.intValue());

    NumberFormat formatter = new DecimalFormat("###,###,##0.00");

    String sql = SalesAnalysisReportManager.getTabularDataSetSQL(ctx, account_id, fromDate, toDate, salesGroup);
    ArrayList<Object[]> tmpData = ReportManager.getReportData(ctx, sql, true);
    String currency = POSTerminalManager.getDefaultSalesCurrency(ctx).getCurSymbol();

    ArrayList<Object[]> reportData = new ArrayList<Object[]>();
    Object[] data = null;//from w  w w.j a v  a2  s .  c om
    BigDecimal b = null;

    if (isTaxCredit || isTaxDue) {
        reportData.add(tmpData.remove(0));
        Iterator<Object[]> iter = tmpData.iterator();

        while (iter.hasNext()) {
            data = iter.next();

            if (data.length == 1) {
                b = (BigDecimal) data[0];
                data[0] = formatter.format(b.doubleValue());
            }

            reportData.add(data);
        }
    } else {
        //----------------------------------------------------------------------------------------------------------------------------------------------------------
        TreeMap<String, TabularReportRecordBean> map = new TreeMap<String, TabularReportRecordBean>();

        String productName = null;
        BigDecimal price = null;
        BigDecimal qty = null;

        TabularReportRecordBean bean = null;

        ArrayList<Object[]> reportData2 = new ArrayList<Object[]>();
        Object[] headers = tmpData.remove(0);

        //adding headers
        reportData2.add(new Object[] { headers[0],
                //headers[1],
                headers[2] + "(" + currency + ")", headers[3] });

        double totalAmt = 0.0d;
        int totalQty = 0;

        for (Object[] record : tmpData) {
            productName = (String) record[0];
            price = (BigDecimal) record[2];
            qty = (BigDecimal) record[3];

            totalAmt += price.doubleValue();
            totalQty += qty.intValue();

            bean = map.get(productName);

            if (bean == null) {
                bean = new TabularReportRecordBean();

                bean.setProductName(productName);
                bean.setDate("");
                bean.setPrice(price);
                bean.setQty(qty);
            } else {
                bean.setPrice(bean.getPrice().add(price));
                bean.setQty(bean.getQty().add(qty));
            }

            map.put(productName, bean);

        } //for 

        Collection<TabularReportRecordBean> c = map.values();

        for (TabularReportRecordBean tbean : c) {
            Object[] obj = new Object[] { tbean.getProductName(), tbean.getPrice(), tbean.getQty() };

            reportData2.add(obj);
        }

        reportData.add(reportData2.remove(0));

        Iterator<Object[]> iter = reportData2.iterator();

        while (iter.hasNext()) {
            data = iter.next();

            if (data.length > 2) {
                b = (BigDecimal) data[1];
                data[1] = formatter.format(b.doubleValue());
            }

            reportData.add(data);
        }

        reportData.add(new Object[] { "Total", "" + formatter.format(totalAmt), totalQty + "" });

    }

    //style for table
    String tableStyle = "display";
    //style for columns        
    String[] styles = new String[] { "string", "currency", "numeric" };

    if (isTaxCredit || isTaxDue) {
        styles = new String[] { "numeric" };
    }

    //constructing the table
    TabularReport tReport = new TabularReport(reportData);
    //tReport.setSortable(true);
    tReport.setHeaderStyle(styles);
    tReport.setStyle(tableStyle);
    tReport.setTitle(title);
    tReport.setSubtitle(subtitle);
    tReport.createReport();

    return tReport;
}