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:at.tuwien.ifs.somtoolbox.apps.viewer.controls.ClusteringControl.java

public void init() {

    maxCluster = state.growingLayer.getXSize() * state.growingLayer.getYSize();

    spinnerNoCluster = new JSpinner(new SpinnerNumberModel(1, 1, maxCluster, 1));
    spinnerNoCluster.addChangeListener(new ChangeListener() {
        @Override/*from   w w w . j a va 2 s.  co m*/
        public void stateChanged(ChangeEvent e) {
            numClusters = (Integer) ((JSpinner) e.getSource()).getValue();
            SortedMap<Integer, ClusterElementsStorage> m = mapPane.getMap().getCurrentClusteringTree()
                    .getAllClusteringElements();
            if (m.containsKey(numClusters)) {
                st = m.get(numClusters).sticky;
            } else {
                st = false;
            }
            sticky.setSelected(st);
            redrawClustering();
        }
    });

    JPanel clusterPanel = UiUtils.makeBorderedPanel(new FlowLayout(FlowLayout.LEFT, 10, 0), "Clusters");

    sticky.setToolTipText(
            "Marks this number of clusters as sticky for a certain leve; the next set of clusters will have a smaller boundary");
    sticky.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            st = sticky.isSelected();
            SortedMap<Integer, ClusterElementsStorage> m = mapPane.getMap().getCurrentClusteringTree()
                    .getAllClusteringElements();
            if (m.containsKey(numClusters)) {
                ClusterElementsStorage c = m.get(numClusters);
                c.sticky = st;
                // System.out.println("test");
                // ((ClusterElementsStorageNode)m.get(numClusters)).sticky = st;
                redrawClustering();
            }
        }
    });

    colorCluster = new JCheckBox("colour", state.colorClusters);
    colorCluster.setToolTipText("Fill the clusters in colours");
    colorCluster.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            state.colorClusters = colorCluster.isSelected();
            // TODO: Palette anzeigen (?)
            redrawClustering();
        }
    });

    UiUtils.fillPanel(clusterPanel, new JLabel("#"), spinnerNoCluster, sticky, colorCluster);
    getContentPane().add(clusterPanel, c.nextRow());

    dendogramPanel = UiUtils.makeBorderedPanel(new GridLayout(0, 1), "Dendogram");
    getContentPane().add(dendogramPanel, c.nextRow());

    JPanel numLabelPanel = UiUtils.makeBorderedPanel(new GridBagLayout(), "Labels");
    GridBagConstraintsIFS gcLabels = new GridBagConstraintsIFS();

    labelSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 99, 1));
    labelSpinner.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            numLabels = (Integer) ((JSpinner) e.getSource()).getValue();
            state.clusterWithLabels = numLabels;
            redrawClustering();
        }
    });

    this.showValues = new JCheckBox("values", state.labelsWithValues);
    this.showValues.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            state.labelsWithValues = showValues.isSelected();
            redrawClustering();
        }
    });

    int start = new Double((1 - state.clusterByValue) * 100).intValue();
    valueQe = new JSlider(0, 100, start);
    valueQe.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            int byValue = ((JSlider) e.getSource()).getValue();
            state.clusterByValue = 1 - byValue / 100;
            redrawClustering();
        }
    });

    numLabelPanel.add(new JLabel("# Labels"), gcLabels);
    numLabelPanel.add(labelSpinner, gcLabels.nextCol());
    numLabelPanel.add(showValues, gcLabels.nextCol());
    numLabelPanel.add(valueQe, gcLabels.nextRow().setGridWidth(3).setFill(GridBagConstraints.HORIZONTAL));
    getContentPane().add(numLabelPanel, c.nextRow());

    Hashtable<Integer, JLabel> labelTable = new Hashtable<Integer, JLabel>();
    labelTable.put(0, new JLabel("by Value"));
    labelTable.put(100, new JLabel("by Qe"));
    valueQe.setToolTipText("Method how to select representative labels - by QE, or the attribute values");
    valueQe.setLabelTable(labelTable);
    valueQe.setPaintLabels(true);

    final JComboBox initialisationBox = new JComboBox(KMeans.InitType.values());
    initialisationBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Object o = mapPane.getMap().getClusteringTreeBuilder();
            if (o instanceof KMeansTreeBuilder) {
                ((KMeansTreeBuilder) o).reInit((KMeans.InitType) initialisationBox.getSelectedItem());
                // FIXME: is this call needed?
                mapPane.getMap().getCurrentClusteringTree().getAllClusteringElements();
                redrawClustering();
            }
        }
    });

    getContentPane().add(UiUtils.fillPanel(kmeansInitialisationPanel, new JLabel("k-Means initialisation"),
            initialisationBox), c.nextRow());

    JPanel borderPanel = new TitledCollapsiblePanel("Border", new GridLayout(1, 4), true);

    JSpinner borderSpinner = new JSpinner(
            new SpinnerNumberModel(ClusteringTree.INITIAL_BORDER_WIDTH_MAGNIFICATION_FACTOR, 0.1, 5, 0.1));
    borderSpinner.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            state.clusterBorderWidthMagnificationFactor = ((Double) ((JSpinner) e.getSource()).getValue())
                    .floatValue();
            redrawClustering();
        }
    });

    borderPanel.add(new JLabel("width"));
    borderPanel.add(borderSpinner);

    borderPanel.add(new JLabel("colour"));
    buttonColour = new JButton("");
    buttonColour.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            new ClusterBoderColorChooser(state.parentFrame, state.clusterBorderColour, ClusteringControl.this);
        }
    });
    buttonColour.setBackground(state.clusterBorderColour);
    borderPanel.add(buttonColour);

    getContentPane().add(borderPanel, c.nextRow());

    JPanel evaluationPanel = new TitledCollapsiblePanel("Cluster Evaluation", new GridLayout(3, 2), true);

    evaluationPanel.add(new JLabel("quality measure"));
    qualityMeasureButton = new JButton();
    qualityMeasureButton.setText("ent/pur calc");
    qualityMeasureButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("doing entropy here");
            ClusteringTree clusteringTree = state.mapPNode.getClusteringTree();
            if (clusteringTree == null) {
                // we have not clustered yet
                return;
            }
            // System.out.println(clusteringTree.getChildrenCount());

            // FIXME put this in a method and call it on numcluster.change()
            SOMLibClassInformation classInfo = state.inputDataObjects.getClassInfo();
            ArrayList<ClusterNode> clusters = clusteringTree.getNodesAtLevel(numClusters);
            System.out.println(clusters.size());
            // EntropyMeasure.computeEntropy(clusters, classInfo);
            EntropyAndPurityCalculator eapc = new EntropyAndPurityCalculator(clusters, classInfo);
            // FIXME round first
            entropyLabel.setText(String.valueOf(eapc.getEntropy()));
            purityLabel.setText(String.valueOf(eapc.getPurity()));

        }
    });
    evaluationPanel.add(qualityMeasureButton);
    GridBagConstraintsIFS gcEval = new GridBagConstraintsIFS();

    evaluationPanel.add(new JLabel("entropy"), gcEval);
    evaluationPanel.add(new JLabel("purity"), gcEval.nextCol());

    entropyLabel = new JLabel("n/a");
    purityLabel = new JLabel("n/a");

    evaluationPanel.add(entropyLabel, gcEval.nextRow());
    evaluationPanel.add(purityLabel, gcEval.nextCol());

    getContentPane().add(evaluationPanel, c.nextRow());

    JPanel panelButtons = new JPanel(new GridLayout(1, 4));

    JButton saveButton = new JButton("Save");
    saveButton.setFont(smallFont);
    saveButton.setMargin(SMALL_INSETS);
    saveButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser;
            if (state.fileChooser.getSelectedFile() != null) {
                fileChooser = new JFileChooser(state.fileChooser.getSelectedFile().getPath());
            } else {
                fileChooser = new JFileChooser();
            }
            fileChooser.addChoosableFileFilter(clusteringFilter);
            fileChooser.addChoosableFileFilter(xmlFilter);

            File filePath = ExportUtils.getFilePath(ClusteringControl.this, fileChooser,
                    "Save Clustering and Labels");

            if (filePath != null) {
                if (xmlFilter.accept(filePath)) {
                    LabelXmlUtils.saveLabelsToFile(state.mapPNode, filePath);
                } else {
                    try {
                        FileOutputStream fos = new FileOutputStream(filePath);
                        GZIPOutputStream gzipOs = new GZIPOutputStream(fos);
                        PObjectOutputStream oos = new PObjectOutputStream(gzipOs);

                        oos.writeObjectTree(mapPane.getMap().getCurrentClusteringTree());
                        oos.writeObjectTree(mapPane.getMap().getManualLabels());
                        oos.writeInt(state.clusterWithLabels);
                        oos.writeBoolean(state.labelsWithValues);
                        oos.writeDouble(state.clusterByValue);
                        oos.writeObject(spinnerNoCluster.getValue());

                        oos.close();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
                // keep the selected path for future references
                state.fileChooser.setSelectedFile(filePath.getParentFile());
            }
        }
    });
    panelButtons.add(saveButton);

    JButton loadButton = new JButton("Load");
    loadButton.setFont(smallFont);
    loadButton.setMargin(SMALL_INSETS);
    loadButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = getFileChooser();
            fileChooser.setName("Open Clustering");
            fileChooser.addChoosableFileFilter(xmlFilter);
            fileChooser.addChoosableFileFilter(clusteringFilter);

            int returnVal = fileChooser.showDialog(ClusteringControl.this, "Open");
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File filePath = fileChooser.getSelectedFile();
                if (xmlFilter.accept(filePath)) {
                    PNode restoredLabels = null;
                    try {
                        restoredLabels = LabelXmlUtils.restoreLabelsFromFile(fileChooser.getSelectedFile());
                        PNode manual = state.mapPNode.getManualLabels();

                        ArrayList<PNode> tmp = new ArrayList<PNode>();
                        for (ListIterator<?> iter = restoredLabels.getChildrenIterator(); iter.hasNext();) {
                            PNode element = (PNode) iter.next();
                            tmp.add(element);
                        }
                        manual.addChildren(tmp);
                        Logger.getLogger("at.tuwien.ifs.somtoolbox")
                                .info("Successfully loaded cluster labels.");
                    } catch (Exception e1) {
                        e1.printStackTrace();
                        Logger.getLogger("at.tuwien.ifs.somtoolbox")
                                .info("Error loading cluster labels: " + e1.getMessage());
                    }

                } else {

                    try {
                        FileInputStream fis = new FileInputStream(filePath);
                        GZIPInputStream gzipIs = new GZIPInputStream(fis);
                        ObjectInputStream ois = new ObjectInputStream(gzipIs);
                        ClusteringTree tree = (ClusteringTree) ois.readObject();

                        PNode manual = (PNode) ois.readObject();
                        PNode all = mapPane.getMap().getManualLabels();
                        ArrayList<PNode> tmp = new ArrayList<PNode>();
                        for (ListIterator<?> iter = manual.getChildrenIterator(); iter.hasNext();) {
                            PNode element = (PNode) iter.next();
                            tmp.add(element);
                        }
                        all.addChildren(tmp);

                        state.clusterWithLabels = ois.readInt();
                        labelSpinner.setValue(state.clusterWithLabels);
                        state.labelsWithValues = ois.readBoolean();
                        showValues.setSelected(state.labelsWithValues);
                        state.clusterByValue = ois.readDouble();
                        valueQe.setValue(new Double((1 - state.clusterByValue) * 100).intValue());

                        mapPane.getMap().buildTree(tree);
                        spinnerNoCluster.setValue(ois.readObject());

                        ois.close();
                        Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Successfully loaded clustering.");
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        Logger.getLogger("at.tuwien.ifs.somtoolbox")
                                .info("Error loading clustering: " + ex.getMessage());
                    }

                }
                // keep the selected path for future references
                state.fileChooser.setSelectedFile(filePath.getParentFile());
            }
        }

    });
    panelButtons.add(loadButton);

    JButton exportImages = new JButton("Export");
    exportImages.setFont(smallFont);
    exportImages.setMargin(SMALL_INSETS);
    exportImages.setToolTipText("Export labels as images (not yet working)");
    exportImages.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            if (CommonSOMViewerStateData.fileNamePrefix != null
                    && !CommonSOMViewerStateData.fileNamePrefix.equals("")) {
                fileChooser.setCurrentDirectory(new File(CommonSOMViewerStateData.fileNamePrefix));
            } else {
                fileChooser.setCurrentDirectory(state.getFileChooser().getCurrentDirectory());
            }
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            if (fileChooser.getSelectedFile() != null) { // reusing the dialog
                fileChooser.setSelectedFile(null);
            }
            fileChooser.setName("Choose path");
            int returnVal = fileChooser.showDialog(ClusteringControl.this, "Choose path");
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                // save images
                String path = fileChooser.getSelectedFile().getAbsolutePath();
                Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Writing label images to " + path);
            }
        }
    });
    panelButtons.add(exportImages);

    JButton deleteManual = new JButton("Delete");
    deleteManual.setFont(smallFont);
    deleteManual.setMargin(SMALL_INSETS);
    deleteManual.setToolTipText("Delete manually added labels.");
    deleteManual.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            state.mapPNode.getManualLabels().removeAllChildren();
            Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Manual Labels deleted.");
        }
    });
    panelButtons.add(deleteManual);
    c.anchor = GridBagConstraints.NORTH;
    this.getContentPane().add(panelButtons, c.nextRow());

    this.setVisible(true);
}

