Java Code Examples for com.google.common.collect.BiMap

The following are top voted examples for showing how to use com.google.common.collect.BiMap. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: CustomWorldGen   File: GameData.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void onCreate(Map<ResourceLocation, ?> slaveset, BiMap<ResourceLocation, ? extends IForgeRegistry<?>> registries)
{
    final ClearableObjectIntIdentityMap<IBlockState> idMap = new ClearableObjectIntIdentityMap<IBlockState>()
    {
        @SuppressWarnings("deprecation")
        @Override
        public int get(IBlockState key)
        {
            Integer integer = (Integer)this.identityMap.get(key);
            // There are some cases where this map is queried to serialize a state that is valid,
            //but somehow not in this list, so attempt to get real metadata. Doing this hear saves us 7 patches
            if (integer == null && key != null)
                integer = this.identityMap.get(key.getBlock().getStateFromMeta(key.getBlock().getMetaFromState(key)));
            return integer == null ? -1 : integer.intValue();
        }
    };
    ((Map<ResourceLocation,Object>)slaveset).put(BLOCKSTATE_TO_ID, idMap);
    final HashBiMap<Block, Item> map = HashBiMap.create();
    ((Map<ResourceLocation,Object>)slaveset).put(BLOCK_TO_ITEM, map);
}
 
Example 2
Project: BaseClient   File: SoundManager.java   Source Code and License 6 votes vote down vote up
public SoundManager(SoundHandler p_i45119_1_, GameSettings p_i45119_2_)
{
    this.invPlayingSounds = ((BiMap)this.playingSounds).inverse();
    this.playingSoundPoolEntries = Maps.<ISound, SoundPoolEntry>newHashMap();
    this.categorySounds = HashMultimap.<SoundCategory, String>create();
    this.tickableSounds = Lists.<ITickableSound>newArrayList();
    this.delayedSounds = Maps.<ISound, Integer>newHashMap();
    this.playingSoundsStopTime = Maps.<String, Integer>newHashMap();
    this.sndHandler = p_i45119_1_;
    this.options = p_i45119_2_;

    try
    {
        SoundSystemConfig.addLibrary(LibraryLWJGLOpenAL.class);
        SoundSystemConfig.setCodec("ogg", CodecJOrbis.class);
    }
    catch (SoundSystemException soundsystemexception)
    {
        logger.error(LOG_MARKER, (String)"Error linking with the LibraryJavaSound plug-in", (Throwable)soundsystemexception);
    }
}
 
Example 3
Project: n4js   File: N4HeadlessCompiler.java   Source Code and License 6 votes vote down vote up
private void configureResourceSetContainerState(final List<N4JSProject> allProjects) {
	// a container is a project.
	List<String> containers = new LinkedList<>();
	BiMap<String, N4JSProject> container2project = HashBiMap.create();

	// the URIs of all resources directly contained in a project/container.
	Multimap<String, URI> container2Uris = HashMultimap.create();

	for (N4JSProject project : allProjects) {
		String container = FileBasedWorkspace.N4FBPRJ + project.getLocation();
		container2project.put(container, project);
		containers.add(container);

		for (IN4JSSourceContainer sourceContainer : project.getSourceContainers()) {
			Iterables.addAll(container2Uris.get(container), sourceContainer);
		}
	}

	// Define the Mapping of Resources (URIs to Container === Projects),
	rsbAcs.configure(containers, container2Uris);
}
 
Example 4
Project: cakes   File: HashBiMapDemo.java   Source Code and License 6 votes vote down vote up
/**
 * BiMap存储数据时出现冲突
 * 存储时,如果key相同,则会覆盖,则逆转后不会有问题
 * 存储时,如果key不同,value有相同,则逆转时会抛出异常IllegalArgumentException
 */
@Test
public void testConflictInsertKV() {
    // 存储相同key数据,此时会覆盖k1=v1
    BiMap<String, String> biMap1 = HashBiMap.create();
    biMap1.put("k1", "v1");
    biMap1.put("k1", "v2");
    System.out.println("biMap1: " + biMap1);

    // 获取的只有 v2=k1
    BiMap<String, String> inverseBiMap1 = biMap1.inverse();
    System.out.println("inverseBiMap1: " + inverseBiMap1);

    System.out.println("--------------------------------------");

    // 存储相同的value数据
    BiMap<String, String> biMap2 = HashBiMap.create();
    biMap2.put("k1", "v1");

    // 此时抛出异常 java.lang.IllegalArgumentException: value already present: v1
    biMap2.put("k2", "v1");
    System.out.println("biMap2: " + biMap2);

    BiMap<String, String> inverseBiMap2 = biMap2.inverse();
    System.out.println("inverseBiMap2: " + inverseBiMap2);
}
 
Example 5
Project: BIMplatform   File: IfcModel.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private void fixOids(IdEObject idEObject, OidProvider oidProvider, BiMap<Long, IdEObject> temp) {
	if (idEObject == null) {
		return;
	}
	if (temp.containsValue(idEObject)) {
		return;
	}
	((IdEObjectImpl) idEObject).setOid(oidProvider.newOid(idEObject.eClass()));
	if (objects.containsValue(idEObject)) {
		temp.put(idEObject.getOid(), idEObject);
	}
	for (EReference eReference : idEObject.eClass().getEAllReferences()) {
		Object val = idEObject.eGet(eReference);
		if (eReference.isMany()) {
			List list = (List) val;
			for (Object o : list) {
				fixOids((IdEObject) o, oidProvider, temp);
			}
		} else {
			fixOids((IdEObject) val, oidProvider, temp);
		}
	}
}
 
