Example usage for com.google.common.collect Maps newTreeMap

List of usage examples for com.google.common.collect Maps newTreeMap

Introduction

In this page you can find the example usage for com.google.common.collect Maps newTreeMap.

Prototype

public static <K extends Comparable, V> TreeMap<K, V> newTreeMap() 

Source Link

Document

Creates a mutable, empty TreeMap instance using the natural ordering of its elements.

Usage

From source file:org.jclouds.trmk.vcloud_0_8.binders.BindInstantiateVAppTemplateParamsToXmlPayload.java

@Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {
    checkArgument(checkNotNull(request, "request") instanceof GeneratedHttpRequest,
            "this binder is only valid for GeneratedHttpRequests!");
    GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request;
    String name = checkNotNull(postParams.remove("name"), "name").toString();
    String template = checkNotNull(postParams.remove("template"), "template").toString();

    SortedMap<ResourceType, String> virtualHardwareQuantity = Maps.newTreeMap();

    InstantiateVAppTemplateOptions options = findOptionsInArgsOrNull(gRequest);
    String network = (defaultNetwork != null) ? defaultNetwork.get().getHref().toASCIIString() : null;
    String fenceMode = defaultFenceMode;
    String networkName = name;/*from   ww w  . java2s. c  om*/
    if (options != null) {
        if (options.getNetworkConfig().size() > 0) {
            NetworkConfig config = Iterables.get(options.getNetworkConfig(), 0);
            network = ifNullDefaultTo(config.getParentNetwork(), network);
            fenceMode = ifNullDefaultTo(config.getFenceMode(), defaultFenceMode);
            networkName = ifNullDefaultTo(config.getNetworkName(), networkName);
        }
        addQuantity(options, virtualHardwareQuantity);
    }
    try {
        return stringBinder.bindToRequest(request, generateXml(name, template, virtualHardwareQuantity,
                networkName, fenceMode, URI.create(network)));
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    } catch (FactoryConfigurationError e) {
        throw new RuntimeException(e);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }

}

From source file:org.jclouds.vcloud.binders.BindInstantiateVCloudExpressVAppTemplateParamsToXmlPayload.java

@Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, String> postParams) {
    checkArgument(checkNotNull(request, "request") instanceof GeneratedHttpRequest<?>,
            "this binder is only valid for GeneratedHttpRequests!");
    GeneratedHttpRequest<?> gRequest = (GeneratedHttpRequest<?>) request;
    checkState(gRequest.getArgs() != null, "args should be initialized at this point");
    String name = checkNotNull(postParams.remove("name"), "name");
    String template = checkNotNull(postParams.remove("template"), "template");

    SortedMap<ResourceType, String> virtualHardwareQuantity = Maps.newTreeMap();

    InstantiateVAppTemplateOptions options = findOptionsInArgsOrNull(gRequest);
    String network = (defaultNetwork != null) ? defaultNetwork.toASCIIString() : null;
    String fenceMode = defaultFenceMode;
    String networkName = name;/*www  . ja  v  a 2  s .com*/
    if (options != null) {
        if (options.getNetworkConfig().size() > 0) {
            NetworkConfig config = Iterables.get(options.getNetworkConfig(), 0);
            network = ifNullDefaultTo(config.getParentNetwork(), network);
            fenceMode = ifNullDefaultTo(config.getFenceMode(), defaultFenceMode);
            if (apiVersion.indexOf("0.8") != -1 && fenceMode.equals("bridged"))
                fenceMode = "allowInOut";
            networkName = ifNullDefaultTo(config.getNetworkName(), networkName);
        }
        addQuantity(options, virtualHardwareQuantity);
    }
    try {
        return stringBinder.bindToRequest(request, generateXml(name, template, virtualHardwareQuantity,
                networkName, fenceMode, URI.create(network)));
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    } catch (FactoryConfigurationError e) {
        throw new RuntimeException(e);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }

}

From source file:io.druid.query.metadata.SegmentMetadataQueryRunnerFactory.java

