HashIdGenerator { public String getId(String name) { if (name.length() <= maxHashLength && usedIds.add(name)) { return name; } final String hexString = Integer.toHexString(name.hashCode()); final String origId = hexString.length() <= maxHashLength ? hexString : hexString.substring(Math.max(0, hexString.length() - maxHashLength)); String id = origId; int suffixNum = 2; while (!usedIds.add(id)) { id = origId + "-" + suffixNum++; } LOG.info("Name {} is mapped to id {}", name, id); return id; } HashIdGenerator(int maxHashLength);  HashIdGenerator(); String getId(String name);  }
@Test public void testGetId() { final HashIdGenerator idGenerator = new HashIdGenerator(); final Set<String> ids = ImmutableSet.of( idGenerator.getId(Count.perKey().getName()), idGenerator.getId(MapElements.into(null).getName()), idGenerator.getId(Count.globally().getName()), idGenerator.getId(Combine.perKey(mock(SerializableFunction.class)).getName()), idGenerator.getId(Min.perKey().getName()), idGenerator.getId(Max.globally().getName())); Assert.assertEquals(6, ids.size()); }
@Test public void testGetShortId() { final HashIdGenerator idGenerator = new HashIdGenerator(); String id = idGenerator.getId("abcd"); Assert.assertEquals("abcd", id); }
@Test public void testSameNames() { final HashIdGenerator idGenerator = new HashIdGenerator(); String id1 = idGenerator.getId(Count.perKey().getName()); String id2 = idGenerator.getId(Count.perKey().getName()); Assert.assertNotEquals(id1, id2); }
@Test public void testSameShortNames() { final HashIdGenerator idGenerator = new HashIdGenerator(); String id = idGenerator.getId("abcd"); Assert.assertEquals("abcd", id); String id2 = idGenerator.getId("abcd"); Assert.assertNotEquals("abcd", id2); }
@Test public void testLongHash() { final HashIdGenerator idGenerator = new HashIdGenerator(10); String id1 = idGenerator.getId(Count.perKey().getName()); String id2 = idGenerator.getId(Count.perKey().getName()); String id3 = idGenerator.getId(Count.perKey().getName()); String id4 = idGenerator.getId(Count.perKey().getName()); Assert.assertNotEquals(id1, id2); Assert.assertNotEquals(id3, id2); Assert.assertNotEquals(id3, id4); }