com.google.common.collect.BiMap#get ( )源码实例Demo

下面列出了com.google.common.collect.BiMap#get ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: atlas   文件: HBaseStoreManager.java
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;
}
 
源代码2 项目: reactor_simulator   文件: FakeReactorWorld.java
@Override
public String display() {
  String result = "";
  int y = 1;
  for (int i = 1; i < maxDims.x - 1; i++) {
    for (int j = 1; j < maxDims.z - 1; j++) {
      if (this.getTileEntity(i, y, j) != null) {
        result += "X ";
      } else if (this.isAirBlock(i, y, j)) {
        result += "O ";
      } else {
        String blockName = this.getBlockName(i, y, j);
        BiMap<String, Character> inverse = ReactorParser.mappings.inverse();
        Character c = inverse.get(blockName);
        result += c + " ";
      }
    }
    result += "\n";
  }
  return result;
}
 
源代码3 项目: usergrid   文件: RootResource.java
@Path(ORGANIZATION_ID_PATH+"/"+APPLICATION_ID_PATH)
public ApplicationResource getApplicationByUuids( @PathParam("organizationId") String organizationIdStr,
                                                  @PathParam("applicationId") String applicationIdStr )

        throws Exception {

    UUID applicationId = UUID.fromString( applicationIdStr );
    UUID organizationId = UUID.fromString( organizationIdStr );
    if ( applicationId == null || organizationId == null ) {
        return null;
    }
    BiMap<UUID, String> apps = management.getApplicationsForOrganization( organizationId );
    if ( apps.get( applicationId ) == null ) {
        return null;
    }
    return appResourceFor( applicationId );
}
 
源代码4 项目: incubator-pinot   文件: GenericResultSetMapper.java
List<Map<String, Object>> toResultMapList(ResultSet rs,
    Class<? extends AbstractEntity> entityClass) throws Exception {
  List<Map<String, Object>> resultMapList = new ArrayList<>();
  String tableName =
      entityMappingHolder.tableToEntityNameMap.inverse().get(entityClass.getSimpleName());
  BiMap<String, String> dbNameToEntityNameMapping =
      entityMappingHolder.columnMappingPerTable.get(tableName);
  while (rs.next()) {
    ResultSetMetaData resultSetMetaData = rs.getMetaData();
    int numColumns = resultSetMetaData.getColumnCount();
    HashMap<String, Object> map = new HashMap<>();
    for (int i = 1; i <= numColumns; i++) {
      String dbColumnName = resultSetMetaData.getColumnLabel(i).toLowerCase();
      String entityFieldName = dbNameToEntityNameMapping.get(dbColumnName);
      Object val = rs.getObject(i);
      if (val != null) {
        map.put(entityFieldName, val.toString());
      }
    }
    resultMapList.add(map);
  }
  System.out.println(resultMapList);
  return resultMapList;
}
 
源代码5 项目: binnavi   文件: PostgreSQLNodeSaver.java
/**
 * Sorts the group nodes of a view in a way that makes sure that group nodes inside other group
 * nodes come later in the list.
 *
 * @param groupNodeIndices Database indices of the group nodes to sort.
 * @param groupNodeMap Maps between group node database indices and objects.
 *
 * @return The sorted list of group node indices.
 */
protected static List<Integer> sortGroupNodes(final List<Integer> groupNodeIndices,
    final BiMap<Integer, INaviGroupNode> groupNodeMap) {
  final List<Integer> sortedList = new ArrayList<Integer>();
  final List<Integer> clonedList = new ArrayList<Integer>(groupNodeIndices);
  final Set<INaviGroupNode> addedNodes = new HashSet<INaviGroupNode>();

  while (!clonedList.isEmpty()) {
    for (final Integer id : clonedList) {
      final INaviGroupNode node = groupNodeMap.get(id);

      if ((node.getParentGroup() == null) || addedNodes.contains(node.getParentGroup())) {
        addedNodes.add(node);
        sortedList.add(id);
        clonedList.remove(id);
        break;
      }
    }
  }

  return sortedList;
}
 
源代码6 项目: dataflow-java   文件: CallSetNamesOptions.java
/**
 * Return the call set ids corresponding to the call set names provided in the options.
 *
 * This has a side-effect of confirming that the call set names within the variant set are unique.
 *
 * @param options
 * @return a list of unique call set ids
 * @throws IOException
 */
