Search in sources :

Example 26 with InstanceIdentifierContext

use of org.opendaylight.restconf.common.context.InstanceIdentifierContext in project netconf by opendaylight.

the class RestconfDocumentedExceptionMapper method toXMLResponseBody.

private static Object toXMLResponseBody(final NormalizedNodeContext errorsNode, final DataNodeContainer errorsSchemaNode) {
    final InstanceIdentifierContext<?> pathContext = errorsNode.getInstanceIdentifierContext();
    final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    final XMLStreamWriter xmlWriter;
    try {
        xmlWriter = XML_FACTORY.createXMLStreamWriter(outStream, StandardCharsets.UTF_8.name());
    } catch (final XMLStreamException | FactoryConfigurationError e) {
        throw new IllegalStateException(e);
    }
    NormalizedNode data = errorsNode.getData();
    SchemaPath schemaPath;
    boolean isDataRoot = false;
    if (pathContext.getSchemaNode() instanceof SchemaContext) {
        isDataRoot = true;
        schemaPath = SchemaPath.ROOT;
    } else {
        final List<QName> qNames = pathContext.getInstanceIdentifier().getPathArguments().stream().filter(arg -> !(arg instanceof NodeIdentifierWithPredicates)).filter(arg -> !(arg instanceof AugmentationIdentifier)).map(PathArgument::getNodeType).collect(Collectors.toList());
        schemaPath = SchemaPath.of(Absolute.of(qNames)).getParent();
    }
    final NormalizedNodeStreamWriter xmlStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter, pathContext.getSchemaContext(), schemaPath);
    // We create a delegating writer to special-case error-info as error-info is defined as an empty
    // container in the restconf yang schema but we create a leaf node so we can output it. The delegate
    // stream writer validates the node type against the schema and thus will expect a LeafSchemaNode but
    // the schema has a ContainerSchemaNode so, to avoid an error, we override the leafNode behavior
    // for error-info.
    final NormalizedNodeStreamWriter streamWriter = new ForwardingNormalizedNodeStreamWriter() {

        private boolean inOurLeaf;

        @Override
        protected NormalizedNodeStreamWriter delegate() {
            return xmlStreamWriter;
        }

        @Override
        public void startLeafNode(final NodeIdentifier name) throws IOException {
            if (name.getNodeType().equals(RestConfModule.ERROR_INFO_QNAME)) {
                String ns = RestConfModule.ERROR_INFO_QNAME.getNamespace().toString();
                try {
                    xmlWriter.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, RestConfModule.ERROR_INFO_QNAME.getLocalName(), ns);
                } catch (XMLStreamException e) {
                    throw new IOException("Error writing error-info", e);
                }
                inOurLeaf = true;
            } else {
                super.startLeafNode(name);
            }
        }

        @Override
        public void scalarValue(final Object value) throws IOException {
            if (inOurLeaf) {
                try {
                    xmlWriter.writeCharacters(value.toString());
                } catch (XMLStreamException e) {
                    throw new IOException("Error writing error-info", e);
                }
            } else {
                super.scalarValue(value);
            }
        }

        @Override
        public void endNode() throws IOException {
            if (inOurLeaf) {
                try {
                    xmlWriter.writeEndElement();
                } catch (XMLStreamException e) {
                    throw new IOException("Error writing error-info", e);
                }
                inOurLeaf = false;
            } else {
                super.endNode();
            }
        }
    };
    final NormalizedNodeWriter nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter);
    try {
        if (isDataRoot) {
            writeRootElement(xmlWriter, nnWriter, (ContainerNode) data);
        } else {
            if (data instanceof MapEntryNode) {
                // Restconf allows returning one list item. We need to wrap it
                // in map node in order to serialize it properly
                data = ImmutableNodes.mapNodeBuilder(data.getIdentifier().getNodeType()).addChild((MapEntryNode) data).build();
            }
            nnWriter.write(data);
            nnWriter.flush();
        }
    } catch (final IOException e) {
        LOG.warn("Error writing error response body.", e);
    }
    return outStream.toString(StandardCharsets.UTF_8);
}
Also used : JSONNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamWriter) JSONCodecFactorySupplier(org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier) Provider(javax.ws.rs.ext.Provider) NodeIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier) ForwardingNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.api.schema.stream.ForwardingNormalizedNodeStreamWriter) SchemaContext(org.opendaylight.yangtools.yang.model.api.SchemaContext) ExceptionMapper(javax.ws.rs.ext.ExceptionMapper) LoggerFactory(org.slf4j.LoggerFactory) XMLNamespace(org.opendaylight.yangtools.yang.common.XMLNamespace) Absolute(org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) ERRORS_CONTAINER_QNAME(org.opendaylight.netconf.sal.rest.api.Draft02.RestConfModule.ERRORS_CONTAINER_QNAME) MediaType(javax.ws.rs.core.MediaType) NormalizedNodeWriter(org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter) XMLStreamException(javax.xml.stream.XMLStreamException) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) ContainerNode(org.opendaylight.yangtools.yang.data.api.schema.ContainerNode) CollectionNodeBuilder(org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder) Context(javax.ws.rs.core.Context) ListSchemaNode(org.opendaylight.yangtools.yang.model.api.ListSchemaNode) ContainerSchemaNode(org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode) DataContainerChild(org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Preconditions.checkState(com.google.common.base.Preconditions.checkState) ErrorTags(org.opendaylight.restconf.common.ErrorTags) XMLStreamNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Response(javax.ws.rs.core.Response) PathArgument(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument) ImmutableNodes(org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes) MapEntryNode(org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode) Iterables(com.google.common.collect.Iterables) SchemaPath(org.opendaylight.yangtools.yang.model.api.SchemaPath) ByteArrayOutputStream(java.io.ByteArrayOutputStream) InstanceIdentifierContext(org.opendaylight.restconf.common.context.InstanceIdentifierContext) ArrayList(java.util.ArrayList) RestConfModule(org.opendaylight.netconf.sal.rest.api.Draft02.RestConfModule) JsonWriterFactory(org.opendaylight.yangtools.yang.data.codec.gson.JsonWriterFactory) Objects.requireNonNull(java.util.Objects.requireNonNull) OutputStreamWriter(java.io.OutputStreamWriter) SystemMapNode(org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode) XMLConstants(javax.xml.XMLConstants) JsonWriter(com.google.gson.stream.JsonWriter) Status(javax.ws.rs.core.Response.Status) SchemaAwareBuilders(org.opendaylight.yangtools.yang.data.impl.schema.SchemaAwareBuilders) Logger(org.slf4j.Logger) DataContainerNodeBuilder(org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder) IOException(java.io.IOException) NodeIdentifierWithPredicates(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates) RestconfError(org.opendaylight.restconf.common.errors.RestconfError) QName(org.opendaylight.yangtools.yang.common.QName) FactoryConfigurationError(javax.xml.stream.FactoryConfigurationError) XMLOutputFactory(javax.xml.stream.XMLOutputFactory) DataNodeContainer(org.opendaylight.yangtools.yang.model.api.DataNodeContainer) NormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter) DataSchemaNode(org.opendaylight.yangtools.yang.model.api.DataSchemaNode) ControllerContext(org.opendaylight.netconf.sal.restconf.impl.ControllerContext) RestconfDocumentedException(org.opendaylight.restconf.common.errors.RestconfDocumentedException) AugmentationIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier) NormalizedNode(org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode) LeafSchemaNode(org.opendaylight.yangtools.yang.model.api.LeafSchemaNode) AugmentationIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier) NormalizedNodeWriter(org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter) QName(org.opendaylight.yangtools.yang.common.QName) JSONNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamWriter) ForwardingNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.api.schema.stream.ForwardingNormalizedNodeStreamWriter) XMLStreamNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter) NormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) NodeIdentifierWithPredicates(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates) MapEntryNode(org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode) XMLStreamException(javax.xml.stream.XMLStreamException) SchemaPath(org.opendaylight.yangtools.yang.model.api.SchemaPath) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) NodeIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier) ForwardingNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.api.schema.stream.ForwardingNormalizedNodeStreamWriter) SchemaContext(org.opendaylight.yangtools.yang.model.api.SchemaContext) NormalizedNode(org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode) FactoryConfigurationError(javax.xml.stream.FactoryConfigurationError)

