Example usage for com.google.common.collect ImmutableMap get

List of usage examples for com.google.common.collect ImmutableMap get

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableMap get.

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:edu.mit.streamjit.impl.compiler.Schedule.java

private static <T> Schedule<T> schedule(ImmutableSet<T> things,
        ImmutableSet<ExecutionConstraint<T>> executionConstraints,
        ImmutableSet<BufferingConstraint<T>> bufferingConstraints, int multiplier, int fireCost,
        int excessBufferCost) {
    ILPSolver solver = new ILPSolver();
    //There's one variable for each thing, which represents the number of
    //times it fires.  This uses the default bounds.  (TODO: perhaps a bound
    //at 1 if we're steady-state scheduling, maybe by marking things as
    //must-fire and marking the bottommost thing?)
    ImmutableMap.Builder<T, ILPSolver.Variable> variablesBuilder = ImmutableMap.builder();
    for (T thing : things)
        variablesBuilder.put(thing, solver.newVariable(thing.toString()));
    ImmutableMap<T, ILPSolver.Variable> variables = variablesBuilder.build();

    for (ExecutionConstraint<T> constraint : executionConstraints)
        solver.constrainAtLeast(variables.get(constraint.thing).asLinearExpr(1), constraint.minExecutions);

    HashMap<ILPSolver.Variable, Integer> sumOfConstraints = new HashMap<>();
    for (ILPSolver.Variable v : variables.values())
        sumOfConstraints.put(v, 0);//from   www .j a v  a  2s.  c  o m
    for (BufferingConstraint<T> constraint : bufferingConstraints) {
        ILPSolver.Variable upstreamVar = variables.get(constraint.upstream),
                downstreamVar = variables.get(constraint.downstream);
        ILPSolver.LinearExpr expr = upstreamVar.asLinearExpr(constraint.pushRate).minus(constraint.popRate,
                downstreamVar);
        switch (constraint.condition) {
        case LESS_THAN_EQUAL:
            solver.constrainAtMost(expr, constraint.bufferDelta);
            break;
        case EQUAL:
            solver.constrainEquals(expr, constraint.bufferDelta);
            break;
        case GREATER_THAN_EQUAL:
            solver.constrainAtLeast(expr, constraint.bufferDelta);
            break;
        default:
            throw new AssertionError(constraint.condition);
        }

        sumOfConstraints.put(upstreamVar, sumOfConstraints.get(upstreamVar) + constraint.pushRate);
        sumOfConstraints.put(downstreamVar, sumOfConstraints.get(downstreamVar) - constraint.popRate);
    }

    //Add a special constraint to ensure at least one filter fires.
    //TODO: in init schedules we might not always need this...
    Iterator<ILPSolver.Variable> variablesIter = variables.values().iterator();
    ILPSolver.LinearExpr totalFirings = variablesIter.next().asLinearExpr(1);
    while (variablesIter.hasNext())
        totalFirings = totalFirings.plus(1, variablesIter.next());
    solver.constrainAtLeast(totalFirings, 1);

    for (ILPSolver.Variable v : variables.values())
        sumOfConstraints.put(v, sumOfConstraints.get(v) * excessBufferCost + fireCost);
    ILPSolver.ObjectiveFunction objFn = solver.minimize(
            solver.newLinearExpr(Maps.filterValues(sumOfConstraints, Predicates.not(Predicates.equalTo(0)))));

    try {
        solver.solve();
    } catch (SolverException ex) {
        throw new ScheduleException(ex);
    }

    ImmutableMap.Builder<T, Integer> schedule = ImmutableMap.builder();
    for (Map.Entry<T, ILPSolver.Variable> e : variables.entrySet())
        schedule.put(e.getKey(), e.getValue().value() * multiplier);
    return new Schedule<>(things, bufferingConstraints, schedule.build());
}

From source file:google.registry.ui.server.SoyTemplateUtils.java

/** Returns a memoized supplier of the thing you pass to {@code setCssRenamingMap()}. */
public static Supplier<SoyCssRenamingMap> createCssRenamingMapSupplier(final URL cssMap,
        final URL cssMapDebug) {
    return memoize(new Supplier<SoyCssRenamingMap>() {
        @Override/*w  w w .  java 2 s  . c om*/
        public SoyCssRenamingMap get() {
            final ImmutableMap<String, String> renames = getCssRenames(cssMap, cssMapDebug);
            return new SoyCssRenamingMap() {
                @Override
                public String get(String cssClassName) {
                    List<String> result = new ArrayList<>();
                    for (String part : CSS_CLASS_SPLITTER.split(cssClassName)) {
                        result.add(firstNonNull(renames.get(part), part));
                    }
                    return CSS_CLASS_JOINER.join(result);
                }
            };
        }
    });
}

From source file:com.facebook.buck.support.cli.args.BuckArgsMethods.java

