Java Code Examples for com.google.common.collect.BiMap#containsKey()

The following examples show how to use com.google.common.collect.BiMap#containsKey() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HBaseStoreManager.java    From atlas with Apache License 2.0 6 votes vote down vote up
public static String shortenCfName(BiMap<String, String> shortCfNameMap, String longName) throws PermanentBackendException {
    final String s;
    if (shortCfNameMap.containsKey(longName)) {
        s = shortCfNameMap.get(longName);
        Preconditions.checkNotNull(s);
        logger.debug("Substituted default CF name \"{}\" with short form \"{}\" to reduce HBase KeyValue size", longName, s);
    } else {
        if (shortCfNameMap.containsValue(longName)) {
            String fmt = "Must use CF long-form name \"%s\" instead of the short-form name \"%s\" when configured with %s=true";
            String msg = String.format(fmt, shortCfNameMap.inverse().get(longName), longName, SHORT_CF_NAMES.getName());
            throw new PermanentBackendException(msg);
        }
        s = longName;
        logger.debug("Kept default CF name \"{}\" because it has no associated short form", s);
    }
    return s;
}
 
Example 2
Source File: MAPO.java    From api-mining with GNU General Public License v3.0 6 votes vote down vote up
private static void generateTransactionDatabase(final Collection<String> callSeqs,
		final BiMap<String, Integer> dictionary, final File transactionDB) throws IOException {

	final PrintWriter out = new PrintWriter(transactionDB);

	int mID = 0;
	for (final String callSeq : callSeqs) {
		for (final String call : callSeq.split(" ")) {
			if (dictionary.containsKey(call)) {
				final int ID = dictionary.get(call);
				out.print(ID + " -1 ");
			} else {
				out.print(mID + " -1 ");
				dictionary.put(call, mID);
				mID++;
			}
		}
		out.println("-2");
	}
	out.close();
}
 
Example 3
Source File: UPMiner.java    From api-mining with GNU General Public License v3.0 6 votes vote down vote up
private static void generateTransactionDatabase(final Collection<String> callSeqs,
		final BiMap<String, Integer> dictionary, final File transactionDB) throws IOException {

	final PrintWriter out = new PrintWriter(transactionDB);

	int mID = 0;
	for (final String callSeq : callSeqs) {
		for (final String call : callSeq.split(" ")) {
			if (dictionary.containsKey(call)) {
				final int ID = dictionary.get(call);
				out.print(ID + " -1 ");
			} else {
				out.print(mID + " -1 ");
				dictionary.put(call, mID);
				mID++;
			}
		}
		out.println("-2");
	}
	out.close();
}
 
Example 4
Source File: GobblinTrackingEventFlattenFilterConverter.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@Override
public Iterable<GenericRecord> convertRecordImpl(Schema outputSchema, GenericRecord inputRecord, WorkUnitState workUnit)
    throws DataConversionException {
  GenericRecord genericRecord = new GenericData.Record(outputSchema);

  BiMap<String, String> inversedViewOfFieldsRenameMap = this.fieldsRenameMap.inverse();
  for (Schema.Field field : outputSchema.getFields()) {
    String curFieldName = field.name();
    String originalFieldName =
        inversedViewOfFieldsRenameMap.containsKey(curFieldName) ? inversedViewOfFieldsRenameMap.get(curFieldName)
            : curFieldName;
    if (this.nonMapFields.contains(originalFieldName)) {
      genericRecord.put(curFieldName, inputRecord.get(originalFieldName));
    } else {
      genericRecord.put(curFieldName,
          AvroUtils.getFieldValue(inputRecord, Joiner.on('.').join(this.mapFieldName, originalFieldName)).or(""));
    }
  }
  return new SingleRecordIterable<>(genericRecord);
}
 
Example 5
Source File: FixedIntArrayIdMapTest.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
private BiMap<FixedIntArray, Integer> addValues(IdMap<FixedIntArray> idMap) {
  BiMap<FixedIntArray, Integer> map = HashBiMap.create();
  int numValues = 0;

  for (int row = 0; row < NUM_ROWS; row++) {
    int[] values = new int[NUM_COLUMNS];
    for (int col = 0; col < NUM_COLUMNS; col++) {
      values[col] = RANDOM.nextInt(10); // Max of 1000 unique values possible, so there will be duplicates.
    }
    FixedIntArray value = new FixedIntArray(values);
    idMap.put(value);

    if (!map.containsKey(value)) {
      map.put(value, numValues++);
    }
  }
  return map;
}
 
