com.google.common.collect.HashBiMap Java Examples
The following examples show how to use
com.google.common.collect.HashBiMap.
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: ReverseMapLookup.java From levelup-java-examples with Apache License 2.0 | 6 votes |
@Test public void flip_map_entries_with_guava() { BiMap<String, String> stateCodeToDescription = HashBiMap.create(); stateCodeToDescription.put("WI", "Wisconsin"); stateCodeToDescription.put("MN", "Minnesota"); stateCodeToDescription.put("FL", "Florida"); stateCodeToDescription.put("IA", "Iowa"); stateCodeToDescription.put("OH", "Ohio"); BiMap<String, String> descriptionToStateCode = stateCodeToDescription .inverse(); logger.info(descriptionToStateCode); assertEquals("WI", descriptionToStateCode.get("Wisconsin")); }
Example #2
Source File: EurostagFakeNodes.java From ipst with Mozilla Public License 2.0 | 6 votes |
public static EurostagFakeNodes build(Network network, EurostagEchExportConfig config) { Objects.requireNonNull(network); Objects.requireNonNull(config); BiMap<String, String> fakeNodesMap = HashBiMap.create(new HashMap<>()); AtomicLongMap<String> countUsesMap = AtomicLongMap.create(); //adds 2 default fake nodes fakeNodesMap.put(EchUtil.FAKE_NODE_NAME1, EchUtil.FAKE_NODE_NAME1); countUsesMap.getAndIncrement(EchUtil.FAKE_NODE_NAME1); fakeNodesMap.put(EchUtil.FAKE_NODE_NAME2, EchUtil.FAKE_NODE_NAME2); countUsesMap.getAndIncrement(EchUtil.FAKE_NODE_NAME2); Identifiables.sort(network.getVoltageLevels()).stream().map(VoltageLevel::getId).forEach(vlId -> fakeNodesMap.put(vlId, newEsgId(fakeNodesMap, vlId))); return new EurostagFakeNodes(fakeNodesMap, countUsesMap, network); }
Example #3
Source File: ManagementServiceImpl.java From usergrid with Apache License 2.0 | 6 votes |
@Override public List<OrganizationInfo> getOrganizations( UUID startResult, int count ) throws Exception { // still need the bimap to search for existing BiMap<UUID, String> organizations = HashBiMap.create(); EntityManager em = emf.getEntityManager(smf.getManagementAppId()); Results results = em.getCollection(em.getApplicationRef(), Schema.COLLECTION_GROUPS, startResult, count, Level.ALL_PROPERTIES, false); List<OrganizationInfo> orgs = new ArrayList<>( results.size() ); OrganizationInfo orgInfo; for ( Entity entity : results.getEntities() ) { String path = ( String ) entity.getProperty( PROPERTY_PATH ); if ( organizations.containsValue( path ) ) { path += "DUPLICATE"; } orgInfo = new OrganizationInfo( entity.getUuid(), path ); orgs.add( orgInfo ); organizations.put( entity.getUuid(), path ); } return orgs; }
Example #4
Source File: EnumValueXPathFunctionTest.java From yangtools with Eclipse Public License 1.0 | 6 votes |
@Test public void testEnumValueFunction() throws Exception { final SchemaContext schemaContext = YangParserTestUtils.parseYangResources(EnumValueXPathFunctionTest.class, "/yang-xpath-functions-test/enum-value-function/foo.yang"); assertNotNull(schemaContext); final XPathSchemaContext jaxenSchemaContext = SCHEMA_CONTEXT_FACTORY.createContext(schemaContext); final XPathDocument jaxenDocument = jaxenSchemaContext.createDocument(buildMyContainerNode("major")); final BiMap<String, QNameModule> converterBiMap = HashBiMap.create(); converterBiMap.put("foo-prefix", FOO_MODULE); final NormalizedNodeContextSupport normalizedNodeContextSupport = NormalizedNodeContextSupport.create( (JaxenDocument) jaxenDocument, Maps.asConverter(converterBiMap)); final NormalizedNodeContext normalizedNodeContext = normalizedNodeContextSupport.createContext( buildPathToSeverityLeafNode("major")); final Function enumValueFunction = normalizedNodeContextSupport.getFunctionContext() .getFunction(null, null, "enum-value"); final int enumValueResult = (int) enumValueFunction.call(normalizedNodeContext, ImmutableList.of()); assertEquals(5, enumValueResult); }
Example #5
Source File: MappingServiceImpl.java From canal_mysql_elasticsearch_sync with Apache License 2.0 | 6 votes |
@Override public void afterPropertiesSet() throws Exception { dbEsBiMapping = HashBiMap.create(); dbEsMapping.forEach((key, value) -> { String[] keyStrings = StringUtils.split(key, "."); String[] valueStrings = StringUtils.split(value, "."); dbEsBiMapping.put(new DatabaseTableModel(keyStrings[0], keyStrings[1]), new IndexTypeModel(valueStrings[0], valueStrings[1])); }); mysqlTypeElasticsearchTypeMapping = Maps.newHashMap(); mysqlTypeElasticsearchTypeMapping.put("char", data -> data); mysqlTypeElasticsearchTypeMapping.put("text", data -> data); mysqlTypeElasticsearchTypeMapping.put("blob", data -> data); mysqlTypeElasticsearchTypeMapping.put("int", Long::valueOf); mysqlTypeElasticsearchTypeMapping.put("date", data -> LocalDateTime.parse(data, FORMATTER)); mysqlTypeElasticsearchTypeMapping.put("time", data -> LocalDateTime.parse(data, FORMATTER)); mysqlTypeElasticsearchTypeMapping.put("float", Double::valueOf); mysqlTypeElasticsearchTypeMapping.put("double", Double::valueOf); mysqlTypeElasticsearchTypeMapping.put("decimal", Double::valueOf); }
Example #6
Source File: EnumValueXPathFunctionTest.java From yangtools with Eclipse Public License 1.0 | 6 votes |
@Test public void testInvalidTypeOfCorrespondingSchemaNode() throws Exception { final SchemaContext schemaContext = YangParserTestUtils.parseYangResources(EnumValueXPathFunctionTest.class, "/yang-xpath-functions-test/enum-value-function/foo-invalid.yang"); assertNotNull(schemaContext); final XPathSchemaContext jaxenSchemaContext = SCHEMA_CONTEXT_FACTORY.createContext(schemaContext); final XPathDocument jaxenDocument = jaxenSchemaContext.createDocument(buildMyContainerNode("major")); final BiMap<String, QNameModule> converterBiMap = HashBiMap.create(); converterBiMap.put("foo-prefix", FOO_MODULE); final NormalizedNodeContextSupport normalizedNodeContextSupport = NormalizedNodeContextSupport.create( (JaxenDocument) jaxenDocument, Maps.asConverter(converterBiMap)); final NormalizedNodeContext normalizedNodeContext = normalizedNodeContextSupport.createContext( buildPathToSeverityLeafNode("major")); final Function enumValueFunction = normalizedNodeContextSupport.getFunctionContext() .getFunction(null, null, "enum-value"); final Double enumValueResult = (Double) enumValueFunction.call(normalizedNodeContext, ImmutableList.of()); assertEquals(Double.NaN, enumValueResult, 0.001); }
Example #7
Source File: DefaultValidationNotificationService.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
private static Map<Set<User>, SortedSet<MessagePair>> groupRecipientsForMessagePairs( Map<User, SortedSet<MessagePair>> messagePairsPerUser ) { BiMap<Set<User>, SortedSet<MessagePair>> grouped = HashBiMap.create(); for ( Map.Entry<User, SortedSet<MessagePair>> entry : messagePairsPerUser.entrySet() ) { User user = entry.getKey(); SortedSet<MessagePair> setOfPairs = entry.getValue(); if ( grouped.containsValue( setOfPairs ) ) { // Value exists -> Add user to the existing key set grouped.inverse().get( setOfPairs ).add( user ); } else { // Value doesn't exist -> Add the [user, set] as a new entry grouped.put( Sets.newHashSet( user ), setOfPairs ); } } return grouped; }
Example #8
Source File: ParticipatingClients.java From qpid-broker-j with Apache License 2.0 | 6 votes |
private BiMap<String, String> mapConfiguredToRegisteredClientNames(List<String> configuredClientNamesForTest, ClientRegistry clientRegistry) { BiMap<String, String> configuredToRegisteredNameMap = HashBiMap.create(); TreeSet<String> registeredClients = new TreeSet<String>(clientRegistry.getClients()); for (String configuredClientName : configuredClientNamesForTest) { String allocatedClientName = registeredClients.pollFirst(); if (allocatedClientName == null) { throw new IllegalArgumentException("Too few clients in registry " + clientRegistry + " configured clients " + configuredClientNamesForTest); } configuredToRegisteredNameMap.put(configuredClientName, allocatedClientName); } return configuredToRegisteredNameMap; }
Example #9
Source File: ExportAdmins.java From usergrid with Apache License 2.0 | 6 votes |
private void addOrganizationsToTask(AdminUserWriteTask task) throws Exception { task.orgNamesByUuid = managementService.getOrganizationsForAdminUser( task.adminUser.getUuid() ); List<Org> orgs = userToOrgsMap.get( task.adminUser.getUuid() ); if ( orgs != null && task.orgNamesByUuid.size() < orgs.size() ) { // list of orgs from getOrganizationsForAdminUser() is less than expected, use userToOrgsMap BiMap<UUID, String> bimap = HashBiMap.create(); for (Org org : orgs) { bimap.put( org.orgId, org.orgName ); } task.orgNamesByUuid = bimap; } }
Example #10
Source File: ChronicleMapTest.java From Chronicle-Map with Apache License 2.0 | 6 votes |
@Test public void valuesIteratorRemoveReflectedInMapAndOtherViews() throws IOException { try (ChronicleMap<Integer, CharSequence> map = getViewTestMap(3)) { HashBiMap<Integer, CharSequence> refMap = HashBiMap.create(); map.forEach((k, v) -> refMap.put(k, v.toString())); Set<Map.Entry<Integer, CharSequence>> entrySet = map.entrySet(); Set<Integer> keySet = map.keySet(); Collection<CharSequence> values = map.values(); Iterator<CharSequence> valueIterator = values.iterator(); valueIterator.next(); refMap.inverse().remove(valueIterator.next().toString()); valueIterator.remove(); int[] expectedKeys = Ints.toArray(refMap.keySet()); CharSequence[] expectedValues = new CharSequence[expectedKeys.length]; for (int i = 0; i < expectedKeys.length; i++) { expectedValues[i] = refMap.get(expectedKeys[i]); } assertMap(map, expectedKeys, expectedValues); assertEntrySet(entrySet, expectedKeys, expectedValues); assertKeySet(keySet, expectedKeys); assertValues(values, expectedValues); } }
Example #11
Source File: ProtoRegistry.java From rejoiner with Apache License 2.0 | 6 votes |
/** 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 #12
Source File: UniqueCachedNaming.java From immutables with Apache License 2.0 | 6 votes |
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 #13
Source File: SubjectUtils.java From usergrid with Apache License 2.0 | 6 votes |
@SuppressWarnings( "unchecked" ) public static BiMap<UUID, String> getApplications() { Subject currentUser = getSubject(); if ( currentUser == null ) { return null; } if ( !currentUser.hasRole( ROLE_APPLICATION_ADMIN ) && !currentUser.hasRole( ROLE_APPLICATION_USER ) ) { return null; } Session session = currentUser.getSession(); BiMap<UUID, String> applications = HashBiMap.create(); Map map = (Map)session.getAttribute( "applications" ); applications.putAll(map); return applications; }
Example #14
Source File: DerivedFromXPathFunctionTest.java From yangtools with Eclipse Public License 1.0 | 6 votes |
@Test public void testInvalidTypeOfCorrespondingSchemaNode() throws Exception { final SchemaContext schemaContext = YangParserTestUtils.parseYangResources(DerivedFromXPathFunctionTest.class, "/yang-xpath-functions-test/derived-from-function/bar-invalid.yang"); assertNotNull(schemaContext); final XPathSchemaContext jaxenSchemaContext = SCHEMA_CONTEXT_FACTORY.createContext(schemaContext); final XPathDocument jaxenDocument = jaxenSchemaContext.createDocument(buildMyContainerNode(ID_C2_IDENTITY)); final BiMap<String, QNameModule> converterBiMap = HashBiMap.create(); converterBiMap.put("bar-prefix", BAR_MODULE); final NormalizedNodeContextSupport normalizedNodeContextSupport = NormalizedNodeContextSupport.create( (JaxenDocument) jaxenDocument, Maps.asConverter(converterBiMap)); final NormalizedNodeContext normalizedNodeContext = normalizedNodeContextSupport.createContext( buildPathToIdrefLeafNode()); final Function derivedFromFunction = normalizedNodeContextSupport.getFunctionContext() .getFunction(null, null, "derived-from"); assertFalse(getDerivedFromResult(derivedFromFunction, normalizedNodeContext, "some-identity")); }
Example #15
Source File: AggregationPipelineQueryNodeTest.java From rya with Apache License 2.0 | 6 votes |
@Test public void testFilter() { final AggregationPipelineQueryNode base = new AggregationPipelineQueryNode( collection, new LinkedList<>(), Sets.newHashSet("x", "y"), Sets.newHashSet("x", "y", "opt"), HashBiMap.create()); // Extend with a supported filter AggregationPipelineQueryNode node = base.clone(); boolean success = node.filter(new Compare(new Var("x"), new Var("y"), Compare.CompareOp.EQ)); Assert.assertTrue(success); Assert.assertEquals(Sets.newHashSet("x", "y", "opt"), node.getBindingNames()); Assert.assertEquals(Sets.newHashSet("x", "y"), node.getAssuredBindingNames()); Assert.assertEquals(3, node.getPipeline().size()); // Extend with an unsupported filter node = base.clone(); success = node.filter(new IsLiteral(new Var("opt"))); Assert.assertFalse(success); Assert.assertEquals(Sets.newHashSet("x", "y", "opt"), node.getBindingNames()); Assert.assertEquals(Sets.newHashSet("x", "y"), node.getAssuredBindingNames()); Assert.assertEquals(0, node.getPipeline().size()); }
Example #16
Source File: XlsxFormatter.java From yarg with Apache License 2.0 | 6 votes |
/** * XLSX document does not store empty cells and it might be an issue for formula calculations and etc. * So we need to create fake template cell for each empty cell. */ protected void createFakeTemplateCellsForEmptyOnes(Range oneRowRange, Map<CellReference, Cell> cellsForOneRowRange, List<Cell> templateCells) { if (oneRowRange.toCellReferences().size() != templateCells.size()) { final HashBiMap<CellReference, Cell> referencesToCells = HashBiMap.create(cellsForOneRowRange); for (CellReference cellReference : oneRowRange.toCellReferences()) { if (!cellsForOneRowRange.containsKey(cellReference)) { Cell newCell = Context.getsmlObjectFactory().createCell(); newCell.setV(null); newCell.setT(STCellType.STR); newCell.setR(cellReference.toReference()); templateCells.add(newCell); referencesToCells.put(cellReference, newCell); } } templateCells.sort((o1, o2) -> { CellReference cellReference1 = referencesToCells.inverse().get(o1); CellReference cellReference2 = referencesToCells.inverse().get(o2); return cellReference1.compareTo(cellReference2); }); } }
Example #17
Source File: StorageContext.java From Kylin with Apache License 2.0 | 6 votes |
public StorageContext() { this.threshold = DEFAULT_THRESHOLD; this.limit = DEFAULT_THRESHOLD; this.totalScanCount = 0; this.cuboid = null; this.aliasMap = HashBiMap.create(); this.hasSort = false; this.sortOrders = new ArrayList<OrderEnum>(); this.sortMeasures = new ArrayList<MeasureDesc>(); this.exactAggregation = false; this.enableLimit = false; this.enableCoprocessor = false; this.acceptPartialResult = false; this.partialResultReturned = false; }
Example #18
Source File: SvnToGitMapper.java From naturalize with BSD 3-Clause "New" or "Revised" License | 6 votes |
public BiMap<Integer, String> mapSvnToGit() throws IOException, NoWorkTreeException, NoHeadException, GitAPIException { final BiMap<Integer, String> mappings = HashBiMap.create(); final Git repository = GitCommitUtils .getGitRepository(repositoryDirectory); for (final RevCommit commit : GitCommitUtils .getAllCommitsTopological(repository)) { final String message = commit.getFullMessage(); if (!message.contains("git-svn-id")) { continue; } final Matcher matcher = svnIdMatcher.matcher(message); matcher.find(); mappings.put(Integer.parseInt(matcher.group(1)), commit.name()); } return mappings; }
Example #19
Source File: TargetsDifferTest.java From buck with Apache License 2.0 | 5 votes |
@Test public void throwsExceptionOnRemoveIfMaxDiffsFound() throws MaxDifferencesException { expectedThrownException.expectMessage("Stopping after finding 2 differences"); expectedThrownException.expect(MaxDifferencesException.class); Map<String, String> originalFileContents = ImmutableMap.of( "//:target1", "d70cf68c1773e1c9882e4e3e9c7e9dc06173f82f", "//:target2", "0340a9686229b00c43642d9f8dd07e313ee6c8ba", "//:target3", "927bf4f375b2167c93e8219d5d50056f69019dfb", "//:target4", "2e943f1a14f1190868391ae0e4d660d01457271b", "//:target5", "d48528295847c0bb6856e6f62c2872f9d8e44b9d"); Map<String, String> newFileContents = ImmutableMap.of( "//:target4", "2e943f1a14f1190868391ae0e4d660d01457271b", "//:target5", "d48528295847c0bb6856e6f62c2872f9d8e44b9d"); ParsedTargetsFile originalFile = new ParsedTargetsFile( Paths.get("file1"), HashBiMap.create(originalFileContents), Duration.ofNanos(1)); ParsedTargetsFile newFile = new ParsedTargetsFile( Paths.get("file2"), HashBiMap.create(newFileContents), Duration.ofNanos(1)); DifferState differState = new DifferState(2); TargetsDiffer targetsDiffer = new TargetsDiffer(diffPrinter, differState); targetsDiffer.printDiff(originalFile, newFile); }
Example #20
Source File: AggregationPipelineQueryNodeTest.java From rya with Apache License 2.0 | 5 votes |
@Test public void testDistinct() { final AggregationPipelineQueryNode base = new AggregationPipelineQueryNode( collection, new LinkedList<>(), Sets.newHashSet("x", "y"), Sets.newHashSet("x", "y", "opt"), HashBiMap.create()); AggregationPipelineQueryNode node = base.clone(); boolean success = node.distinct(); Assert.assertTrue(success); Assert.assertEquals(Sets.newHashSet("x", "y", "opt"), node.getBindingNames()); Assert.assertEquals(Sets.newHashSet("x", "y"), node.getAssuredBindingNames()); Assert.assertEquals(1, node.getPipeline().size()); }
Example #21
Source File: GuavaBiMapUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenQueryByKey_returnsValue() { final BiMap<String, String> capitalCountryBiMap = HashBiMap.create(); capitalCountryBiMap.put("New Delhi", "India"); capitalCountryBiMap.put("Washingon, D.C.", "USA"); capitalCountryBiMap.put("Moscow", "Russia"); assertEquals("USA", capitalCountryBiMap.get("Washingon, D.C.")); }
Example #22
Source File: ArrangeObjects.java From txtUML with Eclipse Public License 1.0 | 5 votes |
private void setIndices() { _indices = HashBiMap.create(_objects.size()); // Set indices { Integer index = 1; for (RectangleObject o : _objects) { _indices.put(o.getName(), index); ++index; } } }
Example #23
Source File: TimeGraphFindDialog.java From tracecompass with Eclipse Public License 2.0 | 5 votes |
/** * Returns whether the specified search string can be found using the given * options. * * @param findString * the string to search for * @param options * The search options * @return <code>true</code> if the search string can be found using the * given options * */ private boolean findAndSelect(String findString, SearchOptions options) { FindTarget findTarget = fFindTarget; if (findTarget == null) { return false; } ITimeGraphEntry[] topInput = findTarget.getEntries(); BiMap<@NonNull ITimeGraphEntry, @NonNull Integer> items = HashBiMap.create(); for (ITimeGraphEntry entry : topInput) { listEntries(items, entry); } int startPosition = findTarget.getSelection() == null ? 0 : NonNullUtils.checkNotNull(items.get(findTarget.getSelection())); int index = findNext(findString, startPosition, items, options); if (index == -1) { statusMessage(Messages.TimeGraphFindDialog_StatusNoMatchLabel); return false; } if (options.forwardSearch && index >= startPosition || !options.forwardSearch && index <= startPosition) { statusMessage(""); //$NON-NLS-1$ } // Send the entry found to target findTarget.selectAndReveal(NonNullUtils.checkNotNull(items.inverse().get(index))); return true; }
Example #24
Source File: ShellBasedIdMapping.java From hadoop with Apache License 2.0 | 5 votes |
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 #25
Source File: ClassXMLReader.java From hkxpack with MIT License | 5 votes |
/** * Retrieve all the enumerations described as {@link Node} in the given {@link NodeList}, and store them in this {@link ClassXMLReader}'s {@link HKXEnumResolver}. * @param classname the classname currently read. * @param enums the enumeration node list. */ private void retrieveEnums(final String classname, final NodeList enums) { StringBuffer enumNameBuffer = new StringBuffer(); NodeList enumsObjects = enums.item(0).getChildNodes(); for(int i = 0; i < enumsObjects.getLength(); i++) { Node enumObject = enumsObjects.item(i); if(enumObject.getAttributes() != null) { Map<Integer, String> enumContents = createHashMap(); enumNameBuffer.setLength(0); String enumName = enumNameBuffer .append(classname) .append(".") .append(DOMUtils.getNodeAttr("name", enumObject)) .toString(); for(int j = 0; j < enumObject.getChildNodes().getLength(); j++) { Node enumObjectContent = enumObject.getChildNodes().item(j); if(enumObjectContent.getAttributes() != null) { String enumObjectName = DOMUtils.getNodeAttr("name", enumObjectContent); int enumObjectContents = Integer.parseInt(DOMUtils.getNodeAttr("value", enumObjectContent)); enumContents.put(enumObjectContents, enumObjectName); } } BiMap<Integer, String> test = HashBiMap.create(enumContents); enumResolver.add(enumName, test.inverse()); } } }
Example #26
Source File: GuavaBiMapUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenSameKeyIsPresent_replacesAlreadyPresent() { final BiMap<String, String> capitalCountryBiMap = HashBiMap.create(); capitalCountryBiMap.put("New Delhi", "India"); capitalCountryBiMap.put("Washingon, D.C.", "USA"); capitalCountryBiMap.put("Moscow", "Russia"); capitalCountryBiMap.put("Washingon, D.C.", "HongKong"); assertEquals("HongKong", capitalCountryBiMap.get("Washingon, D.C.")); }
Example #27
Source File: HaloController.java From arcusandroid with Apache License 2.0 | 5 votes |
/** * Get the room types from the device model. The keys / values will be swapped. * * @return map of user string->key */ protected Map<String, String> doGetRoomTypes() { DeviceModel deviceModel = deviceModelOrEmitError(); if (deviceModel != null) { Map<String, String> roomTypes = nonNullMap(deviceModel.get(Halo.ATTR_ROOMNAMES)); return HashBiMap.create(roomTypes).inverse(); } else { return Collections.emptyMap(); } }
Example #28
Source File: TestShellBasedIdMapping.java From hadoop with Apache License 2.0 | 5 votes |
@Test public void testStaticMapping() throws IOException { assumeTrue(!Shell.WINDOWS); Map<Integer, Integer> uidStaticMap = new PassThroughMap<Integer>(); Map<Integer, Integer> gidStaticMap = new PassThroughMap<Integer>(); uidStaticMap.put(11501, 10); gidStaticMap.put(497, 200); // Maps for id to name map BiMap<Integer, String> uMap = HashBiMap.create(); BiMap<Integer, String> gMap = HashBiMap.create(); String GET_ALL_USERS_CMD = "echo \"atm:x:1000:1000:Aaron T. Myers,,,:/home/atm:/bin/bash\n" + "hdfs:x:11501:10787:Grid Distributed File System:/home/hdfs:/bin/bash\"" + " | cut -d: -f1,3"; String GET_ALL_GROUPS_CMD = "echo \"hdfs:*:11501:hrt_hdfs\n" + "mapred:x:497\n" + "mapred2:x:498\"" + " | cut -d: -f1,3"; ShellBasedIdMapping.updateMapInternal(uMap, "user", GET_ALL_USERS_CMD, ":", uidStaticMap); ShellBasedIdMapping.updateMapInternal(gMap, "group", GET_ALL_GROUPS_CMD, ":", gidStaticMap); assertEquals("hdfs", uMap.get(10)); assertEquals(10, (int)uMap.inverse().get("hdfs")); assertEquals("atm", uMap.get(1000)); assertEquals(1000, (int)uMap.inverse().get("atm")); assertEquals("hdfs", gMap.get(11501)); assertEquals(11501, (int)gMap.inverse().get("hdfs")); assertEquals("mapred", gMap.get(200)); assertEquals(200, (int)gMap.inverse().get("mapred")); assertEquals("mapred2", gMap.get(498)); assertEquals(498, (int)gMap.inverse().get("mapred2")); }
Example #29
Source File: ShellBasedIdMapping.java From hadoop with Apache License 2.0 | 5 votes |
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 #30
Source File: ManagementServiceImpl.java From usergrid with Apache License 2.0 | 5 votes |
@Override public BiMap<UUID, String> getApplicationsForOrganizations( Set<UUID> organizationIds ) throws Exception { if ( organizationIds == null ) { return null; } BiMap<UUID, String> applications = HashBiMap.create(); for ( UUID organizationId : organizationIds ) { BiMap<UUID, String> organizationApplications = getApplicationsForOrganization( organizationId ); applications.putAll( organizationApplications ); } return applications; }