/** Extracts command line options from a file identified by {@code arg} with AT-file syntax. */
private static Iterable<String> expandFile(String arg, ImmutableMap<CellName, Path> cellMapping) {
    BuckCellArg argfile = BuckCellArg.of(arg);
    String[] parts = argfile.getArg().split("#", 2);
    String unresolvedArgsPath = parts[0];
    Path projectRoot = null;/*from  ww  w.j  ava  2s .c  om*/

    // Try to resolve the name to a path if present
    if (argfile.getCellName().isPresent()) {
        projectRoot = cellMapping.get(CellName.of(argfile.getCellName().get()));
        if (projectRoot == null) {
            String cellName = argfile.getCellName().get();
            throw new HumanReadableException(String.format("The cell '%s' was not found. Did you mean '%s/%s'?",
                    cellName, cellName, unresolvedArgsPath));
        }
    } else {
        projectRoot = cellMapping.get(CellName.ROOT_CELL_NAME);
    }
    Objects.requireNonNull(projectRoot, "Project root not resolved");
    Path argsPath = projectRoot.resolve(Paths.get(unresolvedArgsPath));

    if (!Files.exists(argsPath)) {
        throw new HumanReadableException("The file " + unresolvedArgsPath
                + " can't be found. Please make sure the path exists relative to the " + "project root.");
    }
    Optional<String> flavors = parts.length == 2 ? Optional.of(parts[1]) : Optional.empty();
    try {
        return getArgsFromPath(argsPath, flavors);
    } catch (IOException e) {
        throw new HumanReadableException(e, "Could not read options from " + arg);
    }
}

From source file:com.spectralogic.ds3contractcomparator.print.htmlprinter.generators.row.ModifiedHtmlRowGenerator.java

/**
 * Recursively traverses two objects using reflection and constructs the modified
 * rows that represent the changes and differences between the objects.
 *///ww  w .  j  a  va2 s  .  c o m
public static <T> ImmutableList<Row> createModifiedRows(final T oldObject, final T newObject,
        final int indent) {
    if (oldObject == null && newObject == null) {
        return ImmutableList.of();
    }
    final Field[] fields = getFields(oldObject, newObject);
    final ImmutableList.Builder<Row> builder = ImmutableList.builder();

    for (final Field field : fields) {
        final String property = field.getName();

        final Optional<String> oldValue = getPropertyValue(oldObject, property);
        final Optional<String> newValue = getPropertyValue(newObject, property);

        if (oldValue.isPresent() || newValue.isPresent()) {
            final int fieldIndent = toModifiedFieldIndent(indent, oldObject, newObject, field);
            if (field.getType() == ImmutableList.class) {
                //Field is a list, recursively print each element in the list
                builder.add(new NoChangeRow(fieldIndent, property, ""));

                final ImmutableList<Object> oldObjList = getListPropertyFromObject(field, oldObject);
                final ImmutableList<Object> newObjList = getListPropertyFromObject(field, newObject);

                if (hasContent(oldObjList) || hasContent(newObjList)) {
                    final String uniqueProperty = getPropertyNameFromList(oldObjList, newObjList);

                    final ImmutableSet<String> parameterUnion = toPropertyUnion(oldObjList, newObjList,
                            uniqueProperty);
                    final ImmutableMap<String, Object> oldMap = toPropertyMap(oldObjList, uniqueProperty);
                    final ImmutableMap<String, Object> newMap = toPropertyMap(newObjList, uniqueProperty);

                    parameterUnion.forEach(param -> builder
                            .addAll(createModifiedRows(oldMap.get(param), newMap.get(param), fieldIndent + 1)));
                }
            } else if (oldValue.isPresent() && newValue.isPresent() && oldValue.get().equals(newValue.get())) {
                //Element is the same in both contracts
                builder.add(new NoChangeRow(fieldIndent, property, oldValue.get()));
            } else {
                //Element is different between old and new contracts
                builder.add(new ModifiedRow(fieldIndent, property, oldValue.orElse(RowConstants.NA),
                        newValue.orElse(RowConstants.NA)));
            }
        }
    }
    return builder.build();
}

From source file:com.spectralogic.ds3client.helpers.JobState.java

private static AutoCloseableCache<String, WindowedChannelFactory> buildCache(
        final ObjectChannelBuilder channelBuilder,
        final ImmutableMap<String, ImmutableMultimap<BulkObject, Range>> objectRanges) {
    return new AutoCloseableCache<>(new ValueBuilder<String, WindowedChannelFactory>() {
        @Override// w  w  w .ja  va2  s . c o  m
        public WindowedChannelFactory get(final String key) {
            try {
                LOG.debug("Opening channel for: {}", key);
                return new WindowedChannelFactory(RangedSeekableByteChannel
                        .wrap(channelBuilder.buildChannel(key), objectRanges.get(key), key));
            } catch (final IOException e) {
                throw new RuntimeException(e);
            }
        }
    });
}

