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:co.cask.tephra.snapshot.SnapshotCodecV4.java

@Override
protected NavigableMap<Long, TransactionManager.InProgressTx> decodeInProgress(BinaryDecoder decoder)
        throws IOException {

    int size = decoder.readInt();
    NavigableMap<Long, TransactionManager.InProgressTx> inProgress = Maps.newTreeMap();
    while (size != 0) { // zero denotes end of list as per AVRO spec
        for (int remaining = size; remaining > 0; --remaining) {
            long txId = decoder.readLong();
            long expiration = decoder.readLong();
            long visibilityUpperBound = decoder.readLong();
            int txTypeIdx = decoder.readInt();
            TransactionType txType;//www .j av  a  2s . c om
            try {
                txType = TransactionType.values()[txTypeIdx];
            } catch (ArrayIndexOutOfBoundsException e) {
                throw new IOException("Type enum ordinal value is out of range: " + txTypeIdx);
            }
            // read checkpoint tx IDs
            int checkpointPointerSize = decoder.readInt();
            LongArrayList checkpointPointers = new LongArrayList(checkpointPointerSize);
            while (checkpointPointerSize != 0) {
                for (int checkpointRemaining = checkpointPointerSize; checkpointRemaining > 0; --checkpointRemaining) {
                    checkpointPointers.add(decoder.readLong());
                }
                checkpointPointerSize = decoder.readInt();
            }
            inProgress.put(txId, new TransactionManager.InProgressTx(visibilityUpperBound, expiration, txType,
                    checkpointPointers));
        }
        size = decoder.readInt();
    }
    return inProgress;
}

From source file:com.google.caliper.model.Host.java

private Host() {
    this.properties = Maps.newTreeMap();
}

From source file:org.apache.isis.core.metamodel.specloader.validator.MetaModelValidatorToCheckModuleExtent.java

private void addValidatorToCheckModuleExtent() {

    final Map<String, List<String>> domainObjectClassNamesByPackage = Maps.newTreeMap();

    MetaModelValidatorVisiting.SummarizingVisitor visitor = new MetaModelValidatorVisiting.SummarizingVisitor() {

        @Override/*from  ww  w .  ja va 2  s . co m*/
        public boolean visit(ObjectSpecification objSpec, ValidationFailures validationFailures) {
            Class<?> correspondingClass = objSpec.getCorrespondingClass();
            if (correspondingClass == null) {
                return true;
            }
            Package aPackage = correspondingClass.getPackage();
            if (aPackage == null) {
                return true;
            }
            final String packageName = aPackage.getName();

            if (objSpec.isValue() || objSpec.isAbstract() || objSpec.isMixin()
                    || objSpec.isParentedOrFreeCollection() || objSpec.getFullIdentifier().startsWith("java")
                    || objSpec.getFullIdentifier().startsWith("org.joda")
                    || objSpec.getFullIdentifier().startsWith("org.apache.isis")) {
                // ignore
            } else {
                List<String> classNames = domainObjectClassNamesByPackage.get(packageName);
                if (classNames == null) {
                    classNames = Lists.newArrayList();
                    domainObjectClassNamesByPackage.put(packageName, classNames);
                }
                classNames.add(objSpec.getFullIdentifier());
            }
            return true;
        }

        @Override
        public void summarize(final ValidationFailures validationFailures) {

            AppManifest2 appManifest = specificationLoader.getServicesInjector()
                    .lookupService(MetaModelService.class).getAppManifest2();
            if (appManifest == null) {
                return;
            }
            Module topLevelModule = appManifest.getModule();
            if (topLevelModule == null) {
                // shouldn't happen
                return;
            }

            ImmutableList<String> modulePackageNames = modulePackageNamesFrom(appManifest);

            final Set<String> domainObjectPackageNames = domainObjectClassNamesByPackage.keySet();
            for (final String pkg : domainObjectPackageNames) {
                List<String> domainObjectClassNames = domainObjectClassNamesByPackage.get(pkg);
                boolean withinSomeModule = isWithinSomeModule(modulePackageNames, pkg);
                if (!withinSomeModule) {
                    String csv = Joiner.on(",").join(domainObjectClassNames);
                    validationFailures.add(
                            "Domain objects discovered in package '%s' are not in the set of modules obtained from "
                                    + "the AppManifest's top-level module '%s'.  Classes are: %s",
                            pkg, topLevelModule.getClass().getName(), csv);
                }
            }
        }

        private ImmutableList<String> modulePackageNamesFrom(final AppManifest appManifest) {
            List<Class<?>> modules = appManifest.getModules();
            return FluentIterable.from(modules).transform(new Function<Class<?>, String>() {
                @Override
                public String apply(final Class<?> aClass) {
                    return aClass.getPackage().getName();
                }
            }).toList();
        }

        private boolean isWithinSomeModule(final ImmutableList<String> modulePackageNames, final String pkg) {
            for (final String modulePackageName : modulePackageNames) {
                if (pkg.startsWith(modulePackageName)) {
                    return true;
                }
            }
            return false;
        }
    };

    add(new MetaModelValidatorVisiting(visitor));
}

