Java Code Examples for com.google.common.collect.BiMap#get()
The following examples show how to use
com.google.common.collect.BiMap#get() .
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: UPMiner.java From api-mining with GNU General Public License v3.0 | 6 votes |
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 2
Source File: HBaseStoreManager.java From atlas with Apache License 2.0 | 6 votes |
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 3
Source File: CallSetNamesOptions.java From dataflow-java with Apache License 2.0 | 6 votes |
/** * 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(); }
Example 4
Source File: PostgreSQLNodeSaver.java From binnavi with Apache License 2.0 | 6 votes |
/** * 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; }
Example 5
Source File: GenericResultSetMapper.java From incubator-pinot with Apache License 2.0 | 6 votes |
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; }
Example 6
Source File: FakeReactorWorld.java From reactor_simulator with MIT License | 6 votes |
@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; }
Example 7
Source File: RootResource.java From usergrid with Apache License 2.0 | 6 votes |
@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 ); }
Example 8
Source File: PAM.java From api-mining with GNU General Public License v3.0 | 5 votes |
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: EnvironmentImpl.java From ldp4j with Apache License 2.0 | 5 votes |
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); }
Example 10
Source File: CommonRegistryCallbacks.java From OpenModsLib with MIT License | 5 votes |
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); }
Example 11
Source File: OperatorMapping.java From xtext-extras with Eclipse Public License 2.0 | 5 votes |
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>"); }
Example 12
Source File: TestTcpDataSender.java From pinpoint with Apache License 2.0 | 5 votes |
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; }
Example 13
Source File: GeneralRegressionModelEvaluator.java From jpmml-evaluator with GNU Affero General Public License v3.0 | 4 votes |
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; }
Example 14
Source File: EquivState.java From mesh with MIT License | 4 votes |
/** * */ 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 15
Source File: ServerTableSizeReader.java From incubator-pinot with Apache License 2.0 | 4 votes |
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; }
Example 16
Source File: AccessibilityViewHierarchyCheck.java From Accessibility-Test-Framework-for-Android with Apache License 2.0 | 4 votes |
/** * 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; }
Example 17
Source File: MetaDataEvolutionValidator.java From fdb-record-layer with Apache License 2.0 | 4 votes |
/** * 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()); } } }
Example 18
Source File: OpenFlowValueMapper.java From onos with Apache License 2.0 | 3 votes |
/** * 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 19
Source File: ControlMessageMetricMapper.java From onos with Apache License 2.0 | 3 votes |
/** * 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 20
Source File: OpenFlowControlMessageMapper.java From onos with Apache License 2.0 | 3 votes |
/** * 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); }