From source file:org.jahia.services.render.scripting.bundle.BundleScriptResolver.java

/**
 * Method for registering a new resource view for a bundle.
 *
 * @param bundle the bundle to register views for
 * @param path   the path of the view to register
 *///from  w  w  w.ja va2 s .co  m
public void addBundleScript(Bundle bundle, String path) {
    if (path.split("/").length != 4) {
        return;
    }
    ViewResourceInfo scriptResource = new ViewResourceInfo(path);
    final String symbolicName = bundle.getSymbolicName();
    SortedMap<String, ViewResourceInfo> existingBundleScripts = availableScripts.get(symbolicName);
    if (existingBundleScripts == null) {
        existingBundleScripts = new TreeMap<>();
        availableScripts.put(symbolicName, existingBundleScripts);
        existingBundleScripts.put(scriptResource.path, scriptResource);
    } else if (!existingBundleScripts.containsKey(scriptResource.path)) {
        existingBundleScripts.put(scriptResource.path, scriptResource);
    } else {
        // if we already have a script resource available, retrieve it to make sure we update it with new properties
        // this is required because it is possible that the properties file is not found when the view is first processed due to
        // file ordering processing in ModulesDataSource.start.process method.
        scriptResource = existingBundleScripts.get(scriptResource.path);
    }

    String properties = StringUtils.substringBeforeLast(path, ".") + ".properties";
    final URL propertiesResource = bundle.getResource(properties);
    if (propertiesResource != null) {
        Properties p = new Properties();
        try {
            p.load(propertiesResource.openStream());
        } catch (IOException e) {
            logger.error("Cannot read properties", e);
        }
        scriptResource.setProperties(p);
    } else {
        scriptResource.setProperties(new Properties());
    }
    clearCaches();
}