From source file:com.google.api.codegen.config.GapicInterfaceConfig.java

static <T> List<T> createMethodConfigs(ImmutableMap<String, T> methodConfigMap,
        InterfaceConfigProto interfaceConfigProto) {
    List<T> methodConfigs = new ArrayList<>();
    for (MethodConfigProto methodConfigProto : interfaceConfigProto.getMethodsList()) {
        methodConfigs.add(methodConfigMap.get(methodConfigProto.getName()));
    }/*from  w  w w .j a v  a  2 s . com*/
    return methodConfigs;
}

From source file:eu.trentorise.opendata.semtext.SemTexts.java

/**
 * Returns a copy of provided metadata with {@code newMetadata} set under
 * the given namespace./*w  w  w .  j a v a2 s. c  o m*/
 *
 * @param newMetadata Must be an immutable object.
 */
static ImmutableMap<String, ?> replaceMetadata(ImmutableMap<String, ?> metadata, String namespace,
        Object newMetadata) {
    ImmutableMap.Builder<String, Object> mapb = ImmutableMap.builder();
    for (String ns : metadata.keySet()) {
        if (!ns.equals(namespace)) {
            mapb.put(ns, metadata.get(ns));
        }
    }
    mapb.put(namespace, newMetadata);
    return mapb.build();
}

From source file:com.google.javascript.jscomp.AccessControlUtils.java

/**
 * Returns the effective visibility of the given name. This can differ
 * from the name's declared visibility if the file's {@code @fileoverview}
 * JsDoc specifies a default visibility.
 *
 * @param name The name node to compute effective visibility for.
 * @param var The name to compute effective visibility for.
 * @param fileVisibilityMap A map of {@code @fileoverview} visibility
 *     annotations, used to compute the name's default visibility.
 *///from w  w  w . j  a  v a2  s.co  m
static Visibility getEffectiveNameVisibility(Node name, Var var,
        ImmutableMap<StaticSourceFile, Visibility> fileVisibilityMap) {
    JSDocInfo jsDocInfo = var.getJSDocInfo();
    Visibility raw = (jsDocInfo == null || jsDocInfo.getVisibility() == null) ? Visibility.INHERITED
            : jsDocInfo.getVisibility();
    if (raw != Visibility.INHERITED) {
        return raw;
    }
    Visibility defaultVisibilityForFile = fileVisibilityMap.get(var.getSourceFile());
    JSType type = name.getJSType();
    boolean createdFromGoogProvide = (type instanceof PrototypeObjectType
            && ((PrototypeObjectType) type).isAnonymous());
    // Ignore @fileoverview visibility when computing the effective visibility
    // for names created by goog.provide.
    //
    // ProcessClosurePrimitives rewrites goog.provide()s as object literal
    // declarations, but the exact form depends on the ordering of the
    // input files. If goog.provide('a.b') occurs in the inputs before
    // goog.provide('a'), it is rewritten like
    //
    // var a={};a.b={};
    //
    // If the file containing goog.provide('a.b') also declares a @fileoverview
    // visibility, it must not apply to a, as this would make every a.* namespace
    // effectively package-private.
    return (createdFromGoogProvide || defaultVisibilityForFile == null) ? raw : defaultVisibilityForFile;
}

From source file:org.ambraproject.wombat.config.site.SiteRequestCondition.java

/**
 * Contains the patterns for all sites that define an appropriate handler.
 *///  ww  w.  j a v a  2s  .  c  o m
private static SiteRequestCondition forSiteMap(SiteResolver siteResolver,
        ImmutableMap<Site, PatternsRequestCondition> requestConditionMap) {
    Objects.requireNonNull(siteResolver);
    Objects.requireNonNull(requestConditionMap);
    return new SiteRequestCondition() {
        @Override
        protected PatternsRequestCondition resolve(HttpServletRequest request) {
            return requestConditionMap.get(siteResolver.resolveSite(request));
        }

        @Override
        protected SiteRequestCondition narrow(HttpServletRequest request) {
            Site site = siteResolver.resolveSite(request);
            PatternsRequestCondition condition = requestConditionMap.get(site);
            return forSingleSite(siteResolver, site, condition);
        }
    };
}

From source file:com.facebook.buck.android.ReplaceManifestPlaceholdersStep.java

@VisibleForTesting
static String replacePlaceholders(String content, ImmutableMap<String, String> placeholders) {
    Iterable<String> escaped = Iterables.transform(placeholders.keySet(), Pattern::quote);

    Joiner joiner = Joiner.on("|");
    String patternString = Pattern.quote("${") + "(" + joiner.join(escaped) + ")" + Pattern.quote("}");
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(content);

    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(sb, placeholders.get(matcher.group(1)));
    }/*from   w  w w . ja  v a2  s  .  c o m*/
    matcher.appendTail(sb);
    return sb.toString();
}