Example 6
Source File: UniqueCachedNaming.java    From immutables with Apache License 2.0 6 votes vote down vote up
private static <T> BiMap<T, String> buildBiMap(Iterable<T> values) {
  @SuppressWarnings("unchecked")
  Suggester<T> suggester = (Suggester<T>) PREFIX_SUGGESTER;
  final BiMap<T, String> map = HashBiMap.create();
  for (T value: values) {
    if (!map.containsKey(value)) {
      String name;
      for (int i = 0; ; i++) {
        name = suggester.suggest(value, i, map.size());
        if (!map.containsValue(name)) {
          map.put(value, name);
          break; // name found, break the loop
        }
      }
    }
  }

  return ImmutableBiMap.copyOf(map);
}
 
Example 7
Source File: LockedTenant.java    From vespa with Apache License 2.0 5 votes vote down vote up
public Cloud withDeveloperKey(PublicKey key, Principal principal) {
    BiMap<PublicKey, Principal> keys = HashBiMap.create(developerKeys);
    if (keys.containsKey(key))
        throw new IllegalArgumentException("Key " + KeyUtils.toPem(key) + " is already owned by " + keys.get(key));
    keys.put(key, principal);
    return new Cloud(name, billingInfo, keys);
}
 
Example 8
Source File: PAM.java    From api-mining with GNU General Public License v3.0 5 votes vote down vote up
private static void generateTransactionDatabase(final String arffFile, final BiMap<String, Integer> dictionary,
		final File transactionDB) throws IOException {

	int mID = 0;
	boolean found = false;
	final PrintWriter out = new PrintWriter(transactionDB);
	final LineIterator it = FileUtils.lineIterator(new File(arffFile));
	while (it.hasNext()) {
		final String line = it.nextLine();

		if (found) {
			for (final String raw_call : line.split(",")[1].replace("\'", "").split(" ")) {
				final String call = raw_call.trim();
				if (call.isEmpty()) // skip empty strings
					continue;
				if (dictionary.containsKey(call)) {
					final int ID = dictionary.get(call);
					out.print(ID + " -1 ");
				} else {
					out.print(mID + " -1 ");
					dictionary.put(call, mID);
					mID++;
				}
			}
			out.println("-2");
		}

		if (line.contains("@data"))
			found = true;

	}
	it.close();
	out.close();
}
 
Example 9
Source File: IfcModel.java    From BIMserver with GNU Affero General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private void checkDoubleOidsPlusReferences(BiMap<IdEObject, Long> done, IdEObject idEObject) {
	if (idEObject == null) {
		return;
	}
	if (idEObject.eClass().getEAnnotation("wrapped") != null) {
		return;
	}
	if (done.containsKey(idEObject)) {
		return;
	}
	if (done.containsValue(idEObject.getOid())) {
		showBackReferences(idEObject);
		IdEObject existing = done.inverse().get(idEObject.getOid());
		showBackReferences(existing);
		throw new RuntimeException("Double oid: " + idEObject.getOid() + " " + idEObject + ", " + existing);
	}
	done.put(idEObject, idEObject.getOid());
	for (EReference eReference : idEObject.eClass().getEAllReferences()) {
		if (eReference.isMany()) {
			List list = (List) idEObject.eGet(eReference);
			for (Object o : list) {
				checkDoubleOidsPlusReferences(done, (IdEObject) o);
			}
		} else {
			checkDoubleOidsPlusReferences(done, (IdEObject) idEObject.eGet(eReference));
		}
	}
}
 