Example 27 with InstanceIdentifierContext

use of org.opendaylight.restconf.common.context.InstanceIdentifierContext in project netconf by opendaylight.

the class JsonToPatchBodyReader method readEditDefinition.

/**
 * Read one patch edit object from Json input.
 * @param edit PatchEdit instance to be filled with read data
 * @param in JsonReader reader
 * @param path InstanceIdentifierContext path context
 * @param codec StringModuleInstanceIdentifierCodec codec
 * @throws IOException if operation fails
 */
private void readEditDefinition(@NonNull final PatchEdit edit, @NonNull final JsonReader in, @NonNull final InstanceIdentifierContext<?> path, @NonNull final StringModuleInstanceIdentifierCodec codec) throws IOException {
    final StringBuilder value = new StringBuilder();
    in.beginObject();
    while (in.hasNext()) {
        final String editDefinition = in.nextName();
        switch(editDefinition) {
            case "edit-id":
                edit.setId(in.nextString());
                break;
            case "operation":
                edit.setOperation(PatchEditOperation.valueOf(in.nextString().toUpperCase(Locale.ROOT)));
                break;
            case "target":
                // target can be specified completely in request URI
                final String target = in.nextString();
                final SchemaInferenceStack stack = SchemaInferenceStack.of(path.getSchemaContext());
                if (target.equals("/")) {
                    edit.setTarget(path.getInstanceIdentifier());
                    edit.setTargetInference(stack.toInference());
                } else {
                    edit.setTarget(codec.deserialize(codec.serialize(path.getInstanceIdentifier()).concat(target)));
                    edit.getTarget().getPathArguments().stream().filter(arg -> !(arg instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates)).filter(arg -> !(arg instanceof YangInstanceIdentifier.AugmentationIdentifier)).forEach(p -> stack.enterSchemaTree(p.getNodeType()));
                    stack.exit();
                    edit.setTargetInference(stack.toInference());
                }
                break;
            case "value":
                // save data defined in value node for next (later) processing, because target needs to be read
                // always first and there is no ordering in Json input
                readValueNode(value, in);
                break;
            default:
                break;
        }
    }
    in.endObject();
    // read saved data to normalized node when target schema is already known
    edit.setData(readEditData(new JsonReader(new StringReader(value.toString())), edit.getTargetInference(), path));
}
Also used : SchemaInferenceStack(org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack) JSONCodecFactorySupplier(org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier) Provider(javax.ws.rs.ext.Provider) ImmutableNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter) InstanceIdentifierContext(org.opendaylight.restconf.common.context.InstanceIdentifierContext) Draft02(org.opendaylight.netconf.sal.rest.api.Draft02) LoggerFactory(org.slf4j.LoggerFactory) AtomicReference(java.util.concurrent.atomic.AtomicReference) JsonReader(com.google.gson.stream.JsonReader) PatchEntity(org.opendaylight.restconf.common.patch.PatchEntity) ArrayList(java.util.ArrayList) ErrorType(org.opendaylight.yangtools.yang.common.ErrorType) MediaType(javax.ws.rs.core.MediaType) ResultAlreadySetException(org.opendaylight.yangtools.yang.data.impl.schema.ResultAlreadySetException) ImmutableList(com.google.common.collect.ImmutableList) Consumes(javax.ws.rs.Consumes) PatchContext(org.opendaylight.restconf.common.patch.PatchContext) NormalizedNodeResult(org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult) Locale(java.util.Locale) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier) RestconfService(org.opendaylight.netconf.sal.rest.api.RestconfService) RestUtil(org.opendaylight.restconf.common.util.RestUtil) Logger(org.slf4j.Logger) SchemaInferenceStack(org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack) ErrorTag(org.opendaylight.yangtools.yang.common.ErrorTag) Inference(org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference) Throwables(com.google.common.base.Throwables) IOException(java.io.IOException) NodeIdentifierWithPredicates(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates) EffectiveModelContext(org.opendaylight.yangtools.yang.model.api.EffectiveModelContext) InputStreamReader(java.io.InputStreamReader) StandardCharsets(java.nio.charset.StandardCharsets) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) JsonToken(com.google.gson.stream.JsonToken) List(java.util.List) StringReader(java.io.StringReader) Type(java.lang.reflect.Type) NormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter) ControllerContext(org.opendaylight.netconf.sal.restconf.impl.ControllerContext) JsonParserStream(org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream) Annotation(java.lang.annotation.Annotation) Optional(java.util.Optional) WebApplicationException(javax.ws.rs.WebApplicationException) NonNull(org.eclipse.jdt.annotation.NonNull) RestconfDocumentedException(org.opendaylight.restconf.common.errors.RestconfDocumentedException) NormalizedNode(org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode) InputStream(java.io.InputStream) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) PatchEditOperation(org.opendaylight.restconf.common.patch.PatchEditOperation) StringReader(java.io.StringReader) JsonReader(com.google.gson.stream.JsonReader) NodeIdentifierWithPredicates(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier)

