Example usage for com.google.common.collect BiMap inverse

List of usage examples for com.google.common.collect BiMap inverse

Introduction

In this page you can find the example usage for com.google.common.collect BiMap inverse.

Prototype

BiMap<V, K> inverse();

Source Link

Document

Returns the inverse view of this bimap, which maps each of this bimap's values to its associated key.

Usage

From source file:fi.hsl.parkandride.back.RequestLogDao.java

@Override
@Transactional(readOnly = false, isolation = SERIALIZABLE, propagation = Propagation.REQUIRES_NEW)
public void batchIncrement(Map<RequestLogKey, Long> nonNormalizedRequestLogCounts) {
    if (nonNormalizedRequestLogCounts.isEmpty()) {
        return;/* w w w  . j  a  va 2s  .c  om*/
    }
    // Normalize timestamps to hour
    final Map<RequestLogKey, Long> requestLogCounts = normalizeTimestamps(nonNormalizedRequestLogCounts);

    // Get rows to update
    final Set<DateTime> timestamps = extractFromKeys(requestLogCounts, key -> key.timestamp);
    final Map<RequestLogKey, Long> previousCountsForUpdate = getPreviousCountsForUpdate(timestamps);

    // Insert new sources and urls
    final BiMap<Long, String> allSources = insertNewSources(
            extractFromKeys(requestLogCounts, key -> key.source));
    final BiMap<Long, String> allUrls = insertNewUrls(extractFromKeys(requestLogCounts, key -> key.urlPattern));

    // Partition for insert/update
    final Map<Boolean, List<Map.Entry<RequestLogKey, Long>>> partitioned = requestLogCounts.entrySet().stream()
            .collect(partitioningBy(entry -> previousCountsForUpdate.containsKey(entry.getKey())));

    // Insert non-existing rows
    insertNew(partitioned.get(Boolean.FALSE), allSources.inverse(), allUrls.inverse());
    // Update
    updateExisting(partitioned.get(Boolean.TRUE), allSources.inverse(), allUrls.inverse());
}

From source file:org.ldp4j.application.kernel.lifecycle.EnvironmentImpl.java

private void addPublication(final BiMap<ResourceId, String> rootResourceMap, RootResource candidateResource)
        throws ApplicationConfigurationException {
    candidateResource.validate();/*from ww w. jav  a  2  s.c o  m*/
    ResourceId resourceId = candidateResource.resourceId();
    String path = candidateResource.path();
    String prevPath = rootResourceMap.get(resourceId);
    if (prevPath != null && !prevPath.equals(path)) {
        throw new ApplicationConfigurationException(
                String.format("Resource %s is already published (%s)", toString(resourceId), prevPath));
    }
    ResourceId prevResource = rootResourceMap.inverse().get(path);
    if (prevResource != null && !prevResource.equals(resourceId)) {
        throw new ApplicationConfigurationException(
                String.format("Path '%s' is already used by resource %s", path, toString(prevResource)));
    }
    rootResourceMap.put(resourceId, path);
}

From source file:net.sourcedestination.sai.comparison.matching.MatchingGenerator.java