Example 6
Project: CustomWorldGen   File: GameData.java   Source Code and License 6 votes vote down vote up
@Override
public void onSubstituteActivated(Map<ResourceLocation, ?> slaveset, Block original, Block replacement, ResourceLocation name)
{
    final BiMap<Block, Item> blockItemMap = (BiMap<Block, Item>)slaveset.get(BLOCK_TO_ITEM);
    if (blockItemMap.containsKey(original))
    {
        Item i = blockItemMap.get(original);
        if (i instanceof ItemBlock)
        {
            try
            {
                FinalFieldHelper.setField(blockField, i, replacement);
            }
            catch (Exception e)
            {
                throw Throwables.propagate(e);
            }
        }
        blockItemMap.forcePut(replacement,i);
    }
}
 
Example 7
Project: Mixinite   File: Mappings.java   Source Code and License 6 votes vote down vote up
public Optional<MethodRef> getUnmappedMethodMapping(CtClass targetClass, CtMethod
        handleMethod) {
    BiMap<MethodRef, MethodRef> methodsInverted = methodRefs.inverse();
    String descriptor = InjectorPlugin.removeCallbackDescriptor(handleMethod.getMethodInfo2()
            .getDescriptor());
    for (Map.Entry<MethodRef, MethodRef> mapping : methodsInverted.entrySet()) {
        MethodRef key = mapping.getKey();
        if (targetClass.getName().replace('.', '/').equals(key.getOwner()) && handleMethod
                .getName
                ().equals
                (key
                .getName()) && descriptor.equals(key.getDesc())) {
            return Optional.of(mapping.getValue());
        }
    }
    return Optional.empty();
}
 
Example 8
Project: rejoiner   File: ProtoRegistry.java   Source Code and License 6 votes vote down vote up
/** Applies the supplied modifications to the GraphQLTypes. */
private static BiMap<String, GraphQLType> modifyTypes(
    BiMap<String, GraphQLType> mapping,
    ImmutableListMultimap<String, TypeModification> modifications) {
  BiMap<String, GraphQLType> result = HashBiMap.create(mapping.size());
  for (String key : mapping.keySet()) {
    if (mapping.get(key) instanceof GraphQLObjectType) {
      GraphQLObjectType val = (GraphQLObjectType) mapping.get(key);
      if (modifications.containsKey(key)) {
        for (TypeModification modification : modifications.get(key)) {
          val = modification.apply(val);
        }
      }
      result.put(key, val);
    } else {
      result.put(key, mapping.get(key));
    }
  }
  return result;
}
 
Example 9
Project: googles-monorepo-demo   File: AbstractBiMapTester.java   Source Code and License 6 votes vote down vote up
@Override
protected void expectMissing(Entry<K, V>... entries) {
  super.expectMissing(entries);
  for (Entry<K, V> entry : entries) {
    Entry<V, K> reversed = reverseEntry(entry);
    BiMap<V, K> inv = getMap().inverse();
    assertFalse(
        "Inverse should not contain entry " + reversed, inv.entrySet().contains(reversed));
    assertFalse(
        "Inverse should not contain key " + reversed.getKey(),
        inv.containsKey(reversed.getKey()));
    assertFalse(
        "Inverse should not contain value " + reversed.getValue(),
        inv.containsValue(reversed.getValue()));
    /*
     * TODO(cpovirk): This is a bit stronger than super.expectMissing(), which permits a <key,
     * someOtherValue> pair.
     */
    assertNull(
        "Inverse should not return a mapping for key " + reversed.getKey(),
        inv.get(reversed.getKey()));
  }
}
 
Example 10
Project: CustomWorldGen   File: SoundManager.java   Source Code and License 6 votes vote down vote up
public SoundManager(SoundHandler p_i45119_1_, GameSettings p_i45119_2_)
{
    this.invPlayingSounds = ((BiMap)this.playingSounds).inverse();
    this.categorySounds = HashMultimap.<SoundCategory, String>create();
    this.tickableSounds = Lists.<ITickableSound>newArrayList();
    this.delayedSounds = Maps.<ISound, Integer>newHashMap();
    this.playingSoundsStopTime = Maps.<String, Integer>newHashMap();
    this.listeners = Lists.<ISoundEventListener>newArrayList();
    this.pausedChannels = Lists.<String>newArrayList();
    this.sndHandler = p_i45119_1_;
    this.options = p_i45119_2_;

    try
    {
        SoundSystemConfig.addLibrary(LibraryLWJGLOpenAL.class);
        SoundSystemConfig.setCodec("ogg", CodecJOrbis.class);
        net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.sound.SoundSetupEvent(this));
    }
    catch (SoundSystemException soundsystemexception)
    {
        LOGGER.error(LOG_MARKER, (String)"Error linking with the LibraryJavaSound plug-in", (Throwable)soundsystemexception);
    }
}
 
Example 11
Project: train-simulator   File: JourneyHelper.java   Source Code and License 5 votes vote down vote up
public BiMap<Train, Train> getTrainsFollowingEachOther() {
  if (false && trailingTrains.size() + 1 == world.getTrains().size()) {
    return trailingTrains;
  }
  trailingTrains.clear();

  Map<Journey, Journey> journeyTrail = getJourneysFollowingEachOther();
  journeyTrail.forEach((key, value) -> trailingTrains.put(key.getTrain(), value.getTrain()));

  return trailingTrains;
}
 
