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:uk.gov.gchq.gaffer.function.MultiFilterFunction.java

@Override
public Class<?>[] getInputClasses() {
    final TreeMap<Integer, Class<?>> inputClassMap = new TreeMap<>();
    for (final ConsumerFunctionContext<Integer, FilterFunction> context : getFunctions()) {
        final Class<?>[] inputClasses = context.getFunction().getInputClasses();
        for (int i = 0; i < inputClasses.length; i++) {
            final Integer index = context.getSelection().get(i);
            if (inputClassMap.containsKey(index)) {
                final Class<?> otherClazz = inputClassMap.get(index);
                if (otherClazz.isAssignableFrom(inputClasses[i])) {
                    inputClassMap.put(index, inputClasses[i]);
                } else if (!inputClasses[i].isAssignableFrom(otherClazz)) {
                    throw new InputMismatchException(
                            "Input types for function " + getClass().getSimpleName() + " are not compatible");
                }//from www. j  av a2  s  .com
            } else {
                inputClassMap.put(index, inputClasses[i]);
            }
        }
    }

    return inputClassMap.values().toArray(new Class<?>[inputClassMap.size()]);
}

From source file:org.cloudata.core.client.TabletLocationCache.java

private void removeFromCache(TreeMap<Row.Key, TabletInfo> cache, Row.Key cacheRowKey, TabletInfo removeTablet) {
    if (cache.containsKey(cacheRowKey)) {
        cache.remove(cacheRowKey);// w  w w .j  av  a2s  .  c om
    }

    SortedMap<Row.Key, TabletInfo> tailMap = cache.tailMap(cacheRowKey);
    if (tailMap.isEmpty()) {
        return;
    }
    Row.Key tailFirst = tailMap.firstKey();

    TabletInfo tabletInfo = tailMap.get(tailFirst);

    if (tabletInfo.equals(removeTablet)) {
        cache.remove(tailFirst);
    }
}

From source file:gsn.wrappers.general.CSVHandler.java

public ArrayList<TreeMap<String, Serializable>> parseValues(Reader datainput, long previousCheckPoint)
        throws IOException {
    ArrayList<TreeMap<String, Serializable>> toReturn = new ArrayList<TreeMap<String, Serializable>>();
    CSVReader reader = new CSVReader(datainput, getSeparator(), getStringSeparator(), getSkipFirstXLines());
    String[] values = null;//from   w  w w  . j av a 2s  .com
    long currentLine = 0;
    while ((values = reader.readNext()) != null) {
        TreeMap<String, Serializable> se = convertTo(formats, fields, getNulls(), values, getSeparator());
        if (isEmpty(se))
            continue;
        if (se.containsKey(TIMESTAMP)) {
            //System.out.println("times "+se.get(TIMESTAMP)+"--"+previousCheckPoint);
            if (((Long) se.get(TIMESTAMP)) <= previousCheckPoint)
                continue;
        } else {// assuming useCounterForCheckPoint = true

            if (logger.isDebugEnabled()) {
                String symbol = (currentLine < previousCheckPoint) ? " < " : " >= ";
                logger.debug("currentLine=" + currentLine + symbol + "checkpoint=" + previousCheckPoint);
            }

            if (currentLine < previousCheckPoint) {// skipping already read lines, based on line count
                logger.debug("skipping");
                currentLine++;
                continue;
            }

        }
        toReturn.add(se);
        currentLine++;
        loggedNoChange = false;
        if (toReturn.size() > 250)
            break; // Move outside the loop as in each call we only read 250 values;
    }
    if (logger.isDebugEnabled() && toReturn.size() == 0 && loggedNoChange == false) {
        logger.debug("There is no new item after most recent checkpoint(previousCheckPoint:"
                + new DateTime(previousCheckPoint) + ").");
        loggedNoChange = true;
    }

    reader.close();
    return toReturn;
}

From source file:net.triptech.buildulator.DataParser.java

/**
 * Parses the text data./* www  .j  av  a 2 s  .c o m*/
 *
 * @param text the text
 *
 * @return the tree map< integer, tree map< integer, string>>
 */