public static GraphMatching includeEdgeMatching(final GraphMatching nodeMatching,
        BiMap<Integer, Integer> edgeMatch) {
    final BiMap<Integer, Integer> copyEdgeMatch = ImmutableBiMap.copyOf(edgeMatch);

    // transform Map.Entry to Pair instances
    final ImmutableSet<Pair<Integer>> matchedEdges = ImmutableSet.copyOf(edgeMatch.entrySet().stream()
            .map((arg) -> Pair.makePair(arg.getKey(), arg.getValue())).collect(toSet()));
    return new GraphMatching() {

        @Override//from  w w  w.ja  v a 2  s. c o  m
        public Graph getGraph1() {
            return nodeMatching.getGraph1();
        }

        @Override
        public Graph getGraph2() {
            return nodeMatching.getGraph2();
        }

        @Override
        public int getMatchedNodeInGraph2(int g1NodeID) {
            return nodeMatching.getMatchedNodeInGraph2(g1NodeID);
        }

        @Override
        public int getMatchedNodeInGraph1(int g2NodeID) {
            return nodeMatching.getMatchedNodeInGraph1(g2NodeID);
        }

        @Override
        public Set<Pair<Integer>> getAllNodeMatches() {
            return nodeMatching.getAllNodeMatches();
        }

        @Override
        public int getMatchedEdgeInGraph2(int g1NodeID) {
            if (copyEdgeMatch.containsKey(g1NodeID))
                return copyEdgeMatch.get(g1NodeID);
            return -1;
        }

        @Override
        public int getMatchedEdgeInGraph1(int g2NodeID) {
            if (copyEdgeMatch.inverse().containsKey(g2NodeID))
                return copyEdgeMatch.inverse().get(g2NodeID);
            return -1;
        }

        @Override
        public Set<Pair<Integer>> getAllEdgeMatches() {
            return matchedEdges;
        }

    };
}

From source file:io.prestosql.sql.planner.NodePartitioningManager.java

public NodePartitionMap getNodePartitioningMap(Session session, PartitioningHandle partitioningHandle) {
    requireNonNull(session, "session is null");
    requireNonNull(partitioningHandle, "partitioningHandle is null");

    if (partitioningHandle.getConnectorHandle() instanceof SystemPartitioningHandle) {
        return ((SystemPartitioningHandle) partitioningHandle.getConnectorHandle()).getNodePartitionMap(session,
                nodeScheduler);/*  w  w w  .  j  a  va2  s .com*/
    }

    ConnectorId connectorId = partitioningHandle.getConnectorId()
            .orElseThrow(() -> new IllegalArgumentException(
                    "No connector ID for partitioning handle: " + partitioningHandle));
    ConnectorNodePartitioningProvider partitioningProvider = partitioningProviders.get(connectorId);
    checkArgument(partitioningProvider != null, "No partitioning provider for connector %s", connectorId);

    ConnectorBucketNodeMap connectorBucketNodeMap = getConnectorBucketNodeMap(session, partitioningHandle);
    // safety check for crazy partitioning
    checkArgument(connectorBucketNodeMap.getBucketCount() < 1_000_000, "Too many buckets in partitioning: %s",
            connectorBucketNodeMap.getBucketCount());

    List<Node> bucketToNode;
    if (connectorBucketNodeMap.hasFixedMapping()) {
        bucketToNode = connectorBucketNodeMap.getFixedMapping();
    } else {
        bucketToNode = createArbitraryBucketToNode(nodeScheduler.createNodeSelector(connectorId).allNodes(),
                connectorBucketNodeMap.getBucketCount());
    }

    int[] bucketToPartition = new int[connectorBucketNodeMap.getBucketCount()];
    BiMap<Node, Integer> nodeToPartition = HashBiMap.create();
    int nextPartitionId = 0;
    for (int bucket = 0; bucket < bucketToNode.size(); bucket++) {
        Node node = bucketToNode.get(bucket);
        Integer partitionId = nodeToPartition.get(node);
        if (partitionId == null) {
            partitionId = nextPartitionId++;
            nodeToPartition.put(node, partitionId);
        }
        bucketToPartition[bucket] = partitionId;
    }

    List<Node> partitionToNode = IntStream.range(0, nodeToPartition.size())
            .mapToObj(partitionId -> nodeToPartition.inverse().get(partitionId)).collect(toImmutableList());

    return new NodePartitionMap(partitionToNode, bucketToPartition,
            getSplitToBucket(session, partitioningHandle));
}

From source file:blue.lapis.pore.converter.data.DataTypeConverter.java