public static List<String> getCallSetIds(final CallSetNamesOptions options) throws IOException {
  List<String> callSetNames = getCallSetNames(options);
  if (callSetNames.isEmpty()) {
    return callSetNames;  // Return the empty list.
  }

  ImmutableSet.Builder<String> callSetIds = ImmutableSet.<String>builder();
  Iterable<CallSet> callSets = GenomicsUtils.getCallSets(options.getVariantSetId(),
      GenomicsOptions.Methods.getGenomicsAuth(options));
  BiMap<String,String> nameToId = null;
  try {
    nameToId = CallSetUtils.getCallSetNameMapping(callSets);
  } catch (IllegalArgumentException e) {
    throw new IllegalArgumentException("VariantSet " + options.getVariantSetId()
        + " contains duplicate callset name(s).", e);
  }
  for (String callSetName : callSetNames) {
    String id = nameToId.get(callSetName);
    Preconditions.checkNotNull(id,
        "Call set name '%s' does not correspond to a call set id in variant set id %s",
        callSetName, options.getVariantSetId());
    callSetIds.add(id);
  }
  return callSetIds.build().asList();
}
 
源代码7 项目: api-mining   文件: UPMiner.java
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();
}
 
源代码8 项目: pinpoint   文件: TestTcpDataSender.java
public int getStringId(String string) {
    BiMap<String, Integer> stringMap = stringIdMap.inverse();
    Integer id = stringMap.get(string);

    if (id == null) {
        throw new NoSuchElementException(string);
    }

    return id;
}
 
源代码9 项目: xtext-extras   文件: OperatorMapping.java
public static void main(String[] args) throws Exception {
	System.out.println(" * <table>");
	System.out.println(" *   <tr><th>Operator</th><th>Method Name</th></tr>");
	Field[] fields = OperatorMapping.class.getFields();
	BiMap<QualifiedName, QualifiedName> map = new OperatorMapping().map;
	for(Field field: fields) {
		if (Modifier.isStatic(field.getModifiers()) && field.getType().equals(QualifiedName.class) ) {
			Object operator = field.get(null);
			QualifiedName methodName = map.get(operator);
			System.out.println(" *   <tr><td>"+ toHtml(operator) + "</td><td>" + toHtml(methodName) + "</td></tr>");
		}
	}
	System.out.println(" * </table>");
}
 
源代码10 项目: OpenModsLib   文件: CommonRegistryCallbacks.java
public static <T, E extends IForgeRegistryEntry<E>> Integer mapObjectToId(IForgeRegistry<E> registry, T object) {
	final Map<T, E> objectToEntryMap = CommonRegistryCallbacks.getObjectToEntryMap(registry);
	final E entry = objectToEntryMap.get(object);

	final BiMap<E, Integer> entryIdMap = CommonRegistryCallbacks.getEntryIdMap(registry);
	return entryIdMap.get(entry);
}
 
源代码11 项目: ldp4j   文件: EnvironmentImpl.java
private void addPublication(final BiMap<ResourceId, String> rootResourceMap, RootResource candidateResource) throws ApplicationConfigurationException {
	candidateResource.validate();
	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);
}
 
源代码12 项目: api-mining   文件: PAM.java
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();
}
 