Example 10
Source File: BindDnsServerImpl.java    From brooklyn-library with Apache License 2.0 4 votes vote down vote up
public void update() {
    Lifecycle serverState = getAttribute(Attributes.SERVICE_STATE_ACTUAL);
    if (Lifecycle.STOPPED.equals(serverState) || Lifecycle.STOPPING.equals(serverState)
            || Lifecycle.DESTROYED.equals(serverState) || !getAttribute(Attributes.SERVICE_UP)) {
        LOG.debug("Skipped update of {} when service state is {} and running is {}",
                new Object[]{this, getAttribute(Attributes.SERVICE_STATE_ACTUAL), getAttribute(SERVICE_UP)});
        return;
    }
    synchronized (this) {
        Iterable<Entity> availableEntities = FluentIterable.from(getEntities().getMembers())
                .filter(new HasHostnameAndValidLifecycle());
        LOG.debug("{} updating with entities: {}", this, Iterables.toString(availableEntities));
        ImmutableListMultimap<String, Entity> hostnameToEntity = Multimaps.index(availableEntities,
                new HostnameTransformer());

        Map<String, String> octetToName = Maps.newHashMap();
        BiMap<String, String> ipToARecord = HashBiMap.create();
        Multimap<String, String> aRecordToCnames = MultimapBuilder.hashKeys().hashSetValues().build();
        Multimap<String, String> ipToAllNames = MultimapBuilder.hashKeys().hashSetValues().build();

        for (Map.Entry<String, Entity> entry : hostnameToEntity.entries()) {
            String domainName = entry.getKey();
            Entity entity = entry.getValue();
            
            String address = null;
            
            AttributeSensor<String> addressSensor = getConfig(ADDRESS_SENSOR);
            if (addressSensor!=null) {
                address = entity.getAttribute(addressSensor);
                
            } else {
                if (!hasLoggedDeprecationAboutAddressSensor) {
                    LOG.warn("BIND entity "+this+" is using legacy machine inspection to determine IP address; set the "+ADDRESS_SENSOR.getName()+" config to ensure compatibility with future versions");
                    hasLoggedDeprecationAboutAddressSensor = true;
                }
                Maybe<SshMachineLocation> location = Machines.findUniqueMachineLocation(entity.getLocations(), SshMachineLocation.class);
                if (!location.isPresent()) {
                    LOG.debug("Member {} of {} does not have an hostname so will not be configured", entity, this);
                } else if (ipToARecord.inverse().containsKey(domainName)) {
                    // already has a hostname, ignore (could log if domain is different?)
                } else {
                    address = location.get().getAddress().getHostAddress();
                }
            }
            
            if (Strings.isBlank(address)) {
                continue;
            }
            
            ipToAllNames.put(address, domainName);
            if (!ipToARecord.containsKey(address)) {
                ipToARecord.put(address, domainName);
                if (getReverseLookupNetwork().contains(new Cidr(address + "/32"))) {
                    String octet = Iterables.get(Splitter.on('.').split(address), 3);
                    if (!octetToName.containsKey(octet)) octetToName.put(octet, domainName);
                }
            } else {
                aRecordToCnames.put(ipToARecord.get(address), domainName);
            }
        }
        sensors().set(A_RECORDS, ImmutableMap.copyOf(ipToARecord.inverse()));
        sensors().set(PTR_RECORDS, ImmutableMap.copyOf(octetToName));
        sensors().set(CNAME_RECORDS, Multimaps.unmodifiableMultimap(aRecordToCnames));
        sensors().set(ADDRESS_MAPPINGS, Multimaps.unmodifiableMultimap(ipToAllNames));

        // Update Bind configuration files and restart the service
        getDriver().updateBindConfiguration();
   }
}
 
Example 11
Source File: EquivState.java    From mesh with MIT License 4 votes vote down vote up
/**
 *
 */
private boolean matchScope(final ScopeType left, final ScopeType right)
{
    if (scopes.containsKey(left))
    {
        final ScopeType prevRight = scopes.get(left);
        if (!right.equals(prevRight))
        {
            if (Session.isDebug())
                Session.debug(left.getLoc(),
                    "scope {0} already matched with scope {1}, can''t match {2}",
                    left.dump(), prevRight.dump(), right.dump());

            return false;
        }
        else
        {
            if (Session.isDebug())
                Session.debug(left.getLoc(), "scope {0} matches scope {1}",
                    left.dump(), right.dump());

            return true;
        }
    }
    else 
    {
        final BiMap<ScopeType, ScopeType> inv = scopes.inverse();
        if (inv.containsKey(right))
        {
            final ScopeType prevLeft = inv.get(right);

            if (Session.isDebug())
                Session.debug(right.getLoc(),
                    "scope {0} already matched with scope {1}, can''t match {2}",
                    right.dump(), prevLeft.dump(), left.dump());

            return false;
        }
        else
        {
            if (Session.isDebug())
                Session.debug(left.getLoc(), "adding scope equiv {0} <=> {1}",
                    left.dump(), right.dump());

            scopes.put(left, right);

            return true;
        }
    }
}
 
