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:kmi.taa.core.Crawler.java

/**
 * Read source triples into a TreeMap//from w  ww .j a  v a2s . c  om
 * TreeMap is RBTree based, the map is sorted according to the natural 
 * ordering of the keys, time complexity is O(lg(n)).
 * However, HashMap does not keep the ordering of keys in addition order,
 * we want to keep the order of the source triples as it is in the triples file. 
 * Key should be type of Integer as String has a different sort method 
 */
public TreeMap<Integer, String> readSourceTriples(String file) {
    TreeMap<Integer, String> map = new TreeMap<>();
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = "\t";

    try {
        br = new BufferedReader(new FileReader(file));
        while ((line = br.readLine()) != null) {
            String[] resource = line.split(cvsSplitBy);
            map.put(new Integer(resource[0]), resource[1]);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return map;

}

From source file:com.alibaba.rocketmq.tools.command.consumer.ConsumerSubCommand.java

@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) {
    DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);

    defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));

    try {/*www.  j a v  a 2  s.com*/
        defaultMQAdminExt.start();

        String group = commandLine.getOptionValue('g').trim();

        ConsumerConnection cc = defaultMQAdminExt.examineConsumerConnectionInfo(group);

        boolean jstack = commandLine.hasOption('s');

        if (!commandLine.hasOption('i')) {

            int i = 1;
            long now = System.currentTimeMillis();
            final TreeMap<String/* clientId */, ConsumerRunningInfo> criTable = new TreeMap<String, ConsumerRunningInfo>();
            for (Connection conn : cc.getConnectionSet()) {
                try {
                    ConsumerRunningInfo consumerRunningInfo = defaultMQAdminExt.getConsumerRunningInfo(group,
                            conn.getClientId(), jstack);
                    if (consumerRunningInfo != null) {
                        criTable.put(conn.getClientId(), consumerRunningInfo);
                        String filePath = now + "/" + conn.getClientId();
                        MixAll.string2FileNotSafe(consumerRunningInfo.formatString(), filePath);
                        System.out.printf("%03d  %-40s %-20s %s%n", //
                                i++, //
                                conn.getClientId(), //
                                MQVersion.getVersionDesc(conn.getVersion()), //
                                filePath);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (!criTable.isEmpty()) {
                boolean subSame = ConsumerRunningInfo.analyzeSubscription(criTable);

                boolean rebalanceOK = subSame && ConsumerRunningInfo.analyzeRebalance(criTable);

                if (subSame) {
                    System.out.println("%n%nSame subscription in the same group of consumer");

                    System.out.printf("%n%nRebalance %s%n", rebalanceOK ? "OK" : "Failed");

                    Iterator<Entry<String, ConsumerRunningInfo>> it = criTable.entrySet().iterator();
                    while (it.hasNext()) {
                        Entry<String, ConsumerRunningInfo> next = it.next();
                        String result = ConsumerRunningInfo.analyzeProcessQueue(next.getKey(), next.getValue());
                        if (result.length() > 0) {
                            System.out.println(result);
                        }
                    }
                } else {
                    System.out.println("\n\nWARN: Different subscription in the same group of consumer!!!");
                }
            }
        } else {
            String clientId = commandLine.getOptionValue('i').trim();
            ConsumerRunningInfo consumerRunningInfo = defaultMQAdminExt.getConsumerRunningInfo(group, clientId,
                    jstack);
            if (consumerRunningInfo != null) {
                System.out.println(consumerRunningInfo.formatString());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        defaultMQAdminExt.shutdown();
    }
}

From source file:mrmc.chart.ROCCurvePlot.java

/**
 * Creates an ROC curve that averages together the scores for all readers in
 * the diagonal direction/*from www  . j av  a2 s  .  c om*/
 * 
 * @param treeMap Mapping of readers to points defining a curve
 * @return Series containing the ROC curve points
 */
private XYSeries generateDiagonalROC(TreeMap<String, TreeSet<XYPair>> treeMap) {
    XYSeries diagAvg = new XYSeries("Diagonal Average", false);
    TreeMap<String, TreeSet<XYPair>> rotatedData = new TreeMap<String, TreeSet<XYPair>>();

    // rotate all points in data 45 degrees clockwise about origin
    for (String r : treeMap.keySet()) {
        rotatedData.put(r, new TreeSet<XYPair>());
        for (XYPair point : treeMap.get(r)) {
            double x2 = (point.x + point.y) / Math.sqrt(2.0);
            double y2 = (point.y - point.x) / Math.sqrt(2.0);
            rotatedData.get(r).add(new XYPair(x2, y2));
        }
    }

    // generate linear interpolation with new points
    ArrayList<InterpolatedLine> rotatedLines = new ArrayList<InterpolatedLine>();
    for (String r : rotatedData.keySet()) {
        rotatedLines.add(new InterpolatedLine(rotatedData.get(r)));
    }

    // take vertical sample averages from x = 0 to x = 1
    for (double i = 0; i <= Math.sqrt(2); i += 0.01) {
        double avg = 0;
        int counter = 0;
        for (InterpolatedLine line : rotatedLines) {
            avg += line.getYatDiag(i);
            counter++;
        }

        // rotate points back 45 degrees counterclockwise
        double x1 = i;
        double y1 = (avg / (double) counter);
        double x2 = (x1 * Math.cos(Math.toRadians(45))) - (y1 * Math.sin(Math.toRadians(45)));
        double y2 = (x1 * Math.sin(Math.toRadians(45))) + (y1 * Math.cos(Math.toRadians(45)));
        diagAvg.add(x2, y2);
    }

    diagAvg.add(1, 1);
    return diagAvg;
}

From source file:service.ModuleService.java

public void changePosition(Long moduleId, Long newPosition, Long pkId) {
    Module Module = moduleDao.find(moduleId);
    Long groupId = Module.getGroup().getId();
    updatePositionsAndGetAvailable(groupId, pkId);
    TreeMap<Long, Module> map = new TreeMap();
    List<Module> modules = moduleDao.getActiveModules(groupId, pkId);
    Long oldPosition = Module.getPosition();
    for (Module m : modules) {
        Long GID = m.getId();/* w  ww  .jav a 2 s.  c  o m*/
        if (GID.equals(moduleId)) {
            map.put(newPosition, m);
        } else {
            //  
            if (oldPosition > newPosition) {
                if (m.getPosition() < newPosition || m.getPosition() > oldPosition) {
                    map.put(m.getPosition(), m);
                } else {
                    map.put(m.getPosition() + 1, m);
                }
                //
            } else {
                if (m.getPosition() > newPosition || m.getPosition() < oldPosition) {
                    map.put(m.getPosition(), m);
                } else {
                    map.put(m.getPosition() - 1, m);
                }
            }
        }
    }
    for (Map.Entry<Long, Module> entry : map.entrySet()) {
        Long pos = entry.getKey();
        Module m = entry.getValue();
        m.setPosition(pos);
        if (validate(m)) {
            moduleDao.update(m);
        }
    }
}

From source file:com.google.android.apps.authenticator.dataimport.Importer.java

private int importAccountDbFromJson(JSONObject json, AccountDb accountDb) {
    Iterator<String> it = json.keys();
    int importedAccountCount = 0;
    TreeMap<String, JSONObject> map = new TreeMap<String, JSONObject>();
    // iterate over the JSON objects and put them in a sorted map
    while (it.hasNext()) {
        try {/* ww w .  jav  a2 s  . c  om*/
            String key = it.next();
            JSONObject value = json.getJSONObject(key);
            map.put(key, value);
        } catch (Exception e) {
            Log.e(LOG_TAG, "Unable to deserialize JSON string");
            Log.e(LOG_TAG, e.getMessage());
            return -1;
        }
    }

    for (Map.Entry<String, JSONObject> entry : map.entrySet()) {
        String key = entry.getKey();
        JSONObject accountJson = entry.getValue();
        String name = null;
        String secret = null;
        Integer counter = null;
        String typeString = null;
        AccountDb.OtpType type = null;

        try {
            name = accountJson.getString(KEY_NAME);
            if (accountDb.nameExists(name)) {
                Log.w(LOG_TAG, "Skipping account #" + key + ": already configured");
                continue;
            }
        } catch (JSONException e1) {
            Log.w(LOG_TAG, "Skipping account #" + key + ": name missing");
            continue;
        }

        try {
            secret = accountJson.getString(KEY_ENCODED_SECRET);
        } catch (JSONException e2) {
            Log.w(LOG_TAG, "Skipping account #" + key + ": secret missing");
            continue;
        }

        try {
            typeString = accountJson.getString(KEY_TYPE);
            type = AccountDb.OtpType.valueOf(typeString);
        } catch (JSONException e3) {
            Log.w(LOG_TAG, "Skipping account #" + key + ": type missing");
            continue;
        }

        try {
            counter = accountJson.getInt(KEY_COUNTER);
        } catch (JSONException e4) {
            if (type == AccountDb.OtpType.HOTP) {
                Log.w(LOG_TAG, "Skipping account #" + key + ": counter missing");
                continue;
            } else {
                counter = AccountDb.DEFAULT_HOTP_COUNTER;
            }
        }

        if (name != null && secret != null && counter != null && type != null) {
            accountDb.update(name, secret, name, type, counter);
            importedAccountCount++;
        }
    }

    Log.i(LOG_TAG, "Imported " + importedAccountCount + " accounts");
    return importedAccountCount;
}

From source file:uk.ac.leeds.ccg.andyt.projects.moses.process.RegressionReport_UK1.java

protected static TreeMap<String, double[]> loadCASOptimistaionConstraints(File dataFile) throws IOException {
    TreeMap<String, double[]> result = new TreeMap<String, double[]>();
    BufferedReader a_BufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(dataFile)));
    boolean read = true;
    String line = a_BufferedReader.readLine(); // read header
    String oa_code;/*from w w  w  . jav a2 s .c  o m*/
    String[] fields;
    double[] values;
    while (read) {
        try {
            line = a_BufferedReader.readLine();
            if (line != null) {
                fields = line.split(",");
                oa_code = fields[0];
                values = new double[fields.length - 1];
                for (int i = 0; i < fields.length - 1; i++) {
                    values[i] = new Double(fields[i + 1]);
                }
                result.put(oa_code, values);
            } else {
                read = false;
            }
        } catch (IOException a_IOException) {
            // File read continue...
            read = false;
        }
    }
    return result;
}

From source file:com.alibaba.rocketmq.tools.command.consumer.ConsumerStatusSubCommand.java

@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) {
    DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);

    defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));

    try {/* ww w  .  j  ava2 s. c  om*/
        defaultMQAdminExt.start();

        String group = commandLine.getOptionValue('g').trim();

        ConsumerConnection cc = defaultMQAdminExt.examineConsumerConnectionInfo(group);

        boolean jstack = commandLine.hasOption('s');

        if (!commandLine.hasOption('i')) {
            // ?
            int i = 1;
            long now = System.currentTimeMillis();
            final TreeMap<String/* clientId */, ConsumerRunningInfo> criTable = new TreeMap<String, ConsumerRunningInfo>();
            for (Connection conn : cc.getConnectionSet()) {
                try {
                    ConsumerRunningInfo consumerRunningInfo = defaultMQAdminExt.getConsumerRunningInfo(group,
                            conn.getClientId(), jstack);
                    if (consumerRunningInfo != null) {
                        criTable.put(conn.getClientId(), consumerRunningInfo);
                        String filePath = now + "/" + conn.getClientId();
                        MixAll.string2FileNotSafe(consumerRunningInfo.formatString(), filePath);
                        System.out.printf("%03d  %-40s %-20s %s\n", //
                                i++, //
                                conn.getClientId(), //
                                MQVersion.getVersionDesc(conn.getVersion()), //
                                filePath);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (!criTable.isEmpty()) {
                boolean subSame = ConsumerRunningInfo.analyzeSubscription(criTable);

                boolean rebalanceOK = subSame && ConsumerRunningInfo.analyzeRebalance(criTable);

                if (subSame) {
                    System.out.println("\n\nSame subscription in the same group of consumer");

                    System.out.printf("\n\nRebalance %s\n", rebalanceOK ? "OK" : "Failed");

                    Iterator<Entry<String, ConsumerRunningInfo>> it = criTable.entrySet().iterator();
                    while (it.hasNext()) {
                        Entry<String, ConsumerRunningInfo> next = it.next();
                        String result = ConsumerRunningInfo.analyzeProcessQueue(next.getKey(), next.getValue());
                        if (result.length() > 0) {
                            System.out.println(result);
                        }
                    }
                } else {
                    System.out.println("\n\nWARN: Different subscription in the same group of consumer!!!");
                }
            }
        } else {
            String clientId = commandLine.getOptionValue('i').trim();
            ConsumerRunningInfo consumerRunningInfo = defaultMQAdminExt.getConsumerRunningInfo(group, clientId,
                    jstack);
            if (consumerRunningInfo != null) {
                System.out.println(consumerRunningInfo.formatString());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        defaultMQAdminExt.shutdown();
    }
}

From source file:org.modeshape.web.jcr.rest.handler.RestItemHandlerImpl.java

private TreeMap<String, JsonNode> createNodesByPathMap(JsonNode requestBodyJSON) {
    TreeMap<String, JsonNode> nodesByPath = new TreeMap<String, JsonNode>();
    for (Iterator<?> iterator = requestBodyJSON.fields(); iterator.hasNext();) {
        String key = iterator.next().toString();
        String nodePath = absPath(key);
        JsonNode nodeJSON = requestBodyJSON.get(key);
        nodesByPath.put(nodePath, nodeJSON);
    }//from   w w w . ja  v a  2  s  .c o m
    return nodesByPath;
}

From source file:com.espertech.esper.epl.core.OrderByProcessorImpl.java

public EventBean[] sort(EventBean[] outgoingEvents, Object[] orderKeys,
        ExprEvaluatorContext exprEvaluatorContext) {
    TreeMap<Object, Object> sort = new TreeMap<Object, Object>(factory.getComparator());

    if (outgoingEvents == null || outgoingEvents.length < 2) {
        return outgoingEvents;
    }//from w  w  w. j  a  v  a 2 s .  c om

    for (int i = 0; i < outgoingEvents.length; i++) {
        Object entry = sort.get(orderKeys[i]);
        if (entry == null) {
            sort.put(orderKeys[i], outgoingEvents[i]);
        } else if (entry instanceof EventBean) {
            List<EventBean> list = new ArrayList<EventBean>();
            list.add((EventBean) entry);
            list.add(outgoingEvents[i]);
            sort.put(orderKeys[i], list);
        } else {
            List<EventBean> list = (List<EventBean>) entry;
            list.add(outgoingEvents[i]);
        }
    }

    EventBean[] result = new EventBean[outgoingEvents.length];
    int count = 0;
    for (Object entry : sort.values()) {
        if (entry instanceof List) {
            List<EventBean> output = (List<EventBean>) entry;
            for (EventBean theEvent : output) {
                result[count++] = theEvent;
            }
        } else {
            result[count++] = (EventBean) entry;
        }
    }
    return result;
}

From source file:io.mapzone.arena.analytics.graph.ui.GraphPanel.java

@Override
public void createContents(final Composite parent) {
    try {/*  ww w .  j  ava  2s .  com*/
        if (!featureLayer.isPresent()) {
            tk().createFlowText(parent, i18n.get("noFeatures"));
            return;
        }
        // this.parent = parent;
        parent.setLayout(FormLayoutFactory.defaults().create());

        MdToolbar2 toolbar = tk().createToolbar(parent, SWT.TOP);
        new NodeStylerItem(toolbar);
        new EdgeStylerItem(toolbar);

        final TreeMap<String, GraphFunction> functions = Maps.newTreeMap();
        for (Class<GraphFunction> cl : AVAILABLE_FUNCTIONS) {
            try {
                GraphFunction function = cl.newInstance();
                functions.put(function.title(), function);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        final Composite functionContainer = tk().createComposite(parent, SWT.NONE);

        final ComboViewer combo = new ComboViewer(parent,
                SWT.SINGLE | SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY);
        combo.setContentProvider(new ArrayContentProvider());
        combo.setInput(functions.keySet());
        combo.addSelectionChangedListener(ev -> {
            String selected = SelectionAdapter.on(ev.getSelection()).first(String.class).get();
            GraphFunction function = functions.get(selected);

            FormDataFactory.on(functionContainer).top(combo.getCombo(), 5).height(function.preferredHeight())
                    .left(0).right(100);

            UIUtils.disposeChildren(functionContainer);
            // create panel
            //                Section section = tk().createSection( functionContainer, function.description(), ExpandableComposite.TREE_NODE, Section.SHORT_TITLE_BAR, Section.FOCUS_TITLE, SWT.BORDER );
            //                section.setBackground( UIUtils.getColor( 235,  235, 235) );
            //                ((Composite)section.getClient()).setLayout( FormLayoutFactory.defaults().create() );

            IPanelSection section = tk().createPanelSection(functionContainer, function.description(),
                    SWT.Expand, IPanelSection.EXPANDABLE);
            section.getControl().setBackground(UIUtils.getColor(235, 235, 235));
            section.getBody().setBackground(UIUtils.getColor(235, 235, 235));
            section.setExpanded(true);
            section.getBody().setLayout(FormLayoutFactory.defaults().create());

            //
            graph.clear();
            function.createContents(tk(), section.getBody(), graph);
            if (!section.isExpanded()) {
                section.setExpanded(true);
            }

            FormDataFactory.on(section.getBody()).fill();

            // functionContainer.layout();
            parent.layout();
        });

        //
        // mapContainer
        mapContainer = tk().createComposite(parent, SWT.NONE);
        mapContainer.setLayout(new FillLayout());
        if (mapViewer != null) {
            mapViewer.dispose();
        }
        createMapViewer();

        // layout
        on(toolbar.getControl()).left(0, 3).right(100, -3).top(0, 5);

        final Label selectLabel = tk().createLabel(parent, i18n.get("selectFunction"), SWT.NONE);
        on(selectLabel).top(toolbar.getControl(), 8).left(1);
        on(combo.getCombo()).top(selectLabel, 2).left(1);
        on(functionContainer).top(combo.getCombo(), 5).height(0).left(0).right(100);
        on(mapContainer).fill().top(functionContainer, 5);
    } catch (Exception e) {
        StatusDispatcher.handleError("", e);
    }
}