Example 28 with InstanceIdentifierContext

use of org.opendaylight.restconf.common.context.InstanceIdentifierContext in project netconf by opendaylight.

the class NormalizedNodeJsonBodyWriter method writeNormalizedNode.

private static void writeNormalizedNode(final JsonWriter jsonWriter, final InstanceIdentifierContext<SchemaNode> context, NormalizedNode data, @Nullable final Integer depth) throws IOException {
    final RestconfNormalizedNodeWriter nnWriter;
    if (context.getSchemaNode() instanceof SchemaContext) {
        /*
             *  Creates writer without initialNs and we write children of root data container
             *  which is not visible in restconf
             */
        nnWriter = createNormalizedNodeWriter(context, SchemaPath.ROOT, jsonWriter, depth);
        if (data instanceof ContainerNode) {
            writeChildren(nnWriter, (ContainerNode) data);
        } else if (data instanceof DOMSourceAnyxmlNode) {
            try {
                writeChildren(nnWriter, (ContainerNode) NetconfUtil.transformDOMSourceToNormalizedNode(context.getSchemaContext(), ((DOMSourceAnyxmlNode) data).body()).getResult());
            } catch (XMLStreamException | URISyntaxException | SAXException e) {
                throw new IOException("Cannot write anyxml.", e);
            }
        }
    } else if (context.getSchemaNode() instanceof RpcDefinition) {
        /*
             *  RpcDefinition is not supported as initial codec in JSONStreamWriter,
             *  so we need to emit initial output declaratation..
             */
        final RpcDefinition rpc = (RpcDefinition) context.getSchemaNode();
        final SchemaPath path = SchemaPath.of(Absolute.of(rpc.getQName(), rpc.getOutput().getQName()));
        nnWriter = createNormalizedNodeWriter(context, path, jsonWriter, depth);
        jsonWriter.name("output");
        jsonWriter.beginObject();
        writeChildren(nnWriter, (ContainerNode) data);
        jsonWriter.endObject();
    } else {
        final List<QName> qnames = context.getInstanceIdentifier().getPathArguments().stream().filter(arg -> !(arg instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates)).filter(arg -> !(arg instanceof YangInstanceIdentifier.AugmentationIdentifier)).map(PathArgument::getNodeType).collect(Collectors.toList());
        final SchemaPath path = SchemaPath.of(Absolute.of(qnames)).getParent();
        if (data instanceof MapEntryNode) {
            data = ImmutableNodes.mapNodeBuilder(data.getIdentifier().getNodeType()).withChild((MapEntryNode) data).build();
        }
        nnWriter = createNormalizedNodeWriter(context, path, jsonWriter, depth);
        nnWriter.write(data);
    }
    nnWriter.flush();
}
Also used : JSONNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamWriter) JSONCodecFactorySupplier(org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier) SchemaPath(org.opendaylight.yangtools.yang.model.api.SchemaPath) Produces(javax.ws.rs.Produces) Provider(javax.ws.rs.ext.Provider) SchemaContext(org.opendaylight.yangtools.yang.model.api.SchemaContext) URISyntaxException(java.net.URISyntaxException) InstanceIdentifierContext(org.opendaylight.restconf.common.context.InstanceIdentifierContext) RpcDefinition(org.opendaylight.yangtools.yang.model.api.RpcDefinition) Draft02(org.opendaylight.netconf.sal.rest.api.Draft02) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) NetconfUtil(org.opendaylight.netconf.util.NetconfUtil) XMLNamespace(org.opendaylight.yangtools.yang.common.XMLNamespace) JsonWriterFactory(org.opendaylight.yangtools.yang.data.codec.gson.JsonWriterFactory) Absolute(org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute) MediaType(javax.ws.rs.core.MediaType) Nullable(org.eclipse.jdt.annotation.Nullable) XMLStreamException(javax.xml.stream.XMLStreamException) OutputStreamWriter(java.io.OutputStreamWriter) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier) RestconfService(org.opendaylight.netconf.sal.rest.api.RestconfService) JsonWriter(com.google.gson.stream.JsonWriter) ContainerNode(org.opendaylight.yangtools.yang.data.api.schema.ContainerNode) OutputStream(java.io.OutputStream) RestconfNormalizedNodeWriter(org.opendaylight.netconf.sal.rest.api.RestconfNormalizedNodeWriter) IOException(java.io.IOException) DataContainerChild(org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) QName(org.opendaylight.yangtools.yang.common.QName) DOMSourceAnyxmlNode(org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode) SchemaNode(org.opendaylight.yangtools.yang.model.api.SchemaNode) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) List(java.util.List) PathArgument(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument) Type(java.lang.reflect.Type) NormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter) ImmutableNodes(org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes) DataSchemaNode(org.opendaylight.yangtools.yang.model.api.DataSchemaNode) SAXException(org.xml.sax.SAXException) Annotation(java.lang.annotation.Annotation) Entry(java.util.Map.Entry) JSONCodecFactory(org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactory) WebApplicationException(javax.ws.rs.WebApplicationException) MapEntryNode(org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode) NormalizedNode(org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode) RestconfNormalizedNodeWriter(org.opendaylight.netconf.sal.rest.api.RestconfNormalizedNodeWriter) DOMSourceAnyxmlNode(org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode) RpcDefinition(org.opendaylight.yangtools.yang.model.api.RpcDefinition) IOException(java.io.IOException) MapEntryNode(org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier) SchemaPath(org.opendaylight.yangtools.yang.model.api.SchemaPath) ContainerNode(org.opendaylight.yangtools.yang.data.api.schema.ContainerNode) List(java.util.List) SchemaContext(org.opendaylight.yangtools.yang.model.api.SchemaContext) PathArgument(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument)