public static String[][] parseTextData(final String text) {

    TreeMap<Integer, TreeMap<Integer, String>> rowData = new TreeMap<Integer, TreeMap<Integer, String>>();

    // This counter holds the maximum number of columns provided
    int maxNumberOfTokens = 0;

    if (text != null) {
        BufferedReader in = new BufferedReader(new StringReader(text));

        String line;
        int lineCounter = 0;

        try {
            while ((line = in.readLine()) != null) {
                TreeMap<Integer, String> parsedLine = new TreeMap<Integer, String>();

                SmartTokenizer tabTokenizer = new SmartTokenizer(line, "\t");
                if (tabTokenizer.countTokens() > 1) {
                    parsedLine = tokenizerToMap(tabTokenizer);
                } else {
                    SmartTokenizer commaTokenizer = new SmartTokenizer(line, ",");
                    parsedLine = tokenizerToMap(commaTokenizer);
                }
                if (parsedLine.size() > maxNumberOfTokens) {
                    maxNumberOfTokens = parsedLine.size();
                }

                rowData.put(lineCounter, parsedLine);
                lineCounter++;
            }
        } catch (IOException ioe) {
            // Error reading string
        }
    }

    String[][] parsedData = new String[rowData.size()][];

    // Now cycle through all the parsed data
    // Ensure that each row has the same (max) number of tokens
    for (int rowIndex : rowData.keySet()) {
        TreeMap<Integer, String> parsedLine = rowData.get(rowIndex);

        // This map holds the final values
        TreeMap<Integer, String> columnTokens = new TreeMap<Integer, String>();

        for (int i = 0; i < maxNumberOfTokens; i++) {
            String value = "";
            if (parsedLine.containsKey(i)) {
                value = parsedLine.get(i);
            }
            columnTokens.put(i, value);
        }

        parsedData[rowIndex] = new String[columnTokens.size()];

        for (int columnIndex : columnTokens.keySet()) {
            String value = columnTokens.get(columnIndex);
            parsedData[rowIndex][columnIndex] = value;
        }
    }
    return parsedData;
}

From source file:org.pentaho.di.baserver.utils.inspector.Inspector.java

protected boolean inspectEndpoints(final String moduleName) {
    URI uri = null;//from   w  ww  .j  ava 2s.c o m
    try {
        uri = new URI(getApplicationWadlEndpoint(moduleName));
    } catch (URISyntaxException e) {
        // do nothing
    }

    if (uri != null) {
        Response response = callHttp(uri.toASCIIString());

        if (response != null && response.getStatusCode() == HttpStatus.SC_OK) {
            Document doc = getDocument(response.getResult());

            if (doc != null) {
                TreeMap<String, LinkedList<Endpoint>> endpointMap = new TreeMap<String, LinkedList<Endpoint>>();

                for (Endpoint endpoint : getParser().getEndpoints(doc)) {
                    final String path = endpoint.getPath();
                    if (!endpointMap.containsKey(path)) {
                        endpointMap.put(path, new LinkedList<Endpoint>());
                    }
                    endpointMap.get(path).add(endpoint);
                }

                getEndpointsTree().put(moduleName, endpointMap);

                return true;
            }
        }
    }

    return false;
}

From source file:karma.oss.zookeeper.queue.ZkMessageQueue.java

/**
 * Get first available (that is un-claimed) element from the ordered child list. Then get the child's data from
 * zookeeper//from  w w  w .j  av  a 2 s.  c om
 * @param orderedChildren
 *         List of ordered children from zookeeper
 * @param markClaimed
 *         Whether to claim this child. If true, the child will not be available in the next read until
*         put back by calling putbackElement()
 * @return
 *         Bytes of available element, Optional.absent() otherwise
 * @throws KeeperException
 * @throws InterruptedException
 */
private Optional<Element<byte[]>> getFirstAvailableElement(NavigableMap<Long, String> orderedChildren,
        boolean markClaimed) throws KeeperException, InterruptedException {

    boolean hasUnClaimedElements = false;
    TreeMap<Long, String> claimedChildren = orderedClaimedChildren(null);

    for (Entry<Long, String> entry : orderedChildren.entrySet()) {
        // skip children already claimed
        if (claimedChildren.containsKey(entry.getKey())) {
            LOG.debug("Element already claimed: " + entry.getValue(), "; skipping");
            continue;
        }

        hasUnClaimedElements = true;
        final String elementId = entry.getValue();
        try {
            final String claimPath = claimDir + "/" + elementId;
            while (markClaimed) {
                try {
                    final byte[] hostNameBytes = StringUtils.getBytesUtf8(getLocalHostName());
                    zookeeperRef.get().create(claimPath, hostNameBytes, acl, CreateMode.EPHEMERAL);
                    LOG.info("Element claimed: " + entry.getValue());
                    break;
                } catch (KeeperException.NodeExistsException e) {
                    LOG.info("Node at path: " + claimPath + " already exists. Trying different node.");
                    throw e; // will be caught by the outer loop.
                } catch (KeeperException.NoNodeException e) {
                    createDir();
                }
            }

            final String path = dir + "/" + elementId;
            byte[] data = zookeeperRef.get().getData(path, false, null);
            return Optional.of(Element.create(elementId, data));
        } catch (KeeperException.NodeExistsException e) {
            // Another client claimed the node first.
            // Refresh claimed children
            claimedChildren = orderedClaimedChildren(null);
        }
    }

    if (!hasUnClaimedElements) {
        throw new NoSuchElementException("No unclaimed element found");
    }

    return Optional.absent();
}

From source file:net.anthonypoon.ngram.rollingregression.RollingRegressionReducer.java

