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:blusunrize.immersiveengineering.client.models.multilayer.MultiLayerModel.java

@Nonnull
@Override/* ww  w. j  av  a2  s  . c om*/
public IModel process(ImmutableMap<String, String> customData) {
    Map<BlockRenderLayer, List<ModelData>> newSubs = new HashMap<>();
    JsonParser parser = new JsonParser();
    Map<String, String> unused = new HashMap<>();
    for (String layerStr : customData.keySet())
        if (LAYERS_BY_NAME.containsKey(layerStr)) {

            BlockRenderLayer layer = LAYERS_BY_NAME.get(layerStr);
            JsonElement ele = parser.parse(customData.get(layerStr));
            if (ele.isJsonObject()) {
                ModelData data = ModelData.fromJson(ele.getAsJsonObject(), ImmutableList.of(),
                        ImmutableMap.of());
                newSubs.put(layer, ImmutableList.of(data));
            } else if (ele.isJsonArray()) {
                JsonArray array = ele.getAsJsonArray();
                List<ModelData> models = new ArrayList<>();
                for (JsonElement subEle : array)
                    if (subEle.isJsonObject())
                        models.add(ModelData.fromJson(ele.getAsJsonObject(), ImmutableList.of(),
                                ImmutableMap.of()));
                newSubs.put(layer, models);
            }
        } else
            unused.put(layerStr, customData.get(layerStr));
    JsonObject unusedJson = ModelData.asJsonObject(unused);
    for (Entry<BlockRenderLayer, List<ModelData>> entry : newSubs.entrySet())
        for (ModelData d : entry.getValue())
            for (Entry<String, JsonElement> entryJ : unusedJson.entrySet())
                if (!d.data.has(entryJ.getKey()))
                    d.data.add(entryJ.getKey(), entryJ.getValue());
    if (!newSubs.equals(subModels))
        return new MultiLayerModel(newSubs);
    return this;
}

From source file:com.facebook.buck.cli.Config.java

/**
 * @return the value at sectionName, propertyName, without any decoding,
 *   or absent() if the key is not present.
 *//*from   w w  w.  j  a v a  2  s  .c o m*/
private Optional<String> getRawValue(String sectionName, String propertyName) {
    ImmutableMap<String, String> properties = get(sectionName);
    return Optional.fromNullable(properties.get(propertyName));
}

From source file:com.opengamma.strata.collect.io.XmlFile.java

