+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.rest.gson;
-
-import com.google.gson.JsonArray;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonIOException;
-import com.google.gson.JsonNull;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParseException;
-import com.google.gson.JsonPrimitive;
-import com.google.gson.JsonSyntaxException;
-import com.google.gson.internal.LazilyParsedNumber;
-import com.google.gson.stream.JsonReader;
-import com.google.gson.stream.MalformedJsonException;
-import java.io.EOFException;
-import java.io.IOException;
-
-/**
- * @deprecated class will be removed in Lithium release
- *
- * This class parses JSON elements from a gson JsonReader. It disallows multiple elements of the same name unlike the
- * default gson JsonParser."
- */
-@Deprecated
-public class JsonParser {
- public JsonElement parse(final JsonReader reader) throws JsonIOException, JsonSyntaxException {
- // code copied from gson's JsonParser and Stream classes
-
- final boolean lenient = reader.isLenient();
- reader.setLenient(true);
- boolean isEmpty = true;
- try {
- reader.peek();
- isEmpty = false;
- return read(reader);
- } catch (final EOFException e) {
- if (isEmpty) {
- return JsonNull.INSTANCE;
- }
- // The stream ended prematurely so it is likely a syntax error.
- throw new JsonSyntaxException(e);
- } catch (final MalformedJsonException e) {
- throw new JsonSyntaxException(e);
- } catch (final IOException e) {
- throw new JsonIOException(e);
- } catch (final NumberFormatException e) {
- throw new JsonSyntaxException(e);
- } catch (StackOverflowError | OutOfMemoryError e) {
- throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e);
- } finally {
- reader.setLenient(lenient);
- }
- }
-
- public JsonElement read(final JsonReader in) throws IOException {
- switch (in.peek()) {
- case STRING:
- return new JsonPrimitive(in.nextString());
- case NUMBER:
- final String number = in.nextString();
- return new JsonPrimitive(new LazilyParsedNumber(number));
- case BOOLEAN:
- return new JsonPrimitive(in.nextBoolean());
- case NULL:
- in.nextNull();
- return JsonNull.INSTANCE;
- case BEGIN_ARRAY:
- final JsonArray array = new JsonArray();
- in.beginArray();
- while (in.hasNext()) {
- array.add(read(in));
- }
- in.endArray();
- return array;
- case BEGIN_OBJECT:
- final JsonObject object = new JsonObject();
- in.beginObject();
- while (in.hasNext()) {
- final String childName = in.nextName();
- if (object.has(childName)) {
- throw new JsonSyntaxException("Duplicate name " + childName + " in JSON input.");
- }
- object.add(childName, read(in));
- }
- in.endObject();
- return object;
- case END_DOCUMENT:
- case NAME:
- case END_OBJECT:
- case END_ARRAY:
- default:
- throw new IllegalArgumentException();
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.rest.impl;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import com.google.common.base.Preconditions;
-import com.google.gson.stream.JsonWriter;
-import java.io.IOException;
-import java.net.URI;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import javax.activation.UnsupportedDataTypeException;
-import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
-import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
-import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO;
-import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO.IdentityValue;
-import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO.Predicate;
-import org.opendaylight.controller.sal.restconf.impl.RestCodec;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-class JsonMapper {
- private static final Logger LOG = LoggerFactory.getLogger(JsonMapper.class);
- private final DOMMountPoint mountPoint;
-
- public JsonMapper(final DOMMountPoint mountPoint) {
- this.mountPoint = mountPoint;
- }
-
- public void write(final JsonWriter writer, final CompositeNode data, final DataNodeContainer schema)
- throws IOException {
- Preconditions.checkNotNull(writer);
- Preconditions.checkNotNull(data);
- Preconditions.checkNotNull(schema);
-
- writer.beginObject();
-
- if (schema instanceof ContainerSchemaNode) {
- writeContainer(writer, data, (ContainerSchemaNode) schema);
- } else if (schema instanceof ListSchemaNode) {
- writeList(writer, null, data, (ListSchemaNode) schema);
- } else {
- throw new UnsupportedDataTypeException(
- "Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
- }
-
- writer.endObject();
- }
-
- private void writeChildrenOfParent(final JsonWriter writer, final CompositeNode parent,
- final DataNodeContainer parentSchema) throws IOException {
- checkNotNull(parent);
-
- final Set<QName> foundLists = new HashSet<>();
-
- Collection<DataSchemaNode> parentSchemaChildNodes = parentSchema == null ? Collections.<DataSchemaNode> emptySet()
- : parentSchema.getChildNodes();
-
- for (Node<?> child : parent.getValue()) {
- DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchemaChildNodes);
-
- if (childSchema == null) {
- // Node may not conform to schema or allows "anyxml" - we'll process it.
-
- LOG.debug("No schema found for data node \"{}\"", child.getNodeType());
-
- if (!foundLists.contains(child.getNodeType())) {
- handleNoSchemaFound(writer, child, parent);
-
- // Since we don't have a schema, we don't know which nodes are supposed to be
- // lists so treat every one as a potential list to avoid outputting duplicates.
-
- foundLists.add(child.getNodeType());
- }
- } else if (childSchema instanceof ContainerSchemaNode) {
- Preconditions.checkState(child instanceof CompositeNode,
- "Data representation of Container should be CompositeNode - %s", child.getNodeType());
- writeContainer(writer, (CompositeNode) child, (ContainerSchemaNode) childSchema);
- } else if (childSchema instanceof ListSchemaNode) {
- if (!foundLists.contains(child.getNodeType())) {
- Preconditions.checkState(child instanceof CompositeNode,
- "Data representation of List should be CompositeNode - %s", child.getNodeType());
- foundLists.add(child.getNodeType());
- writeList(writer, parent, (CompositeNode) child, (ListSchemaNode) childSchema);
- }
- } else if (childSchema instanceof LeafListSchemaNode) {
- if (!foundLists.contains(child.getNodeType())) {
- Preconditions.checkState(child instanceof SimpleNode<?>,
- "Data representation of LeafList should be SimpleNode - %s", child.getNodeType());
- foundLists.add(child.getNodeType());
- writeLeafList(writer, parent, (SimpleNode<?>) child, (LeafListSchemaNode) childSchema);
- }
- } else if (childSchema instanceof LeafSchemaNode) {
- Preconditions.checkState(child instanceof SimpleNode<?>,
- "Data representation of LeafList should be SimpleNode - %s", child.getNodeType());
- writeLeaf(writer, (SimpleNode<?>) child, (LeafSchemaNode) childSchema);
- } else if (childSchema instanceof AnyXmlSchemaNode) {
- if (child instanceof CompositeNode) {
- writeContainer(writer, (CompositeNode) child, null);
- } else {
- handleNoSchemaFound(writer, child, parent);
- }
- } else {
- throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode, ListSchemaNode, "
- + "LeafListSchemaNode, or LeafSchemaNode. Other types are not supported yet.");
- }
- }
- }
-
- private static void writeValue(final JsonWriter writer, final Object value) throws IOException {
- writer.value(value == null ? "" : String.valueOf(value));
- }
-
- private void handleNoSchemaFound(final JsonWriter writer, final Node<?> node, final CompositeNode parent)
- throws IOException {
- if (node instanceof SimpleNode<?>) {
- List<SimpleNode<?>> nodeLeafList = parent.getSimpleNodesByName(node.getNodeType());
- if (nodeLeafList.size() == 1) {
- writeName(node, null, writer);
- writeValue(writer, node.getValue());
- } else { // more than 1, write as a json array
- writeName(node, null, writer);
- writer.beginArray();
- for (SimpleNode<?> leafNode : nodeLeafList) {
- writeValue(writer, leafNode.getValue());
- }
-
- writer.endArray();
- }
- } else { // CompositeNode
- Preconditions.checkState(node instanceof CompositeNode,
- "Data representation of Container should be CompositeNode - %s", node.getNodeType());
-
- List<CompositeNode> nodeList = parent.getCompositesByName(node.getNodeType());
- if (nodeList.size() == 1) {
- writeContainer(writer, (CompositeNode) node, null);
- } else { // more than 1, write as a json array
- writeList(writer, parent, (CompositeNode) node, null);
- }
- }
- }
-
- private static DataSchemaNode findFirstSchemaForNode(final Node<?> node, final Iterable<DataSchemaNode> dataSchemaNode) {
- for (DataSchemaNode dsn : dataSchemaNode) {
- if (node.getNodeType().equals(dsn.getQName())) {
- return dsn;
- }
- if (dsn instanceof ChoiceSchemaNode) {
- for (ChoiceCaseNode choiceCase : ((ChoiceSchemaNode) dsn).getCases()) {
- DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
- if (foundDsn != null) {
- return foundDsn;
- }
- }
- }
- }
- return null;
- }
-
- private void writeContainer(final JsonWriter writer, final CompositeNode node, final ContainerSchemaNode schema)
- throws IOException {
- writeName(node, schema, writer);
- writer.beginObject();
- writeChildrenOfParent(writer, node, schema);
- writer.endObject();
- }
-
- private void writeList(final JsonWriter writer, final CompositeNode nodeParent, final CompositeNode node,
- final ListSchemaNode schema) throws IOException {
- writeName(node, schema, writer);
- writer.beginArray();
-
- if (nodeParent != null) {
- List<CompositeNode> nodeLists = nodeParent.getCompositesByName(node.getNodeType());
- for (CompositeNode nodeList : nodeLists) {
- writer.beginObject();
- writeChildrenOfParent(writer, nodeList, schema);
- writer.endObject();
- }
- } else {
- writer.beginObject();
- writeChildrenOfParent(writer, node, schema);
- writer.endObject();
- }
-
- writer.endArray();
- }
-
- private void writeLeafList(final JsonWriter writer, final CompositeNode nodeParent, final SimpleNode<?> node,
- final LeafListSchemaNode schema) throws IOException {
- writeName(node, schema, writer);
- writer.beginArray();
-
- List<SimpleNode<?>> nodeLeafLists = nodeParent.getSimpleNodesByName(node.getNodeType());
- for (SimpleNode<?> nodeLeafList : nodeLeafLists) {
- writeValueOfNodeByType(writer, nodeLeafList, schema.getType(), schema);
- }
- writer.endArray();
- }
-
- private void writeLeaf(final JsonWriter writer, final SimpleNode<?> node, final LeafSchemaNode schema)
- throws IOException {
- writeName(node, schema, writer);
- writeValueOfNodeByType(writer, node, schema.getType(), schema);
- }
-
- private void writeValueOfNodeByType(final JsonWriter writer, final SimpleNode<?> node,
- final TypeDefinition<?> type, final DataSchemaNode schema) throws IOException {
-
- TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(type);
-
- if (node.getValue() == null && !(baseType instanceof EmptyTypeDefinition)) {
- LOG.debug("While generationg JSON output null value was found for type {}.", baseType.getClass()
- .getSimpleName());
- }
-
- if (baseType instanceof IdentityrefTypeDefinition) {
- if (node.getValue() instanceof QName) {
- IdentityValuesDTO valueDTO = (IdentityValuesDTO) RestCodec.from(baseType, mountPoint).serialize(
- node.getValue());
- IdentityValue valueFromDTO = valueDTO.getValuesWithNamespaces().get(0);
- String moduleName;
- if (mountPoint != null) {
- moduleName = ControllerContext.getInstance().findModuleNameByNamespace(mountPoint,
- URI.create(valueFromDTO.getNamespace()));
- } else {
- moduleName = ControllerContext.getInstance().findModuleNameByNamespace(
- URI.create(valueFromDTO.getNamespace()));
- }
- writer.value(moduleName + ":" + valueFromDTO.getValue());
- } else {
- writeStringRepresentation(writer, node, baseType, QName.class);
- }
- } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
- if (node.getValue() instanceof YangInstanceIdentifier) {
- IdentityValuesDTO valueDTO = (IdentityValuesDTO) RestCodec.from(baseType, mountPoint).serialize(
- node.getValue());
- writeIdentityValuesDTOToJson(writer, valueDTO);
- } else {
- writeStringRepresentation(writer, node, baseType, YangInstanceIdentifier.class);
- }
- } else if (baseType instanceof DecimalTypeDefinition || baseType instanceof IntegerTypeDefinition
- || baseType instanceof UnsignedIntegerTypeDefinition) {
- writer.value(new NumberForJsonWriter((String) RestCodec.from(baseType, mountPoint).serialize(
- node.getValue())));
- } else if (baseType instanceof BooleanTypeDefinition) {
- writer.value(Boolean.parseBoolean((String) RestCodec.from(baseType, mountPoint).serialize(node.getValue())));
- } else if (baseType instanceof EmptyTypeDefinition) {
- writeEmptyDataTypeToJson(writer);
- } else {
- String value = String.valueOf(RestCodec.from(baseType, mountPoint).serialize(node.getValue()));
- if (value == null) {
- value = String.valueOf(node.getValue());
- }
- writer.value(value.equals("null") ? "" : value);
- }
- }
-
- private static void writeIdentityValuesDTOToJson(final JsonWriter writer, final IdentityValuesDTO valueDTO)
- throws IOException {
- StringBuilder result = new StringBuilder();
- for (IdentityValue identityValue : valueDTO.getValuesWithNamespaces()) {
- result.append('/');
-
- writeModuleNameAndIdentifier(result, identityValue);
- if (identityValue.getPredicates() != null && !identityValue.getPredicates().isEmpty()) {
- for (Predicate predicate : identityValue.getPredicates()) {
- IdentityValue identityValuePredicate = predicate.getName();
- result.append('[');
- if (identityValuePredicate == null) {
- result.append('.');
- } else {
- writeModuleNameAndIdentifier(result, identityValuePredicate);
- }
- result.append("='");
- result.append(predicate.getValue());
- result.append("']");
- }
- }
- }
-
- writer.value(result.toString());
- }
-
- private static void writeModuleNameAndIdentifier(final StringBuilder result, final IdentityValue identityValue) {
- String moduleName = ControllerContext.getInstance().findModuleNameByNamespace(
- URI.create(identityValue.getNamespace()));
- if (moduleName != null && !moduleName.isEmpty()) {
- result.append(moduleName);
- result.append(':');
- }
- result.append(identityValue.getValue());
- }
-
- private static void writeStringRepresentation(final JsonWriter writer, final SimpleNode<?> node,
- final TypeDefinition<?> baseType, final Class<?> requiredType) throws IOException {
- Object value = node.getValue();
- LOG.debug("Value of {}:{} is not instance of {} but is {}", baseType.getQName().getNamespace(), baseType
- .getQName().getLocalName(), requiredType.getClass(), node.getValue().getClass());
- if (value == null) {
- writer.value("");
- } else {
- writer.value(String.valueOf(value));
- }
- }
-
- private void writeEmptyDataTypeToJson(final JsonWriter writer) throws IOException {
- writer.beginArray();
- writer.nullValue();
- writer.endArray();
- }
-
- private void writeName(final Node<?> node, final DataSchemaNode schema, final JsonWriter writer) throws IOException {
- String nameForOutput = node.getNodeType().getLocalName();
- if (schema != null && schema.isAugmenting()) {
- ControllerContext contContext = ControllerContext.getInstance();
- CharSequence moduleName = null;
- if (mountPoint == null) {
- moduleName = contContext.toRestconfIdentifier(schema.getQName());
- } else {
- moduleName = contContext.toRestconfIdentifier(mountPoint, schema.getQName());
- }
- if (moduleName != null) {
- nameForOutput = moduleName.toString();
- } else {
- LOG.info("Module '{}' was not found in schema from mount point", schema.getQName());
- }
- }
- writer.name(nameForOutput);
- }
-
- private static final class NumberForJsonWriter extends Number {
-
- private static final long serialVersionUID = -3147729419814417666L;
- private final String value;
-
- public NumberForJsonWriter(final String value) {
- this.value = value;
- }
-
- @Override
- public int intValue() {
- throw new IllegalStateException("Should not be invoked");
- }
-
- @Override
- public long longValue() {
- throw new IllegalStateException("Should not be invoked");
- }
-
- @Override
- public float floatValue() {
- throw new IllegalStateException("Should not be invoked");
- }
-
- @Override
- public double doubleValue() {
- throw new IllegalStateException("Should not be invoked");
- }
-
- @Override
- public String toString() {
- return value;
- }
-
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.rest.impl;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Type;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.ext.MessageBodyReader;
-import javax.ws.rs.ext.Provider;
-import org.opendaylight.controller.sal.rest.api.Draft02;
-import org.opendaylight.controller.sal.rest.api.RestconfService;
-import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
-import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
-import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @deprecated class will be removed in Lithium release
- */
-@Provider
-@Consumes({ Draft02.MediaTypes.DATA + RestconfService.JSON, Draft02.MediaTypes.OPERATION + RestconfService.JSON,
- MediaType.APPLICATION_JSON })
-public enum JsonToCompositeNodeProvider implements MessageBodyReader<Node<?>> {
- INSTANCE;
-
- private final static Logger LOG = LoggerFactory.getLogger(JsonToCompositeNodeProvider.class);
-
- @Override
- public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
- final MediaType mediaType) {
- return true;
- }
-
- @Override
- public Node<?> readFrom(final Class<Node<?>> type, final Type genericType,
- final Annotation[] annotations, final MediaType mediaType,
- final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
- WebApplicationException {
- try {
- return JsonToCompositeNodeReader.read(entityStream);
- } catch (final Exception e) {
- LOG.debug("Error parsing json input", e);
-
- throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
- ErrorTag.MALFORMED_MESSAGE);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.rest.impl;
-
-import com.google.common.base.Splitter;
-import com.google.common.collect.Iterators;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonPrimitive;
-import com.google.gson.stream.JsonReader;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.net.URI;
-import java.util.Iterator;
-import java.util.Map.Entry;
-import java.util.Set;
-import org.opendaylight.controller.sal.rest.gson.JsonParser;
-import org.opendaylight.controller.sal.rest.impl.RestUtil.PrefixMapingFromJson;
-import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
-import org.opendaylight.controller.sal.restconf.impl.EmptyNodeWrapper;
-import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO;
-import org.opendaylight.controller.sal.restconf.impl.SimpleNodeWrapper;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @deprecated class will be removed in Lithium release
- */
-@Deprecated
-class JsonToCompositeNodeReader {
- private static final Logger LOG = LoggerFactory.getLogger(JsonToCompositeNodeReader.class);
- private static final Splitter COLON_SPLITTER = Splitter.on(':');
-
- private JsonToCompositeNodeReader() {
-
- }
-
- public static CompositeNodeWrapper read(final InputStream entityStream) throws UnsupportedFormatException {
- final JsonParser parser = new JsonParser();
-
- final JsonElement rootElement = parser.parse(new JsonReader(new InputStreamReader(entityStream)));
- if (rootElement.isJsonNull()) {
- // no content, so return null to indicate no input
- return null;
- }
-
- if (!rootElement.isJsonObject()) {
- throw new UnsupportedFormatException("Root element of Json has to be Object");
- }
-
- final Set<Entry<String, JsonElement>> entrySetsOfRootJsonObject = rootElement.getAsJsonObject().entrySet();
- if (entrySetsOfRootJsonObject.size() != 1) {
- throw new UnsupportedFormatException("Json Object should contain one element");
- }
-
- final Entry<String, JsonElement> childEntry = entrySetsOfRootJsonObject.iterator().next();
- final String firstElementName = childEntry.getKey();
- final JsonElement firstElementType = childEntry.getValue();
- if (firstElementType.isJsonObject()) {
- // container in yang
- return createStructureWithRoot(firstElementName, firstElementType.getAsJsonObject());
- }
- if (firstElementType.isJsonArray()) {
- // list in yang
- if (firstElementType.getAsJsonArray().size() == 1) {
- final JsonElement firstElementInArray = firstElementType.getAsJsonArray().get(0);
- if (firstElementInArray.isJsonObject()) {
- return createStructureWithRoot(firstElementName, firstElementInArray.getAsJsonObject());
- }
- throw new UnsupportedFormatException(
- "Array as the first element in Json Object can have only Object element");
- }
- }
- throw new UnsupportedFormatException(
- "First element in Json Object has to be \"Object\" or \"Array with one Object element\". Other scenarios are not supported yet.");
- }
-
- private static CompositeNodeWrapper createStructureWithRoot(final String rootObjectName, final JsonObject rootObject) {
- final CompositeNodeWrapper firstNode = new CompositeNodeWrapper(getNamespaceFor(rootObjectName),
- getLocalNameFor(rootObjectName));
- for (final Entry<String, JsonElement> childOfFirstNode : rootObject.entrySet()) {
- addChildToParent(childOfFirstNode.getKey(), childOfFirstNode.getValue(), firstNode);
- }
- return firstNode;
- }
-
- private static void addChildToParent(final String childName, final JsonElement childType,
- final CompositeNodeWrapper parent) {
- if (childType.isJsonObject()) {
- final CompositeNodeWrapper child = new CompositeNodeWrapper(getNamespaceFor(childName),
- getLocalNameFor(childName));
- parent.addValue(child);
- for (final Entry<String, JsonElement> childOfChild : childType.getAsJsonObject().entrySet()) {
- addChildToParent(childOfChild.getKey(), childOfChild.getValue(), child);
- }
- } else if (childType.isJsonArray()) {
- if (childType.getAsJsonArray().size() == 1 && childType.getAsJsonArray().get(0).isJsonNull()) {
- parent.addValue(new EmptyNodeWrapper(getNamespaceFor(childName), getLocalNameFor(childName)));
-
- } else {
- for (final JsonElement childOfChildType : childType.getAsJsonArray()) {
- addChildToParent(childName, childOfChildType, parent);
- }
- }
- } else if (childType.isJsonPrimitive()) {
- final JsonPrimitive childPrimitive = childType.getAsJsonPrimitive();
- final String value = childPrimitive.getAsString().trim();
- parent.addValue(new SimpleNodeWrapper(getNamespaceFor(childName), getLocalNameFor(childName),
- resolveValueOfElement(value)));
- } else {
- LOG.debug("Ignoring unhandled child type {}", childType);
- }
- }
-
- /**
- * Transform input value to URI instance.
- *
- * Input string has to be in format moduleName:localName. moduleName part is then transformed to URI instance.
- * If moduleName part contains character like "<" or ">" then null value is returned because they
- * aren't valid URI characters.
- *
- * @param jsonElementName
- * value in format moduleName:localName
- * @return
- */
- private static URI getNamespaceFor(final String jsonElementName) {
- final Iterator<String> it = COLON_SPLITTER.split(jsonElementName).iterator();
-
- // The string needs to be in form "moduleName:localName"
- if (it.hasNext()) {
- final String maybeURI = it.next();
- if (Iterators.size(it) == 1) {
- try {
- return URI.create(maybeURI);
- } catch (final IllegalArgumentException e) {
- LOG.debug("Value {} couldn't be interpreted as URI.", maybeURI);
- }
- }
- }
-
- return null;
- }
-
- private static String getLocalNameFor(final String jsonElementName) {
- final Iterator<String> it = COLON_SPLITTER.split(jsonElementName).iterator();
-
- // The string needs to me in form "moduleName:localName"
- final String ret = Iterators.get(it, 1, null);
- return ret != null && !it.hasNext() ? ret : jsonElementName;
- }
-
- private static Object resolveValueOfElement(final String value) {
- // it could be instance-identifier Built-In Type
- if (!value.isEmpty() && value.charAt(0) == '/') {
- final IdentityValuesDTO resolvedValue = RestUtil.asInstanceIdentifier(value, new PrefixMapingFromJson());
- if (resolvedValue != null) {
- return resolvedValue;
- }
- }
-
- // it could be identityref Built-In Type therefore it is necessary to look at value as module_name:local_name
- final URI namespace = getNamespaceFor(value);
- if (namespace != null) {
- return new IdentityValuesDTO(namespace.toString(), getLocalNameFor(value), null, value);
- }
-
- // it is not "prefix:value" but just "value"
- return value;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.rest.impl;
-
-import com.google.common.base.Charsets;
-import com.google.gson.stream.JsonWriter;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Type;
-import javax.ws.rs.Produces;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.ext.MessageBodyWriter;
-import javax.ws.rs.ext.Provider;
-import org.opendaylight.controller.sal.rest.api.Draft02;
-import org.opendaylight.controller.sal.rest.api.RestconfService;
-import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
-import org.opendaylight.controller.sal.restconf.impl.StructuredData;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
-
-/**
- * @deprecated class will be removed in Lithium release
- */
-@Provider
-@Produces({ Draft02.MediaTypes.API + RestconfService.JSON, Draft02.MediaTypes.DATA + RestconfService.JSON,
- Draft02.MediaTypes.OPERATION + RestconfService.JSON, MediaType.APPLICATION_JSON })
-public enum StructuredDataToJsonProvider implements MessageBodyWriter<StructuredData> {
- INSTANCE;
-
- @Override
- public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) {
- return type.equals(StructuredData.class);
- }
-
- @Override
- public long getSize(final StructuredData t, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) {
- return -1;
- }
-
- @Override
- public void writeTo(final StructuredData t, final Class<?> type, final Type genericType, final Annotation[] annotations,
- final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream)
- throws IOException, WebApplicationException {
- final CompositeNode data = t.getData();
- if (data == null) {
- throw new RestconfDocumentedException(Response.Status.NOT_FOUND);
- }
-
- final JsonWriter writer = new JsonWriter(new OutputStreamWriter(entityStream, Charsets.UTF_8));
-
- if (t.isPrettyPrintMode()) {
- writer.setIndent(" ");
- } else {
- writer.setIndent("");
- }
- final JsonMapper jsonMapper = new JsonMapper(t.getMountPoint());
- jsonMapper.write(writer, data, (DataNodeContainer) t.getSchema());
- writer.flush();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.rest.impl;
-
-import java.io.IOException;
-import java.io.OutputStream;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Type;
-import javax.ws.rs.Produces;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.ext.MessageBodyWriter;
-import javax.ws.rs.ext.Provider;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerConfigurationException;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-import org.opendaylight.controller.sal.rest.api.Draft02;
-import org.opendaylight.controller.sal.rest.api.RestconfService;
-import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
-import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
-import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
-import org.opendaylight.controller.sal.restconf.impl.StructuredData;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-
-/**
- * @deprecated class will be removed in Lithium release
- */
-@Provider
-@Produces({ Draft02.MediaTypes.API + RestconfService.XML, Draft02.MediaTypes.DATA + RestconfService.XML,
- Draft02.MediaTypes.OPERATION + RestconfService.XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML })
-public enum StructuredDataToXmlProvider implements MessageBodyWriter<StructuredData> {
- INSTANCE;
-
- private static final Logger LOG = LoggerFactory.getLogger(StructuredDataToXmlProvider.class);
- private static final TransformerFactory FACTORY = TransformerFactory.newInstance();
- private static final ThreadLocal<Transformer> TRANSFORMER = new ThreadLocal<Transformer>() {
- @Override
- protected Transformer initialValue() {
- final Transformer ret;
- try {
- ret = FACTORY.newTransformer();
- } catch (final TransformerConfigurationException e) {
- LOG.error("Failed to instantiate XML transformer", e);
- throw new IllegalStateException("XML encoding currently unavailable", e);
- }
-
- ret.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
- ret.setOutputProperty(OutputKeys.METHOD, "xml");
- ret.setOutputProperty(OutputKeys.INDENT, "yes");
- ret.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
- ret.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
-
- return ret;
- }
- };
-
- @Override
- public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations,
- final MediaType mediaType) {
- return type.equals(StructuredData.class);
- }
-
- @Override
- public long getSize(final StructuredData t, final Class<?> type, final Type genericType,
- final Annotation[] annotations, final MediaType mediaType) {
- return -1;
- }
-
- @Override
- public void writeTo(final StructuredData t, final Class<?> type, final Type genericType,
- final Annotation[] annotations, final MediaType mediaType,
- final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException,
- WebApplicationException {
- final CompositeNode data = t.getData();
- if (data == null) {
- throw new RestconfDocumentedException(Response.Status.NOT_FOUND);
- }
-
- final Transformer trans;
- try {
- trans = TRANSFORMER.get();
- if (t.isPrettyPrintMode()) {
- trans.setOutputProperty(OutputKeys.INDENT, "yes");
- } else {
- trans.setOutputProperty(OutputKeys.INDENT, "no");
- }
- } catch (final RuntimeException e) {
- throw new RestconfDocumentedException(e.getMessage(), ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED);
- }
-
- // FIXME: BUG-1281: eliminate the intermediate Document
- final Document domTree = new XmlMapper().write(data, (DataNodeContainer) t.getSchema());
- try {
- trans.transform(new DOMSource(domTree), new StreamResult(entityStream));
- } catch (final TransformerException e) {
- LOG.error("Error during translation of Document to OutputStream", e);
- throw new RestconfDocumentedException(e.getMessage(), ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED);
- }
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.rest.impl;
-
-import com.google.common.base.Optional;
-import javax.activation.UnsupportedDataTypeException;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.codec.LeafrefCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlCodecProvider;
-import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
-import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
-import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
-import org.opendaylight.yangtools.yang.model.util.Leafref;
-import org.w3c.dom.Document;
-
-/**
- * @deprecated class will be removed for lithium release
- */
-@Deprecated
-public class XmlMapper {
- private static final LeafrefCodecImpl LEAFREF_DEFAULT_CODEC = new LeafrefCodecImpl(
- Optional.<LeafrefTypeDefinition> absent());
-
- private static class LeafrefCodecImpl extends TypeDefinitionAwareCodec<Object, LeafrefTypeDefinition> implements
- LeafrefCodec<String> {
-
- protected LeafrefCodecImpl(final Optional<LeafrefTypeDefinition> typeDef) {
- super(typeDef, Object.class);
- }
-
- @Override
- public String serialize(final Object data) {
- return String.valueOf(data);
- }
-
- @Override
- public Object deserialize(final String data) {
- return data;
- }
- }
-
- private static class XmlCodecProviderImpl implements XmlCodecProvider {
- @Override
- public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(final TypeDefinition<?> baseType) {
- final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codec = TypeDefinitionAwareCodec
- .from(baseType);
-
- if (codec == null) {
- if (baseType instanceof Leafref) {
- return LEAFREF_DEFAULT_CODEC;
- }
- }
- return codec;
- }
- }
-
- private static final XmlCodecProvider XML_CODEC_PROVIDER_IMPL = new XmlCodecProviderImpl();
-
- public Document write(final CompositeNode data, final DataNodeContainer schema) throws UnsupportedDataTypeException {
- return XmlDocumentUtils.toDocument(data, schema, XML_CODEC_PROVIDER_IMPL);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.rest.impl;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Type;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.ext.MessageBodyReader;
-import javax.ws.rs.ext.Provider;
-import javax.xml.stream.XMLStreamException;
-import org.opendaylight.controller.sal.rest.api.Draft02;
-import org.opendaylight.controller.sal.rest.api.RestconfService;
-import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
-import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
-import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @deprecated class will be removed in Lithium release
- */
-@Provider
-@Consumes({ Draft02.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.OPERATION + RestconfService.XML,
- MediaType.APPLICATION_XML, MediaType.TEXT_XML })
-public enum XmlToCompositeNodeProvider implements MessageBodyReader<Node<?>> {
- INSTANCE;
- private final static Logger LOG = LoggerFactory.getLogger(XmlToCompositeNodeProvider.class);
-
- @Override
- public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
- final MediaType mediaType) {
- return true;
- }
-
- @Override
- public Node<?> readFrom(final Class<Node<?>> type, final Type genericType, final Annotation[] annotations,
- final MediaType mediaType, final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
- throws IOException, WebApplicationException {
- final XmlToCompositeNodeReader xmlReader = new XmlToCompositeNodeReader();
- try {
- return xmlReader.read(entityStream);
- } catch (XMLStreamException | UnsupportedFormatException e) {
- LOG.debug("Error parsing json input", e);
- throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
- ErrorTag.MALFORMED_MESSAGE);
- }
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.rest.impl;
-
-import static com.google.common.base.Preconditions.checkArgument;
-import java.io.BufferedInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URI;
-import java.util.Stack;
-import javax.xml.stream.XMLEventReader;
-import javax.xml.stream.XMLInputFactory;
-import javax.xml.stream.XMLStreamConstants;
-import javax.xml.stream.XMLStreamException;
-import javax.xml.stream.events.Characters;
-import javax.xml.stream.events.StartElement;
-import javax.xml.stream.events.XMLEvent;
-import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
-import org.opendaylight.controller.sal.restconf.impl.EmptyNodeWrapper;
-import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO;
-import org.opendaylight.controller.sal.restconf.impl.NodeWrapper;
-import org.opendaylight.controller.sal.restconf.impl.SimpleNodeWrapper;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-/**
- * @deprecated class will be removed in Lithium release
- */
-@Deprecated
-public class XmlToCompositeNodeReader {
-
- private final static XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
- static {
- xmlInputFactory.setProperty("javax.xml.stream.isSupportingExternalEntities", false);
- }
- private XMLEventReader eventReader;
-
- public Node<?> read(InputStream entityStream) throws XMLStreamException,
- UnsupportedFormatException,
- IOException {
- //Get an XML stream which can be marked, and reset, so we can check and see if there is
- //any content being provided.
- entityStream = getMarkableStream(entityStream);
-
- if (isInputStreamEmpty(entityStream)) {
- return null;
- }
-
- eventReader = xmlInputFactory.createXMLEventReader(entityStream);
- if (eventReader.hasNext()) {
- final XMLEvent element = eventReader.peek();
- if (element.isStartDocument()) {
- eventReader.nextEvent();
- }
- }
-
- final Stack<NodeWrapper<?>> processingQueue = new Stack<>();
- NodeWrapper<?> root = null;
- NodeWrapper<?> element = null;
- while (eventReader.hasNext()) {
- final XMLEvent event = eventReader.nextEvent();
-
- if (event.isStartElement()) {
- final StartElement startElement = event.asStartElement();
- CompositeNodeWrapper compParentNode = null;
- if (!processingQueue.isEmpty() && processingQueue.peek() instanceof CompositeNodeWrapper) {
- compParentNode = (CompositeNodeWrapper) processingQueue.peek();
- }
- NodeWrapper<?> newNode = null;
- if (isCompositeNodeEvent(event)) {
- newNode = resolveCompositeNodeFromStartElement(startElement);
- if (root == null) {
- root = newNode;
- }
- } else if (isSimpleNodeEvent(event)) {
- newNode = resolveSimpleNodeFromStartElement(startElement);
- if (root == null) {
- root = newNode;
- }
- }
-
- if (newNode != null) {
- processingQueue.push(newNode);
- if (compParentNode != null) {
- compParentNode.addValue(newNode);
- }
- }
- } else if (event.isEndElement()) {
- element = processingQueue.pop();
- }
- }
-
- if (!root.getLocalName().equals(element.getLocalName())) {
- throw new UnsupportedFormatException("XML should contain only one root element");
- }
-
- return (Node<?>) root;
- }
-
- /**
- * If the input stream is not markable, then it wraps the input stream with a buffered stream, which is mark able.
- * That way we can check if the stream is empty safely.
- *
- * @param entityStream
- * @return
- */
- private InputStream getMarkableStream(InputStream entityStream) {
- if (!entityStream.markSupported()) {
- entityStream = new BufferedInputStream(entityStream);
- }
- return entityStream;
- }
-
- private boolean isInputStreamEmpty(final InputStream entityStream) throws IOException {
- boolean isEmpty = false;
- entityStream.mark(1);
- if (entityStream.read() == -1) {
- isEmpty = true;
- }
- entityStream.reset();
- return isEmpty;
- }
-
- private boolean isSimpleNodeEvent(final XMLEvent event) throws XMLStreamException {
- checkArgument(event != null, "XML Event cannot be NULL!");
- if (event.isStartElement()) {
- final XMLEvent innerEvent = skipCommentsAndWhitespace();
- if (innerEvent != null && (innerEvent.isCharacters() || innerEvent.isEndElement())) {
- return true;
- }
- }
- return false;
- }
-
- private boolean isCompositeNodeEvent(final XMLEvent event) throws XMLStreamException {
- checkArgument(event != null, "XML Event cannot be NULL!");
- if (event.isStartElement()) {
- final XMLEvent innerEvent = skipCommentsAndWhitespace();
- if (innerEvent != null) {
- if (innerEvent.isStartElement()) {
- return true;
- }
- }
- }
- return false;
- }
-
- private XMLEvent skipCommentsAndWhitespace() throws XMLStreamException {
- while (eventReader.hasNext()) {
- final XMLEvent event = eventReader.peek();
- if (event.getEventType() == XMLStreamConstants.COMMENT) {
- eventReader.nextEvent();
- continue;
- }
-
- if (event.isCharacters()) {
- final Characters chars = event.asCharacters();
- if (chars.isWhiteSpace()) {
- eventReader.nextEvent();
- continue;
- }
- }
- return event;
- }
- return null;
- }
-
- private CompositeNodeWrapper resolveCompositeNodeFromStartElement(final StartElement startElement) {
- checkArgument(startElement != null, "Start Element cannot be NULL!");
- return new CompositeNodeWrapper(getNamespaceFor(startElement), getLocalNameFor(startElement));
- }
-
- private NodeWrapper<? extends Node<?>> resolveSimpleNodeFromStartElement(final StartElement startElement)
- throws XMLStreamException {
- checkArgument(startElement != null, "Start Element cannot be NULL!");
- final String data = getValueOf(startElement);
- if (data == null) {
- return new EmptyNodeWrapper(getNamespaceFor(startElement), getLocalNameFor(startElement));
- }
- return new SimpleNodeWrapper(getNamespaceFor(startElement), getLocalNameFor(startElement),
- resolveValueOfElement(data, startElement));
- }
-
- private String getValueOf(final StartElement startElement) throws XMLStreamException {
- String data = null;
- if (eventReader.hasNext()) {
- final XMLEvent innerEvent = eventReader.peek();
- if (innerEvent.isCharacters()) {
- final Characters chars = innerEvent.asCharacters();
- if (!chars.isWhiteSpace()) {
- data = innerEvent.asCharacters().getData();
- data = data + getAdditionalData(eventReader.nextEvent());
- }
- } else if (innerEvent.isEndElement()) {
- if (startElement.getLocation().getCharacterOffset() == innerEvent.getLocation().getCharacterOffset()) {
- data = null;
- } else {
- data = "";
- }
- }
- }
- return data == null ? null : data.trim();
- }
-
- private String getAdditionalData(final XMLEvent event) throws XMLStreamException {
- String data = "";
- if (eventReader.hasNext()) {
- final XMLEvent innerEvent = eventReader.peek();
- if (innerEvent.isCharacters() && !innerEvent.isEndElement()) {
- final Characters chars = innerEvent.asCharacters();
- if (!chars.isWhiteSpace()) {
- data = innerEvent.asCharacters().getData();
- data = data + getAdditionalData(eventReader.nextEvent());
- }
- }
- }
- return data;
- }
-
- private String getLocalNameFor(final StartElement startElement) {
- return startElement.getName().getLocalPart();
- }
-
- private URI getNamespaceFor(final StartElement startElement) {
- final String namespaceURI = startElement.getName().getNamespaceURI();
- return namespaceURI.isEmpty() ? null : URI.create(namespaceURI);
- }
-
- private Object resolveValueOfElement(final String value, final StartElement startElement) {
- // it could be instance-identifier Built-In Type
- if (value.startsWith("/")) {
- final IdentityValuesDTO iiValue = RestUtil.asInstanceIdentifier(value, new RestUtil.PrefixMapingFromXml(
- startElement));
- if (iiValue != null) {
- return iiValue;
- }
- }
- // it could be identityref Built-In Type
- final String[] namespaceAndValue = value.split(":");
- if (namespaceAndValue.length == 2) {
- final String namespace = startElement.getNamespaceContext().getNamespaceURI(namespaceAndValue[0]);
- if (namespace != null && !namespace.isEmpty()) {
- return new IdentityValuesDTO(namespace, namespaceAndValue[1], namespaceAndValue[0], value);
- }
- }
- // it is not "prefix:value" but just "value"
- return value;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.restconf.impl;
-
-import com.google.common.base.Preconditions;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
-
-/**
- * @deprecated class will be removed in Lithium release
- */
-@Deprecated
-public final class CompositeNodeWrapper implements NodeWrapper<CompositeNode>, CompositeNode {
-
- private MutableCompositeNode compositeNode;
-
- private String localName;
- private URI namespace;
- private QName name;
- private List<NodeWrapper<?>> values = new ArrayList<>();
-
- public CompositeNodeWrapper(final String localName) {
- this.localName = Preconditions.checkNotNull(localName);
- }
-
- public CompositeNodeWrapper(final URI namespace, final String localName) {
- this(localName);
- this.namespace = namespace;
- }
-
- @Override
- public void setQname(final QName name) {
- Preconditions.checkState(compositeNode == null, "Cannot change the object, due to data inconsistencies.");
- this.name = name;
- }
-
- @Override
- public QName getQname() {
- return name;
- }
-
- @Override
- public String getLocalName() {
- if (compositeNode != null) {
- return compositeNode.getNodeType().getLocalName();
- }
- return localName;
- }
-
- @Override
- public URI getNamespace() {
- if (compositeNode != null) {
- return compositeNode.getNodeType().getNamespace();
- }
- return namespace;
- }
-
- @Override
- public void setNamespace(final URI namespace) {
- Preconditions.checkState(compositeNode == null, "Cannot change the object, due to data inconsistencies.");
- this.namespace = namespace;
- }
-
- public void addValue(final NodeWrapper<?> value) {
- Preconditions.checkState(compositeNode == null, "Cannot change the object, due to data inconsistencies.");
- values.add(value);
- }
-
- public void removeValue(final NodeWrapper<CompositeNode> value) {
- Preconditions.checkState(compositeNode == null, "Cannot change the object, due to data inconsistencies.");
- values.remove(value);
- }
-
- public List<NodeWrapper<?>> getValues() {
- Preconditions.checkState(compositeNode == null, "Data can be inconsistent.");
- return Collections.unmodifiableList(values);
- }
-
- @Override
- public boolean isChangeAllowed() {
- return compositeNode == null ? true : false;
- }
-
- @Override
- public CompositeNode unwrap() {
- if (compositeNode == null) {
- if (name == null) {
- Preconditions.checkNotNull(namespace);
- name = new QName(namespace, localName);
- }
-
- final List<Node<?>> nodeValues = new ArrayList<>(values.size());
- for (final NodeWrapper<?> nodeWrapper : values) {
- nodeValues.add(nodeWrapper.unwrap());
- }
- compositeNode = NodeFactory.createMutableCompositeNode(name, null, nodeValues, null, null);
-
- values = null;
- namespace = null;
- localName = null;
- name = null;
- }
- return compositeNode;
- }
-
- @Override
- public QName getNodeType() {
- return unwrap().getNodeType();
- }
-
- @Deprecated
- @Override
- public CompositeNode getParent() {
- return unwrap().getParent();
- }
-
- @Override
- public List<Node<?>> getValue() {
- return unwrap().getValue();
- }
-
- @Override
- public ModifyAction getModificationAction() {
- return unwrap().getModificationAction();
- }
-
- /**
- * @deprecated Use {@link #getValue()} instead.
- */
- @Deprecated
- @Override
- public List<Node<?>> getChildren() {
- return unwrap().getValue();
- }
-
- @Override
- public List<CompositeNode> getCompositesByName(final QName children) {
- return unwrap().getCompositesByName(children);
- }
-
- @Override
- public List<CompositeNode> getCompositesByName(final String children) {
- return unwrap().getCompositesByName(children);
- }
-
- @Override
- public List<SimpleNode<?>> getSimpleNodesByName(final QName children) {
- return unwrap().getSimpleNodesByName(children);
- }
-
- @Override
- public List<SimpleNode<?>> getSimpleNodesByName(final String children) {
- return unwrap().getSimpleNodesByName(children);
- }
-
- @Override
- public CompositeNode getFirstCompositeByName(final QName container) {
- return unwrap().getFirstCompositeByName(container);
- }
-
- @Override
- public SimpleNode<?> getFirstSimpleByName(final QName leaf) {
- return unwrap().getFirstSimpleByName(leaf);
- }
-
- @Override
- public MutableCompositeNode asMutable() {
- return unwrap().asMutable();
- }
-
- @Override
- public QName getKey() {
- return unwrap().getKey();
- }
-
- @Override
- public List<Node<?>> setValue(final List<Node<?>> value) {
- return unwrap().setValue(value);
- }
-
- @Override
- public int size() {
- return unwrap().size();
- }
-
- @Override
- public boolean isEmpty() {
- return unwrap().isEmpty();
- }
-
- @Override
- public boolean containsKey(final Object key) {
- return unwrap().containsKey(key);
- }
-
- @Override
- public boolean containsValue(final Object value) {
- return unwrap().containsValue(value);
- }
-
- @Override
- public List<Node<?>> get(final Object key) {
- return unwrap().get(key);
- }
-
- @Override
- public List<Node<?>> put(final QName key, final List<Node<?>> value) {
- return unwrap().put(key, value);
- }
-
- @Override
- public List<Node<?>> remove(final Object key) {
- return unwrap().remove(key);
- }
-
- @Override
- public void putAll(final Map<? extends QName, ? extends List<Node<?>>> m) {
- unwrap().putAll(m);
- }
-
- @Override
- public void clear() {
- unwrap().clear();
- }
-
- @Override
- public Set<QName> keySet() {
- return unwrap().keySet();
- }
-
- @Override
- public Collection<List<Node<?>>> values() {
- return unwrap().values();
- }
-
- @Override
- public Set<java.util.Map.Entry<QName, List<Node<?>>>> entrySet() {
- return unwrap().entrySet();
- }
-
-}
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import javax.ws.rs.core.Response.Status;
import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
import org.opendaylight.yangtools.concepts.Codec;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
}
}
- public Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalized(final YangInstanceIdentifier legacy,
- final CompositeNode compositeNode) {
- try {
- return dataNormalizer.toNormalized(legacy, compositeNode);
- } catch (final NullPointerException e) {
- throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
- }
- }
-
public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
try {
return dataNormalizer.toNormalized(legacy);
}
}
- public CompositeNode toLegacy(final YangInstanceIdentifier instanceIdentifier,
- final NormalizedNode<?,?> normalizedNode) {
- try {
- return dataNormalizer.toLegacy(instanceIdentifier, normalizedNode);
- } catch (final NullPointerException e) {
- throw new RestconfDocumentedException("Data normalizer isn't set. Normalization isn't possible", e);
- }
- }
-
public YangInstanceIdentifier toXpathRepresentation(final YangInstanceIdentifier instanceIdentifier) {
try {
return dataNormalizer.toLegacy(instanceIdentifier);
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.restconf.impl;
-
-import com.google.common.base.Preconditions;
-import java.net.URI;
-import java.util.Collections;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
-
-/**
- * @deprecated class will be removed in Lithium release
- */
-@Deprecated
-public final class EmptyNodeWrapper implements NodeWrapper<Node<?>>, Node<Void> {
-
- private Node<?> unwrapped;
-
- private String localName;
- private URI namespace;
- private QName name;
-
- private boolean composite;
-
- public boolean isComposite() {
- return composite;
- }
-
- public void setComposite(final boolean composite) {
- this.composite = composite;
- }
-
- public EmptyNodeWrapper(final URI namespace, final String localName) {
- this.localName = Preconditions.checkNotNull(localName);
- this.namespace = namespace;
- }
-
- @Override
- public void setQname(final QName name) {
- Preconditions.checkState(unwrapped == null, "Cannot change the object, due to data inconsistencies.");
- this.name = name;
- }
-
- @Override
- public QName getQname() {
- return name;
- }
-
- @Override
- public String getLocalName() {
- if (unwrapped != null) {
- return unwrapped.getNodeType().getLocalName();
- }
- return localName;
- }
-
- @Override
- public URI getNamespace() {
- if (unwrapped != null) {
- return unwrapped.getNodeType().getNamespace();
- }
- return namespace;
- }
-
- @Override
- public void setNamespace(final URI namespace) {
- Preconditions.checkState(unwrapped == null, "Cannot change the object, due to data inconsistencies.");
- this.namespace = namespace;
- }
-
- @Override
- public boolean isChangeAllowed() {
- return unwrapped == null ? true : false;
- }
-
- @Override
- public Node<?> unwrap() {
- if (unwrapped == null) {
- if (name == null) {
- Preconditions.checkNotNull(namespace);
- name = new QName(namespace, localName);
- }
- if (composite) {
- unwrapped = NodeFactory.createImmutableCompositeNode(name, null, Collections.<Node<?>> emptyList(),
- null);
- } else {
- unwrapped = NodeFactory.createImmutableSimpleNode(name, null, null);
- }
- namespace = null;
- localName = null;
- name = null;
- }
- return unwrapped;
- }
-
- @Override
- public QName getNodeType() {
- return unwrap().getNodeType();
- }
-
- @Override
- @Deprecated
- public CompositeNode getParent() {
- return unwrap().getParent();
- }
-
- @Override
- public Void getValue() {
- return null;
- }
-
- @Override
- public QName getKey() {
- return unwrap().getKey();
- }
-
- @Override
- public Void setValue(final Void value) {
- return null;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.restconf.impl;
-
-import java.net.URI;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-/**
- * @deprecated class will be removed in Lithium release
- */
-@Deprecated
-public interface NodeWrapper<T extends Node<?>> {
-
- void setQname(QName name);
-
- QName getQname();
-
- T unwrap();
-
- boolean isChangeAllowed();
-
- URI getNamespace();
-
- void setNamespace(URI namespace);
-
- String getLocalName();
-}
*/
package org.opendaylight.controller.sal.restconf.impl;
-import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicates;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
-import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.sal.rest.api.RestconfService;
import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
-import org.opendaylight.controller.sal.restconf.rpc.impl.BrokerRpcExecutor;
-import org.opendaylight.controller.sal.restconf.rpc.impl.MountPointRpcExecutor;
-import org.opendaylight.controller.sal.restconf.rpc.impl.RpcExecutor;
import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
import org.opendaylight.controller.sal.streams.listeners.Notificator;
import org.opendaylight.controller.sal.streams.websockets.WebSocketServer;
-import org.opendaylight.yangtools.concepts.Codec;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
-import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser.CnSnToNormalizedNodeParserFactory;
-import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
-import org.opendaylight.yangtools.yang.model.util.EmptyType;
import org.opendaylight.yangtools.yang.model.util.ExtendedType;
import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
-import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
-import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
}
- /**
- * @deprecated method will be removed in Lithium release
- */
- @Deprecated
- private StructuredData operationsFromModulesToStructuredData(final Set<Module> modules,
- final DOMMountPoint mountPoint, final boolean prettyPrint) {
- final List<Node<?>> operationsAsData = new ArrayList<Node<?>>();
- final Module restconfModule = getRestconfModule();
- final DataSchemaNode operationsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
- restconfModule, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
- final QName qName = operationsSchemaNode.getQName();
- final SchemaPath path = operationsSchemaNode.getPath();
- final ContainerSchemaNodeBuilder containerSchemaNodeBuilder = new ContainerSchemaNodeBuilder(
- Draft02.RestConfModule.NAME, 0, qName, path);
- final ContainerSchemaNodeBuilder fakeOperationsSchemaNode = containerSchemaNodeBuilder;
- for (final Module module : modules) {
- final Set<RpcDefinition> rpcs = module.getRpcs();
- for (final RpcDefinition rpc : rpcs) {
- final QName rpcQName = rpc.getQName();
- final SimpleNode<Object> immutableSimpleNode = NodeFactory.<Object> createImmutableSimpleNode(rpcQName, null,
- null);
- operationsAsData.add(immutableSimpleNode);
-
- final String name = module.getName();
- final LeafSchemaNodeBuilder leafSchemaNodeBuilder = new LeafSchemaNodeBuilder(name, 0, rpcQName,
- SchemaPath.create(true, QName.create("dummy")));
- final LeafSchemaNodeBuilder fakeRpcSchemaNode = leafSchemaNodeBuilder;
- fakeRpcSchemaNode.setAugmenting(true);
-
- final EmptyType instance = EmptyType.getInstance();
- fakeRpcSchemaNode.setType(instance);
- fakeOperationsSchemaNode.addChildNode(fakeRpcSchemaNode.build());
- }
- }
-
- final CompositeNode operationsNode = NodeFactory.createImmutableCompositeNode(qName, null, operationsAsData);
- final ContainerSchemaNode schemaNode = fakeOperationsSchemaNode.build();
- return new StructuredData(operationsNode, schemaNode, mountPoint, prettyPrint);
- }
-
private Module getRestconfModule() {
final Module restconfModule = controllerContext.getRestconfModule();
if (restconfModule == null) {
}
}
- /**
- * @deprecated method will be removed for Lithium release
- * so, please use toStreamEntryNode method
- *
- * @param streamName
- * @param streamSchemaNode
- * @return
- */
- @Deprecated
- private CompositeNode toStreamCompositeNode(final String streamName, final DataSchemaNode streamSchemaNode) {
- final List<Node<?>> streamNodeValues = new ArrayList<Node<?>>();
- List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
- ((DataNodeContainer) streamSchemaNode), "name");
- final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
- streamNodeValues
- .add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null, streamName));
-
- instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
- ((DataNodeContainer) streamSchemaNode), "description");
- final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
- streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(descriptionSchemaNode.getQName(), null,
- "DESCRIPTION_PLACEHOLDER"));
-
- instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
- ((DataNodeContainer) streamSchemaNode), "replay-support");
- final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
- streamNodeValues.add(NodeFactory.<Boolean> createImmutableSimpleNode(replaySupportSchemaNode.getQName(), null,
- Boolean.valueOf(true)));
-
- instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
- ((DataNodeContainer) streamSchemaNode), "replay-log-creation-time");
- final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
- streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(),
- null, ""));
-
- instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
- ((DataNodeContainer) streamSchemaNode), "events");
- final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
- streamNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(eventsSchemaNode.getQName(), null, ""));
-
- return NodeFactory.createImmutableCompositeNode(streamSchemaNode.getQName(), null, streamNodeValues);
- }
-
- /**
- * @deprecated method will be removed for Lithium release
- * so, please use toModuleEntryNode method
- *
- * @param module
- * @param moduleSchemaNode
- * @return
- */
- @Deprecated
- private CompositeNode toModuleCompositeNode(final Module module, final DataSchemaNode moduleSchemaNode) {
- final List<Node<?>> moduleNodeValues = new ArrayList<Node<?>>();
- List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
- ((DataNodeContainer) moduleSchemaNode), "name");
- final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
- moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null,
- module.getName()));
-
- instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
- ((DataNodeContainer) moduleSchemaNode), "revision");
- final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
- final Date _revision = module.getRevision();
- moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(revisionSchemaNode.getQName(), null,
- REVISION_FORMAT.format(_revision)));
-
- instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
- ((DataNodeContainer) moduleSchemaNode), "namespace");
- final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
- moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(namespaceSchemaNode.getQName(), null,
- module.getNamespace().toString()));
-
- instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
- ((DataNodeContainer) moduleSchemaNode), "feature");
- final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
- for (final FeatureDefinition feature : module.getFeatures()) {
- moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(featureSchemaNode.getQName(), null,
- feature.getQName().getLocalName()));
- }
-
- return NodeFactory.createImmutableCompositeNode(moduleSchemaNode.getQName(), null, moduleNodeValues);
- }
-
@Override
public Object getRoot() {
return null;
// }
}
- /**
- * @deprecated method will be removed for Lithium release
- *
- * @param inputSchema
- * @param payload
- */
- @Deprecated
- private void validateInput(final DataSchemaNode inputSchema, final Node<?> payload) {
- if (inputSchema != null && payload == null) {
- // expected a non null payload
- throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
- } else if (inputSchema == null && payload != null) {
- // did not expect any input
- throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
- }
- // else
- // {
- // TODO: Validate "mandatory" and "config" values here??? Or should those be
- // those be
- // validate in a more central location inside MD-SAL core.
- // }
- }
-
private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
final ContainerNode value = (ContainerNode) payload.getData();
final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
schemaContext), resultData);
}
- private RpcExecutor resolveIdentifierInInvokeRpc(final String identifier) {
- String identifierEncoded = null;
- DOMMountPoint mountPoint = null;
- if (identifier.contains(ControllerContext.MOUNT)) {
- // mounted RPC call - look up mount instance.
- final InstanceIdentifierContext mountPointId = controllerContext.toMountPointIdentifier(identifier);
- mountPoint = mountPointId.getMountPoint();
-
- final int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
- + ControllerContext.MOUNT.length() + 1;
- final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
- identifierEncoded = remoteRpcName;
-
- } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
- final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
- + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
- throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
- } else {
- identifierEncoded = identifier;
- }
-
- final String identifierDecoded = controllerContext.urlPathArgDecode(identifierEncoded);
-
- RpcDefinition rpc = null;
- if (mountPoint == null) {
- rpc = controllerContext.getRpcDefinition(identifierDecoded);
- } else {
- rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
- }
-
- if (rpc == null) {
- throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
- }
-
- if (mountPoint == null) {
- return new BrokerRpcExecutor(rpc, broker);
- } else {
- return new MountPointRpcExecutor(rpc, mountPoint);
- }
-
- }
-
private RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
final String[] splittedIdentifier = identifierDecoded.split(":");
if (splittedIdentifier.length != 2) {
return null;
}
- /**
- * @deprecated method will be removed for Lithium release
- */
- @Deprecated
- private StructuredData callRpc(final RpcExecutor rpcExecutor, final CompositeNode payload, final boolean prettyPrint) {
- if (rpcExecutor == null) {
- throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
- }
-
- CompositeNode rpcRequest = null;
- final RpcDefinition rpc = rpcExecutor.getRpcDefinition();
- final QName rpcName = rpc.getQName();
-
- if (payload == null) {
- rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, null, null, null);
- } else {
- final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
- final List<Node<?>> input = Collections.<Node<?>> singletonList(value);
- rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, input, null, null);
- }
-
- final RpcResult<CompositeNode> rpcResult = rpcExecutor.invokeRpc(rpcRequest);
-
- checkRpcSuccessAndThrowException(rpcResult);
-
- if (rpcResult.getResult() == null) {
- return null;
- }
-
- if (rpc.getOutput() == null) {
- return null; // no output, nothing to send back.
- }
-
- return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null, prettyPrint);
- }
-
- private void checkRpcSuccessAndThrowException(final RpcResult<CompositeNode> rpcResult) {
- if (rpcResult.isSuccessful() == false) {
-
- throw new RestconfDocumentedException("The operation was not successful", null,
- rpcResult.getErrors());
- }
- }
-
@Override
public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
return new NormalizedNodeContext(iiWithData, data);
}
- @SuppressWarnings("unchecked")
- private <T extends Node<?>> T pruneDataAtDepth(final T node, final Integer depth) {
- if (depth == null) {
- return node;
- }
-
- if (node instanceof CompositeNode) {
- final ImmutableList.Builder<Node<?>> newChildNodes = ImmutableList.<Node<?>> builder();
- if (depth > 1) {
- for (final Node<?> childNode : ((CompositeNode) node).getValue()) {
- newChildNodes.add(pruneDataAtDepth(childNode, depth - 1));
- }
- }
-
- return (T) ImmutableCompositeNode.create(node.getNodeType(), newChildNodes.build());
- } else { // SimpleNode
- return node;
- }
- }
-
private Integer parseDepthParameter(final UriInfo info) {
final String param = info.getQueryParameters(false).getFirst(UriParameters.DEPTH.toString());
if (Strings.isNullOrEmpty(param) || "unbounded".equals(param)) {
}
}
- /**
- * @deprecated method will be removed for Lithium release
- *
- * @param node
- * @param identifier
- */
- @Deprecated
- private void validateTopLevelNodeName(final Node<?> node,
- final YangInstanceIdentifier identifier) {
- final String payloadName = getName(node);
- final Iterator<PathArgument> pathArguments = identifier.getReversePathArguments().iterator();
-
- //no arguments
- if (!pathArguments.hasNext()) {
- //no "data" payload
- if (!node.getNodeType().equals(NETCONF_BASE_QNAME)) {
- throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
- ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
- }
- //any arguments
- } else {
- final String identifierName = pathArguments.next().getNodeType().getLocalName();
- if (!payloadName.equals(identifierName)) {
- throw new RestconfDocumentedException("Payload name (" + payloadName
- + ") is different from identifier name (" + identifierName + ")", ErrorType.PROTOCOL,
- ErrorTag.MALFORMED_MESSAGE);
- }
- }
- }
-
/**
* Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
*
}
}
- /**
- * @deprecated method will be removed for Lithium release
- *
- * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
- *
- * @throws RestconfDocumentedException
- * if key values or key count in payload and URI isn't equal
- *
- */
- @Deprecated
- private void validateListKeysEqualityInPayloadAndUri(final InstanceIdentifierContext iiWithData,
- final CompositeNode payload) {
- if (iiWithData.getSchemaNode() instanceof ListSchemaNode) {
- final List<QName> keyDefinitions = ((ListSchemaNode) iiWithData.getSchemaNode()).getKeyDefinition();
- final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
- if (lastPathArgument instanceof NodeIdentifierWithPredicates) {
- final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument)
- .getKeyValues();
- isEqualUriAndPayloadKeyValues(uriKeyValues, payload, keyDefinitions);
- }
- }
- }
-
private void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final NormalizedNode<?, ?> payload,
final List<QName> keyDefinitions) {
for (final QName keyDefinition : keyDefinitions) {
}
}
- /**
- * @deprecated method will be removed for Lithium release
- *
- * @param uriKeyValues
- * @param payload
- * @param keyDefinitions
- */
- @Deprecated
- private void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final CompositeNode payload,
- final List<QName> keyDefinitions) {
- for (final QName keyDefinition : keyDefinitions) {
- final Object uriKeyValue = uriKeyValues.get(keyDefinition);
- // should be caught during parsing URI to InstanceIdentifier
- if (uriKeyValue == null) {
- throw new RestconfDocumentedException("Missing key " + keyDefinition + " in URI.", ErrorType.PROTOCOL,
- ErrorTag.DATA_MISSING);
- }
- final List<SimpleNode<?>> payloadKeyValues = payload.getSimpleNodesByName(keyDefinition.getLocalName());
- if (payloadKeyValues.isEmpty()) {
- throw new RestconfDocumentedException("Missing key " + keyDefinition.getLocalName()
- + " in the message body.", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
- }
-
- final Object payloadKeyValue = payloadKeyValues.iterator().next().getValue();
- if (!uriKeyValue.equals(payloadKeyValue)) {
- throw new RestconfDocumentedException("The value '" + uriKeyValue + "' for key '"
- + keyDefinition.getLocalName() + "' specified in the URI doesn't match the value '"
- + payloadKeyValue + "' specified in the message body. ", ErrorType.PROTOCOL,
- ErrorTag.INVALID_VALUE);
- }
- }
- }
-
@Override
public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
return createConfigurationData(payload, uriInfo);
return result;
}
- private Module findModule(final DOMMountPoint mountPoint, final Node<?> data) {
- Module module = null;
- if (data instanceof NodeWrapper) {
- module = findModule(mountPoint, (NodeWrapper<?>) data);
- } else if (data != null) {
- final URI namespace = data.getNodeType().getNamespace();
- if (mountPoint != null) {
- module = controllerContext.findModuleByNamespace(mountPoint, namespace);
- } else {
- module = controllerContext.findModuleByNamespace(namespace);
- }
- }
- if (module != null) {
- return module;
- }
- throw new RestconfDocumentedException(
- "Data has bad format. Root element node has incorrect namespace (XML format) or module name(JSON format)",
- ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
- }
-
- private Module findModule(final DOMMountPoint mountPoint, final NodeWrapper<?> data) {
- final URI namespace = data.getNamespace();
- Preconditions.<URI> checkNotNull(namespace);
-
- Module module = null;
- if (mountPoint != null) {
- module = controllerContext.findModuleByNamespace(mountPoint, namespace);
- if (module == null) {
- module = controllerContext.findModuleByName(mountPoint, namespace.toString());
- }
- } else {
- module = controllerContext.findModuleByNamespace(namespace);
- if (module == null) {
- module = controllerContext.findModuleByName(namespace.toString());
- }
- }
-
- return module;
- }
-
- private InstanceIdentifierContext addLastIdentifierFromData(final InstanceIdentifierContext identifierWithSchemaNode,
- final CompositeNode data, final DataSchemaNode schemaOfData, final SchemaContext schemaContext) {
- YangInstanceIdentifier instanceIdentifier = null;
- if (identifierWithSchemaNode != null) {
- instanceIdentifier = identifierWithSchemaNode.getInstanceIdentifier();
- }
-
- final YangInstanceIdentifier iiOriginal = instanceIdentifier;
- InstanceIdentifierBuilder iiBuilder = null;
- if (iiOriginal == null) {
- iiBuilder = YangInstanceIdentifier.builder();
- } else {
- iiBuilder = YangInstanceIdentifier.builder(iiOriginal);
- }
-
- if ((schemaOfData instanceof ListSchemaNode)) {
- final HashMap<QName, Object> keys = resolveKeysFromData(((ListSchemaNode) schemaOfData), data);
- iiBuilder.nodeWithKey(schemaOfData.getQName(), keys);
- } else {
- iiBuilder.node(schemaOfData.getQName());
- }
-
- final YangInstanceIdentifier instance = iiBuilder.toInstance();
- DOMMountPoint mountPoint = null;
- final SchemaContext schemaCtx = null;
- if (identifierWithSchemaNode != null) {
- mountPoint = identifierWithSchemaNode.getMountPoint();
- }
-
- return new InstanceIdentifierContext(instance, schemaOfData, mountPoint,schemaContext);
- }
-
- private HashMap<QName, Object> resolveKeysFromData(final ListSchemaNode listNode, final CompositeNode dataNode) {
- final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
- final List<QName> _keyDefinition = listNode.getKeyDefinition();
- for (final QName key : _keyDefinition) {
- SimpleNode<? extends Object> head = null;
- final String localName = key.getLocalName();
- final List<SimpleNode<? extends Object>> simpleNodesByName = dataNode.getSimpleNodesByName(localName);
- if (simpleNodesByName != null) {
- head = Iterables.getFirst(simpleNodesByName, null);
- }
-
- Object dataNodeKeyValueObject = null;
- if (head != null) {
- dataNodeKeyValueObject = head.getValue();
- }
-
- if (dataNodeKeyValueObject == null) {
- throw new RestconfDocumentedException("Data contains list \"" + dataNode.getNodeType().getLocalName()
- + "\" which does not contain key: \"" + key.getLocalName() + "\"", ErrorType.PROTOCOL,
- ErrorTag.INVALID_VALUE);
- }
-
- keyValues.put(key, dataNodeKeyValueObject);
- }
-
- return keyValues;
- }
-
private boolean endsWithMountPoint(final String identifier) {
return identifier.endsWith(ControllerContext.MOUNT) || identifier.endsWith(ControllerContext.MOUNT + "/");
}
- private boolean representsMountPointRootData(final Node<?> data) {
- final URI namespace = namespace(data);
- return (SchemaContext.NAME.getNamespace().equals(namespace) /*
- * || MOUNT_POINT_MODULE_NAME .equals( namespace .
- * toString( ) )
- */)
- && SchemaContext.NAME.getLocalName().equals(localName(data));
- }
-
private String addMountPointIdentifier(final String identifier) {
final boolean endsWith = identifier.endsWith("/");
if (endsWith) {
return identifier + "/" + ControllerContext.MOUNT;
}
- /**
- * @deprecated method will be removed in Lithium release
- * we don't wish to use Node and CompositeNode anywhere
- */
- @Deprecated
- public CompositeNode normalizeNode(final Node<?> node, final DataSchemaNode schema, final DOMMountPoint mountPoint) {
- if (schema == null) {
- final String localName = node == null ? null :
- node instanceof NodeWrapper ? ((NodeWrapper<?>)node).getLocalName() :
- node.getNodeType().getLocalName();
-
- throw new RestconfDocumentedException("Data schema node was not found for " + localName,
- ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
- }
-
- if (!(schema instanceof DataNodeContainer)) {
- throw new RestconfDocumentedException("Root element has to be container or list yang datatype.",
- ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
- }
-
- if ((node instanceof NodeWrapper<?>)) {
- NodeWrapper<?> nodeWrap = (NodeWrapper<?>) node;
- final boolean isChangeAllowed = ((NodeWrapper<?>) node).isChangeAllowed();
- if (isChangeAllowed) {
- nodeWrap = topLevelElementAsCompositeNodeWrapper((NodeWrapper<?>) node, schema);
- try {
- this.normalizeNode(nodeWrap, schema, null, mountPoint);
- } catch (final IllegalArgumentException e) {
- final RestconfDocumentedException restconfDocumentedException = new RestconfDocumentedException(e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
- restconfDocumentedException.addSuppressed(e);
- throw restconfDocumentedException;
- }
- if (nodeWrap instanceof CompositeNodeWrapper) {
- return ((CompositeNodeWrapper) nodeWrap).unwrap();
- }
- }
- }
-
- if (node instanceof CompositeNode) {
- return (CompositeNode) node;
- }
-
- throw new RestconfDocumentedException("Top level element is not interpreted as composite node.",
- ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
- }
-
- private void normalizeNode(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
- final QName previousAugment, final DOMMountPoint mountPoint) {
- if (schema == null) {
- throw new RestconfDocumentedException("Data has bad format.\n\"" + nodeBuilder.getLocalName()
- + "\" does not exist in yang schema.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
- }
-
- QName currentAugment = null;
- if (nodeBuilder.getQname() != null) {
- currentAugment = previousAugment;
- } else {
- currentAugment = normalizeNodeName(nodeBuilder, schema, previousAugment, mountPoint);
- if (nodeBuilder.getQname() == null) {
- throw new RestconfDocumentedException(
- "Data has bad format.\nIf data is in XML format then namespace for \""
- + nodeBuilder.getLocalName() + "\" should be \"" + schema.getQName().getNamespace()
- + "\".\n" + "If data is in JSON format then module name for \""
- + nodeBuilder.getLocalName() + "\" should be corresponding to namespace \""
- + schema.getQName().getNamespace() + "\".", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
- }
- }
-
- if (nodeBuilder instanceof CompositeNodeWrapper) {
- if (schema instanceof DataNodeContainer) {
- normalizeCompositeNode((CompositeNodeWrapper) nodeBuilder, (DataNodeContainer) schema, mountPoint,
- currentAugment);
- } else if (schema instanceof AnyXmlSchemaNode) {
- normalizeAnyXmlNode((CompositeNodeWrapper) nodeBuilder, (AnyXmlSchemaNode) schema);
- }
- } else if (nodeBuilder instanceof SimpleNodeWrapper) {
- normalizeSimpleNode((SimpleNodeWrapper) nodeBuilder, schema, mountPoint);
- } else if ((nodeBuilder instanceof EmptyNodeWrapper)) {
- normalizeEmptyNode((EmptyNodeWrapper) nodeBuilder, schema);
- }
- }
-
- private void normalizeAnyXmlNode(final CompositeNodeWrapper compositeNode, final AnyXmlSchemaNode schema) {
- final List<NodeWrapper<?>> children = compositeNode.getValues();
- for (final NodeWrapper<? extends Object> child : children) {
- child.setNamespace(schema.getQName().getNamespace());
- if (child instanceof CompositeNodeWrapper) {
- normalizeAnyXmlNode((CompositeNodeWrapper) child, schema);
- }
- }
- }
-
- private void normalizeEmptyNode(final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema) {
- if ((schema instanceof LeafSchemaNode)) {
- emptyNodeBuilder.setComposite(false);
- } else {
- if ((schema instanceof ContainerSchemaNode)) {
- // FIXME: Add presence check
- emptyNodeBuilder.setComposite(true);
- }
- }
- }
-
- private void normalizeSimpleNode(final SimpleNodeWrapper simpleNode, final DataSchemaNode schema,
- final DOMMountPoint mountPoint) {
- final Object value = simpleNode.getValue();
- Object inputValue = value;
- final TypeDef typeDef = this.typeDefinition(schema);
- TypeDefinition<? extends Object> typeDefinition = typeDef != null ? typeDef.typedef : null;
-
- // For leafrefs, extract the type it is pointing to
- if(typeDefinition instanceof LeafrefTypeDefinition) {
- if (schema.getQName().equals(typeDef.qName)) {
- typeDefinition = SchemaContextUtil.getBaseTypeForLeafRef(((LeafrefTypeDefinition) typeDefinition), mountPoint == null ? controllerContext.getGlobalSchema() : mountPoint.getSchemaContext(), schema);
- } else {
- typeDefinition = SchemaContextUtil.getBaseTypeForLeafRef(((LeafrefTypeDefinition) typeDefinition), mountPoint == null ? controllerContext.getGlobalSchema() : mountPoint.getSchemaContext(), typeDef.qName);
- }
- }
-
- if (typeDefinition instanceof IdentityrefTypeDefinition) {
- inputValue = parseToIdentityValuesDTO(simpleNode, value, inputValue);
- }
-
- Object outputValue = inputValue;
-
- if (typeDefinition != null) {
- final Codec<Object, Object> codec = RestCodec.from(typeDefinition, mountPoint);
- outputValue = codec == null ? null : codec.deserialize(inputValue);
- }
-
- simpleNode.setValue(outputValue);
- }
-
- private Object parseToIdentityValuesDTO(final SimpleNodeWrapper simpleNode, final Object value, Object inputValue) {
- if ((value instanceof String)) {
- inputValue = new IdentityValuesDTO(simpleNode.getNamespace().toString(), (String) value, null,
- (String) value);
- } // else value is already instance of IdentityValuesDTO
- return inputValue;
- }
-
- private void normalizeCompositeNode(final CompositeNodeWrapper compositeNodeBuilder,
- final DataNodeContainer schema, final DOMMountPoint mountPoint, final QName currentAugment) {
- final List<NodeWrapper<?>> children = compositeNodeBuilder.getValues();
- checkNodeMultiplicityAccordingToSchema(schema, children);
- for (final NodeWrapper<? extends Object> child : children) {
- final List<DataSchemaNode> potentialSchemaNodes = ControllerContext.findInstanceDataChildrenByName(
- schema, child.getLocalName());
-
- if (potentialSchemaNodes.size() > 1 && child.getNamespace() == null) {
- final StringBuilder builder = new StringBuilder();
- for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
- builder.append(" ").append(potentialSchemaNode.getQName().getNamespace().toString()).append("\n");
- }
-
- throw new RestconfDocumentedException("Node \"" + child.getLocalName()
- + "\" is added as augment from more than one module. "
- + "Therefore node must have namespace (XML format) or module name (JSON format)."
- + "\nThe node is added as augment from modules with namespaces:\n" + builder,
- ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
- }
-
- boolean rightNodeSchemaFound = false;
- for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
- if (!rightNodeSchemaFound) {
- final QName potentialCurrentAugment = normalizeNodeName(child, potentialSchemaNode,
- currentAugment, mountPoint);
- if (child.getQname() != null) {
- this.normalizeNode(child, potentialSchemaNode, potentialCurrentAugment, mountPoint);
- rightNodeSchemaFound = true;
- }
- }
- }
-
- if (!rightNodeSchemaFound) {
- throw new RestconfDocumentedException("Schema node \"" + child.getLocalName()
- + "\" was not found in module.", ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
- }
- }
-
- if ((schema instanceof ListSchemaNode)) {
- final ListSchemaNode listSchemaNode = (ListSchemaNode) schema;
- final List<QName> listKeys = listSchemaNode.getKeyDefinition();
- for (final QName listKey : listKeys) {
- boolean foundKey = false;
- for (final NodeWrapper<? extends Object> child : children) {
- if (Objects.equal(child.unwrap().getNodeType().getLocalName(), listKey.getLocalName())) {
- foundKey = true;
- }
- }
-
- if (!foundKey) {
- throw new RestconfDocumentedException("Missing key in URI \"" + listKey.getLocalName()
- + "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"", ErrorType.PROTOCOL,
- ErrorTag.DATA_MISSING);
- }
- }
- }
- }
-
- private void checkNodeMultiplicityAccordingToSchema(final DataNodeContainer dataNodeContainer,
- final List<NodeWrapper<?>> nodes) {
- final Map<String, Integer> equalNodeNamesToCounts = new HashMap<String, Integer>();
- for (final NodeWrapper<?> child : nodes) {
- Integer count = equalNodeNamesToCounts.get(child.getLocalName());
- equalNodeNamesToCounts.put(child.getLocalName(), count == null ? 1 : ++count);
- }
-
- for (final DataSchemaNode childSchemaNode : dataNodeContainer.getChildNodes()) {
- if (childSchemaNode instanceof ContainerSchemaNode || childSchemaNode instanceof LeafSchemaNode) {
- final String localName = childSchemaNode.getQName().getLocalName();
- final Integer count = equalNodeNamesToCounts.get(localName);
- if (count != null && count > 1) {
- throw new RestconfDocumentedException("Multiple input data elements were specified for '"
- + childSchemaNode.getQName().getLocalName()
- + "'. The data for this element type can only be specified once.", ErrorType.APPLICATION,
- ErrorTag.BAD_ELEMENT);
- }
- }
- }
- }
-
- private QName normalizeNodeName(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
- final QName previousAugment, final DOMMountPoint mountPoint) {
- QName validQName = schema.getQName();
- QName currentAugment = previousAugment;
- if (schema.isAugmenting()) {
- currentAugment = schema.getQName();
- } else if (previousAugment != null
- && !Objects.equal(schema.getQName().getNamespace(), previousAugment.getNamespace())) {
- validQName = QName.create(currentAugment, schema.getQName().getLocalName());
- }
-
- String moduleName = null;
- if (mountPoint == null) {
- moduleName = controllerContext.findModuleNameByNamespace(validQName.getNamespace());
- } else {
- moduleName = controllerContext.findModuleNameByNamespace(mountPoint, validQName.getNamespace());
- }
-
- if (nodeBuilder.getNamespace() == null || Objects.equal(nodeBuilder.getNamespace(), validQName.getNamespace())
- || Objects.equal(nodeBuilder.getNamespace().toString(), moduleName)) {
- /*
- * || Note : this check is wrong -
- * can never be true as it compares
- * a URI with a String not sure what
- * the intention is so commented out
- * ... Objects . equal ( nodeBuilder
- * . getNamespace ( ) ,
- * MOUNT_POINT_MODULE_NAME )
- */
-
- nodeBuilder.setQname(validQName);
- }
-
- return currentAugment;
- }
-
- private URI namespace(final Node<?> data) {
- if (data instanceof NodeWrapper) {
- return ((NodeWrapper<?>) data).getNamespace();
- } else if (data != null) {
- return data.getNodeType().getNamespace();
- } else {
- throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
- }
- }
-
- private String localName(final Node<?> data) {
- if (data instanceof NodeWrapper) {
- return ((NodeWrapper<?>) data).getLocalName();
- } else if (data != null) {
- return data.getNodeType().getLocalName();
- } else {
- throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
- }
- }
-
- /**
- * @deprecated method will be removed for Lithium release
- *
- * @param data
- * @return
- */
- @Deprecated
- private String getName(final Node<?> data) {
- if (data instanceof NodeWrapper) {
- return ((NodeWrapper<?>) data).getLocalName();
- } else if (data != null) {
- return data.getNodeType().getLocalName();
- } else {
- throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
- }
- }
-
private TypeDef typeDefinition(final TypeDefinition<?> type, final QName nodeQName) {
TypeDefinition<?> baseType = type;
QName qName = nodeQName;
}
}
- private CompositeNode datastoreNormalizedNodeToCompositeNode(final NormalizedNode<?, ?> dataNode, final DataSchemaNode schema) {
- Node<?> nodes = null;
- if (dataNode == null) {
- throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.DATA_MISSING,
- "No data was found."));
- }
- nodes = DataNormalizer.toLegacy(dataNode);
- if (nodes != null) {
- if (nodes instanceof CompositeNode) {
- return (CompositeNode) nodes;
- } else {
- LOG.error("The node " + dataNode.getNodeType() + " couldn't be transformed to compositenode.");
- }
- } else {
- LOG.error("Top level node isn't of type Container or List schema node but "
- + schema.getClass().getSimpleName());
- }
-
- throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
- "It wasn't possible to correctly interpret data."));
- }
-
- private NormalizedNode<?, ?> compositeNodeToDatastoreNormalizedNode(final CompositeNode compNode,
- final DataSchemaNode schema) {
- final List<Node<?>> lst = new ArrayList<Node<?>>();
- lst.add(compNode);
- if (schema instanceof ContainerSchemaNode) {
- return CnSnToNormalizedNodeParserFactory.getInstance().getContainerNodeParser()
- .parse(lst, (ContainerSchemaNode) schema);
- } else if (schema instanceof ListSchemaNode) {
- return CnSnToNormalizedNodeParserFactory.getInstance().getMapEntryNodeParser()
- .parse(lst, (ListSchemaNode) schema);
- }
-
- LOG.error("Top level isn't of type container, list, leaf schema node but " + schema.getClass().getSimpleName());
-
- throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
- "It wasn't possible to translate specified data to datastore readable form."));
- }
-
private InstanceIdentifierContext normalizeInstanceIdentifierWithSchemaNode(
final InstanceIdentifierContext iiWithSchemaNode) {
return normalizeInstanceIdentifierWithSchemaNode(iiWithSchemaNode, false);
return YangInstanceIdentifier.create(result);
}
- private CompositeNodeWrapper topLevelElementAsCompositeNodeWrapper(final NodeWrapper<?> node,
- final DataSchemaNode schemaNode) {
- if (node instanceof CompositeNodeWrapper) {
- return (CompositeNodeWrapper) node;
- } else if (node instanceof SimpleNodeWrapper && isDataContainerNode(schemaNode)) {
- final SimpleNodeWrapper simpleNodeWrapper = (SimpleNodeWrapper) node;
- return new CompositeNodeWrapper(namespace(simpleNodeWrapper), localName(simpleNodeWrapper));
- }
-
- throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
- "Top level element has to be composite node or has to represent data container node."));
- }
-
private boolean isDataContainerNode(final DataSchemaNode schemaNode) {
if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
return true;
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.restconf.impl;
-
-import com.google.common.base.Preconditions;
-import java.net.URI;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
-
-/**
- * @deprecated class will be removed in Lithium release
- */
-@Deprecated
-public final class SimpleNodeWrapper implements NodeWrapper<SimpleNode<?>>, SimpleNode<Object> {
-
- private SimpleNode<Object> simpleNode;
-
- private String localName;
- private Object value;
- private URI namespace;
- private QName name;
-
- public SimpleNodeWrapper(final String localName, final Object value) {
- this.localName = Preconditions.checkNotNull(localName);
- this.value = value;
- }
-
- public SimpleNodeWrapper(final URI namespace, final String localName, final Object value) {
- this(localName, value);
- this.namespace = namespace;
- }
-
- @Override
- public void setQname(final QName name) {
- Preconditions.checkState(simpleNode == null, "Cannot change the object, due to data inconsistencies.");
- this.name = name;
- }
-
- @Override
- public QName getQname() {
- return name;
- }
-
- @Override
- public String getLocalName() {
- if (simpleNode != null) {
- return simpleNode.getNodeType().getLocalName();
- }
- return localName;
- }
-
- @Override
- public URI getNamespace() {
- if (simpleNode != null) {
- return simpleNode.getNodeType().getNamespace();
- }
- return namespace;
- }
-
- @Override
- public void setNamespace(final URI namespace) {
- Preconditions.checkState(simpleNode == null, "Cannot change the object, due to data inconsistencies.");
- this.namespace = namespace;
- }
-
- @Override
- public boolean isChangeAllowed() {
- return simpleNode == null ? true : false;
- }
-
- @Override
- public SimpleNode<Object> unwrap() {
- if (simpleNode == null) {
- if (name == null) {
- Preconditions.checkNotNull(namespace);
- name = new QName(namespace, localName);
- }
- simpleNode = NodeFactory.createImmutableSimpleNode(name, null, value);
-
- value = null;
- namespace = null;
- localName = null;
- name = null;
- }
- return simpleNode;
- }
-
- @Override
- public QName getNodeType() {
- return unwrap().getNodeType();
- }
-
- @Override
- @Deprecated
- public CompositeNode getParent() {
- return unwrap().getParent();
- }
-
- @Override
- public Object getValue() {
- return unwrap().getValue();
- }
-
- @Override
- @Deprecated
- public ModifyAction getModificationAction() {
- return unwrap().getModificationAction();
- }
-
- @Override
- public MutableSimpleNode<Object> asMutable() {
- return unwrap().asMutable();
- }
-
- @Override
- public QName getKey() {
- return unwrap().getKey();
- }
-
- @Override
- public Object setValue(final Object value) {
- return unwrap().setValue(value);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.restconf.impl;
-
-import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-
-/**
- * @deprecated class will be removed in Lithium release
- */
-@Deprecated
-public class StructuredData {
-
- private final CompositeNode data;
- private final DataSchemaNode schema;
- private final DOMMountPoint mountPoint;
- private final boolean prettyPrintMode;
-
- public StructuredData(final CompositeNode data, final DataSchemaNode schema, final DOMMountPoint mountPoint) {
- this(data, schema, mountPoint, false);
- }
-
- public StructuredData(final CompositeNode data, final DataSchemaNode schema, final DOMMountPoint mountPoint,
- final boolean preattyPrintMode) {
- this.data = data;
- this.schema = schema;
- this.mountPoint = mountPoint;
- prettyPrintMode = preattyPrintMode;
- }
-
- public CompositeNode getData() {
- return data;
- }
-
- public DataSchemaNode getSchema() {
- return schema;
- }
-
- public DOMMountPoint getMountPoint() {
- return mountPoint;
- }
-
- public boolean isPrettyPrintMode() {
- return prettyPrintMode;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.restconf.rpc.impl;
-
-import java.util.concurrent.CancellationException;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
-import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
-import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
-import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
-
-public abstract class AbstractRpcExecutor implements RpcExecutor {
- private final RpcDefinition rpcDef;
-
- public AbstractRpcExecutor(RpcDefinition rpcDef) {
- this.rpcDef = rpcDef;
- }
-
- @Override
- public RpcDefinition getRpcDefinition() {
- return rpcDef;
- }
-
- @Override
- public RpcResult<CompositeNode> invokeRpc(CompositeNode rpcRequest) throws RestconfDocumentedException {
- try {
- return getRpcResult(invokeRpcUnchecked(rpcRequest));
- } catch (IllegalArgumentException e) {
- throw new RestconfDocumentedException(e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
- } catch (UnsupportedOperationException e) {
- throw new RestconfDocumentedException(e.getMessage(), ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
- } catch (RestconfDocumentedException e) {
- throw e;
- } catch (Exception e) {
- throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.", e);
- }
- }
-
- protected abstract Future<RpcResult<CompositeNode>> invokeRpcUnchecked(CompositeNode rpcRequest);
-
- protected RpcResult<CompositeNode> getRpcResult(Future<RpcResult<CompositeNode>> fromFuture) {
- try {
- return fromFuture.get();
- } catch (InterruptedException e) {
- throw new RestconfDocumentedException(
- "The operation was interrupted while executing and did not complete.", ErrorType.RPC,
- ErrorTag.PARTIAL_OPERATION);
- } catch (ExecutionException e) {
- Throwable cause = e.getCause();
- if (cause instanceof CancellationException) {
- throw new RestconfDocumentedException("The operation was cancelled while executing.", ErrorType.RPC,
- ErrorTag.PARTIAL_OPERATION);
- } else if (cause != null) {
- while (cause.getCause() != null) {
- cause = cause.getCause();
- }
-
- if (cause instanceof IllegalArgumentException) {
- throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
- ErrorTag.INVALID_VALUE);
- }
-
- throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
- cause);
- } else {
- throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
- e);
- }
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.restconf.rpc.impl;
-
-import java.util.concurrent.Future;
-import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
-
-public class BrokerRpcExecutor extends AbstractRpcExecutor {
- private final BrokerFacade broker;
-
- public BrokerRpcExecutor(final RpcDefinition rpcDef, final BrokerFacade broker) {
- super(rpcDef);
- this.broker = broker;
- }
-
- /**
- * @deprecated Method has to be removed for Lithium release
- */
- @Deprecated
- @Override
- protected Future<RpcResult<CompositeNode>> invokeRpcUnchecked(final CompositeNode rpcRequest) {
- throw new AbstractMethodError("Unsuported functionality");
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.restconf.rpc.impl;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import java.util.concurrent.Future;
-import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
-import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
-import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
-
-/**
- * Provides an implementation which invokes rpc methods via a mounted yang data model.
- *
- * @author Devin Avery
- *
- */
-public class MountPointRpcExecutor extends AbstractRpcExecutor {
- private final DOMMountPoint mountPoint;
-
- public MountPointRpcExecutor(RpcDefinition rpcDef, DOMMountPoint mountPoint) {
- super(rpcDef);
- this.mountPoint = mountPoint;
- Preconditions.checkNotNull(mountPoint, "MountInstance can not be null.");
- }
-
- @Override
- protected Future<RpcResult<CompositeNode>> invokeRpcUnchecked(CompositeNode rpcRequest) {
- Optional<RpcProvisionRegistry> service = mountPoint.getService(RpcProvisionRegistry.class);
- if (service.isPresent()) {
- return service.get().invokeRpc(getRpcDefinition().getQName(), rpcRequest);
- }
- throw new RestconfDocumentedException("Rpc service is missing.");
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.restconf.rpc.impl;
-
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
-
-public interface RpcExecutor {
-
- /**
- * @deprecated method will be removed in Lithium release
- */
- @Deprecated
- RpcResult<CompositeNode> invokeRpc(CompositeNode rpcRequest);
-
- RpcDefinition getRpcDefinition();
-}
\ No newline at end of file
import javax.xml.transform.stream.StreamResult;
import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
import org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener;
-import org.opendaylight.controller.sal.rest.impl.XmlMapper;
import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.yang.common.QName;
private static final TransformerFactory FACTORY = TransformerFactory.newInstance();
private static final Pattern RFC3339_PATTERN = Pattern.compile("(\\d\\d)(\\d\\d)$");
- private final XmlMapper xmlMapper = new XmlMapper();
private final SimpleDateFormat rfc3339 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
private final YangInstanceIdentifier path;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import java.io.IOException;
import java.io.StringReader;
import java.util.Map;
import java.util.Set;
-import javax.ws.rs.WebApplicationException;
import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
-import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
-import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
import org.opendaylight.controller.sal.restconf.impl.test.structures.Cont;
import org.opendaylight.controller.sal.restconf.impl.test.structures.Lf;
import org.opendaylight.controller.sal.restconf.impl.test.structures.LfLst;
import org.opendaylight.controller.sal.restconf.impl.test.structures.Lst;
import org.opendaylight.controller.sal.restconf.impl.test.structures.LstItem;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
dataLoad("/cnsn-to-json/simple-yang-types", 1, "simple-yang-types", "cont1");
}
- /**
- * Test of json output when as input are specified composite node with empty data + YANG file
- */
-
- @Test
- public void compositeNodeAndYangWithJsonReaderEmptyDataTest() {
- CompositeNode compositeNode = prepareCompositeNodeWithEmpties();
- TestUtils.normalizeCompositeNode(compositeNode, modules, searchedModuleName + ":" + searchedDataSchemaName);
- String jsonOutput = null;
- try {
- jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(compositeNode, modules, dataSchemaNode,
- StructuredDataToJsonProvider.INSTANCE);
- } catch (WebApplicationException | IOException e) {
- }
-
- verifyJsonOutputForEmptyData(jsonOutput);
- }
-
- /**
- * Test of json output when as input are specified xml file (no empty elements)and YANG file
- */
- @Test
- public void xmlAndYangTypesWithJsonReaderTest() {
- Node<?> node = TestUtils.readInputToCnSn("/cnsn-to-json/simple-yang-types/xml/data.xml",
- XmlToCompositeNodeProvider.INSTANCE);
- TestUtils.normalizeCompositeNode(node, modules, searchedModuleName + ":" + searchedDataSchemaName);
- String jsonOutput = null;
- try {
- jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(node, modules, dataSchemaNode,
- StructuredDataToJsonProvider.INSTANCE);
- } catch (WebApplicationException | IOException e) {
- }
-
- verifyJsonOutput(jsonOutput);
- }
-
private void verifyJsonOutputForEmptyData(final String jsonOutput) {
assertNotNull(jsonOutput);
- StringReader strReader = new StringReader(jsonOutput);
- JsonReader jReader = new JsonReader(strReader);
+ final StringReader strReader = new StringReader(jsonOutput);
+ final JsonReader jReader = new JsonReader(strReader);
String exception = null;
Cont dataFromJson = null;
try {
dataFromJson = jsonReadCont1(jReader);
- } catch (IOException e) {
+ } catch (final IOException e) {
exception = e.getMessage();
}
private void verifyJsonOutput(final String jsonOutput) {
assertNotNull(jsonOutput);
- StringReader strReader = new StringReader(jsonOutput);
- JsonReader jReader = new JsonReader(strReader);
+ final StringReader strReader = new StringReader(jsonOutput);
+ final JsonReader jReader = new JsonReader(strReader);
String exception = null;
Cont dataFromJson = null;
try {
dataFromJson = jsonReadCont1(jReader);
- } catch (IOException e) {
+ } catch (final IOException e) {
exception = e.getMessage();
}
private Cont jsonReadCont1Elements(final JsonReader jReader, final Cont redData) throws IOException {
jReader.beginObject();
while (jReader.hasNext()) {
- String keyName = jReader.nextName();
+ final String keyName = jReader.nextName();
if (keyName.equals("lf11")) {
redData.addLf(new Lf(keyName, nextValue(jReader)));
} else if (keyName.equals("lflst11")) {
lfLst = jsonReadLflstValues(jReader, lfLst);
redData.addLfLst(lfLst);
} else if (keyName.equals("lflst12")) {
- LfLst lfLst = new LfLst(keyName);
+ final LfLst lfLst = new LfLst(keyName);
jsonReadLflstValues(jReader, lfLst);
redData.addLfLst(lfLst);
} else if (keyName.equals("lst11")) {
jReader.beginArray();
while (jReader.hasNext()) {
- LstItem lstItem = jsonReadLst11Elements(jReader);
+ final LstItem lstItem = jsonReadLst11Elements(jReader);
lst.addLstItem(lstItem);
}
jReader.endArray();
}
private LstItem jsonReadLst11Elements(final JsonReader jReader) throws IOException {
- LstItem lstItem = new LstItem();
+ final LstItem lstItem = new LstItem();
jReader.beginObject();
while (jReader.hasNext()) {
- String keyName = jReader.nextName();
+ final String keyName = jReader.nextName();
if (keyName.equals("lf111")) {
lstItem.addLf(new Lf(keyName, nextValue(jReader)));
} else if (keyName.equals("lf112")) {
private Lst jsonReadLst112(final JsonReader jReader, final Lst lst) throws IOException {
jReader.beginArray();
while (jReader.hasNext()) {
- LstItem lstItem = jsonReadLst112Elements(jReader);
+ final LstItem lstItem = jsonReadLst112Elements(jReader);
lst.addLstItem(lstItem);
}
jReader.endArray();
}
private LstItem jsonReadLst112Elements(final JsonReader jReader) throws IOException {
- LstItem lstItem = new LstItem();
+ final LstItem lstItem = new LstItem();
jReader.beginObject();
if (jReader.hasNext()) {
- String keyName = jReader.nextName();
+ final String keyName = jReader.nextName();
if (keyName.equals("lf1121")) {
lstItem.addLf(new Lf(keyName, nextValue(jReader)));
}
private Lst jsonReadLst111(final JsonReader jReader, final Lst lst) throws IOException {
jReader.beginArray();
while (jReader.hasNext()) {
- LstItem lstItem = jsonReadLst111Elements(jReader);
+ final LstItem lstItem = jsonReadLst111Elements(jReader);
lst.addLstItem(lstItem);
}
jReader.endArray();
}
private LstItem jsonReadLst111Elements(final JsonReader jReader) throws IOException {
- LstItem lstItem = new LstItem();
+ final LstItem lstItem = new LstItem();
jReader.beginObject();
if (jReader.hasNext()) {
- String keyName = jReader.nextName();
+ final String keyName = jReader.nextName();
if (keyName.equals("lf1111")) {
lstItem.addLf(new Lf(keyName, nextValue(jReader)));
}
private Cont jsonReadCont111Elements(final JsonReader jReader, final Cont cont) throws IOException {
while (jReader.hasNext()) {
- String keyName = jReader.nextName();
+ final String keyName = jReader.nextName();
if (keyName.equals("lf1111")) {
cont.addLf(new Lf(keyName, nextValue(jReader)));
} else if (keyName.equals("lflst1111")) {
private Lst jsonReadLst1111(final JsonReader jReader, final Lst lst) throws IOException {
jReader.beginArray();
while (jReader.hasNext()) {
- LstItem lstItem = jsonReadLst1111Elements(jReader);
+ final LstItem lstItem = jsonReadLst1111Elements(jReader);
lst.addLstItem(lstItem);
}
jReader.endArray();
private LstItem jsonReadLst1111Elements(final JsonReader jReader) throws IOException {
jReader.beginObject();
- LstItem lstItem = new LstItem();
+ final LstItem lstItem = new LstItem();
while (jReader.hasNext()) {
- String keyName = jReader.nextName();
+ final String keyName = jReader.nextName();
if (keyName.equals("lf1111A") || keyName.equals("lf1111B")) {
lstItem.addLf(new Lf(keyName, nextValue(jReader)));
}
assertTrue(dataFromJson.getLfLsts().isEmpty());
assertTrue(dataFromJson.getConts().isEmpty());
- Map<String, Lst> lsts = dataFromJson.getLsts();
+ final Map<String, Lst> lsts = dataFromJson.getLsts();
assertEquals(1, lsts.size());
- Lst lst11 = lsts.get("lst11");
+ final Lst lst11 = lsts.get("lst11");
assertNotNull(lst11);
- Set<LstItem> lstItems = lst11.getLstItems();
+ final Set<LstItem> lstItems = lst11.getLstItems();
assertNotNull(lstItems);
LstItem lst11_1 = null;
LstItem lst11_2 = null;
LstItem lst11_3 = null;
- for (LstItem lstItem : lstItems) {
+ for (final LstItem lstItem : lstItems) {
if (lstItem.getLfs().get("lf111").getValue().equals(1)) {
lst11_1 = lstItem;
} else if (lstItem.getLfs().get("lf111").getValue().equals(2)) {
assertEquals(1, lst11_2.getConts().size());
assertEquals(1, lst11_2.getLsts().size());
- Cont lst11_2_cont111 = lst11_2.getConts().get("cont111");
+ final Cont lst11_2_cont111 = lst11_2.getConts().get("cont111");
// -cont111
assertNotNull(lst11_2_cont111);
assertTrue(lst11_3.getLsts().isEmpty());
// -cont111
- Cont lst11_3_cont111 = lst11_3.getConts().get("cont111");
+ final Cont lst11_3_cont111 = lst11_3.getConts().get("cont111");
assertEquals(0, lst11_3_cont111.getLfs().size());
assertEquals(0, lst11_3_cont111.getLfLsts().size());
assertEquals(1, lst11_3_cont111.getLsts().size());
assertTrue(lflst12.getLfs().contains(new Lf("lflst12 str3")));
assertEquals(1, dataFromJson.getLsts().size());
- Lst lst11 = dataFromJson.getLsts().get("lst11");
+ final Lst lst11 = dataFromJson.getLsts().get("lst11");
assertNotNull(lst11);
assertEquals(2, lst11.getLstItems().size());
LstItem lst11_1 = null;
LstItem lst11_2 = null;
- for (LstItem lstItem : lst11.getLstItems()) {
- Lf lf = lstItem.getLfs().get("lf111");
+ for (final LstItem lstItem : lst11.getLstItems()) {
+ final Lf lf = lstItem.getLfs().get("lf111");
if (lf != null && lf.getValue().equals(140)) {
lst11_1 = lstItem;
} else if (lf != null && lf.getValue().equals(141)) {
assertEquals(lst11_2.getLfs().get("lf112"), new Lf("lf112", "lf112 str2"));
- Cont lst11_2_cont = lst11_2.getConts().get("cont111");
+ final Cont lst11_2_cont = lst11_2.getConts().get("cont111");
assertEquals(0, lst11_2_cont.getConts().size());
assertEquals(1, lst11_2_cont.getLfLsts().size());
assertEquals(1, lst11_2_cont.getLfs().size());
assertEquals(lst11_1.getLfs().get("lf112"), new Lf("lf112", "lf112 str"));
- Cont lst11_1_cont = lst11_1.getConts().get("cont111");
+ final Cont lst11_1_cont = lst11_1.getConts().get("cont111");
assertEquals(0, lst11_1_cont.getConts().size());
assertEquals(1, lst11_1_cont.getLfLsts().size());
assertEquals(1, lst11_1_cont.getLfs().size());
private void checkLst11x(final Lst lst, final LstItem... lstItems) {
assertNotNull(lst);
- Lst requiredLst = new Lst(lst.getName());
- for (LstItem lstItem : lstItems) {
+ final Lst requiredLst = new Lst(lst.getName());
+ for (final LstItem lstItem : lstItems) {
requiredLst.addLstItem(lstItem);
}
private void checkLst1111(final Set<LstItem> lstItems, final Lf lf11, final Lf lf12, final Lf lf21, final Lf lf22) {
LstItem lst11_1_cont_lst1111_1 = null;
LstItem lst11_1_cont_lst1111_2 = null;
- for (LstItem lstItem : lstItems) {
+ for (final LstItem lstItem : lstItems) {
if (new LstItem().addLf(lf11).addLf(lf12).equals(lstItem)) {
lst11_1_cont_lst1111_1 = lstItem;
} else if (new LstItem().addLf(lf21).addLf(lf22).equals(lstItem)) {
assertNotNull(lst11_1_cont_lst1111_2);
}
- private CompositeNode prepareCompositeNodeWithEmpties() {
- MutableCompositeNode cont1 = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("cont1", "simple:yang:types", "2013-11-5"), null, null, ModifyAction.CREATE, null);
-
- // lst11_1
- MutableCompositeNode lst11_1 = NodeFactory
- .createMutableCompositeNode(TestUtils.buildQName("lst11", "simple:yang:types", "2013-11-5"), cont1,
- null, ModifyAction.CREATE, null);
- cont1.getValue().add(lst11_1);
-
- MutableSimpleNode<?> lf111_1 = NodeFactory.createMutableSimpleNode(
- TestUtils.buildQName("lf111", "simple:yang:types", "2013-11-5"), lst11_1, (short) 1,
- ModifyAction.CREATE, null);
- lst11_1.getValue().add(lf111_1);
-
- // lst111_1_1
- MutableCompositeNode lst111_1_1 = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("lst111", "simple:yang:types", "2013-11-5"), lst11_1, null, ModifyAction.CREATE,
- null);
- lst11_1.getValue().add(lst111_1_1);
- MutableSimpleNode<?> lf1111_1_1 = NodeFactory.createMutableSimpleNode(
- TestUtils.buildQName("lf1111", "simple:yang:types", "2013-11-5"), lst111_1_1, 34, ModifyAction.CREATE,
- null);
- lst111_1_1.getValue().add(lf1111_1_1);
- lst111_1_1.init();
- // :lst111_1_1
-
- // lst111_1_2
- MutableCompositeNode lst111_1_2 = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("lst111", "simple:yang:types", "2013-11-5"), lst11_1, null, ModifyAction.CREATE,
- null);
- lst11_1.getValue().add(lst111_1_2);
- MutableSimpleNode<?> lf1111_1_2 = NodeFactory.createMutableSimpleNode(
- TestUtils.buildQName("lf1111", "simple:yang:types", "2013-11-5"), lst111_1_2, 35, ModifyAction.CREATE,
- null);
- lst111_1_2.getValue().add(lf1111_1_2);
- lst111_1_2.init();
- // :lst111_1_2
-
- // lst111_1_3
- MutableCompositeNode lst111_1_3 = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("lst111", "simple:yang:types", "2013-11-5"), lst11_1, null, ModifyAction.CREATE,
- null);
- lst11_1.getValue().add(lst111_1_3);
- lst111_1_2.init();
- // :lst111_1_3
-
- // lst111_1_4
- MutableCompositeNode lst111_1_4 = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("lst111", "simple:yang:types", "2013-11-5"), lst11_1, null, ModifyAction.CREATE,
- null);
- lst11_1.getValue().add(lst111_1_4);
- lst111_1_2.init();
- // :lst111_1_4
-
- MutableCompositeNode cont111_1 = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("cont111", "simple:yang:types", "2013-11-5"), lst11_1, null, ModifyAction.CREATE,
- null);
- lst11_1.getValue().add(cont111_1);
-
- lst11_1.init();
- // :lst11_1
-
- // lst11_2
- MutableCompositeNode lst11_2 = NodeFactory
- .createMutableCompositeNode(TestUtils.buildQName("lst11", "simple:yang:types", "2013-11-5"), cont1,
- null, ModifyAction.CREATE, null);
- cont1.getValue().add(lst11_2);
-
- MutableSimpleNode<?> lf111_2 = NodeFactory.createMutableSimpleNode(
- TestUtils.buildQName("lf111", "simple:yang:types", "2013-11-5"), lst11_2, (short) 2,
- ModifyAction.CREATE, null);
- lst11_2.getValue().add(lf111_2);
-
- // cont111_2
- MutableCompositeNode cont111_2 = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("cont111", "simple:yang:types", "2013-11-5"), lst11_2, null, ModifyAction.CREATE,
- null);
- lst11_2.getValue().add(cont111_2);
-
- MutableSimpleNode<?> lflst1111_2_2 = NodeFactory.createMutableSimpleNode(
- TestUtils.buildQName("lflst1111", "simple:yang:types", "2013-11-5"), cont111_2, 1024,
- ModifyAction.CREATE, null);
- cont111_2.getValue().add(lflst1111_2_2);
- MutableSimpleNode<?> lflst1111_2_3 = NodeFactory.createMutableSimpleNode(
- TestUtils.buildQName("lflst1111", "simple:yang:types", "2013-11-5"), cont111_2, 4096,
- ModifyAction.CREATE, null);
- cont111_2.getValue().add(lflst1111_2_3);
-
- // lst1111_2
- MutableCompositeNode lst1111_2_1 = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("lst1111", "simple:yang:types", "2013-11-5"), cont111_2, null,
- ModifyAction.CREATE, null);
- cont111_2.getValue().add(lst1111_2_1);
- MutableSimpleNode<?> lf1111B_2_1 = NodeFactory.createMutableSimpleNode(
- TestUtils.buildQName("lf1111B", "simple:yang:types", "2013-11-5"), lst1111_2_1, (short) 4,
- ModifyAction.CREATE, null);
- lst1111_2_1.getValue().add(lf1111B_2_1);
- lst1111_2_1.init();
-
- MutableCompositeNode lst1111_2_2 = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("lst1111", "simple:yang:types", "2013-11-5"), cont111_2, null,
- ModifyAction.CREATE, null);
- cont111_2.getValue().add(lst1111_2_2);
- MutableSimpleNode<?> lf1111A_2_2 = NodeFactory.createMutableSimpleNode(
- TestUtils.buildQName("lf1111A", "simple:yang:types", "2013-11-5"), lst1111_2_2, "lf1111A str12",
- ModifyAction.CREATE, null);
- lst1111_2_2.getValue().add(lf1111A_2_2);
- lst1111_2_2.init();
- // :lst1111_2
-
- cont111_2.init();
- // :cont111_2
-
- MutableCompositeNode lst112_2 = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("lst112", "simple:yang:types", "2013-11-5"), lst11_2, null, ModifyAction.CREATE,
- null);
- lst11_2.getValue().add(lst112_2);
- lst112_2.init();
- lst11_2.init();
-
- // :lst11_2
-
- // lst11_3
- MutableCompositeNode lst11_3 = NodeFactory
- .createMutableCompositeNode(TestUtils.buildQName("lst11", "simple:yang:types", "2013-11-5"), cont1,
- null, ModifyAction.CREATE, null);
- cont1.getValue().add(lst11_3);
-
- MutableSimpleNode<?> lf111_3 = NodeFactory.createMutableSimpleNode(
- TestUtils.buildQName("lf111", "simple:yang:types", "2013-11-5"), lst11_3, (short) 3,
- ModifyAction.CREATE, null);
- lst11_3.getValue().add(lf111_3);
-
- // cont111_3
- MutableCompositeNode cont111_3 = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("cont111", "simple:yang:types", "2013-11-5"), lst11_3, null, ModifyAction.CREATE,
- null);
- lst11_3.getValue().add(cont111_3);
-
- MutableCompositeNode lst1111_3_1 = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("lst1111", "simple:yang:types", "2013-11-5"), cont111_3, null,
- ModifyAction.CREATE, null);
- cont111_3.getValue().add(lst1111_3_1);
- lst1111_3_1.init();
-
- MutableCompositeNode lst1111_3_2 = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("lst1111", "simple:yang:types", "2013-11-5"), cont111_3, null,
- ModifyAction.CREATE, null);
- cont111_3.getValue().add(lst1111_3_2);
- lst1111_3_2.init();
-
- cont111_3.init();
- // :cont111_3
-
- lst11_3.init();
- // :lst11_3
-
- cont1.init();
- return cont1;
- }
-
}
*/
package org.opendaylight.controller.sal.restconf.impl.cnsn.to.json.test;
-import static org.junit.Assert.assertTrue;
-
-import java.io.IOException;
-import javax.ws.rs.WebApplicationException;
import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
-import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
-import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.valid.DataValidationException;
public class CnSnJsonChoiceCaseTest extends YangAndXmlAndDataSchemaLoader {
dataLoad("/cnsn-to-json/choice");
}
- /**
- * Test when some data are in one case node and other in another. This isn't correct. Next Json validator should
- * return error because nodes has to be from one case below concrete choice.
- *
- */
- @Test(expected=DataValidationException.class)
- public void nodeSchemasOnVariousChoiceCasePathTest() {
- testWrapper("/cnsn-to-json/choice/xml/data_various_path_err.xml", "choice-case-test:cont");
- }
-
- /**
- * Test when some data are in one case node and other in another. Additionally data are loadef from various choices.
- * This isn't correct. Next Json validator should return error because nodes has to be from one case below concrete
- * choice.
- *
- */
- @Test(expected=DataValidationException.class)
- public void nodeSchemasOnVariousChoiceCasePathAndMultipleChoicesTest() {
- testWrapper("/cnsn-to-json/choice/xml/data_more_choices_same_level_various_paths_err.xml",
- "choice-case-test:cont");
- }
-
- /**
- * Test when second level data are red first, then first and at the end third level. Level represents pass through
- * couple choice-case
- */
-
- @Test
- public void nodeSchemasWithRandomOrderAccordingLevel() {
- testWrapper("/cnsn-to-json/choice/xml/data_random_level.xml", "choice-case-test:cont");
- }
-
- /**
- * Test when element from no first case is used
- */
- @Test
- public void nodeSchemasNotInFirstCase() {
- testWrapper("/cnsn-to-json/choice/xml/data_no_first_case.xml", "choice-case-test:cont");
- }
-
- /**
- * Test when element in case is list
- */
- @Test
- public void nodeSchemaAsList() {
- testWrapper("/cnsn-to-json/choice/xml/data_list.xml", "choice-case-test:cont");
- }
-
- /**
- * Test when element in case is container
- */
- @Test
- public void nodeSchemaAsContainer() {
- testWrapper("/cnsn-to-json/choice/xml/data_container.xml", "choice-case-test:cont");
- }
-
- /**
- * Test when element in case is leaflist
- */
- @Test
- public void nodeSchemaAsLeafList() {
- testWrapper("/cnsn-to-json/choice/xml/data_leaflist.xml", "choice-case-test:cont");
- }
-
- /**
- *
- */
- @Test
- public void nodeSchemasInMultipleChoicesTest() {
- testWrapper("/cnsn-to-json/choice/xml/data_more_choices_same_level.xml", "choice-case-test:cont");
- }
-
- /**
- * Test whether is possible to find data schema for node which is specified as dirrect subnode of choice (case
- * without CASE key word)
- */
- @Test
- public void nodeSchemasInCaseNotDefinedWithCaseKeyword() {
- testWrapper("/cnsn-to-json/choice/xml/data_case_defined_without_case.xml", "choice-case-test:cont");
- }
-
- /**
- * Test of multiple use of choices
- */
- @Test
- public void nodeSchemasInThreeChoicesAtSameLevel() {
- testWrapper("/cnsn-to-json/choice/xml/data_three_choices_same_level.xml", "choice-case-test:cont");
- }
-
- private void testWrapper(String xmlPath, String pathToSchemaNode) {
- Node<?> node = TestUtils.readInputToCnSn(xmlPath, XmlToCompositeNodeProvider.INSTANCE);
- TestUtils.normalizeCompositeNode(node, modules, pathToSchemaNode);
- try {
- TestUtils.writeCompNodeWithSchemaContextToOutput(node, modules, dataSchemaNode,
- StructuredDataToJsonProvider.INSTANCE);
- } catch (WebApplicationException | IOException e) {
- // shouldn't end here
- assertTrue(false);
- }
- }
}
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
-
import com.google.common.collect.Maps;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import java.io.StringReader;
import java.util.Map;
import org.junit.BeforeClass;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
-import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
-import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
-import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
-import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
-import org.opendaylight.yangtools.yang.data.api.Node;
public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader {
dataLoad("/cnsn-to-json/simple-data-types");
}
- @Test
- @Ignore
- public void simpleYangDataTest() throws Exception {
-
- final Node<?> node = TestUtils.readInputToCnSn("/cnsn-to-json/simple-data-types/xml/data.xml",
- XmlToCompositeNodeProvider.INSTANCE);
-
- TestUtils.normalizeCompositeNode(node, modules, "simple-data-types:cont");
-
- final String jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(node, modules, dataSchemaNode,
- StructuredDataToJsonProvider.INSTANCE);
-
- assertNotNull(jsonOutput);
-
- verifyJsonOutput(jsonOutput);
- }
-
private void verifyJsonOutput(final String jsonOutput) {
final StringReader strReader = new StringReader(jsonOutput);
final JsonReader jReader = new JsonReader(strReader);
jReader.endObject();
}
- @Test
- public void testBadData() throws Exception {
-
- try {
- final Node<?> node = TestUtils.readInputToCnSn("/cnsn-to-json/simple-data-types/xml/bad-data.xml",
- XmlToCompositeNodeProvider.INSTANCE);
-
- TestUtils.normalizeCompositeNode(node, modules, "simple-data-types:cont");
- fail("Expected RestconfDocumentedException");
- } catch (final RestconfDocumentedException e) {
- assertEquals("getErrorTag", ErrorTag.INVALID_VALUE, e.getErrors().get(0).getErrorTag());
- }
- }
}
*/
package org.opendaylight.controller.sal.restconf.impl.cnsn.to.json.test;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.io.IOException;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import javax.ws.rs.WebApplicationException;
import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
-import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
public class CnSnToJsonIdentityrefTest extends YangAndXmlAndDataSchemaLoader {
dataLoad("/cnsn-to-json/identityref", 2, "identityref-module", "cont");
}
- @Test
- public void identityrefToJsonTest() {
- String json = null;
- try {
- QName valueAsQname = TestUtils.buildQName("name_test", "identityref:module", "2013-12-2");
- json = TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(valueAsQname), modules,
- dataSchemaNode, StructuredDataToJsonProvider.INSTANCE);
- } catch (WebApplicationException | IOException e) {
- // shouldn't end here
- assertTrue(false);
- }
- assertNotNull(json);
- Pattern ptrn = Pattern.compile(".*\"lf1\"\\p{Space}*:\\p{Space}*\"identityref-module:name_test\".*",
- Pattern.DOTALL);
- Matcher mtch = ptrn.matcher(json);
-
- assertTrue(mtch.matches());
- }
-
- @Test
- public void identityrefToJsonWithoutQNameTest() {
- String json = null;
- try {
- String value = "not q name value";
- json = TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(value), modules,
- dataSchemaNode, StructuredDataToJsonProvider.INSTANCE);
- } catch (WebApplicationException | IOException e) {
- // shouldn't end here
- assertTrue(false);
- }
- System.out.println(json);
- assertNotNull(json);
- Pattern ptrn = Pattern.compile(".*\"lf1\"\\p{Space}*:\\p{Space}*\"not q name value\".*", Pattern.DOTALL);
- Matcher mtch = ptrn.matcher(json);
-
- assertTrue(mtch.matches());
- }
-
- private CompositeNode prepareCompositeNode(final Object value) {
- MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("cont", "identityref:module", "2013-12-2"), null, null, ModifyAction.CREATE, null);
- MutableCompositeNode cont1 = NodeFactory
- .createMutableCompositeNode(TestUtils.buildQName("cont1", "identityref:module", "2013-12-2"), cont,
- null, ModifyAction.CREATE, null);
- cont.getValue().add(cont1);
-
- MutableSimpleNode<?> lf1 = NodeFactory
- .createMutableSimpleNode(TestUtils.buildQName("lf1", "identityref:module", "2013-12-2"), cont1, value,
- ModifyAction.CREATE, null);
-
- cont1.getValue().add(lf1);
- cont1.init();
- cont.init();
-
- return cont;
- }
-
}
*/
package org.opendaylight.controller.sal.restconf.impl.cnsn.to.json.test;
-import static org.junit.Assert.assertTrue;
-
-import java.io.IOException;
import java.util.List;
import java.util.Set;
-import javax.activation.UnsupportedDataTypeException;
-import javax.ws.rs.WebApplicationException;
import org.junit.BeforeClass;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
-import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
-import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
}
- @Test
- @Ignore
- public void incorrectTopLevelElementTest() {
-
- final Node<?> node = TestUtils.readInputToCnSn("/cnsn-to-json/simple-data-types/xml/data.xml", XmlToCompositeNodeProvider.INSTANCE);
- DataSchemaNode incorrectDataSchema = null;
- incorrectDataSchema = new IncorrectDataSchema();
-
- TestUtils.normalizeCompositeNode(node, modules, "simple-data-types:cont");
-
- boolean exceptionRaised = false;
- try {
- TestUtils.writeCompNodeWithSchemaContextToOutput(node, modules, incorrectDataSchema,
- StructuredDataToJsonProvider.INSTANCE);
- } catch (final UnsupportedDataTypeException e) {
- exceptionRaised = true;
- } catch (WebApplicationException | IOException e) {
- LOG.error("WebApplicationException or IOException was raised");
- }
-
- assertTrue(exceptionRaised);
- }
-
}
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-
-import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import javax.ws.rs.WebApplicationException;
import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
-import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
-import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
-import org.opendaylight.yangtools.yang.data.api.Node;
/**
*
dataLoad("/cnsn-to-json/leafref", 2, "main-module", "cont");
}
- @Test
- public void leafrefAbsolutePathToExistingLeafTest() {
- String json = toJson("/cnsn-to-json/leafref/xml/data_absolut_ref_to_existing_leaf.xml");
- validateJson(".*\"lf3\":\\p{Blank}*\"true\".*", json);
- }
-
- @Test
- public void leafrefRelativePathToExistingLeafTest() {
- String json = toJson("/cnsn-to-json/leafref/xml/data_relativ_ref_to_existing_leaf.xml");
- validateJson(".*\"lf2\":\\p{Blank}*\"121\".*", json);
- }
-
- /**
- * Tests case when reference to not existing element is present. In this case value from single node is printed as
- * string.
- */
- @Test
- public void leafrefToNonExistingLeafTest() {
- String json = toJson("/cnsn-to-json/leafref/xml/data_ref_to_non_existing_leaf.xml");
- validateJson(".*\"lf5\":\\p{Blank}*\"137\".*", json);
- }
-
- /**
- * Tests case when non leaf element is referenced. In this case value from single node is printed as string.
- */
- @Test
- public void leafrefToNotLeafTest() {
- String json = toJson("/cnsn-to-json/leafref/xml/data_ref_to_not_leaf.xml");
- validateJson(".*\"cont-augment-module\\p{Blank}*:\\p{Blank}*lf6\":\\p{Blank}*\"44\".*", json);
- }
-
- /**
- * Tests case when leaflist element is refers to leaf.
- */
- @Test
- public void leafrefFromLeafListToLeafTest() {
- String json = toJson("/cnsn-to-json/leafref/xml/data_relativ_ref_from_leaflist_to_existing_leaf.xml");
- validateJson(
- ".*\"cont-augment-module\\p{Blank}*:\\p{Blank}*lflst1\":\\p{Blank}*.*\"345\",\\p{Space}*\"346\",\\p{Space}*\"347\".*",
- json);
- }
-
- /**
- * Tests case when leaflist element is refers to leaf.
- */
- @Test
- public void leafrefFromLeafrefToLeafrefTest() {
- String json = toJson("/cnsn-to-json/leafref/xml/data_from_leafref_to_leafref.xml");
- validateJson(".*\"cont-augment-module\\p{Blank}*:\\p{Blank}*lf7\":\\p{Blank}*\"200\".*", json);
- }
-
- private void validateJson(String regex, String value) {
+ private void validateJson(final String regex, final String value) {
assertNotNull(value);
- Pattern ptrn = Pattern.compile(regex, Pattern.DOTALL);
- Matcher mtch = ptrn.matcher(value);
+ final Pattern ptrn = Pattern.compile(regex, Pattern.DOTALL);
+ final Matcher mtch = ptrn.matcher(value);
assertTrue(mtch.matches());
}
- private String toJson(String xmlDataPath) {
- try {
- Node<?> node = TestUtils.readInputToCnSn(xmlDataPath, XmlToCompositeNodeProvider.INSTANCE);
- TestUtils.normalizeCompositeNode(node, modules, searchedModuleName + ":" + searchedDataSchemaName);
- return TestUtils.writeCompNodeWithSchemaContextToOutput(node, modules, dataSchemaNode,
- StructuredDataToJsonProvider.INSTANCE);
- } catch (WebApplicationException | IOException e) {
- }
- return "";
- }
-
}
*/
package org.opendaylight.controller.sal.restconf.impl.cnsn.to.json.test;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.opendaylight.controller.sal.restconf.impl.test.TestUtils.containsStringData;
-
-import java.io.IOException;
-import java.util.Collections;
-import javax.ws.rs.WebApplicationException;
import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
import org.opendaylight.controller.sal.restconf.impl.test.DummyType;
import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
dataLoad("/cnsn-to-json/simple-data-types");
}
- @Test
- public void incorrectTopLevelElementTest() throws WebApplicationException, IOException {
- String jsonOutput = null;
- jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(),
- Collections.<Module> emptySet(), prepareDataSchemaNode(), StructuredDataToJsonProvider.INSTANCE);
- assertNotNull(jsonOutput);
-
- // pattern for e.g. > "lf1" : "" < or >"lf1":""<
- assertTrue(containsStringData(jsonOutput, "\"lf1\"", ":", "\"\""));
- }
-
- private CompositeNode prepareCompositeNode() {
- MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("cont", "simple:uri", "2012-12-17"), null, null, ModifyAction.CREATE, null);
- MutableSimpleNode<?> lf1 = NodeFactory.createMutableSimpleNode(
- TestUtils.buildQName("lf1", "simple:uri", "2012-12-17"), cont, "any value", ModifyAction.CREATE, null);
- cont.getValue().add(lf1);
- cont.init();
- return cont;
- }
-
private DataSchemaNode prepareDataSchemaNode() {
- ContainerSchemaNodeBuilder contBuild = new ContainerSchemaNodeBuilder("module", 1, TestUtils.buildQName("cont",
+ final ContainerSchemaNodeBuilder contBuild = new ContainerSchemaNodeBuilder("module", 1, TestUtils.buildQName("cont",
"simple:uri", "2012-12-17"), SchemaPath.create(true, QName.create("dummy")));
- LeafSchemaNodeBuilder leafBuild = new LeafSchemaNodeBuilder("module", 2, TestUtils.buildQName("lf1",
+ final LeafSchemaNodeBuilder leafBuild = new LeafSchemaNodeBuilder("module", 2, TestUtils.buildQName("lf1",
"simple:uri", "2012-12-17"), SchemaPath.create(true, QName.create("dummy")));
leafBuild.setType(new DummyType());
leafBuild.setConfiguration(true);
*/
package org.opendaylight.controller.sal.restconf.impl.cnsn.to.json.test;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.opendaylight.controller.sal.restconf.impl.test.TestUtils.containsStringData;
-
-import java.io.IOException;
-import javax.ws.rs.WebApplicationException;
import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
-import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
-import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
-import org.opendaylight.yangtools.yang.data.api.Node;
public class CnSnToJsonWithAugmentTest extends YangAndXmlAndDataSchemaLoader {
dataLoad("/cnsn-to-json/augmentation", 5, "yang", "cont");
}
- /**
- * Test of json output when as input are specified composite node with empty data + YANG file
- */
- @Test
- public void augmentedElementsToJson() {
- Node<?> node = TestUtils.readInputToCnSn("/cnsn-to-json/augmentation/xml/data.xml",
- XmlToCompositeNodeProvider.INSTANCE);
- TestUtils.normalizeCompositeNode(node, modules, searchedModuleName + ":" + searchedDataSchemaName);
-
- String jsonOutput = null;
- try {
- jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(node, modules, dataSchemaNode,
- StructuredDataToJsonProvider.INSTANCE);
- } catch (WebApplicationException | IOException e) {
- }
- assertNotNull(jsonOutput);
-
- assertTrue(containsStringData(jsonOutput, "\"augment-leaf:lf2\"", ":", "\"lf2\""));
- assertTrue(containsStringData(jsonOutput, "\"augment-container:cont1\"", ":", "\\{"));
- assertTrue(containsStringData(jsonOutput, "\"augment-container:lf11\"", ":", "\"lf11\""));
- assertTrue(containsStringData(jsonOutput, "\"augment-list:lst1\"", ":", "\\["));
- assertTrue(containsStringData(jsonOutput, "\"augment-list:lf11\"", ":", "\"lf1_1\""));
- assertTrue(containsStringData(jsonOutput, "\"augment-list:lf11\"", ":", "\"lf1_2\""));
- assertTrue(containsStringData(jsonOutput, "\"augment-leaflist:lflst1\"", ":", "\\["));
- }
-}
+}
\ No newline at end of file
*/
package org.opendaylight.controller.sal.restconf.impl.cnsn.to.json.test;
-import static org.junit.Assert.assertTrue;
-
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import javax.ws.rs.WebApplicationException;
import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
-import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
public class CnSnToJsonWithDataFromSeveralModulesTest extends YangAndXmlAndDataSchemaLoader {
public static void initialize() {
dataLoad("/xml-to-cnsn/data-of-several-modules/yang", 2, "module1", "cont_m1");
}
-
- @Test
- public void dataFromSeveralModulesToJsonTest() throws WebApplicationException, IOException, URISyntaxException {
- SchemaContext schemaContext = TestUtils.loadSchemaContext(modules);
- String output = TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCnSn(), modules, schemaContext,
- StructuredDataToJsonProvider.INSTANCE);
-
- // String output =
- // String.format("\"data\" : {\n" +
- // "\t\"cont_m1\" : {\n" +
- // "\t\t\"lf1_m1\" : \"lf1 m1 value\"\n" +
- // "\t}\n" +
- // "\t\"cont_m2\" : {\n" +
- // "\t\t\"lf1_m2\" : \"lf1 m2 value\"\n" +
- // "\t}\n" +
- // "}");
-
- StringBuilder regex = new StringBuilder();
- regex.append("^");
-
- regex.append(".*\"data\"");
- regex.append(".*:");
- regex.append(".*\\{");
-
- regex.append(".*\"cont_m1\"");
- regex.append(".*:");
- regex.append(".*\\{");
- regex.append(".*\\}");
-
- regex.append(".*\"contB_m1\"");
- regex.append(".*:");
- regex.append(".*\\{");
- regex.append(".*\\}");
-
- regex.append(".*\"cont_m2\"");
- regex.append(".*:");
- regex.append(".*\\{");
- regex.append(".*\\}");
-
- regex.append(".*\"contB_m2\"");
- regex.append(".*:");
- regex.append(".*\\{");
- regex.append(".*\\}");
-
- regex.append(".*\\}");
-
- regex.append(".*");
- regex.append("$");
-
- Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
- Matcher matcher = ptrn.matcher(output);
-
- assertTrue(matcher.find());
-
- }
-
- private CompositeNode prepareCnSn() throws URISyntaxException {
- String uri1 = "module:one";
- String rev1 = "2014-01-17";
-
- MutableCompositeNode data = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("data", "urn:ietf:params:xml:ns:netconf:base:1.0", "2000-01-01"), null, null,
- null, null);
-
- MutableCompositeNode cont_m1 = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("cont_m1", uri1, rev1), data, null, null, null);
- data.getValue().add(cont_m1);
-
- MutableSimpleNode<?> lf1_m1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1_m1", uri1, rev1),
- cont_m1, "lf1 m1 value", null, null);
- cont_m1.getValue().add(lf1_m1);
- cont_m1.init();
-
- MutableCompositeNode contB_m1 = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("contB_m1", uri1, rev1), data, null, null, null);
- data.getValue().add(contB_m1);
- contB_m1.init();
-
- String uri2 = "module:two";
- String rev2 = "2014-01-17";
- MutableCompositeNode cont_m2 = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("cont_m2", uri2, rev2), data, null, null, null);
- data.getValue().add(cont_m2);
-
- MutableSimpleNode<?> lf1_m2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1_m2", uri2, rev2),
- cont_m1, "lf1 m2 value", null, null);
- cont_m2.getValue().add(lf1_m2);
- cont_m2.init();
-
- MutableCompositeNode contB_m2 = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("contB_m2", uri2, rev2), data, null, null, null);
- data.getValue().add(contB_m2);
- contB_m2.init();
-
- data.init();
- return data;
- }
-
}
*/
package org.opendaylight.controller.sal.restconf.impl.cnsn.to.xml.test;
-import static org.junit.Assert.assertNotNull;
-
-import java.io.IOException;
-import java.net.URI;
import java.net.URISyntaxException;
-import javax.ws.rs.WebApplicationException;
import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
-import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
-import org.opendaylight.controller.sal.restconf.impl.SimpleNodeWrapper;
-import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
/**
*
dataLoad("/instanceidentifier/yang", 4, "instance-identifier-module", "cont");
}
- @Test
- public void snAsYangInstanceIdentifier() throws WebApplicationException, IOException, URISyntaxException {
- CompositeNode cnSnData = prepareCnStructForYangData();
- String xmlOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(cnSnData, modules, dataSchemaNode,
- StructuredDataToXmlProvider.INSTANCE);
- assertNotNull(xmlOutput);
- }
-
- private CompositeNode prepareCnStructForYangData() throws URISyntaxException {
- CompositeNodeWrapper cont = new CompositeNodeWrapper(new URI("instance:identifier:module"), "cont");
- CompositeNodeWrapper cont1 = new CompositeNodeWrapper(new URI("augment:module"), "cont1");
- cont.addValue(cont1);
- SimpleNodeWrapper lf11 = new SimpleNodeWrapper(new URI("augment:augment:module"), "lf11", "/cont/cont1/lf12");
- SimpleNodeWrapper lf12 = new SimpleNodeWrapper(new URI("augment:augment:module"), "lf12", "lf12 value");
- cont1.addValue(lf11);
- cont1.addValue(lf12);
- cont.unwrap();
- return cont;
- }
-
}
*/
package org.opendaylight.controller.sal.restconf.impl.cnsn.to.xml.test;
-import static org.junit.Assert.assertTrue;
-
-import java.io.IOException;
-import java.util.Collections;
-import javax.ws.rs.WebApplicationException;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
import org.opendaylight.controller.sal.restconf.impl.test.DummyType;
import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
import org.slf4j.Logger;
private static final Logger LOG = LoggerFactory.getLogger(CnSnToXmlNotExistingLeafTypeTest.class);
- @Ignore
- @Test
- public void incorrectTopLevelElementTest() {
-
- boolean nullPointerExceptionRaised = false;
- try {
- TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(), Collections.<Module> emptySet(),
- prepareDataSchemaNode(), StructuredDataToXmlProvider.INSTANCE);
- } catch (WebApplicationException | IOException e) {
- LOG.error("WebApplicationException or IOException was raised");
- } catch (NullPointerException e) {
- nullPointerExceptionRaised = true;
- }
- assertTrue(nullPointerExceptionRaised);
-
- }
-
- private CompositeNode prepareCompositeNode() {
- MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("cont", "simple:uri", "2012-12-17"), null, null, ModifyAction.CREATE, null);
- MutableSimpleNode<?> lf1 = NodeFactory.createMutableSimpleNode(
- TestUtils.buildQName("lf1", "simple:uri", "2012-12-17"), cont, "any value", ModifyAction.CREATE, null);
- cont.getValue().add(lf1);
- cont.init();
- return cont;
- }
private DataSchemaNode prepareDataSchemaNode() {
- ContainerSchemaNodeBuilder contBuild = new ContainerSchemaNodeBuilder("module", 1, TestUtils.buildQName("cont",
+ final ContainerSchemaNodeBuilder contBuild = new ContainerSchemaNodeBuilder("module", 1, TestUtils.buildQName("cont",
"simple:uri", "2012-12-17"), null);
- LeafSchemaNodeBuilder leafBuild = new LeafSchemaNodeBuilder("module", 2, TestUtils.buildQName("lf1",
+ final LeafSchemaNodeBuilder leafBuild = new LeafSchemaNodeBuilder("module", 2, TestUtils.buildQName("lf1",
"simple:uri", "2012-12-17"), null);
leafBuild.setType(new DummyType());
leafBuild.setConfiguration(true);
*/
package org.opendaylight.controller.sal.restconf.impl.cnsn.to.xml.test;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.Lists;
-import java.io.IOException;
-import java.util.List;
-import javax.ws.rs.WebApplicationException;
-import javax.xml.transform.TransformerFactoryConfigurationError;
import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
-import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
-import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
-import org.opendaylight.yangtools.yang.model.util.BinaryType;
-import org.opendaylight.yangtools.yang.model.util.BitsType;
-import org.opendaylight.yangtools.yang.model.util.BooleanType;
-import org.opendaylight.yangtools.yang.model.util.EmptyType;
-import org.opendaylight.yangtools.yang.model.util.EnumerationType;
-import org.opendaylight.yangtools.yang.model.util.Int16;
-import org.opendaylight.yangtools.yang.model.util.Int32;
-import org.opendaylight.yangtools.yang.model.util.Int64;
-import org.opendaylight.yangtools.yang.model.util.Int8;
-import org.opendaylight.yangtools.yang.model.util.StringType;
-import org.opendaylight.yangtools.yang.model.util.Uint16;
-import org.opendaylight.yangtools.yang.model.util.Uint32;
-import org.opendaylight.yangtools.yang.model.util.Uint64;
-import org.opendaylight.yangtools.yang.model.util.Uint8;
-import org.opendaylight.yangtools.yang.model.util.UnionType;
/**
*
dataLoad("/cnsn-to-xml/yang", 2, "basic-module", "cont");
}
- @Test
- public void snAsYangIdentityrefToXMLTest() {
- serializeToXml(prepareIdentityrefData(null, true), "<lf11 xmlns:x=\"referenced:module\">x:iden</lf11>");
- }
-
- @Test
- public void snAsYangIdentityrefWithQNamePrefixToXMLTest() {
- serializeToXml(prepareIdentityrefData("prefix", true),
- "<lf11 xmlns","=\"referenced:module\">",":iden</lf11>");
- }
-
- @Test
- public void snAsYangIdentityrefWithPrefixToXMLTest() {
- serializeToXml(prepareIdentityrefData("prefix", false), "<lf11>no qname value</lf11>");
- }
-
- @Test
- public void snAsYangLeafrefWithPrefixToXMLTest() {
- serializeToXml(prepareLeafrefData(), "<lfBoolean>true</lfBoolean>", "<lfLfref>true</lfLfref>");
- }
-
- @Test
- public void snAsYangStringToXmlTest() {
- serializeToXml(
- prepareCnStructForYangData(
- TypeDefinitionAwareCodec.from(StringType.getInstance()).deserialize("lfStr value"), "lfStr"),
- "<lfStr>lfStr value</lfStr>");
- }
-
- @Test
- public void snAsYangInt8ToXmlTest() {
- final String elName = "lfInt8";
- serializeToXml(
- prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int8.getInstance()).deserialize("14"), elName),
- "<" + elName + ">14</" + elName + ">");
- }
-
- @Test
- public void snAsYangInt16ToXmlTest() {
- final String elName = "lfInt16";
- serializeToXml(
- prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int16.getInstance()).deserialize("3000"),
- elName), "<" + elName + ">3000</" + elName + ">");
- }
-
- @Test
- public void snAsYangInt32ToXmlTest() {
- final String elName = "lfInt32";
- serializeToXml(
- prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int32.getInstance()).deserialize("201234"),
- elName), "<" + elName + ">201234</" + elName + ">");
- }
-
- @Test
- public void snAsYangInt64ToXmlTest() {
- final String elName = "lfInt64";
- serializeToXml(
- prepareCnStructForYangData(
- TypeDefinitionAwareCodec.from(Int64.getInstance()).deserialize("5123456789"), elName), "<"
- + elName + ">5123456789</" + elName + ">");
- }
-
- @Test
- public void snAsYangUint8ToXmlTest() {
- final String elName = "lfUint8";
- serializeToXml(
- prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint8.getInstance()).deserialize("200"),
- elName), "<" + elName + ">200</" + elName + ">");
- }
-
- @Test
- public void snAsYangUint16ToXmlTest() {
- final String elName = "lfUint16";
- serializeToXml(
- prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint16.getInstance()).deserialize("4000"),
- elName), "<" + elName + ">4000</" + elName + ">");
- }
-
- @Test
- public void snAsYangUint32ToXmlTest() {
- final String elName = "lfUint32";
- serializeToXml(
- prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint32.getInstance())
- .deserialize("4123456789"), elName), "<" + elName + ">4123456789</" + elName + ">");
- }
-
- @Test
- public void snAsYangUint64ToXmlTest() {
- final String elName = "lfUint64";
- serializeToXml(
- prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint64.getInstance())
- .deserialize("5123456789"), elName), "<" + elName + ">5123456789</" + elName + ">");
- }
-
- @Test
- public void snAsYangBinaryToXmlTest() {
- final String elName = "lfBinary";
- serializeToXml(
- prepareCnStructForYangData(
- TypeDefinitionAwareCodec.from(BinaryType.getInstance()).deserialize(
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567"), elName), "<" + elName
- + ">ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567</" + elName + ">");
- }
-
- @Test
- public void snAsYangBitsToXmlTest() {
- final BitsTypeDefinition.Bit mockBit1 = mock(BitsTypeDefinition.Bit.class);
- when(mockBit1.getName()).thenReturn("one");
- final BitsTypeDefinition.Bit mockBit2 = mock(BitsTypeDefinition.Bit.class);
- when(mockBit2.getName()).thenReturn("two");
- final List<BitsTypeDefinition.Bit> bitList = Lists.newArrayList(mockBit1, mockBit2);
-
- final String elName = "lfBits";
- serializeToXml(
- prepareCnStructForYangData(
- TypeDefinitionAwareCodec.from(BitsType.create(mock(SchemaPath.class), bitList)).deserialize(
- "one two"), elName), "<" + elName + ">one two</" + elName + ">", "<" + elName
- + ">two one</" + elName + ">");
- }
-
- @Test
- public void snAsYangEnumerationToXmlTest() {
- final EnumTypeDefinition.EnumPair mockEnum = mock(EnumTypeDefinition.EnumPair.class);
- when(mockEnum.getName()).thenReturn("enum2");
- final List<EnumPair> enumList = Lists.newArrayList(mockEnum);
-
- final String elName = "lfEnumeration";
- serializeToXml(
- prepareCnStructForYangData(
- TypeDefinitionAwareCodec.from(
- EnumerationType.create(mock(SchemaPath.class), enumList,
- Optional.<EnumTypeDefinition.EnumPair> absent())).deserialize("enum2"), elName),
- "<" + elName + ">enum2</" + elName + ">");
- }
-
- @Test
- public void snAsYangEmptyToXmlTest() {
- final String elName = "lfEmpty";
- serializeToXml(
- prepareCnStructForYangData(TypeDefinitionAwareCodec.from(EmptyType.getInstance()).deserialize(null),
- elName), "<" + elName + "/>");
- }
-
- @Test
- public void snAsYangBooleanToXmlTest() {
- final String elName = "lfBoolean";
- serializeToXml(
- prepareCnStructForYangData(TypeDefinitionAwareCodec.from(BooleanType.getInstance()).deserialize("str"),
- elName), "<" + elName + ">false</" + elName + ">");
- serializeToXml(
- prepareCnStructForYangData(
- TypeDefinitionAwareCodec.from(BooleanType.getInstance()).deserialize("true"), elName), "<"
- + elName + ">true</" + elName + ">");
- }
-
- @Test
- public void snAsYangUnionToXmlTest() {
-
- final BitsTypeDefinition.Bit mockBit1 = mock(BitsTypeDefinition.Bit.class);
- when(mockBit1.getName()).thenReturn("first");
- final BitsTypeDefinition.Bit mockBit2 = mock(BitsTypeDefinition.Bit.class);
- when(mockBit2.getName()).thenReturn("second");
- final List<BitsTypeDefinition.Bit> bitList = Lists.newArrayList(mockBit1, mockBit2);
-
- final List<TypeDefinition<?>> types = Lists.<TypeDefinition<?>> newArrayList(Int8.getInstance(),
- BitsType.create(mock(SchemaPath.class), bitList), BooleanType.getInstance());
- final UnionType unionType = UnionType.create(types);
-
- final String elName = "lfUnion";
- final String int8 = "15";
- serializeToXml(prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(int8), elName),
- "<" + elName + ">15</" + elName + ">");
-
- final String bits = "first second";
- serializeToXml(prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(bits), elName),
- "<" + elName + ">first second</" + elName + ">");
-
- final String bool = "str";
- serializeToXml(prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(bool), elName),
- "<" + elName + ">str</" + elName + ">");
- }
-
- private void serializeToXml(final CompositeNode compositeNode, final String... xmlRepresentation)
- throws TransformerFactoryConfigurationError {
- String xmlString = "";
- try {
- xmlString = TestUtils.writeCompNodeWithSchemaContextToOutput(compositeNode, modules, dataSchemaNode,
- StructuredDataToXmlProvider.INSTANCE);
- } catch (WebApplicationException | IOException e) {
- }
- assertNotNull(xmlString);
- boolean containSearchedStr = false;
- String strRepresentation = "";
- for (final String searchedStr : xmlRepresentation) {
- if (xmlString.contains(searchedStr)) {
- containSearchedStr = true;
- break;
- }
- strRepresentation = strRepresentation + "[" + searchedStr + "]";
- }
- assertTrue("At least one of specified strings " + strRepresentation + " wasn't found.", containSearchedStr);
-
- }
-
- private CompositeNode prepareIdentityrefData(final String prefix, final boolean valueAsQName) {
- final MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("cont", "basic:module", "2013-12-2"), null, null, ModifyAction.CREATE, null);
- final MutableCompositeNode cont1 = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("cont1", "basic:module", "2013-12-2"), cont, null, ModifyAction.CREATE, null);
- cont.getValue().add(cont1);
-
- Object value = null;
- if (valueAsQName) {
- value = TestUtils.buildQName("iden", "referenced:module", "2013-12-2", prefix);
- } else {
- value = "no qname value";
- }
- final MutableSimpleNode<Object> lf11 = NodeFactory.createMutableSimpleNode(
- TestUtils.buildQName("lf11", "basic:module", "2013-12-2"), cont1, value, ModifyAction.CREATE, null);
- cont1.getValue().add(lf11);
- cont1.init();
- cont.init();
-
- return cont;
- }
-
- private CompositeNode prepareCnStructForYangData(final Object data, final String leafName) {
- final MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(
- TestUtils.buildQName("cont", "basic:module", "2013-12-2"), null, null, ModifyAction.CREATE, null);
-
- final MutableSimpleNode<Object> lf1 = NodeFactory.createMutableSimpleNode(
- TestUtils.buildQName(leafName, "basic:module", "2013-12-2"), cont, data, ModifyAction.CREATE, null);
- cont.getValue().add(lf1);
- cont.init();
-
- return cont;
- }
-
- private CompositeNode prepareLeafrefData() {
- final MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont"), null, null,
- ModifyAction.CREATE, null);
-
- final MutableSimpleNode<Object> lfBoolean = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfBoolean"),
- cont, Boolean.TRUE, ModifyAction.CREATE, null);
- final MutableSimpleNode<Object> lfLfref = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lfLfref"), cont,
- "true", ModifyAction.CREATE, null);
- cont.getValue().add(lfBoolean);
- cont.getValue().add(lfLfref);
- cont.init();
-
- return cont;
- }
-
-}
+}
\ No newline at end of file
*/
package org.opendaylight.controller.sal.restconf.impl.cnsn.to.xml.test;
-import static org.junit.Assert.assertTrue;
-
-import java.io.IOException;
-import javax.ws.rs.WebApplicationException;
import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
-import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
/**
*
dataLoad("/cnsn-to-xml/choice", 1, "module-with-choice", "cont");
}
- @Test
- public void cnSnToXmlWithYangChoice() {
- String xmlOutput = "";
- try {
- xmlOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(
- prepareCnStructForYangData("lf1", "String data1"), modules, dataSchemaNode,
- StructuredDataToXmlProvider.INSTANCE);
- } catch (WebApplicationException | IOException e) {
- }
-
- assertTrue(xmlOutput.contains("<lf1>String data1</lf1>"));
-
- try {
- xmlOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(
- prepareCnStructForYangData("lf2", "String data2"), modules, dataSchemaNode,
- StructuredDataToXmlProvider.INSTANCE);
- } catch (WebApplicationException | IOException e) {
- }
- assertTrue(xmlOutput.contains("<lf2>String data2</lf2>"));
-
- }
-
- private CompositeNode prepareCnStructForYangData(final String lfName, final Object data) {
- MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont"), null, null,
- ModifyAction.CREATE, null);
-
- MutableSimpleNode<Object> lf1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName(lfName), cont, data,
- ModifyAction.CREATE, null);
- cont.getValue().add(lf1);
- cont.init();
-
- return cont;
- }
-
}
*/
package org.opendaylight.controller.sal.restconf.impl.cnsn.to.xml.test;
-import static org.junit.Assert.assertTrue;
-
-import java.io.IOException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import javax.ws.rs.WebApplicationException;
import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
-import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
-import org.opendaylight.controller.sal.restconf.impl.SimpleNodeWrapper;
-import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
public class CnSnToXmlWithDataFromSeveralModulesTest extends YangAndXmlAndDataSchemaLoader {
dataLoad("/xml-to-cnsn/data-of-several-modules/yang", 2, "module1", "cont_m1");
}
- @Test
- public void dataFromSeveralModulesToXmlTest() throws WebApplicationException, IOException, URISyntaxException {
- SchemaContext schemaContext = TestUtils.loadSchemaContext(modules);
- String output = TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCnSn(), modules, schemaContext,
- StructuredDataToXmlProvider.INSTANCE);
-
- // String output =
- // String.format("<data>" +
- // "\n<cont_m1>" +
- // "\n\t<lf1_m1>" +
- // "\n\t\tlf1 m1 value" +
- // "\n\t</lf1_m1>" +
- // "\n</cont_m1>" +
- // "\n<cont_m2>" +
- // "\n\t<lf1_m2>" +
- // "\n\t\tlf1 m2 value" +
- // "\n\t</lf1_m2>" +
- // "\n</cont_m2>" +
- // "\n</data>");
-
- StringBuilder regex = new StringBuilder();
- regex.append("^");
-
- regex.append(".*<data.*");
- regex.append(".*xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"");
- regex.append(".*>");
-
- regex.append(".*<contB_m1.*\\/>");
- regex.append(".*xmlns=\"module:one\"");
- regex.append(".*>");
- regex.append(".*<lf1_m1.*>");
- regex.append(".*<\\/lf1_m1>");
- regex.append(".*<\\/cont_m1>");
-
- regex.append(".*<contB_m2.*/>");
- regex.append(".*<cont_m2.*");
- regex.append(".*xmlns=\"module:two\"");
- regex.append(".*>");
- regex.append(".*<lf1_m2.*>");
- regex.append(".*<\\/lf1_m2>");
- regex.append(".*<\\/cont_m2>");
-
- regex.append(".*<\\/data.*>");
-
- regex.append(".*");
- regex.append("$");
-
- Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
- Matcher matcher = ptrn.matcher(output);
-
- assertTrue(matcher.find());
-
- }
-
- private CompositeNode prepareCnSn() throws URISyntaxException {
- CompositeNodeWrapper data = new CompositeNodeWrapper(new URI("urn:ietf:params:xml:ns:netconf:base:1.0"), "data");
-
- URI uriModule1 = new URI("module:one");
- CompositeNodeWrapper cont_m1 = new CompositeNodeWrapper(uriModule1, "cont_m1");
- SimpleNodeWrapper lf1_m1 = new SimpleNodeWrapper(uriModule1, "lf1_m1", "lf1 m1 value");
- cont_m1.addValue(lf1_m1);
- CompositeNodeWrapper contB_m1 = new CompositeNodeWrapper(uriModule1, "contB_m1");
-
- data.addValue(contB_m1);
- data.addValue(cont_m1);
-
- URI uriModule2 = new URI("module:two");
- CompositeNodeWrapper cont_m2 = new CompositeNodeWrapper(uriModule2, "cont_m2");
- SimpleNodeWrapper lf1_m2 = new SimpleNodeWrapper(uriModule2, "lf1_m2", "lf1 m2 value");
- cont_m2.addValue(lf1_m2);
- CompositeNodeWrapper contB_m2 = new CompositeNodeWrapper(uriModule2, "contB_m2");
- data.addValue(contB_m2);
- data.addValue(cont_m2);
- return data;
- }
-
}
*/
package org.opendaylight.controller.sal.restconf.impl.json.to.cnsn.test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.List;
import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
-import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
public class JsonIdentityrefToCnSnTest extends YangAndXmlAndDataSchemaLoader {
dataLoad("/json-to-cnsn/identityref", 2, "identityref-module", "cont");
}
- @Test
- public void jsonIdentityrefToCompositeNode() {
- Node<?> node = TestUtils.readInputToCnSn("/json-to-cnsn/identityref/json/data.json", false,
- JsonToCompositeNodeProvider.INSTANCE);
- assertNotNull(node);
-
- TestUtils.normalizeCompositeNode(node, modules, searchedModuleName + ":" + searchedDataSchemaName);
-
- assertEquals("cont", node.getNodeType().getLocalName());
-
- assert(node instanceof CompositeNode);
- List<Node<?>> childs = ((CompositeNode)node).getValue();
- assertEquals(1, childs.size());
- Node<?> nd = childs.iterator().next();
- assertTrue(nd instanceof CompositeNode);
- assertEquals("cont1", nd.getNodeType().getLocalName());
-
- childs = ((CompositeNode) nd).getValue();
- assertEquals(4, childs.size());
- SimpleNode<?> lf11 = null;
- SimpleNode<?> lf12 = null;
- SimpleNode<?> lf13 = null;
- SimpleNode<?> lf14 = null;
- for (Node<?> child : childs) {
- assertTrue(child instanceof SimpleNode);
- if (child.getNodeType().getLocalName().equals("lf11")) {
- lf11 = (SimpleNode<?>) child;
- } else if (child.getNodeType().getLocalName().equals("lf12")) {
- lf12 = (SimpleNode<?>) child;
- } else if (child.getNodeType().getLocalName().equals("lf13")) {
- lf13 = (SimpleNode<?>) child;
- } else if (child.getNodeType().getLocalName().equals("lf14")) {
- lf14 = (SimpleNode<?>) child;
- }
- }
-
- assertTrue(lf11.getValue() instanceof QName);
- assertEquals("iden", ((QName) lf11.getValue()).getLocalName());
- assertEquals("identity:module", ((QName) lf11.getValue()).getNamespace().toString());
-
- assertTrue(lf12.getValue() instanceof QName);
- assertEquals("iden_local", ((QName) lf12.getValue()).getLocalName());
- assertEquals("identityref:module", ((QName) lf12.getValue()).getNamespace().toString());
-
- assertTrue(lf13.getValue() instanceof QName);
- assertEquals("iden_local", ((QName) lf13.getValue()).getLocalName());
- assertEquals("identityref:module", ((QName) lf13.getValue()).getNamespace().toString());
-
- assertTrue(lf14.getValue() instanceof QName);
- assertEquals("iden_local", ((QName) lf14.getValue()).getLocalName());
- assertEquals("identity:module", ((QName) lf14.getValue()).getNamespace().toString());
- }
-
}
*/
package org.opendaylight.controller.sal.restconf.impl.json.to.cnsn.test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
-import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
public class JsonLeafrefToCnSnTest extends YangAndXmlAndDataSchemaLoader {
dataLoad("/json-to-cnsn/leafref",2,"leafref-module","cont");
}
- /**
- * JSON values which represents leafref are always loaded to simple node as string
- */
- @Test
- public void jsonIdentityrefToCompositeNode() {
- Node<?> node = TestUtils.readInputToCnSn("/json-to-cnsn/leafref/json/data.json", false,
- JsonToCompositeNodeProvider.INSTANCE);
- assertNotNull(node);
- TestUtils.normalizeCompositeNode(node, modules, searchedModuleName + ":" + searchedDataSchemaName);
-
- assertEquals("cont", node.getNodeType().getLocalName());
-
- SimpleNode<?> lf2 = null;
- assertTrue(node instanceof CompositeNode);
- for (Node<?> childNode : ((CompositeNode) node).getValue()) {
- if (childNode instanceof SimpleNode) {
- if (childNode.getNodeType().getLocalName().equals("lf2")) {
- lf2 = (SimpleNode<?>) childNode;
- break;
- }
- }
- }
-
- assertNotNull(lf2);
- assertEquals(121, lf2.getValue());
- }
-
}
*/
package org.opendaylight.controller.sal.restconf.impl.json.to.cnsn.test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
-import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
-import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
-import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JsonToCnSnTest {
private static final Logger LOG = LoggerFactory.getLogger(JsonToCnSnTest.class);
-
- @Test
- public void simpleListTest() {
- simpleTest("/json-to-cnsn/simple-list.json", "/json-to-cnsn/simple-list-yang/1", "lst", "simple:list:yang1",
- "simple-list-yang1");
- }
-
- @Test
- public void simpleContainerTest() {
- simpleTest("/json-to-cnsn/simple-container.json", "/json-to-cnsn/simple-container-yang", "cont",
- "simple:container:yang", "simple-container-yang");
- }
-
- /**
- * test if for every leaf list item is simple node instance created
- */
- @Test
- public void multipleItemsInLeafList() {
- Node<?> node = TestUtils.readInputToCnSn("/json-to-cnsn/multiple-leaflist-items.json", true,
- JsonToCompositeNodeProvider.INSTANCE);
- assertNotNull(node);
- assertTrue(node instanceof CompositeNode);
- CompositeNode compositeNode = (CompositeNode)node;
- assertEquals(3, compositeNode.getValue().size());
-
- boolean lflst1_1 = false;
- boolean lflst1_2 = false;
- boolean lflst1_3 = false;
-
- for (Node<?> nd : compositeNode.getValue()) {
- assertEquals("lflst1", nd.getNodeType().getLocalName());
- assertTrue(nd instanceof SimpleNode<?>);
- SimpleNode<?> simpleNode = (SimpleNode<?>) nd;
- if (simpleNode.getValue().equals("45")) {
- lflst1_1 = true;
- } else if (simpleNode.getValue().equals("55")) {
- lflst1_2 = true;
- } else if (simpleNode.getValue().equals("66")) {
- lflst1_3 = true;
- }
- }
-
- assertTrue(lflst1_1);
- assertTrue(lflst1_2);
- assertTrue(lflst1_3);
-
- }
-
- /**
- * List contains 4 items and in every item are other elements. It is supposed that there should be: lf11, lflst11,
- * cont11, lst11
- */
- @Test
- public void multipleItemsInListTest() {
- Node<?> node = TestUtils.readInputToCnSn("/json-to-cnsn/multiple-items-in-list.json", true,
- JsonToCompositeNodeProvider.INSTANCE);
-
- assertTrue(node instanceof CompositeNode);
- CompositeNode compositeNode = (CompositeNode)node;
-
- assertNotNull(compositeNode);
- assertEquals("lst", compositeNode.getNodeType().getLocalName());
-
- verityMultipleItemsInList(compositeNode);
- }
-
- @Test
- public void nullArrayToSimpleNodeWithNullValueTest() {
- Node<?> node = TestUtils.readInputToCnSn("/json-to-cnsn/array-with-null.json", true,
- JsonToCompositeNodeProvider.INSTANCE);
- assertTrue(node instanceof CompositeNode);
- CompositeNode compositeNode = (CompositeNode)node;
- assertEquals("cont", compositeNode.getNodeType().getLocalName());
-
- assertNotNull(compositeNode.getValue());
- assertEquals(1, compositeNode.getValue().size());
- Node<?> lfNode = compositeNode.getValue().iterator().next();
-
- assertTrue(lfNode instanceof SimpleNode<?>);
- assertEquals(null, ((SimpleNode<?>) lfNode).getValue());
-
- }
-
- @Test
- public void incorrectTopLevelElementsTest() {
- RestconfDocumentedException cause1 = null;
- try {
- TestUtils
- .readInputToCnSn("/json-to-cnsn/wrong-top-level1.json", true, JsonToCompositeNodeProvider.INSTANCE);
- } catch (RestconfDocumentedException e) {
- cause1 = e;
- }
-
- assertNotNull(cause1);
- assertTrue(cause1
- .getErrors()
- .get(0)
- .getErrorMessage()
- .contains(
- "First element in Json Object has to be \"Object\" or \"Array with one Object element\". Other scenarios are not supported yet."));
-
- RestconfDocumentedException cause2 = null;
- try {
- TestUtils
- .readInputToCnSn("/json-to-cnsn/wrong-top-level2.json", true, JsonToCompositeNodeProvider.INSTANCE);
- } catch (RestconfDocumentedException e) {
- cause2 = e;
- }
- assertNotNull(cause2);
- assertTrue(cause2.getErrors().get(0).getErrorMessage().contains("Json Object should contain one element"));
-
- RestconfDocumentedException cause3 = null;
- try {
- TestUtils
-
- .readInputToCnSn("/json-to-cnsn/wrong-top-level3.json", true, JsonToCompositeNodeProvider.INSTANCE);
- } catch (RestconfDocumentedException e) {
- cause3 = e;
- }
- assertNotNull(cause3);
- assertTrue(cause3
- .getErrors()
- .get(0)
- .getErrorMessage()
- .contains(
- "First element in Json Object has to be \"Object\" or \"Array with one Object element\". Other scenarios are not supported yet."));
-
- }
-
- /**
- * if leaf list with no data is in json then no corresponding data is created in composite node. if leaf with no
- * data then exception is raised
- */
- @Test
- public void emptyDataReadTest() {
- Node<?> node = TestUtils.readInputToCnSn("/json-to-cnsn/empty-data.json", true,
- JsonToCompositeNodeProvider.INSTANCE);
- assertTrue(node instanceof CompositeNode);
- CompositeNode compositeNode = (CompositeNode)node;
-
- assertEquals("cont", compositeNode.getNodeType().getLocalName());
- assertTrue(compositeNode instanceof CompositeNode);
- List<Node<?>> children = compositeNode.getValue();
- assertEquals(1, children.size());
- assertEquals("lflst2", children.get(0).getNodeType().getLocalName());
- assertEquals("45", children.get(0).getValue());
-
- String reason = null;
- try {
- TestUtils.readInputToCnSn("/json-to-cnsn/empty-data1.json", true, JsonToCompositeNodeProvider.INSTANCE);
- } catch (RestconfDocumentedException e) {
- reason = e.getErrors().get(0).getErrorMessage();
- }
-
- assertTrue(reason.contains("Expected value at line"));
-
- }
-
- @Test
- public void testJsonBlankInput() throws Exception {
- InputStream inputStream = new ByteArrayInputStream("".getBytes());
- Node<?> node =
- JsonToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null, inputStream);
- assertNull( node );
- }
-
- /**
- * Tests whether namespace <b>stay unchanged</b> if concrete values are present in composite or simple node and if
- * the method for update is called.
- *
- */
- @Test
- public void notSupplyNamespaceIfAlreadySupplied() {
-
- Node<?> node = TestUtils.readInputToCnSn("/json-to-cnsn/simple-list.json", false,
- JsonToCompositeNodeProvider.INSTANCE);
- assertTrue(node instanceof CompositeNode);
- CompositeNode compositeNode = (CompositeNode)node;
-
- // supplement namespaces according to first data schema -
- // "simple:data:types1"
- Set<Module> modules1 = new HashSet<>();
- Set<Module> modules2 = new HashSet<>();
- modules1 = TestUtils.loadModulesFrom("/json-to-cnsn/simple-list-yang/1");
- modules2 = TestUtils.loadModulesFrom("/json-to-cnsn/simple-list-yang/2");
- assertNotNull(modules1);
- assertNotNull(modules2);
-
- TestUtils.normalizeCompositeNode(compositeNode, modules1, "simple-list-yang1:lst");
-
- assertTrue(compositeNode instanceof CompositeNodeWrapper);
- CompositeNode compNode = ((CompositeNodeWrapper) compositeNode).unwrap();
-
- assertEquals("lst", compNode.getNodeType().getLocalName());
- verifyCompositeNode(compNode, "simple:list:yang1");
-
- try {
- TestUtils.normalizeCompositeNode(compositeNode, modules2, "simple-list-yang2:lst");
- fail("Conversion to normalized node shouldn't be successfull because of different namespaces");
- } catch (IllegalStateException e) {
- }
-// veryfing has still meaning. despite exception, first phase where normalization of NodeWrappers is called passed successfuly.
- verifyCompositeNode(compNode, "simple:list:yang1");
- }
-
- @Test
- public void jsonIdentityrefToCompositeNode() {
- Node<?> node = TestUtils.readInputToCnSn("/json-to-cnsn/identityref/json/data.json", false,
- JsonToCompositeNodeProvider.INSTANCE);
- assertTrue(node instanceof CompositeNode);
- CompositeNode compositeNode = (CompositeNode)node;
-
- Set<Module> modules = TestUtils.loadModulesFrom("/json-to-cnsn/identityref");
- assertEquals(2, modules.size());
-
- TestUtils.normalizeCompositeNode(compositeNode, modules, "identityref-module:cont");
-
- assertEquals("cont", compositeNode.getNodeType().getLocalName());
-
- List<Node<?>> childs = compositeNode.getValue();
- assertEquals(1, childs.size());
- Node<?> nd = childs.iterator().next();
- assertTrue(nd instanceof CompositeNode);
- assertEquals("cont1", nd.getNodeType().getLocalName());
-
- childs = ((CompositeNode) nd).getValue();
- assertEquals(4, childs.size());
- SimpleNode<?> lf11 = null;
- SimpleNode<?> lf12 = null;
- SimpleNode<?> lf13 = null;
- SimpleNode<?> lf14 = null;
- for (Node<?> child : childs) {
- assertTrue(child instanceof SimpleNode);
- if (child.getNodeType().getLocalName().equals("lf11")) {
- lf11 = (SimpleNode<?>) child;
- } else if (child.getNodeType().getLocalName().equals("lf12")) {
- lf12 = (SimpleNode<?>) child;
- } else if (child.getNodeType().getLocalName().equals("lf13")) {
- lf13 = (SimpleNode<?>) child;
- } else if (child.getNodeType().getLocalName().equals("lf14")) {
- lf14 = (SimpleNode<?>) child;
- }
- }
-
- assertTrue(lf11.getValue() instanceof QName);
- assertEquals("iden", ((QName) lf11.getValue()).getLocalName());
- assertEquals("identity:module", ((QName) lf11.getValue()).getNamespace().toString());
-
- assertTrue(lf12.getValue() instanceof QName);
- assertEquals("iden_local", ((QName) lf12.getValue()).getLocalName());
- assertEquals("identityref:module", ((QName) lf12.getValue()).getNamespace().toString());
-
- assertTrue(lf13.getValue() instanceof QName);
- assertEquals("iden_local", ((QName) lf13.getValue()).getLocalName());
- assertEquals("identityref:module", ((QName) lf13.getValue()).getNamespace().toString());
-
- assertTrue(lf14.getValue() instanceof QName);
- assertEquals("iden_local", ((QName) lf14.getValue()).getLocalName());
- assertEquals("identity:module", ((QName) lf14.getValue()).getNamespace().toString());
- }
-
- @Ignore
- @Test
- public void loadDataAugmentedSchemaMoreEqualNamesTest() {
- loadAndNormalizeData("/common/augment/json/dataa.json", "/common/augment/yang", "cont", "main");
- loadAndNormalizeData("/common/augment/json/datab.json", "/common/augment/yang", "cont", "main");
-
- }
-
- private void simpleTest(final String jsonPath, final String yangPath, final String topLevelElementName,
- final String namespace, final String moduleName) {
- CompositeNode compNode = loadAndNormalizeData(jsonPath, yangPath, topLevelElementName, moduleName);
- verifyCompositeNode(compNode, namespace);
- }
-
- private CompositeNode loadAndNormalizeData(final String jsonPath, final String yangPath,
- final String topLevelElementName, final String moduleName) {
- Node<?> node = TestUtils.readInputToCnSn(jsonPath, false, JsonToCompositeNodeProvider.INSTANCE);
- assertTrue(node instanceof CompositeNode);
- CompositeNode compositeNode = (CompositeNode)node;
-
- Set<Module> modules = null;
- modules = TestUtils.loadModulesFrom(yangPath);
- assertNotNull(modules);
-
- TestUtils.normalizeCompositeNode(compositeNode, modules, moduleName + ":" + topLevelElementName);
-
- assertTrue(compositeNode instanceof CompositeNodeWrapper);
- CompositeNode compNode = ((CompositeNodeWrapper) compositeNode).unwrap();
-
- assertEquals(topLevelElementName, compNode.getNodeType().getLocalName());
- return compNode;
- }
-
- private void verityMultipleItemsInList(final CompositeNode compositeNode) {
- List<Node<?>> childrenNodes = compositeNode.getValue();
- assertEquals(4, childrenNodes.size());
- boolean lf11Found = false;
- boolean cont11Found = false;
- boolean lst11Found = false;
- for (Node<?> lst1Item : childrenNodes) {
- assertEquals("lst1", lst1Item.getNodeType().getLocalName());
- assertTrue(lst1Item instanceof CompositeNode);
-
- List<Node<?>> childrenLst1 = ((CompositeNode) lst1Item).getValue();
- assertEquals(1, childrenLst1.size());
- String localName = childrenLst1.get(0).getNodeType().getLocalName();
- if (localName.equals("lf11")) {
- assertTrue(childrenLst1.get(0) instanceof SimpleNode);
- lf11Found = true;
- } else if (localName.equals("lflst11")) {
- assertTrue(childrenLst1.get(0) instanceof SimpleNode);
- assertEquals("45", ((SimpleNode<?>) childrenLst1.get(0)).getValue());
- lf11Found = true;
- } else if (localName.equals("cont11")) {
- assertTrue(childrenLst1.get(0) instanceof CompositeNode);
- cont11Found = true;
- } else if (localName.equals("lst11")) {
- lst11Found = true;
- assertTrue(childrenLst1.get(0) instanceof CompositeNode);
- assertEquals(0, ((CompositeNode) childrenLst1.get(0)).getValue().size());
- }
-
- }
- assertTrue(lf11Found);
- assertTrue(cont11Found);
- assertTrue(lst11Found);
- }
-
- private void verifyCompositeNode(final CompositeNode compositeNode, final String namespace) {
- boolean cont1Found = false;
- boolean lst1Found = false;
- boolean lflst1_1Found = false;
- boolean lflst1_2Found = false;
- boolean lf1Found = false;
-
- // assertEquals(namespace,
- // compositeNode.getNodeType().getNamespace().toString());
-
- for (Node<?> node : compositeNode.getValue()) {
- if (node.getNodeType().getLocalName().equals("cont1")) {
- if (node instanceof CompositeNode) {
- cont1Found = true;
- assertEquals(0, ((CompositeNode) node).getValue().size());
- }
- } else if (node.getNodeType().getLocalName().equals("lst1")) {
- if (node instanceof CompositeNode) {
- lst1Found = true;
- assertEquals(0, ((CompositeNode) node).getValue().size());
- }
- } else if (node.getNodeType().getLocalName().equals("lflst1")) {
- if (node instanceof SimpleNode) {
- if (((SimpleNode<?>) node).getValue().equals("lflst1_1")) {
- lflst1_1Found = true;
- } else if (((SimpleNode<?>) node).getValue().equals("lflst1_2")) {
- lflst1_2Found = true;
- }
- }
-
- } else if (node.getNodeType().getLocalName().equals("lf1")) {
- if (node instanceof SimpleNode) {
- if (((SimpleNode<?>) node).getValue().equals("lf1")) {
- lf1Found = true;
- }
- }
- }
- assertEquals(namespace, node.getNodeType().getNamespace().toString());
- }
- assertTrue(cont1Found);
- assertTrue(lst1Found);
- assertTrue(lflst1_1Found);
- assertTrue(lflst1_2Found);
- assertTrue(lf1Found);
- }
-
- @Test
- public void unsupportedDataFormatTest() {
- String exceptionMessage = "";
- try {
- TestUtils.readInputToCnSn("/json-to-cnsn/unsupported-json-format.json", true,
- JsonToCompositeNodeProvider.INSTANCE);
- } catch (RestconfDocumentedException e) {
- exceptionMessage = e.getErrors().get(0).getErrorMessage();
- }
- assertTrue(exceptionMessage.contains("Root element of Json has to be Object"));
- }
-
- /**
- * Tests case when JSON input data value is in format string1:string2 and first string contain characters "<" or ">" (invalid URI characters).
- *
- * During loading data it is also interpreting as data value in moduleName:localName (potential leafref value).
- * ModuleName part is transformed to URI which causes exception which is caught and URI value is null which cause that potential value in simple node is
- * simple string (value from JSON input) and not IdentityValueDTO instance which is used for leaf-ref candidates.
- */
- @Test
- public void invalidUriCharacterInValue() {
- final Node<?> rootNode = TestUtils.readInputToCnSn("/json-to-cnsn/invalid-uri-character-in-value.json", true,
- JsonToCompositeNodeProvider.INSTANCE);
-
- assertTrue(rootNode instanceof CompositeNode);
- Node<?> lf1 = null;
- Node<?> lf2 = null;
- for(Node<?> child : ((CompositeNode)rootNode).getChildren()) {
- if (child.getNodeType().getLocalName().equals("lf1")) {
- lf1 = child;
- } else if (child.getNodeType().getLocalName().equals("lf2")) {
- lf2 = child;
- }
- }
-
- assertNotNull(lf1);
- assertNotNull(lf2);
- assertTrue(lf1 instanceof SimpleNode<?>);
- assertTrue(lf2 instanceof SimpleNode<?>);
-
- assertEquals("module<Name:value lf1", ((SimpleNode<?>) lf1).getValue());
- assertEquals("module>Name:value lf2", ((SimpleNode<?>) lf2).getValue());
- }
-
}
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.opendaylight.controller.sal.restconf.impl.test.TestUtils.containsStringData;
-
import java.io.ByteArrayInputStream;
-import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import javax.ws.rs.WebApplicationException;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
-import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
-import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
public class CnSnToXmlAndJsonInstanceIdentifierTest extends YangAndXmlAndDataSchemaLoader {
dataLoad("/instanceidentifier/yang", 4, "instance-identifier-module", "cont");
}
- @Test
- public void saveCnSnToXmlTest() throws WebApplicationException, IOException, URISyntaxException, XMLStreamException {
- CompositeNode cnSn = prepareCnSn(createInstanceIdentifier());
- String output = TestUtils.writeCompNodeWithSchemaContextToOutput(cnSn, modules, dataSchemaNode,
- StructuredDataToXmlProvider.INSTANCE);
- validateXmlOutput(output);
-
- }
-
- @Test
- public void saveCnSnWithLeafListInstIdentifierToXmlTest() throws WebApplicationException, IOException,
- URISyntaxException, XMLStreamException {
- CompositeNode cnSn = prepareCnSn(createInstanceIdentifierWithLeafList());
- String output = TestUtils.writeCompNodeWithSchemaContextToOutput(cnSn, modules, dataSchemaNode,
- StructuredDataToXmlProvider.INSTANCE);
- validateXmlOutputWithLeafList(output);
- }
-
- @Test
- public void saveCnSnToJsonTest() throws WebApplicationException, IOException, URISyntaxException {
- CompositeNode cnSn = prepareCnSn(createInstanceIdentifier());
- String output = TestUtils.writeCompNodeWithSchemaContextToOutput(cnSn, modules, dataSchemaNode,
- StructuredDataToJsonProvider.INSTANCE);
- boolean strInOutput = false;
- strInOutput = containsStringData(
- output,
- "\"augment-augment-module:lf111\"",
- ":",
- "\"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module:lst11\\[augment-module:keyvalue111=\\\\\"value1\\\\\"\\]\\[augment-module:keyvalue112=\\\\\"value2\\\\\"\\]/augment-augment-module:lf112\"");
-
- if (!strInOutput) {
- strInOutput = containsStringData(
- output,
- "\"augment-augment-module:lf111\"",
- ":",
- "\"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module:lst11\\[augment-module:keyvalue111='value1'\\]\\[augment-module:keyvalue112='value2'\\]/augment-augment-module:lf112\"");
- }
- assertTrue(strInOutput);
- }
-
- @Test
- public void saveCnSnWithLeafListInstIdentifierToJsonTest() throws WebApplicationException, IOException,
- URISyntaxException {
- CompositeNode cnSn = prepareCnSn(createInstanceIdentifierWithLeafList());
- String output = TestUtils.writeCompNodeWithSchemaContextToOutput(cnSn, modules, dataSchemaNode,
- StructuredDataToJsonProvider.INSTANCE);
- boolean strInOutput = false;
- strInOutput = containsStringData(
- output,
- "\"augment-augment-module:lf111\"",
- ":",
- "\"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module-leaf-list:lflst11\\[.='lflst11_1'\\]\"");
- if (!strInOutput) {
- strInOutput = containsStringData(
- output,
- "\"augment-augment-module:lf111\"",
- ":",
- "\"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module-leaf-list:lflst11\\[.=\\\\\"lflst11_1\\\\\"\\]\"");
- }
-
- assertTrue(strInOutput);
- }
private void validateXmlOutput(final String xml) throws XMLStreamException {
- XMLInputFactory xmlInFactory = XMLInputFactory.newInstance();
+ final XMLInputFactory xmlInFactory = XMLInputFactory.newInstance();
XMLEventReader eventReader;
eventReader = xmlInFactory.createXMLEventReader(new ByteArrayInputStream(xml.getBytes()));
String aModulePrefix = null;
String iiModulePrefix = null;
while (eventReader.hasNext()) {
- XMLEvent nextEvent = eventReader.nextEvent();
+ final XMLEvent nextEvent = eventReader.nextEvent();
if (nextEvent.isStartElement()) {
- StartElement startElement = (StartElement) nextEvent;
+ final StartElement startElement = (StartElement) nextEvent;
if (startElement.getName().getLocalPart().equals("lf111")) {
- Iterator<?> prefixes = startElement.getNamespaceContext().getPrefixes("augment:augment:module");
+ final Iterator<?> prefixes = startElement.getNamespaceContext().getPrefixes("augment:augment:module");
while (prefixes.hasNext() && aaModulePrefix == null) {
- String prefix = (String) prefixes.next();
+ final String prefix = (String) prefixes.next();
if (!prefix.isEmpty()) {
aaModulePrefix = prefix;
}
assertNotNull(aModulePrefix);
assertNotNull(iiModulePrefix);
- String instanceIdentifierValue = "/" + iiModulePrefix + ":cont/" + iiModulePrefix + ":cont1/" + aModulePrefix
+ final String instanceIdentifierValue = "/" + iiModulePrefix + ":cont/" + iiModulePrefix + ":cont1/" + aModulePrefix
+ ":lst11[" + aModulePrefix + ":keyvalue111='value1'][" + aModulePrefix + ":keyvalue112='value2']/"
+ aaModulePrefix + ":lf112";
}
private void validateXmlOutputWithLeafList(final String xml) throws XMLStreamException {
- XMLInputFactory xmlInFactory = XMLInputFactory.newInstance();
+ final XMLInputFactory xmlInFactory = XMLInputFactory.newInstance();
XMLEventReader eventReader;
eventReader = xmlInFactory.createXMLEventReader(new ByteArrayInputStream(xml.getBytes()));
String aModuleLfLstPrefix = null;
String iiModulePrefix = null;
while (eventReader.hasNext()) {
- XMLEvent nextEvent = eventReader.nextEvent();
+ final XMLEvent nextEvent = eventReader.nextEvent();
if (nextEvent.isStartElement()) {
- StartElement startElement = (StartElement) nextEvent;
+ final StartElement startElement = (StartElement) nextEvent;
if (startElement.getName().getLocalPart().equals("lf111")) {
- Iterator<?> prefixes = startElement.getNamespaceContext().getPrefixes("augment:module:leaf:list");
+ final Iterator<?> prefixes = startElement.getNamespaceContext().getPrefixes("augment:module:leaf:list");
while (prefixes.hasNext() && aModuleLfLstPrefix == null) {
- String prefix = (String) prefixes.next();
+ final String prefix = (String) prefixes.next();
if (!prefix.isEmpty()) {
aModuleLfLstPrefix = prefix;
}
assertNotNull(aModuleLfLstPrefix);
assertNotNull(iiModulePrefix);
- String instanceIdentifierValue = "/" + iiModulePrefix + ":cont/" + iiModulePrefix + ":cont1/"
+ final String instanceIdentifierValue = "/" + iiModulePrefix + ":cont/" + iiModulePrefix + ":cont1/"
+ aModuleLfLstPrefix + ":lflst11[.='lflst11_1']";
assertTrue(xml.contains(instanceIdentifierValue));
}
- private CompositeNode prepareCnSn(final YangInstanceIdentifier instanceIdentifier) throws URISyntaxException {
- CompositeNodeBuilder<ImmutableCompositeNode> cont = ImmutableCompositeNode.builder();
- cont.setQName(QName.create("instance:identifier:module", "2014-01-17", "cont"));
-
- CompositeNodeBuilder<ImmutableCompositeNode> cont1 = ImmutableCompositeNode.builder();
- cont1.setQName(QName.create("instance:identifier:module", "2014-01-17", "cont1"));
-
- CompositeNodeBuilder<ImmutableCompositeNode> lst11 = ImmutableCompositeNode.builder();
- lst11.setQName(QName.create("augment:module", "2014-01-17", "lst11"));
-
- SimpleNode<?> lf111 = NodeFactory.createImmutableSimpleNode(
- QName.create("augment:augment:module", "2014-01-17", "lf111"), null, instanceIdentifier);
- lst11.add(lf111);
- cont1.add(lst11.toInstance());
- cont.add(cont1.toInstance());
- return cont.toInstance();
- }
-
private YangInstanceIdentifier createInstanceIdentifier() throws URISyntaxException {
- List<PathArgument> pathArguments = new ArrayList<>();
+ final List<PathArgument> pathArguments = new ArrayList<>();
pathArguments.add(new NodeIdentifier(new QName(new URI("instance:identifier:module"), "cont")));
pathArguments.add(new NodeIdentifier(new QName(new URI("instance:identifier:module"), "cont1")));
- QName qName = new QName(new URI("augment:module"), "lst11");
- Map<QName, Object> keyValues = new HashMap<>();
+ final QName qName = new QName(new URI("augment:module"), "lst11");
+ final Map<QName, Object> keyValues = new HashMap<>();
keyValues.put(new QName(new URI("augment:module"), "keyvalue111"), "value1");
keyValues.put(new QName(new URI("augment:module"), "keyvalue112"), "value2");
- NodeIdentifierWithPredicates nodeIdentifierWithPredicates = new NodeIdentifierWithPredicates(qName, keyValues);
+ final NodeIdentifierWithPredicates nodeIdentifierWithPredicates = new NodeIdentifierWithPredicates(qName, keyValues);
pathArguments.add(nodeIdentifierWithPredicates);
pathArguments.add(new NodeIdentifier(new QName(new URI("augment:augment:module"), "lf112")));
}
private YangInstanceIdentifier createInstanceIdentifierWithLeafList() throws URISyntaxException {
- List<PathArgument> pathArguments = new ArrayList<>();
+ final List<PathArgument> pathArguments = new ArrayList<>();
pathArguments.add(new NodeIdentifier(new QName(new URI("instance:identifier:module"), "cont")));
pathArguments.add(new NodeIdentifier(new QName(new URI("instance:identifier:module"), "cont1")));
pathArguments.add(new NodeWithValue(new QName(new URI("augment:module:leaf:list"), "lflst11"), "lflst11_1"));
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
-
import com.google.common.base.Optional;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
import java.io.FileNotFoundException;
import java.net.URI;
import java.net.URISyntaxException;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
-import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
-import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
import org.opendaylight.controller.sal.restconf.impl.InstanceIdentifierContext;
import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.RpcError;
-import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
@Test
@Ignore // FIXME find how to use mockito for it
public void testMountedRpcCallNoPayload_Success() throws Exception {
- final RpcResult<CompositeNode> rpcResult = RpcResultBuilder.<CompositeNode>success().build();
-
- final ListenableFuture<RpcResult<CompositeNode>> mockListener = mock(ListenableFuture.class);
- when(mockListener.get()).thenReturn(rpcResult);
-
- final QName cancelToastQName = QName.create("namespace", "2014-05-28", "cancelToast");
-
- final RpcDefinition mockRpc = mock(RpcDefinition.class);
- when(mockRpc.getQName()).thenReturn(cancelToastQName);
-
- final DOMMountPoint mockMountPoint = mock(DOMMountPoint.class);
- final RpcProvisionRegistry mockedRpcProvisionRegistry = mock(RpcProvisionRegistry.class);
- when(mockedRpcProvisionRegistry.invokeRpc(eq(cancelToastQName), any(CompositeNode.class))).thenReturn(mockListener);
- when(mockMountPoint.getService(eq(RpcProvisionRegistry.class))).thenReturn(Optional.of(mockedRpcProvisionRegistry));
- when(mockMountPoint.getSchemaContext()).thenReturn(TestUtils.loadSchemaContext("/invoke-rpc"));
-
- final InstanceIdentifierContext mockedInstanceId = mock(InstanceIdentifierContext.class);
- when(mockedInstanceId.getMountPoint()).thenReturn(mockMountPoint);
-
- final ControllerContext mockedContext = mock(ControllerContext.class);
- final String rpcNoop = "invoke-rpc-module:rpc-noop";
- when(mockedContext.urlPathArgDecode(rpcNoop)).thenReturn(rpcNoop);
- when(mockedContext.getRpcDefinition(rpcNoop)).thenReturn(mockRpc);
- when(
- mockedContext.toMountPointIdentifier(eq("opendaylight-inventory:nodes/node/"
- + "REMOTE_HOST/yang-ext:mount/invoke-rpc-module:rpc-noop"))).thenReturn(mockedInstanceId);
-
- restconfImpl.setControllerContext(mockedContext);
- try {
- restconfImpl.invokeRpc(
- "opendaylight-inventory:nodes/node/REMOTE_HOST/yang-ext:mount/invoke-rpc-module:rpc-noop", "",
- uriInfo);
- fail("RestconfDocumentedException wasn't raised");
- } catch (final RestconfDocumentedException e) {
- final List<RestconfError> errors = e.getErrors();
- assertNotNull(errors);
- assertEquals(1, errors.size());
- assertEquals(ErrorType.APPLICATION, errors.iterator().next().getErrorType());
- assertEquals(ErrorTag.OPERATION_FAILED, errors.iterator().next().getErrorTag());
- }
-
- // additional validation in the fact that the restconfImpl does not
- // throw an exception.
}
}
*/
package org.opendaylight.controller.sal.restconf.impl.test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
-
-import java.util.List;
-import java.util.Set;
-import javax.ws.rs.ext.MessageBodyReader;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
-import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
-import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
-import org.opendaylight.controller.sal.restconf.impl.RestconfError;
-import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
-import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.model.api.Module;
/**
* If more then one data element with equal name exists where container or leaf schema node should be present the
*/
public class MultipleEqualNamesForDataNodesTest {
- @Test
- public void multipleEqualNameDataNodeTestForContainerJsonTest() {
- multipleEqualNameDataNodeTest("/equal-data-node-names/equal-name-data-for-container.json",
- ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, JsonToCompositeNodeProvider.INSTANCE);
- }
-
- @Test
- public void multipleEqualNameDataNodeTestForLeafJsonTest() {
- multipleEqualNameDataNodeTest("/equal-data-node-names/equal-name-data-for-leaf.json", ErrorType.PROTOCOL,
- ErrorTag.MALFORMED_MESSAGE, JsonToCompositeNodeProvider.INSTANCE);
- }
-
- @Test
- public void multipleEqualNameDataNodeTestForContainerXmlTest() {
- multipleEqualNameDataNodeTest("/equal-data-node-names/equal-name-data-for-container.xml",
- ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, XmlToCompositeNodeProvider.INSTANCE);
- }
-
- @Test
- public void multipleEqualNameDataNodeTestForLeafXmlTest() {
- multipleEqualNameDataNodeTest("/equal-data-node-names/equal-name-data-for-leaf.xml", ErrorType.APPLICATION,
- ErrorTag.BAD_ELEMENT, XmlToCompositeNodeProvider.INSTANCE);
- }
-
- private void multipleEqualNameDataNodeTest(String path, ErrorType errorType, ErrorTag errorTag,
- MessageBodyReader<Node<?>> messageBodyReader) {
- try {
- Node<?> node = TestUtils.readInputToCnSn(path, false, messageBodyReader);
- assertNotNull(node);
-
- Set<Module> modules = null;
- modules = TestUtils.loadModulesFrom("/equal-data-node-names/yang");
- assertNotNull(modules);
-
- TestUtils.normalizeCompositeNode(node, modules, "equal-data-node-names" + ":" + "cont");
- fail("Exception RestconfDocumentedException should be raised");
- } catch (RestconfDocumentedException e) {
- List<RestconfError> errors = e.getErrors();
- assertNotNull(errors);
-
- assertEquals(1, errors.size());
-
- RestconfError restconfError = errors.get(0);
-
- assertEquals(errorType, restconfError.getErrorType());
- assertEquals(errorTag, restconfError.getErrorTag());
- }
- }
-
}
*/
package org.opendaylight.controller.sal.restconf.impl.test;
-import static org.junit.Assert.assertNotNull;
-
-import java.net.URI;
-import java.net.URISyntaxException;
import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
-import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
-import org.opendaylight.controller.sal.restconf.impl.SimpleNodeWrapper;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
public class NormalizeNodeTest extends YangAndXmlAndDataSchemaLoader {
dataLoad("/normalize-node/yang/");
}
- @Test(expected = RestconfDocumentedException.class)
- public void namespaceNotNullAndInvalidNamespaceAndNoModuleNameTest() {
-
- TestUtils.normalizeCompositeNode(prepareCnSn("wrongnamespace"), modules, schemaNodePath);
- }
-
- @Test
- public void namespaceNullTest() {
-
- TestUtils.normalizeCompositeNode(prepareCnSn(null), modules, schemaNodePath);
- }
-
- @Test
- public void namespaceValidNamespaceTest() {
-
- TestUtils.normalizeCompositeNode(prepareCnSn("normalize:node:module"), modules, schemaNodePath);
- }
-
- @Test
- public void namespaceValidModuleNameTest() {
-
- TestUtils.normalizeCompositeNode(prepareCnSn("normalize-node-module"), modules, schemaNodePath);
- }
-
- private CompositeNode prepareCnSn(final String namespace) {
- URI uri = null;
- if (namespace != null) {
- try {
- uri = new URI(namespace);
- } catch (URISyntaxException e) {
- }
- assertNotNull(uri);
- }
-
- SimpleNodeWrapper lf1 = new SimpleNodeWrapper(uri, "lf1", 43);
- CompositeNodeWrapper cont = new CompositeNodeWrapper(uri, "cont");
- cont.addValue(lf1);
-
- return cont;
- }
-
}
import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
-import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
-import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
assertFalse(matcher.matches());
}
- @Test
- @Ignore
- public void getDataWithUriDepthParameterTest() throws UnsupportedEncodingException {
- setControllerContext(schemaContextModules);
-
- final CompositeNode depth1Cont = toCompositeNode(toCompositeNodeData(
- toNestedQName("depth1-cont"),
- toCompositeNodeData(
- toNestedQName("depth2-cont1"),
- toCompositeNodeData(
- toNestedQName("depth3-cont1"),
- toCompositeNodeData(toNestedQName("depth4-cont1"),
- toSimpleNodeData(toNestedQName("depth5-leaf1"), "depth5-leaf1-value")),
- toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")),
- toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value")),
- toCompositeNodeData(
- toNestedQName("depth2-cont2"),
- toCompositeNodeData(
- toNestedQName("depth3-cont2"),
- toCompositeNodeData(toNestedQName("depth4-cont2"),
- toSimpleNodeData(toNestedQName("depth5-leaf2"), "depth5-leaf2-value")),
- toSimpleNodeData(toNestedQName("depth4-leaf2"), "depth4-leaf2-value")),
- toSimpleNodeData(toNestedQName("depth3-leaf2"), "depth3-leaf2-value")),
- toSimpleNodeData(toNestedQName("depth2-leaf1"), "depth2-leaf1-value")));
-
- final Module module = TestUtils.findModule(schemaContextModules.getModules(), "nested-module");
- assertNotNull(module);
-
- final DataSchemaNode dataSchemaNode = TestUtils.resolveDataSchemaNode("depth1-cont", module);
- assertNotNull(dataSchemaNode);
-
- when(brokerFacade.readConfigurationData(any(YangInstanceIdentifier.class))).thenReturn(
- TestUtils.compositeNodeToDatastoreNormalizedNode(depth1Cont, dataSchemaNode));
-
- // Test config with depth 1
-
- Response response = target("/config/nested-module:depth1-cont").queryParam("depth", "1")
- .request("application/xml").get();
-
- verifyXMLResponse(response, expectEmptyContainer("depth1-cont"));
-
- // Test config with depth 2
-
- response = target("/config/nested-module:depth1-cont").queryParam("depth", "2").request("application/xml")
- .get();
-
- // String
- // xml="<depth1-cont><depth2-cont1/><depth2-cont2/><depth2-leaf1>depth2-leaf1-value</depth2-leaf1></depth1-cont>";
- // Response mr=mock(Response.class);
- // when(mr.getEntity()).thenReturn( new
- // java.io.StringBufferInputStream(xml) );
-
- verifyXMLResponse(
- response,
- expectContainer("depth1-cont", expectEmptyContainer("depth2-cont1"),
- expectEmptyContainer("depth2-cont2"), expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
-
- // Test config with depth 3
-
- response = target("/config/nested-module:depth1-cont").queryParam("depth", "3").request("application/xml")
- .get();
-
- verifyXMLResponse(
- response,
- expectContainer(
- "depth1-cont",
- expectContainer("depth2-cont1", expectEmptyContainer("depth3-cont1"),
- expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
- expectContainer("depth2-cont2", expectEmptyContainer("depth3-cont2"),
- expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
- expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
-
- // Test config with depth 4
-
- response = target("/config/nested-module:depth1-cont").queryParam("depth", "4").request("application/xml")
- .get();
-
- verifyXMLResponse(
- response,
- expectContainer(
- "depth1-cont",
- expectContainer(
- "depth2-cont1",
- expectContainer("depth3-cont1", expectEmptyContainer("depth4-cont1"),
- expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
- expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
- expectContainer(
- "depth2-cont2",
- expectContainer("depth3-cont2", expectEmptyContainer("depth4-cont2"),
- expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
- expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
- expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
-
- // Test config with depth 5
-
- response = target("/config/nested-module:depth1-cont").queryParam("depth", "5").request("application/xml")
- .get();
-
- verifyXMLResponse(
- response,
- expectContainer(
- "depth1-cont",
- expectContainer(
- "depth2-cont1",
- expectContainer(
- "depth3-cont1",
- expectContainer("depth4-cont1",
- expectLeaf("depth5-leaf1", "depth5-leaf1-value")),
- expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
- expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
- expectContainer(
- "depth2-cont2",
- expectContainer(
- "depth3-cont2",
- expectContainer("depth4-cont2",
- expectLeaf("depth5-leaf2", "depth5-leaf2-value")),
- expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
- expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
- expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
-
- // Test config with depth unbounded
-
- response = target("/config/nested-module:depth1-cont").queryParam("depth", "unbounded")
- .request("application/xml").get();
-
- verifyXMLResponse(
- response,
- expectContainer(
- "depth1-cont",
- expectContainer(
- "depth2-cont1",
- expectContainer(
- "depth3-cont1",
- expectContainer("depth4-cont1",
- expectLeaf("depth5-leaf1", "depth5-leaf1-value")),
- expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
- expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
- expectContainer(
- "depth2-cont2",
- expectContainer(
- "depth3-cont2",
- expectContainer("depth4-cont2",
- expectLeaf("depth5-leaf2", "depth5-leaf2-value")),
- expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
- expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
- expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
-
- // Test operational
-
- final CompositeNode depth2Cont1 = toCompositeNode(toCompositeNodeData(
- toNestedQName("depth2-cont1"),
- toCompositeNodeData(
- toNestedQName("depth3-cont1"),
- toCompositeNodeData(toNestedQName("depth4-cont1"),
- toSimpleNodeData(toNestedQName("depth5-leaf1"), "depth5-leaf1-value")),
- toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")),
- toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value")));
-
- assertTrue(dataSchemaNode instanceof DataNodeContainer);
- DataSchemaNode depth2cont1Schema = null;
- for (final DataSchemaNode childNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
- if (childNode.getQName().getLocalName().equals("depth2-cont1")) {
- depth2cont1Schema = childNode;
- break;
- }
- }
- assertNotNull(depth2Cont1);
-
- when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn(
- TestUtils.compositeNodeToDatastoreNormalizedNode(depth2Cont1, depth2cont1Schema));
-
- response = target("/operational/nested-module:depth1-cont/depth2-cont1").queryParam("depth", "3")
- .request("application/xml").get();
-
- verifyXMLResponse(
- response,
- expectContainer(
- "depth2-cont1",
- expectContainer("depth3-cont1", expectEmptyContainer("depth4-cont1"),
- expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
- expectLeaf("depth3-leaf1", "depth3-leaf1-value")));
- }
-
/**
* Tests behavior when invalid value of depth URI parameter
*/
return QName.create("urn:nested:module", "2014-06-3", localName);
}
- @SuppressWarnings("unchecked")
- private CompositeNode toCompositeNode(final NodeData nodeData) {
- final CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
- builder.setQName((QName) nodeData.key);
-
- for (final NodeData child : (List<NodeData>) nodeData.data) {
- if (child.data instanceof List) {
- builder.add(toCompositeNode(child));
- } else {
- builder.addLeaf((QName) child.key, child.data);
- }
- }
-
- return builder.toInstance();
- }
-
private NodeData toCompositeNodeData(final QName key, final NodeData... childData) {
return new NodeData(key, Lists.newArrayList(childData));
}
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
-import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
import java.util.Set;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Application;
import org.opendaylight.controller.sal.rest.impl.RestconfDocumentedExceptionMapper;
import org.opendaylight.controller.sal.rest.impl.XmlNormalizedNodeBodyReader;
import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
-import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
-import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
-import org.opendaylight.yangtools.yang.common.RpcError;
-import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.model.api.Module;
private static String xmlDataRpcInput;
private static String xmlBlockData;
private static String xmlTestInterface;
- private static CompositeNodeWrapper cnSnDataOutput;
private static String xmlData3;
private static String xmlData4;
restconfImpl.setControllerContext(context);
}
-// @Test
-// public void postRpcNoPayload() throws Exception {
-// setSchemaControllerContext(schemaContextTestModule);
-// final String uri = "/operations/test-module:no-payload-rpc-test";
-// final String mediaType = MediaType.APPLICATION_XML;
-// final Response response = target(uri).request(mediaType).post(Entity.entity("", mediaType));
-// assertNotNull(response);
-//
-// }
-
- @Test
- @Ignore //FIXME we don't wish to mock CompositeNode as result
- public void postOperationsStatusCodes() throws IOException {
- setSchemaControllerContext(schemaContextTestModule);
- mockInvokeRpc(cnSnDataOutput, true);
- String uri = "/operations/test-module:rpc-test";
- assertEquals(200, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
-
- mockInvokeRpc(null, true);
- assertEquals(204, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
-
- mockInvokeRpc(null, false);
- assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
-
- final List<RpcError> rpcErrors = new ArrayList<>();
- rpcErrors.add(RpcResultBuilder.newError(ErrorType.RPC, "tag1", "message1", "applicationTag1", "info1", null));
- rpcErrors.add(RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "tag2", "message2", "applicationTag2", "info2",
- null));
- mockInvokeRpc(null, false, rpcErrors);
- assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
-
- uri = "/operations/test-module:rpc-wrongtest";
- assertEquals(400, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
- }
-
- @Test
- @Ignore // TODO RestconfDocumentedExceptionMapper needs be fixed before
- public void postConfigOnlyStatusCodes() throws UnsupportedEncodingException {
- setSchemaControllerContext(schemaContextYangsIetf);
- final String uri = "/config";
- mockCommitConfigurationDataPostMethod(true);
- assertEquals(204, post(uri, MediaType.APPLICATION_XML, xmlDataAbsolutePath));
-
- mockCommitConfigurationDataPostMethod(false);
- assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataAbsolutePath));
-
- assertEquals(400, post(uri, MediaType.APPLICATION_XML, ""));
- }
-
- @Test
- @Ignore //jenkins has problem with JerseyTest - we expecting problems with singletons ControllerContext as schemaContext holder
- public void postConfigStatusCodes() throws UnsupportedEncodingException {
- setSchemaControllerContext(schemaContextYangsIetf);
- final String uri = "/config/ietf-interfaces:interfaces";
-
- mockCommitConfigurationDataPostMethod(true);
- assertEquals(204, post(uri, MediaType.APPLICATION_XML, xmlDataInterfaceAbsolutePath));
-
- mockCommitConfigurationDataPostMethod(false);
- assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataInterfaceAbsolutePath));
-
- // FIXME : empty json input post value return NullPointerException by parsing -> err. code 500
-// assertEquals(400, post(uri, MediaType.APPLICATION_JSON, ""));
- }
-
@Test
@Ignore /// xmlData* need netconf-yang
public void postDataViaUrlMountPoint() throws UnsupportedEncodingException {
assertEquals(400, post(uri, MediaType.APPLICATION_JSON, ""));
}
- private void mockInvokeRpc(final CompositeNode result, final boolean sucessful, final Collection<RpcError> errors) {
-
- final DummyRpcResult.Builder<CompositeNode> builder = new DummyRpcResult.Builder<CompositeNode>().result(result)
- .isSuccessful(sucessful);
- if (!errors.isEmpty()) {
- builder.errors(errors);
- }
- final RpcResult<CompositeNode> rpcResult = builder.build();
-// when(brokerFacade.invokeRpc(any(QName.class), any(CompositeNode.class))).thenReturn(
-// Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
- }
-
- /**
- * @deprecated has to be removed for lithium release
- */
- @Deprecated
- private void mockInvokeRpc(final CompositeNode result, final boolean sucessful) {
- mockInvokeRpc(result, sucessful, Collections.<RpcError> emptyList());
- }
-
- private void mockCommitConfigurationDataPostMethod(final boolean succesfulComit) {
- if (succesfulComit) {
- doReturn(mock(CheckedFuture.class)).when(brokerFacade).commitConfigurationDataPost(any(YangInstanceIdentifier.class), any(NormalizedNode.class));
- } else {
- doThrow(RestconfDocumentedException.class).when(brokerFacade).commitConfigurationDataPost(
- any(YangInstanceIdentifier.class), any(NormalizedNode.class));
- }
- }
-
@Test
@Ignore //jenkins has problem with JerseyTest - we expecting problems with singletons ControllerContext as schemaContext holder
public void createConfigurationDataTest() throws UnsupportedEncodingException, ParseException {
final String xmlPathTestInterface = RestconfImplTest.class.getResource("/test-config-data/xml/test-interface.xml")
.getPath();
xmlTestInterface = TestUtils.loadTextFile(xmlPathTestInterface);
- cnSnDataOutput = prepareCnSnRpcOutput();
+// cnSnDataOutput = prepareCnSnRpcOutput();
final String data3Input = RestconfImplTest.class.getResource("/full-versions/test-data2/data3.xml").getPath();
xmlData3 = TestUtils.loadTextFile(data3Input);
final String data4Input = RestconfImplTest.class.getResource("/full-versions/test-data2/data7.xml").getPath();
xmlData4 = TestUtils.loadTextFile(data4Input);
}
- private static CompositeNodeWrapper prepareCnSnRpcOutput() throws URISyntaxException {
- final CompositeNodeWrapper cnSnDataOutput = new CompositeNodeWrapper(new URI("test:module"), "output");
- final CompositeNodeWrapper cont = new CompositeNodeWrapper(new URI("test:module"), "cont-output");
- cnSnDataOutput.addValue(cont);
- cnSnDataOutput.unwrap();
- return cnSnDataOutput;
- }
}
import org.junit.Test;
import org.opendaylight.controller.sal.rest.api.Draft02;
import org.opendaylight.controller.sal.rest.api.RestconfService;
+import org.opendaylight.controller.sal.rest.impl.JsonNormalizedNodeBodyReader;
+import org.opendaylight.controller.sal.rest.impl.NormalizedNodeJsonBodyWriter;
+import org.opendaylight.controller.sal.rest.impl.NormalizedNodeXmlBodyWriter;
import org.opendaylight.controller.sal.rest.impl.RestconfDocumentedExceptionMapper;
-import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
-import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
+import org.opendaylight.controller.sal.rest.impl.XmlNormalizedNodeBodyReader;
import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
import org.opendaylight.controller.sal.restconf.impl.NormalizedNodeContext;
import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
@Override
protected Application configure() {
ResourceConfig resourceConfig = new ResourceConfig();
- resourceConfig = resourceConfig.registerInstances(mockRestConf, StructuredDataToXmlProvider.INSTANCE,
- StructuredDataToJsonProvider.INSTANCE);
+ resourceConfig = resourceConfig.registerInstances(mockRestConf, new XmlNormalizedNodeBodyReader(),
+ new JsonNormalizedNodeBodyReader(), new NormalizedNodeJsonBodyWriter(), new NormalizedNodeXmlBodyWriter());
resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
return resourceConfig;
}
testJsonResponse(new RestconfDocumentedException("mock error"), Status.INTERNAL_SERVER_ERROR,
ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null, null);
+
// To test verification code
// String json =
// "{ errors: {" +
testXMLResponse(new RestconfDocumentedException("mock error"), Status.INTERNAL_SERVER_ERROR,
ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null, null);
- // To test verification code
+ // To test verification code
// String xml =
// "<errors xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\">"+
// " <error>" +
package org.opendaylight.controller.sal.restconf.impl.test;
import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.ext.MessageBodyReader;
-import javax.ws.rs.ext.MessageBodyWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
-import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
-import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
-import org.opendaylight.controller.sal.restconf.impl.InstanceIdentifierContext;
-import org.opendaylight.controller.sal.restconf.impl.NodeWrapper;
-import org.opendaylight.controller.sal.restconf.impl.NormalizedNodeContext;
-import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
-import org.opendaylight.controller.sal.restconf.impl.RestconfError;
-import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
-import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
-import org.opendaylight.controller.sal.restconf.impl.StructuredData;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser.CnSnToNormalizedNodeParserFactory;
-import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
-import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
-import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.parser.api.YangContextParser;
}
- /**
- * @deprecated method will be removed in Lithium release
- * we don't wish to use Node and CompositeNode anywhere -
- *
- * Fill missing data (namespaces) and build correct data type in {@code compositeNode} according to
- * {@code dataSchemaNode}. The method {@link RestconfImpl#createConfigurationData createConfigurationData} is used
- * because it contains calling of method {code normalizeNode}
- */
- @Deprecated
- public static void normalizeCompositeNode(final Node<?> node, final Set<Module> modules, final String schemaNodePath) {
- final RestconfImpl restconf = RestconfImpl.getInstance();
- ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext(modules));
- prepareMocksForRestconf(modules, restconf);
-
- final InstanceIdentifierContext iiContext = ControllerContext.getInstance().toInstanceIdentifier(schemaNodePath);
- final DOMMountPoint mountPoint = iiContext.getMountPoint();
- final CompositeNode value = RestconfImpl.getInstance().normalizeNode(node, (DataSchemaNode) iiContext.getSchemaNode(), mountPoint);
- final NormalizedNode<?, ?> normNodePayload = compositeNodeToDatastoreNormalizedNode(value, (DataSchemaNode) iiContext.getSchemaNode());
- final NormalizedNodeContext normlNodeContext = new NormalizedNodeContext(iiContext, normNodePayload);
-
- restconf.updateConfigurationData(schemaNodePath, normlNodeContext);
- }
-
/**
* Searches module with name {@code searchedModuleName} in {@code modules}. If module name isn't specified and
* module set has only one element then this element is returned.
return buildQName(name, "", null);
}
- private static void addDummyNamespaceToAllNodes(final NodeWrapper<?> wrappedNode) throws URISyntaxException {
- wrappedNode.setNamespace(new URI(""));
- if (wrappedNode instanceof CompositeNodeWrapper) {
- for (final NodeWrapper<?> childNodeWrapper : ((CompositeNodeWrapper) wrappedNode).getValues()) {
- addDummyNamespaceToAllNodes(childNodeWrapper);
- }
- }
- }
-
private static void prepareMocksForRestconf(final Set<Module> modules, final RestconfImpl restconf) {
final ControllerContext controllerContext = ControllerContext.getInstance();
final BrokerFacade mockedBrokerFacade = mock(BrokerFacade.class);
restconf.setBroker(mockedBrokerFacade);
}
- public static Node<?> readInputToCnSn(final String path, final boolean dummyNamespaces,
- final MessageBodyReader<Node<?>> reader) throws WebApplicationException {
-
- final InputStream inputStream = TestUtils.class.getResourceAsStream(path);
- try {
- final Node<?> node = reader.readFrom(null, null, null, null, null, inputStream);
- assertTrue(node instanceof CompositeNodeWrapper);
- if (dummyNamespaces) {
- try {
- TestUtils.addDummyNamespaceToAllNodes((CompositeNodeWrapper) node);
- return ((CompositeNodeWrapper) node).unwrap();
- } catch (final URISyntaxException e) {
- LOG.error(e.getMessage());
- assertTrue(e.getMessage(), false);
- }
- }
- return node;
- } catch (final IOException e) {
- LOG.error(e.getMessage());
- assertTrue(e.getMessage(), false);
- }
- return null;
- }
-
-// public static Node<?> readInputToCnSnNew(String path, MessageBodyReader<Node<?>> reader) throws WebApplicationException {
-// InputStream inputStream = TestUtils.class.getResourceAsStream(path);
-// try {
-// return reader.readFrom(null, null, null, null, null, inputStream);
-// } catch (IOException e) {
-// LOG.error(e.getMessage());
-// assertTrue(e.getMessage(), false);
-// }
-// return null;
-// }
-
- public static Node<?> readInputToCnSn(final String path, final MessageBodyReader<Node<?>> reader) {
- return readInputToCnSn(path, false, reader);
- }
-
- public static String writeCompNodeWithSchemaContextToOutput(final Node<?> node, final Set<Module> modules,
- final DataSchemaNode dataSchemaNode, final MessageBodyWriter<StructuredData> messageBodyWriter) throws IOException,
- WebApplicationException {
-
- assertNotNull(dataSchemaNode);
- assertNotNull("Composite node can't be null", node);
- final ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
-
- ControllerContext.getInstance().setSchemas(loadSchemaContext(modules));
-
- assertTrue(node instanceof CompositeNode);
- messageBodyWriter.writeTo(new StructuredData((CompositeNode)node, dataSchemaNode, null), null, null, null, null,
- null, byteArrayOS);
-
- return byteArrayOS.toString();
- }
-
public static String loadTextFile(final String filePath) throws IOException {
final FileReader fileReader = new FileReader(filePath);
final BufferedReader bufReader = new BufferedReader(fileReader);
return matcher.matches();
}
- public static NormalizedNode compositeNodeToDatastoreNormalizedNode(final CompositeNode compositeNode,
- final DataSchemaNode schema) {
- final List<Node<?>> lst = new ArrayList<Node<?>>();
- lst.add(compositeNode);
- if (schema instanceof ContainerSchemaNode) {
- return CnSnToNormalizedNodeParserFactory.getInstance().getContainerNodeParser()
- .parse(lst, (ContainerSchemaNode) schema);
- } else if (schema instanceof ListSchemaNode) {
- return CnSnToNormalizedNodeParserFactory.getInstance().getMapNodeParser()
- .parse(lst, (ListSchemaNode) schema);
- }
-
- LOG.error("Top level isn't of type container, list, leaf schema node but " + schema.getClass().getSimpleName());
-
- throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
- "It wasn't possible to translate specified data to datastore readable form."));
- }
-
public static YangInstanceIdentifier.NodeIdentifier getNodeIdentifier(final String localName, final String namespace,
final String revision) throws ParseException {
return new YangInstanceIdentifier.NodeIdentifier(QName.create(namespace, revision, localName));
predicate);
}
- /**
- * @deprecated method has to be removed for Lithium release
- * so please use prepareNormalizedNodeWithIetfInterfacesInterfacesData method
- */
- @Deprecated
- public static CompositeNode prepareCompositeNodeWithIetfInterfacesInterfacesData() {
- final CompositeNodeBuilder<ImmutableCompositeNode> interfaceBuilder = ImmutableCompositeNode.builder();
- interfaceBuilder.addLeaf(buildQName("name", "dummy", "2014-07-29"), "eth0");
- interfaceBuilder.addLeaf(buildQName("type", "dummy", "2014-07-29"), "ethernetCsmacd");
- interfaceBuilder.addLeaf(buildQName("enabled", "dummy", "2014-07-29"), "false");
- interfaceBuilder.addLeaf(buildQName("description", "dummy", "2014-07-29"), "some interface");
- return interfaceBuilder.toInstance();
- }
-
static NormalizedNode<?,?> prepareNormalizedNodeWithIetfInterfacesInterfacesData() throws ParseException {
final String ietfInterfacesDate = "2013-07-04";
final String namespace = "urn:ietf:params:xml:ns:yang:ietf-interfaces";
import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
import org.opendaylight.controller.sal.streams.listeners.Notificator;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
-import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
-import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
return new NormalizedNodeContext(new InstanceIdentifierContext(null, rpcInputSchemaNode, null, schema), container.build());
}
-
- /**
- * @deprecated method has to be removed for a Lithium release
- */
- @Deprecated
- private CompositeNode prepareRpcNode(final String datastore, final String scope) {
- final CompositeNodeBuilder<ImmutableCompositeNode> inputBuilder = ImmutableCompositeNode.builder();
- inputBuilder.setQName(QName.create("urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote",
- "2014-01-14", "input"));
- inputBuilder.addLeaf(
- QName.create("urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "2014-01-14", "path"),
- YangInstanceIdentifier.builder().node(QName.create("urn:opendaylight:inventory", "2013-08-19", "nodes")).build());
- inputBuilder.addLeaf(QName.create("urn:sal:restconf:event:subscription", "2014-7-8", "datastore"), datastore);
- inputBuilder.addLeaf(QName.create("urn:sal:restconf:event:subscription", "2014-7-8", "scope"), scope);
- return inputBuilder.toInstance();
- }
}
*/
package org.opendaylight.controller.sal.restconf.impl.test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.util.Iterator;
-import java.util.Map;
-import javax.ws.rs.WebApplicationException;
import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
-import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
public class XmlAndJsonToCnSnInstanceIdentifierTest extends YangAndXmlAndDataSchemaLoader {
dataLoad("/instanceidentifier/yang", 4, "instance-identifier-module", "cont");
}
- @Test
- public void loadXmlToCnSn() throws WebApplicationException, IOException, URISyntaxException {
- Node<?> node = TestUtils.readInputToCnSn("/instanceidentifier/xml/xmldata.xml",
- XmlToCompositeNodeProvider.INSTANCE);
-
- assertTrue(node instanceof CompositeNode);
- CompositeNode cnSn = (CompositeNode)node;
- TestUtils.normalizeCompositeNode(cnSn, modules, schemaNodePath);
- verifyListPredicate(cnSn);
- }
-
- @Test
- public void loadXmlLeafListToCnSn() throws WebApplicationException, IOException, URISyntaxException {
- Node<?> node = TestUtils.readInputToCnSn("/instanceidentifier/xml/xmldata_leaf_list.xml",
- XmlToCompositeNodeProvider.INSTANCE);
-
- assertTrue(node instanceof CompositeNode);
- CompositeNode cnSn = (CompositeNode)node;
- TestUtils.normalizeCompositeNode(cnSn, modules, schemaNodePath);
- verifyLeafListPredicate(cnSn);
- }
-
- @Test
- public void loadJsonToCnSn() throws WebApplicationException, IOException, URISyntaxException {
- Node<?> node = TestUtils.readInputToCnSn("/instanceidentifier/json/jsondata.json",
- JsonToCompositeNodeProvider.INSTANCE);
-
- assertTrue(node instanceof CompositeNode);
- CompositeNode cnSn = (CompositeNode)node;
- TestUtils.normalizeCompositeNode(cnSn, modules, schemaNodePath);
- verifyListPredicate(cnSn);
- }
-
- @Test
- public void loadJsonLeafListToCnSn() throws WebApplicationException, IOException, URISyntaxException {
- Node<?> node = TestUtils.readInputToCnSn("/instanceidentifier/json/jsondata_leaf_list.json",
- JsonToCompositeNodeProvider.INSTANCE);
- assertTrue(node instanceof CompositeNode);
- CompositeNode cnSn = (CompositeNode)node;
-
- TestUtils.normalizeCompositeNode(cnSn, modules, schemaNodePath);
- verifyLeafListPredicate(cnSn);
- }
-
- private void verifyLeafListPredicate(final CompositeNode cnSn) throws URISyntaxException {
- SimpleNode<?> lf11 = getSnWithInstanceIdentifierWhenLeafList(cnSn);
- Object value = lf11.getValue();
- assertTrue(value instanceof YangInstanceIdentifier);
-
- YangInstanceIdentifier instanceIdentifier = (YangInstanceIdentifier) value;
- Iterator<PathArgument> it = instanceIdentifier.getPathArguments().iterator();
- String revisionDate = "2014-01-17";
-
- assertEquals(TestUtils.buildQName("cont", "instance:identifier:module", revisionDate), it.next().getNodeType());
- assertEquals(TestUtils.buildQName("cont1", "instance:identifier:module", revisionDate), it.next().getNodeType());
-
- PathArgument arg = it.next();
- assertFalse(it.hasNext());
- assertEquals(TestUtils.buildQName("lflst11", "augment:module:leaf:list", "2014-01-27"), arg.getNodeType());
-
- assertTrue(arg instanceof NodeWithValue);
- assertEquals("lflst11_1", ((NodeWithValue) arg).getValue());
-
- }
-
- private void verifyListPredicate(final CompositeNode cnSn) throws URISyntaxException {
- SimpleNode<?> lf111 = getSnWithInstanceIdentifierWhenList(cnSn);
- Object value = lf111.getValue();
- assertTrue(value instanceof YangInstanceIdentifier);
-
- YangInstanceIdentifier instanceIdentifier = (YangInstanceIdentifier) value;
- Iterator<PathArgument> it = instanceIdentifier.getPathArguments().iterator();
- String revisionDate = "2014-01-17";
- assertEquals(TestUtils.buildQName("cont", "instance:identifier:module", revisionDate), it.next().getNodeType());
- assertEquals(TestUtils.buildQName("cont1", "instance:identifier:module", revisionDate), it.next().getNodeType());
-
- PathArgument arg = it.next();
- assertEquals(TestUtils.buildQName("lst11", "augment:module", revisionDate), arg.getNodeType());
- assertEquals(TestUtils.buildQName("lf112", "augment:augment:module", revisionDate), it.next().getNodeType());
- assertFalse(it.hasNext());
-
- assertTrue(arg instanceof NodeIdentifierWithPredicates);
- Map<QName, Object> predicates = ((NodeIdentifierWithPredicates) arg).getKeyValues();
- assertEquals(2, predicates.size());
- assertEquals("value1", predicates.get(TestUtils.buildQName("keyvalue111", "augment:module", revisionDate)));
- assertEquals("value2", predicates.get(TestUtils.buildQName("keyvalue112", "augment:module", revisionDate)));
- }
-
- private SimpleNode<?> getSnWithInstanceIdentifierWhenList(final CompositeNode cnSn) throws URISyntaxException {
- CompositeNode cont1 = cnSn.getFirstCompositeByName(TestUtils.buildQName("cont1", "instance:identifier:module",
- "2014-01-17"));
- assertNotNull(cont1);
- CompositeNode lst11 = cont1.getFirstCompositeByName(TestUtils.buildQName("lst11", "augment:module",
- "2014-01-17"));
- assertNotNull(lst11);
- SimpleNode<?> lf111 = lst11.getFirstSimpleByName(TestUtils.buildQName("lf111", "augment:augment:module",
- "2014-01-17"));
- assertNotNull(lf111);
- return lf111;
- }
-
- private SimpleNode<?> getSnWithInstanceIdentifierWhenLeafList(final CompositeNode cnSn) throws URISyntaxException {
- CompositeNode cont1 = cnSn.getFirstCompositeByName(TestUtils.buildQName("cont1", "instance:identifier:module",
- "2014-01-17"));
- assertNotNull(cont1);
- SimpleNode<?> lf11 = cont1.getFirstSimpleByName(TestUtils.buildQName("lf11", "augment:module:leaf:list",
- "2014-01-27"));
- assertNotNull(lf11);
- return lf11;
- }
-
}
*/
package org.opendaylight.controller.sal.restconf.impl.test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.io.IOException;
-import java.net.URISyntaxException;
-
-import javax.ws.rs.WebApplicationException;
-
import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
-import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
public class XmlAndJsonToCnSnLeafRefTest extends YangAndXmlAndDataSchemaLoader {
dataLoad("/leafref/yang", 2, "leafref-module", "cont");
}
- @Test
- public void loadXmlToCnSn() throws WebApplicationException, IOException, URISyntaxException {
- Node<?> node = TestUtils.readInputToCnSn("/leafref/xml/xmldata.xml", XmlToCompositeNodeProvider.INSTANCE);
-
- assertTrue(node instanceof CompositeNode);
- CompositeNode cnSn = (CompositeNode)node;
-
- TestUtils.normalizeCompositeNode(cnSn, modules, schemaNodePath);
-
- verifyContPredicate(cnSn, "lf4", YangInstanceIdentifier.builder().node(refContQName).node(refLf1QName).build());
- verifyContPredicate(cnSn, "lf2", YangInstanceIdentifier.builder().node(contQName).node(lf1QName).build());
- verifyContPredicate(cnSn, "lf3", YangInstanceIdentifier.builder().node(contQName).node(lf2QName).build());
- verifyContPredicate(cnSn, "lf5", YangInstanceIdentifier.builder().node(contQName).node(lf3QName).build());
- }
-
- @Test
- public void loadJsonToCnSn() throws WebApplicationException, IOException, URISyntaxException {
- Node<?> node = TestUtils.readInputToCnSn("/leafref/json/jsondata.json",
- JsonToCompositeNodeProvider.INSTANCE);
- assertTrue(node instanceof CompositeNode);
- CompositeNode cnSn = (CompositeNode)node;
-
- TestUtils.normalizeCompositeNode(cnSn, modules, schemaNodePath);
-
- verifyContPredicate(cnSn, "lf4", YangInstanceIdentifier.builder().node(refContQName).node(refLf1QName).build());
- verifyContPredicate(cnSn, "lf2", YangInstanceIdentifier.builder().node(contQName).node(lf1QName).build());
- verifyContPredicate(cnSn, "lf3", YangInstanceIdentifier.builder().node(contQName).node(lf2QName).build());
- verifyContPredicate(cnSn, "lf5", YangInstanceIdentifier.builder().node(contQName).node(lf3QName).build());
- }
-
- private void verifyContPredicate(CompositeNode cnSn, String leafName, Object value) throws URISyntaxException {
- Object parsed = null;
-
- for (final Node<?> node : cnSn.getValue()) {
- if (node.getNodeType().getLocalName().equals(leafName)) {
- parsed = node.getValue();
- }
- }
-
- assertEquals(value, parsed);
- }
}
*/
package org.opendaylight.controller.sal.restconf.impl.xml.to.cnsn.test;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.Set;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
-import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.model.api.Module;
public class XmlAugmentedElementToCnSnTest {
- @Test
- public void loadDataAugmentedSchemaMoreEqualNamesTest() {
- loadAndNormalizeData("/common/augment/xml/dataa.xml", "/common/augment/yang", "main", "cont");
- loadAndNormalizeData("/common/augment/xml/datab.xml", "/common/augment/yang", "main", "cont");
- }
-
- private void loadAndNormalizeData(String xmlPath, String yangPath, String topLevelElementName, String moduleName) {
- Node<?> node = TestUtils.readInputToCnSn(xmlPath, false,
- XmlToCompositeNodeProvider.INSTANCE);
- assertTrue(node instanceof CompositeNode);
- CompositeNode cnSn = (CompositeNode)node;
-
- Set<Module> modules = TestUtils.loadModulesFrom(yangPath);
-
- assertNotNull(modules);
- TestUtils.normalizeCompositeNode(cnSn, modules, topLevelElementName + ":" + moduleName);
- }
-
}
*/
package org.opendaylight.controller.sal.restconf.impl.xml.to.cnsn.test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.List;
-import java.util.Set;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
-import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class XmlLeafrefToCnSnTest {
private static final Logger LOG = LoggerFactory.getLogger(XmlLeafrefToCnSnTest.class);
- /**
- * top level element represents container. second level element is list with two elements.
- */
- @Test
- public void testXmlDataContainer() {
- Node<?> node = TestUtils.readInputToCnSn("/xml-to-cnsn/data-container.xml", false,
- XmlToCompositeNodeProvider.INSTANCE);
- assertTrue(node instanceof CompositeNode);
- CompositeNode compNode = (CompositeNode)node;
-
- assertNotNull(compNode);
- Set<Module> modules = TestUtils.loadModulesFrom("/xml-to-cnsn/data-container-yang");
-
- assertNotNull(modules);
- TestUtils.normalizeCompositeNode(compNode, modules, "data-container-yang:cont");
-
- String nameSpace = "data:container:yang";
- assertEquals(nameSpace, compNode.getNodeType().getNamespace().toString());
-
- verifyNullAndEmptyStringSingleNode(compNode, nameSpace);
- verifyCommonPartAOfXml(compNode, "", nameSpace);
- }
-
- private void verifyNullAndEmptyStringSingleNode(final CompositeNode compNode, final String nameSpace) {
- assertEquals("cont", compNode.getNodeType().getLocalName());
-
- SimpleNode<?> lf2 = null;
- SimpleNode<?> lf3 = null;
- int found = 0;
- for (Node<?> child : compNode.getValue()) {
- if (found == 0x3)
- break;
- if (child instanceof SimpleNode<?>) {
- SimpleNode<?> childSimple = (SimpleNode<?>) child;
- if (childSimple.getNodeType().getLocalName().equals("lf3")) {
- lf3 = childSimple;
- found = found | (1 << 0);
- } else if (childSimple.getNodeType().getLocalName().equals("lf2")) {
- lf2 = childSimple;
- found = found | (1 << 1);
- }
- }
- assertEquals(nameSpace, child.getNodeType().getNamespace().toString());
- }
-
- assertEquals("", lf2.getValue());
- assertEquals(null, lf3.getValue());
- }
-
- @Test
- public void testXmlDataList() {
- Node<?> node = TestUtils.readInputToCnSn("/xml-to-cnsn/data-list.xml", false,
- XmlToCompositeNodeProvider.INSTANCE);
- assertTrue(node instanceof CompositeNode);
- CompositeNode compNode = (CompositeNode)node;
-
-
- Set<Module> modules = TestUtils.loadModulesFrom("/xml-to-cnsn/data-list-yang");
- assertNotNull(modules);
-
- TestUtils.normalizeCompositeNode(compNode, modules, "data-container-yang:cont");
-
- String nameSpaceList = "data:list:yang";
- String nameSpaceCont = "data:container:yang";
- assertEquals(nameSpaceCont, compNode.getNodeType().getNamespace().toString());
- assertEquals("cont", compNode.getNodeType().getLocalName());
- assertEquals(3, compNode.getValue().size());
- CompositeNode lst1_1 = null;
- CompositeNode lst1_2 = null;
- int loopCount = 0;
- for (Node<?> nd : compNode.getValue()) {
- if (nd.getNodeType().getLocalName().equals("lf1")) {
- assertEquals(nameSpaceList, nd.getNodeType().getNamespace().toString());
- assertTrue(nd instanceof SimpleNode<?>);
- assertEquals("lf1", nd.getValue());
- } else {
- assertTrue(nd instanceof CompositeNode);
- switch (loopCount++) {
- case 0:
- lst1_1 = (CompositeNode) nd;
- break;
- case 1:
- lst1_2 = (CompositeNode) nd;
- break;
- }
- assertEquals(nameSpaceCont, nd.getNodeType().getNamespace().toString());
- }
- }
- // lst1_1
- verifyCommonPartAOfXml(lst1_1, "1", nameSpaceCont);
- // :lst1_1
-
- // lst1_2
- SimpleNode<?> lflst11 = null;
- CompositeNode cont11 = null;
- for (Node<?> nd : lst1_2.getValue()) {
- String nodeName = nd.getNodeType().getLocalName();
- if (nodeName.equals("lflst11")) {
- assertTrue(nd instanceof SimpleNode<?>);
- lflst11 = (SimpleNode<?>) nd;
-
- } else if (nodeName.equals("cont11")) {
- assertTrue(nd instanceof CompositeNode);
- cont11 = (CompositeNode) nd;
- }
- assertEquals(nameSpaceCont, compNode.getNodeType().getNamespace().toString());
- }
- assertEquals("221", lflst11.getValue());
-
- assertEquals(1, cont11.getValue().size());
- assertTrue(cont11.getValue().get(0) instanceof SimpleNode<?>);
- SimpleNode<?> cont11_lf111 = (SimpleNode<?>) cont11.getValue().get(0);
- assertEquals(nameSpaceCont, cont11_lf111.getNodeType().getNamespace().toString());
- assertEquals("lf111", cont11_lf111.getNodeType().getLocalName());
- assertEquals((short) 100, cont11_lf111.getValue());
- // :lst1_2
-
- }
-
- @Test
- public void testXmlEmptyData() {
- Node<?> node = TestUtils.readInputToCnSn("/xml-to-cnsn/empty-data.xml", true,
- XmlToCompositeNodeProvider.INSTANCE);
- assertTrue(node instanceof CompositeNode);
- CompositeNode compNode = (CompositeNode)node;
-
- assertEquals("cont", compNode.getNodeType().getLocalName());
- SimpleNode<?> lf1 = null;
- SimpleNode<?> lflst1_1 = null;
- SimpleNode<?> lflst1_2 = null;
- CompositeNode lst1 = null;
- int lflst1Count = 0;
- for (Node<?> nd : compNode.getValue()) {
- if (nd.getNodeType().getLocalName().equals("lf1")) {
- assertTrue(nd instanceof SimpleNode<?>);
- lf1 = (SimpleNode<?>) nd;
- } else if (nd.getNodeType().getLocalName().equals("lflst1")) {
- assertTrue(nd instanceof SimpleNode<?>);
-
- switch (lflst1Count++) {
- case 0:
- lflst1_1 = (SimpleNode<?>) nd;
- break;
- case 1:
- lflst1_2 = (SimpleNode<?>) nd;
- break;
- }
- } else if (nd.getNodeType().getLocalName().equals("lst1")) {
- assertTrue(nd instanceof CompositeNode);
- lst1 = (CompositeNode) nd;
- }
- }
-
- assertNotNull(lf1);
- assertNotNull(lflst1_1);
- assertNotNull(lflst1_2);
- assertNotNull(lst1);
-
- assertEquals("", lf1.getValue());
- assertEquals("", lflst1_1.getValue());
- assertEquals("", lflst1_2.getValue());
- assertEquals(1, lst1.getValue().size());
- assertEquals("lf11", lst1.getValue().get(0).getNodeType().getLocalName());
-
- assertTrue(lst1.getValue().get(0) instanceof SimpleNode<?>);
- assertEquals("", lst1.getValue().get(0).getValue());
-
- }
-
- /**
- * Test case like this <lf11 xmlns:x="namespace">x:identity</lf11>
- */
- @Test
- public void testIdentityrefNmspcInElement() {
- testIdentityrefToCnSn("/xml-to-cnsn/identityref/xml/data-nmspc-in-element.xml", "/xml-to-cnsn/identityref",
- "identityref-module", "cont", 2, "iden", "identity:module");
- }
-
- /**
- *
- * Test case like <lf11 xmlns="namespace1" xmlns:x="namespace">identity</lf11>
- */
-
- @Test
- public void testIdentityrefDefaultNmspcInElement() {
- testIdentityrefToCnSn("/xml-to-cnsn/identityref/xml/data-default-nmspc-in-element.xml",
- "/xml-to-cnsn/identityref/yang-augments", "general-module", "cont", 3, "iden", "identityref:module");
- }
-
- /**
- *
- * Test case like <cont1 xmlns="namespace1"> <lf11 xmlns:x="namespace">identity</lf11> </cont1>
- */
- @Test
- public void testIdentityrefDefaultNmspcInParrentElement() {
- testIdentityrefToCnSn("/xml-to-cnsn/identityref/xml/data-default-nmspc-in-parrent-element.xml",
- "/xml-to-cnsn/identityref", "identityref-module", "cont", 2, "iden", "identityref:module");
- }
-
- /**
- *
- * Test case like <cont1 xmlns="namespace1" xmlns:x="namespace"> <lf11>x:identity</lf11> </cont1>
- */
- @Ignore
- @Test
- public void testIdentityrefNmspcInParrentElement() {
- testIdentityrefToCnSn("/xml-to-cnsn/identityref/xml/data-nmspc-in-parrent-element.xml",
- "/xml-to-cnsn/identityref", "identityref-module", "cont", 2, "iden", "z:namespace");
- }
-
- /**
- *
- * Test case like (without namespace in xml) <cont1> <lf11>x:identity</lf11> </cont1>
- */
- @Test
- public void testIdentityrefNoNmspcValueWithPrefix() {
- testIdentityrefToCnSn("/xml-to-cnsn/identityref/xml/data-no-nmspc-value-with-prefix.xml",
- "/xml-to-cnsn/identityref", "identityref-module", "cont", 2, "x:iden", "identityref:module");
- }
-
- /**
- *
- * Test case like (without namespace in xml) <cont1> <lf11>identity</lf11> </cont1>
- */
- @Test
- public void testIdentityrefNoNmspcValueWithoutPrefix() {
- testIdentityrefToCnSn("/xml-to-cnsn/identityref/xml/data-no-nmspc-value-without-prefix.xml",
- "/xml-to-cnsn/identityref", "identityref-module", "cont", 2, "iden", "identityref:module");
- }
-
- private void verifyCommonPartAOfXml(final CompositeNode compNode, final String suf, final String nameSpace) {
- SimpleNode<?> lf1suf = null;
- SimpleNode<?> lflst1suf_1 = null;
- SimpleNode<?> lflst1suf_2 = null;
- SimpleNode<?> lflst1suf_3 = null;
- CompositeNode cont1suf = null;
- CompositeNode lst1suf = null;
-
- int lflstCount = 0;
-
- for (Node<?> node : compNode.getValue()) {
- String localName = node.getNodeType().getLocalName();
- if (localName.equals("lf1" + suf)) {
- assertTrue(node instanceof SimpleNode<?>);
- lf1suf = (SimpleNode<?>) node;
- } else if (localName.equals("lflst1" + suf)) {
- assertTrue(node instanceof SimpleNode<?>);
- switch (lflstCount++) {
- case 0:
- lflst1suf_1 = (SimpleNode<?>) node;
- break;
- case 1:
- lflst1suf_2 = (SimpleNode<?>) node;
- break;
- case 2:
- lflst1suf_3 = (SimpleNode<?>) node;
- break;
- }
- } else if (localName.equals("lst1" + suf)) {
- assertTrue(node instanceof CompositeNode);
- lst1suf = (CompositeNode) node;
- } else if (localName.equals("cont1" + suf)) {
- assertTrue(node instanceof CompositeNode);
- cont1suf = (CompositeNode) node;
- }
- assertEquals(nameSpace, node.getNodeType().getNamespace().toString());
- }
-
- assertNotNull(lf1suf);
- assertNotNull(lflst1suf_1);
- assertNotNull(lflst1suf_2);
- assertNotNull(lflst1suf_3);
- assertNotNull(lst1suf);
- assertNotNull(cont1suf);
-
- assertEquals("str0", lf1suf.getValue());
- assertEquals("121", lflst1suf_1.getValue());
- assertEquals("131", lflst1suf_2.getValue());
- assertEquals("str1", lflst1suf_3.getValue());
-
- assertEquals(1, lst1suf.getValue().size());
-
- assertTrue(lst1suf.getValue().get(0) instanceof SimpleNode<?>);
- SimpleNode<?> lst11_lf11 = (SimpleNode<?>) lst1suf.getValue().get(0);
- assertEquals(nameSpace, lst11_lf11.getNodeType().getNamespace().toString());
- assertEquals("lf11" + suf, lst11_lf11.getNodeType().getLocalName());
- assertEquals("str2", lst11_lf11.getValue());
-
- assertTrue(cont1suf.getValue().get(0) instanceof SimpleNode<?>);
- SimpleNode<?> cont1_lf11 = (SimpleNode<?>) cont1suf.getValue().get(0);
- assertEquals(nameSpace, cont1_lf11.getNodeType().getNamespace().toString());
- assertEquals("lf11" + suf, cont1_lf11.getNodeType().getLocalName());
- assertEquals((short) 100, cont1_lf11.getValue());
- }
-
- private void testIdentityrefToCnSn(final String xmlPath, final String yangPath, final String moduleName,
- final String schemaName, final int moduleCount, final String resultLocalName, final String resultNamespace) {
- Node<?> node = TestUtils.readInputToCnSn(xmlPath, false, XmlToCompositeNodeProvider.INSTANCE);
- assertTrue(node instanceof CompositeNode);
- CompositeNode compositeNode = (CompositeNode)node;
-
-
- Set<Module> modules = TestUtils.loadModulesFrom(yangPath);
- assertEquals(moduleCount, modules.size());
-
- TestUtils.normalizeCompositeNode(compositeNode, modules, moduleName + ":" + schemaName);
-
- SimpleNode<?> lf11 = getLf11(compositeNode);
- assertTrue(lf11.getValue() instanceof QName);
- QName qName = (QName) lf11.getValue();
- assertEquals(resultLocalName, qName.getLocalName());
- assertEquals(resultNamespace, qName.getNamespace().toString());
- }
-
- private SimpleNode<?> getLf11(final CompositeNode compositeNode) {
- assertEquals("cont", compositeNode.getNodeType().getLocalName());
-
- List<Node<?>> childs = compositeNode.getValue();
- assertEquals(1, childs.size());
- Node<?> nd = childs.iterator().next();
- assertTrue(nd instanceof CompositeNode);
- assertEquals("cont1", nd.getNodeType().getLocalName());
-
- childs = ((CompositeNode) nd).getValue();
- SimpleNode<?> lf11 = null;
- for (Node<?> child : childs) {
- assertTrue(child instanceof SimpleNode);
- if (child.getNodeType().getLocalName().equals("lf11")) {
- lf11 = (SimpleNode<?>) child;
- }
- }
- assertNotNull(lf11);
- return lf11;
- }
-
}
*/
package org.opendaylight.controller.sal.restconf.impl.xml.to.cnsn.test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
-import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
public class XmlToCnSnTest extends YangAndXmlAndDataSchemaLoader {
dataLoad("/xml-to-cnsn/leafref");
}
- @Test
- public void testXmlLeafrefToCnSn() {
- Node<?> node = TestUtils.readInputToCnSn("/xml-to-cnsn/leafref/xml/data.xml", false,
- XmlToCompositeNodeProvider.INSTANCE);
- assertTrue(node instanceof CompositeNode);
- CompositeNode compositeNode = (CompositeNode)node;
-
-
- assertNotNull(dataSchemaNode);
- TestUtils.normalizeCompositeNode(compositeNode, modules, schemaNodePath);
-
- assertEquals("cont", compositeNode.getNodeType().getLocalName());
-
- SimpleNode<?> lf2 = null;
- for (Node<?> childNode : compositeNode.getValue()) {
- if (childNode instanceof SimpleNode) {
- if (childNode.getNodeType().getLocalName().equals("lf2")) {
- lf2 = (SimpleNode<?>) childNode;
- break;
- }
- }
- }
-
- assertNotNull(lf2);
- assertEquals(121, lf2.getValue());
- }
-
- @Test
- public void testXmlBlankInput() throws Exception {
- InputStream inputStream = new ByteArrayInputStream("".getBytes());
- Node<?> node =
- XmlToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null, inputStream);
-
- assertNull( node );
- }
-
- @Test
- public void testXmlBlankInputUnmarkableStream() throws Exception {
- InputStream inputStream = new ByteArrayInputStream("".getBytes()) {
- @Override
- public boolean markSupported() {
- return false;
- }
- };
- Node<?> node =
- XmlToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null, inputStream);
-
- assertNull( node );
- }
-
}