From source file:com.activecq.tools.errorpagehandler.impl.ErrorPageHandlerImpl.java

/**
 * Merge two Maps together. In the event of any key collisions the Master map wins
 *
 * Any blank value keys are dropped from the final Map
 *
 * Map is sorted by value (String) length
 *
 * @param master//from w  ww  .j ava 2s .  co  m
 * @param slave
 * @return
 */
private SortedMap<String, String> mergeMaps(SortedMap<String, String> master, SortedMap<String, String> slave) {
    SortedMap<String, String> map = new TreeMap<String, String>(new StringLengthComparator());

    for (final String key : master.keySet()) {
        if (StringUtils.isNotBlank(master.get(key))) {
            map.put(key, master.get(key));
        }
    }

    for (final String key : slave.keySet()) {
        if (master.containsKey(key)) {
            continue;
        }
        if (StringUtils.isNotBlank(slave.get(key))) {
            map.put(key, slave.get(key));
        }
    }

    return map;
}

From source file:okuyama.imdst.util.DataDispatcher.java

/**
 * Rule?????????KeyNode?????????.<br>
 * ConsistentHash.<br>//  ww w  . j a  v  a  2 s  .c om
 * ????????????????6?Third????9??<br>
 *
 * @param key 
 * @param useOldCircle 
 * @return String[] ?(??????)
 */