Example 12
Project: SubgraphIsomorphismIndex   File: IsoMatcherJena.java   Source Code and License 5 votes vote down vote up
@Override
public Iterable<BiMap<V, V>> match(BiMap<V, V> baseIso, G viewGraph, G insertGraph) {
    ProblemNeighborhoodAware<BiMap<V, V>, V> problem = toProblem(baseIso, viewGraph, insertGraph);
    Iterable<BiMap<V, V>> result = () -> problem.generateSolutions().iterator();

    return result;
}
 
Example 13
Project: CustomWorldGen   File: GameData.java   Source Code and License 5 votes vote down vote up
void registerSubstitutionAlias(String name, GameRegistry.Type type, Object toReplace) throws ExistingSubstitutionException
{
    ResourceLocation nameToSubstitute = new ResourceLocation(name);
    final BiMap<Block, Item> blockItemMap = getBlockItemMap();
    if (type == GameRegistry.Type.BLOCK)
    {
        iBlockRegistry.addSubstitutionAlias(Loader.instance().activeModContainer().getModId(), nameToSubstitute, (Block)toReplace);
        iBlockRegistry.activateSubstitution(nameToSubstitute);
    }
    else if (type == GameRegistry.Type.ITEM)
    {
        iItemRegistry.addSubstitutionAlias(Loader.instance().activeModContainer().getModId(), nameToSubstitute, (Item)toReplace);
        iItemRegistry.activateSubstitution(nameToSubstitute);
    }
}
 
Example 14
Project: Equella   File: WorkflowNode.java   Source Code and License 5 votes vote down vote up
public static BiMap<String, Integer> getTypeMap()
{
	BiMap<String, Integer> typeMap = HashBiMap.create();
	typeMap.put(ITEM_NODE_TYPE, ITEM_TYPE);
	typeMap.put(PARALLEL_NODE_TYPE, PARALLEL_TYPE);
	typeMap.put(SERIAL_NODE_TYPE, SERIAL_TYPE);
	typeMap.put(DECISION_NODE_TYPE, DECISION_TYPE);
	return typeMap;
}
 
Example 15
Project: powsybl-core   File: StringToIntMapper.java   Source Code and License 5 votes vote down vote up
public synchronized void dump(Writer writer) throws IOException {
    for (Map.Entry<S, BiMap<String, Integer>> entry : id2num.entrySet()) {
        S subset = entry.getKey();
        for (Map.Entry<String, Integer> entry1 : entry.getValue().entrySet()) {
            String id = entry1.getKey();
            Integer num = entry1.getValue();
            writer.write(subset + ";" + id + ";" + num + System.lineSeparator());
        }
    }
}
 
Example 16
Project: SubgraphIsomorphismIndex   File: IsoMatcherJena.java   Source Code and License 5 votes vote down vote up
public ProblemNeighborhoodAware<BiMap<V, V>, V> toProblem(BiMap<V, V> baseIso, G viewGraph, G insertGraph) {
    ProblemNeighborhoodAware<BiMap<V, V>, V> result = new ProblemNodeMappingGraph<V, E, G, V>(
            baseIso, viewGraph, insertGraph,
            createVertexComparator, createEdgeComparator);

    //Stream<BiMap<V, V>> result = tmp.generateSolutions();

    return result;
}
 
Example 17
Project: googles-monorepo-demo   File: DerivedGoogleCollectionGenerators.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public BiMap<V, K> create(Object... elements) {
  Entry<?, ?>[] entries = new Entry<?, ?>[elements.length];
  for (int i = 0; i < elements.length; i++) {
    entries[i] = reverse((Entry<K, V>) elements[i]);
  }
  return generator.create((Object[]) entries).inverse();
}
 
Example 18
Project: googles-monorepo-demo   File: BiMapClearTester.java   Source Code and License 5 votes vote down vote up
@MapFeature.Require(SUPPORTS_REMOVE)
public void testClearClearsInverse() {
  BiMap<V, K> inv = getMap().inverse();
  getMap().clear();
  assertTrue(getMap().isEmpty());
  assertTrue(inv.isEmpty());
}
 
Example 19
Project: hadoop-oss   File: ShellBasedIdMapping.java   Source Code and License 5 votes vote down vote up
synchronized private void loadFullGroupMap() throws IOException {
  BiMap<Integer, String> gMap = HashBiMap.create();

  if (OS.startsWith("Mac")) {
    updateMapInternal(gMap, "group", MAC_GET_ALL_GROUPS_CMD, "\\s+",
        staticMapping.gidMapping);
  } else {
    updateMapInternal(gMap, "group", GET_ALL_GROUPS_CMD, ":",
        staticMapping.gidMapping);
  }
  gidNameMap = gMap;
  lastUpdateTime = Time.monotonicNow();
}
 
