use of org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack in project controller by opendaylight.
the class DataStoreAppConfigDefaultXMLReader method createDefaultInstance.
@SuppressWarnings("unchecked")
public T createDefaultInstance(final FallbackConfigProvider fallback) throws ConfigXMLReaderException, URISyntaxException, ParserConfigurationException, XMLStreamException, SAXException, IOException {
YangInstanceIdentifier yangPath = bindingSerializer.toYangInstanceIdentifier(bindingContext.appConfigPath);
LOG.debug("{}: Creating app config instance from path {}, Qname: {}", logName, yangPath, bindingContext.bindingQName);
checkNotNull(schemaService, "%s: Could not obtain the SchemaService OSGi service", logName);
EffectiveModelContext schemaContext = schemaService.getGlobalContext();
Module module = schemaContext.findModule(bindingContext.bindingQName.getModule()).orElse(null);
checkNotNull(module, "%s: Could not obtain the module schema for namespace %s, revision %s", logName, bindingContext.bindingQName.getNamespace(), bindingContext.bindingQName.getRevision());
final SchemaInferenceStack schemaStack = SchemaInferenceStack.of(schemaContext);
final SchemaTreeEffectiveStatement<?> dataSchema;
try {
dataSchema = schemaStack.enterSchemaTree(bindingContext.bindingQName);
} catch (IllegalArgumentException e) {
throw new ConfigXMLReaderException(logName + ": Could not obtain the schema for " + bindingContext.bindingQName, e);
}
checkCondition(bindingContext.schemaType.isInstance(dataSchema), "%s: Expected schema type %s for %s but actual type is %s", logName, bindingContext.schemaType, bindingContext.bindingQName, dataSchema.getClass());
NormalizedNode dataNode = parsePossibleDefaultAppConfigXMLFile(schemaStack);
if (dataNode == null) {
dataNode = fallback.get(schemaStack.toSchemaTreeInference());
}
DataObject appConfig = bindingSerializer.fromNormalizedNode(yangPath, dataNode).getValue();
// This shouldn't happen but need to handle it in case...
checkNotNull(appConfig, "%s: Could not create instance for app config binding %s", logName, bindingContext.appConfigBindingClass);
return (T) appConfig;
}
use of org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack in project yangtools by opendaylight.
the class XmlStreamUtilsTest method getTargetNodeForLeafRef.
private static TypeDefinition<?> getTargetNodeForLeafRef(final Class<?> clas, final String... names) {
final SchemaInferenceStack stack = SchemaInferenceStack.of(schemaContext);
stack.enterDataTree(QName.create(leafRefModule.getQNameModule(), "cont2"));
for (String name : names) {
stack.enterDataTree(QName.create(leafRefModule.getQNameModule(), name));
}
final EffectiveStatement<?, ?> leaf = stack.currentStatement();
assertThat(leaf, instanceOf(LeafSchemaNode.class));
final TypeDefinition<? extends TypeDefinition<?>> type = ((TypedDataSchemaNode) leaf).getType();
assertThat(type, instanceOf(LeafrefTypeDefinition.class));
final TypeDefinition<?> resolved = stack.resolveLeafref((LeafrefTypeDefinition) type);
assertThat(resolved, instanceOf(clas));
return resolved;
}
use of org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack in project yangtools by opendaylight.
the class StreamWriterFacade method emitNormalizedAnydata.
void emitNormalizedAnydata(final NormalizedAnydata anydata) throws XMLStreamException {
flushElement();
// Adjust state to point to parent node and ensure it can handle data tree nodes
final SchemaInferenceStack.Inference inference;
try {
final SchemaInferenceStack stack = SchemaInferenceStack.ofInference(anydata.getInference());
stack.exitToDataTree();
inference = stack.toInference();
} catch (IllegalArgumentException | IllegalStateException | NoSuchElementException e) {
throw new XMLStreamException("Cannot emit " + anydata, e);
}
try {
anydata.writeTo(XMLStreamNormalizedNodeStreamWriter.create(writer, inference));
} catch (IOException e) {
throw new XMLStreamException("Failed to emit anydata " + anydata, e);
}
}
use of org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack in project netconf by opendaylight.
the class XmlToPatchBodyReader method parse.
private static PatchContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc) throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
final List<PatchEntity> resultCollection = new ArrayList<>();
final String patchId = doc.getElementsByTagName("patch-id").item(0).getFirstChild().getNodeValue();
final NodeList editNodes = doc.getElementsByTagName("edit");
for (int i = 0; i < editNodes.getLength(); i++) {
DataSchemaNode schemaNode = (DataSchemaNode) pathContext.getSchemaNode();
final Element element = (Element) editNodes.item(i);
final String operation = element.getElementsByTagName("operation").item(0).getFirstChild().getNodeValue();
final PatchEditOperation oper = PatchEditOperation.valueOf(operation.toUpperCase(Locale.ROOT));
final String editId = element.getElementsByTagName("edit-id").item(0).getFirstChild().getNodeValue();
final String target = element.getElementsByTagName("target").item(0).getFirstChild().getNodeValue();
final List<Element> values = readValueNodes(element, oper);
final Element firstValueElement = values != null ? values.get(0) : null;
// get namespace according to schema node from path context or value
final String namespace = firstValueElement == null ? schemaNode.getQName().getNamespace().toString() : firstValueElement.getNamespaceURI();
// find module according to namespace
final Module module = pathContext.getSchemaContext().findModules(XMLNamespace.of(namespace)).iterator().next();
// initialize codec + set default prefix derived from module name
final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(pathContext.getSchemaContext(), module.getName());
// find complete path to target and target schema node
// target can be also empty (only slash)
YangInstanceIdentifier targetII;
final SchemaNode targetNode;
final Inference inference;
if (target.equals("/")) {
targetII = pathContext.getInstanceIdentifier();
targetNode = pathContext.getSchemaContext();
inference = Inference.ofDataTreePath(pathContext.getSchemaContext(), schemaNode.getQName());
} else {
targetII = codec.deserialize(codec.serialize(pathContext.getInstanceIdentifier()).concat(prepareNonCondXpath(schemaNode, target.replaceFirst("/", ""), firstValueElement, namespace, module.getQNameModule().getRevision().map(Revision::toString).orElse(null))));
// move schema node
schemaNode = verifyNotNull(codec.getDataContextTree().findChild(targetII).orElseThrow().getDataSchemaNode());
final SchemaInferenceStack stack = SchemaInferenceStack.of(pathContext.getSchemaContext());
targetII.getPathArguments().stream().filter(arg -> !(arg instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates)).filter(arg -> !(arg instanceof YangInstanceIdentifier.AugmentationIdentifier)).forEach(p -> stack.enterSchemaTree(p.getNodeType()));
final EffectiveStatement<?, ?> parentStmt = stack.exit();
verify(parentStmt instanceof SchemaNode, "Unexpected parent %s", parentStmt);
targetNode = (SchemaNode) parentStmt;
inference = stack.toInference();
}
if (targetNode == null) {
LOG.debug("Target node {} not found in path {} ", target, pathContext.getSchemaNode());
throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
}
if (oper.isWithValue()) {
final NormalizedNode parsed;
if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
final XmlParserStream xmlParser = XmlParserStream.create(writer, inference);
xmlParser.traverse(new DOMSource(firstValueElement));
parsed = resultHolder.getResult();
} else {
parsed = null;
}
// for lists allow to manipulate with list items through their parent
if (targetII.getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
targetII = targetII.getParent();
}
resultCollection.add(new PatchEntity(editId, oper, targetII, parsed));
} else {
resultCollection.add(new PatchEntity(editId, oper, targetII));
}
}
return new PatchContext(pathContext, ImmutableList.copyOf(resultCollection), patchId);
}
use of org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack in project netconf by opendaylight.
the class JsonNormalizedNodeBodyReader method readFrom.
private static NormalizedNodeContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream, final boolean isPost) throws IOException {
final Optional<InputStream> nonEmptyInputStreamOptional = RestUtil.isInputStreamEmpty(entityStream);
if (nonEmptyInputStreamOptional.isEmpty()) {
return new NormalizedNodeContext(path, null);
}
final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
final SchemaInferenceStack stack;
if (path.getSchemaNode() instanceof RpcEffectiveStatement) {
stack = SchemaInferenceStack.of(path.getSchemaContext(), Absolute.of(path.getSchemaNode().getQName()));
} else {
stack = SchemaInferenceStack.of(path.getSchemaContext());
path.getInstanceIdentifier().getPathArguments().stream().filter(arg -> !(arg instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates)).filter(arg -> !(arg instanceof YangInstanceIdentifier.AugmentationIdentifier)).forEach(p -> stack.enterSchemaTree(p.getNodeType()));
}
if (!isPost) {
stack.exit();
}
final JsonParserStream jsonParser = JsonParserStream.create(writer, JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(path.getSchemaContext()), stack.toInference());
final JsonReader reader = new JsonReader(new InputStreamReader(nonEmptyInputStreamOptional.get(), StandardCharsets.UTF_8));
jsonParser.parse(reader);
NormalizedNode result = resultHolder.getResult();
final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
InstanceIdentifierContext<? extends SchemaNode> newIIContext;
while (result instanceof AugmentationNode || result instanceof ChoiceNode) {
final Object childNode = ((DataContainerNode) result).body().iterator().next();
if (isPost) {
iiToDataList.add(result.getIdentifier());
}
result = (NormalizedNode) childNode;
}
if (isPost) {
if (result instanceof MapEntryNode) {
iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(result.getIdentifier().getNodeType()));
iiToDataList.add(result.getIdentifier());
} else {
iiToDataList.add(result.getIdentifier());
}
} else {
if (result instanceof MapNode) {
result = Iterables.getOnlyElement(((MapNode) result).body());
}
}
final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(path.getInstanceIdentifier().getPathArguments(), iiToDataList));
newIIContext = new InstanceIdentifierContext<>(fullIIToData, path.getSchemaNode(), path.getMountPoint(), path.getSchemaContext());
return new NormalizedNodeContext(newIIContext, result);
}
Aggregations