Example usage for java.util TreeMap containsKey

List of usage examples for java.util TreeMap containsKey

Introduction

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

Prototype

public boolean containsKey(Object key) 

Source Link

Document

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

Usage

From source file:org.lockss.servlet.AddContentTab.java

public static TreeMap<String, List<TitleConfig>> orderTitleConfigByTitle(Collection<TitleConfig> allTitles) {
    TreeMap<String, List<TitleConfig>> titleMap = new TreeMap<String, List<TitleConfig>>();
    for (TitleConfig tc : allTitles) {
        String titleString = tc.getJournalTitle();
        List<TitleConfig> titleList;
        if (titleMap.containsKey(titleString)) {
            titleList = titleMap.get(titleString);
            titleList.add(tc);/*from  w ww  . ja  v  a  2 s.c  o  m*/
        } else {
            titleList = new ArrayList<TitleConfig>();
            titleList.add(tc);
        }
        titleMap.put(titleString, titleList);
    }
    return titleMap;
}

From source file:com.eucalyptus.objectstorage.pipeline.handlers.S3Authentication.java

/**
 * Query params are included in cases of Query-String/Presigned-url auth where they are considered just like headers
 * /*w w w .  j a  v  a2  s.com*/
 * @param httpRequest
 * @param includeQueryParams
 * @return
 */