@SuppressWarnings("rawtypes") // I am very tired and do not feel like dealing with generics anymore
public Collection<AbstractDataValue> of(byte data) throws IllegalArgumentException {
    ArrayList<AbstractDataValue> converted = new ArrayList<AbstractDataValue>();
    int i = 0;//from   w ww  .j  a  v a 2  s.co  m
    for (Map.Entry<BiMap<AbstractDataValue, Byte>, Byte> e : converters.entrySet()) {
        BiMap<AbstractDataValue, Byte> c = e.getKey();
        int bitsToConsider = e.getValue(); // the number of bits to consider from the data byte
        assert i + bitsToConsider <= 8; // we can't consider more than 8 bits within a single byte
        byte masked = data;
        masked >>= i; // right-shift to discard bits considered in previous iterations
        byte mask = (byte) (Math.pow(2, bitsToConsider) - 1); // calculate the bitmask based on the size
        masked &= mask; // apply the mask
        if (!c.containsValue(masked)) {
            throw new IllegalArgumentException(
                    "Out of bounds data byte for " + this.getClass().getSimpleName() + ": " + data);
        }
        AbstractDataValue adv = c.inverse().get(masked);
        if (adv.getValue() != AbstractDataValue.ABSENT) {
            converted.add(adv);
        }
        i += bitsToConsider; // increment the offset for future iterations
    }
    return converted;
}

From source file:at.bitandart.zoubek.mervin.diagram.diff.AddOverlayNodesCommand.java

public AddOverlayNodesCommand(TransactionalEditingDomain domain, Comparison diagramComparison,
        BiMap<EObject, EObject> copyMap, View container, Collection<Object> overlayedViews,
        PreferencesHint preferencesHint, ModelReviewFactory reviewFactory, ModelReview modelReview) {
    super(domain, "", null);
    this.diagramComparison = diagramComparison;
    this.container = container;
    this.inverseCopyMap = copyMap.inverse();
    this.preferencesHint = preferencesHint;
    this.reviewFactory = reviewFactory;
    this.overlayedViews = overlayedViews;
    this.modelReview = modelReview;
}

From source file:de.hzi.helmholtz.Compare.PathwayComparisonWithModules.java

public String reconstructWithGeneId(String positionIdStr, BiMap<Integer, Integer> newGeneIdToPositionMap) {
    String geneIdStr = "";
    String[] positions = positionIdStr.split("\\+");
    for (String position : positions) {
        int pos = Integer.parseInt(position.trim());
        geneIdStr += newGeneIdToPositionMap.inverse().get(pos) + "+";
    }/*ww w.  j  av  a 2  s  .  co m*/
    geneIdStr = geneIdStr.substring(0, geneIdStr.length() - 1);
    return geneIdStr;
}

From source file:com.google.android.apps.common.testing.accessibility.framework.uielement.AccessibilityHierarchy.java

/**
 * Associates {@link ViewHierarchyElement}s based on labeling ({@code android:labelFor})
 * relationships//from  w  w w.j  a va  2s .  com
 *
 * @param originMap A map from condensed unique IDs to the originating {@link
 *     AccessibilityNodeInfo} structures from which a {@link ViewHierarchyElement} was
 *     constructed, as populated by {@link AccessibilityHierarchy} constructors.
 */
@RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void resolveLabelForRelationshipsAmongInfos(BiMap<Long, AccessibilityNodeInfo> originMap) {
    for (Entry<Long, AccessibilityNodeInfo> entry : originMap.entrySet()) {
        AccessibilityNodeInfo labeledNode = entry.getValue().getLabelFor();
        if (labeledNode != null) {
            Long labeledElementId = originMap.inverse().get(labeledNode);
            if (labeledElementId != null) {
                ViewHierarchyElement labelElement = getViewById(entry.getKey());
                ViewHierarchyElement labeledElement = getViewById(labeledElementId);
                labeledElement.setLabeledBy(labelElement);
            }
        }
    }
}

From source file:org.shaf.server.controller.ActionProcessController.java