Example 29 with InstanceIdentifierContext

use of org.opendaylight.restconf.common.context.InstanceIdentifierContext in project netconf by opendaylight.

the class RestconfDataServiceImpl method invokeAction.

/**
 * Invoke Action operation.
 *
 * @param payload {@link NormalizedNodePayload} - the body of the operation
 * @return {@link NormalizedNodePayload} wrapped in {@link Response}
 */
public Response invokeAction(final NormalizedNodePayload payload) {
    final InstanceIdentifierContext<?> context = payload.getInstanceIdentifierContext();
    final DOMMountPoint mountPoint = context.getMountPoint();
    final YangInstanceIdentifier yangIIdContext = context.getInstanceIdentifier();
    final NormalizedNode data = payload.getData();
    if (yangIIdContext.isEmpty() && !NETCONF_BASE_QNAME.equals(data.getIdentifier().getNodeType())) {
        throw new RestconfDocumentedException("Instance identifier need to contain at least one path argument", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
    }
    final List<QName> qNames = yangIIdContext.getPathArguments().stream().filter(arg -> !(arg instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates)).filter(arg -> !(arg instanceof YangInstanceIdentifier.AugmentationIdentifier)).map(PathArgument::getNodeType).collect(Collectors.toList());
    qNames.add(context.getSchemaNode().getQName());
    final Absolute schemaPath = Absolute.of(qNames);
    final DOMActionResult response;
    final EffectiveModelContext schemaContextRef;
    if (mountPoint != null) {
        response = invokeAction((ContainerNode) data, schemaPath, yangIIdContext, mountPoint);
        schemaContextRef = modelContext(mountPoint);
    } else {
        response = invokeAction((ContainerNode) data, schemaPath, yangIIdContext, actionService);
        schemaContextRef = schemaContextHandler.get();
    }
    final DOMActionResult result = checkActionResponse(response);
    ActionDefinition resultNodeSchema = null;
    ContainerNode resultData = null;
    if (result != null) {
        final Optional<ContainerNode> optOutput = result.getOutput();
        if (optOutput.isPresent()) {
            resultData = optOutput.get();
            resultNodeSchema = (ActionDefinition) context.getSchemaNode();
        }
    }
    if (resultData != null && resultData.isEmpty()) {
        return Response.status(Status.NO_CONTENT).build();
    }
    return Response.status(Status.OK).entity(NormalizedNodePayload.ofNullable(new InstanceIdentifierContext<>(yangIIdContext, resultNodeSchema, mountPoint, schemaContextRef), resultData)).build();
}
Also used : DOMDataTreeWriteTransaction(org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction) DOMActionResult(org.opendaylight.mdsal.dom.api.DOMActionResult) WriteDataParams(org.opendaylight.restconf.nb.rfc8040.WriteDataParams) PlainPatchDataTransactionUtil(org.opendaylight.restconf.nb.rfc8040.rests.utils.PlainPatchDataTransactionUtil) SchemaContext(org.opendaylight.yangtools.yang.model.api.SchemaContext) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) DOMActionException(org.opendaylight.mdsal.dom.api.DOMActionException) Absolute(org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute) STREAM_ACCESS_PATH_PART(org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_ACCESS_PATH_PART) PatchContext(org.opendaylight.restconf.common.patch.PatchContext) Map(java.util.Map) QueryParams(org.opendaylight.restconf.nb.rfc8040.databind.jaxrs.QueryParams) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier) URI(java.net.URI) ContainerNode(org.opendaylight.yangtools.yang.data.api.schema.ContainerNode) DOMDataTreeIdentifier(org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier) DOMActionService(org.opendaylight.mdsal.dom.api.DOMActionService) ListSchemaNode(org.opendaylight.yangtools.yang.model.api.ListSchemaNode) CancellationException(java.util.concurrent.CancellationException) STREAM_LOCATION_PATH_PART(org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_LOCATION_PATH_PART) NotificationOutputType(org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType) Collectors(java.util.stream.Collectors) STREAM_PATH_PART(org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_PATH_PART) ParserIdentifier(org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier) List(java.util.List) NOTIFICATION_STREAM(org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.NOTIFICATION_STREAM) Revision(org.opendaylight.yangtools.yang.common.Revision) Response(javax.ws.rs.core.Response) DOMDataBroker(org.opendaylight.mdsal.dom.api.DOMDataBroker) PathArgument(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument) RestconfDataService(org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfDataService) Optional(java.util.Optional) UriInfo(javax.ws.rs.core.UriInfo) DOMSchemaService(org.opendaylight.mdsal.dom.api.DOMSchemaService) MapEntryNode(org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode) SimpleDOMActionResult(org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult) NotificationDefinition(org.opendaylight.yangtools.yang.model.api.NotificationDefinition) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) ReadDataTransactionUtil(org.opendaylight.restconf.nb.rfc8040.rests.utils.ReadDataTransactionUtil) ReadDataParams(org.opendaylight.restconf.nb.rfc8040.ReadDataParams) PutDataTransactionUtil(org.opendaylight.restconf.nb.rfc8040.rests.utils.PutDataTransactionUtil) InstanceIdentifierContext(org.opendaylight.restconf.common.context.InstanceIdentifierContext) PostDataTransactionUtil(org.opendaylight.restconf.nb.rfc8040.rests.utils.PostDataTransactionUtil) LocalDateTime(java.time.LocalDateTime) HashMap(java.util.HashMap) DOMMountPointService(org.opendaylight.mdsal.dom.api.DOMMountPointService) NormalizedNodePayload(org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload) STREAMS_PATH(org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAMS_PATH) NotificationListenerAdapter(org.opendaylight.restconf.nb.rfc8040.streams.listeners.NotificationListenerAdapter) DeleteDataTransactionUtil(org.opendaylight.restconf.nb.rfc8040.rests.utils.DeleteDataTransactionUtil) PatchStatusContext(org.opendaylight.restconf.common.patch.PatchStatusContext) ErrorType(org.opendaylight.yangtools.yang.common.ErrorType) ImmutableList(com.google.common.collect.ImmutableList) Objects.requireNonNull(java.util.Objects.requireNonNull) SchemaContextHandler(org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler) Status(javax.ws.rs.core.Response.Status) PatchDataTransactionUtil(org.opendaylight.restconf.nb.rfc8040.rests.utils.PatchDataTransactionUtil) Logger(org.slf4j.Logger) DOMDataTreeWriteOperations(org.opendaylight.mdsal.dom.api.DOMDataTreeWriteOperations) ErrorTag(org.opendaylight.yangtools.yang.common.ErrorTag) NodeIdentifierWithPredicates(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates) EffectiveModelContext(org.opendaylight.yangtools.yang.model.api.EffectiveModelContext) QueryParameters(org.opendaylight.restconf.nb.rfc8040.legacy.QueryParameters) Configuration(org.opendaylight.restconf.nb.rfc8040.streams.Configuration) QName(org.opendaylight.yangtools.yang.common.QName) RestconfStreamsSubscriptionService(org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfStreamsSubscriptionService) SchemaNode(org.opendaylight.yangtools.yang.model.api.SchemaNode) ExecutionException(java.util.concurrent.ExecutionException) STREAM_PATH(org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_PATH) DOMMountPoint(org.opendaylight.mdsal.dom.api.DOMMountPoint) Futures(com.google.common.util.concurrent.Futures) RestconfMappingNodeUtil(org.opendaylight.restconf.nb.rfc8040.utils.mapping.RestconfMappingNodeUtil) RestconfStrategy(org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfStrategy) RpcResultBuilder(org.opendaylight.yangtools.yang.common.RpcResultBuilder) DateTimeFormatter(java.time.format.DateTimeFormatter) LogicalDatastoreType(org.opendaylight.mdsal.common.api.LogicalDatastoreType) Clock(java.time.Clock) MdsalRestconfStrategy(org.opendaylight.restconf.nb.rfc8040.rests.transactions.MdsalRestconfStrategy) VisibleForTesting(com.google.common.annotations.VisibleForTesting) ActionDefinition(org.opendaylight.yangtools.yang.model.api.ActionDefinition) RestconfDocumentedException(org.opendaylight.restconf.common.errors.RestconfDocumentedException) Rfc8040(org.opendaylight.restconf.nb.rfc8040.Rfc8040) RpcError(org.opendaylight.yangtools.yang.common.RpcError) NormalizedNode(org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode) RestconfDocumentedException(org.opendaylight.restconf.common.errors.RestconfDocumentedException) QName(org.opendaylight.yangtools.yang.common.QName) DOMMountPoint(org.opendaylight.mdsal.dom.api.DOMMountPoint) NodeIdentifierWithPredicates(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates) Absolute(org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier) ActionDefinition(org.opendaylight.yangtools.yang.model.api.ActionDefinition) ContainerNode(org.opendaylight.yangtools.yang.data.api.schema.ContainerNode) NormalizedNode(org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode) DOMActionResult(org.opendaylight.mdsal.dom.api.DOMActionResult) SimpleDOMActionResult(org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult) EffectiveModelContext(org.opendaylight.yangtools.yang.model.api.EffectiveModelContext)