@Override
public QueryRunner<SegmentAnalysis> createRunner(final Segment segment) {
    return new QueryRunner<SegmentAnalysis>() {
        @Override/*from  w w w. j  a v  a2  s .co m*/
        public Sequence<SegmentAnalysis> run(Query<SegmentAnalysis> inQ, Map<String, Object> responseContext) {
            SegmentMetadataQuery query = (SegmentMetadataQuery) inQ;

            final QueryableIndex index = segment.asQueryableIndex();

            final Map<String, ColumnAnalysis> analyzedColumns;
            final int numRows;
            long totalSize = 0;
            if (index == null) {
                // IncrementalIndexSegments (used by in-memory hydrants in the realtime service) do not have a QueryableIndex
                StorageAdapter segmentAdapter = segment.asStorageAdapter();
                analyzedColumns = analyzer.analyze(segmentAdapter, query.getAnalysisTypes());
                numRows = segmentAdapter.getNumRows();
            } else {
                analyzedColumns = analyzer.analyze(index, query.getAnalysisTypes());
                numRows = index.getNumRows();
            }

            if (query.hasSize()) {
                // Initialize with the size of the whitespace, 1 byte per
                totalSize = analyzedColumns.size() * numRows;
            }

            Map<String, ColumnAnalysis> columns = Maps.newTreeMap();
            ColumnIncluderator includerator = query.getToInclude();
            for (Map.Entry<String, ColumnAnalysis> entry : analyzedColumns.entrySet()) {
                final String columnName = entry.getKey();
                final ColumnAnalysis column = entry.getValue();

                if (!column.isError()) {
                    totalSize += column.getSize();
                }
                if (includerator.include(columnName)) {
                    columns.put(columnName, column);
                }
            }

            return Sequences.simple(Arrays.asList(new SegmentAnalysis(segment.getIdentifier(),
                    Arrays.asList(segment.getDataInterval()), columns, totalSize)));
        }
    };
}

From source file:org.sonar.test.i18n.BundleSynchronizedMatcher.java

@VisibleForTesting
protected static SortedMap<String, String> retrieveMissingTranslations(InputStream bundle,
        InputStream referenceBundle) throws IOException {
    SortedMap<String, String> missingKeys = Maps.newTreeMap();

    Properties bundleProps = loadProperties(bundle);
    Properties referenceProperties = loadProperties(referenceBundle);

    for (Map.Entry<Object, Object> entry : referenceProperties.entrySet()) {
        String key = (String) entry.getKey();
        if (!bundleProps.containsKey(key)) {
            missingKeys.put(key, (String) entry.getValue());
        }//w ww.j a va 2s.  c om
    }

    return missingKeys;
}

From source file:com.zimbra.doc.soap.changelog.SoapApiChangeLog.java

public void makeChangeLogDataModel()
        throws JsonParseException, JsonMappingException, IOException, TemplateException {
    Map<String, SoapApiCommand> baselineCmds = Maps.newTreeMap();
    Map<String, SoapApiCommand> currentCmds = Maps.newTreeMap();
    for (SoapApiCommand cmd : currentDesc.getCommands()) {
        currentCmds.put(cmd.getId(), cmd);
    }//w w  w  . j a  v a 2s  .c  o  m
    for (SoapApiCommand cmd : baselineDesc.getCommands()) {
        baselineCmds.put(cmd.getId(), cmd);
    }
    for (Entry<String, SoapApiCommand> entry : currentCmds.entrySet()) {
        SoapApiCommand baselineCmd = baselineCmds.get(entry.getKey());
        if (baselineCmd != null) {
            CommandChanges cmd = new CommandChanges(baselineCmd, entry.getValue(), baselineDesc.getTypes(),
                    currentDesc.getTypes());
            if (cmd.hasChanges()) {
                modifiedCommands.add(cmd);
            }
        } else {
            newCommands.add(entry.getValue());
        }
    }
    for (Entry<String, SoapApiCommand> entry : baselineCmds.entrySet()) {
        if (!currentCmds.containsKey(entry.getKey())) {
            deletedCommands.add(entry.getValue());
        }
    }
    changelogDataModel = createChangeLogDataModel();
}