Example 12
Source File: EquivState.java    From mesh with MIT License 4 votes vote down vote up
/**
 *
 */
public boolean matchParam(final TypeParam left, final TypeParam right)
{
    if (left.getKind() != right.getKind())
    {
        Session.error(left.getLoc(), "param {0} kind differs from param {1} kind",
            left.dump(), right.dump());

        return false;
    }

    final ScopeType leftScope = left.getTypeScope();
    final ScopeType rightScope = right.getTypeScope();

    if (!matchScope(leftScope, rightScope))
    {
        Session.error(left.getLoc(),
            "param {0} scoped at {1} is not compatible with param {2} scoped at {3}",
            left.dump(), leftScope.getLoc(),
            right.dump(), rightScope.getLoc());

        return false;
    }

    if (params.containsKey(left))
    {
        final TypeParam prev = params.get(left);

        if (!right.equals(prev))
        {
            if (Session.isDebug())
                Session.debug(left.getLoc(),
                    "param {0} already matched with param {1}, can''t match {2}",
                    left.dump(), prev.dump(), right.dump());

            return false;
        }

        return true;
    }
    else
    {
        final BiMap<TypeParam, TypeParam> inv = params.inverse();

        if (inv.containsKey(right))
        {
            final TypeParam prevLeft = inv.get(right);

            if (Session.isDebug())
                Session.debug(right.getLoc(),
                    "param {0} already matched with param {1}, can''t match {2}",
                    right.dump(), prevLeft.dump(), left.dump());

            return false;
        }

        params.put(left, right);

        return true;
    }
}
 
Example 13
Source File: OpenFlowControlMessageMapper.java    From onos with Apache License 2.0 3 votes vote down vote up
/**
 * Looks up the specified input value to the corresponding value with the specified map.
 *
 * @param map   bidirectional mapping
 * @param input input type
 * @param cls   class of output value
 * @param <I>   type of input value
 * @param <O>   type of output value
 * @return the corresponding value stored in the specified map
 */
private static <I, O> O lookup(BiMap<I, O> map, I input, Class<O> cls) {
    if (!map.containsKey(input)) {
        throw new IllegalArgumentException(
                String.format("No mapping found for %s when converting to %s",
                        input, cls.getName()));
    }
    return map.get(input);
}
 
Example 14
Source File: OpenFlowDeviceValueMapper.java    From onos with Apache License 2.0 3 votes vote down vote up
/**
 * Looks up the specified input value to the corresponding value with the specified map.
 *
 * @param map bidirectional mapping
 * @param input input value
 * @param cls class of output value
 * @param <I> type of input value
 * @param <O> type of output value
 * @return the corresponding value stored in the specified map
 */
private static <I, O> O lookup(BiMap<I, O> map, I input, Class<O> cls) {
    if (!map.containsKey(input)) {
        throw new IllegalArgumentException(
                String.format("No mapping found for %s when converting to %s", input, cls.getName()));
    }

    return map.get(input);
}
 
Example 15
Source File: OpenFlowValueMapper.java    From onos with Apache License 2.0 3 votes vote down vote up
/**
 * Looks up the specified input value to the corresponding value with the specified map.
 *
 * @param map bidirectional mapping
 * @param input input value
 * @param cls class of output value
 * @param <I> type of input value
 * @param <O> type of output value
 * @return the corresponding value stored in the specified map
 * @throws NoMappingFoundException if no corresponding value is found
 */
private static <I, O> O lookup(BiMap<I, O> map, I input, Class<O> cls) {
    if (!map.containsKey(input)) {
        throw new NoMappingFoundException(input, cls);
    }

    return map.get(input);
}
 
Example 16
Source File: ControlMessageMetricMapper.java    From onos with Apache License 2.0 3 votes vote down vote up
/**
 * Looks up the specified input value to the corresponding value with the specified map.
 *
 * @param map   bidirectional mapping
 * @param input input type
 * @param cls   class of output value
 * @param <I>   type of input value
 * @param <O>   type of output value
 * @return the corresponding value stored in the specified map
 */
private static <I, O> O lookup(BiMap<I, O> map, I input, Class<O> cls) {
    if (!map.containsKey(input)) {
        throw new IllegalArgumentException(
                String.format("No mapping found for %s when converting to %s",
                        input, cls.getName()));
    }
    return map.get(input);
}