Example 30 with InstanceIdentifierContext

use of org.opendaylight.restconf.common.context.InstanceIdentifierContext in project netconf by opendaylight.

the class RestconfDataServiceImplTest method testPutDataWithMountPoint.

@Test
public void testPutDataWithMountPoint() {
    final InstanceIdentifierContext<DataSchemaNode> iidContext = new InstanceIdentifierContext<>(iidBase, schemaNode, mountPoint, contextRef);
    final NormalizedNodePayload payload = NormalizedNodePayload.of(iidContext, buildBaseCont);
    doReturn(immediateTrueFluentFuture()).when(read).exists(LogicalDatastoreType.CONFIGURATION, iidBase);
    doNothing().when(readWrite).put(LogicalDatastoreType.CONFIGURATION, iidBase, payload.getData());
    final Response response = dataService.putData(null, payload, uriInfo);
    assertNotNull(response);
    assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus());
}
Also used : Response(javax.ws.rs.core.Response) DataSchemaNode(org.opendaylight.yangtools.yang.model.api.DataSchemaNode) InstanceIdentifierContext(org.opendaylight.restconf.common.context.InstanceIdentifierContext) NormalizedNodePayload(org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload) Test(org.junit.Test)

Aggregations

InstanceIdentifierContext (org.opendaylight.restconf.common.context.InstanceIdentifierContext)50 Test (org.junit.Test)29 DataSchemaNode (org.opendaylight.yangtools.yang.model.api.DataSchemaNode)28 NormalizedNodePayload (org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload)26 YangInstanceIdentifier (org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier)24 NormalizedNode (org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode)20 ArrayList (java.util.ArrayList)18 NetconfRestconfStrategy (org.opendaylight.restconf.nb.rfc8040.rests.transactions.NetconfRestconfStrategy)16 DefaultDOMRpcResult (org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult)15 List (java.util.List)14 MdsalRestconfStrategy (org.opendaylight.restconf.nb.rfc8040.rests.transactions.MdsalRestconfStrategy)14 QName (org.opendaylight.yangtools.yang.common.QName)14 NormalizedNodeStreamWriter (org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter)14 Provider (javax.ws.rs.ext.Provider)13 IOException (java.io.IOException)12 RestconfDocumentedException (org.opendaylight.restconf.common.errors.RestconfDocumentedException)12 PatchContext (org.opendaylight.restconf.common.patch.PatchContext)12 MapEntryNode (org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode)12 StandardCharsets (java.nio.charset.StandardCharsets)11 WebApplicationException (javax.ws.rs.WebApplicationException)11