Example 20
Project: librec-to-movies   File: RecommendMgr.java   Source Code and License 5 votes vote down vote up
public void initData(SparseMatrix dataMatrix) throws LibrecException {
	Table<Integer, Integer, Double> dataTable = dataMatrix.getDataTable();
	BiMap<String, Integer> userIds = dataModel.getUserMappingData();
	BiMap<String, Integer> itemIds = dataModel.getItemMappingData();
	SparseMatrix dateTimeDataSet = (SparseMatrix) dataModel.getDatetimeDataSet();
	Table<Integer, Integer, Double> dateTimeTable = dateTimeDataSet.getDataTable();
	for (Map.Entry<String, Integer> userId : userIds.entrySet()) {
		for (Map.Entry<String, Integer> itemId : itemIds.entrySet()) {
			Object scValue = dataTable.get(userId.getValue(), itemId.getValue());
			Object dtValue = dateTimeTable.get(userId.getValue(), itemId.getValue());
			if (scValue != null && dtValue != null) {
				Long user_id = Long.parseLong(userId.getKey());
				Long movie_id = Long.parseLong(itemId.getKey());
				Double score = (Double)scValue;
				Double datetime = (Double)dtValue;
				Rating rating = new Rating(user_id, movie_id, score);
				User user = User.findUser(user_id);
				if (user == null) continue;
				MovieEx movie = (MovieEx) MovieEx.findMovie(movie_id);
				if (movie == null) continue;
				try {
					user.addMovie(movie, score, datetime);
					movie.addUser(user, score, datetime);
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					throw new LibrecException("load rating set error");
				}
				//rating.save();
				Rating.allRatings.add(rating);
			}
		}
	}
}
 
Example 21
Project: googles-monorepo-demo   File: BiMapClearTester.java   Source Code and License 5 votes vote down vote up
@MapFeature.Require(SUPPORTS_REMOVE)
public void testClearInverseKeySetClears() {
  BiMap<V, K> inv = getMap().inverse();
  inv.keySet().clear();
  assertTrue(getMap().isEmpty());
  assertTrue(inv.isEmpty());
}
 
Example 22
Project: CustomWorldGen   File: GameData.java   Source Code and License 5 votes vote down vote up
@Override
public void onAdd(Item item, int blockId, Map<ResourceLocation, ?> slaves)
{
    if (item instanceof ItemBlock)
    {
        ItemBlock itemBlock = (ItemBlock)item;
        @SuppressWarnings("unchecked") BiMap<Block, Item> blockToItem = (BiMap<Block, Item>)slaves.get(BLOCK_TO_ITEM);
        final Block block = itemBlock.getBlock().delegate.get();
        blockToItem.forcePut(block, item);
    }
}
 
Example 23
Project: googles-monorepo-demo   File: BiMapClearTester.java   Source Code and License 5 votes vote down vote up
@MapFeature.Require(SUPPORTS_REMOVE)
public void testKeySetClearClearsInverse() {
  BiMap<V, K> inv = getMap().inverse();
  getMap().keySet().clear();
  assertTrue(getMap().isEmpty());
  assertTrue(inv.isEmpty());
}
 
Example 24
Project: oryx2   File: CategoricalValueEncodings.java   Source Code and License 5 votes vote down vote up
private static <T> BiMap<T,Integer> mapDistinctValues(Collection<T> distinct) {
  BiMap<T,Integer> mapping = HashBiMap.create(distinct.size());
  int encoding = 0;
  for (T t : distinct) {
    mapping.put(t, encoding);
    encoding++;
  }
  return mapping;
}
 
Example 25
Project: neto   File: ProtocolUnificationHandler.java   Source Code and License 5 votes vote down vote up
private ProtocolUnificationHandler(boolean isUnificationMode, BiMap<Integer, Class<? extends NetoJsonMessage>> opcodeMap, SslContext sslCtx, boolean detectSsl, int maxFrameLength, String charset) {
    this.isUnificationMode = isUnificationMode;
    this.opcodeMap = opcodeMap;
    this.sslCtx = sslCtx;
    this.detectSsl = detectSsl;
    this.maxFrameLength = maxFrameLength;
    this.charset = charset;
}
 
Example 26
Project: hashsdn-controller   File: YangStoreSnapshot.java   Source Code and License 5 votes vote down vote up
@Override
public String fromYang(final String enumClass, final String enumYangValue) {
    Preconditions.checkState(this.bindingContextProvider != null, "Binding context provider was not set yet");
    final BiMap<String, String> enumMapping = this.bindingContextProvider.getEnumMapping(enumClass);
    final String javaName = enumMapping.get(enumYangValue);
    return Preconditions.checkNotNull(javaName,
            "Unable to resolve enum value %s for enum class %s with assumed enum mapping: %s", enumYangValue,
            enumClass, enumMapping);
}
 
Example 27
Project: rejoiner   File: ProtoRegistry.java   Source Code and License 5 votes vote down vote up
ProtoRegistry build() {
  ImmutableListMultimap<String, TypeModification> modificationsMap =
      ImmutableListMultimap.copyOf(
          this.typeModifications
              .stream()
              .map(
                  modification ->
                      new SimpleImmutableEntry<>(modification.getTypeName(), modification))
              .collect(Collectors.toList()));

  final BiMap<String, GraphQLType> mapping = HashBiMap.create();

  GraphQLInterfaceType nodeInterface =
      new Relay()
          .nodeInterface(
              env -> {
                Relay.ResolvedGlobalId resolvedGlobalId =
                    new Relay().fromGlobalId(env.getArguments().get("id").toString());
                return (GraphQLObjectType) mapping.get(resolvedGlobalId.getType());
              });

  mapping.putAll(
      modifyTypes(
          getMap(fileDescriptors, descriptors, enumDescriptors, nodeInterface),
          modificationsMap));

  return new ProtoRegistry(mapping, nodeInterface);
}
 