private static String[] decisionConsistentHashKeyNode(String key, boolean useOldCircle) {
    String[] ret = null;
    boolean noWaitFlg = false;
    SortedMap useNodeCircle = null;
    String targetNode = null;
    String[] mainDataNodeInfo = null;
    String[] slaveDataNodeInfo = null;
    String[] thirdDataNodeInfo = null;

    // ??
    String[][] allNodeDetailList = (String[][]) keyNodeMap.get("list");

    // Key?Hash?
    int execKeyInt = sha1Hash4Int(key);

    // ??
    // useOldCircle???????
    if (useOldCircle && oldCircle != null) {
        useNodeCircle = oldCircle;
    } else {
        useNodeCircle = nodeCircle;
    }

    // ?
    int hash = sha1Hash4Int(key);

    if (!useNodeCircle.containsKey(hash)) {
        SortedMap<Integer, Map> tailMap = useNodeCircle.tailMap(hash);
        if (tailMap.isEmpty()) {
            hash = ((Integer) useNodeCircle.firstKey()).intValue();
        } else {
            hash = ((Integer) tailMap.firstKey()).intValue();
        }
    }

    // ???
    targetNode = (String) useNodeCircle.get(hash);

    // ??
    mainDataNodeInfo = (String[]) keyNodeMap.get(targetNode);
    // ??
    slaveDataNodeInfo = (String[]) keyNodeMap.get(targetNode + "_sub");
    // ??
    thirdDataNodeInfo = (String[]) keyNodeMap.get(targetNode + "_third");

    // ????????
    if (thirdDataNodeInfo != null) {
        ret = new String[9];

        ret[3] = slaveDataNodeInfo[0];
        ret[4] = slaveDataNodeInfo[1];
        ret[5] = slaveDataNodeInfo[2];
        ret[6] = thirdDataNodeInfo[0];
        ret[7] = thirdDataNodeInfo[1];
        ret[8] = thirdDataNodeInfo[2];

    } else if (slaveDataNodeInfo != null) {
        // ????????
        ret = new String[6];

        ret[3] = slaveDataNodeInfo[0];
        ret[4] = slaveDataNodeInfo[1];
        ret[5] = slaveDataNodeInfo[2];
    } else {
        ret = new String[3];
    }

    ret[0] = mainDataNodeInfo[0];
    ret[1] = mainDataNodeInfo[1];
    ret[2] = mainDataNodeInfo[2];

    // ??????????(???)
    // ????????Wait
    while (true) {
        noWaitFlg = false;
        // ????
        if (ret.length == 3) {
            if (!StatusUtil.isWaitStatus(mainDataNodeInfo[2]))
                noWaitFlg = true;
        }

        if (ret.length == 6) {
            if (!StatusUtil.isWaitStatus(mainDataNodeInfo[2])
                    && !StatusUtil.isWaitStatus(slaveDataNodeInfo[2])) {

                noWaitFlg = true;
            }
        }

        if (ret.length == 9) {
            if (!StatusUtil.isWaitStatus(mainDataNodeInfo[2]) && !StatusUtil.isWaitStatus(slaveDataNodeInfo[2])
                    && !StatusUtil.isWaitStatus(thirdDataNodeInfo[2])) {

                noWaitFlg = true;
            }
        }

        if (noWaitFlg)
            break;

        try {
            //System.out.println("DataDispatcher - ?");
            Thread.sleep(50);
        } catch (Exception e) {
        }
    }

    // ??
    // ?MasterManagerHelper??
    StatusUtil.addNodeUse(mainDataNodeInfo[2]);

    if (ret.length > 3) {
        StatusUtil.addNodeUse(slaveDataNodeInfo[2]);
    }

    if (ret.length > 6) {
        StatusUtil.addNodeUse(thirdDataNodeInfo[2]);
    }

    return ret;
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.router.TrafficRouter.java

/**
 * Utilizes the hashValues stored with each cache to select the cache that
 * the specified hash should map to.//  w w w  .ja v a2s  .  c o  m
 * 
 * @param caches
 *            the list of caches to choose from
 * @param request
 *            the request string from which the hash will be generated
 * @return a cache or null if no cache can be found to map to
 */
protected SortedMap<Double, Cache> consistentHash(final List<Cache> caches, final String request) {
    double hash = 0;
    HashFunction hashFunction = null;
    try {
        hashFunction = (HashFunction) hashFunctionPool.borrowObject();
        try {
            hash = hashFunction.hash(request);
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        hashFunctionPool.returnObject(hashFunction);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    if (hash == 0) {
        LOGGER.warn("Problem with hashFunctionPool, request: " + request);
        return null;
    }

    final SortedMap<Double, Cache> cacheMap = new TreeMap<Double, Cache>();

    for (final Cache cache : caches) {
        final double r = cache.getClosestHash(hash);
        if (r == 0) {
            LOGGER.warn("Error: getClosestHash returned 0: " + cache);
            return null;
        }

        double diff = Math.abs(r - hash);

        if (cacheMap.containsKey(diff)) {
            LOGGER.warn("Error: cacheMap contains diff " + diff + "; incrementing to avoid collision");
            long bits = Double.doubleToLongBits(diff);

            while (cacheMap.containsKey(diff)) {
                bits++;
                diff = Double.longBitsToDouble(bits);
            }
        }

        cacheMap.put(diff, cache);
    }

    return cacheMap;
}

From source file:com.oltpbenchmark.catalog.Catalog.java

/**
 * Construct the set of Table objects from a given Connection handle
 * @param conn//from   w  ww.  j a  v a 2 s .co  m
 * @return
 * @throws SQLException
 * @see http://docs.oracle.com/javase/6/docs/api/java/sql/DatabaseMetaData.html
 */
protected void init() throws SQLException {
    // Load the database's DDL
    this.benchmark.createDatabase(DB_TYPE, this.conn);

    // TableName -> ColumnName -> <FkeyTable, FKeyColumn>
    Map<String, Map<String, Pair<String, String>>> foreignKeys = new HashMap<String, Map<String, Pair<String, String>>>();

    DatabaseMetaData md = conn.getMetaData();
    ResultSet table_rs = md.getTables(null, null, null, new String[] { "TABLE" });
    while (table_rs.next()) {
        if (LOG.isDebugEnabled())
            LOG.debug(SQLUtil.debug(table_rs));
        String internal_table_name = table_rs.getString(3);
        String table_name = origTableNames.get(table_rs.getString(3).toUpperCase());
        assert (table_name != null) : "Unexpected table '" + table_rs.getString(3) + "' from catalog";
        LOG.debug(String.format("ORIG:%s -> CATALOG:%s", internal_table_name, table_name));

        String table_type = table_rs.getString(4);
        if (table_type.equalsIgnoreCase("TABLE") == false)
            continue;
        Table catalog_tbl = new Table(table_name);

        // COLUMNS
        if (LOG.isDebugEnabled())
            LOG.debug("Retrieving COLUMN information for " + table_name);
        ResultSet col_rs = md.getColumns(null, null, internal_table_name, null);
        while (col_rs.next()) {
            if (LOG.isTraceEnabled())
                LOG.trace(SQLUtil.debug(col_rs));
            String col_name = col_rs.getString(4);
            int col_type = col_rs.getInt(5);
            String col_typename = col_rs.getString(6);
            Integer col_size = col_rs.getInt(7);
            String col_defaultValue = col_rs.getString(13);
            boolean col_nullable = col_rs.getString(18).equalsIgnoreCase("YES");
            boolean col_autoinc = false; // FIXME col_rs.getString(22).toUpperCase().equals("YES");

            Column catalog_col = new Column(catalog_tbl, col_name, col_type, col_typename, col_size);
            catalog_col.setDefaultValue(col_defaultValue);
            catalog_col.setAutoincrement(col_autoinc);
            catalog_col.setNullable(col_nullable);
            // FIXME col_catalog.setSigned();

            if (LOG.isDebugEnabled())
                LOG.debug(
                        String.format("Adding %s.%s [%s / %d]", table_name, col_name, col_typename, col_type));
            catalog_tbl.addColumn(catalog_col);
        } // WHILE
        col_rs.close();

        // PRIMARY KEYS
        if (LOG.isDebugEnabled())
            LOG.debug("Retrieving PRIMARY KEY information for " + table_name);
        ResultSet pkey_rs = md.getPrimaryKeys(null, null, internal_table_name);
        SortedMap<Integer, String> pkey_cols = new TreeMap<Integer, String>();
        while (pkey_rs.next()) {
            String col_name = pkey_rs.getString(4);
            assert (catalog_tbl.getColumnByName(col_name) != null) : String
                    .format("Unexpected primary key column %s.%s", table_name, col_name);
            int col_idx = pkey_rs.getShort(5);
            // HACK: SQLite doesn't return the KEY_SEQ, so if we get back
            //       a zero for this value, then we'll just length of the pkey_cols map
            if (col_idx == 0)
                col_idx = pkey_cols.size();
            LOG.debug(String.format("PKEY[%02d]: %s.%s", col_idx, table_name, col_name));
            assert (pkey_cols.containsKey(col_idx) == false);
            pkey_cols.put(col_idx, col_name);
        } // WHILE
        pkey_rs.close();
        catalog_tbl.setPrimaryKeyColumns(pkey_cols.values());

        // INDEXES
        if (LOG.isDebugEnabled())
            LOG.debug("Retrieving INDEX information for " + table_name);
        ResultSet idx_rs = md.getIndexInfo(null, null, internal_table_name, false, false);
        while (idx_rs.next()) {
            if (LOG.isDebugEnabled())
                LOG.debug(SQLUtil.debug(idx_rs));
            boolean idx_unique = (idx_rs.getBoolean(4) == false);
            String idx_name = idx_rs.getString(6);
            int idx_type = idx_rs.getShort(7);
            int idx_col_pos = idx_rs.getInt(8) - 1;
            String idx_col_name = idx_rs.getString(9);
            String sort = idx_rs.getString(10);
            SortDirectionType idx_direction;
            if (sort != null) {
                idx_direction = sort.equalsIgnoreCase("A") ? SortDirectionType.ASC : SortDirectionType.DESC;
            } else
                idx_direction = null;

            Index catalog_idx = catalog_tbl.getIndex(idx_name);
            if (catalog_idx == null) {
                catalog_idx = new Index(catalog_tbl, idx_name, idx_type, idx_unique);
                catalog_tbl.addIndex(catalog_idx);
            }
            assert (catalog_idx != null);
            catalog_idx.addColumn(idx_col_name, idx_direction, idx_col_pos);
        } // WHILE
        idx_rs.close();

        // FOREIGN KEYS
        if (LOG.isDebugEnabled())
            LOG.debug("Retrieving FOREIGN KEY information for " + table_name);
        ResultSet fk_rs = md.getImportedKeys(null, null, internal_table_name);
        foreignKeys.put(table_name, new HashMap<String, Pair<String, String>>());
        while (fk_rs.next()) {
            if (LOG.isDebugEnabled())
                LOG.debug(table_name + " => " + SQLUtil.debug(fk_rs));
            assert (fk_rs.getString(7).equalsIgnoreCase(table_name));

            String colName = fk_rs.getString(8);
            String fk_tableName = origTableNames.get(fk_rs.getString(3).toUpperCase());
            String fk_colName = fk_rs.getString(4);

            foreignKeys.get(table_name).put(colName, Pair.of(fk_tableName, fk_colName));
        } // WHILE
        fk_rs.close();

        tables.put(table_name, catalog_tbl);
    } // WHILE
    table_rs.close();

    // FOREIGN KEYS
    if (LOG.isDebugEnabled())
        LOG.debug("Foreign Key Mappings:\n" + StringUtil.formatMaps(foreignKeys));
    for (Table catalog_tbl : tables.values()) {
        Map<String, Pair<String, String>> fk = foreignKeys.get(catalog_tbl.getName());
        for (Entry<String, Pair<String, String>> e : fk.entrySet()) {
            String colName = e.getKey();
            Column catalog_col = catalog_tbl.getColumnByName(colName);
            assert (catalog_col != null);

            Pair<String, String> fkey = e.getValue();
            assert (fkey != null);

            Table fkey_tbl = tables.get(fkey.first);
            if (fkey_tbl == null) {
                throw new RuntimeException("Unexpected foreign key parent table " + fkey);
            }
            Column fkey_col = fkey_tbl.getColumnByName(fkey.second);
            if (fkey_col == null) {
                throw new RuntimeException("Unexpected foreign key parent column " + fkey);
            }

            if (LOG.isDebugEnabled())
                LOG.debug(catalog_col.fullName() + " -> " + fkey_col.fullName());
            catalog_col.setForeignKey(fkey_col);
        } // FOR
    } // FOR

    return;
}

From source file:com.oneops.transistor.service.BomManagerImpl.java

private SortedMap<Integer, SortedMap<Integer, List<CmsCIRelation>>> getOrderedClouds(
        List<CmsCIRelation> cloudRels, boolean reverse) {

    SortedMap<Integer, SortedMap<Integer, List<CmsCIRelation>>> result = reverse
            ? new TreeMap<Integer, SortedMap<Integer, List<CmsCIRelation>>>(Collections.reverseOrder())
            : new TreeMap<Integer, SortedMap<Integer, List<CmsCIRelation>>>();

    for (CmsCIRelation binding : cloudRels) {

        Integer priority = Integer.valueOf(binding.getAttribute("priority").getDjValue());
        Integer order = 1;//from   w ww  .j a  va 2  s  . com
        if (binding.getAttributes().containsKey("dpmt_order")) {
            order = Integer.valueOf(binding.getAttribute("dpmt_order").getDjValue());
        }
        if (!result.containsKey(priority)) {
            result.put(priority, new TreeMap<Integer, List<CmsCIRelation>>());
        }
        if (!result.get(priority).containsKey(order)) {
            result.get(priority).put(order, new ArrayList<CmsCIRelation>());
        }
        result.get(priority).get(order).add(binding);
    }

    return result;
}

From source file:lisong_mechlab.view.graphs.DamageGraph.java

private TableXYDataset getSeries() {
    final Collection<Modifier> modifiers = loadout.getModifiers();
    SortedMap<Weapon, List<Pair<Double, Double>>> data = new TreeMap<Weapon, List<Pair<Double, Double>>>(
            new Comparator<Weapon>() {
                @Override//from w  ww  .  j a  v a2 s .c o  m
                public int compare(Weapon aO1, Weapon aO2) {
                    int comp = Double.compare(aO2.getRangeMax(modifiers), aO1.getRangeMax(modifiers));
                    if (comp == 0)
                        return aO1.compareTo(aO2);
                    return comp;
                }
            });

    Double[] ranges = WeaponRanges.getRanges(loadout);
    for (double range : ranges) {
        Set<Entry<Weapon, Double>> damageDistributio = maxSustainedDPS.getWeaponRatios(range).entrySet();
        for (Map.Entry<Weapon, Double> entry : damageDistributio) {
            final Weapon weapon = entry.getKey();
            final double ratio = entry.getValue();
            final double dps = weapon.getStat("d/s", modifiers);
            final double rangeEff = weapon.getRangeEffectivity(range, modifiers);

            if (!data.containsKey(weapon)) {
                data.put(weapon, new ArrayList<Pair<Double, Double>>());
            }
            data.get(weapon).add(new Pair<Double, Double>(range, dps * ratio * rangeEff));
        }
    }

    DefaultTableXYDataset dataset = new DefaultTableXYDataset();
    for (Map.Entry<Weapon, List<Pair<Double, Double>>> entry : data.entrySet()) {
        XYSeries series = new XYSeries(entry.getKey().getName(), true, false);
        for (Pair<Double, Double> pair : entry.getValue()) {
            series.add(pair.first, pair.second);
        }
        dataset.addSeries(series);
    }
    return dataset;
}

From source file:lisong_mechlab.view.graphs.SustainedDpsGraph.java

private TableXYDataset getSeries() {
    final Collection<Modifier> modifiers = loadout.getModifiers();
    SortedMap<Weapon, List<Pair<Double, Double>>> data = new TreeMap<Weapon, List<Pair<Double, Double>>>(
            new Comparator<Weapon>() {
                @Override//from w  ww . j a  v a  2 s .co m
                public int compare(Weapon aO1, Weapon aO2) {
                    int comp = Double.compare(aO2.getRangeMax(modifiers), aO1.getRangeMax(modifiers));
                    if (comp == 0)
                        return aO1.compareTo(aO2);
                    return comp;
                }
            });

    Double[] ranges = WeaponRanges.getRanges(loadout);
    for (double range : ranges) {
        Set<Entry<Weapon, Double>> damageDistributio = maxSustainedDPS.getWeaponRatios(range).entrySet();
        for (Map.Entry<Weapon, Double> entry : damageDistributio) {
            final Weapon weapon = entry.getKey();
            final double ratio = entry.getValue();
            final double dps = weapon.getStat("d/s", modifiers);
            final double rangeEff = weapon.getRangeEffectivity(range, modifiers);

            if (!data.containsKey(weapon)) {
                data.put(weapon, new ArrayList<Pair<Double, Double>>());
            }
            data.get(weapon).add(new Pair<Double, Double>(range, dps * ratio * rangeEff));
        }
    }

    List<Weapon> orderedWeapons = new ArrayList<>();
    DefaultTableXYDataset dataset = new DefaultTableXYDataset();
    for (Map.Entry<Weapon, List<Pair<Double, Double>>> entry : data.entrySet()) {
        XYSeries series = new XYSeries(entry.getKey().getName(), true, false);
        for (Pair<Double, Double> pair : entry.getValue()) {
            series.add(pair.first, pair.second);
        }
        dataset.addSeries(series);
        orderedWeapons.add(entry.getKey());
    }
    Collections.reverse(orderedWeapons);
    colours.updateColoursToMatch(orderedWeapons);

    return dataset;
}

From source file:com.googlecode.fascinator.common.StorageDataUtil.java

/**
 * Getlist method to get the values of key from the sourceMap
 *
 * @param sourceMap Map container/*  www  . j a  va2 s  . c  o  m*/
 * @param baseKey   field to searchclass
 * @return list of value based on baseKey
 */
public Map<String, Object> getList(Map<String, Object> sourceMap, String baseKey) {
    SortedMap<String, Object> valueMap = new TreeMap<String, Object>();
    Map<String, Object> data;

    if (baseKey == null) {
        log.error("NULL baseKey provided!");
        return valueMap;
    }
    if (!baseKey.endsWith(".")) {
        baseKey = baseKey + ".";
    }
    if (sourceMap == null) {
        log.error("NULL sourceMap provided!");
        return valueMap;
    }

    for (String key : sourceMap.keySet()) {
        if (key.startsWith(baseKey)) {

            String value = sourceMap.get(key).toString();
            String field = baseKey;
            if (key.length() >= baseKey.length()) {
                field = key.substring(baseKey.length(), key.length());
            }

            String index = field;
            if (field.indexOf(".") > 0) {
                index = field.substring(0, field.indexOf("."));
            }

            if (valueMap.containsKey(index)) {
                data = (Map<String, Object>) valueMap.get(index);
            } else {
                data = new LinkedHashMap<String, Object>();
                valueMap.put(index, data);
            }

            if (value.length() == 1) {
                value = String.valueOf(value.charAt(0));
            }

            data.put(field.substring(field.indexOf(".") + 1, field.length()), value);

        }
    }

    return valueMap;
}