/**
 * Validate that the record types have all been evolved in a legal way. In particular, this makes sure that
 * each record type defined in the union descriptor is in the new union descriptor in the correct
 * place. It will then verify that each message type has been updated in a legal way, i.e., that it only
 * includes new fields.
 *
 * @param oldUnionDescriptor the union descriptor for the existing meta-data for some record store
 * @param newUnionDescriptor the new proposed meta-data
 */
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public void validateUnion(@Nonnull Descriptor oldUnionDescriptor, @Nonnull Descriptor newUnionDescriptor) {
    if (oldUnionDescriptor == newUnionDescriptor) {
        // Don't bother validating the record types if they are all the same.
        return;
    }
    final BiMap<Descriptor, Descriptor> updatedDescriptors = HashBiMap.create(oldUnionDescriptor.getFields().size());
    final Set<Pair<Descriptor, Descriptor>> seenDescriptors = new HashSet<>();

    for (FieldDescriptor oldUnionField : oldUnionDescriptor.getFields()) {
        if (!oldUnionField.getType().equals(FieldDescriptor.Type.MESSAGE)) {
            throw new MetaDataException("field in union is not a message type", LogMessageKeys.FIELD_NAME, oldUnionField.getName());
        }
        int fieldNumber = oldUnionField.getNumber();
        FieldDescriptor newUnionField = newUnionDescriptor.findFieldByNumber(fieldNumber);
        if (newUnionField != null) {
            if (!newUnionField.getType().equals(FieldDescriptor.Type.MESSAGE)) {
                throw new MetaDataException("field in new union is not a message type", LogMessageKeys.FIELD_NAME, newUnionField.getName());
            }
            Descriptor oldRecord = oldUnionField.getMessageType();
            Descriptor newRecord = newUnionField.getMessageType();

            // Verify that all fields of the same type in the old union are also of the same type
            // in the new union (i.e., that there are no "splits" or "merges" of record types).
            Descriptor alreadySeenNewRecord = updatedDescriptors.get(oldRecord);
            if (alreadySeenNewRecord != null) {
                if (alreadySeenNewRecord != newRecord) {
                    // A "split" -- the same type in the old union points to two different types in the new union
                    throw new MetaDataException("record type corresponds to multiple types in new meta-data",
                            LogMessageKeys.OLD_RECORD_TYPE, oldRecord.getName(),
                            LogMessageKeys.NEW_RECORD_TYPE, newRecord.getName() + " & " + alreadySeenNewRecord.getName());
                }
            } else {
                if (updatedDescriptors.containsValue(newRecord)) {
                    // A "merge" -- two different types in the old union point to the same type in the new union
                    final Descriptor alreadySeenOldRecord = updatedDescriptors.inverse().get(newRecord);
                    throw new MetaDataException("record type corresponds to multiple types in old meta-data",
                            LogMessageKeys.OLD_RECORD_TYPE, oldRecord.getName() + " & " + alreadySeenOldRecord.getName(),
                            LogMessageKeys.NEW_RECORD_TYPE, newRecord.getName());
                }
            }
            updatedDescriptors.put(oldRecord, newRecord);

            // Validate the form of the old and new record types
            validateMessage(oldRecord, newRecord, seenDescriptors);
        } else {
            throw new MetaDataException("record type removed from union", LogMessageKeys.RECORD_TYPE, oldUnionField.getMessageType());
        }
    }
}
 
源代码14 项目: incubator-pinot   文件: ServerTableSizeReader.java
public Map<String, List<SegmentSizeInfo>> getSegmentSizeInfoFromServers(BiMap<String, String> serverEndPoints,
    String tableNameWithType, int timeoutMs) {
  int numServers = serverEndPoints.size();
  LOGGER.info("Reading segment sizes from {} servers for table: {} with timeout: {}ms", numServers, tableNameWithType,
      timeoutMs);

  List<String> serverUrls = new ArrayList<>(numServers);
  BiMap<String, String> endpointsToServers = serverEndPoints.inverse();
  for (String endpoint : endpointsToServers.keySet()) {
    String tableSizeUri = "http://" + endpoint + "/table/" + tableNameWithType + "/size";
    serverUrls.add(tableSizeUri);
  }

  // TODO: use some service other than completion service so that we know which server encounters the error
  CompletionService<GetMethod> completionService =
      new MultiGetRequest(_executor, _connectionManager).execute(serverUrls, timeoutMs);
  Map<String, List<SegmentSizeInfo>> serverToSegmentSizeInfoListMap = new HashMap<>();

  for (int i = 0; i < numServers; i++) {
    GetMethod getMethod = null;
    try {
      getMethod = completionService.take().get();
      URI uri = getMethod.getURI();
      String instance = endpointsToServers.get(uri.getHost() + ":" + uri.getPort());
      if (getMethod.getStatusCode() >= 300) {
        LOGGER.error("Server: {} returned error: {}", instance, getMethod.getStatusCode());
        continue;
      }
      TableSizeInfo tableSizeInfo =
          JsonUtils.inputStreamToObject(getMethod.getResponseBodyAsStream(), TableSizeInfo.class);
      serverToSegmentSizeInfoListMap.put(instance, tableSizeInfo.segments);
    } catch (Exception e) {
      // Ignore individual exceptions because the exception has been logged in MultiGetRequest
      // Log the number of failed servers after gathering all responses
    } finally {
      if (getMethod != null) {
        getMethod.releaseConnection();
      }
    }
  }

  int numServersResponded = serverToSegmentSizeInfoListMap.size();
  if (numServersResponded != numServers) {
    LOGGER.warn("Finish reading segment sizes for table: {} with {}/{} servers responded", tableNameWithType,
        numServersResponded, numServers);
  } else {
    LOGGER.info("Finish reading segment sizes for table: {}", tableNameWithType);
  }
  return serverToSegmentSizeInfoListMap;
}
 