/**
 * Parses the tree from the StAX stream reader, capturing references.
 * <p>/*from w w w.  java 2  s  .  c o  m*/
 * The reader should be created using the factory returned from {@link #xmlInputFactory()}.
 * <p>
 * This method supports capturing attribute references, such as an id/href pair.
 * Wherever the parser finds an attribute with the specified name, the element is added
 * to the specified map. Note that the map is mutated.
 * 
 * @param reader  the StAX stream reader, positioned at or before the element to be parsed
 * @param refAttr  the attribute name that should be parsed as a reference, null if not applicable
 * @param refs  the mutable map of references to update, null if not applicable
 * @return the parsed element
 * @throws IllegalArgumentException if the input cannot be parsed
 */
private static XmlElement parse(XMLStreamReader reader, String refAttr, Map<String, XmlElement> refs) {
    try {
        // parse start element
        String elementName = parseElementName(reader);
        ImmutableMap<String, String> attrs = parseAttributes(reader);

        // parse children or content
        ImmutableList.Builder<XmlElement> childBuilder = ImmutableList.builder();
        String content = "";
        int event = reader.next();
        while (event != XMLStreamConstants.END_ELEMENT) {
            switch (event) {
            // parse child when start element found
            case XMLStreamConstants.START_ELEMENT:
                childBuilder.add(parse(reader, refAttr, refs));
                break;
            // append content when characters found
            // since XMLStreamReader has IS_COALESCING=true means there should only be one content call
            case XMLStreamConstants.CHARACTERS:
            case XMLStreamConstants.CDATA:
                content += reader.getText();
                break;
            default:
                break;
            }
            event = reader.next();
        }
        ImmutableList<XmlElement> children = childBuilder.build();
        XmlElement parsed = children.isEmpty() ? XmlElement.ofContent(elementName, attrs, content)
                : XmlElement.ofChildren(elementName, attrs, children);
        String ref = attrs.get(refAttr);
        if (ref != null) {
            refs.put(ref, parsed);
        }
        return parsed;

    } catch (XMLStreamException ex) {
        throw new IllegalArgumentException(ex);
    }
}

From source file:org.eclipse.xtext.tasks.DefaultTaskParser.java

@Override
public List<Task> parseTasks(final String source, final TaskTags taskTags) {
    ArrayList<Task> _xblockexpression = null;
    {//from w w w.  j  ava2s .  co  m
        boolean _isEmpty = IterableExtensions.isEmpty(taskTags);
        if (_isEmpty) {
            return Collections.<Task>unmodifiableList(CollectionLiterals.<Task>newArrayList());
        }
        final Function<TaskTag, String> _function = (TaskTag it) -> {
            return it.getName().toLowerCase();
        };
        final ImmutableMap<String, TaskTag> taskTagsByName = Maps.<String, TaskTag>uniqueIndex(taskTags,
                _function);
        final Matcher matcher = this.toPattern(taskTags).matcher(source);
        final ArrayList<Task> tasks = CollectionLiterals.<Task>newArrayList();
        int prevLine = 1;
        int prevOffset = 0;
        while (matcher.find()) {
            {
                final Task task = new Task();
                task.setTag(taskTagsByName.get(matcher.group(2).toLowerCase()));
                task.setDescription(matcher.group(3));
                task.setOffset(matcher.start(2));
                int _countLineBreaks = Strings.countLineBreaks(source, prevOffset, task.getOffset());
                int _plus = (_countLineBreaks + prevLine);
                task.setLineNumber(_plus);
                prevLine = task.getLineNumber();
                prevOffset = task.getOffset();
                tasks.add(task);
            }
        }
        _xblockexpression = tasks;
    }
    return _xblockexpression;
}

From source file:com.google.devtools.build.lib.skyframe.GraphBackedRecursivePackageProvider.java

private void collectPackagesUnder(final RepositoryName repository, Set<TraversalInfo> traversals,
        ImmutableList.Builder<PathFragment> builder) throws InterruptedException {
    Map<TraversalInfo, SkyKey> traversalToKeyMap = Maps.asMap(traversals,
            new Function<TraversalInfo, SkyKey>() {
                @Override//from w w w .  j  a  va 2  s  .  c o m
                public SkyKey apply(TraversalInfo traversalInfo) {
                    return CollectPackagesUnderDirectoryValue.key(repository, traversalInfo.rootedDir,
                            traversalInfo.excludedSubdirectories);
                }
            });
    Map<SkyKey, SkyValue> values = graph.getSuccessfulValues(traversalToKeyMap.values());

    ImmutableSet.Builder<TraversalInfo> subdirTraversalBuilder = ImmutableSet.builder();
    for (Map.Entry<TraversalInfo, SkyKey> entry : traversalToKeyMap.entrySet()) {
        TraversalInfo info = entry.getKey();
        SkyKey key = entry.getValue();
        SkyValue val = values.get(key);
        CollectPackagesUnderDirectoryValue collectPackagesValue = (CollectPackagesUnderDirectoryValue) val;
        if (collectPackagesValue != null) {
            if (collectPackagesValue.isDirectoryPackage()) {
                builder.add(info.rootedDir.getRelativePath());
            }

            ImmutableMap<RootedPath, Boolean> subdirectoryTransitivelyContainsPackages = collectPackagesValue
                    .getSubdirectoryTransitivelyContainsPackages();
            for (RootedPath subdirectory : subdirectoryTransitivelyContainsPackages.keySet()) {
                if (subdirectoryTransitivelyContainsPackages.get(subdirectory)) {
                    PathFragment subdirectoryRelativePath = subdirectory.getRelativePath();
                    ImmutableSet<PathFragment> excludedSubdirectoriesBeneathThisSubdirectory = PathFragment
                            .filterPathsStartingWith(info.excludedSubdirectories, subdirectoryRelativePath);
                    subdirTraversalBuilder.add(
                            new TraversalInfo(subdirectory, excludedSubdirectoriesBeneathThisSubdirectory));
                }
            }
        }
    }

    ImmutableSet<TraversalInfo> subdirTraversals = subdirTraversalBuilder.build();
    if (!subdirTraversals.isEmpty()) {
        collectPackagesUnder(repository, subdirTraversals, builder);
    }
}

From source file:com.facebook.buck.util.versioncontrol.VersionControlStatsGenerator.java

private void generateStats() throws InterruptedException, VersionControlCommandFailedException {
    LOG.info("Starting generation of version control stats.");

    VersionControlCmdLineInterface vcCmdLineInterface = versionControlCmdLineInterfaceFactory
            .createCmdLineInterface();//w  ww  . j av  a 2  s .co  m

    if (!vcCmdLineInterface.isSupportedVersionControlSystem()) {
        LOG.warn("Skipping generation of version control stats as unsupported repository type.");
        return;
    }

    VersionControlStats.Builder versionControlStats = VersionControlStats.builder();
    try (SimplePerfEvent.Scope ignored = SimplePerfEvent.scope(buckEventBus, "gen_source_control_info")) {
        try {
            // Get a list of the revision ids of all the tracked bookmarks.
            ImmutableMap<String, String> bookmarksRevisionIds = vcCmdLineInterface
                    .bookmarksRevisionsId(TRACKED_BOOKMARKS);
            // Get the current revision id.
            String currentRevisionId = vcCmdLineInterface.currentRevisionId();
            // Get the common ancestor of master and current revision
            String branchedFromMasterRevisionId = vcCmdLineInterface.commonAncestor(currentRevisionId,
                    bookmarksRevisionIds.get("remote/master"));
            // Get the list of tracked changes files.
            ImmutableSet<String> changedFiles = vcCmdLineInterface.changedFiles(".");

            ImmutableSet.Builder<String> baseBookmarks = ImmutableSet.builder();
            for (Map.Entry<String, String> bookmark : bookmarksRevisionIds.entrySet()) {
                if (bookmark.getValue().startsWith(currentRevisionId)) {
                    baseBookmarks.add(bookmark.getKey());
                }
            }

            versionControlStats.setPathsChangedInWorkingDirectory(changedFiles)
                    .setCurrentRevisionId(currentRevisionId)
                    .setBranchedFromMasterRevisionId(branchedFromMasterRevisionId)
                    .setBaseBookmarks(baseBookmarks.build()).build();
        } catch (VersionControlCommandFailedException e) {
            LOG.warn("Failed to gather source control stats.");
        }
    }

    LOG.info("Stats generated successfully. \n%s", versionControlStats);
    buckEventBus.post(new VersionControlStatsEvent(versionControlStats.build()));
}

From source file:com.facebook.buck.ide.intellij.BaseIjModuleRule.java

private Set<Path> findConfiguredGeneratedSourcePathsUsingDeps(TargetNode<T, ?> targetNode) {
    ImmutableMap<String, String> depToGeneratedSourcesMap = projectConfig.getDepToGeneratedSourcesMap();
    BuildTarget buildTarget = targetNode.getBuildTarget();

    Set<Path> generatedSourcePaths = new HashSet<>();

    for (BuildTarget dependencyTarget : targetNode.getBuildDeps()) {
        String buildTargetName = dependencyTarget.toString();
        String generatedSourceWithPattern = depToGeneratedSourcesMap.get(buildTargetName);
        if (generatedSourceWithPattern != null) {
            String generatedSource = generatedSourceWithPattern.replaceAll("%name%",
                    buildTarget.getShortNameAndFlavorPostfix());
            Path generatedSourcePath = BuildTargets.getGenPath(projectFilesystem, buildTarget, generatedSource);

            generatedSourcePaths.add(generatedSourcePath);
        }/*w ww. jav  a  2s  .  co m*/
    }

    return generatedSourcePaths;
}

From source file:org.elasticsearch.action.admin.cluster.snapshots.status.TransportSnapshotsStatusAction.java

private SnapshotsStatusResponse buildResponse(SnapshotsStatusRequest request,
        ImmutableList<SnapshotMetaData.Entry> currentSnapshots,
        TransportNodesSnapshotsStatus.NodesSnapshotStatus nodeSnapshotStatuses) {
    // First process snapshot that are currently processed
    ImmutableList.Builder<SnapshotStatus> builder = ImmutableList.builder();
    Set<SnapshotId> currentSnapshotIds = newHashSet();
    if (!currentSnapshots.isEmpty()) {
        Map<String, TransportNodesSnapshotsStatus.NodeSnapshotStatus> nodeSnapshotStatusMap;
        if (nodeSnapshotStatuses != null) {
            nodeSnapshotStatusMap = nodeSnapshotStatuses.getNodesMap();
        } else {//from   w  ww  .j a  v a 2 s. c o  m
            nodeSnapshotStatusMap = newHashMap();
        }

        for (SnapshotMetaData.Entry entry : currentSnapshots) {
            currentSnapshotIds.add(entry.snapshotId());
            ImmutableList.Builder<SnapshotIndexShardStatus> shardStatusBuilder = ImmutableList.builder();
            for (ImmutableMap.Entry<ShardId, SnapshotMetaData.ShardSnapshotStatus> shardEntry : entry.shards()
                    .entrySet()) {
                SnapshotMetaData.ShardSnapshotStatus status = shardEntry.getValue();
                if (status.nodeId() != null) {
                    // We should have information about this shard from the shard:
                    TransportNodesSnapshotsStatus.NodeSnapshotStatus nodeStatus = nodeSnapshotStatusMap
                            .get(status.nodeId());
                    if (nodeStatus != null) {
                        ImmutableMap<ShardId, SnapshotIndexShardStatus> shardStatues = nodeStatus.status()
                                .get(entry.snapshotId());
                        if (shardStatues != null) {
                            SnapshotIndexShardStatus shardStatus = shardStatues.get(shardEntry.getKey());
                            if (shardStatus != null) {
                                // We have full information about this shard
                                shardStatusBuilder.add(shardStatus);
                                continue;
                            }
                        }
                    }
                }
                final SnapshotIndexShardStage stage;
                switch (shardEntry.getValue().state()) {
                case FAILED:
                case ABORTED:
                case MISSING:
                    stage = SnapshotIndexShardStage.FAILURE;
                    break;
                case INIT:
                case WAITING:
                case STARTED:
                    stage = SnapshotIndexShardStage.STARTED;
                    break;
                case SUCCESS:
                    stage = SnapshotIndexShardStage.DONE;
                    break;
                default:
                    throw new ElasticsearchIllegalArgumentException(
                            "Unknown snapshot state " + shardEntry.getValue().state());
                }
                SnapshotIndexShardStatus shardStatus = new SnapshotIndexShardStatus(
                        shardEntry.getKey().getIndex(), shardEntry.getKey().getId(), stage);
                shardStatusBuilder.add(shardStatus);
            }
            builder.add(new SnapshotStatus(entry.snapshotId(), entry.state(), shardStatusBuilder.build()));
        }
    }
    // Now add snapshots on disk that are not currently running
    if (Strings.hasText(request.repository())) {
        if (request.snapshots() != null && request.snapshots().length > 0) {
            for (String snapshotName : request.snapshots()) {
                SnapshotId snapshotId = new SnapshotId(request.repository(), snapshotName);
                if (currentSnapshotIds.contains(snapshotId)) {
                    // This is a snapshot the is currently running - skipping
                    continue;
                }
                Snapshot snapshot = snapshotsService.snapshot(snapshotId);
                ImmutableList.Builder<SnapshotIndexShardStatus> shardStatusBuilder = ImmutableList.builder();
                if (snapshot.state().completed()) {
                    ImmutableMap<ShardId, IndexShardSnapshotStatus> shardStatues = snapshotsService
                            .snapshotShards(snapshotId);
                    for (ImmutableMap.Entry<ShardId, IndexShardSnapshotStatus> shardStatus : shardStatues
                            .entrySet()) {
                        shardStatusBuilder.add(
                                new SnapshotIndexShardStatus(shardStatus.getKey(), shardStatus.getValue()));
                    }
                    final SnapshotMetaData.State state;
                    switch (snapshot.state()) {
                    case FAILED:
                        state = SnapshotMetaData.State.FAILED;
                        break;
                    case SUCCESS:
                    case PARTIAL:
                        // Translating both PARTIAL and SUCCESS to SUCCESS for now
                        // TODO: add the differentiation on the metadata level in the next major release
                        state = SnapshotMetaData.State.SUCCESS;
                        break;
                    default:
                        throw new ElasticsearchIllegalArgumentException(
                                "Unknown snapshot state " + snapshot.state());
                    }
                    builder.add(new SnapshotStatus(snapshotId, state, shardStatusBuilder.build()));
                }
            }
        }
    }

    return new SnapshotsStatusResponse(builder.build());
}

From source file:com.facebook.buck.rules.coercer.DefaultConstructorArgMarshaller.java

@CheckReturnValue
@Override//from   ww  w.  j  a  va 2s.  co m
public <T> T populate(CellPathResolver cellRoots, ProjectFilesystem filesystem, BuildTarget buildTarget,
        Class<T> dtoClass, ImmutableSet.Builder<BuildTarget> declaredDeps, Map<String, ?> instance)
        throws ParamInfoException {
    Pair<Object, Function<Object, T>> dtoAndBuild = CoercedTypeCache.instantiateSkeleton(dtoClass, buildTarget);
    ImmutableMap<String, ParamInfo> allParamInfo = CoercedTypeCache.INSTANCE.getAllParamInfo(typeCoercerFactory,
            dtoClass);
    for (ParamInfo info : allParamInfo.values()) {
        info.setFromParams(cellRoots, filesystem, buildTarget, buildTarget.getTargetConfiguration(),
                dtoAndBuild.getFirst(), instance);
    }
    T dto = dtoAndBuild.getSecond().apply(dtoAndBuild.getFirst());
    collectDeclaredDeps(cellRoots, allParamInfo.get("deps"), declaredDeps, dto);
    return dto;
}

From source file:org.apache.cloudstack.outofbandmanagement.driver.nestedcloudstack.NestedCloudStackOutOfBandManagementDriver.java

private OutOfBandManagementDriverResponse execute(final OutOfBandManagementDriverPowerCommand cmd) {
    if (cmd == null || cmd.getPowerOperation() == null) {
        throw new CloudRuntimeException(
                "Invalid out-of-band management power command provided to the nested-cloudstack driver");
    }/*from w w  w  .jav  a 2s  . c o m*/

    final ImmutableMap<OutOfBandManagement.Option, String> options = cmd.getOptions();
    ensureOptionExists(options, OutOfBandManagement.Option.ADDRESS);
    ensureOptionExists(options, OutOfBandManagement.Option.PORT);
    ensureOptionExists(options, OutOfBandManagement.Option.USERNAME);
    ensureOptionExists(options, OutOfBandManagement.Option.PASSWORD);

    final String url = options.get(OutOfBandManagement.Option.ADDRESS);
    final String vmUuid = options.get(OutOfBandManagement.Option.PORT);
    final String apiKey = options.get(OutOfBandManagement.Option.USERNAME);
    final String secretKey = options.get(OutOfBandManagement.Option.PASSWORD);

    final ApacheCloudStackUser apacheCloudStackUser = new ApacheCloudStackUser(secretKey, apiKey);
    final ApacheCloudStackClient client = new ApacheCloudStackClient(url, apacheCloudStackUser);
    client.setValidateServerHttpsCertificate(false);
    client.setShouldRequestsExpire(false);
    client.setConnectionTimeout((int) cmd.getTimeout().getStandardSeconds());

    String apiName = "listVirtualMachines";
    switch (cmd.getPowerOperation()) {
    case ON:
        apiName = "startVirtualMachine";
        break;
    case OFF:
    case SOFT:
        apiName = "stopVirtualMachine";
        break;
    case CYCLE:
    case RESET:
        apiName = "rebootVirtualMachine";
        break;
    }

    final ApacheCloudStackRequest apacheCloudStackRequest = new ApacheCloudStackRequest(apiName);
    apacheCloudStackRequest.addParameter("response", "json");
    apacheCloudStackRequest.addParameter("forced", "true");
    apacheCloudStackRequest.addParameter("id", vmUuid);

    final String apiResponse;
    try {
        apiResponse = client.executeRequest(apacheCloudStackRequest);
    } catch (final ApacheCloudStackClientRequestRuntimeException e) {
        LOG.error("Nested CloudStack oobm plugin failed due to API error: ", e);
        final OutOfBandManagementDriverResponse failedResponse = new OutOfBandManagementDriverResponse(
                e.getResponse(), "HTTP error code: " + e.getStatusCode(), false);
        if (e.getStatusCode() == 401) {
            failedResponse.setAuthFailure(true);
        }
        return failedResponse;
    }

    final OutOfBandManagementDriverResponse response = new OutOfBandManagementDriverResponse(apiResponse, null,
            true);
    if (OutOfBandManagement.PowerOperation.STATUS.equals(cmd.getPowerOperation())) {
        response.setPowerState(getNestedVMPowerState(apiResponse));
    }
    return response;
}