Example 28
Project: rejoiner   File: ProtoRegistry.java   Source Code and License 5 votes vote down vote up
private static BiMap<String, GraphQLType> getMap(
    List<FileDescriptor> fileDescriptors,
    List<Descriptor> descriptors,
    List<EnumDescriptor> enumDescriptors,
    GraphQLInterfaceType nodeInterface) {
  HashBiMap<String, GraphQLType> mapping = HashBiMap.create(getEnumMap(enumDescriptors));
  LinkedList<Descriptor> loop = new LinkedList<>(descriptors);

  Set<FileDescriptor> fileDescriptorSet = extractDependencies(fileDescriptors);

  for (FileDescriptor fileDescriptor : fileDescriptorSet) {
    loop.addAll(fileDescriptor.getMessageTypes());
    mapping.putAll(getEnumMap(fileDescriptor.getEnumTypes()));
  }

  while (!loop.isEmpty()) {
    Descriptor descriptor = loop.pop();
    if (!mapping.containsKey(descriptor.getFullName())) {
      mapping.put(
          ProtoToGql.getReferenceName(descriptor),
          ProtoToGql.convert(descriptor, nodeInterface));
      GqlInputConverter inputConverter =
          GqlInputConverter.newBuilder().add(descriptor.getFile()).build();
      mapping.put(
          GqlInputConverter.getReferenceName(descriptor),
          inputConverter.getInputType(descriptor));
      loop.addAll(descriptor.getNestedTypes());

      mapping.putAll(getEnumMap(descriptor.getEnumTypes()));
    }
  }
  return ImmutableBiMap.copyOf(mapping);
}
 
Example 29
Project: enigma-vk   File: MappingsConverter.java   Source Code and License 5 votes vote down vote up
private static Signature translate(Signature signature, final BiMap<ClassEntry,ClassEntry> map) {
	if (signature == null) {
		return null;
	}
	return new Signature(signature, new ClassNameReplacer() {
		@Override
		public String replace(String inClassName) {
			ClassEntry outClassEntry = map.get(new ClassEntry(inClassName));
			if (outClassEntry == null) {
				return null;
			}
			return outClassEntry.getName();
		}
	});
}
 
Example 30
Project: TextHIN   File: FileUtils.java   Source Code and License 5 votes vote down vote up
public static BiMap<String, Integer> loadString2IntegerBiMap(String file, String delimiter) throws IOException {

    BiMap<String, Integer> res = HashBiMap.create();
    BufferedReader reader = IOUtils.getBufferedFileReader(file);
    String line;
    while ((line = reader.readLine()) != null) {

      String[] tokens = line.split(delimiter);
      res.put(tokens[0], Integer.parseInt(tokens[1]));

    }
    reader.close();
    return res;
  }
 
Example 31
Project: SubgraphIsomorphismIndex   File: ProblemNodeMappingGraph.java   Source Code and License 5 votes vote down vote up
public ProblemNodeMappingGraph(
        BiMap<V, V> baseSolution,
        G viewGraph,
        G queryGraph,
        Function<BiMap<V, V>, Comparator<V>> nodeComparatorFactory,
        Function<BiMap<V, V>, Comparator<E>> edgeComparatorFactory)
{
    this(
        baseSolution, viewGraph, queryGraph,
        nodeComparatorFactory, edgeComparatorFactory,
        true);
}
 
Example 32
Project: SubgraphIsomorphismIndex   File: SubgraphIsomorphismIndexImpl.java   Source Code and License 5 votes vote down vote up
/**
     * Lookup only pref keys / this skips results isomorphic to the given keys
     * @param queryGraph
     * @param exactMatch
     * @return
     */
    public Multimap<K, BiMap<V, V>> lookupFlat(G queryGraph, boolean exactMatch) {

        Set<T> queryGraphTags = extractGraphTagsWrapper(queryGraph);


        Collection<InsertPosition<K, G, V, T>> positions = new LinkedList<>();

        findInsertPositions(positions, rootNode, queryGraph, queryGraphTags, HashBiMap.create(), HashBiMap.create(), true, exactMatch); //, writer);

        Multimap<K, BiMap<V, V>> result = HashMultimap.create();

        if(logger.isDebugEnabled()) {
            logger.debug("Lookup result candidates: " + positions.size());
        }

        for(InsertPosition<K, G, V, T> pos : positions) {
            // Match with the children

            result.put(pos.getNode().getKey(), pos.getIso());
            //System.out.println("Node " + pos.node + " with keys " + pos.node.getKeys() + " iso: " + pos.getGraphIso().getInToOut());
//            for(K key : pos.node.getKeys()) {
//                result.put(key, pos.getIso());
//            }
        }
        return result;
    }
 
Example 33
Project: googles-monorepo-demo   File: DerivedGoogleCollectionGenerators.java   Source Code and License 5 votes vote down vote up
public BiMapValueSetGenerator(
    OneSizeTestContainerGenerator<BiMap<K, V>, Entry<K, V>> mapGenerator) {
  this.mapGenerator = mapGenerator;
  final SampleElements<Map.Entry<K, V>> mapSamples = this.mapGenerator.samples();
  this.samples =
      new SampleElements<V>(
          mapSamples.e0().getValue(),
          mapSamples.e1().getValue(),
          mapSamples.e2().getValue(),
          mapSamples.e3().getValue(),
          mapSamples.e4().getValue());
}
 