/**
 * Launches the process execution,/*  w w w .  jav  a  2 s  .co  m*/
 * 
 * @param cmd
 *            the command which launches a process.
 * @return the view model.
 * @throws Exception
 *             is the view constructing has failed.
 */
@RequestMapping(value = "/launch/{cmd}", method = RequestMethod.POST)
public ModelAndView onLaunch(@PathVariable String cmd) throws Exception {
    LOG.debug("CALL: /proc/action/launch/{" + cmd + "}");

    // Launching parameters extraction.
    BiMap<String, String> params = HashBiMap.create();
    Enumeration<String> names = REQUEST.getParameterNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        String value = REQUEST.getParameter(name);
        LOG.debug("PARAMS: " + name + "=" + value);

        if (name.startsWith("radio")) {
            String group = name.substring(0, name.indexOf('-'));
            String quantifier = name.substring(name.indexOf('-') + 1);

            if (quantifier.equals("opt")) {
                // This is a selected radio button option.
                if (params.containsKey(name)) {
                    params.inverse().put(params.get(name), value);
                } else {
                    params.put(value, group + "-arg");
                }
            } else {
                // This is a selected radio button argument.
                if (params.inverse().containsKey(name)) {
                    params.put(params.inverse().get(name), value);
                } else {
                    params.inverse().put(value, group + "-opt");
                }
            }
        } else {
            params.put(name, value);
        }
    }

    // Launching parameters cleanup.
    Iterator<String> keys = params.keySet().iterator();
    while (keys.hasNext()) {
        String key = keys.next();
        if (key.startsWith("radio")) {
            keys.remove();
        } else {

            String value = params.get(key);
            if (value == null) {
                params.put(key, "");
            } else {
                if (value.startsWith("radio")) {
                    params.put(key, "");
                }
            }
        }

    }

    StringBuilder args = new StringBuilder();
    if (params.containsKey("command-line")) {
        args.append(params.get("command-line"));
    } else {
        for (Map.Entry<String, String> param : params.entrySet()) {
            if (args.length() > 0) {
                args.append(' ');
            }
            args.append('-');
            args.append(param.getKey());
            if (!param.getValue().isEmpty()) {
                args.append(' ');
                if (param.getValue().contains(" ")) {
                    args.append('\"' + param.getValue() + '\"');
                } else {
                    args.append(param.getValue());
                }
            }
        }
    }

    String id = OPER.launchProcess(cmd, args.toString());

    return ViewJob.getInfoView().header("job", "Job: " + id).addJobId(id).addJobActiveStatus(true)
            .addJobFailedStatus(false).addJobOutcome(OPER.getJobOutcome(id))
            .info("The job execution in progress.");
}

From source file:seeit3d.base.ui.ide.view.MappingViewComposite.java

private void updateCurrentMappingAndVisualProperties(List<Container> containers,
        BiMap<MetricCalculator, VisualProperty> currentMapping) {

    for (VisualProperty visualProperty : VisualProperty.values()) {
        Group visualPropGroup = new Group(rootComposite, SWT.SHADOW_OUT);
        GridData visualGroupLayoutData = new GridData(GridData.FILL_HORIZONTAL);
        visualGroupLayoutData.heightHint = 50;
        visualGroupLayoutData.minimumWidth = 90;

        visualPropGroup.setLayoutData(visualGroupLayoutData);
        visualPropGroup.setText(visualProperty.toString());
        visualPropGroup.setLayout(new GridLayout(1, true));
        MetricCalculator metric = currentMapping.inverse().get(visualProperty);
        if (metric != null) {
            DragAndDropHelper.createMetricDraggableLabel(visualPropGroup, metric);
        }/*from   ww  w  .j  a v  a2 s. c  o m*/
        visualPropGroup.setData(VISUAL_PROPERTY, visualProperty);
        DragAndDropHelper.registerAsDroppable(visualPropGroup,
                new DropMetricOnVisualPropertyListener(visualPropGroup));
    }
}