From source file:org.elasticsearch.search.suggest.completion.old.context.ContextBuilder.java

public static SortedMap<String, ContextMapping> loadMappings(Object configuration, Version indexVersionCreated)
        throws ElasticsearchParseException {
    if (configuration instanceof Map) {
        Map<String, Object> configurations = (Map<String, Object>) configuration;
        SortedMap<String, ContextMapping> mappings = Maps.newTreeMap();
        for (Entry<String, Object> config : configurations.entrySet()) {
            String name = config.getKey();
            mappings.put(name, loadMapping(name, (Map<String, Object>) config.getValue(), indexVersionCreated));
        }/*from   ww  w  .j a v  a2 s  .co m*/
        return mappings;
    } else if (configuration == null) {
        return ContextMapping.EMPTY_MAPPING;
    } else {
        throw new ElasticsearchParseException("no valid context configuration");
    }
}

From source file:com.cloudera.oryx.serving.web.AbstractOryxServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);

    ServletContext context = config.getServletContext();

    Map<String, ServletStats> timings;
    synchronized (context) {
        @SuppressWarnings("unchecked")
        Map<String, ServletStats> temp = (Map<String, ServletStats>) context.getAttribute(TIMINGS_KEY);
        timings = temp;//from  ww w  .  ja v  a  2  s.c o m
        if (timings == null) {
            timings = Maps.newTreeMap();
            context.setAttribute(TIMINGS_KEY, timings);
        }
    }

    String key = getClass().getSimpleName();
    ServletStats theTiming = timings.get(key);
    if (theTiming == null) {
        theTiming = new ServletStats();
        timings.put(key, theTiming);
    }
    timing = theTiming;
}

From source file:org.sbs.goodcrawler.extractor.selector.IFConditions.java

/**
 * ???/*  w  w  w . j  a  va2 s . c o m*/
 * 
 * @param depend
 * @return
 */