Example 34
Project: guava-mock   File: BiMapClearTester.java   Source Code and License 5 votes vote down vote up
@MapFeature.Require(SUPPORTS_REMOVE)
public void testValuesClearClearsInverse() {
  BiMap<V, K> inv = getMap().inverse();
  getMap().values().clear();
  assertTrue(getMap().isEmpty());
  assertTrue(inv.isEmpty());
}
 
Example 35
Project: guava-mock   File: BiMapClearTester.java   Source Code and License 5 votes vote down vote up
@MapFeature.Require(SUPPORTS_REMOVE)
public void testClearInverseKeySetClears() {
  BiMap<V, K> inv = getMap().inverse();
  inv.keySet().clear();
  assertTrue(getMap().isEmpty());
  assertTrue(inv.isEmpty());
}
 
Example 36
Project: guava-mock   File: BiMapClearTester.java   Source Code and License 5 votes vote down vote up
@MapFeature.Require(SUPPORTS_REMOVE)
public void testClearInverseValuesClears() {
  BiMap<V, K> inv = getMap().inverse();
  inv.values().clear();
  assertTrue(getMap().isEmpty());
  assertTrue(inv.isEmpty());
}
 
Example 37
Project: hadoop   File: ShellBasedIdMapping.java   Source Code and License 5 votes vote down vote up
synchronized private void loadFullUserMap() throws IOException {
  BiMap<Integer, String> uMap = HashBiMap.create();
  if (OS.startsWith("Mac")) {
    updateMapInternal(uMap, "user", MAC_GET_ALL_USERS_CMD, "\\s+",
        staticMapping.uidMapping);
  } else {
    updateMapInternal(uMap, "user", GET_ALL_USERS_CMD, ":",
        staticMapping.uidMapping);
  }
  uidNameMap = uMap;
  lastUpdateTime = Time.monotonicNow();
}
 
Example 38
Project: googles-monorepo-demo   File: BiMapInverseTester.java   Source Code and License 4 votes vote down vote up
BiMapPair(BiMap<K, V> original) {
  this.forward = original;
  this.backward = original.inverse();
}
 
Example 39
Project: train-simulator   File: GlobalMap.java   Source Code and License 4 votes vote down vote up
public BiMap<Integer, JourneyPath> getJourneyPaths() {
  return journeyPathsMap;
}
 
Example 40
Project: googles-monorepo-demo   File: AbstractBiMapTester.java   Source Code and License 4 votes vote down vote up
@Override
protected BiMap<K, V> getMap() {
  return (BiMap<K, V>) super.getMap();
}
 
Example 41
Project: SubgraphIsomorphismIndex   File: GraphVar.java   Source Code and License 4 votes vote down vote up
default BiMap<Node, Var> getNodeToVar() {
    return getVarToNode().inverse();
}
 
Example 42
Project: hadoop   File: TestShellBasedIdMapping.java   Source Code and License 4 votes vote down vote up
@Test
public void testIdOutOfIntegerRange() throws IOException {
  assumeTrue(!Shell.WINDOWS);
  String GET_ALL_USERS_CMD = "echo \""
      + "nfsnobody:x:4294967294:4294967294:Anonymous NFS User:/var/lib/nfs:/sbin/nologin\n"
      + "nfsnobody1:x:4294967295:4294967295:Anonymous NFS User:/var/lib/nfs1:/sbin/nologin\n"
      + "maxint:x:2147483647:2147483647:Grid Distributed File System:/home/maxint:/bin/bash\n"
      + "minint:x:2147483648:2147483648:Grid Distributed File System:/home/minint:/bin/bash\n"
      + "archivebackup:*:1031:4294967294:Archive Backup:/home/users/archivebackup:/bin/sh\n"
      + "hdfs:x:11501:10787:Grid Distributed File System:/home/hdfs:/bin/bash\n"
      + "daemon:x:2:2:daemon:/sbin:/sbin/nologin\""
      + " | cut -d: -f1,3";
  String GET_ALL_GROUPS_CMD = "echo \""
      + "hdfs:*:11501:hrt_hdfs\n"
      + "rpcuser:*:29:\n"
      + "nfsnobody:*:4294967294:\n"
      + "nfsnobody1:*:4294967295:\n"
      + "maxint:*:2147483647:\n"
      + "minint:*:2147483648:\n"
      + "mapred3:x:498\"" 
      + " | cut -d: -f1,3";
  // Maps for id to name map
  BiMap<Integer, String> uMap = HashBiMap.create();
  BiMap<Integer, String> gMap = HashBiMap.create();

  ShellBasedIdMapping.updateMapInternal(uMap, "user", GET_ALL_USERS_CMD, ":",
      EMPTY_PASS_THROUGH_MAP);
  assertTrue(uMap.size() == 7);
  assertEquals("nfsnobody", uMap.get(-2));
  assertEquals("nfsnobody1", uMap.get(-1));
  assertEquals("maxint", uMap.get(2147483647));
  assertEquals("minint", uMap.get(-2147483648));
  assertEquals("archivebackup", uMap.get(1031));
  assertEquals("hdfs",uMap.get(11501));
  assertEquals("daemon", uMap.get(2));

  ShellBasedIdMapping.updateMapInternal(gMap, "group", GET_ALL_GROUPS_CMD, ":",
      EMPTY_PASS_THROUGH_MAP);
  assertTrue(gMap.size() == 7);
  assertEquals("hdfs",gMap.get(11501));
  assertEquals("rpcuser", gMap.get(29));
  assertEquals("nfsnobody", gMap.get(-2));
  assertEquals("nfsnobody1", gMap.get(-1));
  assertEquals("maxint", gMap.get(2147483647));
  assertEquals("minint", gMap.get(-2147483648));
  assertEquals("mapred3", gMap.get(498));
}
 