From source file:com.github.strawberry.util.Types.java

public static Map<?, ?> mapImplementationOf(Class<?> clazz) {
    Map map = null;//from   w  w w  . j  a  v a 2s.c  om
    // If it is a map, use linked hash-map as the implementation.
    if (clazz.equals(Map.class)) {
        map = Maps.newLinkedHashMap();
    }
    // If it is a sorted map, fall back to using a tree-map as the implementation.
    else if (clazz.equals(SortedMap.class)) {
        map = Maps.newTreeMap();
    }
    // Else, create implementation by calling constructor via reflection.
    else {
        map = (Map) implementationOf(clazz);
    }
    return map;
}

From source file:com.google.devtools.build.lib.buildtool.SymlinkForest.java

void plantSymlinkForest() throws IOException {
    deleteTreesBelowNotPrefixed(workspace, prefixes);

    // Create a sorted map of all dirs (packages and their ancestors) to sets of their roots.
    // Packages come from exactly one root, but their shared ancestors may come from more.
    // The map is maintained sorted lexicographically, so parents are before their children.
    Map<PackageIdentifier, Set<Path>> dirRootsMap = Maps.newTreeMap();
    for (Map.Entry<PackageIdentifier, Path> entry : packageRoots.entrySet()) {
        PackageIdentifier pkgId = entry.getKey();
        Path pkgRoot = entry.getValue();
        for (int i = 1; i <= pkgId.getPackageFragment().segmentCount(); i++) {
            if (pkgId.equals(Label.EXTERNAL_PACKAGE_IDENTIFIER)) {
                // This isn't a "real" package, don't add it to the symlink tree.
                continue;
            }//from   w  w  w  . j  a  va 2 s.  c om
            PackageIdentifier dir = createInRepo(pkgId, pkgId.getPackageFragment().subFragment(0, i));
            Set<Path> roots = dirRootsMap.get(dir);
            if (roots == null) {
                roots = Sets.newHashSet();
                dirRootsMap.put(dir, roots);
            }
            roots.add(pkgRoot);
        }
    }
    // Now add in roots for all non-pkg dirs that are in between two packages, and missed above.
    for (Map.Entry<PackageIdentifier, Set<Path>> entry : dirRootsMap.entrySet()) {
        PackageIdentifier dir = entry.getKey();
        if (!packageRoots.containsKey(dir)) {
            PackageIdentifier pkgId = longestPathPrefix(dir, packageRoots.keySet());
            if (pkgId != null) {
                entry.getValue().add(packageRoots.get(pkgId));
            }
        }
    }
    // Create output dirs for all dirs that have more than one root and need to be split.
    for (Map.Entry<PackageIdentifier, Set<Path>> entry : dirRootsMap.entrySet()) {
        PackageIdentifier dir = entry.getKey();
        if (!dir.getRepository().isMain()) {
            FileSystemUtils.createDirectoryAndParents(
                    workspace.getRelative(dir.getRepository().getPathUnderExecRoot()));
        }
        if (entry.getValue().size() > 1) {
            if (LOG_FINER) {
                LOG.finer("mkdir " + workspace.getRelative(dir.getPathUnderExecRoot()));
            }
            FileSystemUtils.createDirectoryAndParents(workspace.getRelative(dir.getPathUnderExecRoot()));
        }
    }

    // Make dir links for single rooted dirs.
    for (Map.Entry<PackageIdentifier, Set<Path>> entry : dirRootsMap.entrySet()) {
        PackageIdentifier dir = entry.getKey();
        Set<Path> roots = entry.getValue();
        // Simple case of one root for this dir.
        if (roots.size() == 1) {
            if (dir.getPackageFragment().segmentCount() > 1 && dirRootsMap.get(getParent(dir)).size() == 1) {
                continue; // skip--an ancestor will link this one in from above
            }
            // This is the top-most dir that can be linked to a single root. Make it so.
            Path root = roots.iterator().next(); // lone root in set
            if (LOG_FINER) {
                LOG.finer("ln -s " + root.getRelative(dir.getSourceRoot()) + " "
                        + workspace.getRelative(dir.getPathUnderExecRoot()));
            }
            workspace.getRelative(dir.getPathUnderExecRoot())
                    .createSymbolicLink(root.getRelative(dir.getSourceRoot()));
        }
    }
    // Make links for dirs within packages, skip parent-only dirs.
    for (Map.Entry<PackageIdentifier, Set<Path>> entry : dirRootsMap.entrySet()) {
        PackageIdentifier dir = entry.getKey();
        if (entry.getValue().size() > 1) {
            // If this dir is at or below a package dir, link in its contents.
            PackageIdentifier pkgId = longestPathPrefix(dir, packageRoots.keySet());
            if (pkgId != null) {
                Path root = packageRoots.get(pkgId);
                try {
                    Path absdir = root.getRelative(dir.getSourceRoot());
                    if (absdir.isDirectory()) {
                        if (LOG_FINER) {
                            LOG.finer("ln -s " + absdir + "/* " + workspace.getRelative(dir.getSourceRoot())
                                    + "/");
                        }
                        for (Path target : absdir.getDirectoryEntries()) {
                            PathFragment p = target.relativeTo(root);
                            if (!dirRootsMap.containsKey(createInRepo(pkgId, p))) {
                                //LOG.finest("ln -s " + target + " " + linkRoot.getRelative(p));
                                workspace.getRelative(p).createSymbolicLink(target);
                            }
                        }
                    } else {
                        LOG.fine("Symlink planting skipping dir '" + absdir + "'");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // Otherwise its just an otherwise empty common parent dir.
            }
        }
    }

    for (Map.Entry<PackageIdentifier, Path> entry : packageRoots.entrySet()) {
        PackageIdentifier pkgId = entry.getKey();
        if (!pkgId.getPackageFragment().equals(PathFragment.EMPTY_FRAGMENT)) {
            continue;
        }
        Path execrootDirectory = workspace.getRelative(pkgId.getPathUnderExecRoot());
        // If there were no subpackages, this directory might not exist yet.
        if (!execrootDirectory.exists()) {
            FileSystemUtils.createDirectoryAndParents(execrootDirectory);
        }
        // For the top-level directory, generate symlinks to everything in the directory instead of
        // the directory itself.
        Path sourceDirectory = entry.getValue().getRelative(pkgId.getSourceRoot());
        for (Path target : sourceDirectory.getDirectoryEntries()) {
            String baseName = target.getBaseName();
            Path execPath = execrootDirectory.getRelative(baseName);
            // Create any links that don't exist yet and don't start with bazel-.
            if (!baseName.startsWith(productName + "-") && !execPath.exists()) {
                execPath.createSymbolicLink(target);
            }
        }
    }

    symlinkCorrectWorkspaceName();
}

From source file:org.eclipse.wb.internal.core.model.generic.ContainerObjectValidators.java

public static ContainerObjectValidator forReferenceExpression(final String expression) {
    return new ContainerObjectValidator() {
        public boolean validate(Object container, Object reference) {
            ILayoutRequestValidatorHelper validatorHelper = GlobalState.getValidatorHelper();
            if (validatorHelper.isComponent(container) && validatorHelper.isComponent(reference)) {
                Map<String, Object> variables = Maps.newTreeMap();
                variables.put("container", container);
                variables.put("reference", reference);
                return evaluate(expression, variables);
            }//w ww  . j  a  v  a  2  s  .  c  o m
            return false;
        }

        @Override
        public String toString() {
            return expression;
        }
    };
}

From source file:org.wikidata.wdtk.examples.TypeHistogram.java

@Override
public void processItemDocument(ItemDocument itemDocument) {

    // Print status once in a while
    if (this.nprocessed % 100000 == 0) {
        printStatus();//from   w  ww . j  av a2  s .c o  m
    }
    this.nprocessed++;

    Map<String, String> attributes = Maps.newTreeMap();

    for (StatementGroup sg : itemDocument.getStatementGroups()) {
        EntityIdValue subject = sg.getSubject();
        switch (sg.getProperty().getId()) {
        case "P31": // P31 is "instance of"
        {
            // Iterate over all statements
            for (Statement s : sg.getStatements()) {
                // Find the main claim and check if it has a value
                if (s.getClaim().getMainSnak() instanceof ValueSnak) {
                    Value v = ((ValueSnak) s.getClaim().getMainSnak()).getValue();
                    if (v instanceof ItemIdValue) {
                        EntityIdValue ev = (ItemIdValue) v;
                        String type = ev.getId();
                        //String title = ev.getTitle();
                        Integer count = histogram.get(type);
                        if (count == null) {
                            histogram.put(type, 1);
                        } else {
                            histogram.put(type, count + 1);
                        }
                    }
                }
            }
            break;
        }
        }
    }
}

From source file:org.apache.druid.query.metadata.SegmentAnalyzer.java

public Map<String, ColumnAnalysis> analyze(Segment segment) {
    Preconditions.checkNotNull(segment, "segment");

    // index is null for incremental-index-based segments, but storageAdapter is always available
    final QueryableIndex index = segment.asQueryableIndex();
    final StorageAdapter storageAdapter = segment.asStorageAdapter();

    // get length and column names from storageAdapter
    final int length = storageAdapter.getNumRows();
    final Set<String> columnNames = Sets.newHashSet();
    Iterables.addAll(columnNames, storageAdapter.getAvailableDimensions());
    Iterables.addAll(columnNames, storageAdapter.getAvailableMetrics());

    Map<String, ColumnAnalysis> columns = Maps.newTreeMap();

    for (String columnName : columnNames) {
        final ColumnHolder columnHolder = index == null ? null : index.getColumnHolder(columnName);
        final ColumnCapabilities capabilities = columnHolder != null ? columnHolder.getCapabilities()
                : storageAdapter.getColumnCapabilities(columnName);

        final ColumnAnalysis analysis;
        final ValueType type = capabilities.getType();
        switch (type) {
        case LONG:
            analysis = analyzeNumericColumn(capabilities, length, Long.BYTES);
            break;
        case FLOAT:
            analysis = analyzeNumericColumn(capabilities, length, NUM_BYTES_IN_TEXT_FLOAT);
            break;
        case DOUBLE:
            analysis = analyzeNumericColumn(capabilities, length, Double.BYTES);
            break;
        case STRING:
            if (index != null) {
                analysis = analyzeStringColumn(capabilities, columnHolder);
            } else {
                analysis = analyzeStringColumn(capabilities, storageAdapter, columnName);
            }//from   w w w . j  a  v  a  2s  .c  om
            break;
        case COMPLEX:
            analysis = analyzeComplexColumn(capabilities, columnHolder,
                    storageAdapter.getColumnTypeName(columnName));
            break;
        default:
            log.warn("Unknown column type[%s].", type);
            analysis = ColumnAnalysis.error(StringUtils.format("unknown_type_%s", type));
        }

        columns.put(columnName, analysis);
    }

    // Add time column too
    ColumnCapabilities timeCapabilities = storageAdapter.getColumnCapabilities(ColumnHolder.TIME_COLUMN_NAME);
    if (timeCapabilities == null) {
        timeCapabilities = new ColumnCapabilitiesImpl().setType(ValueType.LONG).setHasMultipleValues(false);
    }
    columns.put(ColumnHolder.TIME_COLUMN_NAME,
            analyzeNumericColumn(timeCapabilities, length, NUM_BYTES_IN_TIMESTAMP));

    return columns;
}