private static String getCanonicalizedAmzHeaders(MappingHttpRequest httpRequest, boolean includeQueryParams) {
    String result = "";
    Set<String> headerNames = httpRequest.getHeaderNames();
    TreeMap<String, String> amzHeaders = new TreeMap<String, String>();
    for (String headerName : headerNames) {
        String headerNameString = headerName.toLowerCase().trim();
        if (headerNameString.startsWith("x-amz-")) {
            String value = httpRequest.getHeader(headerName).trim();
            String[] parts = value.split("\n");
            value = "";
            for (String part : parts) {
                part = part.trim();
                value += part + " ";
            }
            value = value.trim();
            if (amzHeaders.containsKey(headerNameString)) {
                String oldValue = (String) amzHeaders.remove(headerNameString);
                oldValue += "," + value;
                amzHeaders.put(headerNameString, oldValue);
            } else {
                amzHeaders.put(headerNameString, value);
            }
        }
    }

    if (includeQueryParams) {
        // For query-string auth, header values may include 'x-amz-*' that need to be signed
        for (String paramName : httpRequest.getParameters().keySet()) {
            processHeaderValue(paramName, httpRequest.getParameters().get(paramName), amzHeaders);
        }
    }

    // Build the canonical string
    Iterator<String> iterator = amzHeaders.keySet().iterator();
    while (iterator.hasNext()) {
        String key = iterator.next();
        String value = (String) amzHeaders.get(key);
        result += key + ":" + value + "\n";
    }
    return result;
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.clustering.ClusterCentroidsMain.java

public static TreeMap<Integer, Vector> computeClusterCentroids(String inputVectorsPath,
        String clusterOutputPath) throws IOException {
    TreeMap<Integer, Vector> result = new TreeMap<>();
    Map<Integer, Integer> counts = new TreeMap<>();

    // input for cluto
    File inputVectors = new File(inputVectorsPath);

    // resulting clusters
    File clutoClustersOutput = new File(clusterOutputPath);

    LineIterator clustersIterator = IOUtils.lineIterator(new FileInputStream(clutoClustersOutput), "utf-8");

    LineIterator vectorsIterator = IOUtils.lineIterator(new FileInputStream(inputVectors), "utf-8");

    // skip first line (number of clusters and vector size
    vectorsIterator.next();//from  w  w w. j a v a2 s.  c  o  m

    while (clustersIterator.hasNext()) {
        String clusterString = clustersIterator.next();
        String vectorString = vectorsIterator.next();

        int clusterNumber = Integer.valueOf(clusterString);

        // now parse the vector
        DenseVector vector = ClusteringUtils.parseVector(vectorString);

        // if there is no resulting vector for the particular cluster, add this one
        if (!result.containsKey(clusterNumber)) {
            result.put(clusterNumber, vector);
        } else {
            // otherwise add this one to the previous one
            result.put(clusterNumber, result.get(clusterNumber).add(vector));
        }

        // and update counts
        if (!counts.containsKey(clusterNumber)) {
            counts.put(clusterNumber, 0);
        }

        counts.put(clusterNumber, counts.get(clusterNumber) + 1);
    }

    // now compute average for each vector
    for (Map.Entry<Integer, Vector> entry : result.entrySet()) {
        // cluster number
        int clusterNumber = entry.getKey();
        // get counts
        int count = counts.get(clusterNumber);

        // divide by count of vectors for each cluster (averaging)
        for (VectorEntry vectorEntry : entry.getValue()) {
            vectorEntry.set(vectorEntry.get() / (double) count);
        }
    }

    return result;
}

From source file:org.apache.tajo.storage.thirdparty.orc.ByteBufferAllocatorPool.java

public void putBuffer(ByteBuffer buffer) {
    TreeMap<Key, ByteBuffer> tree = getBufferTree(buffer.isDirect());
    while (true) {
        Key key = new Key(buffer.capacity(), currentGeneration++);
        if (!tree.containsKey(key)) {
            tree.put(key, buffer);/*  w  w w.  j av  a2  s  . c  o m*/
            return;
        }
        // Buffers are indexed by (capacity, generation).
        // If our key is not unique on the first try, we try again
    }
}

From source file:org.apache.hadoop.io.ElasticByteBufferPool.java

@Override
public synchronized void putBuffer(ByteBuffer buffer) {
    TreeMap<Key, ByteBuffer> tree = getBufferTree(buffer.isDirect());
    while (true) {
        Key key = new Key(buffer.capacity(), System.nanoTime());
        if (!tree.containsKey(key)) {
            tree.put(key, buffer);/*from ww  w  .  j  a  va  2s .co  m*/
            return;
        }
        // Buffers are indexed by (capacity, time).
        // If our key is not unique on the first try, we try again, since the
        // time will be different.  Since we use nanoseconds, it's pretty
        // unlikely that we'll loop even once, unless the system clock has a
        // poor granularity.
    }
}

From source file:ark.util.CounterTable.java

public TreeMap<Integer, List<T>> getSortedCounts() {
    TreeMap<Integer, List<T>> sortedCounts = new TreeMap<Integer, List<T>>();

    for (Entry<T, Integer> entry : this.counts.entrySet()) {
        if (!sortedCounts.containsKey(entry.getValue()))
            sortedCounts.put(entry.getValue(), new ArrayList<T>());

        sortedCounts.get(entry.getValue()).add(entry.getKey());
    }/*w w  w.ja  v a  2s.com*/

    return sortedCounts;
}

From source file:gda.jython.commands.ScannableCommands.java

/**
 * The pos command. Reports the current position of a scannable or moves one or more scannables concurrently.
 * /*  w w  w. j av a  2s .c om*/
 * @param args
 * @return String reporting final positions
 * @throws Exception
 *             - any exception within this method
 */
public static String pos(Object... args) throws Exception {
    if (args.length == 1) {
        if (args[0] == null) {// example: pos None, Jython command: pos([None])
            throw new Exception(
                    "Usage: pos [ScannableName] - returns the position of all Scannables [or the given scannable]");
        } else if (args[0] instanceof IScannableGroup) {
            return ScannableUtils.prettyPrintScannableGroup((IScannableGroup) args[0]);
        } else if (args[0] instanceof ScannableBase) {// example: pos pseudoDeviceName, Jython command:
            // pos([pseudoDeviceName])
            return ((ScannableBase) args[0]).__str__().toString();
        }
        return args[0].toString();
    } else if (args.length >= 2) {// example pos pseudoDeviceName newPosition, Jython command:
        // pos([pseudoDeviceName, newPosition]
        // identify scannables and the positions to move them to
        Scannable[] scannableList = new Scannable[args.length / 2];
        HashMap<Scannable, Object> positionMap = new HashMap<Scannable, Object>();
        int j = 0;
        for (int i = 0; i < args.length; i += 2) {
            if (args[i] instanceof Scannable) {
                scannableList[j] = (Scannable) args[i];
                positionMap.put((Scannable) args[i], args[i + 1]);
                j++;
            }
        }

        // Check positions valid
        for (Scannable scannable : scannableList) {
            Object target = positionMap.get(scannable);
            if (!(scannable instanceof Detector)) {
                raiseDeviceExceptionIfPositionNotValid(scannable, target);
            }
        }

        try {
            // Group by level
            TreeMap<Integer, List<Scannable>> scannablesByLevel = new TreeMap<Integer, List<Scannable>>();
            for (Scannable scn : scannableList) {
                Integer level = scn.getLevel();
                if (!scannablesByLevel.containsKey(level)) {
                    scannablesByLevel.put(level, new ArrayList<Scannable>());
                }
                scannablesByLevel.get(level).add(scn);
            }

            // Move scannables of the same level concurrently
            String output = "Move completed: "; // KLUDGE

            for (Entry<Integer, List<Scannable>> currentLevelScannables : scannablesByLevel.entrySet()) {
                for (Scannable scn1 : currentLevelScannables.getValue()) {
                    scn1.atLevelStart();
                }
                for (Scannable scn1 : currentLevelScannables.getValue()) {
                    scn1.atLevelMoveStart();
                }
                // asynchronousMoveTo()
                for (Scannable scn1 : currentLevelScannables.getValue()) {
                    if (scn1 instanceof DetectorSnapper) {
                        Double collectionTime = PositionConvertorFunctions.toDouble(positionMap.get(scn1));
                        ((DetectorSnapper) scn1).prepareForAcquisition(collectionTime);
                        ((DetectorSnapper) scn1).acquire();
                    } else if (scn1 instanceof Detector) {
                        Double collectionTime = PositionConvertorFunctions.toDouble(positionMap.get(scn1));
                        ((Detector) scn1).setCollectionTime(collectionTime);
                        ((Detector) scn1).prepareForCollection();
                        ((Detector) scn1).collectData();
                    } else {
                        scn1.asynchronousMoveTo(positionMap.get(scn1));
                    }
                }
                // **isBusy()**
                // Wait for all moves to complete. If there is a problem with one, then stop the Scannables
                // which may still be moving (those that have not yet been waited for), and _then_ throw the
                // exception.
                Exception exceptionCaughtWhileWaitingOnIsBusy = null;
                for (Scannable scn1 : currentLevelScannables.getValue()) {
                    if (exceptionCaughtWhileWaitingOnIsBusy == null) {
                        // normal behaviour
                        try {
                            scn1.waitWhileBusy();
                        } catch (Exception e) {
                            logger.error("Exception occured while waiting for " + scn1.getName()
                                    + " to complete move: ", e.getMessage());
                            // cause future passes through the loop to stop Scannables
                            exceptionCaughtWhileWaitingOnIsBusy = e;
                        }
                    } else {
                        // stop any motors that may be still moving
                        try {
                            logger.info("Stopping " + scn1.getName()
                                    + " due to problem moving previous scannable.");
                            scn1.stop();
                        } catch (DeviceException e) {
                            logger.error("Caught exception while stopping " + scn1.getName() + ": "
                                    + e.getMessage());
                        }
                    }
                }
                if (exceptionCaughtWhileWaitingOnIsBusy != null) {
                    throw exceptionCaughtWhileWaitingOnIsBusy;
                }
                for (Scannable scn1 : currentLevelScannables.getValue()) {
                    scn1.atLevelEnd();
                }
            }

            if (scannableList.length > 1) {
                output += "\n";
            }

            // return position
            for (Scannable scn3 : scannableList) {
                output += ScannableUtils.getFormattedCurrentPosition(scn3) + "\n";
            }
            return output.trim();
        } catch (Exception e) {
            // Call the atCommandFailure() hooks
            for (Scannable scn : scannableList) {
                scn.atCommandFailure();
            }
            throw e;
        }
    }
    return "";
}

From source file:com.opengamma.analytics.financial.interestrate.CashFlowEquivalentCalculator.java

/**
 * Add a cash flow amount at a given time in the flow map. If the time is present, the amount is added; if the time is not present a new entry is created.
 * @param flow The map describing the cash flows.
 * @param time The time of the flow to add.
 * @param amount The amount of the flow to add.
 *//*from  www  .ja  v a 2s. co m*/
private void addcf(TreeMap<Double, Double> flow, double time, double amount) {
    if (flow.containsKey(time)) {
        flow.put(time, flow.get(time) + amount);
    } else {
        flow.put(time, amount);
    }
}

From source file:updater.Controller.java

public TreeMap<String, String> deleteDuplicate(List<Episode> episodeList) {
    TreeMap<String, String> map = new TreeMap<>();
    String mapKey;//from   ww  w . ja  v  a  2s  .com
    for (Episode ep : episodeList) {
        mapKey = ep.getLanguage() + "." + ep.getTitle() + "." + ep.getEpisodeNumber();

        if (!map.containsKey(mapKey)) {
            map.put(mapKey, ep.getEpisodeName());
        } else {
            if (map.get(mapKey).equals(" ")) {
                map.put(mapKey, ep.getEpisodeName());
            }
        }
    }
    return map;
}

From source file:captureplugin.drivers.defaultdriver.configpanels.ChannelTableModel.java

/**
 * Updates the List of Channels/*ww w  .  j  av  a 2  s.c o  m*/
 */
private void updateChannels() {
    PluginManager pl = Plugin.getPluginManager();
    if (pl == null) {
        return;
    }
    TreeMap<Channel, String> channels = mData.getChannels();

    final Channel[] channelArray = pl.getSubscribedChannels();
    for (Channel channel : channelArray) {
        if (!channels.containsKey(channel)) {
            channels.put(channel, "");
        }
    }
    mData.setChannels(channels);
    mChannelRows = new ArrayList<Channel>(mData.getChannels().keySet());

    Collections.sort(mChannelRows, new Comparator<Channel>() {
        public int compare(Channel a, Channel b) {
            return ArrayUtils.indexOf(channelArray, a) - ArrayUtils.indexOf(channelArray, b);
        }
    });
}