@Override
protected void reduce(Text key, Iterable<Text> values, Context context)
        throws IOException, InterruptedException {
    TreeMap<String, Double> currElement = new TreeMap();
    boolean pastThreshold = false;
    for (Text val : values) {
        String[] strArray = val.toString().split("\t");
        if (Double.valueOf(strArray[1]) > threshold) {
            pastThreshold = true;//from w ww . jav  a  2s  . com
        }
        currElement.put(strArray[0], Math.log(Double.valueOf(strArray[1])));
    }
    if (pastThreshold) {
        for (Integer i = 0; i <= upbound - lowbound; i++) {
            if (!currElement.containsKey(String.valueOf(lowbound + i))) {
                if (i != 0) {
                    currElement.put(String.valueOf(lowbound + i),
                            currElement.get(String.valueOf(lowbound + i - 1)));
                } else {
                    currElement.put(String.valueOf(lowbound + i), 0.0);
                }
            }

        }
        TreeMap<String, Double> result = new TreeMap();
        for (Integer i = 0 + range; i <= upbound - lowbound - range; i++) {
            SimpleRegression regression = new SimpleRegression();
            for (Integer l = -range; l <= range; l++) {
                regression.addData(l.doubleValue(), currElement.get(String.valueOf(i + lowbound + l)));
            }
            if (!Double.isNaN(regression.getSlope())) {
                if (!positiveOnly || regression.getSlope() > 0) {
                    result.put(String.valueOf(lowbound + i), regression.getSlope());
                }
            }
        }
        for (Map.Entry<String, Double> pair : result.entrySet()) {
            context.write(key, new Text(pair.getKey() + "\t" + String.format("%.5f", pair.getValue())));
        }
    }
}

From source file:ubic.gemma.model.association.coexpression.GeneCoexpressionNodeDegreeValueObject.java

private int[] asIntArray(TreeMap<Integer, Integer> nodedeg) {
    IntArrayList list = new IntArrayList();
    if (nodedeg.isEmpty())
        return this.toPrimitive(list);
    Integer maxSupport = nodedeg.lastKey();
    list.setSize(maxSupport + 1);/* w  w  w.  jav  a2  s. c  o m*/
    for (Integer s = 0; s <= maxSupport; s++) {
        if (nodedeg.containsKey(s)) {
            list.set(s, nodedeg.get(s));
        } else {
            list.set(s, 0);
        }
    }
    return this.toPrimitive(list);
}

From source file:org.cloudata.core.client.TabletLocationCache.java

protected TabletInfo findFromCache(String tableName, TreeMap<Row.Key, TabletInfo> cache, Row.Key cacheRowKey,
        Row.Key dataRowKey) {/*  w ww .  j  a va  2  s.  c  o m*/
    cacheLock.obtainReadLock();
    try {
        if (cache.containsKey(cacheRowKey)) {
            TabletInfo tabletInfo = cache.get(cacheRowKey);
            if (tabletInfo.belongRowRange(cacheRowKey)) {
                return tabletInfo;
            } else {
                return null;
            }
        }

        SortedMap<Row.Key, TabletInfo> tailMap = cache.tailMap(cacheRowKey);
        if (tailMap.isEmpty()) {
            return null;
        }
        Row.Key tailFirst = tailMap.firstKey();

        TabletInfo tabletInfo = tailMap.get(tailFirst);
        if (tableName.equals(tabletInfo.getTableName()) && tabletInfo.belongRowRange(dataRowKey)) {
            return tabletInfo;
        } else {
            return null;
        }
    } finally {
        cacheLock.releaseReadLock();
    }
}

From source file:org.kalypso.gml.ui.internal.coverage.CoverageColormapHandler.java

/**
 * update the colorMap of the {@link RasterSymbolizer}
 *///from   www  .j a  v  a 2  s  . c  o m
public void updateRasterSymbolizer(final Shell shell, final ColorMapEntry[] entries) {
    final TreeMap<Double, ColorMapEntry> newRasterColorMap = new TreeMap<>();

    // FIXME: move this code to the place, where the entries are created
    for (final ColorMapEntry colorMapEntry : entries) {
        // WHY? why do we not just ignore duplicate entries
        if (!newRasterColorMap.containsKey(new Double(colorMapEntry.getQuantity())))
            newRasterColorMap.put(new Double(colorMapEntry.getQuantity()), colorMapEntry.clone());
    }

    final List<PolygonColorMapEntry> newPolygonColorMap = translateColormap(newRasterColorMap);

    /* Update the symbolizers */
    for (final Symbolizer symbolizer : m_symbolizers) {
        if (symbolizer instanceof RasterSymbolizer)
            ((RasterSymbolizer) symbolizer).setColorMap(newRasterColorMap);
        else if (symbolizer instanceof SurfacePolygonSymbolizer) {
            final PolygonColorMap colorMap = ((SurfacePolygonSymbolizer) symbolizer).getColorMap();
            colorMap.replaceColorMap(newPolygonColorMap);
        }
    }

    saveStyle(shell);
}