Example 43
Project: SubgraphIsomorphismIndex   File: GraphIsoMapImpl.java   Source Code and License 4 votes vote down vote up
public BiMap<Node, Node> getOutToIn() {
    return inToOut.inverse();
}
 
Example 44
Project: train-simulator   File: GlobalMap.java   Source Code and License 4 votes vote down vote up
public BiMap<Integer, Integer> getTrackPairs() {
  return trackPairMap;
}
 
Example 45
Project: train-simulator   File: OriginalMapBuilder.java   Source Code and License 4 votes vote down vote up
public BiMap<Integer, Journey> getJourneys() {
  return journeysMap;
}
 
Example 46
Project: train-simulator   File: OriginalMapBuilder.java   Source Code and License 4 votes vote down vote up
public BiMap<Integer, JourneyPath> getJourneyPaths() {
  return journeyPathsMap;
}
 
Example 47
Project: train-simulator   File: OriginalMapBuilder.java   Source Code and License 4 votes vote down vote up
public BiMap<Integer, Track> getTracks() {
  return trackMap;
}
 
Example 48
Project: GitHub   File: ExtraCollection.java   Source Code and License 4 votes vote down vote up
@Value.Parameter
BiMap<Integer, String> biMap();
 
Example 49
Project: GitHub   File: Struct.java   Source Code and License 4 votes vote down vote up
@Value.Parameter
BiMap<Integer, String> biMap();
 
Example 50
Project: BaseClient   File: RegistryNamespaced.java   Source Code and License 4 votes vote down vote up
public RegistryNamespaced()
{
    this.inverseObjectRegistry = ((BiMap)this.registryObjects).inverse();
}
 
Example 51
Project: googles-monorepo-demo   File: DerivedGoogleCollectionGenerators.java   Source Code and License 4 votes vote down vote up
public MapGenerator(
    OneSizeTestContainerGenerator<BiMap<K, V>, Entry<K, V>> oneSizeTestContainerGenerator) {
  this.generator = oneSizeTestContainerGenerator;
}
 
Example 52
Project: HardVox   File: EnumArg.java   Source Code and License 4 votes vote down vote up
public static <E extends Enum<E>> EnumArg<E> create(Class<E> enumClass, String name, Function<E, String> argFunc) {
    BiMap<E, String> arguments = getArguments(enumClass, argFunc);
    return new EnumArg<>(arguments, name);
}
 
Example 53
Project: HardVox   File: EnumArg.java   Source Code and License 4 votes vote down vote up
private static <E extends Enum<E>> BiMap<E, String> getArguments(Class<E> enumClass, Function<E, String> argFunc) {
    return Stream.of(enumClass.getEnumConstants())
            .collect(toImmutableBiMap(Function.identity(), argFunc));
}
 
Example 54
Project: CustomWorldGen   File: GameData.java   Source Code and License 4 votes vote down vote up
@Override
public void onSubstituteActivated(Map<ResourceLocation, ?> slaveset, Item original, Item replacement, ResourceLocation name)
{
    final BiMap<Block, Item> blockItemMap = (BiMap<Block, Item>)slaveset.get(BLOCK_TO_ITEM);
}
 
Example 55
Project: Equella   File: WizardState.java   Source Code and License 4 votes vote down vote up
public BiMap<UUID, String> getRegisteredFilenames()
{
	return registeredFilenames;
}
 
Example 56
Project: ggvm   File: KeyboardInputProcessor.java   Source Code and License 4 votes vote down vote up
public BiMap<Axis, Integer> getActualAxisToAxisCode() {
    return actualAxisToAxisCode;
}
 
Example 57
Project: API   File: NameRegistry.java   Source Code and License 4 votes vote down vote up
@Override
public BiMap<IResourceName, T> getUnmodifiable(){
    return this.unmodifiableMap;
}
 