private <V extends Number> Value<V> computeReferencePoint(ValueFactory<V> valueFactory){
	GeneralRegressionModel generalRegressionModel = getModel();

	BiMap<String, Parameter> parameters = getParameterRegistry();

	Map<?, List<PCell>> paramMatrixMap = getParamMatrixMap();

	Iterable<PCell> parameterCells = paramMatrixMap.get(null);

	if(paramMatrixMap.size() != 1 || parameterCells == null){
		ParamMatrix paramMatrix = generalRegressionModel.getParamMatrix();

		throw new InvalidElementException(paramMatrix);
	}

	Value<V> result = null;

	for(PCell parameterCell : parameterCells){
		String parameterName = parameterCell.getParameterName();
		if(parameterName == null){
			throw new MissingAttributeException(parameterCell, PMMLAttributes.PCELL_PARAMETERNAME);
		}

		Number beta = parameterCell.getBeta();
		if(beta == null){
			throw new MissingAttributeException(parameterCell, PMMLAttributes.PCELL_BETA);
		} // End if

		if(result == null){
			result = valueFactory.newValue();
		}

		Parameter parameter = parameters.get(parameterName);
		if(parameter != null){
			result.add(beta, parameter.getReferencePoint());
		} else

		{
			return null;
		}
	}

	return result;
}
 
源代码16 项目: mesh   文件: EquivState.java
/**
 *
 */
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;
        }
    }
}
 
/**
 * Delegate a legacy view based check to a more complete AccessibilityHierarchyCheck
 *
 * @param root The root view of the hierarchy to check.
 * @param fromCheck The legacy view which calls this method.
 * @param toCheck The AccessibilityHierarchyCheck to be run.
 * @param parameters Optional input data or preferences.
 * @return A list of interesting results encountered while running the check. The list will be
 *     empty if the check passes without incident.
 */
@SuppressWarnings("deprecation") // AccessibilityViewCheckResult used for legacy check delegation
protected List<AccessibilityViewCheckResult> runDelegationCheckOnView(
    View root,
    AccessibilityCheck fromCheck,
    AccessibilityHierarchyCheck toCheck,
    @Nullable Parameters parameters) {

  // Construct the AccessibilityHierarchyAndroid from the actual view root, as to capture all
  // available information within the view hierarchy.
  View actualRoot = root.getRootView();
  BiMap<Long, View> mapFromElementIdToView = HashBiMap.<Long, View>create();
  AccessibilityHierarchyAndroid hierarchy =
      AccessibilityHierarchyAndroid.newBuilder(actualRoot)
          .setViewOriginMap(mapFromElementIdToView)
          .build();

  // Although we captured our hierarchy from the actual root view, we pass along information about
  // the provided "root" in order to constrain evaluation to the provided sub-hierarchy.
  Long rootId = mapFromElementIdToView.inverse().get(root);
  ViewHierarchyElement evalRoot = (rootId != null) ? hierarchy.getViewById(rootId) : null;
  if (evalRoot == null) {
    LogUtils.e(
        TAG,
        "Unable to determine root during accessibility check delegation, using full hierarchy.");
  }

  // Run the delegated check
  List<AccessibilityHierarchyCheckResult> hierarchyCheckResults =
      toCheck.runCheckOnHierarchy(hierarchy, evalRoot, parameters);

  // Remap results to the original format
  ArrayList<AccessibilityViewCheckResult> results = new ArrayList<>(hierarchyCheckResults.size());
  for (AccessibilityHierarchyCheckResult hierarchyCheckResult : hierarchyCheckResults) {
    ViewHierarchyElement element = hierarchyCheckResult.getElement();
    View checkedView =
        (element != null) ? mapFromElementIdToView.get(element.getCondensedUniqueId()) : null;
    results.add(
        new AccessibilityViewCheckResult(toCheck.getClass(), hierarchyCheckResult, checkedView));
  }

  return results;
}
 
源代码18 项目: onos   文件: OpenFlowValueMapper.java
/**
 * 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);
}
 
源代码19 项目: onos   文件: ControlMessageMetricMapper.java
/**
 * 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);
}
 
源代码20 项目: onos   文件: OpenFlowControlMessageMapper.java
/**
 * 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);
}