public boolean test(Map<String, Object> selectContent) throws ExtractException {
    TreeMap<Integer, String> conIndex = Maps.newTreeMap();
    Queue<SimpleExpression> expressionQueue = Queues.newArrayDeque();
    Queue<String> logicQueue = Queues.newArrayDeque();
    // a=b and c=d or c=e or x=y
    int index = 0;
    for (String co : cond) {
        index = 0;
        while ((index = conditions.indexOf(co, index + 1)) > -1) {
            int i = index;
            conIndex.put(i, co);
        }
    }
    index = 0;
    for (Entry<Integer, String> entry : conIndex.entrySet()) {
        String subExp = conditions.substring(index, entry.getKey());
        for (String op : operations) {
            int i = subExp.indexOf(op);
            if (i > -1) {
                String[] ss = subExp.split(op);
                if (null == selectContent.get(ss[0].trim())) {
                    throw new ExtractException("?????["
                            + this.conditions + "] " + ss[0]);
                }
                expressionQueue
                        .add(new SimpleExpression(StringUtils.trim((String) selectContent.get(ss[0].trim())),
                                StringUtils.trim(ss[1]), op));
                logicQueue.add(StringUtils.trim(entry.getValue()));
            }
        }
        index = entry.getKey() + entry.getValue().length();
    }
    // ??
    String subExp = conditions.substring(index);
    for (String op : operations) {
        int i = subExp.indexOf(op);
        if (i > -1) {
            String[] ss = subExp.split(op);
            if (null == selectContent.get(ss[0].trim())) {
                throw new ExtractException("?????[" + this.conditions
                        + "] " + ss[0]);
            }
            expressionQueue.add(new SimpleExpression(StringUtils.trim((String) selectContent.get(ss[0].trim())),
                    StringUtils.trim(ss[1]), op));
        }
    }
    boolean b;
    try {
        b = expressionQueue.poll().test();
        while (!expressionQueue.isEmpty()) {
            b = cacl(b, logicQueue.poll(), expressionQueue.poll());
        }
        return b;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return false;
}

From source file:com.cloudera.gertrude.space.LayerBuilder.java

Layer build(Map<Integer, Segment> finalSegments) {
    ImmutableMap.Builder<Integer, NavigableMap<Integer, Set<Segment>>> b = ImmutableMap.builder();
    Set<Integer> allSegmentIds = Sets.newHashSet();
    for (Map.Entry<Integer, Map<Integer, Integer>> e : allocatedBucketsByDiversion.entrySet()) {
        int diversionId = e.getKey();
        NavigableMap<Integer, Set<Segment>> bucketToSegment = Maps.newTreeMap();
        for (Map.Entry<Integer, Integer> ee : e.getValue().entrySet()) {
            int bucketId = ee.getKey();
            int segmentId = ee.getValue();
            Segment segment = experiments.get(segmentId);
            if (segment == null) {
                segment = parent.getDomain(domains.get(segmentId), finalSegments);
            } else {
                allSegmentIds.add(segmentId);
            }//from  w w w .  java2s . c  o m
            Set<Segment> segments = bucketToSegment.get(bucketId);
            if (segments == null) {
                segments = Sets.newHashSet();
                bucketToSegment.put(bucketId, segments);
            }
            segments.add(segment);
            finalSegments.put(segmentId, segment);
        }
        b.put(diversionId, bucketToSegment);
    }
    // TODO: check the collision properties of faster impls (e.g., MurmurHash3)
    return new LayerImpl(info, Hashing.md5(), allSegmentIds, b.build(), parent.getRandom());
}

From source file:org.apache.giraph.utils.GiraphDepVersions.java

/** Log the dependency versions we're using */
public void logVersionsUsed() {
    Map<String, String> sortedVersions = Maps.newTreeMap();
    for (Map.Entry<Object, Object> entry : properties.entrySet()) {
        sortedVersions.put(entry.getKey().toString(), entry.getValue().toString());
    }//from  w w  w  . jav  a  2 s  .c  om
    StringBuilder sb = new StringBuilder(sortedVersions.size() * 20);
    for (Map.Entry<String, String> entry : sortedVersions.entrySet()) {
        sb.append("  ").append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
    }
    LOG.info("Versions of Giraph dependencies =>\n" + sb);
}

From source file:com.metamx.druid.query.metadata.SegmentMetadataQueryRunnerFactory.java

@Override
public QueryRunner<SegmentAnalysis> createRunner(final Segment segment) {
    return new QueryRunner<SegmentAnalysis>() {
        @Override/*w  w w. ja  v a 2s  .c o m*/
        public Sequence<SegmentAnalysis> run(Query<SegmentAnalysis> inQ) {
            SegmentMetadataQuery query = (SegmentMetadataQuery) inQ;

            final QueryableIndex index = segment.asQueryableIndex();
            if (index == null) {
                return Sequences.empty();
            }

            final Map<String, ColumnAnalysis> analyzedColumns = analyzer.analyze(index);

            // Initialize with the size of the whitespace, 1 byte per
            long totalSize = analyzedColumns.size() * index.getNumRows();

            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.isisaddons.wicket.wickedcharts.fixture.app.WickedChartsWicketToDoItemChartingService.java

@Action(semantics = SemanticsOf.SAFE)
public WickedChart pieChart() {

    Map<Category, AtomicInteger> byCategory = Maps.newTreeMap();
    List<WickedChartsWicketToDoItem> allToDos = toDoItems.allToDos();
    for (WickedChartsWicketToDoItem toDoItem : allToDos) {
        Category category = toDoItem.getCategory();
        AtomicInteger integer = byCategory.get(category);
        if (integer == null) {
            integer = new AtomicInteger();
            byCategory.put(category, integer);
        }//from w w  w  . ja v  a  2 s  . c  o  m
        integer.incrementAndGet();
    }

    return new WickedChart(new PieWithGradientOptions(byCategory));
}