下面列出了怎么用com.google.common.collect.HashBiMap的API类实例代码及写法,或者点击链接到github查看源代码。
@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());
}
@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"));
}
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;
}
}
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;
}
@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;
}
/** 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;
}
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;
}
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;
}
@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);
}
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);
}
@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);
}
@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);
}
@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);
}
}
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);
}
@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;
}
@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"));
}
/**
* 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);
});
}
}
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;
}
/**
* 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();
}
}
@Override
public Result apply(FilterNode node, Captures captures, Context context)
{
Set<DereferenceExpression> dereferences = extractDereferences(ImmutableList.of(node.getPredicate()), true);
if (dereferences.isEmpty()) {
return Result.empty();
}
Assignments assignments = Assignments.of(dereferences, context.getSession(), context.getSymbolAllocator(), typeAnalyzer);
Map<Expression, SymbolReference> mappings = HashBiMap.create(assignments.getMap())
.inverse()
.entrySet().stream()
.collect(toImmutableMap(Map.Entry::getKey, entry -> entry.getValue().toSymbolReference()));
PlanNode source = node.getSource();
return Result.ofPlanNode(new ProjectNode(
context.getIdAllocator().getNextId(),
new FilterNode(
context.getIdAllocator().getNextId(),
new ProjectNode(
context.getIdAllocator().getNextId(),
source,
Assignments.builder()
.putIdentities(source.getOutputSymbols())
.putAll(assignments)
.build()),
replaceExpression(node.getPredicate(), mappings)),
Assignments.identity(node.getOutputSymbols())));
}
@Test(timeout = 5000)
public void testParseAllPluginsNoneSpecified() throws IOException {
Configuration conf = new Configuration(false);
conf.set(TEST_KEY, TEST_VAL);
UserPayload defaultPayload = TezUtils.createUserPayloadFromConf(conf);
List<NamedEntityDescriptor> tsDescriptors;
BiMap<String, Integer> tsMap;
List<NamedEntityDescriptor> clDescriptors;
BiMap<String, Integer> clMap;
List<NamedEntityDescriptor> tcDescriptors;
BiMap<String, Integer> tcMap;
// No plugins. Non local
tsDescriptors = Lists.newLinkedList();
tsMap = HashBiMap.create();
clDescriptors = Lists.newLinkedList();
clMap = HashBiMap.create();
tcDescriptors = Lists.newLinkedList();
tcMap = HashBiMap.create();
DAGAppMaster.parseAllPlugins(tsDescriptors, tsMap, clDescriptors, clMap, tcDescriptors, tcMap,
null, false, defaultPayload);
verifyDescAndMap(tsDescriptors, tsMap, 1, true, TezConstants.getTezYarnServicePluginName());
verifyDescAndMap(clDescriptors, clMap, 1, true, TezConstants.getTezYarnServicePluginName());
verifyDescAndMap(tcDescriptors, tcMap, 1, true, TezConstants.getTezYarnServicePluginName());
// No plugins. Local
tsDescriptors = Lists.newLinkedList();
tsMap = HashBiMap.create();
clDescriptors = Lists.newLinkedList();
clMap = HashBiMap.create();
tcDescriptors = Lists.newLinkedList();
tcMap = HashBiMap.create();
DAGAppMaster.parseAllPlugins(tsDescriptors, tsMap, clDescriptors, clMap, tcDescriptors, tcMap,
null, true, defaultPayload);
verifyDescAndMap(tsDescriptors, tsMap, 1, true, TezConstants.getTezUberServicePluginName());
verifyDescAndMap(clDescriptors, clMap, 1, true, TezConstants.getTezUberServicePluginName());
verifyDescAndMap(tcDescriptors, tcMap, 1, true, TezConstants.getTezUberServicePluginName());
}
@Override
public Result apply(ProjectNode projectNode, Captures captures, Context context)
{
AssignUniqueId assignUniqueId = captures.get(CHILD);
// Extract dereferences from project node assignments for pushdown
Set<DereferenceExpression> dereferences = extractDereferences(projectNode.getAssignments().getExpressions(), false);
// We do not need to filter dereferences on idColumn symbol since it is supposed to be of BIGINT type.
if (dereferences.isEmpty()) {
return Result.empty();
}
// Create new symbols for dereference expressions
Assignments dereferenceAssignments = Assignments.of(dereferences, context.getSession(), context.getSymbolAllocator(), typeAnalyzer);
// Rewrite project node assignments using new symbols for dereference expressions
Map<Expression, SymbolReference> mappings = HashBiMap.create(dereferenceAssignments.getMap())
.inverse()
.entrySet().stream()
.collect(toImmutableMap(Map.Entry::getKey, entry -> entry.getValue().toSymbolReference()));
Assignments newAssignments = projectNode.getAssignments().rewrite(expression -> replaceExpression(expression, mappings));
return Result.ofPlanNode(
new ProjectNode(
context.getIdAllocator().getNextId(),
assignUniqueId.replaceChildren(ImmutableList.of(
new ProjectNode(
context.getIdAllocator().getNextId(),
assignUniqueId.getSource(),
Assignments.builder()
.putIdentities(assignUniqueId.getSource().getOutputSymbols())
.putAll(dereferenceAssignments)
.build()))),
newAssignments));
}
public static void main(String[] args) {
String[] englishWords = {"one", "two", "three","ball","snow"};
String[] russianWords = {"jeden", "dwa", "trzy", "kula", "snieg"};
// Create Multiset
BiMap<String, String> biMap = HashBiMap.create(englishWords.length);
// Create English-Polish dictionary
int i = 0;
for(String englishWord: englishWords) {
biMap.put(englishWord, russianWords[i]);
i++;
}
// Print count words
System.out.println(biMap); // print {two=dwa, three=trzy, snow=snieg, ball=kula, one=jeden} - in random orders
// Print all unique words
System.out.println(biMap.keySet()); // print [two, three, snow, ball, one] - in random orders
System.out.println(biMap.values()); // print [dwa, trzy, snieg, kula, jeden]- in random orders
// Print translate by words
System.out.println("one = " + biMap.get("one")); // print one = jeden
System.out.println("two = " + biMap.get("two")); // print two = dwa
System.out.println("kula = " + biMap.inverse().get("kula")); // print kula = ball
System.out.println("snieg = " + biMap.inverse().get("snieg")); // print snieg = snow
System.out.println("empty = " + biMap.get("empty")); // print empty = null
// Print count word's pair
System.out.println(biMap.size()); //print 5
}
@Override
public Result apply(ProjectNode projectNode, Captures captures, Context context)
{
SortNode sortNode = captures.get(CHILD);
// Extract dereferences from project node assignments for pushdown
Set<DereferenceExpression> dereferences = extractDereferences(projectNode.getAssignments().getExpressions(), false);
// Exclude dereferences on symbols used in ordering scheme to avoid replication of data
dereferences = dereferences.stream()
.filter(expression -> !sortNode.getOrderingScheme().getOrderBy().contains(getBase(expression)))
.collect(toImmutableSet());
if (dereferences.isEmpty()) {
return Result.empty();
}
// Create new symbols for dereference expressions
Assignments dereferenceAssignments = Assignments.of(dereferences, context.getSession(), context.getSymbolAllocator(), typeAnalyzer);
// Rewrite project node assignments using new symbols for dereference expressions
Map<Expression, SymbolReference> mappings = HashBiMap.create(dereferenceAssignments.getMap())
.inverse()
.entrySet().stream()
.collect(toImmutableMap(Map.Entry::getKey, entry -> entry.getValue().toSymbolReference()));
Assignments newAssignments = projectNode.getAssignments().rewrite(expression -> replaceExpression(expression, mappings));
return Result.ofPlanNode(
new ProjectNode(
context.getIdAllocator().getNextId(),
sortNode.replaceChildren(ImmutableList.of(
new ProjectNode(
context.getIdAllocator().getNextId(),
sortNode.getSource(),
Assignments.builder()
.putIdentities(sortNode.getSource().getOutputSymbols())
.putAll(dereferenceAssignments)
.build()))),
newAssignments));
}
@Override
public Result apply(ProjectNode projectNode, Captures captures, Context context)
{
RowNumberNode rowNumberNode = captures.get(CHILD);
// Extract dereferences from project node assignments for pushdown
Set<DereferenceExpression> dereferences = extractDereferences(projectNode.getAssignments().getExpressions(), false);
// Exclude dereferences on symbols being used in partitionBy
dereferences = dereferences.stream()
.filter(expression -> !rowNumberNode.getPartitionBy().contains(getBase(expression)))
.collect(toImmutableSet());
if (dereferences.isEmpty()) {
return Result.empty();
}
// Create new symbols for dereference expressions
Assignments dereferenceAssignments = Assignments.of(dereferences, context.getSession(), context.getSymbolAllocator(), typeAnalyzer);
// Rewrite project node assignments using new symbols for dereference expressions
Map<Expression, SymbolReference> mappings = HashBiMap.create(dereferenceAssignments.getMap())
.inverse()
.entrySet().stream()
.collect(toImmutableMap(Map.Entry::getKey, entry -> entry.getValue().toSymbolReference()));
Assignments newAssignments = projectNode.getAssignments().rewrite(expression -> replaceExpression(expression, mappings));
return Result.ofPlanNode(
new ProjectNode(
context.getIdAllocator().getNextId(),
rowNumberNode.replaceChildren(ImmutableList.of(
new ProjectNode(
context.getIdAllocator().getNextId(),
rowNumberNode.getSource(),
Assignments.builder()
.putIdentities(rowNumberNode.getSource().getOutputSymbols())
.putAll(dereferenceAssignments)
.build()))),
newAssignments));
}
@SuppressWarnings("unchecked")
@Unique
private static <T> TagRegistry<T> setExtraTags(TagContainer<T> container, Consumer<TagRegistry<T>> tagsAdder) {
TagContainerAccessor<T> accessor = (TagContainerAccessor<T>) container;
TagRegistry<T> tags = new TagRegistry<>();
container.getEntries().forEach((id, tag) -> tags.put(id, new HashSet<>(tag.values())));
tagsAdder.accept(tags);
BiMap<Identifier, Tag<T>> tagBiMap = HashBiMap.create(tags.size());
tags.forEach((id, set) -> tagBiMap.put(id, Tag.of(set)));
accessor.multiconnect_setEntries(tagBiMap);
return tags;
}
@Test
public void shouldFailOnUnknownBitArgument() throws Exception {
final Set<String> setOfBits = ImmutableSet.of("UP", "PROMISCUOUS");
final SchemaContext schemaContext = YangParserTestUtils.parseYangResources(BitIsSetXPathFunctionTest.class,
"/yang-xpath-functions-test/bit-is-set-function/foo.yang");
assertNotNull(schemaContext);
final XPathSchemaContext jaxenSchemaContext = SCHEMA_CONTEXT_FACTORY.createContext(schemaContext);
final XPathDocument jaxenDocument = jaxenSchemaContext.createDocument(buildMyContainerNode(setOfBits));
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(
buildPathToFlagsLeafNode(setOfBits));
final Function bitIsSetFunction = normalizedNodeContextSupport.getFunctionContext()
.getFunction(null, null, "bit-is-set");
try {
bitIsSetFunction.call(normalizedNodeContext, ImmutableList.of("UNKNOWN"));
fail("Function call should have failed on unknown bit-name argument");
} catch (final IllegalStateException ex) {
assertTrue(ex.getMessage().startsWith("Bit UNKNOWN does not belong to bits"));
}
}
@Test
public void testPutAll_nullKey() {
thrown.expect(NullPointerException.class);
behaviorTester
.with(biMapPropertyType)
.with(testBuilder()
.addLine("%1$s<%2$s, %3$s> items = %4$s.create();",
BiMap.class, keys.type(), values.type(), HashBiMap.class)
.addLine("items.put(%s, %s);", keys.example(0), values.example(0))
.addLine("items.put((%s) null, %s);", keys.type(), values.example(1))
.addLine("new DataType.Builder().putAllItems(items);")
.build())
.runTest();
}
public AddOnManager(HeavySpleef heavySpleef) {
this.addOnMap = HashBiMap.create();
this.classContext = new SharedClassContext();
this.heavySpleef = heavySpleef;
this.logger = heavySpleef.getLogger();
this.flagRegistryAccess = new FlagRegistryAccess(heavySpleef.getFlagRegistry());
this.extensionRegistryAccess = new ExtensionRegistryAccess(heavySpleef.getExtensionRegistry());
this.commandManagerAccess = new CommandManagerAccess(heavySpleef.getCommandManager());
}
@Test
public void shouldFailOnUnknownEnumNodeValue() 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("unknown"));
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("unknown"));
final Function enumValueFunction = normalizedNodeContextSupport.getFunctionContext()
.getFunction(null, null, "enum-value");
try {
enumValueFunction.call(normalizedNodeContext, ImmutableList.of());
fail("Function call should have failed on unknown enum node value");
} catch (final IllegalStateException ex) {
assertTrue(ex.getMessage().startsWith("Enum unknown does not belong to enumeration"));
}
}