Example 58
Project: guava-mock   File: ArbitraryInstancesTest.java   Source Code and License 4 votes vote down vote up
public void testGet_collections() {
  assertEquals(ImmutableSet.of().iterator(), ArbitraryInstances.get(Iterator.class));
  assertFalse(ArbitraryInstances.get(PeekingIterator.class).hasNext());
  assertFalse(ArbitraryInstances.get(ListIterator.class).hasNext());
  assertEquals(ImmutableSet.of(), ArbitraryInstances.get(Iterable.class));
  assertEquals(ImmutableSet.of(), ArbitraryInstances.get(Set.class));
  assertEquals(ImmutableSet.of(), ArbitraryInstances.get(ImmutableSet.class));
  assertEquals(ImmutableSortedSet.of(), ArbitraryInstances.get(SortedSet.class));
  assertEquals(ImmutableSortedSet.of(), ArbitraryInstances.get(ImmutableSortedSet.class));
  assertEquals(ImmutableList.of(), ArbitraryInstances.get(Collection.class));
  assertEquals(ImmutableList.of(), ArbitraryInstances.get(ImmutableCollection.class));
  assertEquals(ImmutableList.of(), ArbitraryInstances.get(List.class));
  assertEquals(ImmutableList.of(), ArbitraryInstances.get(ImmutableList.class));
  assertEquals(ImmutableMap.of(), ArbitraryInstances.get(Map.class));
  assertEquals(ImmutableMap.of(), ArbitraryInstances.get(ImmutableMap.class));
  assertEquals(ImmutableSortedMap.of(), ArbitraryInstances.get(SortedMap.class));
  assertEquals(ImmutableSortedMap.of(), ArbitraryInstances.get(ImmutableSortedMap.class));
  assertEquals(ImmutableMultiset.of(), ArbitraryInstances.get(Multiset.class));
  assertEquals(ImmutableMultiset.of(), ArbitraryInstances.get(ImmutableMultiset.class));
  assertTrue(ArbitraryInstances.get(SortedMultiset.class).isEmpty());
  assertEquals(ImmutableMultimap.of(), ArbitraryInstances.get(Multimap.class));
  assertEquals(ImmutableMultimap.of(), ArbitraryInstances.get(ImmutableMultimap.class));
  assertTrue(ArbitraryInstances.get(SortedSetMultimap.class).isEmpty());
  assertEquals(ImmutableTable.of(), ArbitraryInstances.get(Table.class));
  assertEquals(ImmutableTable.of(), ArbitraryInstances.get(ImmutableTable.class));
  assertTrue(ArbitraryInstances.get(RowSortedTable.class).isEmpty());
  assertEquals(ImmutableBiMap.of(), ArbitraryInstances.get(BiMap.class));
  assertEquals(ImmutableBiMap.of(), ArbitraryInstances.get(ImmutableBiMap.class));
  assertTrue(ArbitraryInstances.get(ImmutableClassToInstanceMap.class).isEmpty());
  assertTrue(ArbitraryInstances.get(ClassToInstanceMap.class).isEmpty());
  assertTrue(ArbitraryInstances.get(ListMultimap.class).isEmpty());
  assertTrue(ArbitraryInstances.get(ImmutableListMultimap.class).isEmpty());
  assertTrue(ArbitraryInstances.get(SetMultimap.class).isEmpty());
  assertTrue(ArbitraryInstances.get(ImmutableSetMultimap.class).isEmpty());
  assertTrue(ArbitraryInstances.get(MapDifference.class).areEqual());
  assertTrue(ArbitraryInstances.get(SortedMapDifference.class).areEqual());
  assertEquals(Range.all(), ArbitraryInstances.get(Range.class));
  assertTrue(ArbitraryInstances.get(NavigableSet.class).isEmpty());
  assertTrue(ArbitraryInstances.get(NavigableMap.class).isEmpty());
  assertTrue(ArbitraryInstances.get(LinkedList.class).isEmpty());
  assertTrue(ArbitraryInstances.get(Deque.class).isEmpty());
  assertTrue(ArbitraryInstances.get(Queue.class).isEmpty());
  assertTrue(ArbitraryInstances.get(PriorityQueue.class).isEmpty());
  assertTrue(ArbitraryInstances.get(BitSet.class).isEmpty());
  assertTrue(ArbitraryInstances.get(TreeSet.class).isEmpty());
  assertTrue(ArbitraryInstances.get(TreeMap.class).isEmpty());
  assertFreshInstanceReturned(
      LinkedList.class, Deque.class, Queue.class, PriorityQueue.class, BitSet.class,
      TreeSet.class, TreeMap.class);
}
 
Example 59
Project: r8   File: R8DebugStrippingTest.java   Source Code and License 4 votes vote down vote up
@Test
public void testStackTraces()
    throws IOException, ProguardRuleParserException, ExecutionException, CompilationException {

  // Temporary directory for R8 output.
  Path out = temp.getRoot().toPath();

  R8Command command =
      R8Command.builder()
          .addProgramFiles(Paths.get(ROOT, EXAMPLE_DEX))
          .setOutputPath(out)
          .setProguardMapFile(Paths.get(ROOT, EXAMPLE_MAP))
          .build();

  // Generate R8 processed version.
  AndroidApp result =
      ToolHelper.runR8(command, (options) -> options.skipDebugLineNumberOpt = !compressRanges);

  ClassNameMapper classNameMapper;
  try (InputStream is = result.getProguardMap()) {
    classNameMapper = ProguardMapReader.mapperFromInputStream(is);
  }
  if (compressRanges) {
    classNameMapper.forAllClassNamings(this::ensureRangesAreUniquePerClass);
  }

  if (!ToolHelper.artSupported()) {
    return;
  }
  // Run art on original.
  String originalOutput =
      ToolHelper.runArtNoVerificationErrors(ROOT + EXAMPLE_DEX, EXAMPLE_CLASS);
  // Run art on R8 processed version.
  String otherOutput =
      ToolHelper.runArtNoVerificationErrors(out + "/classes.dex", EXAMPLE_CLASS);
  // Check that exceptions are in same range
  assertStacktracesMatchRanges(originalOutput, otherOutput, classNameMapper);

  // Check that we have debug information in all the places required.
  DexInspector inspector = new DexInspector(out.resolve("classes.dex"));
  BiMap<String, String> obfuscationMap
      = classNameMapper.getObfuscatedToOriginalMapping().inverse();
  ClassSubject overloaded = inspector.clazz(obfuscationMap.get("throwing.Overloaded"));
  assertTrue(overloaded.isPresent());
  ensureDebugInfosExist(overloaded);
}
 
Example 60
Project: hadoop-oss   File: ShellBasedIdMapping.java   Source Code and License 4 votes vote down vote up
@VisibleForTesting
public BiMap<Integer, String> getUidNameMap() {
  return uidNameMap;
}