From: Jozef Gloncak Date: Fri, 11 Jul 2014 08:26:07 +0000 (+0200) Subject: Apply style rules on whole sal-rest-connector X-Git-Tag: release/helium~489 X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?p=controller.git;a=commitdiff_plain;h=484151212f586dd533984a11063c92799c414ec8 Apply style rules on whole sal-rest-connector No changes in function of code, just formatting. Change-Id: I52bf10a3b84fa61ec35c31145acbbc6b9bf349ec Signed-off-by: Jozef Gloncak --- diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/Draft02.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/Draft02.java index af763cce0d..51ac43be7c 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/Draft02.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/Draft02.java @@ -47,26 +47,24 @@ public class Draft02 { String ERROR_LIST_SCHEMA_NODE = "error"; - QName IETF_RESTCONF_QNAME = QName.create( Draft02.RestConfModule.NAMESPACE, - Draft02.RestConfModule.REVISION, - Draft02.RestConfModule.NAME ); + QName IETF_RESTCONF_QNAME = QName.create(Draft02.RestConfModule.NAMESPACE, Draft02.RestConfModule.REVISION, + Draft02.RestConfModule.NAME); - QName ERRORS_CONTAINER_QNAME = QName.create( IETF_RESTCONF_QNAME, ERRORS_CONTAINER_SCHEMA_NODE ); + QName ERRORS_CONTAINER_QNAME = QName.create(IETF_RESTCONF_QNAME, ERRORS_CONTAINER_SCHEMA_NODE); - QName ERROR_LIST_QNAME = QName.create( IETF_RESTCONF_QNAME, ERROR_LIST_SCHEMA_NODE ); + QName ERROR_LIST_QNAME = QName.create(IETF_RESTCONF_QNAME, ERROR_LIST_SCHEMA_NODE); - QName ERROR_TYPE_QNAME = QName.create( IETF_RESTCONF_QNAME, "error-type" ); + QName ERROR_TYPE_QNAME = QName.create(IETF_RESTCONF_QNAME, "error-type"); - QName ERROR_TAG_QNAME = QName.create( IETF_RESTCONF_QNAME, "error-tag" ); + QName ERROR_TAG_QNAME = QName.create(IETF_RESTCONF_QNAME, "error-tag"); - QName ERROR_APP_TAG_QNAME = QName.create( IETF_RESTCONF_QNAME, "error-app-tag" ); + QName ERROR_APP_TAG_QNAME = QName.create(IETF_RESTCONF_QNAME, "error-app-tag"); - QName ERROR_MESSAGE_QNAME = QName.create( IETF_RESTCONF_QNAME, "error-message" ); + QName ERROR_MESSAGE_QNAME = QName.create(IETF_RESTCONF_QNAME, "error-message"); - QName ERROR_INFO_QNAME = QName.create( IETF_RESTCONF_QNAME, "error-info" ); + QName ERROR_INFO_QNAME = QName.create(IETF_RESTCONF_QNAME, "error-info"); } - public static interface Paths { } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/RestconfService.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/RestconfService.java index 2f11d8ed7d..a6c4ea5ab8 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/RestconfService.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/RestconfService.java @@ -25,23 +25,20 @@ import org.opendaylight.controller.sal.restconf.impl.StructuredData; import org.opendaylight.yangtools.yang.data.api.CompositeNode; /** - * The URI hierarchy for the RESTCONF resources consists of an entry point - * container, 4 top-level resources, and 1 field. + * The URI hierarchy for the RESTCONF resources consists of an entry point container, 4 top-level resources, and 1 + * field. * @@ -93,7 +90,8 @@ public interface RestconfService { @Consumes({ Draft02.MediaTypes.OPERATION + JSON, Draft02.MediaTypes.OPERATION + XML, Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML }) - public StructuredData invokeRpc(@Encoded @PathParam("identifier") String identifier, CompositeNode payload, @Context UriInfo uriInfo); + public StructuredData invokeRpc(@Encoded @PathParam("identifier") String identifier, CompositeNode payload, + @Context UriInfo uriInfo); @POST @Path("/operations/{identifier:.+}") @@ -114,7 +112,8 @@ public interface RestconfService { @Path("/operational/{identifier:.+}") @Produces({ Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML }) - public StructuredData readOperationalData(@Encoded @PathParam("identifier") String identifier, @Context UriInfo uriInfo); + public StructuredData readOperationalData(@Encoded @PathParam("identifier") String identifier, + @Context UriInfo uriInfo); @PUT @Path("/config/{identifier:.+}") diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/package-info.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/package-info.java index fc3674eefe..49d8d66a3f 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/package-info.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/package-info.java @@ -6,3 +6,4 @@ * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.sal.rest.api; + diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/gson/JsonParser.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/gson/JsonParser.java index f3b61de457..a784be2adc 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/gson/JsonParser.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/gson/JsonParser.java @@ -22,8 +22,8 @@ import java.io.EOFException; import java.io.IOException; /** - * This class parses JSON elements from a gson JsonReader. It disallows multiple - * elements of the same name unlike the default gson JsonParser." + * This class parses JSON elements from a gson JsonReader. It disallows multiple elements of the same name unlike the + * default gson JsonParser." */ public class JsonParser { public JsonElement parse(JsonReader reader) throws JsonIOException, JsonSyntaxException { diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonMapper.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonMapper.java index 85b4b2dee0..4b4cef9f70 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonMapper.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonMapper.java @@ -11,16 +11,13 @@ 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.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; - import javax.activation.UnsupportedDataTypeException; - import org.opendaylight.controller.sal.core.api.mount.MountInstance; import org.opendaylight.controller.sal.restconf.impl.ControllerContext; import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO; @@ -80,100 +77,95 @@ class JsonMapper { writer.endObject(); } - private void writeChildrenOfParent(final JsonWriter writer, final CompositeNode parent, final DataNodeContainer parentSchema) - throws IOException { + private void writeChildrenOfParent(final JsonWriter writer, final CompositeNode parent, + final DataNodeContainer parentSchema) throws IOException { checkNotNull(parent); final Set foundLists = new HashSet<>(); - Set parentSchemaChildNodes = parentSchema == null ? - Collections.emptySet() : parentSchema.getChildNodes(); - + Set parentSchemaChildNodes = parentSchema == null ? Collections. emptySet() + : parentSchema.getChildNodes(); - for (Node child : parent.getValue()) { - DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchemaChildNodes); + 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. + 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()); + LOG.debug("No schema found for data node \"{}\"", child.getNodeType()); - if( !foundLists.contains( child.getNodeType() ) ) { - handleNoSchemaFound( writer, child, parent ); + 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. + // 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."); - } + 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> 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 ); + private void handleNoSchemaFound(final JsonWriter writer, final Node node, final CompositeNode parent) + throws IOException { + if (node instanceof SimpleNode) { + List> 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() ); + for (SimpleNode leafNode : nodeLeafList) { + writeValue(writer, leafNode.getValue()); } writer.endArray(); } } else { // CompositeNode - Preconditions.checkState( node instanceof CompositeNode, + Preconditions.checkState(node instanceof CompositeNode, "Data representation of Container should be CompositeNode - %s", node.getNodeType()); - List 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 ); + List 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); } } } @@ -195,15 +187,16 @@ class JsonMapper { return null; } - private void writeContainer(final JsonWriter writer, final CompositeNode node, final ContainerSchemaNode schema) throws IOException { + 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 { + private void writeList(final JsonWriter writer, final CompositeNode nodeParent, final CompositeNode node, + final ListSchemaNode schema) throws IOException { writeName(node, schema, writer); writer.beginArray(); @@ -235,19 +228,20 @@ class JsonMapper { writer.endArray(); } - private void writeLeaf(final JsonWriter writer, final SimpleNode node, final LeafSchemaNode schema) throws IOException { + 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 { + 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()); + LOG.debug("While generationg JSON output null value was found for type {}.", baseType.getClass() + .getSimpleName()); } if (baseType instanceof IdentityrefTypeDefinition) { @@ -292,7 +286,8 @@ class JsonMapper { } } - private static void writeIdentityValuesDTOToJson(final JsonWriter writer, final IdentityValuesDTO valueDTO) throws IOException { + private static void writeIdentityValuesDTOToJson(final JsonWriter writer, final IdentityValuesDTO valueDTO) + throws IOException { StringBuilder result = new StringBuilder(); for (IdentityValue identityValue : valueDTO.getValuesWithNamespaces()) { result.append('/'); @@ -327,12 +322,11 @@ class JsonMapper { result.append(identityValue.getValue()); } - private static void writeStringRepresentation(final JsonWriter writer, final SimpleNode node, final TypeDefinition baseType, - final Class requiredType) throws IOException { + 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()); + 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 { @@ -348,7 +342,7 @@ class JsonMapper { private void writeName(final Node node, final DataSchemaNode schema, final JsonWriter writer) throws IOException { String nameForOutput = node.getNodeType().getLocalName(); - if ( schema != null && schema.isAugmenting()) { + if (schema != null && schema.isAugmenting()) { ControllerContext contContext = ControllerContext.getInstance(); CharSequence moduleName = null; if (mountPoint == null) { diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonToCompositeNodeProvider.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonToCompositeNodeProvider.java index 211e7e818a..2f3499e269 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonToCompositeNodeProvider.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonToCompositeNodeProvider.java @@ -28,32 +28,30 @@ import org.slf4j.LoggerFactory; @Provider @Consumes({ Draft02.MediaTypes.DATA + RestconfService.JSON, Draft02.MediaTypes.OPERATION + RestconfService.JSON, - MediaType.APPLICATION_JSON }) + MediaType.APPLICATION_JSON }) public enum JsonToCompositeNodeProvider implements MessageBodyReader { 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) { + public boolean isReadable(final Class type, final Type genericType, final Annotation[] annotations, + final MediaType mediaType) { return true; } @Override public CompositeNode readFrom(final Class type, final Type genericType, - final Annotation[] annotations, final MediaType mediaType, - final MultivaluedMap httpHeaders, - final InputStream entityStream) - throws IOException, WebApplicationException { + final Annotation[] annotations, final MediaType mediaType, + final MultivaluedMap httpHeaders, final InputStream entityStream) throws IOException, + WebApplicationException { try { return JsonToCompositeNodeReader.read(entityStream); } catch (Exception e) { - LOG.debug( "Error parsing json input", e); + LOG.debug("Error parsing json input", e); - throw new RestconfDocumentedException( - "Error parsing input: " + e.getMessage(), - ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE); + throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL, + ErrorTag.MALFORMED_MESSAGE); } } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonToCompositeNodeReader.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonToCompositeNodeReader.java index 082675b6d1..5fbb605558 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonToCompositeNodeReader.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonToCompositeNodeReader.java @@ -13,14 +13,12 @@ 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.Map.Entry; 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; @@ -38,12 +36,10 @@ class JsonToCompositeNodeReader { } - public static CompositeNodeWrapper read(final InputStream entityStream) - throws UnsupportedFormatException { + public static CompositeNodeWrapper read(final InputStream entityStream) throws UnsupportedFormatException { JsonParser parser = new JsonParser(); - JsonElement rootElement = parser.parse(new JsonReader( - new InputStreamReader(entityStream))); + JsonElement rootElement = parser.parse(new JsonReader(new InputStreamReader(entityStream))); if (rootElement.isJsonNull()) { // no content, so return null to indicate no input return null; @@ -53,8 +49,7 @@ class JsonToCompositeNodeReader { throw new UnsupportedFormatException("Root element of Json has to be Object"); } - Set> entrySetsOfRootJsonObject = - rootElement.getAsJsonObject().entrySet(); + Set> entrySetsOfRootJsonObject = rootElement.getAsJsonObject().entrySet(); if (entrySetsOfRootJsonObject.size() != 1) { throw new UnsupportedFormatException("Json Object should contain one element"); } @@ -81,8 +76,7 @@ class JsonToCompositeNodeReader { "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) { + private static CompositeNodeWrapper createStructureWithRoot(final String rootObjectName, final JsonObject rootObject) { CompositeNodeWrapper firstNode = new CompositeNodeWrapper(getNamespaceFor(rootObjectName), getLocalNameFor(rootObjectName)); for (Entry childOfFirstNode : rootObject.entrySet()) { @@ -92,7 +86,7 @@ class JsonToCompositeNodeReader { } private static void addChildToParent(final String childName, final JsonElement childType, - final CompositeNodeWrapper parent) { + final CompositeNodeWrapper parent) { if (childType.isJsonObject()) { CompositeNodeWrapper child = new CompositeNodeWrapper(getNamespaceFor(childName), getLocalNameFor(childName)); diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestUtil.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestUtil.java index cd263d3c55..7890931a27 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestUtil.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestUtil.java @@ -11,9 +11,7 @@ import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; - import javax.xml.stream.events.StartElement; - 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; @@ -106,8 +104,7 @@ public final class RestUtil { } result.add(new Predicate(null, predicateValue)); } else { - IdentityValue identityValue = toIdentity(predicate.substring(0, indexOfEqualityMark), - prefixMap); + IdentityValue identityValue = toIdentity(predicate.substring(0, indexOfEqualityMark), prefixMap); if (identityValue == null || predicateValue == null) { return null; } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfApplication.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfApplication.java index a5fd7bdaab..b4b2a1f9ef 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfApplication.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfApplication.java @@ -7,22 +7,19 @@ */ package org.opendaylight.controller.sal.rest.impl; +import com.google.common.collect.ImmutableSet; import java.util.HashSet; import java.util.Set; - import javax.ws.rs.core.Application; - import org.opendaylight.controller.sal.restconf.impl.BrokerFacade; import org.opendaylight.controller.sal.restconf.impl.ControllerContext; import org.opendaylight.controller.sal.restconf.impl.RestconfImpl; -import com.google.common.collect.ImmutableSet; - public class RestconfApplication extends Application { @Override public Set> getClasses() { - return ImmutableSet.>of( RestconfDocumentedExceptionMapper.class ); + return ImmutableSet.> of(RestconfDocumentedExceptionMapper.class); } @Override @@ -43,5 +40,4 @@ public class RestconfApplication extends Application { return singletons; } - } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfDocumentedExceptionMapper.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfDocumentedExceptionMapper.java index 0854ca7167..63a5b1b540 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfDocumentedExceptionMapper.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfDocumentedExceptionMapper.java @@ -21,7 +21,6 @@ import com.google.common.base.Charsets; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.gson.stream.JsonWriter; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; @@ -29,7 +28,6 @@ import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Map.Entry; - import javax.activation.UnsupportedDataTypeException; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; @@ -46,7 +44,6 @@ import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; - import org.opendaylight.controller.sal.restconf.impl.ControllerContext; import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException; import org.opendaylight.controller.sal.restconf.impl.RestconfError; @@ -63,24 +60,23 @@ import org.w3c.dom.Document; import org.xml.sax.InputSource; /** - * This class defines an ExceptionMapper that handles RestconfDocumentedExceptions thrown by - * resource implementations and translates appropriately to restconf error response as defined in - * the RESTCONF RFC draft. + * This class defines an ExceptionMapper that handles RestconfDocumentedExceptions thrown by resource implementations + * and translates appropriately to restconf error response as defined in the RESTCONF RFC draft. * * @author Thomas Pantelis */ @Provider public class RestconfDocumentedExceptionMapper implements ExceptionMapper { - private final static Logger LOG = LoggerFactory.getLogger( RestconfDocumentedExceptionMapper.class ); + private final static Logger LOG = LoggerFactory.getLogger(RestconfDocumentedExceptionMapper.class); @Context private HttpHeaders headers; @Override - public Response toResponse( final RestconfDocumentedException exception ) { + public Response toResponse(final RestconfDocumentedException exception) { - LOG.debug( "In toResponse: {}", exception.getMessage() ); + LOG.debug("In toResponse: {}", exception.getMessage()); // Default to the content type if there's no Accept header @@ -88,169 +84,158 @@ public class RestconfDocumentedExceptionMapper implements ExceptionMapper accepts = headers.getAcceptableMediaTypes(); - LOG.debug( "Accept headers: {}", accepts ); + LOG.debug("Accept headers: {}", accepts); - if( accepts != null && accepts.size() > 0 ) { - mediaType = accepts.get( 0 ); // just pick the first one + if (accepts != null && accepts.size() > 0) { + mediaType = accepts.get(0); // just pick the first one } - LOG.debug( "Using MediaType: {}", mediaType ); + LOG.debug("Using MediaType: {}", mediaType); List errors = exception.getErrors(); - if( errors.isEmpty() ) { + if (errors.isEmpty()) { // We don't actually want to send any content but, if we don't set any content here, // the tomcat front-end will send back an html error report. To prevent that, set a // single space char in the entity. - return Response.status( exception.getStatus() ) - .type( MediaType.TEXT_PLAIN_TYPE ) - .entity( " " ).build(); + return Response.status(exception.getStatus()).type(MediaType.TEXT_PLAIN_TYPE).entity(" ").build(); } int status = errors.iterator().next().getErrorTag().getStatusCode(); ControllerContext context = ControllerContext.getInstance(); - DataNodeContainer errorsSchemaNode = (DataNodeContainer)context.getRestconfModuleErrorsSchemaNode(); + DataNodeContainer errorsSchemaNode = (DataNodeContainer) context.getRestconfModuleErrorsSchemaNode(); - if( errorsSchemaNode == null ) { - return Response.status( status ) - .type( MediaType.TEXT_PLAIN_TYPE ) - .entity( exception.getMessage() ).build(); + if (errorsSchemaNode == null) { + return Response.status(status).type(MediaType.TEXT_PLAIN_TYPE).entity(exception.getMessage()).build(); } ImmutableList.Builder> errorNodes = ImmutableList.> builder(); - for( RestconfError error: errors ) { - errorNodes.add( toDomNode( error ) ); + for (RestconfError error : errors) { + errorNodes.add(toDomNode(error)); } - ImmutableCompositeNode errorsNode = - ImmutableCompositeNode.create( ERRORS_CONTAINER_QNAME, errorNodes.build() ); + ImmutableCompositeNode errorsNode = ImmutableCompositeNode.create(ERRORS_CONTAINER_QNAME, errorNodes.build()); Object responseBody; - if( mediaType.getSubtype().endsWith( "json" ) ) { - responseBody = toJsonResponseBody( errorsNode, errorsSchemaNode ); - } - else { - responseBody = toXMLResponseBody( errorsNode, errorsSchemaNode ); + if (mediaType.getSubtype().endsWith("json")) { + responseBody = toJsonResponseBody(errorsNode, errorsSchemaNode); + } else { + responseBody = toXMLResponseBody(errorsNode, errorsSchemaNode); } - return Response.status( status ).type( mediaType ).entity( responseBody ).build(); + return Response.status(status).type(mediaType).entity(responseBody).build(); } - private Object toJsonResponseBody( final ImmutableCompositeNode errorsNode, - final DataNodeContainer errorsSchemaNode ) { + private Object toJsonResponseBody(final ImmutableCompositeNode errorsNode, final DataNodeContainer errorsSchemaNode) { JsonMapper jsonMapper = new JsonMapper(null); Object responseBody = null; try { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - JsonWriter writer = new JsonWriter(new OutputStreamWriter( outStream, Charsets.UTF_8)); - writer.setIndent( " " ); + JsonWriter writer = new JsonWriter(new OutputStreamWriter(outStream, Charsets.UTF_8)); + writer.setIndent(" "); - jsonMapper.write( writer, errorsNode, errorsSchemaNode); + jsonMapper.write(writer, errorsNode, errorsSchemaNode); writer.flush(); - responseBody = outStream.toString( "UTF-8" ); - } catch( IOException e ) { - LOG.error( "Error writing error response body", e ); + responseBody = outStream.toString("UTF-8"); + } catch (IOException e) { + LOG.error("Error writing error response body", e); } return responseBody; } - private Object toXMLResponseBody( final ImmutableCompositeNode errorsNode, - final DataNodeContainer errorsSchemaNode ) { + private Object toXMLResponseBody(final ImmutableCompositeNode errorsNode, final DataNodeContainer errorsSchemaNode) { XmlMapper xmlMapper = new XmlMapper(); Object responseBody = null; try { - Document xmlDoc = xmlMapper.write( errorsNode, errorsSchemaNode ); + Document xmlDoc = xmlMapper.write(errorsNode, errorsSchemaNode); - responseBody = documentToString( xmlDoc ); - } - catch( TransformerException | UnsupportedDataTypeException | UnsupportedEncodingException e ) { - LOG.error( "Error writing error response body", e ); + responseBody = documentToString(xmlDoc); + } catch (TransformerException | UnsupportedDataTypeException | UnsupportedEncodingException e) { + LOG.error("Error writing error response body", e); } return responseBody; } - private String documentToString( final Document doc ) throws TransformerException, UnsupportedEncodingException { + private String documentToString(final Document doc) throws TransformerException, UnsupportedEncodingException { Transformer transformer = createTransformer(); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - transformer.transform( new DOMSource( doc ), new StreamResult( outStream ) ); + transformer.transform(new DOMSource(doc), new StreamResult(outStream)); - return outStream.toString( "UTF-8" ); + return outStream.toString("UTF-8"); } private Transformer createTransformer() throws TransformerFactoryConfigurationError, - TransformerConfigurationException { + TransformerConfigurationException { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); - transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "no" ); - transformer.setOutputProperty( OutputKeys.METHOD, "xml" ); - transformer.setOutputProperty( OutputKeys.INDENT, "yes" ); - transformer.setOutputProperty( OutputKeys.ENCODING, "UTF-8" ); - transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", "4" ); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); + transformer.setOutputProperty(OutputKeys.METHOD, "xml"); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); return transformer; } - private Node toDomNode( final RestconfError error ) { + private Node toDomNode(final RestconfError error) { CompositeNodeBuilder builder = ImmutableCompositeNode.builder(); - builder.setQName( ERROR_LIST_QNAME ); + builder.setQName(ERROR_LIST_QNAME); - addLeaf( builder, ERROR_TYPE_QNAME, error.getErrorType().getErrorTypeTag() ); - addLeaf( builder, ERROR_TAG_QNAME, error.getErrorTag().getTagValue() ); - addLeaf( builder, ERROR_MESSAGE_QNAME, error.getErrorMessage() ); - addLeaf( builder, ERROR_APP_TAG_QNAME, error.getErrorAppTag() ); + addLeaf(builder, ERROR_TYPE_QNAME, error.getErrorType().getErrorTypeTag()); + addLeaf(builder, ERROR_TAG_QNAME, error.getErrorTag().getTagValue()); + addLeaf(builder, ERROR_MESSAGE_QNAME, error.getErrorMessage()); + addLeaf(builder, ERROR_APP_TAG_QNAME, error.getErrorAppTag()); - Node errorInfoNode = parseErrorInfo( error.getErrorInfo() ); - if( errorInfoNode != null ) { - builder.add( errorInfoNode ); + Node errorInfoNode = parseErrorInfo(error.getErrorInfo()); + if (errorInfoNode != null) { + builder.add(errorInfoNode); } return builder.toInstance(); } - private Node parseErrorInfo( final String errorInfo ) { - if( Strings.isNullOrEmpty( errorInfo ) ) { + private Node parseErrorInfo(final String errorInfo) { + if (Strings.isNullOrEmpty(errorInfo)) { return null; } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware( true ); - factory.setCoalescing( true ); - factory.setIgnoringElementContentWhitespace( true ); - factory.setIgnoringComments( true ); + factory.setNamespaceAware(true); + factory.setCoalescing(true); + factory.setIgnoringElementContentWhitespace(true); + factory.setIgnoringComments(true); // Wrap the error info content in a root element so it can be parsed // as XML. The error info content may or may not be XML. If not then it will be // parsed as text content of the element. - String errorInfoWithRoot = - new StringBuilder( "" ) - .append( errorInfo ).append( "" ).toString(); + String errorInfoWithRoot = new StringBuilder("") + .append(errorInfo).append("").toString(); Document doc = null; try { - doc = factory.newDocumentBuilder().parse( - new InputSource( new StringReader( errorInfoWithRoot ) ) ); - } catch( Exception e ) { - // TODO: what if the content is text that happens to contain invalid markup? Could - // wrap in CDATA and try again. + doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(errorInfoWithRoot))); + } catch (Exception e) { + // TODO: what if the content is text that happens to contain invalid markup? + // Could wrap in CDATA and try again. - LOG.warn( "Error parsing restconf error-info, \"{}\", as XML", errorInfo, e); + LOG.warn("Error parsing restconf error-info, \"{}\", as XML", errorInfo, e); return null; } - Node errorInfoNode = XmlDocumentUtils.toDomNode( doc ); + Node errorInfoNode = XmlDocumentUtils.toDomNode(doc); - if( errorInfoNode instanceof CompositeNode ) { - CompositeNode compositeNode = (CompositeNode)XmlDocumentUtils.toDomNode( doc ); + if (errorInfoNode instanceof CompositeNode) { + CompositeNode compositeNode = (CompositeNode) XmlDocumentUtils.toDomNode(doc); // At this point the QName for the "error-info" CompositeNode doesn't contain the revision // as it isn't present in the XML. So we'll copy all the child nodes and create a new @@ -258,20 +243,20 @@ public class RestconfDocumentedExceptionMapper implements ExceptionMapper> childNodes = ImmutableList.builder(); - for( Entry>> entry: compositeNode.entrySet() ) { - childNodes.addAll( entry.getValue() ); + for (Entry>> entry : compositeNode.entrySet()) { + childNodes.addAll(entry.getValue()); } - errorInfoNode = ImmutableCompositeNode.create( ERROR_INFO_QNAME, childNodes.build() ); + errorInfoNode = ImmutableCompositeNode.create(ERROR_INFO_QNAME, childNodes.build()); } return errorInfoNode; } - private void addLeaf( final CompositeNodeBuilder builder, final QName qname, - final String value ) { - if( !Strings.isNullOrEmpty( value ) ) { - builder.addLeaf( qname, value ); + private void addLeaf(final CompositeNodeBuilder builder, final QName qname, + final String value) { + if (!Strings.isNullOrEmpty(value)) { + builder.addLeaf(qname, value); } } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfProvider.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfProvider.java index 1c95f1327b..1f1d0eb831 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfProvider.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfProvider.java @@ -9,7 +9,6 @@ package org.opendaylight.controller.sal.rest.impl; import java.util.Collection; import java.util.Collections; - import org.opendaylight.controller.sal.core.api.Broker; import org.opendaylight.controller.sal.core.api.Broker.ProviderSession; import org.opendaylight.controller.sal.core.api.Provider; @@ -52,8 +51,8 @@ public class RestconfProvider implements BundleActivator, Provider, ServiceTrack @Override public void start(BundleContext context) throws Exception { String websocketPortStr = context.getProperty(WebSocketServer.WEBSOCKET_SERVER_CONFIG_PROPERTY); - int websocketPort = (websocketPortStr != null && !"".equals(websocketPortStr)) - ? Integer.parseInt(websocketPortStr) : WebSocketServer.DEFAULT_PORT; + int websocketPort = (websocketPortStr != null && !"".equals(websocketPortStr)) ? Integer + .parseInt(websocketPortStr) : WebSocketServer.DEFAULT_PORT; bundleContext = context; webSocketServerThread = new Thread(WebSocketServer.createInstance(websocketPort)); webSocketServerThread.setName("Web socket server"); diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToJsonProvider.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToJsonProvider.java index 063d2f51af..933ed0f849 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToJsonProvider.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToJsonProvider.java @@ -30,24 +30,27 @@ import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; @Provider @Produces({ Draft02.MediaTypes.API + RestconfService.JSON, Draft02.MediaTypes.DATA + RestconfService.JSON, - Draft02.MediaTypes.OPERATION + RestconfService.JSON, MediaType.APPLICATION_JSON }) + Draft02.MediaTypes.OPERATION + RestconfService.JSON, MediaType.APPLICATION_JSON }) public enum StructuredDataToJsonProvider implements MessageBodyWriter { INSTANCE; @Override - public boolean isWriteable(final Class type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) { + 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) { + 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 httpHeaders, final OutputStream entityStream) - throws IOException, WebApplicationException { + public void writeTo(final StructuredData t, final Class type, final Type genericType, + final Annotation[] annotations, final MediaType mediaType, + final MultivaluedMap httpHeaders, final OutputStream entityStream) throws IOException, + WebApplicationException { CompositeNode data = t.getData(); if (data == null) { throw new RestconfDocumentedException(Response.Status.NOT_FOUND); diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToXmlProvider.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToXmlProvider.java index 3a235ced85..703a2a4634 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToXmlProvider.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToXmlProvider.java @@ -39,7 +39,7 @@ import org.w3c.dom.Document; @Provider @Produces({ Draft02.MediaTypes.API + RestconfService.XML, Draft02.MediaTypes.DATA + RestconfService.XML, - Draft02.MediaTypes.OPERATION + RestconfService.XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML }) + Draft02.MediaTypes.OPERATION + RestconfService.XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML }) public enum StructuredDataToXmlProvider implements MessageBodyWriter { INSTANCE; @@ -67,19 +67,22 @@ public enum StructuredDataToXmlProvider implements MessageBodyWriter type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) { + 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) { + 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 httpHeaders, final OutputStream entityStream) - throws IOException, WebApplicationException { + public void writeTo(final StructuredData t, final Class type, final Type genericType, + final Annotation[] annotations, final MediaType mediaType, + final MultivaluedMap httpHeaders, final OutputStream entityStream) throws IOException, + WebApplicationException { CompositeNode data = t.getData(); if (data == null) { throw new RestconfDocumentedException(Response.Status.NOT_FOUND); @@ -94,8 +97,7 @@ public enum StructuredDataToXmlProvider implements MessageBodyWriter absent()); diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/XmlToCompositeNodeReader.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/XmlToCompositeNodeReader.java index 7d0690cdc2..413823f520 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/XmlToCompositeNodeReader.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/XmlToCompositeNodeReader.java @@ -36,8 +36,7 @@ public class XmlToCompositeNodeReader { public CompositeNodeWrapper 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. + // see if there is any content being provided. entityStream = getMarkableStream(entityStream); if (isInputStreamEmpty(entityStream)) { @@ -103,9 +102,8 @@ public class XmlToCompositeNodeReader { } /** - * 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. + * 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 diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/package-info.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/package-info.java index 62afdbd10d..9560333e71 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/package-info.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/package-info.java @@ -5,4 +5,4 @@ * 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; +package org.opendaylight.controller.sal.rest.impl; \ No newline at end of file diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/BrokerFacade.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/BrokerFacade.java index 3d047dd07f..a2c228788f 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/BrokerFacade.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/BrokerFacade.java @@ -32,7 +32,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BrokerFacade implements DataReader { - private final static Logger LOG = LoggerFactory.getLogger( BrokerFacade.class ); + private final static Logger LOG = LoggerFactory.getLogger(BrokerFacade.class); private final static BrokerFacade INSTANCE = new BrokerFacade(); @@ -42,11 +42,11 @@ public class BrokerFacade implements DataReader> invokeRpc( final QName type, final CompositeNode payload ) { + public Future> invokeRpc(final QName type, final CompositeNode payload) { this.checkPreconditions(); - return context.rpc( type, payload ); + return context.rpc(type, payload); } - public Future> commitConfigurationDataPut( final InstanceIdentifier path, - final CompositeNode payload ) { + public Future> commitConfigurationDataPut(final InstanceIdentifier path, + final CompositeNode payload) { this.checkPreconditions(); final DataModificationTransaction transaction = dataService.beginTransaction(); - BrokerFacade.LOG.trace( "Put Configuration via Restconf: {}", path ); - transaction.putConfigurationData( path, payload ); + BrokerFacade.LOG.trace("Put Configuration via Restconf: {}", path); + transaction.putConfigurationData(path, payload); return transaction.commit(); } public Future> commitConfigurationDataPutBehindMountPoint( - final MountInstance mountPoint, final InstanceIdentifier path, final CompositeNode payload ) { + final MountInstance mountPoint, final InstanceIdentifier path, final CompositeNode payload) { this.checkPreconditions(); final DataModificationTransaction transaction = mountPoint.beginTransaction(); - BrokerFacade.LOG.trace( "Put Configuration via Restconf: {}", path ); - transaction.putConfigurationData( path, payload ); + BrokerFacade.LOG.trace("Put Configuration via Restconf: {}", path); + transaction.putConfigurationData(path, payload); return transaction.commit(); } - public Future> commitConfigurationDataPost( final InstanceIdentifier path, - final CompositeNode payload) { + public Future> commitConfigurationDataPost(final InstanceIdentifier path, + final CompositeNode payload) { this.checkPreconditions(); final DataModificationTransaction transaction = dataService.beginTransaction(); /* check for available Node in Configuration DataStore by path */ - CompositeNode availableNode = transaction.readConfigurationData( path ); + CompositeNode availableNode = transaction.readConfigurationData(path); if (availableNode != null) { String errMsg = "Post Configuration via Restconf was not executed because data already exists"; BrokerFacade.LOG.warn((new StringBuilder(errMsg)).append(" : ").append(path).toString()); - throw new RestconfDocumentedException( - "Data already exists for path: " + path, ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS ); + throw new RestconfDocumentedException("Data already exists for path: " + path, ErrorType.PROTOCOL, + ErrorTag.DATA_EXISTS); } - BrokerFacade.LOG.trace( "Post Configuration via Restconf: {}", path ); - transaction.putConfigurationData( path, payload ); + BrokerFacade.LOG.trace("Post Configuration via Restconf: {}", path); + transaction.putConfigurationData(path, payload); return transaction.commit(); } public Future> commitConfigurationDataPostBehindMountPoint( - final MountInstance mountPoint, final InstanceIdentifier path, final CompositeNode payload ) { + final MountInstance mountPoint, final InstanceIdentifier path, final CompositeNode payload) { this.checkPreconditions(); final DataModificationTransaction transaction = mountPoint.beginTransaction(); /* check for available Node in Configuration DataStore by path */ - CompositeNode availableNode = transaction.readConfigurationData( path ); + CompositeNode availableNode = transaction.readConfigurationData(path); if (availableNode != null) { String errMsg = "Post Configuration via Restconf was not executed because data already exists"; BrokerFacade.LOG.warn((new StringBuilder(errMsg)).append(" : ").append(path).toString()); - throw new RestconfDocumentedException( - "Data already exists for path: " + path, ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS ); + throw new RestconfDocumentedException("Data already exists for path: " + path, ErrorType.PROTOCOL, + ErrorTag.DATA_EXISTS); } - BrokerFacade.LOG.trace( "Post Configuration via Restconf: {}", path ); - transaction.putConfigurationData( path, payload ); + BrokerFacade.LOG.trace("Post Configuration via Restconf: {}", path); + transaction.putConfigurationData(path, payload); return transaction.commit(); } - public Future> commitConfigurationDataDelete( final InstanceIdentifier path ) { + public Future> commitConfigurationDataDelete(final InstanceIdentifier path) { this.checkPreconditions(); - return deleteDataAtTarget(path,dataService.beginTransaction()); + return deleteDataAtTarget(path, dataService.beginTransaction()); } public Future> commitConfigurationDataDeleteBehindMountPoint( - final MountInstance mountPoint, final InstanceIdentifier path ) { + final MountInstance mountPoint, final InstanceIdentifier path) { this.checkPreconditions(); - return deleteDataAtTarget(path,mountPoint.beginTransaction()); + return deleteDataAtTarget(path, mountPoint.beginTransaction()); } private Future> deleteDataAtTarget(final InstanceIdentifier path, @@ -183,17 +183,17 @@ public class BrokerFacade implements DataReader registration = - dataService.registerDataChangeListener( path, listener ); + final ListenerRegistration registration = dataService.registerDataChangeListener(path, + listener); - listener.setRegistration( registration ); + listener.setRegistration(registration); } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/CompositeNodeWrapper.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/CompositeNodeWrapper.java index 69b975dab7..206dbdeab6 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/CompositeNodeWrapper.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/CompositeNodeWrapper.java @@ -8,7 +8,6 @@ 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; @@ -16,7 +15,6 @@ 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; diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/ControllerContext.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/ControllerContext.java index 28e6a3c247..29672f39d4 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/ControllerContext.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/ControllerContext.java @@ -18,7 +18,6 @@ import com.google.common.collect.BiMap; import com.google.common.collect.FluentIterable; import com.google.common.collect.HashBiMap; import com.google.common.collect.Iterables; - import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLDecoder; @@ -32,9 +31,7 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; - import javax.ws.rs.core.Response.Status; - import org.opendaylight.controller.sal.core.api.mount.MountInstance; import org.opendaylight.controller.sal.core.api.mount.MountService; import org.opendaylight.controller.sal.rest.api.Draft02; @@ -68,7 +65,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ControllerContext implements SchemaContextListener { - private final static Logger LOG = LoggerFactory.getLogger( ControllerContext.class ); + private final static Logger LOG = LoggerFactory.getLogger(ControllerContext.class); private final static ControllerContext INSTANCE = new ControllerContext(); @@ -95,11 +92,11 @@ public class ControllerContext implements SchemaContextListener { private volatile SchemaContext globalSchema; private volatile MountService mountService; - public void setGlobalSchema( final SchemaContext globalSchema ) { + public void setGlobalSchema(final SchemaContext globalSchema) { this.globalSchema = globalSchema; } - public void setMountService( final MountService mountService ) { + public void setMountService(final MountService mountService) { this.mountService = mountService; } @@ -111,162 +108,157 @@ public class ControllerContext implements SchemaContextListener { } private void checkPreconditions() { - if( globalSchema == null ) { - throw new RestconfDocumentedException( Status.SERVICE_UNAVAILABLE ); + if (globalSchema == null) { + throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE); } } - public void setSchemas( final SchemaContext schemas ) { - this.onGlobalContextUpdated( schemas ); + public void setSchemas(final SchemaContext schemas) { + this.onGlobalContextUpdated(schemas); } - public InstanceIdWithSchemaNode toInstanceIdentifier( final String restconfInstance ) { - return this.toIdentifier( restconfInstance, false ); + public InstanceIdWithSchemaNode toInstanceIdentifier(final String restconfInstance) { + return this.toIdentifier(restconfInstance, false); } - public InstanceIdWithSchemaNode toMountPointIdentifier( final String restconfInstance ) { - return this.toIdentifier( restconfInstance, true ); + public InstanceIdWithSchemaNode toMountPointIdentifier(final String restconfInstance) { + return this.toIdentifier(restconfInstance, true); } - private InstanceIdWithSchemaNode toIdentifier( final String restconfInstance, - final boolean toMountPointIdentifier ) { + private InstanceIdWithSchemaNode toIdentifier(final String restconfInstance, final boolean toMountPointIdentifier) { this.checkPreconditions(); - final List pathArgs = urlPathArgsDecode( SLASH_SPLITTER.split( restconfInstance ) ); - omitFirstAndLastEmptyString( pathArgs ); - if( pathArgs.isEmpty() ) { + final List pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance)); + omitFirstAndLastEmptyString(pathArgs); + if (pathArgs.isEmpty()) { return null; } String first = pathArgs.iterator().next(); - final String startModule = ControllerContext.toModuleName( first ); - if( startModule == null ) { - throw new RestconfDocumentedException( - "First node in URI has to be in format \"moduleName:nodeName\"", - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + final String startModule = ControllerContext.toModuleName(first); + if (startModule == null) { + throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"", + ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } InstanceIdentifierBuilder builder = InstanceIdentifier.builder(); - Module latestModule = this.getLatestModule( globalSchema, startModule ); - InstanceIdWithSchemaNode iiWithSchemaNode = this.collectPathArguments( builder, pathArgs, - latestModule, null, toMountPointIdentifier ); + Module latestModule = this.getLatestModule(globalSchema, startModule); + InstanceIdWithSchemaNode iiWithSchemaNode = this.collectPathArguments(builder, pathArgs, latestModule, null, + toMountPointIdentifier); - if( iiWithSchemaNode == null ) { - throw new RestconfDocumentedException( - "URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + if (iiWithSchemaNode == null) { + throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } return iiWithSchemaNode; } - private static List omitFirstAndLastEmptyString( final List list ) { - if( list.isEmpty() ) { + private static List omitFirstAndLastEmptyString(final List list) { + if (list.isEmpty()) { return list; } String head = list.iterator().next(); - if( head.isEmpty() ) { - list.remove( 0 ); + if (head.isEmpty()) { + list.remove(0); } - if( list.isEmpty() ) { + if (list.isEmpty()) { return list; } - String last = list.get( list.size() - 1 ); - if( last.isEmpty() ) { - list.remove( list.size() - 1 ); + String last = list.get(list.size() - 1); + if (last.isEmpty()) { + list.remove(list.size() - 1); } return list; } - private Module getLatestModule( final SchemaContext schema, final String moduleName ) { - Preconditions.checkArgument( schema != null ); - Preconditions.checkArgument( moduleName != null && !moduleName.isEmpty() ); + private Module getLatestModule(final SchemaContext schema, final String moduleName) { + Preconditions.checkArgument(schema != null); + Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty()); Predicate filter = new Predicate() { @Override - public boolean apply( final Module m ) { - return Objects.equal( m.getName(), moduleName ); + public boolean apply(final Module m) { + return Objects.equal(m.getName(), moduleName); } }; - Iterable modules = Iterables.filter( schema.getModules(), filter ); - return this.filterLatestModule( modules ); + Iterable modules = Iterables.filter(schema.getModules(), filter); + return this.filterLatestModule(modules); } - private Module filterLatestModule( final Iterable modules ) { + private Module filterLatestModule(final Iterable modules) { Module latestModule = modules.iterator().hasNext() ? modules.iterator().next() : null; - for( final Module module : modules ) { - if( module.getRevision().after( latestModule.getRevision() ) ) { + for (final Module module : modules) { + if (module.getRevision().after(latestModule.getRevision())) { latestModule = module; } } return latestModule; } - public Module findModuleByName( final String moduleName ) { + public Module findModuleByName(final String moduleName) { this.checkPreconditions(); - Preconditions.checkArgument( moduleName != null && !moduleName.isEmpty() ); - return this.getLatestModule( globalSchema, moduleName ); + Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty()); + return this.getLatestModule(globalSchema, moduleName); } - public Module findModuleByName( final MountInstance mountPoint, final String moduleName ) { - Preconditions.checkArgument( moduleName != null && mountPoint != null ); + public Module findModuleByName(final MountInstance mountPoint, final String moduleName) { + Preconditions.checkArgument(moduleName != null && mountPoint != null); final SchemaContext mountPointSchema = mountPoint.getSchemaContext(); - return mountPointSchema == null ? null : this.getLatestModule( mountPointSchema, moduleName ); + return mountPointSchema == null ? null : this.getLatestModule(mountPointSchema, moduleName); } - public Module findModuleByNamespace( final URI namespace ) { + public Module findModuleByNamespace(final URI namespace) { this.checkPreconditions(); - Preconditions.checkArgument( namespace != null ); + Preconditions.checkArgument(namespace != null); - final Set moduleSchemas = globalSchema.findModuleByNamespace( namespace ); - return moduleSchemas == null ? null : this.filterLatestModule( moduleSchemas ); + final Set moduleSchemas = globalSchema.findModuleByNamespace(namespace); + return moduleSchemas == null ? null : this.filterLatestModule(moduleSchemas); } - public Module findModuleByNamespace( final MountInstance mountPoint, final URI namespace ) { - Preconditions.checkArgument( namespace != null && mountPoint != null ); + public Module findModuleByNamespace(final MountInstance mountPoint, final URI namespace) { + Preconditions.checkArgument(namespace != null && mountPoint != null); final SchemaContext mountPointSchema = mountPoint.getSchemaContext(); - Set moduleSchemas = mountPointSchema == null ? null : - mountPointSchema.findModuleByNamespace( namespace ); - return moduleSchemas == null ? null : this.filterLatestModule( moduleSchemas ); + Set moduleSchemas = mountPointSchema == null ? null : mountPointSchema.findModuleByNamespace(namespace); + return moduleSchemas == null ? null : this.filterLatestModule(moduleSchemas); } - public Module findModuleByNameAndRevision( final QName module ) { + public Module findModuleByNameAndRevision(final QName module) { this.checkPreconditions(); - Preconditions.checkArgument( module != null && module.getLocalName() != null && - module.getRevision() != null ); + Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null); - return globalSchema.findModuleByName( module.getLocalName(), module.getRevision() ); + return globalSchema.findModuleByName(module.getLocalName(), module.getRevision()); } - public Module findModuleByNameAndRevision( final MountInstance mountPoint, final QName module ) { + public Module findModuleByNameAndRevision(final MountInstance mountPoint, final QName module) { this.checkPreconditions(); - Preconditions.checkArgument( module != null && module.getLocalName() != null && - module.getRevision() != null && mountPoint != null ); + Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null + && mountPoint != null); SchemaContext schemaContext = mountPoint.getSchemaContext(); - return schemaContext == null ? null : - schemaContext.findModuleByName( module.getLocalName(), module.getRevision() ); + return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(), + module.getRevision()); } - public DataNodeContainer getDataNodeContainerFor( final InstanceIdentifier path ) { + public DataNodeContainer getDataNodeContainerFor(final InstanceIdentifier path) { this.checkPreconditions(); final Iterable elements = path.getPathArguments(); PathArgument head = elements.iterator().next(); final QName startQName = head.getNodeType(); - final Module initialModule = globalSchema.findModuleByNamespaceAndRevision( - startQName.getNamespace(), startQName.getRevision() ); + final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(), + startQName.getRevision()); DataNodeContainer node = initialModule; - for( final PathArgument element : elements ) { + for (final PathArgument element : elements) { QName _nodeType = element.getNodeType(); - final DataSchemaNode potentialNode = ControllerContext.childByQName( node, _nodeType ); - if( potentialNode == null || !this.isListOrContainer( potentialNode ) ) { + final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType); + if (potentialNode == null || !this.isListOrContainer(potentialNode)) { return null; } node = (DataNodeContainer) potentialNode; @@ -275,68 +267,68 @@ public class ControllerContext implements SchemaContextListener { return node; } - public String toFullRestconfIdentifier( final InstanceIdentifier path ) { + public String toFullRestconfIdentifier(final InstanceIdentifier path) { this.checkPreconditions(); final Iterable elements = path.getPathArguments(); final StringBuilder builder = new StringBuilder(); PathArgument head = elements.iterator().next(); final QName startQName = head.getNodeType(); - final Module initialModule = globalSchema.findModuleByNamespaceAndRevision( - startQName.getNamespace(), startQName.getRevision() ); + final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(), + startQName.getRevision()); DataNodeContainer node = initialModule; - for( final PathArgument element : elements ) { + for (final PathArgument element : elements) { QName _nodeType = element.getNodeType(); - final DataSchemaNode potentialNode = ControllerContext.childByQName( node, _nodeType ); - if( !this.isListOrContainer( potentialNode ) ) { + final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType); + if (!this.isListOrContainer(potentialNode)) { return null; } node = ((DataNodeContainer) potentialNode); - builder.append( this.convertToRestconfIdentifier( element, node ) ); + builder.append(this.convertToRestconfIdentifier(element, node)); } return builder.toString(); } - public String findModuleNameByNamespace( final URI namespace ) { + public String findModuleNameByNamespace(final URI namespace) { this.checkPreconditions(); - String moduleName = this.uriToModuleName.get( namespace ); - if( moduleName == null ) { - final Module module = this.findModuleByNamespace( namespace ); - if( module != null ) { + String moduleName = this.uriToModuleName.get(namespace); + if (moduleName == null) { + final Module module = this.findModuleByNamespace(namespace); + if (module != null) { moduleName = module.getName(); - this.uriToModuleName.put( namespace, moduleName ); + this.uriToModuleName.put(namespace, moduleName); } } return moduleName; } - public String findModuleNameByNamespace( final MountInstance mountPoint, final URI namespace ) { - final Module module = this.findModuleByNamespace( mountPoint, namespace ); + public String findModuleNameByNamespace(final MountInstance mountPoint, final URI namespace) { + final Module module = this.findModuleByNamespace(mountPoint, namespace); return module == null ? null : module.getName(); } - public URI findNamespaceByModuleName( final String moduleName ) { - URI namespace = this.moduleNameToUri.get( moduleName ); - if( namespace == null ) { - Module module = this.findModuleByName( moduleName ); - if( module != null ) { + public URI findNamespaceByModuleName(final String moduleName) { + URI namespace = this.moduleNameToUri.get(moduleName); + if (namespace == null) { + Module module = this.findModuleByName(moduleName); + if (module != null) { URI _namespace = module.getNamespace(); namespace = _namespace; - this.uriToModuleName.put( namespace, moduleName ); + this.uriToModuleName.put(namespace, moduleName); } } return namespace; } - public URI findNamespaceByModuleName( final MountInstance mountPoint, final String moduleName ) { - final Module module = this.findModuleByName( mountPoint, moduleName ); + public URI findNamespaceByModuleName(final MountInstance mountPoint, final String moduleName) { + final Module module = this.findModuleByName(mountPoint, moduleName); return module == null ? null : module.getNamespace(); } - public Set getAllModules( final MountInstance mountPoint ) { + public Set getAllModules(final MountInstance mountPoint) { this.checkPreconditions(); SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext(); @@ -348,55 +340,55 @@ public class ControllerContext implements SchemaContextListener { return globalSchema.getModules(); } - public CharSequence toRestconfIdentifier( final QName qname ) { + public CharSequence toRestconfIdentifier(final QName qname) { this.checkPreconditions(); - String module = this.uriToModuleName.get( qname.getNamespace() ); - if( module == null ) { - final Module moduleSchema = globalSchema.findModuleByNamespaceAndRevision( - qname.getNamespace(), qname.getRevision() ); - if( moduleSchema == null ) { + String module = this.uriToModuleName.get(qname.getNamespace()); + if (module == null) { + final Module moduleSchema = globalSchema.findModuleByNamespaceAndRevision(qname.getNamespace(), + qname.getRevision()); + if (moduleSchema == null) { return null; } - this.uriToModuleName.put( qname.getNamespace(), moduleSchema.getName() ); + this.uriToModuleName.put(qname.getNamespace(), moduleSchema.getName()); module = moduleSchema.getName(); } StringBuilder builder = new StringBuilder(); - builder.append( module ); - builder.append( ":" ); - builder.append( qname.getLocalName() ); + builder.append(module); + builder.append(":"); + builder.append(qname.getLocalName()); return builder.toString(); } - public CharSequence toRestconfIdentifier( final MountInstance mountPoint, final QName qname ) { - if( mountPoint == null ) { + public CharSequence toRestconfIdentifier(final MountInstance mountPoint, final QName qname) { + if (mountPoint == null) { return null; } SchemaContext schemaContext = mountPoint.getSchemaContext(); - final Module moduleSchema = schemaContext.findModuleByNamespaceAndRevision( - qname.getNamespace(), qname.getRevision() ); - if( moduleSchema == null ) { + final Module moduleSchema = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(), + qname.getRevision()); + if (moduleSchema == null) { return null; } StringBuilder builder = new StringBuilder(); - builder.append( moduleSchema.getName() ); - builder.append( ":" ); - builder.append( qname.getLocalName() ); + builder.append(moduleSchema.getName()); + builder.append(":"); + builder.append(qname.getLocalName()); return builder.toString(); } public Module getRestconfModule() { - return findModuleByNameAndRevision( Draft02.RestConfModule.IETF_RESTCONF_QNAME ); + return findModuleByNameAndRevision(Draft02.RestConfModule.IETF_RESTCONF_QNAME); } public DataSchemaNode getRestconfModuleErrorsSchemaNode() { Module restconfModule = getRestconfModule(); - if( restconfModule == null ) { + if (restconfModule == null) { return null; } @@ -405,8 +397,7 @@ public class ControllerContext implements SchemaContextListener { final Predicate filter = new Predicate() { @Override public boolean apply(final GroupingDefinition g) { - return Objects.equal(g.getQName().getLocalName(), - Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE); + return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE); } }; @@ -414,20 +405,18 @@ public class ControllerContext implements SchemaContextListener { final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null); - List instanceDataChildrenByName = - this.findInstanceDataChildrenByName(restconfGrouping, - Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE); + List instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping, + Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE); return Iterables.getFirst(instanceDataChildrenByName, null); } - public DataSchemaNode getRestconfModuleRestConfSchemaNode( final Module inRestconfModule, - final String schemaNodeName ) { + public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) { Module restconfModule = inRestconfModule; - if( restconfModule == null ) { + if (restconfModule == null) { restconfModule = getRestconfModule(); } - if( restconfModule == null ) { + if (restconfModule == null) { return null; } @@ -436,8 +425,7 @@ public class ControllerContext implements SchemaContextListener { final Predicate filter = new Predicate() { @Override public boolean apply(final GroupingDefinition g) { - return Objects.equal(g.getQName().getLocalName(), - Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE); + return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE); } }; @@ -445,61 +433,49 @@ public class ControllerContext implements SchemaContextListener { final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null); - List instanceDataChildrenByName = - this.findInstanceDataChildrenByName(restconfGrouping, - Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE); + List instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping, + Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE); final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null); if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) { - List instances = - this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer), - Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE); + List instances = this.findInstanceDataChildrenByName( + ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE); return Iterables.getFirst(instances, null); - } - else if(Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) { - List instances = - this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer), - Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE); + } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) { + List instances = this.findInstanceDataChildrenByName( + ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE); return Iterables.getFirst(instances, null); - } - else if(Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) { - List instances = - this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer), - Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE); + } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) { + List instances = this.findInstanceDataChildrenByName( + ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE); final DataSchemaNode modules = Iterables.getFirst(instances, null); instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules), Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE); return Iterables.getFirst(instances, null); - } - else if(Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) { - List instances = - this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer), - Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE); + } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) { + List instances = this.findInstanceDataChildrenByName( + ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE); return Iterables.getFirst(instances, null); - } - else if(Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) { - List instances = - this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer), - Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE); + } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) { + List instances = this.findInstanceDataChildrenByName( + ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE); final DataSchemaNode modules = Iterables.getFirst(instances, null); instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules), Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE); return Iterables.getFirst(instances, null); - } - else if(Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) { - List instances = - this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer), - Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE); + } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) { + List instances = this.findInstanceDataChildrenByName( + ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE); return Iterables.getFirst(instances, null); } return null; } - private static DataSchemaNode childByQName( final ChoiceNode container, final QName name ) { - for( final ChoiceCaseNode caze : container.getCases() ) { - final DataSchemaNode ret = ControllerContext.childByQName( caze, name ); - if( ret != null ) { + private static DataSchemaNode childByQName(final ChoiceNode container, final QName name) { + for (final ChoiceCaseNode caze : container.getCases()) { + final DataSchemaNode ret = ControllerContext.childByQName(caze, name); + if (ret != null) { return ret; } } @@ -507,34 +483,34 @@ public class ControllerContext implements SchemaContextListener { return null; } - private static DataSchemaNode childByQName( final ChoiceCaseNode container, final QName name ) { - return container.getDataChildByName( name ); + private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) { + return container.getDataChildByName(name); } - private static DataSchemaNode childByQName( final ContainerSchemaNode container, final QName name ) { - return ControllerContext.dataNodeChildByQName( container, name ); + private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) { + return ControllerContext.dataNodeChildByQName(container, name); } - private static DataSchemaNode childByQName( final ListSchemaNode container, final QName name ) { - return ControllerContext.dataNodeChildByQName( container, name ); + private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) { + return ControllerContext.dataNodeChildByQName(container, name); } - private static DataSchemaNode childByQName( final Module container, final QName name ) { - return ControllerContext.dataNodeChildByQName( container, name ); + private static DataSchemaNode childByQName(final Module container, final QName name) { + return ControllerContext.dataNodeChildByQName(container, name); } - private static DataSchemaNode childByQName( final DataSchemaNode container, final QName name ) { + private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) { return null; } - private static DataSchemaNode dataNodeChildByQName( final DataNodeContainer container, final QName name ) { - DataSchemaNode ret = container.getDataChildByName( name ); - if( ret == null ) { - for( final DataSchemaNode node : container.getChildNodes() ) { - if( (node instanceof ChoiceCaseNode) ) { + private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) { + DataSchemaNode ret = container.getDataChildByName(name); + if (ret == null) { + for (final DataSchemaNode node : container.getChildNodes()) { + if ((node instanceof ChoiceCaseNode)) { final ChoiceCaseNode caseNode = ((ChoiceCaseNode) node); - DataSchemaNode childByQName = ControllerContext.childByQName( caseNode, name ); - if( childByQName != null ) { + DataSchemaNode childByQName = ControllerContext.childByQName(caseNode, name); + if (childByQName != null) { return childByQName; } } @@ -543,463 +519,427 @@ public class ControllerContext implements SchemaContextListener { return ret; } - private String toUriString( final Object object ) throws UnsupportedEncodingException { - return object == null ? "" : - URLEncoder.encode( object.toString(), ControllerContext.URI_ENCODING_CHAR_SET ); + private String toUriString(final Object object) throws UnsupportedEncodingException { + return object == null ? "" : URLEncoder.encode(object.toString(), ControllerContext.URI_ENCODING_CHAR_SET); } - private InstanceIdWithSchemaNode collectPathArguments( final InstanceIdentifierBuilder builder, + private InstanceIdWithSchemaNode collectPathArguments(final InstanceIdentifierBuilder builder, final List strings, final DataNodeContainer parentNode, final MountInstance mountPoint, - final boolean returnJustMountPoint ) { - Preconditions.> checkNotNull( strings ); + final boolean returnJustMountPoint) { + Preconditions.> checkNotNull(strings); - if( parentNode == null ) { + if (parentNode == null) { return null; } - if( strings.isEmpty() ) { - return new InstanceIdWithSchemaNode( builder.toInstance(), - ((DataSchemaNode) parentNode), mountPoint ); + if (strings.isEmpty()) { + return new InstanceIdWithSchemaNode(builder.toInstance(), ((DataSchemaNode) parentNode), mountPoint); } String head = strings.iterator().next(); - final String nodeName = toNodeName( head ); - final String moduleName = ControllerContext.toModuleName( head ); + final String nodeName = toNodeName(head); + final String moduleName = ControllerContext.toModuleName(head); DataSchemaNode targetNode = null; - if( !Strings.isNullOrEmpty( moduleName ) ) { - if( Objects.equal( moduleName, ControllerContext.MOUNT_MODULE ) && - Objects.equal( nodeName, ControllerContext.MOUNT_NODE ) ) { - if( mountPoint != null ) { - throw new RestconfDocumentedException( - "Restconf supports just one mount point in URI.", - ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED ); + if (!Strings.isNullOrEmpty(moduleName)) { + if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE) + && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) { + if (mountPoint != null) { + throw new RestconfDocumentedException("Restconf supports just one mount point in URI.", + ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED); } - if( mountService == null ) { + if (mountService == null) { throw new RestconfDocumentedException( "MountService was not found. Finding behind mount points does not work.", - ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED ); + ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED); } final InstanceIdentifier partialPath = builder.toInstance(); - final MountInstance mount = mountService.getMountPoint( partialPath ); - if( mount == null ) { - LOG.debug( "Instance identifier to missing mount point: {}", partialPath ); - throw new RestconfDocumentedException( - "Mount point does not exist.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT ); + final MountInstance mount = mountService.getMountPoint(partialPath); + if (mount == null) { + LOG.debug("Instance identifier to missing mount point: {}", partialPath); + throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL, + ErrorTag.UNKNOWN_ELEMENT); } final SchemaContext mountPointSchema = mount.getSchemaContext(); - if( mountPointSchema == null ) { - throw new RestconfDocumentedException( - "Mount point does not contain any schema with modules.", - ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT ); + if (mountPointSchema == null) { + throw new RestconfDocumentedException("Mount point does not contain any schema with modules.", + ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT); } - if( returnJustMountPoint ) { + if (returnJustMountPoint) { InstanceIdentifier instance = InstanceIdentifier.builder().toInstance(); - return new InstanceIdWithSchemaNode( instance, mountPointSchema, mount ); + return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount); } - if( strings.size() == 1 ) { + if (strings.size() == 1) { InstanceIdentifier instance = InstanceIdentifier.builder().toInstance(); - return new InstanceIdWithSchemaNode( instance, mountPointSchema, mount ); + return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount); } - final String moduleNameBehindMountPoint = toModuleName( strings.get( 1 ) ); - if( moduleNameBehindMountPoint == null ) { + final String moduleNameBehindMountPoint = toModuleName(strings.get(1)); + if (moduleNameBehindMountPoint == null) { throw new RestconfDocumentedException( "First node after mount point in URI has to be in format \"moduleName:nodeName\"", - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } - final Module moduleBehindMountPoint = this.getLatestModule( mountPointSchema, - moduleNameBehindMountPoint ); - if( moduleBehindMountPoint == null ) { - throw new RestconfDocumentedException( - "\"" +moduleName + "\" module does not exist in mount point.", - ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT ); + final Module moduleBehindMountPoint = this + .getLatestModule(mountPointSchema, moduleNameBehindMountPoint); + if (moduleBehindMountPoint == null) { + throw new RestconfDocumentedException("\"" + moduleName + + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT); } - List subList = strings.subList( 1, strings.size() ); - return this.collectPathArguments( InstanceIdentifier.builder(), subList, moduleBehindMountPoint, - mount, returnJustMountPoint ); + List subList = strings.subList(1, strings.size()); + return this.collectPathArguments(InstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount, + returnJustMountPoint); } Module module = null; - if( mountPoint == null ) { - module = this.getLatestModule( globalSchema, moduleName ); - if( module == null ) { - throw new RestconfDocumentedException( - "\"" + moduleName + "\" module does not exist.", - ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT ); + if (mountPoint == null) { + module = this.getLatestModule(globalSchema, moduleName); + if (module == null) { + throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.", + ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT); } - } - else { + } else { SchemaContext schemaContext = mountPoint.getSchemaContext(); - module = schemaContext == null ? null : - this.getLatestModule( schemaContext, moduleName ); - if( module == null ) { - throw new RestconfDocumentedException( - "\"" + moduleName + "\" module does not exist in mount point.", - ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT ); + module = schemaContext == null ? null : this.getLatestModule(schemaContext, moduleName); + if (module == null) { + throw new RestconfDocumentedException("\"" + moduleName + + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT); } } - targetNode = this.findInstanceDataChildByNameAndNamespace( - parentNode, nodeName, module.getNamespace() ); - if( targetNode == null ) { - throw new RestconfDocumentedException( - "URI has bad format. Possible reasons:\n" + - " 1. \"" + head + "\" was not found in parent data node.\n" + - " 2. \"" + head + "\" is behind mount point. Then it should be in format \"/" + - MOUNT + "/" + head + "\".", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + targetNode = this.findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace()); + if (targetNode == null) { + throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head + + "\" was not found in parent data node.\n" + " 2. \"" + head + + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".", + ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } } else { - final List potentialSchemaNodes = - this.findInstanceDataChildrenByName( parentNode, nodeName ); - if( potentialSchemaNodes.size() > 1 ) { + final List potentialSchemaNodes = this.findInstanceDataChildrenByName(parentNode, nodeName); + if (potentialSchemaNodes.size() > 1) { final StringBuilder strBuilder = new StringBuilder(); - for( final DataSchemaNode potentialNodeSchema : potentialSchemaNodes ) { - strBuilder.append( " " ) - .append( potentialNodeSchema.getQName().getNamespace() ) - .append( "\n" ); + for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) { + strBuilder.append(" ").append(potentialNodeSchema.getQName().getNamespace()).append("\n"); } throw new RestconfDocumentedException( - "URI has bad format. Node \"" + nodeName + - "\" is added as augment from more than one module. " + - "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"." + - "\nThe node is added as augment from modules with namespaces:\n" + - strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + "URI has bad format. Node \"" + + nodeName + + "\" is added as augment from more than one module. " + + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"." + + "\nThe node is added as augment from modules with namespaces:\n" + + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } - if( potentialSchemaNodes.isEmpty() ) { - throw new RestconfDocumentedException( - "\"" + nodeName + "\" in URI was not found in parent data node", - ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT ); + if (potentialSchemaNodes.isEmpty()) { + throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node", + ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT); } targetNode = potentialSchemaNodes.iterator().next(); } - if( !this.isListOrContainer( targetNode ) ) { - throw new RestconfDocumentedException( - "URI has bad format. Node \"" + head + "\" must be Container or List yang type.", - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + if (!this.isListOrContainer(targetNode)) { + throw new RestconfDocumentedException("URI has bad format. Node \"" + head + + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } int consumed = 1; - if( (targetNode instanceof ListSchemaNode) ) { + if ((targetNode instanceof ListSchemaNode)) { final ListSchemaNode listNode = ((ListSchemaNode) targetNode); final int keysSize = listNode.getKeyDefinition().size(); - if( (strings.size() - consumed) < keysSize ) { - throw new RestconfDocumentedException( - "Missing key value for list element '" + listNode.getQName().getLocalName() + "' in the URI.", - ErrorType.PROTOCOL, ErrorTag.DATA_MISSING ); + if ((strings.size() - consumed) < keysSize) { + throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName() + + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING); } - final List uriKeyValues = strings.subList( consumed, consumed + keysSize ); + final List uriKeyValues = strings.subList(consumed, consumed + keysSize); final HashMap keyValues = new HashMap(); int i = 0; - for( final QName key : listNode.getKeyDefinition() ) { + for (final QName key : listNode.getKeyDefinition()) { { - final String uriKeyValue = uriKeyValues.get( i ); - if( uriKeyValue.equals( NULL_VALUE ) ) { - throw new RestconfDocumentedException( - "URI has bad format. List \"" + listNode.getQName().getLocalName() + - "\" cannot contain \"null\" value as a key.", - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + final String uriKeyValue = uriKeyValues.get(i); + if (uriKeyValue.equals(NULL_VALUE)) { + throw new RestconfDocumentedException("URI has bad format. List \"" + + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.", + ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } - this.addKeyValue( keyValues, listNode.getDataChildByName( key ), - uriKeyValue, mountPoint ); + this.addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint); i++; } } consumed = consumed + i; - builder.nodeWithKey( targetNode.getQName(), keyValues ); - } - else { - builder.node( targetNode.getQName() ); + builder.nodeWithKey(targetNode.getQName(), keyValues); + } else { + builder.node(targetNode.getQName()); } - if( (targetNode instanceof DataNodeContainer) ) { - final List remaining = strings.subList( consumed, strings.size() ); - return this.collectPathArguments( builder, remaining, - ((DataNodeContainer) targetNode), mountPoint, returnJustMountPoint ); + if ((targetNode instanceof DataNodeContainer)) { + final List remaining = strings.subList(consumed, strings.size()); + return this.collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint, + returnJustMountPoint); } - return new InstanceIdWithSchemaNode( builder.toInstance(), targetNode, mountPoint ); + return new InstanceIdWithSchemaNode(builder.toInstance(), targetNode, mountPoint); } - public DataSchemaNode findInstanceDataChildByNameAndNamespace( final DataNodeContainer container, - final String name, final URI namespace ) { - Preconditions. checkNotNull( namespace ); + public DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name, + final URI namespace) { + Preconditions. checkNotNull(namespace); - final List potentialSchemaNodes = this.findInstanceDataChildrenByName( container, name ); + final List potentialSchemaNodes = this.findInstanceDataChildrenByName(container, name); Predicate filter = new Predicate() { @Override - public boolean apply( final DataSchemaNode node ) { - return Objects.equal( node.getQName().getNamespace(), namespace ); + public boolean apply(final DataSchemaNode node) { + return Objects.equal(node.getQName().getNamespace(), namespace); } }; - Iterable result = Iterables.filter( potentialSchemaNodes, filter ); - return Iterables.getFirst( result, null ); + Iterable result = Iterables.filter(potentialSchemaNodes, filter); + return Iterables.getFirst(result, null); } - public List findInstanceDataChildrenByName( final DataNodeContainer container, - final String name ) { - Preconditions. checkNotNull( container ); - Preconditions. checkNotNull( name ); + public List findInstanceDataChildrenByName(final DataNodeContainer container, final String name) { + Preconditions. checkNotNull(container); + Preconditions. checkNotNull(name); List instantiatedDataNodeContainers = new ArrayList(); - this.collectInstanceDataNodeContainers( instantiatedDataNodeContainers, container, name ); + this.collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name); return instantiatedDataNodeContainers; } - private void collectInstanceDataNodeContainers( final List potentialSchemaNodes, - final DataNodeContainer container, final String name ) { + private void collectInstanceDataNodeContainers(final List potentialSchemaNodes, + final DataNodeContainer container, final String name) { Set childNodes = container.getChildNodes(); Predicate filter = new Predicate() { @Override - public boolean apply( final DataSchemaNode node ) { - return Objects.equal( node.getQName().getLocalName(), name ); + public boolean apply(final DataSchemaNode node) { + return Objects.equal(node.getQName().getLocalName(), name); } }; - Iterable nodes = Iterables.filter( childNodes, filter ); + Iterable nodes = Iterables.filter(childNodes, filter); - // Can't combine this loop with the filter above because the filter is lazily-applied - // by Iterables.filter. - for( final DataSchemaNode potentialNode : nodes ) { - if( this.isInstantiatedDataSchema( potentialNode ) ) { - potentialSchemaNodes.add( potentialNode ); + // Can't combine this loop with the filter above because the filter is + // lazily-applied by Iterables.filter. + for (final DataSchemaNode potentialNode : nodes) { + if (this.isInstantiatedDataSchema(potentialNode)) { + potentialSchemaNodes.add(potentialNode); } } - Iterable choiceNodes = Iterables. filter( container.getChildNodes(), - ChoiceNode.class ); + Iterable choiceNodes = Iterables. filter(container.getChildNodes(), ChoiceNode.class); - final Function> choiceFunction = - new Function>() { + final Function> choiceFunction = new Function>() { @Override - public Set apply( final ChoiceNode node ) { + public Set apply(final ChoiceNode node) { return node.getCases(); } }; - Iterable> map = Iterables.> transform( - choiceNodes, choiceFunction ); + Iterable> map = Iterables.> transform(choiceNodes, + choiceFunction); - final Iterable allCases = Iterables. concat( map ); - for( final ChoiceCaseNode caze : allCases ) { - this.collectInstanceDataNodeContainers( potentialSchemaNodes, caze, name ); + final Iterable allCases = Iterables. concat(map); + for (final ChoiceCaseNode caze : allCases) { + this.collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name); } } - public boolean isInstantiatedDataSchema( final DataSchemaNode node ) { - return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode || - node instanceof ContainerSchemaNode || node instanceof ListSchemaNode || - node instanceof AnyXmlSchemaNode; + public boolean isInstantiatedDataSchema(final DataSchemaNode node) { + return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode + || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode + || node instanceof AnyXmlSchemaNode; } - private void addKeyValue( final HashMap map, final DataSchemaNode node, - final String uriValue, final MountInstance mountPoint ) { - Preconditions. checkNotNull( uriValue ); - Preconditions.checkArgument( (node instanceof LeafSchemaNode) ); + private void addKeyValue(final HashMap map, final DataSchemaNode node, final String uriValue, + final MountInstance mountPoint) { + Preconditions. checkNotNull(uriValue); + Preconditions.checkArgument((node instanceof LeafSchemaNode)); - final String urlDecoded = urlPathArgDecode( uriValue ); + final String urlDecoded = urlPathArgDecode(uriValue); final TypeDefinition typedef = ((LeafSchemaNode) node).getType(); - Codec codec = RestCodec.from( typedef, mountPoint ); + Codec codec = RestCodec.from(typedef, mountPoint); - Object decoded = codec == null ? null : codec.deserialize( urlDecoded ); + Object decoded = codec == null ? null : codec.deserialize(urlDecoded); String additionalInfo = ""; - if( decoded == null ) { - TypeDefinition baseType = RestUtil.resolveBaseTypeFrom( typedef ); - if( (baseType instanceof IdentityrefTypeDefinition) ) { - decoded = this.toQName( urlDecoded ); + if (decoded == null) { + TypeDefinition baseType = RestUtil.resolveBaseTypeFrom(typedef); + if ((baseType instanceof IdentityrefTypeDefinition)) { + decoded = this.toQName(urlDecoded); additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name."; } } - if( decoded == null ) { - throw new RestconfDocumentedException( - uriValue + " from URI can't be resolved. " + additionalInfo, - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + if (decoded == null) { + throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo, + ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } - map.put( node.getQName(), decoded ); + map.put(node.getQName(), decoded); } - private static String toModuleName( final String str ) { - Preconditions. checkNotNull( str ); - if( str.indexOf( ':' ) != -1 ) { - final Iterable args = COLON_SPLITTER.split( str ); - if( Iterables.size( args ) == 2 ) { + private static String toModuleName(final String str) { + Preconditions. checkNotNull(str); + if (str.indexOf(':') != -1) { + final Iterable args = COLON_SPLITTER.split(str); + if (Iterables.size(args) == 2) { return args.iterator().next(); } } return null; } - private static String toNodeName( final String str ) { - if( str.indexOf( ':' ) != -1 ) { - final Iterable args = COLON_SPLITTER.split( str ); - if( Iterables.size( args ) == 2 ) { - return Iterables.get( args, 1 ); + private static String toNodeName(final String str) { + if (str.indexOf(':') != -1) { + final Iterable args = COLON_SPLITTER.split(str); + if (Iterables.size(args) == 2) { + return Iterables.get(args, 1); } } return str; } - private QName toQName( final String name ) { - final String module = toModuleName( name ); - final String node = toNodeName( name ); + private QName toQName(final String name) { + final String module = toModuleName(name); + final String node = toNodeName(name); Set modules = globalSchema.getModules(); final Comparator comparator = new Comparator() { @Override - public int compare( final Module o1, final Module o2 ) { - return o1.getRevision().compareTo( o2.getRevision() ); + public int compare(final Module o1, final Module o2) { + return o1.getRevision().compareTo(o2.getRevision()); } }; - List sorted = new ArrayList( modules ); - Collections. sort( new ArrayList( modules ), comparator ); + List sorted = new ArrayList(modules); + Collections. sort(new ArrayList(modules), comparator); final Function transform = new Function() { @Override - public QName apply( final Module m ) { - return QName.create( m.getNamespace(), m.getRevision(), m.getName() ); + public QName apply(final Module m) { + return QName.create(m.getNamespace(), m.getRevision(), m.getName()); } }; final Predicate findFirst = new Predicate() { @Override - public boolean apply( final QName qn ) { - return Objects.equal( module, qn.getLocalName() ); + public boolean apply(final QName qn) { + return Objects.equal(module, qn.getLocalName()); } }; - Optional namespace = FluentIterable.from( sorted ) - .transform( transform ) - .firstMatch( findFirst ); - return namespace.isPresent() ? QName.create( namespace.get(), node ) : null; + Optional namespace = FluentIterable.from(sorted).transform(transform).firstMatch(findFirst); + return namespace.isPresent() ? QName.create(namespace.get(), node) : null; } - private boolean isListOrContainer( final DataSchemaNode node ) { + private boolean isListOrContainer(final DataSchemaNode node) { return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode; } - public RpcDefinition getRpcDefinition( final String name ) { - final QName validName = this.toQName( name ); - return validName == null ? null : this.qnameToRpc.get( validName ); + public RpcDefinition getRpcDefinition(final String name) { + final QName validName = this.toQName(name); + return validName == null ? null : this.qnameToRpc.get(validName); } @Override - public void onGlobalContextUpdated( final SchemaContext context ) { - if( context != null ) { + public void onGlobalContextUpdated(final SchemaContext context) { + if (context != null) { this.qnameToRpc.clear(); - this.setGlobalSchema( context ); + this.setGlobalSchema(context); Set _operations = context.getOperations(); - for( final RpcDefinition operation : _operations ) { + for (final RpcDefinition operation : _operations) { { - this.qnameToRpc.put( operation.getQName(), operation ); + this.qnameToRpc.put(operation.getQName(), operation); } } } } - public static List urlPathArgsDecode( final Iterable strings ) { + public static List urlPathArgsDecode(final Iterable strings) { try { List decodedPathArgs = new ArrayList(); - for( final String pathArg : strings ) { - String _decode = URLDecoder.decode( pathArg, URI_ENCODING_CHAR_SET ); - decodedPathArgs.add( _decode ); + for (final String pathArg : strings) { + String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET); + decodedPathArgs.add(_decode); } return decodedPathArgs; - } - catch( UnsupportedEncodingException e ) { - throw new RestconfDocumentedException( - "Invalid URL path '" + strings + "': " + e.getMessage(), - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + } catch (UnsupportedEncodingException e) { + throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(), + ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } } - public String urlPathArgDecode( final String pathArg ) { - if( pathArg != null ) { + public String urlPathArgDecode(final String pathArg) { + if (pathArg != null) { try { - return URLDecoder.decode( pathArg, URI_ENCODING_CHAR_SET ); - } - catch( UnsupportedEncodingException e ) { - throw new RestconfDocumentedException( - "Invalid URL path arg '" + pathArg + "': " + e.getMessage(), - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET); + } catch (UnsupportedEncodingException e) { + throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(), + ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } } return null; } - private CharSequence convertToRestconfIdentifier( final PathArgument argument, - final DataNodeContainer node ) { - if( argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode ) { - return convertToRestconfIdentifier( (NodeIdentifier) argument, (ContainerSchemaNode) node ); - } - else if( argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode ) { - return convertToRestconfIdentifier( (NodeIdentifierWithPredicates) argument, (ListSchemaNode) node ); - } - else if( argument != null && node != null ) { - throw new IllegalArgumentException( - "Conversion of generic path argument is not supported" ); - } - else { - throw new IllegalArgumentException( "Unhandled parameter types: " - + Arrays. asList( argument, node ).toString() ); + private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node) { + if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) { + return convertToRestconfIdentifier((NodeIdentifier) argument, (ContainerSchemaNode) node); + } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) { + return convertToRestconfIdentifier((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node); + } else if (argument != null && node != null) { + throw new IllegalArgumentException("Conversion of generic path argument is not supported"); + } else { + throw new IllegalArgumentException("Unhandled parameter types: " + + Arrays. asList(argument, node).toString()); } } - private CharSequence convertToRestconfIdentifier( final NodeIdentifier argument, - final ContainerSchemaNode node ) { + private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final ContainerSchemaNode node) { StringBuilder builder = new StringBuilder(); - builder.append( "/" ); + builder.append("/"); QName nodeType = argument.getNodeType(); - builder.append( this.toRestconfIdentifier( nodeType ) ); + builder.append(this.toRestconfIdentifier(nodeType)); return builder.toString(); } - private CharSequence convertToRestconfIdentifier( final NodeIdentifierWithPredicates argument, - final ListSchemaNode node ) { + private CharSequence convertToRestconfIdentifier(final NodeIdentifierWithPredicates argument, + final ListSchemaNode node) { QName nodeType = argument.getNodeType(); - final CharSequence nodeIdentifier = this.toRestconfIdentifier( nodeType ); + final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType); final Map keyValues = argument.getKeyValues(); StringBuilder builder = new StringBuilder(); - builder.append( "/" ); - builder.append( nodeIdentifier ); - builder.append( "/" ); + builder.append("/"); + builder.append(nodeIdentifier); + builder.append("/"); List keyDefinition = node.getKeyDefinition(); boolean hasElements = false; - for( final QName key : keyDefinition ) { - if( !hasElements ) { + for (final QName key : keyDefinition) { + if (!hasElements) { hasElements = true; - } - else { - builder.append( "/" ); + } else { + builder.append("/"); } try { - builder.append( this.toUriString( keyValues.get( key ) ) ); - } catch( UnsupportedEncodingException e ) { - LOG.error( "Error parsing URI: {}", keyValues.get( key ), e ); + builder.append(this.toUriString(keyValues.get(key))); + } catch (UnsupportedEncodingException e) { + LOG.error("Error parsing URI: {}", keyValues.get(key), e); return null; } } @@ -1007,28 +947,22 @@ public class ControllerContext implements SchemaContextListener { return builder.toString(); } - private static DataSchemaNode childByQName( final Object container, final QName name ) { - if( container instanceof ChoiceCaseNode ) { - return childByQName( (ChoiceCaseNode) container, name ); - } - else if( container instanceof ChoiceNode ) { - return childByQName( (ChoiceNode) container, name ); - } - else if( container instanceof ContainerSchemaNode ) { - return childByQName( (ContainerSchemaNode) container, name ); - } - else if( container instanceof ListSchemaNode ) { - return childByQName( (ListSchemaNode) container, name ); - } - else if( container instanceof DataSchemaNode ) { - return childByQName( (DataSchemaNode) container, name ); - } - else if( container instanceof Module ) { - return childByQName( (Module) container, name ); - } - else { - throw new IllegalArgumentException( "Unhandled parameter types: " - + Arrays. asList( container, name ).toString() ); + private static DataSchemaNode childByQName(final Object container, final QName name) { + if (container instanceof ChoiceCaseNode) { + return childByQName((ChoiceCaseNode) container, name); + } else if (container instanceof ChoiceNode) { + return childByQName((ChoiceNode) container, name); + } else if (container instanceof ContainerSchemaNode) { + return childByQName((ContainerSchemaNode) container, name); + } else if (container instanceof ListSchemaNode) { + return childByQName((ListSchemaNode) container, name); + } else if (container instanceof DataSchemaNode) { + return childByQName((DataSchemaNode) container, name); + } else if (container instanceof Module) { + return childByQName((Module) container, name); + } else { + throw new IllegalArgumentException("Unhandled parameter types: " + + Arrays. asList(container, name).toString()); } } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/EmptyNodeWrapper.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/EmptyNodeWrapper.java index f93a0aea70..a3d44d3572 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/EmptyNodeWrapper.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/EmptyNodeWrapper.java @@ -8,10 +8,8 @@ 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; @@ -85,8 +83,9 @@ public final class EmptyNodeWrapper implements NodeWrapper>, Node Preconditions.checkNotNull(namespace); name = new QName(namespace, localName); } - if(composite) { - unwrapped = NodeFactory.createImmutableCompositeNode(name, null, Collections.>emptyList(),null); + if (composite) { + unwrapped = NodeFactory.createImmutableCompositeNode(name, null, Collections.> emptyList(), + null); } else { unwrapped = NodeFactory.createImmutableSimpleNode(name, null, null); } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/IdentityValuesDTO.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/IdentityValuesDTO.java index d66e1610a5..4e797d9057 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/IdentityValuesDTO.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/IdentityValuesDTO.java @@ -16,7 +16,7 @@ public final class IdentityValuesDTO { private final List elementData = new ArrayList<>(); private final String originValue; - public IdentityValuesDTO(String namespace, String value, String prefix,String originValue) { + public IdentityValuesDTO(String namespace, String value, String prefix, String originValue) { elementData.add(new IdentityValue(namespace, value, prefix)); this.originValue = originValue; } @@ -37,7 +37,6 @@ public final class IdentityValuesDTO { elementData.add(identityValue); } - public List getValuesWithNamespaces() { return Collections.unmodifiableList(elementData); } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/InstanceIdWithSchemaNode.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/InstanceIdWithSchemaNode.java index 68135dea95..08e0ce1f24 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/InstanceIdWithSchemaNode.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/InstanceIdWithSchemaNode.java @@ -17,7 +17,8 @@ public class InstanceIdWithSchemaNode { private final DataSchemaNode schemaNode; private final MountInstance mountPoint; - public InstanceIdWithSchemaNode(InstanceIdentifier instanceIdentifier, DataSchemaNode schemaNode, MountInstance mountPoint) { + public InstanceIdWithSchemaNode(InstanceIdentifier instanceIdentifier, DataSchemaNode schemaNode, + MountInstance mountPoint) { this.instanceIdentifier = instanceIdentifier; this.schemaNode = schemaNode; this.mountPoint = mountPoint; diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/NodeWrapper.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/NodeWrapper.java index 48fd1a3dfc..9637a36268 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/NodeWrapper.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/NodeWrapper.java @@ -8,7 +8,6 @@ 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; diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestCodec.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestCodec.java index 14b8282312..92a7014438 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestCodec.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestCodec.java @@ -12,7 +12,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.opendaylight.controller.sal.core.api.mount.MountInstance; import org.opendaylight.controller.sal.rest.impl.RestUtil; import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO.IdentityValue; @@ -47,7 +46,8 @@ public class RestCodec { private RestCodec() { } - public static final Codec from(final TypeDefinition typeDefinition, final MountInstance mountPoint) { + public static final Codec from(final TypeDefinition typeDefinition, + final MountInstance mountPoint) { return new ObjectCodec(typeDefinition, mountPoint); } @@ -90,7 +90,7 @@ public class RestCodec { return null; } else if (type instanceof LeafrefTypeDefinition) { if (input instanceof IdentityValuesDTO) { - return LEAFREF_DEFAULT_CODEC.deserialize(((IdentityValuesDTO)input).getOriginValue()); + return LEAFREF_DEFAULT_CODEC.deserialize(((IdentityValuesDTO) input).getOriginValue()); } return LEAFREF_DEFAULT_CODEC.deserialize(input); } else if (type instanceof InstanceIdentifierTypeDefinition) { @@ -106,7 +106,7 @@ public class RestCodec { .from(type); if (typeAwarecodec != null) { if (input instanceof IdentityValuesDTO) { - return typeAwarecodec.deserialize(((IdentityValuesDTO)input).getOriginValue()); + return typeAwarecodec.deserialize(((IdentityValuesDTO) input).getOriginValue()); } return typeAwarecodec.deserialize(String.valueOf(input)); } else { @@ -115,8 +115,7 @@ public class RestCodec { return null; } } - } catch (ClassCastException e) { // TODO remove this catch when - // everyone use codecs + } catch (ClassCastException e) { // TODO remove this catch when everyone use codecs logger.error( "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input), e); @@ -145,8 +144,7 @@ public class RestCodec { return null; } } - } catch (ClassCastException e) { // TODO remove this catch when - // everyone use codecs + } catch (ClassCastException e) { // TODO remove this catch when everyone use codecs logger.error( "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input), e); @@ -168,7 +166,7 @@ public class RestCodec { @Override public IdentityValuesDTO serialize(final QName data) { - return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), data.getPrefix(),null); + return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), data.getPrefix(), null); } @Override @@ -234,8 +232,10 @@ public class RestCodec { IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0); Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), mountPoint); if (module == null) { - logger.info("Module by namespace '{}' of first node in instance-identiefier was not found.", valueWithNamespace.getNamespace()); - logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(valueWithNamespace.getValue())); + logger.info("Module by namespace '{}' of first node in instance-identiefier was not found.", + valueWithNamespace.getNamespace()); + logger.info("Instance-identifier will be translated as NULL for data - {}", + String.valueOf(valueWithNamespace.getValue())); return null; } @@ -248,7 +248,8 @@ public class RestCodec { parentContainer, identityValue.getValue(), validNamespace); if (node == null) { logger.info("'{}' node was not found in {}", identityValue, parentContainer.getChildNodes()); - logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue())); + logger.info("Instance-identifier will be translated as NULL for data - {}", + String.valueOf(identityValue.getValue())); return null; } QName qName = node.getQName(); @@ -260,7 +261,8 @@ public class RestCodec { Predicate leafListPredicate = identityValue.getPredicates().get(0); if (!leafListPredicate.isLeafList()) { logger.info("Predicate's data is not type of leaf-list. It should be in format \".='value'\""); - logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue())); + logger.info("Instance-identifier will be translated as NULL for data - {}", + String.valueOf(identityValue.getValue())); return null; } pathArgument = new NodeWithValue(qName, leafListPredicate.getValue()); @@ -269,24 +271,28 @@ public class RestCodec { Map predicatesMap = new HashMap<>(); for (Predicate predicate : identityValue.getPredicates()) { validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), mountPoint); - DataSchemaNode listKey = ControllerContext.getInstance().findInstanceDataChildByNameAndNamespace( - listNode, predicate.getName().getValue(), validNamespace); + DataSchemaNode listKey = ControllerContext.getInstance() + .findInstanceDataChildByNameAndNamespace(listNode, predicate.getName().getValue(), + validNamespace); predicatesMap.put(listKey.getQName(), predicate.getValue()); } pathArgument = new NodeIdentifierWithPredicates(qName, predicatesMap); } else { logger.info("Node {} is not List or Leaf-list.", node); - logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue())); + logger.info("Instance-identifier will be translated as NULL for data - {}", + String.valueOf(identityValue.getValue())); return null; } } result.add(pathArgument); - if (i < identities.size() - 1) { // last element in instance-identifier can be other than DataNodeContainer + if (i < identities.size() - 1) { // last element in instance-identifier can be other than + // DataNodeContainer if (node instanceof DataNodeContainer) { parentContainer = (DataNodeContainer) node; } else { logger.info("Node {} isn't instance of DataNodeContainer", node); - logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue())); + logger.info("Instance-identifier will be translated as NULL for data - {}", + String.valueOf(identityValue.getValue())); return null; } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfDocumentedException.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfDocumentedException.java index 0548e95044..e3e0c3a2bd 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfDocumentedException.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfDocumentedException.java @@ -8,20 +8,17 @@ package org.opendaylight.controller.sal.restconf.impl; +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableList; import java.util.List; - import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response.Status; - import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag; import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; - /** - * Unchecked exception to communicate error information, as defined in the ietf restcong draft, - * to be sent to the client. + * Unchecked exception to communicate error information, as defined in the ietf restcong draft, to be sent to the + * client. * * @author Devin Avery * @author Thomas Pantelis @@ -35,70 +32,76 @@ public class RestconfDocumentedException extends WebApplicationException { private final Status status; /** - * Constructs an instance with an error message. The error type defaults to APPLICATION and - * the error tag defaults to OPERATION_FAILED. + * Constructs an instance with an error message. The error type defaults to APPLICATION and the error tag defaults + * to OPERATION_FAILED. * - * @param message A string which provides a plain text string describing the error. + * @param message + * A string which provides a plain text string describing the error. */ - public RestconfDocumentedException( String message ) { - this( message, RestconfError.ErrorType.APPLICATION, RestconfError.ErrorTag.OPERATION_FAILED ); + public RestconfDocumentedException(String message) { + this(message, RestconfError.ErrorType.APPLICATION, RestconfError.ErrorTag.OPERATION_FAILED); } /** * Constructs an instance with an error message, error type, and error tag. * - * @param message A string which provides a plain text string describing the error. - * @param errorType The enumerated type indicating the layer where the error occurred. - * @param errorTag The enumerated tag representing a more specific error cause. + * @param message + * A string which provides a plain text string describing the error. + * @param errorType + * The enumerated type indicating the layer where the error occurred. + * @param errorTag + * The enumerated tag representing a more specific error cause. */ - public RestconfDocumentedException( String message, ErrorType errorType, ErrorTag errorTag ) { - this( null, new RestconfError( errorType, errorTag, message ) ); + public RestconfDocumentedException(String message, ErrorType errorType, ErrorTag errorTag) { + this(null, new RestconfError(errorType, errorTag, message)); } /** - * Constructs an instance with an error message and exception cause. The stack trace of the - * exception is included in the error info. + * Constructs an instance with an error message and exception cause. The stack trace of the exception is included in + * the error info. * - * @param message A string which provides a plain text string describing the error. - * @param cause The underlying exception cause. + * @param message + * A string which provides a plain text string describing the error. + * @param cause + * The underlying exception cause. */ - public RestconfDocumentedException( String message, Throwable cause ) { - this( cause, new RestconfError( RestconfError.ErrorType.APPLICATION, - RestconfError.ErrorTag.OPERATION_FAILED, message, - null, RestconfError.toErrorInfo( cause ) ) ); + public RestconfDocumentedException(String message, Throwable cause) { + this(cause, new RestconfError(RestconfError.ErrorType.APPLICATION, RestconfError.ErrorTag.OPERATION_FAILED, + message, null, RestconfError.toErrorInfo(cause))); } /** * Constructs an instance with the given error. */ - public RestconfDocumentedException( RestconfError error ) { - this( null, error ); + public RestconfDocumentedException(RestconfError error) { + this(null, error); } /** * Constructs an instance with the given errors. */ - public RestconfDocumentedException( List errors ) { - this.errors = ImmutableList.copyOf( errors ); - Preconditions.checkArgument( !this.errors.isEmpty(), "RestconfError list can't be empty" ); + public RestconfDocumentedException(List errors) { + this.errors = ImmutableList.copyOf(errors); + Preconditions.checkArgument(!this.errors.isEmpty(), "RestconfError list can't be empty"); status = null; } /** * Constructs an instance with an HTTP status and no error information. * - * @param status the HTTP status. + * @param status + * the HTTP status. */ - public RestconfDocumentedException( Status status ) { - Preconditions.checkNotNull( status, "Status can't be null" ); + public RestconfDocumentedException(Status status) { + Preconditions.checkNotNull(status, "Status can't be null"); errors = ImmutableList.of(); this.status = status; } - private RestconfDocumentedException( Throwable cause, RestconfError error ) { - super( cause ); - Preconditions.checkNotNull( error, "RestconfError can't be null" ); - errors = ImmutableList.of( error ); + private RestconfDocumentedException(Throwable cause, RestconfError error) { + super(cause); + Preconditions.checkNotNull(error, "RestconfError can't be null"); + errors = ImmutableList.of(error); status = null; } @@ -110,7 +113,6 @@ public class RestconfDocumentedException extends WebApplicationException { return status; } - @Override public String getMessage() { return "errors: " + errors + (status != null ? ", status: " + status : ""); diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfError.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfError.java index cc279cbd58..ed20bd01a5 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfError.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfError.java @@ -1,23 +1,23 @@ /* -* 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 -*/ + * 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.impl; +import com.google.common.base.Preconditions; import java.io.PrintWriter; import java.io.StringWriter; - import org.opendaylight.yangtools.yang.common.RpcError; -import com.google.common.base.Preconditions; - /** * Encapsulates a restconf error as defined in the ietf restconf draft. * - *

Note: Enumerations defined within are provided by the ietf restconf draft. + *
+ *
+ * Note: Enumerations defined within are provided by the ietf restconf draft. * * @author Devin Avery * @see {@link https://tools.ietf.org/html/draft-bierman-netconf-restconf-02} @@ -38,37 +38,35 @@ public class RestconfError { return name().toLowerCase(); } - public static ErrorType valueOfCaseInsensitive( String value ) - { + public static ErrorType valueOfCaseInsensitive(String value) { try { - return ErrorType.valueOf( ErrorType.class, value.toUpperCase() ); - } - catch( IllegalArgumentException e ) { + return ErrorType.valueOf(ErrorType.class, value.toUpperCase()); + } catch (IllegalArgumentException e) { return APPLICATION; } } } public static enum ErrorTag { - IN_USE( "in-use", 409 /*Conflict*/ ), - INVALID_VALUE( "invalid-value", 400 /*Bad Request*/ ), - TOO_BIG( "too-big", 413 /*Request Entity Too Large*/ ), - MISSING_ATTRIBUTE( "missing-attribute", 400 /*Bad Request*/ ), - BAD_ATTRIBUTE( "bad-attribute", 400 /*Bad Request*/ ), - UNKNOWN_ATTRIBUTE( "unknown-attribute", 400 /*Bad Request*/ ), - BAD_ELEMENT( "bad-element", 400 /*Bad Request*/ ), - UNKNOWN_ELEMENT( "unknown-element", 400 /*Bad Request*/ ), - UNKNOWN_NAMESPACE( "unknown-namespace", 400 /*Bad Request*/ ), - ACCESS_DENIED( "access-denied", 403 /*Forbidden*/ ), - LOCK_DENIED( "lock-denied", 409 /*Conflict*/ ), - RESOURCE_DENIED( "resource-denied", 409 /*Conflict*/ ), - ROLLBACK_FAILED( "rollback-failed", 500 /*INTERNAL_SERVER_ERROR*/ ), - DATA_EXISTS( "data-exists", 409 /*Conflict*/ ), - DATA_MISSING( "data-missing", 409 /*Conflict*/ ), - OPERATION_NOT_SUPPORTED( "operation-not-supported", 501 /*Not Implemented*/ ), - OPERATION_FAILED( "operation-failed", 500 /*INTERNAL_SERVER_ERROR*/ ), - PARTIAL_OPERATION( "partial-operation", 500 /*INTERNAL_SERVER_ERROR*/ ), - MALFORMED_MESSAGE( "malformed-message", 400 /*Bad Request*/ ); + IN_USE("in-use", 409 /* Conflict */), + INVALID_VALUE("invalid-value", 400 /* Bad Request */), + TOO_BIG("too-big", 413 /* Request Entity Too Large */), + MISSING_ATTRIBUTE("missing-attribute", 400 /* Bad Request */), + BAD_ATTRIBUTE("bad-attribute", 400 /* Bad Request */), + UNKNOWN_ATTRIBUTE("unknown-attribute", 400 /* Bad Request */), + BAD_ELEMENT("bad-element", 400 /* Bad Request */), + UNKNOWN_ELEMENT("unknown-element", 400 /* Bad Request */), + UNKNOWN_NAMESPACE("unknown-namespace", 400 /* Bad Request */), + ACCESS_DENIED("access-denied", 403 /* Forbidden */), + LOCK_DENIED("lock-denied", 409 /* Conflict */), + RESOURCE_DENIED("resource-denied", 409 /* Conflict */), + ROLLBACK_FAILED("rollback-failed", 500 /* INTERNAL_SERVER_ERROR */), + DATA_EXISTS("data-exists", 409 /* Conflict */), + DATA_MISSING("data-missing", 409 /* Conflict */), + OPERATION_NOT_SUPPORTED("operation-not-supported", 501 /* Not Implemented */), + OPERATION_FAILED("operation-failed", 500 /* INTERNAL_SERVER_ERROR */), + PARTIAL_OPERATION("partial-operation", 500 /* INTERNAL_SERVER_ERROR */), + MALFORMED_MESSAGE("malformed-message", 400 /* Bad Request */); private final String tagValue; private final int statusCode; @@ -82,12 +80,10 @@ public class RestconfError { return this.tagValue.toLowerCase(); } - public static ErrorTag valueOfCaseInsensitive( String value ) - { + public static ErrorTag valueOfCaseInsensitive(String value) { try { - return ErrorTag.valueOf( ErrorTag.class, value.toUpperCase().replaceAll( "-","_" ) ); - } - catch( IllegalArgumentException e ) { + return ErrorTag.valueOf(ErrorTag.class, value.toUpperCase().replaceAll("-", "_")); + } catch (IllegalArgumentException e) { return OPERATION_FAILED; } } @@ -102,53 +98,63 @@ public class RestconfError { private final String errorInfo; private final String errorAppTag; private final String errorMessage; - //TODO: Add in the error-path concept as defined in the ietf draft. - static String toErrorInfo( Throwable cause ) { + // TODO: Add in the error-path concept as defined in the ietf draft. + + static String toErrorInfo(Throwable cause) { StringWriter writer = new StringWriter(); - cause.printStackTrace( new PrintWriter( writer ) ); + cause.printStackTrace(new PrintWriter(writer)); return writer.toString(); } /** * Constructs a RestConfError * - * @param errorType The enumerated type indicating the layer where the error occurred. - * @param errorTag The enumerated tag representing a more specific error cause. - * @param errorMessage A string which provides a plain text string describing the error. + * @param errorType + * The enumerated type indicating the layer where the error occurred. + * @param errorTag + * The enumerated tag representing a more specific error cause. + * @param errorMessage + * A string which provides a plain text string describing the error. */ public RestconfError(ErrorType errorType, ErrorTag errorTag, String errorMessage) { - this( errorType, errorTag, errorMessage, null ); + this(errorType, errorTag, errorMessage, null); } /** * Constructs a RestConfError object. * - * @param errorType The enumerated type indicating the layer where the error occurred. - * @param errorTag The enumerated tag representing a more specific error cause. - * @param errorMessage A string which provides a plain text string describing the error. - * @param errorAppTag A string which represents an application-specific error tag that further - * specifies the error cause. + * @param errorType + * The enumerated type indicating the layer where the error occurred. + * @param errorTag + * The enumerated tag representing a more specific error cause. + * @param errorMessage + * A string which provides a plain text string describing the error. + * @param errorAppTag + * A string which represents an application-specific error tag that further specifies the error cause. */ - public RestconfError(ErrorType errorType, ErrorTag errorTag, String errorMessage, - String errorAppTag) { - this( errorType, errorTag, errorMessage, errorAppTag, null ); + public RestconfError(ErrorType errorType, ErrorTag errorTag, String errorMessage, String errorAppTag) { + this(errorType, errorTag, errorMessage, errorAppTag, null); } /** * Constructs a RestConfError object. * - * @param errorType The enumerated type indicating the layer where the error occurred. - * @param errorTag The enumerated tag representing a more specific error cause. - * @param errorMessage A string which provides a plain text string describing the error. - * @param errorAppTag A string which represents an application-specific error tag that further - * specifies the error cause. - * @param errorInfo A string, formatted as XML, which contains additional error information. + * @param errorType + * The enumerated type indicating the layer where the error occurred. + * @param errorTag + * The enumerated tag representing a more specific error cause. + * @param errorMessage + * A string which provides a plain text string describing the error. + * @param errorAppTag + * A string which represents an application-specific error tag that further specifies the error cause. + * @param errorInfo + * A string, formatted as XML, which contains additional error information. */ - public RestconfError(ErrorType errorType, ErrorTag errorTag, String errorMessage, - String errorAppTag, String errorInfo) { - Preconditions.checkNotNull( errorType, "Error type is required for RestConfError" ); - Preconditions.checkNotNull( errorTag, "Error tag is required for RestConfError"); + public RestconfError(ErrorType errorType, ErrorTag errorTag, String errorMessage, String errorAppTag, + String errorInfo) { + Preconditions.checkNotNull(errorType, "Error type is required for RestConfError"); + Preconditions.checkNotNull(errorTag, "Error tag is required for RestConfError"); this.errorType = errorType; this.errorTag = errorTag; this.errorMessage = errorMessage; @@ -159,28 +165,25 @@ public class RestconfError { /** * Constructs a RestConfError object from an RpcError. */ - public RestconfError( RpcError rpcError ) { + public RestconfError(RpcError rpcError) { - this.errorType = rpcError.getErrorType() == null ? ErrorType.APPLICATION : - ErrorType.valueOfCaseInsensitive( rpcError.getErrorType().name() ); + this.errorType = rpcError.getErrorType() == null ? ErrorType.APPLICATION : ErrorType + .valueOfCaseInsensitive(rpcError.getErrorType().name()); - this.errorTag = rpcError.getTag() == null ? ErrorTag.OPERATION_FAILED : - ErrorTag.valueOfCaseInsensitive( rpcError.getTag().toString() ); + this.errorTag = rpcError.getTag() == null ? ErrorTag.OPERATION_FAILED : ErrorTag + .valueOfCaseInsensitive(rpcError.getTag().toString()); this.errorMessage = rpcError.getMessage(); this.errorAppTag = rpcError.getApplicationTag(); String errorInfo = null; - if( rpcError.getInfo() == null ) { - if( rpcError.getCause() != null ) { - errorInfo = toErrorInfo( rpcError.getCause() ); + if (rpcError.getInfo() == null) { + if (rpcError.getCause() != null) { + errorInfo = toErrorInfo(rpcError.getCause()); + } else if (rpcError.getSeverity() != null) { + errorInfo = "" + rpcError.getSeverity().toString().toLowerCase() + ""; } - else if( rpcError.getSeverity() != null ) { - errorInfo = "" + rpcError.getSeverity().toString().toLowerCase() + - ""; - } - } - else { + } else { errorInfo = rpcError.getInfo(); } @@ -209,8 +212,7 @@ public class RestconfError { @Override public String toString() { - return "error-type: " + errorType.getErrorTypeTag() - + ", error-tag: " + errorTag.getTagValue() + ", " + return "error-type: " + errorType.getErrorTypeTag() + ", error-tag: " + errorTag.getTagValue() + ", " + (errorAppTag != null ? "error-app-tag: " + errorAppTag + ", " : "") + (errorMessage != null ? "error-message: " + errorMessage : "") + (errorInfo != null ? "error-info: " + errorInfo + ", " : "") + "]"; diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java index ae48ca7196..bb7547d330 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java @@ -79,10 +79,11 @@ import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder public class RestconfImpl implements RestconfService { private enum UriParameters { - PRETTY_PRINT( "prettyPrint"), - DEPTH( "depth"); + PRETTY_PRINT("prettyPrint"), + DEPTH("depth"); private String uriParameterName; + UriParameters(String uriParameterName) { this.uriParameterName = uriParameterName; } @@ -99,7 +100,7 @@ public class RestconfImpl implements RestconfService { private final static String MOUNT_POINT_MODULE_NAME = "ietf-netconf"; - private final static SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); + private final static SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); private final static String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote"; @@ -129,8 +130,8 @@ public class RestconfImpl implements RestconfService { final Module restconfModule = this.getRestconfModule(); final List> modulesAsData = new ArrayList>(); - final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE); + final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule, + Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE); Set allModules = this.controllerContext.getAllModules(); for (final Module module : allModules) { @@ -138,11 +139,11 @@ public class RestconfImpl implements RestconfService { modulesAsData.add(moduleCompositeNode); } - final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE); + final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule, + Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE); QName qName = modulesSchemaNode.getQName(); final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData); - return new StructuredData(modulesNode, modulesSchemaNode, null,parsePrettyPrintParameter( uriInfo )); + return new StructuredData(modulesNode, modulesSchemaNode, null, parsePrettyPrintParameter(uriInfo)); } @Override @@ -151,122 +152,115 @@ public class RestconfImpl implements RestconfService { final List> streamsAsData = new ArrayList>(); Module restconfModule = this.getRestconfModule(); - final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE); + final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule, + Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE); for (final String streamName : availableStreams) { streamsAsData.add(this.toStreamCompositeNode(streamName, streamSchemaNode)); } - final DataSchemaNode streamsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE); + final DataSchemaNode streamsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule, + Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE); QName qName = streamsSchemaNode.getQName(); final CompositeNode streamsNode = NodeFactory.createImmutableCompositeNode(qName, null, streamsAsData); - return new StructuredData(streamsNode, streamsSchemaNode, null,parsePrettyPrintParameter( uriInfo )); + return new StructuredData(streamsNode, streamsSchemaNode, null, parsePrettyPrintParameter(uriInfo)); } @Override - public StructuredData getModules(final String identifier,final UriInfo uriInfo) { + public StructuredData getModules(final String identifier, final UriInfo uriInfo) { Set modules = null; MountInstance mountPoint = null; if (identifier.contains(ControllerContext.MOUNT)) { - InstanceIdWithSchemaNode mountPointIdentifier = - this.controllerContext.toMountPointIdentifier(identifier); + InstanceIdWithSchemaNode mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier); mountPoint = mountPointIdentifier.getMountPoint(); modules = this.controllerContext.getAllModules(mountPoint); - } - else { + } else { throw new RestconfDocumentedException( - "URI has bad format. If modules behind mount point should be showed, URI has to end with " + - ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + "URI has bad format. If modules behind mount point should be showed, URI has to end with " + + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } final List> modulesAsData = new ArrayList>(); Module restconfModule = this.getRestconfModule(); - final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE); + final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule, + Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE); for (final Module module : modules) { modulesAsData.add(this.toModuleCompositeNode(module, moduleSchemaNode)); } - final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE); + final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule, + Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE); QName qName = modulesSchemaNode.getQName(); final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData); - return new StructuredData(modulesNode, modulesSchemaNode, mountPoint,parsePrettyPrintParameter( uriInfo )); + return new StructuredData(modulesNode, modulesSchemaNode, mountPoint, parsePrettyPrintParameter(uriInfo)); } @Override - public StructuredData getModule(final String identifier,final UriInfo uriInfo) { + public StructuredData getModule(final String identifier, final UriInfo uriInfo) { final QName moduleNameAndRevision = this.getModuleNameAndRevision(identifier); Module module = null; MountInstance mountPoint = null; if (identifier.contains(ControllerContext.MOUNT)) { - InstanceIdWithSchemaNode mountPointIdentifier = - this.controllerContext.toMountPointIdentifier(identifier); + InstanceIdWithSchemaNode mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier); mountPoint = mountPointIdentifier.getMountPoint(); module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision); - } - else { + } else { module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision); } if (module == null) { - throw new RestconfDocumentedException( - "Module with name '" + moduleNameAndRevision.getLocalName() + "' and revision '" + - moduleNameAndRevision.getRevision() + "' was not found.", - ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT ); + throw new RestconfDocumentedException("Module with name '" + moduleNameAndRevision.getLocalName() + + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.", + ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT); } Module restconfModule = this.getRestconfModule(); - final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( - restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE); + final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule, + Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE); final CompositeNode moduleNode = this.toModuleCompositeNode(module, moduleSchemaNode); - return new StructuredData(moduleNode, moduleSchemaNode, mountPoint,parsePrettyPrintParameter( uriInfo )); + return new StructuredData(moduleNode, moduleSchemaNode, mountPoint, parsePrettyPrintParameter(uriInfo)); } @Override public StructuredData getOperations(final UriInfo uriInfo) { Set allModules = this.controllerContext.getAllModules(); - return this.operationsFromModulesToStructuredData(allModules, null,parsePrettyPrintParameter(uriInfo)); + return this.operationsFromModulesToStructuredData(allModules, null, parsePrettyPrintParameter(uriInfo)); } @Override - public StructuredData getOperations(final String identifier,final UriInfo uriInfo) { + public StructuredData getOperations(final String identifier, final UriInfo uriInfo) { Set modules = null; MountInstance mountPoint = null; if (identifier.contains(ControllerContext.MOUNT)) { - InstanceIdWithSchemaNode mountPointIdentifier = - this.controllerContext.toMountPointIdentifier(identifier); + InstanceIdWithSchemaNode mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier); mountPoint = mountPointIdentifier.getMountPoint(); modules = this.controllerContext.getAllModules(mountPoint); - } - else { + } else { throw new RestconfDocumentedException( - "URI has bad format. If operations behind mount point should be showed, URI has to end with " + - ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + "URI has bad format. If operations behind mount point should be showed, URI has to end with " + + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } - return this.operationsFromModulesToStructuredData(modules, mountPoint,parsePrettyPrintParameter(uriInfo)); + return this.operationsFromModulesToStructuredData(modules, mountPoint, parsePrettyPrintParameter(uriInfo)); } private StructuredData operationsFromModulesToStructuredData(final Set modules, - final MountInstance mountPoint,boolean prettyPrint) { + final MountInstance mountPoint, boolean prettyPrint) { final List> operationsAsData = new ArrayList>(); Module restconfModule = this.getRestconfModule(); final DataSchemaNode operationsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode( restconfModule, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE); QName qName = operationsSchemaNode.getQName(); SchemaPath path = operationsSchemaNode.getPath(); - ContainerSchemaNodeBuilder containerSchemaNodeBuilder = - new ContainerSchemaNodeBuilder(Draft02.RestConfModule.NAME, 0, qName, path); + ContainerSchemaNodeBuilder containerSchemaNodeBuilder = new ContainerSchemaNodeBuilder( + Draft02.RestConfModule.NAME, 0, qName, path); final ContainerSchemaNodeBuilder fakeOperationsSchemaNode = containerSchemaNodeBuilder; for (final Module module : modules) { Set rpcs = module.getRpcs(); for (final RpcDefinition rpc : rpcs) { QName rpcQName = rpc.getQName(); - SimpleNode immutableSimpleNode = - NodeFactory.createImmutableSimpleNode(rpcQName, null, null); + SimpleNode immutableSimpleNode = NodeFactory. createImmutableSimpleNode(rpcQName, null, + null); operationsAsData.add(immutableSimpleNode); String name = module.getName(); @@ -281,18 +275,16 @@ public class RestconfImpl implements RestconfService { } } - final CompositeNode operationsNode = - NodeFactory.createImmutableCompositeNode(qName, null, operationsAsData); + final CompositeNode operationsNode = NodeFactory.createImmutableCompositeNode(qName, null, operationsAsData); ContainerSchemaNode schemaNode = fakeOperationsSchemaNode.build(); - return new StructuredData(operationsNode, schemaNode, mountPoint,prettyPrint); + return new StructuredData(operationsNode, schemaNode, mountPoint, prettyPrint); } private Module getRestconfModule() { Module restconfModule = controllerContext.getRestconfModule(); if (restconfModule == null) { - throw new RestconfDocumentedException( - "ietf-restconf module was not found.", ErrorType.APPLICATION, - ErrorTag.OPERATION_NOT_SUPPORTED ); + throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION, + ErrorTag.OPERATION_NOT_SUPPORTED); } return restconfModule; @@ -303,95 +295,90 @@ public class RestconfImpl implements RestconfService { String moduleNameAndRevision = ""; if (mountIndex >= 0) { moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length()); - } - else { + } else { moduleNameAndRevision = identifier; } Splitter splitter = Splitter.on("/").omitEmptyStrings(); Iterable split = splitter.split(moduleNameAndRevision); - final List pathArgs = Lists.newArrayList(split); + final List pathArgs = Lists. newArrayList(split); if (pathArgs.size() < 2) { throw new RestconfDocumentedException( - "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL, + ErrorTag.INVALID_VALUE); } try { - final String moduleName = pathArgs.get( 0 ); + final String moduleName = pathArgs.get(0); String revision = pathArgs.get(1); final Date moduleRevision = REVISION_FORMAT.parse(revision); return QName.create(null, moduleRevision, moduleName); - } - catch (ParseException e) { - throw new RestconfDocumentedException( - "URI has bad format. It should be \'moduleName/yyyy-MM-dd\'", - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + } catch (ParseException e) { + throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'", + ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } } private CompositeNode toStreamCompositeNode(final String streamName, final DataSchemaNode streamSchemaNode) { final List> streamNodeValues = new ArrayList>(); - List instanceDataChildrenByName = - this.controllerContext.findInstanceDataChildrenByName(((DataNodeContainer) streamSchemaNode), - "name"); + List instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( + ((DataNodeContainer) streamSchemaNode), "name"); final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); - streamNodeValues.add(NodeFactory.createImmutableSimpleNode(nameSchemaNode.getQName(), null, - streamName)); + streamNodeValues + .add(NodeFactory. createImmutableSimpleNode(nameSchemaNode.getQName(), null, streamName)); instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( ((DataNodeContainer) streamSchemaNode), "description"); final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); - streamNodeValues.add(NodeFactory.createImmutableSimpleNode(descriptionSchemaNode.getQName(), null, + streamNodeValues.add(NodeFactory. createImmutableSimpleNode(descriptionSchemaNode.getQName(), null, "DESCRIPTION_PLACEHOLDER")); instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( ((DataNodeContainer) streamSchemaNode), "replay-support"); final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); - streamNodeValues.add(NodeFactory.createImmutableSimpleNode(replaySupportSchemaNode.getQName(), null, + streamNodeValues.add(NodeFactory. createImmutableSimpleNode(replaySupportSchemaNode.getQName(), null, Boolean.valueOf(true))); instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( ((DataNodeContainer) streamSchemaNode), "replay-log-creation-time"); final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); - streamNodeValues.add(NodeFactory.createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(), + streamNodeValues.add(NodeFactory. createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(), null, "")); instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( ((DataNodeContainer) streamSchemaNode), "events"); final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); - streamNodeValues.add(NodeFactory.createImmutableSimpleNode(eventsSchemaNode.getQName(), - null, "")); + streamNodeValues.add(NodeFactory. createImmutableSimpleNode(eventsSchemaNode.getQName(), null, "")); return NodeFactory.createImmutableCompositeNode(streamSchemaNode.getQName(), null, streamNodeValues); } private CompositeNode toModuleCompositeNode(final Module module, final DataSchemaNode moduleSchemaNode) { final List> moduleNodeValues = new ArrayList>(); - List instanceDataChildrenByName = - this.controllerContext.findInstanceDataChildrenByName(((DataNodeContainer) moduleSchemaNode), "name"); + List instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( + ((DataNodeContainer) moduleSchemaNode), "name"); final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); - moduleNodeValues.add(NodeFactory.createImmutableSimpleNode(nameSchemaNode.getQName(), - null, module.getName())); + moduleNodeValues.add(NodeFactory. createImmutableSimpleNode(nameSchemaNode.getQName(), null, + module.getName())); instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( ((DataNodeContainer) moduleSchemaNode), "revision"); final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); Date _revision = module.getRevision(); - moduleNodeValues.add(NodeFactory.createImmutableSimpleNode(revisionSchemaNode.getQName(), null, + moduleNodeValues.add(NodeFactory. createImmutableSimpleNode(revisionSchemaNode.getQName(), null, REVISION_FORMAT.format(_revision))); instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( ((DataNodeContainer) moduleSchemaNode), "namespace"); final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); - moduleNodeValues.add(NodeFactory.createImmutableSimpleNode(namespaceSchemaNode.getQName(), null, + moduleNodeValues.add(NodeFactory. createImmutableSimpleNode(namespaceSchemaNode.getQName(), null, module.getNamespace().toString())); instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName( ((DataNodeContainer) moduleSchemaNode), "feature"); final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null); for (final FeatureDefinition feature : module.getFeatures()) { - moduleNodeValues.add(NodeFactory.createImmutableSimpleNode(featureSchemaNode.getQName(), null, + moduleNodeValues.add(NodeFactory. createImmutableSimpleNode(featureSchemaNode.getQName(), null, feature.getQName().getLocalName())); } @@ -404,53 +391,45 @@ public class RestconfImpl implements RestconfService { } @Override - public StructuredData invokeRpc(final String identifier, final CompositeNode payload,final UriInfo uriInfo) { + public StructuredData invokeRpc(final String identifier, final CompositeNode payload, final UriInfo uriInfo) { final RpcExecutor rpc = this.resolveIdentifierInInvokeRpc(identifier); QName rpcName = rpc.getRpcDefinition().getQName(); URI rpcNamespace = rpcName.getNamespace(); - if (Objects.equal(rpcNamespace.toString(), SAL_REMOTE_NAMESPACE) && - Objects.equal(rpcName.getLocalName(), SAL_REMOTE_RPC_SUBSRCIBE)) { - return invokeSalRemoteRpcSubscribeRPC(payload, rpc.getRpcDefinition(),parsePrettyPrintParameter(uriInfo)); + if (Objects.equal(rpcNamespace.toString(), SAL_REMOTE_NAMESPACE) + && Objects.equal(rpcName.getLocalName(), SAL_REMOTE_RPC_SUBSRCIBE)) { + return invokeSalRemoteRpcSubscribeRPC(payload, rpc.getRpcDefinition(), parsePrettyPrintParameter(uriInfo)); } - validateInput( rpc.getRpcDefinition().getInput(), payload ); + validateInput(rpc.getRpcDefinition().getInput(), payload); - return callRpc(rpc, payload,parsePrettyPrintParameter(uriInfo)); + return callRpc(rpc, payload, parsePrettyPrintParameter(uriInfo)); } private void validateInput(final DataSchemaNode inputSchema, final CompositeNode 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 + 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 // validate in a more central location inside MD-SAL core. - //} + // } } - private StructuredData invokeSalRemoteRpcSubscribeRPC(final CompositeNode payload, - final RpcDefinition rpc,final boolean prettyPrint) { + private StructuredData invokeSalRemoteRpcSubscribeRPC(final CompositeNode payload, final RpcDefinition rpc, + final boolean prettyPrint) { final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null); - final SimpleNode pathNode = value == null ? null : - value.getFirstSimpleByName( QName.create(rpc.getQName(), "path") ); + final SimpleNode pathNode = value == null ? null : value.getFirstSimpleByName(QName.create( + rpc.getQName(), "path")); final Object pathValue = pathNode == null ? null : pathNode.getValue(); if (!(pathValue instanceof InstanceIdentifier)) { - throw new RestconfDocumentedException( - "Instance identifier was not normalized correctly.", - ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED ); + throw new RestconfDocumentedException("Instance identifier was not normalized correctly.", + ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED); } final InstanceIdentifier pathIdentifier = ((InstanceIdentifier) pathValue); @@ -463,31 +442,30 @@ public class RestconfImpl implements RestconfService { if (Strings.isNullOrEmpty(streamName)) { throw new RestconfDocumentedException( "Path is empty or contains data node which is not Container or List build-in type.", - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } - final SimpleNode streamNameNode = NodeFactory.createImmutableSimpleNode( + final SimpleNode streamNameNode = NodeFactory. createImmutableSimpleNode( QName.create(rpc.getOutput().getQName(), "stream-name"), null, streamName); final List> output = new ArrayList>(); output.add(streamNameNode); - final MutableCompositeNode responseData = NodeFactory.createMutableCompositeNode( - rpc.getOutput().getQName(), null, output, null, null); + final MutableCompositeNode responseData = NodeFactory.createMutableCompositeNode(rpc.getOutput().getQName(), + null, output, null, null); if (!Notificator.existListenerFor(pathIdentifier)) { Notificator.createListener(pathIdentifier, streamName); } - return new StructuredData(responseData, rpc.getOutput(), null,prettyPrint); + return new StructuredData(responseData, rpc.getOutput(), null, prettyPrint); } @Override public StructuredData invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) { if (StringUtils.isNotBlank(noPayload)) { - throw new RestconfDocumentedException( - "Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } - return invokeRpc( identifier, (CompositeNode)null,uriInfo); + return invokeRpc(identifier, (CompositeNode) null, uriInfo); } private RpcExecutor resolveIdentifierInInvokeRpc(final String identifier) { @@ -495,8 +473,7 @@ public class RestconfImpl implements RestconfService { MountInstance mountPoint = null; if (identifier.contains(ControllerContext.MOUNT)) { // mounted RPC call - look up mount instance. - InstanceIdWithSchemaNode mountPointId = controllerContext - .toMountPointIdentifier(identifier); + InstanceIdWithSchemaNode mountPointId = controllerContext.toMountPointIdentifier(identifier); mountPoint = mountPointId.getMountPoint(); int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT) @@ -505,12 +482,9 @@ public class RestconfImpl implements RestconfService { 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 ); + 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; } @@ -519,8 +493,7 @@ public class RestconfImpl implements RestconfService { RpcDefinition rpc = controllerContext.getRpcDefinition(identifierDecoded); if (rpc == null) { - throw new RestconfDocumentedException( - "RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT ); + throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT); } if (mountPoint == null) { @@ -531,10 +504,9 @@ public class RestconfImpl implements RestconfService { } - private StructuredData callRpc(final RpcExecutor rpcExecutor, final CompositeNode payload,boolean prettyPrint) { + private StructuredData callRpc(final RpcExecutor rpcExecutor, final CompositeNode payload, boolean prettyPrint) { if (rpcExecutor == null) { - throw new RestconfDocumentedException( - "RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT ); + throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT); } CompositeNode rpcRequest = null; @@ -557,30 +529,29 @@ public class RestconfImpl implements RestconfService { return null; } - if( rpc.getOutput() == null ) - { - return null; //no output, nothing to send back. + if (rpc.getOutput() == null) { + return null; // no output, nothing to send back. } - return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null,prettyPrint); + return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null, prettyPrint); } private void checkRpcSuccessAndThrowException(final RpcResult rpcResult) { if (rpcResult.isSuccessful() == false) { Collection rpcErrors = rpcResult.getErrors(); - if( rpcErrors == null || rpcErrors.isEmpty() ) { + if (rpcErrors == null || rpcErrors.isEmpty()) { throw new RestconfDocumentedException( - "The operation was not successful and there were no RPC errors returned", - ErrorType.RPC, ErrorTag.OPERATION_FAILED ); + "The operation was not successful and there were no RPC errors returned", ErrorType.RPC, + ErrorTag.OPERATION_FAILED); } List errorList = Lists.newArrayList(); - for( RpcError rpcError: rpcErrors ) { - errorList.add( new RestconfError( rpcError ) ); + for (RpcError rpcError : rpcErrors) { + errorList.add(new RestconfError(rpcError)); } - throw new RestconfDocumentedException( errorList ); + throw new RestconfDocumentedException(errorList); } } @@ -591,58 +562,54 @@ public class RestconfImpl implements RestconfService { MountInstance mountPoint = iiWithData.getMountPoint(); if (mountPoint != null) { data = broker.readConfigurationDataBehindMountPoint(mountPoint, iiWithData.getInstanceIdentifier()); - } - else { + } else { data = broker.readConfigurationData(iiWithData.getInstanceIdentifier()); } - data = pruneDataAtDepth( data, parseDepthParameter( uriInfo ) ); - boolean prettyPrintMode = parsePrettyPrintParameter( uriInfo ); - return new StructuredData(data, iiWithData.getSchemaNode(), iiWithData.getMountPoint(),prettyPrintMode); + data = pruneDataAtDepth(data, parseDepthParameter(uriInfo)); + boolean prettyPrintMode = parsePrettyPrintParameter(uriInfo); + return new StructuredData(data, iiWithData.getSchemaNode(), iiWithData.getMountPoint(), prettyPrintMode); } @SuppressWarnings("unchecked") - private > T pruneDataAtDepth( final T node, final Integer depth ) { - if( depth == null ) { + private > T pruneDataAtDepth(final T node, final Integer depth) { + if (depth == null) { return node; } - if( node instanceof CompositeNode ) { + if (node instanceof CompositeNode) { ImmutableList.Builder> newChildNodes = ImmutableList.> builder(); - if( depth > 1 ) { - for( Node childNode: ((CompositeNode)node).getValue() ) { - newChildNodes.add( pruneDataAtDepth( childNode, depth - 1 ) ); + if (depth > 1) { + for (Node childNode : ((CompositeNode) node).getValue()) { + newChildNodes.add(pruneDataAtDepth(childNode, depth - 1)); } } - return (T) ImmutableCompositeNode.create( node.getNodeType(), newChildNodes.build() ); - } - else { // SimpleNode + return (T) ImmutableCompositeNode.create(node.getNodeType(), newChildNodes.build()); + } else { // SimpleNode return node; } } - private Integer parseDepthParameter( final UriInfo info ) { - String param = info.getQueryParameters( false ).getFirst( UriParameters.DEPTH.toString() ); - if( Strings.isNullOrEmpty( param ) || "unbounded".equals( param ) ) { + private Integer parseDepthParameter(final UriInfo info) { + String param = info.getQueryParameters(false).getFirst(UriParameters.DEPTH.toString()); + if (Strings.isNullOrEmpty(param) || "unbounded".equals(param)) { return null; } try { - Integer depth = Integer.valueOf( param ); - if( depth < 1 ) { - throw new RestconfDocumentedException( new RestconfError( - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, "Invalid depth parameter: " + depth, - null, "The depth parameter must be an integer > 1 or \"unbounded\"" ) ); + Integer depth = Integer.valueOf(param); + if (depth < 1) { + throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, + "Invalid depth parameter: " + depth, null, + "The depth parameter must be an integer > 1 or \"unbounded\"")); } return depth; - } - catch( NumberFormatException e ) { - throw new RestconfDocumentedException( new RestconfError( - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, - "Invalid depth parameter: " + e.getMessage(), - null, "The depth parameter must be an integer > 1 or \"unbounded\"" ) ); + } catch (NumberFormatException e) { + throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, + "Invalid depth parameter: " + e.getMessage(), null, + "The depth parameter must be an integer > 1 or \"unbounded\"")); } } @@ -653,14 +620,13 @@ public class RestconfImpl implements RestconfService { MountInstance mountPoint = iiWithData.getMountPoint(); if (mountPoint != null) { data = broker.readOperationalDataBehindMountPoint(mountPoint, iiWithData.getInstanceIdentifier()); - } - else { + } else { data = broker.readOperationalData(iiWithData.getInstanceIdentifier()); } - data = pruneDataAtDepth( data, parseDepthParameter( info ) ); - boolean prettyPrintMode = parsePrettyPrintParameter( info ); - return new StructuredData(data, iiWithData.getSchemaNode(), mountPoint,prettyPrintMode); + data = pruneDataAtDepth(data, parseDepthParameter(info)); + boolean prettyPrintMode = parsePrettyPrintParameter(info); + return new StructuredData(data, iiWithData.getSchemaNode(), mountPoint, prettyPrintMode); } private boolean parsePrettyPrintParameter(UriInfo info) { @@ -681,17 +647,16 @@ public class RestconfImpl implements RestconfService { try { if (mountPoint != null) { - status = broker.commitConfigurationDataPutBehindMountPoint( - mountPoint, iiWithData.getInstanceIdentifier(), value).get(); + status = broker.commitConfigurationDataPutBehindMountPoint(mountPoint, + iiWithData.getInstanceIdentifier(), value).get(); } else { status = broker.commitConfigurationDataPut(iiWithData.getInstanceIdentifier(), value).get(); } - } - catch( Exception e ) { - throw new RestconfDocumentedException( "Error updating data", e ); + } catch (Exception e) { + throw new RestconfDocumentedException("Error updating data", e); } - if( status.getResult() == TransactionStatus.COMMITED ) { + if (status.getResult() == TransactionStatus.COMMITED) { return Response.status(Status.OK).build(); } @@ -699,8 +664,7 @@ public class RestconfImpl implements RestconfService { } /** - * Validates whether keys in {@code payload} are equal to values of keys in - * {@code iiWithData} for list schema node + * 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 @@ -725,38 +689,36 @@ public class RestconfImpl implements RestconfService { 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); + throw new RestconfDocumentedException("Missing key " + keyDefinition + " in URI.", ErrorType.PROTOCOL, + ErrorTag.DATA_MISSING); } final List> payloadKeyValues = payload.getSimpleNodesByName(keyDefinition.getLocalName()); if (payloadKeyValues.isEmpty()) { throw new RestconfDocumentedException("Missing key " + keyDefinition.getLocalName() - + " in the message body.", ErrorType.PROTOCOL, - ErrorTag.DATA_MISSING); + + " in the message body.", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING); } 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); + 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 CompositeNode payload) { - if( payload == null ) { - throw new RestconfDocumentedException( "Input is required.", - ErrorType.PROTOCOL, - ErrorTag.MALFORMED_MESSAGE ); + if (payload == null) { + throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE); } URI payloadNS = this.namespace(payload); if (payloadNS == null) { throw new RestconfDocumentedException( "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)", - ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE ); + ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE); } InstanceIdWithSchemaNode iiWithData = null; @@ -765,27 +727,24 @@ public class RestconfImpl implements RestconfService { // payload represents mount point data and URI represents path to the mount point if (this.endsWithMountPoint(identifier)) { - throw new RestconfDocumentedException( - "URI has bad format. URI should be without \"" + ControllerContext.MOUNT + - "\" for POST operation.", - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + throw new RestconfDocumentedException("URI has bad format. URI should be without \"" + + ControllerContext.MOUNT + "\" for POST operation.", ErrorType.PROTOCOL, + ErrorTag.INVALID_VALUE); } final String completeIdentifier = this.addMountPointIdentifier(identifier); iiWithData = this.controllerContext.toInstanceIdentifier(completeIdentifier); value = this.normalizeNode(payload, iiWithData.getSchemaNode(), iiWithData.getMountPoint()); - } - else { - final InstanceIdWithSchemaNode incompleteInstIdWithData = - this.controllerContext.toInstanceIdentifier(identifier); + } else { + final InstanceIdWithSchemaNode incompleteInstIdWithData = this.controllerContext + .toInstanceIdentifier(identifier); final DataNodeContainer parentSchema = (DataNodeContainer) incompleteInstIdWithData.getSchemaNode(); MountInstance mountPoint = incompleteInstIdWithData.getMountPoint(); final Module module = this.findModule(mountPoint, payload); if (module == null) { - throw new RestconfDocumentedException( - "Module was not found for \"" + payloadNS + "\"", - ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT ); + throw new RestconfDocumentedException("Module was not found for \"" + payloadNS + "\"", + ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT); } String payloadName = this.getName(payload); @@ -800,26 +759,23 @@ public class RestconfImpl implements RestconfService { MountInstance mountPoint = iiWithData.getMountPoint(); try { if (mountPoint != null) { - Future> future = - broker.commitConfigurationDataPostBehindMountPoint( - mountPoint, iiWithData.getInstanceIdentifier(), value); + Future> future = broker.commitConfigurationDataPostBehindMountPoint( + mountPoint, iiWithData.getInstanceIdentifier(), value); status = future == null ? null : future.get(); - } - else { - Future> future = - broker.commitConfigurationDataPost(iiWithData.getInstanceIdentifier(), value); + } else { + Future> future = broker.commitConfigurationDataPost( + iiWithData.getInstanceIdentifier(), value); status = future == null ? null : future.get(); } - } - catch( Exception e ) { - throw new RestconfDocumentedException( "Error creating data", e ); + } catch (Exception e) { + throw new RestconfDocumentedException("Error creating data", e); } if (status == null) { return Response.status(Status.ACCEPTED).build(); } - if( status.getResult() == TransactionStatus.COMMITED ) { + if (status.getResult() == TransactionStatus.COMMITED) { return Response.status(Status.NO_CONTENT).build(); } @@ -828,29 +784,27 @@ public class RestconfImpl implements RestconfService { @Override public Response createConfigurationData(final CompositeNode payload) { - if( payload == null ) { - throw new RestconfDocumentedException( "Input is required.", - ErrorType.PROTOCOL, - ErrorTag.MALFORMED_MESSAGE ); + if (payload == null) { + throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE); } URI payloadNS = this.namespace(payload); if (payloadNS == null) { throw new RestconfDocumentedException( "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)", - ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE ); + ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE); } final Module module = this.findModule(null, payload); if (module == null) { 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 ); + ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE); } String payloadName = this.getName(payload); - final DataSchemaNode schemaNode = this.controllerContext.findInstanceDataChildByNameAndNamespace( - module, payloadName, module.getNamespace()); + final DataSchemaNode schemaNode = this.controllerContext.findInstanceDataChildByNameAndNamespace(module, + payloadName, module.getNamespace()); final CompositeNode value = this.normalizeNode(payload, schemaNode, null); final InstanceIdWithSchemaNode iiWithData = this.addLastIdentifierFromData(null, value, schemaNode); RpcResult status = null; @@ -858,26 +812,23 @@ public class RestconfImpl implements RestconfService { try { if (mountPoint != null) { - Future> future = - broker.commitConfigurationDataPostBehindMountPoint( - mountPoint, iiWithData.getInstanceIdentifier(), value); + Future> future = broker.commitConfigurationDataPostBehindMountPoint( + mountPoint, iiWithData.getInstanceIdentifier(), value); status = future == null ? null : future.get(); - } - else { - Future> future = - broker.commitConfigurationDataPost(iiWithData.getInstanceIdentifier(), value); + } else { + Future> future = broker.commitConfigurationDataPost( + iiWithData.getInstanceIdentifier(), value); status = future == null ? null : future.get(); } - } - catch( Exception e ) { - throw new RestconfDocumentedException( "Error creating data", e ); + } catch (Exception e) { + throw new RestconfDocumentedException("Error creating data", e); } if (status == null) { return Response.status(Status.ACCEPTED).build(); } - if( status.getResult() == TransactionStatus.COMMITED ) { + if (status.getResult() == TransactionStatus.COMMITED) { return Response.status(Status.NO_CONTENT).build(); } @@ -892,18 +843,16 @@ public class RestconfImpl implements RestconfService { try { if (mountPoint != null) { - status = broker.commitConfigurationDataDeleteBehindMountPoint( - mountPoint, iiWithData.getInstanceIdentifier()).get(); - } - else { + status = broker.commitConfigurationDataDeleteBehindMountPoint(mountPoint, + iiWithData.getInstanceIdentifier()).get(); + } else { status = broker.commitConfigurationDataDelete(iiWithData.getInstanceIdentifier()).get(); } - } - catch( Exception e ) { - throw new RestconfDocumentedException( "Error creating data", e ); + } catch (Exception e) { + throw new RestconfDocumentedException("Error creating data", e); } - if( status.getResult() == TransactionStatus.COMMITED ) { + if (status.getResult() == TransactionStatus.COMMITED) { return Response.status(Status.OK).build(); } @@ -914,14 +863,12 @@ public class RestconfImpl implements RestconfService { public Response subscribeToStream(final String identifier, final UriInfo uriInfo) { final String streamName = Notificator.createStreamNameFromUri(identifier); if (Strings.isNullOrEmpty(streamName)) { - throw new RestconfDocumentedException( - "Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } final ListenerAdapter listener = Notificator.getListenerFor(streamName); if (listener == null) { - throw new RestconfDocumentedException( - "Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT ); + throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT); } broker.registerToListenDataChanges(listener); @@ -935,26 +882,23 @@ public class RestconfImpl implements RestconfService { private Module findModule(final MountInstance mountPoint, final CompositeNode data) { if (data instanceof CompositeNodeWrapper) { - return findModule(mountPoint, (CompositeNodeWrapper)data); - } - else if (data != null) { + return findModule(mountPoint, (CompositeNodeWrapper) data); + } else if (data != null) { URI namespace = data.getNodeType().getNamespace(); if (mountPoint != null) { return this.controllerContext.findModuleByNamespace(mountPoint, namespace); - } - else { + } else { return this.controllerContext.findModuleByNamespace(namespace); } - } - else { - throw new IllegalArgumentException("Unhandled parameter types: " + - Arrays.asList(mountPoint, data).toString()); + } else { + throw new IllegalArgumentException("Unhandled parameter types: " + + Arrays. asList(mountPoint, data).toString()); } } private Module findModule(final MountInstance mountPoint, final CompositeNodeWrapper data) { URI namespace = data.getNamespace(); - Preconditions.checkNotNull(namespace); + Preconditions. checkNotNull(namespace); Module module = null; if (mountPoint != null) { @@ -962,8 +906,7 @@ public class RestconfImpl implements RestconfService { if (module == null) { module = this.controllerContext.findModuleByName(mountPoint, namespace.toString()); } - } - else { + } else { module = this.controllerContext.findModuleByNamespace(namespace); if (module == null) { module = this.controllerContext.findModuleByName(namespace.toString()); @@ -973,8 +916,7 @@ public class RestconfImpl implements RestconfService { return module; } - private InstanceIdWithSchemaNode addLastIdentifierFromData( - final InstanceIdWithSchemaNode identifierWithSchemaNode, + private InstanceIdWithSchemaNode addLastIdentifierFromData(final InstanceIdWithSchemaNode identifierWithSchemaNode, final CompositeNode data, final DataSchemaNode schemaOfData) { InstanceIdentifier instanceIdentifier = null; if (identifierWithSchemaNode != null) { @@ -985,31 +927,28 @@ public class RestconfImpl implements RestconfService { InstanceIdentifierBuilder iiBuilder = null; if (iiOriginal == null) { iiBuilder = InstanceIdentifier.builder(); - } - else { + } else { iiBuilder = InstanceIdentifier.builder(iiOriginal); } if ((schemaOfData instanceof ListSchemaNode)) { - HashMap keys = this.resolveKeysFromData(((ListSchemaNode) schemaOfData), data); + HashMap keys = this.resolveKeysFromData(((ListSchemaNode) schemaOfData), data); iiBuilder.nodeWithKey(schemaOfData.getQName(), keys); - } - else { + } else { iiBuilder.node(schemaOfData.getQName()); } InstanceIdentifier instance = iiBuilder.toInstance(); MountInstance mountPoint = null; if (identifierWithSchemaNode != null) { - mountPoint=identifierWithSchemaNode.getMountPoint(); + mountPoint = identifierWithSchemaNode.getMountPoint(); } return new InstanceIdWithSchemaNode(instance, schemaOfData, mountPoint); } - private HashMap resolveKeysFromData(final ListSchemaNode listNode, - final CompositeNode dataNode) { - final HashMap keyValues = new HashMap(); + private HashMap resolveKeysFromData(final ListSchemaNode listNode, final CompositeNode dataNode) { + final HashMap keyValues = new HashMap(); List _keyDefinition = listNode.getKeyDefinition(); for (final QName key : _keyDefinition) { SimpleNode head = null; @@ -1025,10 +964,9 @@ public class RestconfImpl implements RestconfService { } if (dataNodeKeyValueObject == null) { - throw new RestconfDocumentedException( - "Data contains list \"" + dataNode.getNodeType().getLocalName() + - "\" which does not contain key: \"" + key.getLocalName() + "\"", - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + 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); @@ -1038,15 +976,16 @@ public class RestconfImpl implements RestconfService { } private boolean endsWithMountPoint(final String identifier) { - return identifier.endsWith(ControllerContext.MOUNT) || - identifier.endsWith(ControllerContext.MOUNT + "/"); + return identifier.endsWith(ControllerContext.MOUNT) || identifier.endsWith(ControllerContext.MOUNT + "/"); } private boolean representsMountPointRootData(final CompositeNode data) { URI namespace = this.namespace(data); - return (SchemaContext.NAME.getNamespace().equals( namespace ) /* || - MOUNT_POINT_MODULE_NAME.equals( namespace.toString() )*/ ) && - SchemaContext.NAME.getLocalName().equals( this.localName(data) ); + return (SchemaContext.NAME.getNamespace().equals(namespace) /* + * || MOUNT_POINT_MODULE_NAME .equals( namespace . + * toString( ) ) + */) + && SchemaContext.NAME.getLocalName().equals(this.localName(data)); } private String addMountPointIdentifier(final String identifier) { @@ -1064,15 +1003,13 @@ public class RestconfImpl implements RestconfService { QName nodeType = node == null ? null : node.getNodeType(); String localName = nodeType == null ? null : nodeType.getLocalName(); - throw new RestconfDocumentedException( - "Data schema node was not found for " + localName, - ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + 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 ); + throw new RestconfDocumentedException("Root element has to be container or list yang datatype.", + ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } if ((node instanceof CompositeNodeWrapper)) { @@ -1080,10 +1017,8 @@ public class RestconfImpl implements RestconfService { if (isChangeAllowed) { try { this.normalizeNode(((CompositeNodeWrapper) node), schema, null, mountPoint); - } - catch (IllegalArgumentException e) { - throw new RestconfDocumentedException( - e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE ); + } catch (IllegalArgumentException e) { + throw new RestconfDocumentedException(e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } } @@ -1093,66 +1028,56 @@ public class RestconfImpl implements RestconfService { return node; } - private void normalizeNode(final NodeWrapper nodeBuilder, - final DataSchemaNode schema, final QName previousAugment, - final MountInstance mountPoint) { + private void normalizeNode(final NodeWrapper nodeBuilder, final DataSchemaNode schema, + final QName previousAugment, final MountInstance 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 ); + 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 { + } else { currentAugment = this.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 ); + "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 ); + 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 ); + } 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 ) { + private void normalizeAnyXmlNode(final CompositeNodeWrapper compositeNode, final AnyXmlSchemaNode schema) { List> children = compositeNode.getValues(); - for( NodeWrapper child : children ) { - child.setNamespace( schema.getQName().getNamespace() ); - if( child instanceof CompositeNodeWrapper ) { - normalizeAnyXmlNode( (CompositeNodeWrapper)child, schema ); + for (NodeWrapper child : children) { + child.setNamespace(schema.getQName().getNamespace()); + if (child instanceof CompositeNodeWrapper) { + normalizeAnyXmlNode((CompositeNodeWrapper) child, schema); } } } - private void normalizeEmptyNode( final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema ) { + private void normalizeEmptyNode(final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema) { if ((schema instanceof LeafSchemaNode)) { emptyNodeBuilder.setComposite(false); - } - else { + } else { if ((schema instanceof ContainerSchemaNode)) { // FIXME: Add presence check emptyNodeBuilder.setComposite(true); @@ -1160,59 +1085,55 @@ public class RestconfImpl implements RestconfService { } } - private void normalizeSimpleNode( final SimpleNodeWrapper simpleNode, final DataSchemaNode schema, - final MountInstance mountPoint ) { + private void normalizeSimpleNode(final SimpleNodeWrapper simpleNode, final DataSchemaNode schema, + final MountInstance mountPoint) { final Object value = simpleNode.getValue(); Object inputValue = value; TypeDefinition typeDefinition = this.typeDefinition(schema); if ((typeDefinition instanceof IdentityrefTypeDefinition)) { if ((value instanceof String)) { - inputValue = new IdentityValuesDTO( simpleNode.getNamespace().toString(), - (String) value, null, (String) value ); + inputValue = new IdentityValuesDTO(simpleNode.getNamespace().toString(), (String) value, null, + (String) value); } // else value is already instance of IdentityValuesDTO } Object outputValue = inputValue; - if( typeDefinition != null ) { - Codec codec = RestCodec.from(typeDefinition, mountPoint); + if (typeDefinition != null) { + Codec codec = RestCodec.from(typeDefinition, mountPoint); outputValue = codec == null ? null : codec.deserialize(inputValue); } simpleNode.setValue(outputValue); } - private void normalizeCompositeNode( final CompositeNodeWrapper compositeNodeBuilder, - final DataNodeContainer schema, final MountInstance mountPoint, - final QName currentAugment ) { + private void normalizeCompositeNode(final CompositeNodeWrapper compositeNodeBuilder, + final DataNodeContainer schema, final MountInstance mountPoint, final QName currentAugment) { final List> children = compositeNodeBuilder.getValues(); - checkNodeMultiplicityAccordingToSchema(schema,children); + checkNodeMultiplicityAccordingToSchema(schema, children); for (final NodeWrapper child : children) { - final List potentialSchemaNodes = - this.controllerContext.findInstanceDataChildrenByName( - schema, child.getLocalName()); + final List potentialSchemaNodes = this.controllerContext.findInstanceDataChildrenByName( + schema, child.getLocalName()); if (potentialSchemaNodes.size() > 1 && child.getNamespace() == null) { StringBuilder builder = new StringBuilder(); for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) { - builder.append(" ").append(potentialSchemaNode.getQName().getNamespace().toString()) - .append("\n"); + 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 ); + 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 = - this.normalizeNodeName(child, potentialSchemaNode, currentAugment, mountPoint); - if (child.getQname() != null ) { + final QName potentialCurrentAugment = this.normalizeNodeName(child, potentialSchemaNode, + currentAugment, mountPoint); + if (child.getQname() != null) { this.normalizeNode(child, potentialSchemaNode, potentialCurrentAugment, mountPoint); rightNodeSchemaFound = true; } @@ -1220,14 +1141,13 @@ public class RestconfImpl implements RestconfService { } if (!rightNodeSchemaFound) { - throw new RestconfDocumentedException( - "Schema node \"" + child.getLocalName() + "\" was not found in module.", - ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT ); + throw new RestconfDocumentedException("Schema node \"" + child.getLocalName() + + "\" was not found in module.", ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT); } } if ((schema instanceof ListSchemaNode)) { - ListSchemaNode listSchemaNode = (ListSchemaNode)schema; + ListSchemaNode listSchemaNode = (ListSchemaNode) schema; final List listKeys = listSchemaNode.getKeyDefinition(); for (final QName listKey : listKeys) { boolean foundKey = false; @@ -1238,10 +1158,9 @@ public class RestconfImpl implements RestconfService { } if (!foundKey) { - throw new RestconfDocumentedException( - "Missing key '" + listKey.getLocalName() + - "' for list '" + listSchemaNode.getQName().getLocalName() + "' in the message body", - ErrorType.PROTOCOL, ErrorTag.DATA_MISSING ); + throw new RestconfDocumentedException("Missing key in URI \"" + listKey.getLocalName() + + "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"", ErrorType.PROTOCOL, + ErrorTag.DATA_MISSING); } } } @@ -1260,43 +1179,43 @@ public class RestconfImpl implements RestconfService { String localName = childSchemaNode.getQName().getLocalName(); Integer count = equalNodeNamesToCounts.get(localName); if (count != null && count > 1) { - throw new RestconfDocumentedException( - "Multiple input data elements were specified for '" + 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); + + "'. The data for this element type can only be specified once.", ErrorType.APPLICATION, + ErrorTag.BAD_ELEMENT); } } } } - private QName normalizeNodeName(final NodeWrapper nodeBuilder, - final DataSchemaNode schema, final QName previousAugment, - final MountInstance mountPoint) { + private QName normalizeNodeName(final NodeWrapper nodeBuilder, final DataSchemaNode schema, + final QName previousAugment, final MountInstance 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())) { + } 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 { + } 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)*/ ) { + 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); } @@ -1306,40 +1225,31 @@ public class RestconfImpl implements RestconfService { private URI namespace(final CompositeNode data) { if (data instanceof CompositeNodeWrapper) { - return ((CompositeNodeWrapper)data).getNamespace(); - } - else if (data != null) { + return ((CompositeNodeWrapper) data).getNamespace(); + } else if (data != null) { return data.getNodeType().getNamespace(); - } - else { - throw new IllegalArgumentException("Unhandled parameter types: " + - Arrays.asList(data).toString()); + } else { + throw new IllegalArgumentException("Unhandled parameter types: " + Arrays. asList(data).toString()); } } private String localName(final CompositeNode data) { if (data instanceof CompositeNodeWrapper) { - return ((CompositeNodeWrapper)data).getLocalName(); - } - else if (data != null) { + return ((CompositeNodeWrapper) data).getLocalName(); + } else if (data != null) { return data.getNodeType().getLocalName(); - } - else { - throw new IllegalArgumentException("Unhandled parameter types: " + - Arrays.asList(data).toString()); + } else { + throw new IllegalArgumentException("Unhandled parameter types: " + Arrays. asList(data).toString()); } } private String getName(final CompositeNode data) { if (data instanceof CompositeNodeWrapper) { - return ((CompositeNodeWrapper)data).getLocalName(); - } - else if (data != null) { + return ((CompositeNodeWrapper) data).getLocalName(); + } else if (data != null) { return data.getNodeType().getLocalName(); - } - else { - throw new IllegalArgumentException("Unhandled parameter types: " + - Arrays.asList(data).toString()); + } else { + throw new IllegalArgumentException("Unhandled parameter types: " + Arrays. asList(data).toString()); } } @@ -1363,17 +1273,13 @@ public class RestconfImpl implements RestconfService { private TypeDefinition typeDefinition(final DataSchemaNode node) { if (node instanceof LeafListSchemaNode) { - return typeDefinition((LeafListSchemaNode)node); - } - else if (node instanceof LeafSchemaNode) { - return _typeDefinition((LeafSchemaNode)node); - } - else if (node instanceof AnyXmlSchemaNode) { + return typeDefinition((LeafListSchemaNode) node); + } else if (node instanceof LeafSchemaNode) { + return _typeDefinition((LeafSchemaNode) node); + } else if (node instanceof AnyXmlSchemaNode) { return null; - } - else { - throw new IllegalArgumentException("Unhandled parameter types: " + - Arrays.asList(node).toString()); + } else { + throw new IllegalArgumentException("Unhandled parameter types: " + Arrays. asList(node).toString()); } } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/SimpleNodeWrapper.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/SimpleNodeWrapper.java index b0959c8398..854e9635cf 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/SimpleNodeWrapper.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/SimpleNodeWrapper.java @@ -8,9 +8,7 @@ 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; @@ -129,6 +127,4 @@ public final class SimpleNodeWrapper implements NodeWrapper>, Simp return unwrap().setValue(value); } - - } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/package-info.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/package-info.java index 6008b1d3c7..120c67d3d5 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/package-info.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/package-info.java @@ -5,4 +5,4 @@ * 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; +package org.opendaylight.controller.sal.restconf.impl; \ No newline at end of file diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/AbstractRpcExecutor.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/AbstractRpcExecutor.java index 417cca6533..4c5e3ab530 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/AbstractRpcExecutor.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/AbstractRpcExecutor.java @@ -1,16 +1,15 @@ /* -* 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 -*/ + * 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; @@ -21,7 +20,7 @@ import org.opendaylight.yangtools.yang.model.api.RpcDefinition; public abstract class AbstractRpcExecutor implements RpcExecutor { private final RpcDefinition rpcDef; - public AbstractRpcExecutor( RpcDefinition rpcDef ){ + public AbstractRpcExecutor(RpcDefinition rpcDef) { this.rpcDef = rpcDef; } @@ -31,60 +30,47 @@ public abstract class AbstractRpcExecutor implements RpcExecutor { } @Override - public RpcResult invokeRpc( CompositeNode rpcRequest ) - throws RestconfDocumentedException { + public RpcResult 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( Exception e ) { - throw new RestconfDocumentedException( - "The operation encountered an unexpected error while executing.", e ); + 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 (Exception e) { + throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.", e); } } - protected abstract Future> invokeRpcUnchecked( CompositeNode rpcRequest ); + protected abstract Future> invokeRpcUnchecked(CompositeNode rpcRequest); - protected RpcResult getRpcResult( - Future> fromFuture ) { + protected RpcResult getRpcResult(Future> fromFuture) { try { return fromFuture.get(); - } - catch( InterruptedException e ) { + } catch (InterruptedException e) { throw new RestconfDocumentedException( - "The operation was interrupted while executing and did not complete.", - ErrorType.RPC, ErrorTag.PARTIAL_OPERATION ); - } - catch( ExecutionException e ) { + "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 ) { + 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 ); + 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 ); + 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); } } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/BrokerRpcExecutor.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/BrokerRpcExecutor.java index e23e95faab..146e69f011 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/BrokerRpcExecutor.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/BrokerRpcExecutor.java @@ -1,14 +1,13 @@ /* -* 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 -*/ + * 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; @@ -17,14 +16,13 @@ import org.opendaylight.yangtools.yang.model.api.RpcDefinition; public class BrokerRpcExecutor extends AbstractRpcExecutor { private final BrokerFacade broker; - public BrokerRpcExecutor( RpcDefinition rpcDef, BrokerFacade broker ) - { - super( rpcDef ); + public BrokerRpcExecutor(RpcDefinition rpcDef, BrokerFacade broker) { + super(rpcDef); this.broker = broker; } @Override - protected Future> invokeRpcUnchecked( CompositeNode rpcRequest ) { - return broker.invokeRpc( getRpcDefinition().getQName(), rpcRequest ); + protected Future> invokeRpcUnchecked(CompositeNode rpcRequest) { + return broker.invokeRpc(getRpcDefinition().getQName(), rpcRequest); } } \ No newline at end of file diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/MountPointRpcExecutor.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/MountPointRpcExecutor.java index 26cb3b8102..36502656c2 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/MountPointRpcExecutor.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/MountPointRpcExecutor.java @@ -1,23 +1,22 @@ /* -* 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 -*/ + * 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.Preconditions; import java.util.concurrent.Future; - import org.opendaylight.controller.sal.core.api.mount.MountInstance; import org.opendaylight.yangtools.yang.common.RpcResult; import org.opendaylight.yangtools.yang.data.api.CompositeNode; import org.opendaylight.yangtools.yang.model.api.RpcDefinition; -import com.google.common.base.Preconditions; - /** * Provides an implementation which invokes rpc methods via a mounted yang data model. + * * @author Devin Avery * */ @@ -25,13 +24,13 @@ public class MountPointRpcExecutor extends AbstractRpcExecutor { private final MountInstance mountPoint; public MountPointRpcExecutor(RpcDefinition rpcDef, MountInstance mountPoint) { - super( rpcDef ); + super(rpcDef); this.mountPoint = mountPoint; - Preconditions.checkNotNull( mountPoint, "MountInstance can not be null." ); + Preconditions.checkNotNull(mountPoint, "MountInstance can not be null."); } @Override - protected Future> invokeRpcUnchecked( CompositeNode rpcRequest ) { - return mountPoint.rpc( getRpcDefinition().getQName(), rpcRequest ); + protected Future> invokeRpcUnchecked(CompositeNode rpcRequest) { + return mountPoint.rpc(getRpcDefinition().getQName(), rpcRequest); } } \ No newline at end of file diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/RpcExecutor.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/RpcExecutor.java index f628a63393..3430226c3a 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/RpcExecutor.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/RpcExecutor.java @@ -1,10 +1,10 @@ /* -* 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 -*/ + * 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; @@ -12,7 +12,7 @@ import org.opendaylight.yangtools.yang.data.api.CompositeNode; import org.opendaylight.yangtools.yang.model.api.RpcDefinition; public interface RpcExecutor { - RpcResult invokeRpc( CompositeNode rpcRequest ); + RpcResult invokeRpc(CompositeNode rpcRequest); RpcDefinition getRpcDefinition(); } \ No newline at end of file diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/ListenerAdapter.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/ListenerAdapter.java index 925a09337c..e526ec13be 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/ListenerAdapter.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/ListenerAdapter.java @@ -12,11 +12,9 @@ import com.google.common.base.Preconditions; import com.google.common.eventbus.AsyncEventBus; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; - import io.netty.channel.Channel; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.util.internal.ConcurrentSet; - import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; @@ -30,7 +28,6 @@ import java.util.Random; import java.util.Set; import java.util.concurrent.Executors; import java.util.regex.Pattern; - import javax.activation.UnsupportedDataTypeException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -41,7 +38,6 @@ 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.md.sal.common.api.data.DataChangeEvent; import org.opendaylight.controller.sal.core.api.data.DataChangeListener; import org.opendaylight.controller.sal.rest.impl.XmlMapper; @@ -61,8 +57,7 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; /** - * {@link ListenerAdapter} is responsible to track events, which occurred by - * changing data in data source. + * {@link ListenerAdapter} is responsible to track events, which occurred by changing data in data source. */ public class ListenerAdapter implements DataChangeListener { @@ -72,8 +67,7 @@ public class ListenerAdapter implements DataChangeListener { 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 SimpleDateFormat rfc3339 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ"); private final InstanceIdentifier path; private ListenerRegistration registration; @@ -82,10 +76,8 @@ public class ListenerAdapter implements DataChangeListener { private final EventBus eventBus; private final EventBusChangeRecorder eventBusChangeRecorder; - /** - * Creates new {@link ListenerAdapter} listener specified by path and stream - * name. + * Creates new {@link ListenerAdapter} listener specified by path and stream name. * * @param path * Path to data in data store. @@ -94,8 +86,7 @@ public class ListenerAdapter implements DataChangeListener { */ ListenerAdapter(final InstanceIdentifier path, final String streamName) { Preconditions.checkNotNull(path); - Preconditions - .checkArgument(streamName != null && !streamName.isEmpty()); + Preconditions.checkArgument(streamName != null && !streamName.isEmpty()); this.path = path; this.streamName = streamName; eventBus = new AsyncEventBus(Executors.newSingleThreadExecutor()); @@ -104,14 +95,10 @@ public class ListenerAdapter implements DataChangeListener { } @Override - public void onDataChanged( - final DataChangeEvent change) { - if (!change.getCreatedConfigurationData().isEmpty() - || !change.getCreatedOperationalData().isEmpty() - || !change.getUpdatedConfigurationData().isEmpty() - || !change.getUpdatedOperationalData().isEmpty() - || !change.getRemovedConfigurationData().isEmpty() - || !change.getRemovedOperationalData().isEmpty()) { + public void onDataChanged(final DataChangeEvent change) { + if (!change.getCreatedConfigurationData().isEmpty() || !change.getCreatedOperationalData().isEmpty() + || !change.getUpdatedConfigurationData().isEmpty() || !change.getUpdatedOperationalData().isEmpty() + || !change.getRemovedConfigurationData().isEmpty() || !change.getRemovedOperationalData().isEmpty()) { String xml = prepareXmlFrom(change); Event event = new Event(EventType.NOTIFY); event.setData(xml); @@ -132,19 +119,14 @@ public class ListenerAdapter implements DataChangeListener { } } else if (event.getType() == EventType.DEREGISTER) { subscribers.remove(event.getSubscriber()); - Notificator - .removeListenerIfNoSubscriberExists(ListenerAdapter.this); + Notificator.removeListenerIfNoSubscriberExists(ListenerAdapter.this); } else if (event.getType() == EventType.NOTIFY) { for (Channel subscriber : subscribers) { if (subscriber.isActive()) { - LOG.debug("Data are sent to subscriber {}:", - subscriber.remoteAddress()); - subscriber.writeAndFlush(new TextWebSocketFrame(event - .getData())); + LOG.debug("Data are sent to subscriber {}:", subscriber.remoteAddress()); + subscriber.writeAndFlush(new TextWebSocketFrame(event.getData())); } else { - LOG.debug( - "Subscriber {} is removed - channel is not active yet.", - subscriber.remoteAddress()); + LOG.debug("Subscriber {} is removed - channel is not active yet.", subscriber.remoteAddress()); subscribers.remove(subscriber); } } @@ -153,8 +135,7 @@ public class ListenerAdapter implements DataChangeListener { } /** - * Represents event of specific {@link EventType} type, holds data and - * {@link Channel} subscriber. + * Represents event of specific {@link EventType} type, holds data and {@link Channel} subscriber. */ private final class Event { private final EventType type; @@ -223,7 +204,9 @@ public class ListenerAdapter implements DataChangeListener { * Type of the event. */ private enum EventType { - REGISTER, DEREGISTER, NOTIFY; + REGISTER, + DEREGISTER, + NOTIFY; } /** @@ -233,11 +216,9 @@ public class ListenerAdapter implements DataChangeListener { * DataChangeEvent * @return Data in printable form. */ - private String prepareXmlFrom( - final DataChangeEvent change) { + private String prepareXmlFrom(final DataChangeEvent change) { Document doc = createDocument(); - Element notificationElement = doc.createElementNS( - "urn:ietf:params:xml:ns:netconf:notification:1.0", + Element notificationElement = doc.createElementNS("urn:ietf:params:xml:ns:netconf:notification:1.0", "notification"); doc.appendChild(notificationElement); @@ -246,10 +227,8 @@ public class ListenerAdapter implements DataChangeListener { notificationElement.appendChild(eventTimeElement); Element dataChangedNotificationEventElement = doc.createElementNS( - "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", - "data-changed-notification"); - addValuesToDataChangedNotificationEventElement(doc, - dataChangedNotificationEventElement, change); + "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "data-changed-notification"); + addValuesToDataChangedNotificationEventElement(doc, dataChangedNotificationEventElement, change); notificationElement.appendChild(dataChangedNotificationEventElement); try { @@ -260,8 +239,7 @@ public class ListenerAdapter implements DataChangeListener { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); - transformer.transform(new DOMSource(doc), new StreamResult( - new OutputStreamWriter(out, Charsets.UTF_8))); + transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, Charsets.UTF_8))); byte[] charData = out.toByteArray(); return new String(charData, "UTF-8"); } catch (TransformerException | UnsupportedEncodingException e) { @@ -310,29 +288,22 @@ public class ListenerAdapter implements DataChangeListener { private void addValuesToDataChangedNotificationEventElement(final Document doc, final Element dataChangedNotificationEventElement, final DataChangeEvent change) { - addValuesFromDataToElement(doc, change.getCreatedConfigurationData(), - dataChangedNotificationEventElement, Store.CONFIG, - Operation.CREATED); - addValuesFromDataToElement(doc, change.getCreatedOperationalData(), - dataChangedNotificationEventElement, Store.OPERATION, - Operation.CREATED); + addValuesFromDataToElement(doc, change.getCreatedConfigurationData(), dataChangedNotificationEventElement, + Store.CONFIG, Operation.CREATED); + addValuesFromDataToElement(doc, change.getCreatedOperationalData(), dataChangedNotificationEventElement, + Store.OPERATION, Operation.CREATED); if (change.getCreatedConfigurationData().isEmpty()) { - addValuesFromDataToElement(doc, - change.getUpdatedConfigurationData(), - dataChangedNotificationEventElement, Store.CONFIG, - Operation.UPDATED); + addValuesFromDataToElement(doc, change.getUpdatedConfigurationData(), dataChangedNotificationEventElement, + Store.CONFIG, Operation.UPDATED); } if (change.getCreatedOperationalData().isEmpty()) { - addValuesFromDataToElement(doc, change.getUpdatedOperationalData(), - dataChangedNotificationEventElement, Store.OPERATION, - Operation.UPDATED); + addValuesFromDataToElement(doc, change.getUpdatedOperationalData(), dataChangedNotificationEventElement, + Store.OPERATION, Operation.UPDATED); } - addValuesFromDataToElement(doc, change.getRemovedConfigurationData(), - dataChangedNotificationEventElement, Store.CONFIG, - Operation.DELETED); - addValuesFromDataToElement(doc, change.getRemovedOperationalData(), - dataChangedNotificationEventElement, Store.OPERATION, - Operation.DELETED); + addValuesFromDataToElement(doc, change.getRemovedConfigurationData(), dataChangedNotificationEventElement, + Store.CONFIG, Operation.DELETED); + addValuesFromDataToElement(doc, change.getRemovedOperationalData(), dataChangedNotificationEventElement, + Store.OPERATION, Operation.DELETED); } /** @@ -349,15 +320,13 @@ public class ListenerAdapter implements DataChangeListener { * @param operation * {@link Operation} */ - private void addValuesFromDataToElement(final Document doc, - final Set data, final Element element, final Store store, - final Operation operation) { + private void addValuesFromDataToElement(final Document doc, final Set data, + final Element element, final Store store, final Operation operation) { if (data == null || data.isEmpty()) { return; } for (InstanceIdentifier path : data) { - Node node = createDataChangeEventElement(doc, path, null, store, - operation); + Node node = createDataChangeEventElement(doc, path, null, store, operation); element.appendChild(node); } } @@ -376,15 +345,13 @@ public class ListenerAdapter implements DataChangeListener { * @param operation * {@link Operation} */ - private void addValuesFromDataToElement(final Document doc, - final Map data, final Element element, - final Store store, final Operation operation) { + private void addValuesFromDataToElement(final Document doc, final Map data, + final Element element, final Store store, final Operation operation) { if (data == null || data.isEmpty()) { return; } for (Entry entry : data.entrySet()) { - Node node = createDataChangeEventElement(doc, entry.getKey(), - entry.getValue(), store, operation); + Node node = createDataChangeEventElement(doc, entry.getKey(), entry.getValue(), store, operation); element.appendChild(node); } } @@ -404,9 +371,8 @@ public class ListenerAdapter implements DataChangeListener { * {@link Operation} * @return {@link Node} node represented by changed event element. */ - private Node createDataChangeEventElement(final Document doc, - final InstanceIdentifier path, final CompositeNode data, final Store store, - final Operation operation) { + private Node createDataChangeEventElement(final Document doc, final InstanceIdentifier path, + final CompositeNode data, final Store store, final Operation operation) { Element dataChangeEventElement = doc.createElement("data-change-event"); Element pathElement = doc.createElement("path"); @@ -442,8 +408,7 @@ public class ListenerAdapter implements DataChangeListener { * @return Data in XML format. */ private Node translateToXml(final InstanceIdentifier path, final CompositeNode data) { - DataNodeContainer schemaNode = ControllerContext.getInstance() - .getDataNodeContainerFor(path); + DataNodeContainer schemaNode = ControllerContext.getInstance().getDataNodeContainerFor(path); if (schemaNode == null) { LOG.info( "Path '{}' contains node with unsupported type (supported type is Container or List) or some node was not found.", @@ -454,9 +419,7 @@ public class ListenerAdapter implements DataChangeListener { Document xml = xmlMapper.write(data, schemaNode); return xml.getFirstChild(); } catch (UnsupportedDataTypeException e) { - LOG.error( - "Error occured during translation of notification to XML.", - e); + LOG.error("Error occured during translation of notification to XML.", e); return null; } } @@ -469,8 +432,7 @@ public class ListenerAdapter implements DataChangeListener { * @param element * {@link Element} */ - private void addPathAsValueToElement(final InstanceIdentifier path, - final Element element) { + private void addPathAsValueToElement(final InstanceIdentifier path, final Element element) { // Map< key = namespace, value = prefix> Map prefixes = new HashMap<>(); InstanceIdentifier instanceIdentifier = path; @@ -479,17 +441,13 @@ public class ListenerAdapter implements DataChangeListener { // FIXME: BUG-1281: this is duplicated code from yangtools (BUG-1275) for (PathArgument pathArgument : instanceIdentifier.getPathArguments()) { textContent.append("/"); - writeIdentifierWithNamespacePrefix(element, textContent, - pathArgument.getNodeType(), prefixes); + writeIdentifierWithNamespacePrefix(element, textContent, pathArgument.getNodeType(), prefixes); if (pathArgument instanceof NodeIdentifierWithPredicates) { - Map predicates = ((NodeIdentifierWithPredicates) pathArgument) - .getKeyValues(); + Map predicates = ((NodeIdentifierWithPredicates) pathArgument).getKeyValues(); for (QName keyValue : predicates.keySet()) { - String predicateValue = String.valueOf(predicates - .get(keyValue)); + String predicateValue = String.valueOf(predicates.get(keyValue)); textContent.append("["); - writeIdentifierWithNamespacePrefix(element, textContent, - keyValue, prefixes); + writeIdentifierWithNamespacePrefix(element, textContent, keyValue, prefixes); textContent.append("='"); textContent.append(predicateValue); textContent.append("'"); @@ -517,14 +475,13 @@ public class ListenerAdapter implements DataChangeListener { * @param prefixes * Map of namespaces and prefixes. */ - private static void writeIdentifierWithNamespacePrefix(final Element element, - final StringBuilder textContent, final QName qName, final Map prefixes) { + private static void writeIdentifierWithNamespacePrefix(final Element element, final StringBuilder textContent, + final QName qName, final Map prefixes) { String namespace = qName.getNamespace().toString(); String prefix = prefixes.get(namespace); if (prefix == null) { prefix = qName.getPrefix(); - if (prefix == null || prefix.isEmpty() - || prefixes.containsValue(prefix)) { + if (prefix == null || prefix.isEmpty() || prefixes.containsValue(prefix)) { prefix = generateNewPrefix(prefixes.values()); } } @@ -573,8 +530,7 @@ public class ListenerAdapter implements DataChangeListener { * @param registration * ListenerRegistration */ - public void setRegistration( - final ListenerRegistration registration) { + public void setRegistration(final ListenerRegistration registration) { this.registration = registration; } @@ -588,8 +544,7 @@ public class ListenerAdapter implements DataChangeListener { } /** - * Removes all subscribers and unregisters event bus change recorder form - * event bus. + * Removes all subscribers and unregisters event bus change recorder form event bus. */ public void close() throws Exception { subscribers = new ConcurrentSet<>(); @@ -608,16 +563,15 @@ public class ListenerAdapter implements DataChangeListener { } /** - * Creates event of type {@link EventType#REGISTER}, set {@link Channel} - * subscriber to the event and post event into event bus. + * Creates event of type {@link EventType#REGISTER}, set {@link Channel} subscriber to the event and post event into + * event bus. * * @param subscriber * Channel */ public void addSubscriber(final Channel subscriber) { if (!subscriber.isActive()) { - LOG.debug("Channel is not active between websocket server and subscriber {}" - + subscriber.remoteAddress()); + LOG.debug("Channel is not active between websocket server and subscriber {}" + subscriber.remoteAddress()); } Event event = new Event(EventType.REGISTER); event.setSubscriber(subscriber); @@ -625,8 +579,8 @@ public class ListenerAdapter implements DataChangeListener { } /** - * Creates event of type {@link EventType#DEREGISTER}, sets {@link Channel} - * subscriber to the event and posts event into event bus. + * Creates event of type {@link EventType#DEREGISTER}, sets {@link Channel} subscriber to the event and posts event + * into event bus. * * @param subscriber */ @@ -640,8 +594,7 @@ public class ListenerAdapter implements DataChangeListener { /** * Checks if exists at least one {@link Channel} subscriber. * - * @return True if exist at least one {@link Channel} subscriber, false - * otherwise. + * @return True if exist at least one {@link Channel} subscriber, false otherwise. */ public boolean hasSubscribers() { return !subscribers.isEmpty(); @@ -651,7 +604,8 @@ public class ListenerAdapter implements DataChangeListener { * Consists of two types {@link Store#CONFIG} and {@link Store#OPERATION}. */ private static enum Store { - CONFIG("config"), OPERATION("operation"); + CONFIG("config"), + OPERATION("operation"); private final String value; @@ -661,11 +615,12 @@ public class ListenerAdapter implements DataChangeListener { } /** - * Consists of three types {@link Operation#CREATED}, - * {@link Operation#UPDATED} and {@link Operation#DELETED}. + * Consists of three types {@link Operation#CREATED}, {@link Operation#UPDATED} and {@link Operation#DELETED}. */ private static enum Operation { - CREATED("created"), UPDATED("updated"), DELETED("deleted"); + CREATED("created"), + UPDATED("updated"), + DELETED("deleted"); private final String value; diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/Notificator.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/Notificator.java index a576eed269..166c473b9c 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/Notificator.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/Notificator.java @@ -12,7 +12,6 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; - import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier; /** @@ -34,7 +33,6 @@ public class Notificator { return listenersByStreamName.keySet(); } - /** * Gets {@link ListenerAdapter} specified by stream name. * @@ -47,8 +45,7 @@ public class Notificator { } /** - * Gets {@link ListenerAdapter} listener specified by - * {@link InstanceIdentifier} path. + * Gets {@link ListenerAdapter} listener specified by {@link InstanceIdentifier} path. * * @param path * Path to data in data repository. @@ -59,8 +56,7 @@ public class Notificator { } /** - * Checks if the listener specified by {@link InstanceIdentifier} path - * exist. + * Checks if the listener specified by {@link InstanceIdentifier} path exist. * * @param path * Path to data in data repository. @@ -71,18 +67,15 @@ public class Notificator { } /** - * Creates new {@link ListenerAdapter} listener from - * {@link InstanceIdentifier} path and stream name. + * Creates new {@link ListenerAdapter} listener from {@link InstanceIdentifier} path and stream name. * * @param path * Path to data in data repository. * @param streamName * The name of the stream. - * @return New {@link ListenerAdapter} listener from - * {@link InstanceIdentifier} path and stream name. + * @return New {@link ListenerAdapter} listener from {@link InstanceIdentifier} path and stream name. */ - public static ListenerAdapter createListener(InstanceIdentifier path, - String streamName) { + public static ListenerAdapter createListener(InstanceIdentifier path, String streamName) { ListenerAdapter listener = new ListenerAdapter(path, streamName); try { lock.lock(); @@ -95,8 +88,7 @@ public class Notificator { } /** - * Looks for listener determined by {@link InstanceIdentifier} path and - * removes it. + * Looks for listener determined by {@link InstanceIdentifier} path and removes it. * * @param path * InstanceIdentifier @@ -107,8 +99,7 @@ public class Notificator { } /** - * Creates String representation of stream name from URI. Removes slash from - * URI in start and end position. + * Creates String representation of stream name from URI. Removes slash from URI in start and end position. * * @param uri * URI for creation stream name. @@ -148,14 +139,12 @@ public class Notificator { } /** - * Checks if listener has at least one subscriber. In case it doesn't have any, delete - * listener. + * Checks if listener has at least one subscriber. In case it doesn't have any, delete listener. * * @param listener * ListenerAdapter */ - public static void removeListenerIfNoSubscriberExists( - ListenerAdapter listener) { + public static void removeListenerIfNoSubscriberExists(ListenerAdapter listener) { if (!listener.hasSubscribers()) { deleteListener(listener); } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServer.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServer.java index 20951b01e2..67ed44f84e 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServer.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServer.java @@ -1,24 +1,21 @@ package org.opendaylight.controller.sal.streams.websockets; +import com.google.common.base.Preconditions; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; - import org.opendaylight.controller.sal.streams.listeners.Notificator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.base.Preconditions; - /** * {@link WebSocketServer} is responsible to start and stop web socket server */ public class WebSocketServer implements Runnable { - private static final Logger logger = LoggerFactory - .getLogger(WebSocketServer.class); + private static final Logger logger = LoggerFactory.getLogger(WebSocketServer.class); public static final String WEBSOCKET_SERVER_CONFIG_PROPERTY = "restconf.websocket.port"; public static final int DEFAULT_PORT = 8181; private EventLoopGroup bossGroup; @@ -32,14 +29,16 @@ public class WebSocketServer implements Runnable { /** * Create instance of {@link WebSocketServer} - * @param port TCP port used for this server + * + * @param port + * TCP port used for this server * @return instance of {@link WebSocketServer} */ public static WebSocketServer createInstance(int port) { - if(singleton != null) { + if (singleton != null) { throw new IllegalStateException("createInstance() has already been called"); } - if(port < 1024) { + if (port < 1024) { throw new IllegalArgumentException("Privileged port (below 1024) is not allowed"); } singleton = new WebSocketServer(port); @@ -55,11 +54,11 @@ public class WebSocketServer implements Runnable { /** * Get instance of {@link WebSocketServer} created by {@link #createInstance(int)} + * * @return instance of {@link WebSocketServer} */ public static WebSocketServer getInstance() { - Preconditions.checkNotNull(singleton, - "createInstance() must be called prior to getInstance()"); + Preconditions.checkNotNull(singleton, "createInstance() must be called prior to getInstance()"); return singleton; } @@ -67,9 +66,8 @@ public class WebSocketServer implements Runnable { * Destroy this already created instance */ public static void destroyInstance() { - if(singleton == null) { - throw new IllegalStateException( - "createInstance() must be called prior to destroyInstance()"); + if (singleton == null) { + throw new IllegalStateException("createInstance() must be called prior to destroyInstance()"); } getInstance().stop(); } @@ -80,8 +78,7 @@ public class WebSocketServer implements Runnable { workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); - b.group(bossGroup, workerGroup) - .channel(NioServerSocketChannel.class) + b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new WebSocketServerInitializer()); Channel ch = b.bind(port).sync().channel(); diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServerHandler.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServerHandler.java index 26e4936d3f..ce12d34e08 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServerHandler.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServerHandler.java @@ -8,6 +8,7 @@ import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN; import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; @@ -25,29 +26,24 @@ import io.netty.handler.codec.http.websocketx.WebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker; import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory; import io.netty.util.CharsetUtil; - import java.io.IOException; - import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter; import org.opendaylight.controller.sal.streams.listeners.Notificator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * {@link WebSocketServerHandler} is implementation of - * {@link SimpleChannelInboundHandler} which allow handle + * {@link WebSocketServerHandler} is implementation of {@link SimpleChannelInboundHandler} which allow handle * {@link FullHttpRequest} and {@link WebSocketFrame} messages. */ public class WebSocketServerHandler extends SimpleChannelInboundHandler { - private static final Logger logger = LoggerFactory - .getLogger(WebSocketServerHandler.class); + private static final Logger logger = LoggerFactory.getLogger(WebSocketServerHandler.class); private WebSocketServerHandshaker handshaker; @Override - protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) - throws Exception { + protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) throws Exception { if (msg instanceof FullHttpRequest) { handleHttpRequest(ctx, (FullHttpRequest) msg); } else if (msg instanceof WebSocketFrame) { @@ -56,27 +52,23 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler } /** - * Checks if HTTP request method is GET and if is possible to decode HTTP - * result of request. + * Checks if HTTP request method is GET and if is possible to decode HTTP result of request. * * @param ctx * ChannelHandlerContext * @param req * FullHttpRequest */ - private void handleHttpRequest(final ChannelHandlerContext ctx, - final FullHttpRequest req) throws Exception { + private void handleHttpRequest(final ChannelHandlerContext ctx, final FullHttpRequest req) throws Exception { // Handle a bad request. if (!req.getDecoderResult().isSuccess()) { - sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, - BAD_REQUEST)); + sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return; } // Allow only GET methods. if (req.getMethod() != GET) { - sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, - FORBIDDEN)); + sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } @@ -86,15 +78,13 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler listener.addSubscriber(ctx.channel()); logger.debug("Subscriber successfully registered."); } else { - logger.error("Listener for stream with name '{}' was not found.", - streamName); - sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, - INTERNAL_SERVER_ERROR)); + logger.error("Listener for stream with name '{}' was not found.", streamName); + sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR)); } // Handshake - WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( - getWebSocketLocation(req), null, false); + WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req), + null, false); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); @@ -114,12 +104,11 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler * @param res * FullHttpResponse */ - private static void sendHttpResponse(final ChannelHandlerContext ctx, - final HttpRequest req, final FullHttpResponse res) { + private static void sendHttpResponse(final ChannelHandlerContext ctx, final HttpRequest req, + final FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.getStatus().code() != 200) { - ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), - CharsetUtil.UTF_8); + ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); setContentLength(res, res.content().readableBytes()); @@ -140,14 +129,10 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler * @param frame * {@link WebSocketFrame} */ - private void handleWebSocketFrame(final ChannelHandlerContext ctx, - final WebSocketFrame frame) throws IOException { + private void handleWebSocketFrame(final ChannelHandlerContext ctx, final WebSocketFrame frame) throws IOException { if (frame instanceof CloseWebSocketFrame) { - handshaker.close(ctx.channel(), - (CloseWebSocketFrame) frame.retain()); - String streamName = Notificator - .createStreamNameFromUri(((CloseWebSocketFrame) frame) - .reasonText()); + handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); + String streamName = Notificator.createStreamNameFromUri(((CloseWebSocketFrame) frame).reasonText()); ListenerAdapter listener = Notificator.getListenerFor(streamName); if (listener != null) { listener.removeSubscriber(ctx.channel()); @@ -156,15 +141,13 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler Notificator.removeListenerIfNoSubscriberExists(listener); return; } else if (frame instanceof PingWebSocketFrame) { - ctx.channel().write( - new PongWebSocketFrame(frame.content().retain())); + ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } } @Override - public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) - throws Exception { + public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception { if (cause instanceof java.nio.channels.ClosedChannelException == false) { // cause.printStackTrace(); } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServerInitializer.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServerInitializer.java index d188a029e7..754f156dde 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServerInitializer.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServerInitializer.java @@ -7,8 +7,8 @@ import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; /** - * {@link WebSocketServerInitializer} is used to setup the - * {@link ChannelPipeline} of a {@link io.netty.channel.Channel}. + * {@link WebSocketServerInitializer} is used to setup the {@link ChannelPipeline} of a {@link io.netty.channel.Channel} + * . */ public class WebSocketServerInitializer extends ChannelInitializer { diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonBasicYangTypesTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonBasicYangTypesTest.java index d978a2f0de..0f059f5024 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonBasicYangTypesTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonBasicYangTypesTest.java @@ -13,13 +13,13 @@ 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; @@ -37,9 +37,6 @@ 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 com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonToken; - public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader { @BeforeClass @@ -48,8 +45,7 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader { } /** - * Test of json output when as input are specified composite node with empty - * data + YANG file + * Test of json output when as input are specified composite node with empty data + YANG file */ @Test @@ -67,8 +63,7 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader { } /** - * Test of json output when as input are specified xml file (no empty - * elements)and YANG file + * Test of json output when as input are specified xml file (no empty elements)and YANG file */ @Test public void xmlAndYangTypesWithJsonReaderTest() { @@ -355,11 +350,8 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader { assertEquals(1, lst11_1.getLfs().size()); assertEquals(1, lst11_1.getConts().size()); assertEquals(1, lst11_1.getLsts().size()); - assertEquals( - lst11_1.getLsts().get("lst111"), - new Lst("lst111").addLstItem(new LstItem().addLf("lf1111", 35)) - .addLstItem(new LstItem().addLf("lf1111", 34)).addLstItem(new LstItem()) - .addLstItem(new LstItem())); + assertEquals(lst11_1.getLsts().get("lst111"), new Lst("lst111").addLstItem(new LstItem().addLf("lf1111", 35)) + .addLstItem(new LstItem().addLf("lf1111", 34)).addLstItem(new LstItem()).addLstItem(new LstItem())); assertEquals(lst11_1.getConts().get("cont111"), new Cont("cont111")); // : lst11_1 @@ -378,8 +370,7 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader { assertEquals(1, lst11_2_cont111.getLsts().size()); assertTrue(lst11_2_cont111.getConts().isEmpty()); - assertEquals(new LfLst("lflst1111").addLf(1024).addLf(4096), - lst11_2_cont111.getLfLsts().get("lflst1111")); + assertEquals(new LfLst("lflst1111").addLf(1024).addLf(4096), lst11_2_cont111.getLfLsts().get("lflst1111")); assertEquals( new Lst("lst1111").addLstItem(new LstItem().addLf("lf1111B", 4)).addLstItem( new LstItem().addLf("lf1111A", "lf1111A str12")), lst11_2_cont111.getLsts().get("lst1111")); @@ -539,90 +530,108 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader { 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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 @@ -630,8 +639,9 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader { 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); + 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(); @@ -639,26 +649,31 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader { // :lst11_2 // lst11_3 - MutableCompositeNode lst11_3 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst11","simple:yang:types","2013-11-5"), cont1, - null, ModifyAction.CREATE, null); + 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); + 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); + 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); + 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); + 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(); diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonChoiceCaseTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonChoiceCaseTest.java index 21590ecb33..0d0ce5cdd3 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonChoiceCaseTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonChoiceCaseTest.java @@ -10,9 +10,7 @@ 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; @@ -29,9 +27,8 @@ public class CnSnJsonChoiceCaseTest extends YangAndXmlAndDataSchemaLoader { } /** - * 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 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 @@ -40,10 +37,9 @@ public class CnSnJsonChoiceCaseTest extends YangAndXmlAndDataSchemaLoader { } /** - * 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 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 @@ -53,8 +49,8 @@ public class CnSnJsonChoiceCaseTest extends YangAndXmlAndDataSchemaLoader { } /** - * Test when second level data are red first, then first and at the end - * third level. Level represents pass through couple choice-case + * Test when second level data are red first, then first and at the end third level. Level represents pass through + * couple choice-case */ @Test @@ -103,8 +99,8 @@ public class CnSnJsonChoiceCaseTest extends YangAndXmlAndDataSchemaLoader { } /** - * Test whether is possible to find data schema for node which is specified - * as dirrect subnode of choice (case without CASE key word) + * 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() { diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonBasicDataTypesTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonBasicDataTypesTest.java index 93d32a1499..4b8b71440a 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonBasicDataTypesTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonBasicDataTypesTest.java @@ -13,10 +13,12 @@ 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.IOException; import java.io.StringReader; import java.util.Map; - import org.junit.BeforeClass; import org.junit.Test; import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider; @@ -27,10 +29,6 @@ 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 com.google.common.collect.Maps; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonToken; - public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader { static abstract class LeafVerifier { @@ -38,15 +36,15 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader Object expectedValue; JsonToken expectedToken; - LeafVerifier( Object expectedValue, JsonToken expectedToken ) { + LeafVerifier(Object expectedValue, JsonToken expectedToken) { this.expectedValue = expectedValue; this.expectedToken = expectedToken; } - abstract Object getActualValue( JsonReader reader ) throws IOException; + abstract Object getActualValue(JsonReader reader) throws IOException; - void verify( JsonReader reader, String keyName ) throws IOException { - assertEquals( "Json value for key " + keyName, expectedValue, getActualValue( reader ) ); + void verify(JsonReader reader, String keyName) throws IOException { + assertEquals("Json value for key " + keyName, expectedValue, getActualValue(reader)); } JsonToken expectedTokenType() { @@ -56,31 +54,29 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader static class BooleanVerifier extends LeafVerifier { - public BooleanVerifier( boolean expected ) { - super( expected, JsonToken.BOOLEAN ); + public BooleanVerifier(boolean expected) { + super(expected, JsonToken.BOOLEAN); } @Override - Object getActualValue( JsonReader reader ) throws IOException { + Object getActualValue(JsonReader reader) throws IOException { return reader.nextBoolean(); } } static class NumberVerifier extends LeafVerifier { - public NumberVerifier( Number expected ) { - super( expected, JsonToken.NUMBER ); + public NumberVerifier(Number expected) { + super(expected, JsonToken.NUMBER); } @Override - Object getActualValue( JsonReader reader ) throws IOException { - if( expectedValue instanceof Double ) { + Object getActualValue(JsonReader reader) throws IOException { + if (expectedValue instanceof Double) { return reader.nextDouble(); - } - else if( expectedValue instanceof Long ) { + } else if (expectedValue instanceof Long) { return reader.nextLong(); - } - else if( expectedValue instanceof Integer ) { + } else if (expectedValue instanceof Integer) { return reader.nextInt(); } @@ -90,12 +86,12 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader static class StringVerifier extends LeafVerifier { - StringVerifier( String expected ) { - super( expected, JsonToken.STRING ); + StringVerifier(String expected) { + super(expected, JsonToken.STRING); } @Override - Object getActualValue( JsonReader reader ) throws IOException { + Object getActualValue(JsonReader reader) throws IOException { return reader.nextString(); } } @@ -103,11 +99,11 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader static class EmptyVerifier extends LeafVerifier { EmptyVerifier() { - super( null, null ); + super(null, null); } @Override - Object getActualValue( JsonReader reader ) throws IOException { + Object getActualValue(JsonReader reader) throws IOException { reader.beginArray(); reader.nextNull(); reader.endArray(); @@ -119,68 +115,68 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader static class ComplexAnyXmlVerifier extends LeafVerifier { ComplexAnyXmlVerifier() { - super( null, JsonToken.BEGIN_OBJECT ); + super(null, JsonToken.BEGIN_OBJECT); } @Override - void verify( JsonReader reader, String keyName ) throws IOException { + void verify(JsonReader reader, String keyName) throws IOException { reader.beginObject(); String innerKey = reader.nextName(); - assertEquals( "Json reader child key for " + keyName, "data", innerKey ); - assertEquals( "Json token type for key " + innerKey, JsonToken.BEGIN_OBJECT, reader.peek() ); + assertEquals("Json reader child key for " + keyName, "data", innerKey); + assertEquals("Json token type for key " + innerKey, JsonToken.BEGIN_OBJECT, reader.peek()); reader.beginObject(); - verifyLeaf( reader, innerKey, "leaf1", "leaf1-value" ); - verifyLeaf( reader, innerKey, "leaf2", "leaf2-value" ); + verifyLeaf(reader, innerKey, "leaf1", "leaf1-value"); + verifyLeaf(reader, innerKey, "leaf2", "leaf2-value"); String nextName = reader.nextName(); - assertEquals( "Json reader child key for " + innerKey, "leaf-list", nextName ); + assertEquals("Json reader child key for " + innerKey, "leaf-list", nextName); reader.beginArray(); - assertEquals( "Json value for key " + nextName, "leaf-list-value1", reader.nextString() ); - assertEquals( "Json value for key " + nextName, "leaf-list-value2", reader.nextString() ); + assertEquals("Json value for key " + nextName, "leaf-list-value1", reader.nextString()); + assertEquals("Json value for key " + nextName, "leaf-list-value2", reader.nextString()); reader.endArray(); nextName = reader.nextName(); - assertEquals( "Json reader child key for " + innerKey, "list", nextName ); + assertEquals("Json reader child key for " + innerKey, "list", nextName); reader.beginArray(); - verifyNestedLists( reader, 1 ); - verifyNestedLists( reader, 3 ); + verifyNestedLists(reader, 1); + verifyNestedLists(reader, 3); reader.endArray(); reader.endObject(); reader.endObject(); } - void verifyNestedLists( JsonReader reader, int leafNum ) throws IOException { + void verifyNestedLists(JsonReader reader, int leafNum) throws IOException { reader.beginObject(); String nextName = reader.nextName(); - assertEquals( "Json reader next name", "nested-list", nextName ); + assertEquals("Json reader next name", "nested-list", nextName); reader.beginArray(); reader.beginObject(); - verifyLeaf( reader, "nested-list", "nested-leaf", "nested-value" + leafNum++ ); + verifyLeaf(reader, "nested-list", "nested-leaf", "nested-value" + leafNum++); reader.endObject(); reader.beginObject(); - verifyLeaf( reader, "nested-list", "nested-leaf", "nested-value" + leafNum ); + verifyLeaf(reader, "nested-list", "nested-leaf", "nested-value" + leafNum); reader.endObject(); reader.endArray(); reader.endObject(); } - void verifyLeaf( JsonReader reader, String parent, String name, String value ) throws IOException { + void verifyLeaf(JsonReader reader, String parent, String name, String value) throws IOException { String nextName = reader.nextName(); - assertEquals( "Json reader child key for " + parent, name, nextName ); - assertEquals( "Json token type for key " + parent, JsonToken.STRING, reader.peek() ); - assertEquals( "Json value for key " + nextName, value, reader.nextString() ); + assertEquals("Json reader child key for " + parent, name, nextName); + assertEquals("Json token type for key " + parent, JsonToken.STRING, reader.peek()); + assertEquals("Json value for key " + nextName, value, reader.nextString()); } @Override - Object getActualValue( JsonReader reader ) throws IOException { + Object getActualValue(JsonReader reader) throws IOException { return null; } } @@ -199,7 +195,7 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader TestUtils.normalizeCompositeNode(compositeNode, modules, "simple-data-types:cont"); String jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(compositeNode, modules, dataSchemaNode, - StructuredDataToJsonProvider.INSTANCE); + StructuredDataToJsonProvider.INSTANCE); assertNotNull(jsonOutput); @@ -236,68 +232,68 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader private void jsonReadContElements(JsonReader jReader) throws IOException { jReader.beginObject(); - Map expectedMap = Maps.newHashMap(); - expectedMap.put( "lfnint8Min", new NumberVerifier( Integer.valueOf( -128 ) ) ); - expectedMap.put( "lfnint8Max", new NumberVerifier( Integer.valueOf( 127 ) ) ); - expectedMap.put( "lfnint16Min", new NumberVerifier( Integer.valueOf( -32768 ) ) ); - expectedMap.put( "lfnint16Max", new NumberVerifier( Integer.valueOf( 32767 ) ) ); - expectedMap.put( "lfnint32Min", new NumberVerifier( Integer.valueOf( -2147483648 ) ) ); - expectedMap.put( "lfnint32Max", new NumberVerifier( Long.valueOf( 2147483647 ) ) ); - expectedMap.put( "lfnint64Min", new NumberVerifier( Long.valueOf( -9223372036854775808L ) ) ); - expectedMap.put( "lfnint64Max", new NumberVerifier( Long.valueOf( 9223372036854775807L ) ) ); - expectedMap.put( "lfnuint8Max", new NumberVerifier( Integer.valueOf( 255 ) ) ); - expectedMap.put( "lfnuint16Max", new NumberVerifier( Integer.valueOf( 65535 ) ) ); - expectedMap.put( "lfnuint32Max", new NumberVerifier( Long.valueOf( 4294967295L ) ) ); - expectedMap.put( "lfstr", new StringVerifier( "lfstr" ) ); - expectedMap.put( "lfstr1", new StringVerifier( "" ) ); - expectedMap.put( "lfbool1", new BooleanVerifier( true ) ); - expectedMap.put( "lfbool2", new BooleanVerifier( false ) ); - expectedMap.put( "lfbool3", new BooleanVerifier( false ) ); - expectedMap.put( "lfdecimal1", new NumberVerifier( new Double( 43.32 ) ) ); - expectedMap.put( "lfdecimal2", new NumberVerifier( new Double( -0.43 ) ) ); - expectedMap.put( "lfdecimal3", new NumberVerifier( new Double( 43 ) ) ); - expectedMap.put( "lfdecimal4", new NumberVerifier( new Double( 43E3 ) ) ); - expectedMap.put( "lfdecimal6", new NumberVerifier( new Double( 33.12345 ) ) ); - expectedMap.put( "lfenum", new StringVerifier( "enum3" ) ); - expectedMap.put( "lfbits", new StringVerifier( "bit3 bit2" ) ); - expectedMap.put( "lfbinary", new StringVerifier( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" ) ); - expectedMap.put( "lfunion1", new StringVerifier( "324" ) ); - expectedMap.put( "lfunion2", new StringVerifier( "33.3" ) ); - expectedMap.put( "lfunion3", new StringVerifier( "55" ) ); - expectedMap.put( "lfunion4", new StringVerifier( "true" ) ); - expectedMap.put( "lfunion5", new StringVerifier( "true" ) ); - expectedMap.put( "lfunion6", new StringVerifier( "10" ) ); - expectedMap.put( "lfunion7", new StringVerifier( "" ) ); - expectedMap.put( "lfunion8", new StringVerifier( "" ) ); - expectedMap.put( "lfunion9", new StringVerifier( "" ) ); - expectedMap.put( "lfunion10", new StringVerifier( "bt1" ) ); - expectedMap.put( "lfunion11", new StringVerifier( "33" ) ); - expectedMap.put( "lfunion12", new StringVerifier( "false" ) ); - expectedMap.put( "lfunion13", new StringVerifier( "b1" ) ); - expectedMap.put( "lfunion14", new StringVerifier( "zero" ) ); - expectedMap.put( "lfempty", new EmptyVerifier() ); - expectedMap.put( "identityref1", new StringVerifier( "simple-data-types:iden" ) ); - expectedMap.put( "complex-any", new ComplexAnyXmlVerifier() ); - expectedMap.put( "simple-any", new StringVerifier( "simple" ) ); - expectedMap.put( "empty-any", new StringVerifier( "" ) ); + Map expectedMap = Maps.newHashMap(); + expectedMap.put("lfnint8Min", new NumberVerifier(Integer.valueOf(-128))); + expectedMap.put("lfnint8Max", new NumberVerifier(Integer.valueOf(127))); + expectedMap.put("lfnint16Min", new NumberVerifier(Integer.valueOf(-32768))); + expectedMap.put("lfnint16Max", new NumberVerifier(Integer.valueOf(32767))); + expectedMap.put("lfnint32Min", new NumberVerifier(Integer.valueOf(-2147483648))); + expectedMap.put("lfnint32Max", new NumberVerifier(Long.valueOf(2147483647))); + expectedMap.put("lfnint64Min", new NumberVerifier(Long.valueOf(-9223372036854775808L))); + expectedMap.put("lfnint64Max", new NumberVerifier(Long.valueOf(9223372036854775807L))); + expectedMap.put("lfnuint8Max", new NumberVerifier(Integer.valueOf(255))); + expectedMap.put("lfnuint16Max", new NumberVerifier(Integer.valueOf(65535))); + expectedMap.put("lfnuint32Max", new NumberVerifier(Long.valueOf(4294967295L))); + expectedMap.put("lfstr", new StringVerifier("lfstr")); + expectedMap.put("lfstr1", new StringVerifier("")); + expectedMap.put("lfbool1", new BooleanVerifier(true)); + expectedMap.put("lfbool2", new BooleanVerifier(false)); + expectedMap.put("lfbool3", new BooleanVerifier(false)); + expectedMap.put("lfdecimal1", new NumberVerifier(new Double(43.32))); + expectedMap.put("lfdecimal2", new NumberVerifier(new Double(-0.43))); + expectedMap.put("lfdecimal3", new NumberVerifier(new Double(43))); + expectedMap.put("lfdecimal4", new NumberVerifier(new Double(43E3))); + expectedMap.put("lfdecimal6", new NumberVerifier(new Double(33.12345))); + expectedMap.put("lfenum", new StringVerifier("enum3")); + expectedMap.put("lfbits", new StringVerifier("bit3 bit2")); + expectedMap.put("lfbinary", new StringVerifier("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")); + expectedMap.put("lfunion1", new StringVerifier("324")); + expectedMap.put("lfunion2", new StringVerifier("33.3")); + expectedMap.put("lfunion3", new StringVerifier("55")); + expectedMap.put("lfunion4", new StringVerifier("true")); + expectedMap.put("lfunion5", new StringVerifier("true")); + expectedMap.put("lfunion6", new StringVerifier("10")); + expectedMap.put("lfunion7", new StringVerifier("")); + expectedMap.put("lfunion8", new StringVerifier("")); + expectedMap.put("lfunion9", new StringVerifier("")); + expectedMap.put("lfunion10", new StringVerifier("bt1")); + expectedMap.put("lfunion11", new StringVerifier("33")); + expectedMap.put("lfunion12", new StringVerifier("false")); + expectedMap.put("lfunion13", new StringVerifier("b1")); + expectedMap.put("lfunion14", new StringVerifier("zero")); + expectedMap.put("lfempty", new EmptyVerifier()); + expectedMap.put("identityref1", new StringVerifier("simple-data-types:iden")); + expectedMap.put("complex-any", new ComplexAnyXmlVerifier()); + expectedMap.put("simple-any", new StringVerifier("simple")); + expectedMap.put("empty-any", new StringVerifier("")); while (jReader.hasNext()) { String keyName = jReader.nextName(); JsonToken peek = jReader.peek(); - LeafVerifier verifier = expectedMap.remove( keyName ); - assertNotNull( "Found unexpected leaf: " + keyName , verifier ); + LeafVerifier verifier = expectedMap.remove(keyName); + assertNotNull("Found unexpected leaf: " + keyName, verifier); JsonToken expToken = verifier.expectedTokenType(); - if( expToken != null ) { - assertEquals( "Json token type for key " + keyName, expToken, peek ); + if (expToken != null) { + assertEquals("Json token type for key " + keyName, expToken, peek); } - verifier.verify( jReader, keyName ); + verifier.verify(jReader, keyName); } - if( !expectedMap.isEmpty() ) { - fail( "Missing leaf nodes in Json output: " +expectedMap.keySet() ); + if (!expectedMap.isEmpty()) { + fail("Missing leaf nodes in Json output: " + expectedMap.keySet()); } jReader.endObject(); @@ -307,15 +303,13 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader public void testBadData() throws Exception { try { - CompositeNode compositeNode = TestUtils.readInputToCnSn( - "/cnsn-to-json/simple-data-types/xml/bad-data.xml", - XmlToCompositeNodeProvider.INSTANCE); + CompositeNode compositeNode = TestUtils.readInputToCnSn("/cnsn-to-json/simple-data-types/xml/bad-data.xml", + XmlToCompositeNodeProvider.INSTANCE); TestUtils.normalizeCompositeNode(compositeNode, modules, "simple-data-types:cont"); - fail( "Expected RestconfDocumentedException" ); - } - catch( RestconfDocumentedException e ) { - assertEquals( "getErrorTag", ErrorTag.INVALID_VALUE, e.getErrors().get( 0 ).getErrorTag() ); + fail("Expected RestconfDocumentedException"); + } catch (RestconfDocumentedException e) { + assertEquals("getErrorTag", ErrorTag.INVALID_VALUE, e.getErrors().get(0).getErrorTag()); } } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonIdentityrefTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonIdentityrefTest.java index fdd3aa6684..506ca847a9 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonIdentityrefTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonIdentityrefTest.java @@ -13,9 +13,7 @@ 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; @@ -74,14 +72,16 @@ public class CnSnToJsonIdentityrefTest extends YangAndXmlAndDataSchemaLoader { } 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); + 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); + MutableSimpleNode lf1 = NodeFactory + .createMutableSimpleNode(TestUtils.buildQName("lf1", "identityref:module", "2013-12-2"), cont1, value, + ModifyAction.CREATE, null); cont1.getValue().add(lf1); cont1.init(); diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonIncorrectTopLevelTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonIncorrectTopLevelTest.java index 050a9925ff..50c834b1ff 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonIncorrectTopLevelTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonIncorrectTopLevelTest.java @@ -12,10 +12,8 @@ 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.Test; import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider; @@ -147,7 +145,8 @@ public class CnSnToJsonIncorrectTopLevelTest extends YangAndXmlAndDataSchemaLoad @Test public void incorrectTopLevelElementTest() { - CompositeNode compositeNode = TestUtils.readInputToCnSn("/cnsn-to-json/simple-data-types/xml/data.xml", XmlToCompositeNodeProvider.INSTANCE); + CompositeNode compositeNode = TestUtils.readInputToCnSn("/cnsn-to-json/simple-data-types/xml/data.xml", + XmlToCompositeNodeProvider.INSTANCE); DataSchemaNode incorrectDataSchema = null; incorrectDataSchema = new IncorrectDataSchema(); diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonLeafrefType.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonLeafrefType.java index 21a46a6cc3..6e41dcb577 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonLeafrefType.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonLeafrefType.java @@ -13,9 +13,7 @@ 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; @@ -50,8 +48,8 @@ public class CnSnToJsonLeafrefType extends YangAndXmlAndDataSchemaLoader { } /** - * Tests case when reference to not existing element is present. In this - * case value from single node is printed as string. + * 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() { @@ -60,8 +58,7 @@ public class CnSnToJsonLeafrefType extends YangAndXmlAndDataSchemaLoader { } /** - * Tests case when non leaf element is referenced. In this case value from - * single node is printed as string. + * Tests case when non leaf element is referenced. In this case value from single node is printed as string. */ @Test public void leafrefToNotLeafTest() { diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonNotExistingLeafTypeTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonNotExistingLeafTypeTest.java index 3f89c97367..3ca29c8d65 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonNotExistingLeafTypeTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonNotExistingLeafTypeTest.java @@ -46,14 +46,12 @@ public class CnSnToJsonNotExistingLeafTypeTest extends YangAndXmlAndDataSchemaLo @Test public void incorrectTopLevelElementTest() throws WebApplicationException, IOException { String jsonOutput = null; - jsonOutput = TestUtils - .writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(), - Collections.emptySet(), prepareDataSchemaNode(), - StructuredDataToJsonProvider.INSTANCE); + jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(), + Collections. emptySet(), prepareDataSchemaNode(), StructuredDataToJsonProvider.INSTANCE); assertNotNull(jsonOutput); -// pattern for e.g. > "lf1" : "" < or >"lf1":""< - assertTrue(containsStringData(jsonOutput, "\"lf1\"",":","\"\"")); + // pattern for e.g. > "lf1" : "" < or >"lf1":""< + assertTrue(containsStringData(jsonOutput, "\"lf1\"", ":", "\"\"")); } private CompositeNode prepareCompositeNode() { diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonWithAugmentTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonWithAugmentTest.java index 3d25955b3c..eb6a5b9e00 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonWithAugmentTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonWithAugmentTest.java @@ -29,8 +29,7 @@ public class CnSnToJsonWithAugmentTest extends YangAndXmlAndDataSchemaLoader { } /** - * Test of json output when as input are specified composite node with empty - * data + YANG file + * Test of json output when as input are specified composite node with empty data + YANG file */ @Test public void augmentedElementsToJson() { @@ -46,12 +45,12 @@ public class CnSnToJsonWithAugmentTest extends YangAndXmlAndDataSchemaLoader { } 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\"",":", "\\[")); + 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\"", ":", "\\[")); } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonWithDataFromSeveralModulesTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonWithDataFromSeveralModulesTest.java index 052bb1a2be..a84fc79b86 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonWithDataFromSeveralModulesTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonWithDataFromSeveralModulesTest.java @@ -13,9 +13,7 @@ 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; diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnInstanceIdentifierToXmlTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnInstanceIdentifierToXmlTest.java index 086e648097..3ab880fe7e 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnInstanceIdentifierToXmlTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnInstanceIdentifierToXmlTest.java @@ -12,9 +12,7 @@ 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; @@ -26,9 +24,8 @@ import org.opendaylight.yangtools.yang.data.api.CompositeNode; /** * - * CnSn = Composite node and Simple node data structure Class contains test of - * serializing simple nodes data values according data types from YANG schema to - * XML file + * CnSn = Composite node and Simple node data structure Class contains test of serializing simple nodes data values + * according data types from YANG schema to XML file * */ public class CnSnInstanceIdentifierToXmlTest extends YangAndXmlAndDataSchemaLoader { @@ -40,7 +37,7 @@ public class CnSnInstanceIdentifierToXmlTest extends YangAndXmlAndDataSchemaLoad @Test public void snAsYangInstanceIdentifier() throws WebApplicationException, IOException, URISyntaxException { - CompositeNode cnSnData = prepareCnStructForYangData( ); + CompositeNode cnSnData = prepareCnStructForYangData(); String xmlOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(cnSnData, modules, dataSchemaNode, StructuredDataToXmlProvider.INSTANCE); assertNotNull(xmlOutput); diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlNotExistingLeafTypeTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlNotExistingLeafTypeTest.java index 2ada6e13e9..800e2d3b48 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlNotExistingLeafTypeTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlNotExistingLeafTypeTest.java @@ -11,9 +11,7 @@ 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; @@ -41,8 +39,8 @@ public class CnSnToXmlNotExistingLeafTypeTest { boolean nullPointerExceptionRaised = false; try { - TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(), - Collections.emptySet(), prepareDataSchemaNode(), StructuredDataToXmlProvider.INSTANCE); + TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(), Collections. emptySet(), + prepareDataSchemaNode(), StructuredDataToXmlProvider.INSTANCE); } catch (WebApplicationException | IOException e) { LOG.error("WebApplicationException or IOException was raised"); } catch (NullPointerException e) { diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlTest.java index 30dc1161bf..3d5fee3ab8 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlTest.java @@ -12,12 +12,12 @@ 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; @@ -50,14 +50,10 @@ import org.opendaylight.yangtools.yang.model.util.Uint64; import org.opendaylight.yangtools.yang.model.util.Uint8; import org.opendaylight.yangtools.yang.model.util.UnionType; -import com.google.common.base.Optional; -import com.google.common.collect.Lists; - /** * - * CnSn = Composite node and Simple node data structure Class contains test of - * serializing simple nodes data values according data types from YANG schema to - * XML file + * CnSn = Composite node and Simple node data structure Class contains test of serializing simple nodes data values + * according data types from YANG schema to XML file * */ public class CnSnToXmlTest extends YangAndXmlAndDataSchemaLoader { @@ -87,76 +83,77 @@ public class CnSnToXmlTest extends YangAndXmlAndDataSchemaLoader { serializeToXml(prepareLeafrefData(), "true", "true"); } - @Test public void snAsYangStringToXmlTest() { serializeToXml( - prepareCnStructForYangData(TypeDefinitionAwareCodec.from(StringType.getInstance()).deserialize("lfStr value"), - "lfStr"), "lfStr value"); + prepareCnStructForYangData( + TypeDefinitionAwareCodec.from(StringType.getInstance()).deserialize("lfStr value"), "lfStr"), + "lfStr value"); } @Test public void snAsYangInt8ToXmlTest() { String elName = "lfInt8"; serializeToXml( - prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int8.getInstance()).deserialize("14"), elName), "<" - + elName + ">14"); + prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int8.getInstance()).deserialize("14"), elName), + "<" + elName + ">14"); } @Test public void snAsYangInt16ToXmlTest() { String elName = "lfInt16"; serializeToXml( - prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int16.getInstance()).deserialize("3000"), elName), - "<" + elName + ">3000"); + prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int16.getInstance()).deserialize("3000"), + elName), "<" + elName + ">3000"); } @Test public void snAsYangInt32ToXmlTest() { String elName = "lfInt32"; serializeToXml( - prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int32.getInstance()).deserialize("201234"), elName), - "<" + elName + ">201234"); + prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int32.getInstance()).deserialize("201234"), + elName), "<" + elName + ">201234"); } @Test public void snAsYangInt64ToXmlTest() { String elName = "lfInt64"; serializeToXml( - prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int64.getInstance()).deserialize("5123456789"), - elName), "<" + elName + ">5123456789"); + prepareCnStructForYangData( + TypeDefinitionAwareCodec.from(Int64.getInstance()).deserialize("5123456789"), elName), "<" + + elName + ">5123456789"); } @Test public void snAsYangUint8ToXmlTest() { String elName = "lfUint8"; serializeToXml( - prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint8.getInstance()).deserialize("200"), elName), - "<" + elName + ">200"); + prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint8.getInstance()).deserialize("200"), + elName), "<" + elName + ">200"); } @Test public void snAsYangUint16ToXmlTest() { String elName = "lfUint16"; serializeToXml( - prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint16.getInstance()).deserialize("4000"), elName), - "<" + elName + ">4000"); + prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint16.getInstance()).deserialize("4000"), + elName), "<" + elName + ">4000"); } @Test public void snAsYangUint32ToXmlTest() { String elName = "lfUint32"; serializeToXml( - prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint32.getInstance()).deserialize("4123456789"), - elName), "<" + elName + ">4123456789"); + prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint32.getInstance()) + .deserialize("4123456789"), elName), "<" + elName + ">4123456789"); } @Test public void snAsYangUint64ToXmlTest() { String elName = "lfUint64"; serializeToXml( - prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint64.getInstance()).deserialize("5123456789"), - elName), "<" + elName + ">5123456789"); + prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint64.getInstance()) + .deserialize("5123456789"), elName), "<" + elName + ">5123456789"); } @Test @@ -164,92 +161,87 @@ public class CnSnToXmlTest extends YangAndXmlAndDataSchemaLoader { String elName = "lfBinary"; serializeToXml( prepareCnStructForYangData( - TypeDefinitionAwareCodec.from(BinaryType.getInstance()) - .deserialize("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567"), - elName), "<" + elName + ">ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567"); + TypeDefinitionAwareCodec.from(BinaryType.getInstance()).deserialize( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567"), elName), "<" + elName + + ">ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567"); } @Test public void snAsYangBitsToXmlTest() { - BitsTypeDefinition.Bit mockBit1 = mock( BitsTypeDefinition.Bit.class ); - when( mockBit1.getName() ).thenReturn( "one" ); - BitsTypeDefinition.Bit mockBit2 = mock( BitsTypeDefinition.Bit.class ); - when( mockBit2.getName() ).thenReturn( "two" ); - List bitList = Lists.newArrayList( mockBit1, mockBit2 ); + BitsTypeDefinition.Bit mockBit1 = mock(BitsTypeDefinition.Bit.class); + when(mockBit1.getName()).thenReturn("one"); + BitsTypeDefinition.Bit mockBit2 = mock(BitsTypeDefinition.Bit.class); + when(mockBit2.getName()).thenReturn("two"); + List bitList = Lists.newArrayList(mockBit1, mockBit2); String elName = "lfBits"; serializeToXml( - prepareCnStructForYangData(TypeDefinitionAwareCodec.from( - BitsType.create( mock( SchemaPath.class ), bitList ) ) - .deserialize("one two"), elName), - "<" + elName + ">one two", "<" + elName + ">two one"); + prepareCnStructForYangData( + TypeDefinitionAwareCodec.from(BitsType.create(mock(SchemaPath.class), bitList)).deserialize( + "one two"), elName), "<" + elName + ">one two", "<" + elName + + ">two one"); } @Test public void snAsYangEnumerationToXmlTest() { - EnumTypeDefinition.EnumPair mockEnum = mock( EnumTypeDefinition.EnumPair.class ); - when( mockEnum.getName() ).thenReturn( "enum2" ); - List enumList = Lists.newArrayList( mockEnum ); + EnumTypeDefinition.EnumPair mockEnum = mock(EnumTypeDefinition.EnumPair.class); + when(mockEnum.getName()).thenReturn("enum2"); + List enumList = Lists.newArrayList(mockEnum); String elName = "lfEnumeration"; serializeToXml( - prepareCnStructForYangData(TypeDefinitionAwareCodec.from( - EnumerationType.create( mock( SchemaPath.class ), enumList, - Optional.absent() ) ) - .deserialize("enum2"), - elName), "<" + elName + ">enum2"); + prepareCnStructForYangData( + TypeDefinitionAwareCodec.from( + EnumerationType.create(mock(SchemaPath.class), enumList, + Optional. absent())).deserialize("enum2"), elName), + "<" + elName + ">enum2"); } @Test public void snAsYangEmptyToXmlTest() { String elName = "lfEmpty"; serializeToXml( - prepareCnStructForYangData(TypeDefinitionAwareCodec.from(EmptyType.getInstance()).deserialize(null), elName), "<" - + elName + "/>"); + prepareCnStructForYangData(TypeDefinitionAwareCodec.from(EmptyType.getInstance()).deserialize(null), + elName), "<" + elName + "/>"); } @Test public void snAsYangBooleanToXmlTest() { String elName = "lfBoolean"; serializeToXml( - prepareCnStructForYangData(TypeDefinitionAwareCodec.from(BooleanType.getInstance()).deserialize("str"), elName), - "<" + elName + ">false"); + prepareCnStructForYangData(TypeDefinitionAwareCodec.from(BooleanType.getInstance()).deserialize("str"), + elName), "<" + elName + ">false"); serializeToXml( - prepareCnStructForYangData(TypeDefinitionAwareCodec.from(BooleanType.getInstance()).deserialize("true"), elName), - "<" + elName + ">true"); + prepareCnStructForYangData( + TypeDefinitionAwareCodec.from(BooleanType.getInstance()).deserialize("true"), elName), "<" + + elName + ">true"); } @Test public void snAsYangUnionToXmlTest() { - BitsTypeDefinition.Bit mockBit1 = mock( BitsTypeDefinition.Bit.class ); - when( mockBit1.getName() ).thenReturn( "first" ); - BitsTypeDefinition.Bit mockBit2 = mock( BitsTypeDefinition.Bit.class ); - when( mockBit2.getName() ).thenReturn( "second" ); - List bitList = Lists.newArrayList( mockBit1, mockBit2 ); + BitsTypeDefinition.Bit mockBit1 = mock(BitsTypeDefinition.Bit.class); + when(mockBit1.getName()).thenReturn("first"); + BitsTypeDefinition.Bit mockBit2 = mock(BitsTypeDefinition.Bit.class); + when(mockBit2.getName()).thenReturn("second"); + List bitList = Lists.newArrayList(mockBit1, mockBit2); - List> types = Lists.>newArrayList( - Int8.getInstance(), - BitsType.create( mock( SchemaPath.class ) , bitList ), - BooleanType.getInstance() ); - UnionType unionType = UnionType.create( types ); + List> types = Lists.> newArrayList(Int8.getInstance(), + BitsType.create(mock(SchemaPath.class), bitList), BooleanType.getInstance()); + UnionType unionType = UnionType.create(types); String elName = "lfUnion"; String int8 = "15"; - serializeToXml( - prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(int8), elName), "<" - + elName + ">15"); + serializeToXml(prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(int8), elName), + "<" + elName + ">15"); String bits = "first second"; - serializeToXml( - prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(bits), elName), "<" - + elName + ">first second"); + serializeToXml(prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(bits), elName), + "<" + elName + ">first second"); String bool = "str"; - serializeToXml( - prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(bool), elName), "<" - + elName + ">str"); + serializeToXml(prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(bool), elName), + "<" + elName + ">str"); } private void serializeToXml(final CompositeNode compositeNode, final String... xmlRepresentation) diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlWithChoiceTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlWithChoiceTest.java index ac7fe20818..8e5449029c 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlWithChoiceTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlWithChoiceTest.java @@ -10,9 +10,7 @@ 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; @@ -26,9 +24,8 @@ import org.opendaylight.yangtools.yang.data.impl.NodeFactory; /** * - * CnSn = Composite node and Simple node data structure Class contains test of - * serializing simple nodes data values according data types from YANG schema to - * XML file + * CnSn = Composite node and Simple node data structure Class contains test of serializing simple nodes data values + * according data types from YANG schema to XML file * */ public class CnSnToXmlWithChoiceTest extends YangAndXmlAndDataSchemaLoader { diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlWithDataFromSeveralModulesTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlWithDataFromSeveralModulesTest.java index f8d04c157f..1e366dcaec 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlWithDataFromSeveralModulesTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlWithDataFromSeveralModulesTest.java @@ -14,9 +14,7 @@ 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; @@ -31,7 +29,7 @@ public class CnSnToXmlWithDataFromSeveralModulesTest extends YangAndXmlAndDataSc @BeforeClass public static void initialize() { - dataLoad("/xml-to-cnsn/data-of-several-modules/yang",2,"module1","cont_m1"); + dataLoad("/xml-to-cnsn/data-of-several-modules/yang", 2, "module1", "cont_m1"); } @Test @@ -40,19 +38,19 @@ public class CnSnToXmlWithDataFromSeveralModulesTest extends YangAndXmlAndDataSc String output = TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCnSn(), modules, schemaContext, StructuredDataToXmlProvider.INSTANCE); -// String output = -// String.format("" + -// "\n" + -// "\n\t" + -// "\n\t\tlf1 m1 value" + -// "\n\t" + -// "\n" + -// "\n" + -// "\n\t" + -// "\n\t\tlf1 m2 value" + -// "\n\t" + -// "\n" + -// "\n"); + // String output = + // String.format("" + + // "\n" + + // "\n\t" + + // "\n\t\tlf1 m1 value" + + // "\n\t" + + // "\n" + + // "\n" + + // "\n\t" + + // "\n\t\tlf1 m2 value" + + // "\n\t" + + // "\n" + + // "\n"); StringBuilder regex = new StringBuilder(); regex.append("^"); @@ -61,7 +59,6 @@ public class CnSnToXmlWithDataFromSeveralModulesTest extends YangAndXmlAndDataSc regex.append(".*xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\""); regex.append(".*>"); - regex.append(".*"); regex.append(".*xmlns=\"module:one\""); regex.append(".*>"); diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonIdentityrefToCnSnTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonIdentityrefToCnSnTest.java index 0c9e95173f..23b040a9a3 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonIdentityrefToCnSnTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonIdentityrefToCnSnTest.java @@ -12,7 +12,6 @@ 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; diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonLeafrefToCnSnTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonLeafrefToCnSnTest.java index 79dd026fd0..913e9f2d70 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonLeafrefToCnSnTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonLeafrefToCnSnTest.java @@ -28,8 +28,7 @@ public class JsonLeafrefToCnSnTest extends YangAndXmlAndDataSchemaLoader { } /** - * JSON values which represents leafref are always loaded to simple node as - * string + * JSON values which represents leafref are always loaded to simple node as string */ @Test public void jsonIdentityrefToCompositeNode() { diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonToCnSnTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonToCnSnTest.java index 47e329cc3e..7b71e42ab8 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonToCnSnTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonToCnSnTest.java @@ -17,7 +17,6 @@ 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; @@ -82,8 +81,8 @@ public class JsonToCnSnTest { } /** - * List contains 4 items and in every item are other elements. It is - * supposed that there should be: lf11, lflst11, cont11, lst11 + * 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() { @@ -116,14 +115,19 @@ public class JsonToCnSnTest { public void incorrectTopLevelElementsTest() { RestconfDocumentedException cause1 = null; try { - TestUtils.readInputToCnSn("/json-to-cnsn/wrong-top-level1.json", true, JsonToCompositeNodeProvider.INSTANCE); + 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.")); + 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 { @@ -133,26 +137,29 @@ public class JsonToCnSnTest { cause2 = e; } assertNotNull(cause2); - assertTrue(cause2.getErrors().get( 0 ).getErrorMessage().contains( - "Json Object should contain one element")); + 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); + .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.")); + 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 + * 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() { @@ -172,7 +179,7 @@ public class JsonToCnSnTest { try { TestUtils.readInputToCnSn("/json-to-cnsn/empty-data1.json", true, JsonToCompositeNodeProvider.INSTANCE); } catch (RestconfDocumentedException e) { - reason = e.getErrors().get( 0 ).getErrorMessage(); + reason = e.getErrors().get(0).getErrorMessage(); } assertTrue(reason.contains("Expected value at line")); @@ -180,17 +187,16 @@ public class JsonToCnSnTest { } @Test - public void testJsonBlankInput() throws Exception{ - InputStream inputStream = new ByteArrayInputStream( "".getBytes() ); - CompositeNode compositeNode = - JsonToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null, inputStream); - assertNull( compositeNode ); + public void testJsonBlankInput() throws Exception { + InputStream inputStream = new ByteArrayInputStream("".getBytes()); + CompositeNode compositeNode = JsonToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null, + inputStream); + assertNull(compositeNode); } /** - * Tests whether namespace stay unchanged if concrete values are - * present in composite or simple node and if the method for update is - * called. + * Tests whether namespace stay unchanged if concrete values are present in composite or simple node and if + * the method for update is called. * */ @Test @@ -284,13 +290,14 @@ public class JsonToCnSnTest { } - private void simpleTest(final String jsonPath, final String yangPath, final String topLevelElementName, final String namespace, - final String moduleName) { + 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) { + private CompositeNode loadAndNormalizeData(final String jsonPath, final String yangPath, + final String topLevelElementName, final String moduleName) { CompositeNode compositeNode = TestUtils.readInputToCnSn(jsonPath, false, JsonToCompositeNodeProvider.INSTANCE); assertNotNull(compositeNode); @@ -395,7 +402,7 @@ public class JsonToCnSnTest { TestUtils.readInputToCnSn("/json-to-cnsn/unsupported-json-format.json", true, JsonToCompositeNodeProvider.INSTANCE); } catch (RestconfDocumentedException e) { - exceptionMessage = e.getErrors().get( 0 ).getErrorMessage(); + exceptionMessage = e.getErrors().get(0).getErrorMessage(); } assertTrue(exceptionMessage.contains("Root element of Json has to be Object")); } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/BrokerFacadeTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/BrokerFacadeTest.java index 19ca812f8e..656427352a 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/BrokerFacadeTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/BrokerFacadeTest.java @@ -7,6 +7,7 @@ */ 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.assertSame; @@ -66,268 +67,252 @@ public class BrokerFacadeTest { BrokerFacade brokerFacade = BrokerFacade.getInstance(); - CompositeNode dataNode = TestUtils.readInputToCnSn( "/parts/ietf-interfaces_interfaces.xml", - XmlToCompositeNodeProvider.INSTANCE ); + CompositeNode dataNode = TestUtils.readInputToCnSn("/parts/ietf-interfaces_interfaces.xml", + XmlToCompositeNodeProvider.INSTANCE); - QName qname = QName.create( "node" ); + QName qname = QName.create("node"); - InstanceIdentifier instanceID = InstanceIdentifier.builder().node( qname ).toInstance(); + InstanceIdentifier instanceID = InstanceIdentifier.builder().node(qname).toInstance(); @Before public void setUp() throws Exception { - MockitoAnnotations.initMocks( this ); + MockitoAnnotations.initMocks(this); - brokerFacade.setDataService( dataBroker ); - brokerFacade.setContext( mockConsumerSession ); + brokerFacade.setDataService(dataBroker); + brokerFacade.setContext(mockConsumerSession); } @Test public void testReadConfigurationData() { - when( dataBroker.readConfigurationData( instanceID ) ).thenReturn( dataNode ); + when(dataBroker.readConfigurationData(instanceID)).thenReturn(dataNode); - CompositeNode actualNode = brokerFacade.readConfigurationData( instanceID ); + CompositeNode actualNode = brokerFacade.readConfigurationData(instanceID); - assertSame( "readConfigurationData", dataNode, actualNode ); + assertSame("readConfigurationData", dataNode, actualNode); } @Test public void testReadConfigurationDataBehindMountPoint() { - when( mockMountInstance.readConfigurationData( instanceID ) ).thenReturn( dataNode ); + when(mockMountInstance.readConfigurationData(instanceID)).thenReturn(dataNode); - CompositeNode actualNode = brokerFacade.readConfigurationDataBehindMountPoint( - mockMountInstance, instanceID ); + CompositeNode actualNode = brokerFacade.readConfigurationDataBehindMountPoint(mockMountInstance, instanceID); - assertSame( "readConfigurationDataBehindMountPoint", dataNode, actualNode ); + assertSame("readConfigurationDataBehindMountPoint", dataNode, actualNode); } @Test public void testReadOperationalData() { - when( dataBroker.readOperationalData( instanceID ) ).thenReturn( dataNode ); + when(dataBroker.readOperationalData(instanceID)).thenReturn(dataNode); - CompositeNode actualNode = brokerFacade.readOperationalData( instanceID ); + CompositeNode actualNode = brokerFacade.readOperationalData(instanceID); - assertSame( "readOperationalData", dataNode, actualNode ); + assertSame("readOperationalData", dataNode, actualNode); } @Test public void testReadOperationalDataBehindMountPoint() { - when( mockMountInstance.readOperationalData( instanceID ) ).thenReturn( dataNode ); + when(mockMountInstance.readOperationalData(instanceID)).thenReturn(dataNode); - CompositeNode actualNode = brokerFacade.readOperationalDataBehindMountPoint( - mockMountInstance, instanceID ); + CompositeNode actualNode = brokerFacade.readOperationalDataBehindMountPoint(mockMountInstance, instanceID); - assertSame( "readOperationalDataBehindMountPoint", dataNode, actualNode ); + assertSame("readOperationalDataBehindMountPoint", dataNode, actualNode); } - @Test(expected=RestconfDocumentedException.class) + @Test(expected = RestconfDocumentedException.class) public void testReadOperationalDataWithNoDataBroker() { - brokerFacade.setDataService( null ); + brokerFacade.setDataService(null); - brokerFacade.readOperationalData( instanceID ); + brokerFacade.readOperationalData(instanceID); } @SuppressWarnings("unchecked") @Test public void testInvokeRpc() throws Exception { - RpcResult expResult = mock( RpcResult.class ); - Future> future = Futures.immediateFuture( expResult ); - when( mockConsumerSession.rpc( qname, dataNode ) ).thenReturn( future ); + RpcResult expResult = mock(RpcResult.class); + Future> future = Futures.immediateFuture(expResult); + when(mockConsumerSession.rpc(qname, dataNode)).thenReturn(future); - Future> actualFuture = brokerFacade.invokeRpc( qname, dataNode ); - assertNotNull( "Future is null", actualFuture ); + Future> actualFuture = brokerFacade.invokeRpc(qname, dataNode); + assertNotNull("Future is null", actualFuture); RpcResult actualResult = actualFuture.get(); - assertSame( "invokeRpc", expResult, actualResult ); + assertSame("invokeRpc", expResult, actualResult); } - @Test(expected=RestconfDocumentedException.class) + @Test(expected = RestconfDocumentedException.class) public void testInvokeRpcWithNoConsumerSession() { - brokerFacade.setContext( null ); + brokerFacade.setContext(null); - brokerFacade.invokeRpc( qname, dataNode ); + brokerFacade.invokeRpc(qname, dataNode); } @Test public void testCommitConfigurationDataPut() { - Future> expFuture = Futures.immediateFuture( null ); + Future> expFuture = Futures.immediateFuture(null); - when( dataBroker.beginTransaction() ).thenReturn( mockTransaction ); - mockTransaction.putConfigurationData( instanceID, dataNode ); - when( mockTransaction.commit() ).thenReturn( expFuture ); + when(dataBroker.beginTransaction()).thenReturn(mockTransaction); + mockTransaction.putConfigurationData(instanceID, dataNode); + when(mockTransaction.commit()).thenReturn(expFuture); - Future> actualFuture = - brokerFacade.commitConfigurationDataPut( instanceID, dataNode ); + Future> actualFuture = brokerFacade.commitConfigurationDataPut(instanceID, + dataNode); - assertSame( "invokeRpc", expFuture, actualFuture ); + assertSame("invokeRpc", expFuture, actualFuture); - InOrder inOrder = inOrder( dataBroker, mockTransaction ); - inOrder.verify( dataBroker ).beginTransaction(); - inOrder.verify( mockTransaction ).putConfigurationData( instanceID, dataNode ); - inOrder.verify( mockTransaction ).commit(); + InOrder inOrder = inOrder(dataBroker, mockTransaction); + inOrder.verify(dataBroker).beginTransaction(); + inOrder.verify(mockTransaction).putConfigurationData(instanceID, dataNode); + inOrder.verify(mockTransaction).commit(); } @Test public void testCommitConfigurationDataPutBehindMountPoint() { - Future> expFuture = Futures.immediateFuture( null ); + Future> expFuture = Futures.immediateFuture(null); - when( mockMountInstance.beginTransaction() ).thenReturn( mockTransaction ); - mockTransaction.putConfigurationData( instanceID, dataNode ); - when( mockTransaction.commit() ).thenReturn( expFuture ); + when(mockMountInstance.beginTransaction()).thenReturn(mockTransaction); + mockTransaction.putConfigurationData(instanceID, dataNode); + when(mockTransaction.commit()).thenReturn(expFuture); - Future> actualFuture = - brokerFacade.commitConfigurationDataPutBehindMountPoint( - mockMountInstance, instanceID, dataNode ); + Future> actualFuture = brokerFacade.commitConfigurationDataPutBehindMountPoint( + mockMountInstance, instanceID, dataNode); - assertSame( "invokeRpc", expFuture, actualFuture ); + assertSame("invokeRpc", expFuture, actualFuture); - InOrder inOrder = inOrder( mockMountInstance, mockTransaction ); - inOrder.verify( mockMountInstance ).beginTransaction(); - inOrder.verify( mockTransaction ).putConfigurationData( instanceID, dataNode ); - inOrder.verify( mockTransaction ).commit(); + InOrder inOrder = inOrder(mockMountInstance, mockTransaction); + inOrder.verify(mockMountInstance).beginTransaction(); + inOrder.verify(mockTransaction).putConfigurationData(instanceID, dataNode); + inOrder.verify(mockTransaction).commit(); } @Test public void testCommitConfigurationDataPost() { - Future> expFuture = Futures.immediateFuture( null ); + Future> expFuture = Futures.immediateFuture(null); - Map nodeMap = - new ImmutableMap.Builder() - .put( instanceID, dataNode ).build(); + Map nodeMap = new ImmutableMap.Builder() + .put(instanceID, dataNode).build(); - when( dataBroker.beginTransaction() ).thenReturn( mockTransaction ); - mockTransaction.putConfigurationData( instanceID, dataNode ); - when( mockTransaction.getCreatedConfigurationData() ).thenReturn( nodeMap ); - when( mockTransaction.commit() ).thenReturn( expFuture ); + when(dataBroker.beginTransaction()).thenReturn(mockTransaction); + mockTransaction.putConfigurationData(instanceID, dataNode); + when(mockTransaction.getCreatedConfigurationData()).thenReturn(nodeMap); + when(mockTransaction.commit()).thenReturn(expFuture); - Future> actualFuture = - brokerFacade.commitConfigurationDataPost( instanceID, dataNode ); + Future> actualFuture = brokerFacade.commitConfigurationDataPost(instanceID, + dataNode); - assertSame( "commitConfigurationDataPut", expFuture, actualFuture ); + assertSame("commitConfigurationDataPut", expFuture, actualFuture); - InOrder inOrder = inOrder( dataBroker, mockTransaction ); - inOrder.verify( dataBroker ).beginTransaction(); - inOrder.verify( mockTransaction ).putConfigurationData( instanceID, dataNode ); - inOrder.verify( mockTransaction ).commit(); + InOrder inOrder = inOrder(dataBroker, mockTransaction); + inOrder.verify(dataBroker).beginTransaction(); + inOrder.verify(mockTransaction).putConfigurationData(instanceID, dataNode); + inOrder.verify(mockTransaction).commit(); } - @Test(expected=RestconfDocumentedException.class) + @Test(expected = RestconfDocumentedException.class) public void testCommitConfigurationDataPostAlreadyExists() { - when( dataBroker.beginTransaction() ).thenReturn( mockTransaction ); - mockTransaction.putConfigurationData( instanceID, dataNode ); - when ( mockTransaction.readConfigurationData( instanceID ) ) - .thenReturn( dataNode ); + when(dataBroker.beginTransaction()).thenReturn(mockTransaction); + mockTransaction.putConfigurationData(instanceID, dataNode); + when(mockTransaction.readConfigurationData(instanceID)).thenReturn(dataNode); try { - brokerFacade.commitConfigurationDataPost( instanceID, dataNode ); - } - catch (RestconfDocumentedException e) { - assertEquals("getErrorTag", - RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get( 0 ).getErrorTag()); + brokerFacade.commitConfigurationDataPost(instanceID, dataNode); + } catch (RestconfDocumentedException e) { + assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag()); throw e; } } @Test public void testCommitConfigurationDataPostBehindMountPoint() { - Future> expFuture = Futures.immediateFuture( null ); + Future> expFuture = Futures.immediateFuture(null); - Map nodeMap = - new ImmutableMap.Builder() - .put( instanceID, dataNode ).build(); + Map nodeMap = new ImmutableMap.Builder() + .put(instanceID, dataNode).build(); - when( mockMountInstance.beginTransaction() ).thenReturn( mockTransaction ); - mockTransaction.putConfigurationData( instanceID, dataNode ); - when( mockTransaction.getCreatedConfigurationData() ).thenReturn( nodeMap ); - when( mockTransaction.commit() ).thenReturn( expFuture ); + when(mockMountInstance.beginTransaction()).thenReturn(mockTransaction); + mockTransaction.putConfigurationData(instanceID, dataNode); + when(mockTransaction.getCreatedConfigurationData()).thenReturn(nodeMap); + when(mockTransaction.commit()).thenReturn(expFuture); - Future> actualFuture = - brokerFacade.commitConfigurationDataPostBehindMountPoint( mockMountInstance, - instanceID, dataNode ); + Future> actualFuture = brokerFacade.commitConfigurationDataPostBehindMountPoint( + mockMountInstance, instanceID, dataNode); - assertSame( "commitConfigurationDataPostBehindMountPoint", expFuture, actualFuture ); + assertSame("commitConfigurationDataPostBehindMountPoint", expFuture, actualFuture); - InOrder inOrder = inOrder( mockMountInstance, mockTransaction ); - inOrder.verify( mockMountInstance ).beginTransaction(); - inOrder.verify( mockTransaction ).putConfigurationData( instanceID, dataNode ); - inOrder.verify( mockTransaction ).commit(); + InOrder inOrder = inOrder(mockMountInstance, mockTransaction); + inOrder.verify(mockMountInstance).beginTransaction(); + inOrder.verify(mockTransaction).putConfigurationData(instanceID, dataNode); + inOrder.verify(mockTransaction).commit(); } - @Test(expected=RestconfDocumentedException.class) + @Test(expected = RestconfDocumentedException.class) public void testCommitConfigurationDataPostBehindMountPointAlreadyExists() { - when( mockMountInstance.beginTransaction() ).thenReturn( mockTransaction ); - mockTransaction.putConfigurationData( instanceID, dataNode ); - when ( mockTransaction.readConfigurationData( instanceID ) ) - .thenReturn( dataNode ); + when(mockMountInstance.beginTransaction()).thenReturn(mockTransaction); + mockTransaction.putConfigurationData(instanceID, dataNode); + when(mockTransaction.readConfigurationData(instanceID)).thenReturn(dataNode); try { - brokerFacade.commitConfigurationDataPostBehindMountPoint( mockMountInstance, - instanceID, dataNode ); - } - catch (RestconfDocumentedException e) { - assertEquals("getErrorTag", - RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get( 0 ).getErrorTag()); + brokerFacade.commitConfigurationDataPostBehindMountPoint(mockMountInstance, instanceID, dataNode); + } catch (RestconfDocumentedException e) { + assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag()); throw e; } } @Test public void testCommitConfigurationDataDelete() { - Future> expFuture = Futures.immediateFuture( null ); + Future> expFuture = Futures.immediateFuture(null); - when( dataBroker.beginTransaction() ).thenReturn( mockTransaction ); + when(dataBroker.beginTransaction()).thenReturn(mockTransaction); when(mockTransaction.readConfigurationData(any(InstanceIdentifier.class))).thenReturn( ImmutableCompositeNode.builder().toInstance()); - mockTransaction.removeConfigurationData( instanceID ); - when( mockTransaction.commit() ).thenReturn( expFuture ); + mockTransaction.removeConfigurationData(instanceID); + when(mockTransaction.commit()).thenReturn(expFuture); - Future> actualFuture = - brokerFacade.commitConfigurationDataDelete( instanceID ); + Future> actualFuture = brokerFacade.commitConfigurationDataDelete(instanceID); - assertSame( "commitConfigurationDataDelete", expFuture, actualFuture ); + assertSame("commitConfigurationDataDelete", expFuture, actualFuture); - InOrder inOrder = inOrder( dataBroker, mockTransaction ); - inOrder.verify( dataBroker ).beginTransaction(); - inOrder.verify( mockTransaction ).removeConfigurationData( instanceID ); - inOrder.verify( mockTransaction ).commit(); + InOrder inOrder = inOrder(dataBroker, mockTransaction); + inOrder.verify(dataBroker).beginTransaction(); + inOrder.verify(mockTransaction).removeConfigurationData(instanceID); + inOrder.verify(mockTransaction).commit(); } @Test public void testCommitConfigurationDataDeleteBehindMountPoint() { - Future> expFuture = Futures.immediateFuture( null ); + Future> expFuture = Futures.immediateFuture(null); - when( mockMountInstance.beginTransaction() ).thenReturn( mockTransaction ); + when(mockMountInstance.beginTransaction()).thenReturn(mockTransaction); when(mockTransaction.readConfigurationData(any(InstanceIdentifier.class))).thenReturn( ImmutableCompositeNode.builder().toInstance()); - mockTransaction.removeConfigurationData( instanceID ); - when( mockTransaction.commit() ).thenReturn( expFuture ); + mockTransaction.removeConfigurationData(instanceID); + when(mockTransaction.commit()).thenReturn(expFuture); - Future> actualFuture = - brokerFacade.commitConfigurationDataDeleteBehindMountPoint( - mockMountInstance, instanceID ); + Future> actualFuture = brokerFacade.commitConfigurationDataDeleteBehindMountPoint( + mockMountInstance, instanceID); - assertSame( "commitConfigurationDataDeleteBehindMountPoint", expFuture, actualFuture ); + assertSame("commitConfigurationDataDeleteBehindMountPoint", expFuture, actualFuture); - InOrder inOrder = inOrder( mockMountInstance, mockTransaction ); - inOrder.verify( mockMountInstance ).beginTransaction(); - inOrder.verify( mockTransaction ).removeConfigurationData( instanceID ); - inOrder.verify( mockTransaction ).commit(); + InOrder inOrder = inOrder(mockMountInstance, mockTransaction); + inOrder.verify(mockMountInstance).beginTransaction(); + inOrder.verify(mockTransaction).removeConfigurationData(instanceID); + inOrder.verify(mockTransaction).commit(); } @SuppressWarnings("unchecked") @Test public void testRegisterToListenDataChanges() { - ListenerAdapter listener = Notificator.createListener( instanceID, "stream" ); + ListenerAdapter listener = Notificator.createListener(instanceID, "stream"); - ListenerRegistration mockRegistration = mock( ListenerRegistration.class ); - when( dataBroker.registerDataChangeListener( instanceID, listener ) ) - .thenReturn( mockRegistration ); + ListenerRegistration mockRegistration = mock(ListenerRegistration.class); + when(dataBroker.registerDataChangeListener(instanceID, listener)).thenReturn(mockRegistration); - brokerFacade.registerToListenDataChanges( listener ); + brokerFacade.registerToListenDataChanges(listener); - verify( dataBroker ).registerDataChangeListener( instanceID, listener ); + verify(dataBroker).registerDataChangeListener(instanceID, listener); - assertEquals( "isListening", true, listener.isListening() ); + assertEquals("isListening", true, listener.isListening()); - brokerFacade.registerToListenDataChanges( listener ); - verifyNoMoreInteractions( dataBroker ); + brokerFacade.registerToListenDataChanges(listener); + verifyNoMoreInteractions(dataBroker); } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/CodecsExceptionsCatchingTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/CodecsExceptionsCatchingTest.java index 307abebdd7..4ff4f70710 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/CodecsExceptionsCatchingTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/CodecsExceptionsCatchingTest.java @@ -3,12 +3,10 @@ package org.opendaylight.controller.sal.restconf.impl.test; import static org.junit.Assert.assertTrue; import java.io.FileNotFoundException; - import javax.ws.rs.client.Entity; import javax.ws.rs.core.Application; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.BeforeClass; @@ -47,7 +45,7 @@ public class CodecsExceptionsCatchingTest extends JerseyTest { resourceConfig = resourceConfig.registerInstances(restConf, StructuredDataToXmlProvider.INSTANCE, StructuredDataToJsonProvider.INSTANCE, XmlToCompositeNodeProvider.INSTANCE, JsonToCompositeNodeProvider.INSTANCE); - resourceConfig.registerClasses( RestconfDocumentedExceptionMapper.class ); + resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class); return resourceConfig; } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyFuture.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyFuture.java index 19a7eff480..8ae8d0bdac 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyFuture.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyFuture.java @@ -34,7 +34,6 @@ public class DummyFuture implements Future> { result = builder.result; } - @Override public boolean cancel(final boolean mayInterruptIfRunning) { return cancel; @@ -56,8 +55,8 @@ public class DummyFuture implements Future> { } @Override - public RpcResult get(final long timeout, final TimeUnit unit) throws InterruptedException, - ExecutionException, TimeoutException { + public RpcResult get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, + TimeoutException { return result; } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyRpcResult.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyRpcResult.java index 16d14842db..3c545c06e9 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyRpcResult.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyRpcResult.java @@ -8,7 +8,6 @@ package org.opendaylight.controller.sal.restconf.impl.test; import java.util.Collection; - import org.opendaylight.yangtools.yang.common.RpcError; import org.opendaylight.yangtools.yang.common.RpcResult; diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyType.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyType.java index d90e9539c8..008fda4e09 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyType.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyType.java @@ -8,7 +8,6 @@ package org.opendaylight.controller.sal.restconf.impl.test; import java.util.List; - import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.model.api.SchemaPath; import org.opendaylight.yangtools.yang.model.api.Status; diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/InvokeRpcMethodTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/InvokeRpcMethodTest.java index b90097bc94..d12bf9e44e 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/InvokeRpcMethodTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/InvokeRpcMethodTest.java @@ -67,17 +67,15 @@ public class InvokeRpcMethodTest { private static ControllerContext controllerContext = null; private static UriInfo uriInfo; - @BeforeClass public static void init() throws FileNotFoundException { - Set allModules = new HashSet( TestUtils - .loadModulesFrom("/full-versions/yangs") ); - allModules.addAll( TestUtils.loadModulesFrom("/invoke-rpc") ); + Set allModules = new HashSet(TestUtils.loadModulesFrom("/full-versions/yangs")); + allModules.addAll(TestUtils.loadModulesFrom("/invoke-rpc")); assertNotNull(allModules); Module module = TestUtils.resolveModule("invoke-rpc-module", allModules); assertNotNull(module); SchemaContext schemaContext = TestUtils.loadSchemaContext(allModules); - controllerContext = spy( ControllerContext.getInstance() ); + controllerContext = spy(ControllerContext.getInstance()); controllerContext.setSchemas(schemaContext); uriInfo = mock(UriInfo.class); MultivaluedMap map = new MultivaluedHashMap<>(); @@ -86,17 +84,15 @@ public class InvokeRpcMethodTest { } @Before - public void initMethod() - { + public void initMethod() { restconfImpl = RestconfImpl.getInstance(); - restconfImpl.setControllerContext( controllerContext ); + restconfImpl.setControllerContext(controllerContext); } /** - * Test method invokeRpc in RestconfImpl class tests if composite node as - * input parameter of method invokeRpc (second argument) is wrapped to - * parent composite node which has QName equals to QName of rpc (resolved - * from string - first argument). + * Test method invokeRpc in RestconfImpl class tests if composite node as input parameter of method invokeRpc + * (second argument) is wrapped to parent composite node which has QName equals to QName of rpc (resolved from + * string - first argument). */ @Test public void invokeRpcMtethodTest() { @@ -115,11 +111,10 @@ public class InvokeRpcMethodTest { CompositeNode payload = preparePayload(); - when(mockedBrokerFacade.invokeRpc(any(QName.class), any(CompositeNode.class))) - .thenReturn( Futures.>immediateFuture( - Rpcs.getRpcResult( true ) ) ); + when(mockedBrokerFacade.invokeRpc(any(QName.class), any(CompositeNode.class))).thenReturn( + Futures.> immediateFuture(Rpcs. getRpcResult(true))); - StructuredData structData = restconf.invokeRpc("invoke-rpc-module:rpc-test", payload,uriInfo); + StructuredData structData = restconf.invokeRpc("invoke-rpc-module:rpc-test", payload, uriInfo); assertTrue(structData == null); } @@ -137,207 +132,203 @@ public class InvokeRpcMethodTest { @Test public void testInvokeRpcWithNoPayloadRpc_FailNoErrors() { - RpcResult rpcResult = Rpcs.getRpcResult( false ); + RpcResult rpcResult = Rpcs. getRpcResult(false); BrokerFacade brokerFacade = mock(BrokerFacade.class); - when( brokerFacade.invokeRpc( - eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")), - any(CompositeNode.class))) - .thenReturn( Futures.>immediateFuture( rpcResult ) ); + when( + brokerFacade.invokeRpc( + eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")), + any(CompositeNode.class))).thenReturn( + Futures.> immediateFuture(rpcResult)); restconfImpl.setBroker(brokerFacade); try { - restconfImpl.invokeRpc("toaster:cancel-toast", "",uriInfo); + restconfImpl.invokeRpc("toaster:cancel-toast", "", uriInfo); fail("Expected an exception to be thrown."); - } - catch (RestconfDocumentedException e) { - verifyRestconfDocumentedException( e, 0, ErrorType.RPC, ErrorTag.OPERATION_FAILED, - Optional.absent(), Optional.absent() ); + } catch (RestconfDocumentedException e) { + verifyRestconfDocumentedException(e, 0, ErrorType.RPC, ErrorTag.OPERATION_FAILED, + Optional. absent(), Optional. absent()); } } - void verifyRestconfDocumentedException( final RestconfDocumentedException e, final int index, - final ErrorType expErrorType, final ErrorTag expErrorTag, - final Optional expErrorMsg, - final Optional expAppTag ) { + void verifyRestconfDocumentedException(final RestconfDocumentedException e, final int index, + final ErrorType expErrorType, final ErrorTag expErrorTag, final Optional expErrorMsg, + final Optional expAppTag) { RestconfError actual = null; try { - actual = e.getErrors().get( index ); - } - catch( ArrayIndexOutOfBoundsException ex ) { - fail( "RestconfError not found at index " + index ); + actual = e.getErrors().get(index); + } catch (ArrayIndexOutOfBoundsException ex) { + fail("RestconfError not found at index " + index); } - assertEquals( "getErrorType", expErrorType, actual.getErrorType() ); - assertEquals( "getErrorTag", expErrorTag, actual.getErrorTag() ); - assertNotNull( "getErrorMessage is null", actual.getErrorMessage() ); + assertEquals("getErrorType", expErrorType, actual.getErrorType()); + assertEquals("getErrorTag", expErrorTag, actual.getErrorTag()); + assertNotNull("getErrorMessage is null", actual.getErrorMessage()); - if( expErrorMsg.isPresent() ) { - assertEquals( "getErrorMessage", expErrorMsg.get(), actual.getErrorMessage() ); + if (expErrorMsg.isPresent()) { + assertEquals("getErrorMessage", expErrorMsg.get(), actual.getErrorMessage()); } - if( expAppTag.isPresent() ) { - assertEquals( "getErrorAppTag", expAppTag.get(), actual.getErrorAppTag() ); + if (expAppTag.isPresent()) { + assertEquals("getErrorAppTag", expAppTag.get(), actual.getErrorAppTag()); } } @Test public void testInvokeRpcWithNoPayloadRpc_FailWithRpcError() { - List rpcErrors = Arrays.asList( - RpcErrors.getRpcError( null, "bogusTag", null, ErrorSeverity.ERROR, "foo", - RpcError.ErrorType.TRANSPORT, null ), - RpcErrors.getRpcError( "app-tag", "in-use", null, ErrorSeverity.WARNING, "bar", - RpcError.ErrorType.RPC, null )); + List rpcErrors = Arrays.asList(RpcErrors.getRpcError(null, "bogusTag", null, ErrorSeverity.ERROR, + "foo", RpcError.ErrorType.TRANSPORT, null), RpcErrors.getRpcError("app-tag", "in-use", null, + ErrorSeverity.WARNING, "bar", RpcError.ErrorType.RPC, null)); - RpcResult rpcResult = Rpcs.getRpcResult( false, rpcErrors ); + RpcResult rpcResult = Rpcs. getRpcResult(false, rpcErrors); BrokerFacade brokerFacade = mock(BrokerFacade.class); - when( brokerFacade.invokeRpc( - eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")), - any(CompositeNode.class))) - .thenReturn( Futures.>immediateFuture( rpcResult ) ); + when( + brokerFacade.invokeRpc( + eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")), + any(CompositeNode.class))).thenReturn( + Futures.> immediateFuture(rpcResult)); restconfImpl.setBroker(brokerFacade); try { - restconfImpl.invokeRpc("toaster:cancel-toast", "",uriInfo); + restconfImpl.invokeRpc("toaster:cancel-toast", "", uriInfo); fail("Expected an exception to be thrown."); - } - catch (RestconfDocumentedException e) { - verifyRestconfDocumentedException( e, 0, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED, - Optional.of( "foo" ), Optional.absent() ); - verifyRestconfDocumentedException( e, 1, ErrorType.RPC, ErrorTag.IN_USE, - Optional.of( "bar" ), Optional.of( "app-tag" ) ); + } catch (RestconfDocumentedException e) { + verifyRestconfDocumentedException(e, 0, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED, Optional.of("foo"), + Optional. absent()); + verifyRestconfDocumentedException(e, 1, ErrorType.RPC, ErrorTag.IN_USE, Optional.of("bar"), + Optional.of("app-tag")); } } @Test public void testInvokeRpcWithNoPayload_Success() { - RpcResult rpcResult = Rpcs.getRpcResult( true ); + RpcResult rpcResult = Rpcs. getRpcResult(true); BrokerFacade brokerFacade = mock(BrokerFacade.class); - when( brokerFacade.invokeRpc( - eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")), - any( CompositeNode.class ))) - .thenReturn( Futures.>immediateFuture( rpcResult ) ); + when( + brokerFacade.invokeRpc( + eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")), + any(CompositeNode.class))).thenReturn( + Futures.> immediateFuture(rpcResult)); restconfImpl.setBroker(brokerFacade); - StructuredData output = restconfImpl.invokeRpc("toaster:cancel-toast", - "",uriInfo); + StructuredData output = restconfImpl.invokeRpc("toaster:cancel-toast", "", uriInfo); assertEquals(null, output); - //additional validation in the fact that the restconfImpl does not throw an exception. + // additional validation in the fact that the restconfImpl does not + // throw an exception. } @Test public void testInvokeRpcMethodExpectingNoPayloadButProvidePayload() { try { - restconfImpl.invokeRpc("toaster:cancel-toast", " a payload ",uriInfo); + restconfImpl.invokeRpc("toaster:cancel-toast", " a payload ", uriInfo); fail("Expected an exception"); } catch (RestconfDocumentedException e) { - verifyRestconfDocumentedException( e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, - Optional.absent(), Optional.absent() ); + verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, + Optional. absent(), Optional. absent()); } } @Test public void testInvokeRpcMethodWithBadMethodName() { try { - restconfImpl.invokeRpc("toaster:bad-method", "",uriInfo); + restconfImpl.invokeRpc("toaster:bad-method", "", uriInfo); fail("Expected an exception"); - } - catch (RestconfDocumentedException e) { - verifyRestconfDocumentedException( e, 0, ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT, - Optional.absent(), Optional.absent() ); + } catch (RestconfDocumentedException e) { + verifyRestconfDocumentedException(e, 0, ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT, + Optional. absent(), Optional. absent()); } } @Test public void testInvokeRpcMethodWithInput() { - RpcResult rpcResult = Rpcs.getRpcResult( true ); + RpcResult rpcResult = Rpcs. getRpcResult(true); CompositeNode payload = mock(CompositeNode.class); BrokerFacade brokerFacade = mock(BrokerFacade.class); - when( brokerFacade.invokeRpc( - eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)make-toast")), - any(CompositeNode.class))) - .thenReturn( Futures.>immediateFuture( rpcResult ) ); + when( + brokerFacade.invokeRpc( + eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)make-toast")), + any(CompositeNode.class))).thenReturn( + Futures.> immediateFuture(rpcResult)); restconfImpl.setBroker(brokerFacade); - StructuredData output = restconfImpl.invokeRpc("toaster:make-toast", - payload,uriInfo); + StructuredData output = restconfImpl.invokeRpc("toaster:make-toast", payload, uriInfo); assertEquals(null, output); - //additional validation in the fact that the restconfImpl does not throw an exception. + // additional validation in the fact that the restconfImpl does not + // throw an exception. } @Test public void testThrowExceptionWhenSlashInModuleName() { try { - restconfImpl.invokeRpc("toaster/slash", "",uriInfo); + restconfImpl.invokeRpc("toaster/slash", "", uriInfo); fail("Expected an exception."); - } - catch (RestconfDocumentedException e) { - verifyRestconfDocumentedException( e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, - Optional.absent(), Optional.absent() ); + } catch (RestconfDocumentedException e) { + verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, + Optional. absent(), Optional. absent()); } } @Test public void testInvokeRpcWithNoPayloadWithOutput_Success() { - CompositeNode compositeNode = mock( CompositeNode.class ); - RpcResult rpcResult = Rpcs.getRpcResult( true, compositeNode, - Collections.emptyList() ); + CompositeNode compositeNode = mock(CompositeNode.class); + RpcResult rpcResult = Rpcs. getRpcResult(true, compositeNode, + Collections. emptyList()); BrokerFacade brokerFacade = mock(BrokerFacade.class); - when( brokerFacade.invokeRpc( + when( + brokerFacade.invokeRpc( eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)testOutput")), - any( CompositeNode.class ))) - .thenReturn( Futures.>immediateFuture( rpcResult ) ); + any(CompositeNode.class))).thenReturn( + Futures.> immediateFuture(rpcResult)); restconfImpl.setBroker(brokerFacade); - StructuredData output = restconfImpl.invokeRpc("toaster:testOutput", "",uriInfo); - assertNotNull( output ); - assertSame( compositeNode, output.getData() ); - assertNotNull( output.getSchema() ); + StructuredData output = restconfImpl.invokeRpc("toaster:testOutput", "", uriInfo); + assertNotNull(output); + assertSame(compositeNode, output.getData()); + assertNotNull(output.getSchema()); } @Test - public void testMountedRpcCallNoPayload_Success() throws Exception - { - RpcResult rpcResult = Rpcs.getRpcResult( true ); + public void testMountedRpcCallNoPayload_Success() throws Exception { + RpcResult rpcResult = Rpcs. getRpcResult(true); - ListenableFuture> mockListener = mock( ListenableFuture.class ); - when( mockListener.get() ).thenReturn( rpcResult ); + ListenableFuture> mockListener = mock(ListenableFuture.class); + when(mockListener.get()).thenReturn(rpcResult); - QName cancelToastQName = QName.create( "namespace", "2014-05-28", "cancelToast" ); + QName cancelToastQName = QName.create("namespace", "2014-05-28", "cancelToast"); - RpcDefinition mockRpc = mock( RpcDefinition.class ); - when( mockRpc.getQName() ).thenReturn( cancelToastQName ); + RpcDefinition mockRpc = mock(RpcDefinition.class); + when(mockRpc.getQName()).thenReturn(cancelToastQName); - MountInstance mockMountPoint = mock( MountInstance.class ); - when( mockMountPoint.rpc( eq( cancelToastQName ), any( CompositeNode.class ) ) ) - .thenReturn( mockListener ); + MountInstance mockMountPoint = mock(MountInstance.class); + when(mockMountPoint.rpc(eq(cancelToastQName), any(CompositeNode.class))).thenReturn(mockListener); - InstanceIdWithSchemaNode mockedInstanceId = mock( InstanceIdWithSchemaNode.class ); - when( mockedInstanceId.getMountPoint() ).thenReturn( mockMountPoint ); + InstanceIdWithSchemaNode mockedInstanceId = mock(InstanceIdWithSchemaNode.class); + when(mockedInstanceId.getMountPoint()).thenReturn(mockMountPoint); - ControllerContext mockedContext = mock( ControllerContext.class ); + ControllerContext mockedContext = mock(ControllerContext.class); String cancelToastStr = "toaster:cancel-toast"; - when( mockedContext.urlPathArgDecode( cancelToastStr ) ).thenReturn( cancelToastStr ); - when( mockedContext.getRpcDefinition( cancelToastStr ) ).thenReturn( mockRpc ); - when( mockedContext.toMountPointIdentifier( "opendaylight-inventory:nodes/node/" - + "REMOTE_HOST/yang-ext:mount/toaster:cancel-toast" ) ).thenReturn( mockedInstanceId ); + when(mockedContext.urlPathArgDecode(cancelToastStr)).thenReturn(cancelToastStr); + when(mockedContext.getRpcDefinition(cancelToastStr)).thenReturn(mockRpc); + when( + mockedContext.toMountPointIdentifier("opendaylight-inventory:nodes/node/" + + "REMOTE_HOST/yang-ext:mount/toaster:cancel-toast")).thenReturn(mockedInstanceId); - restconfImpl.setControllerContext( mockedContext ); + restconfImpl.setControllerContext(mockedContext); StructuredData output = restconfImpl.invokeRpc( - "opendaylight-inventory:nodes/node/REMOTE_HOST/yang-ext:mount/toaster:cancel-toast", - "",uriInfo); + "opendaylight-inventory:nodes/node/REMOTE_HOST/yang-ext:mount/toaster:cancel-toast", "", uriInfo); assertEquals(null, output); - //additional validation in the fact that the restconfImpl does not throw an exception. + // additional validation in the fact that the restconfImpl does not + // throw an exception. } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/MultipleEqualNamesForDataNodesTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/MultipleEqualNamesForDataNodesTest.java index 42131026a5..5fbfc45352 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/MultipleEqualNamesForDataNodesTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/MultipleEqualNamesForDataNodesTest.java @@ -25,9 +25,8 @@ import org.opendaylight.yangtools.yang.data.api.CompositeNode; 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 RestconfDocumentedException has to - * be raised + * If more then one data element with equal name exists where container or leaf schema node should be present the + * RestconfDocumentedException has to be raised * * Tests for BUG 1204 */ @@ -35,31 +34,32 @@ 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); + 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); + 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); + 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); + ErrorTag.BAD_ELEMENT, XmlToCompositeNodeProvider.INSTANCE); } - private void multipleEqualNameDataNodeTest(String path, ErrorType errorType, ErrorTag errorTag,MessageBodyReader messageBodyReader) { + private void multipleEqualNameDataNodeTest(String path, ErrorType errorType, ErrorTag errorTag, + MessageBodyReader messageBodyReader) { try { - CompositeNode compositeNode = TestUtils.readInputToCnSn(path, false,messageBodyReader); + CompositeNode compositeNode = TestUtils.readInputToCnSn(path, false, messageBodyReader); assertNotNull(compositeNode); Set modules = null; diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/NormalizeNodeTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/NormalizeNodeTest.java index 158569af73..7c354acc40 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/NormalizeNodeTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/NormalizeNodeTest.java @@ -11,7 +11,6 @@ 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; @@ -26,7 +25,7 @@ public class NormalizeNodeTest extends YangAndXmlAndDataSchemaLoader { dataLoad("/normalize-node/yang/"); } - @Test(expected=RestconfDocumentedException.class) + @Test(expected = RestconfDocumentedException.class) public void namespaceNotNullAndInvalidNamespaceAndNoModuleNameTest() { TestUtils.normalizeCompositeNode(prepareCnSn("wrongnamespace"), modules, schemaNodePath); diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestCodecExceptionsTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestCodecExceptionsTest.java index 024a93b78e..4000c7cc80 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestCodecExceptionsTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestCodecExceptionsTest.java @@ -12,7 +12,6 @@ import static org.junit.Assert.assertNull; import static org.mockito.Mockito.mock; import java.util.Collections; - import org.junit.Test; import org.opendaylight.controller.sal.restconf.impl.RestCodec; import org.opendaylight.yangtools.concepts.Codec; @@ -28,7 +27,7 @@ public class RestCodecExceptionsTest { @Test public void serializeExceptionTest() { - Codec codec = RestCodec.from(BitsType.create(PATH, Collections.emptyList()), null); + Codec codec = RestCodec.from(BitsType.create(PATH, Collections. emptyList()), null); String serializedValue = (String) codec.serialize("incorrect value"); // set // expected assertEquals("incorrect value", serializedValue); diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestDeleteOperationTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestDeleteOperationTest.java index e8cbf3140f..d1d2a5babf 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestDeleteOperationTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestDeleteOperationTest.java @@ -57,10 +57,10 @@ public class RestDeleteOperationTest extends JerseyTest { @Override protected Application configure() { /* enable/disable Jersey logs to console */ -// enable(TestProperties.LOG_TRAFFIC); -// enable(TestProperties.DUMP_ENTITY); -// enable(TestProperties.RECORD_LOG_LEVEL); -// set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue()); + // enable(TestProperties.LOG_TRAFFIC); + // enable(TestProperties.DUMP_ENTITY); + // enable(TestProperties.RECORD_LOG_LEVEL); + // set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue()); ResourceConfig resourceConfig = new ResourceConfig(); resourceConfig = resourceConfig.registerInstances(restconfImpl, StructuredDataToXmlProvider.INSTANCE, XmlToCompositeNodeProvider.INSTANCE); @@ -82,7 +82,8 @@ public class RestDeleteOperationTest extends JerseyTest { } private Future> createFuture(TransactionStatus statusName) { - RpcResult rpcResult = new DummyRpcResult.Builder().result(statusName).build(); + RpcResult rpcResult = new DummyRpcResult.Builder().result(statusName) + .build(); return new DummyFuture.Builder().rpcResult(rpcResult).build(); } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetAugmentedElementWhenEqualNamesTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetAugmentedElementWhenEqualNamesTest.java index 53183c611c..bab06e9245 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetAugmentedElementWhenEqualNamesTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetAugmentedElementWhenEqualNamesTest.java @@ -12,7 +12,6 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.FileNotFoundException; - import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; @@ -47,10 +46,9 @@ public class RestGetAugmentedElementWhenEqualNamesTest { public void nodeWithoutNamespaceHasMoreAugments() { try { controllerContext.toInstanceIdentifier("main:cont/cont1"); - fail( "Expected exception" ); + fail("Expected exception"); } catch (RestconfDocumentedException e) { - assertTrue(e.getErrors().get( 0 ).getErrorMessage().contains( - "is added as augment from more than one module")); + assertTrue(e.getErrors().get(0).getErrorMessage().contains("is added as augment from more than one module")); } } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetOperationTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetOperationTest.java index 9fd5128d19..536d140cf1 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetOperationTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetOperationTest.java @@ -75,7 +75,7 @@ public class RestGetOperationTest extends JerseyTest { Object key; Object data; // List for a CompositeNode, value Object for a SimpleNode - NodeData( final Object key, final Object data ) { + NodeData(final Object key, final Object data) { this.key = key; this.data = data; } @@ -117,7 +117,7 @@ public class RestGetOperationTest extends JerseyTest { resourceConfig = resourceConfig.registerInstances(restconfImpl, StructuredDataToXmlProvider.INSTANCE, StructuredDataToJsonProvider.INSTANCE, XmlToCompositeNodeProvider.INSTANCE, JsonToCompositeNodeProvider.INSTANCE); - resourceConfig.registerClasses( RestconfDocumentedExceptionMapper.class ); + resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class); return resourceConfig; } @@ -172,19 +172,18 @@ public class RestGetOperationTest extends JerseyTest { /** * MountPoint test. URI represents mount point. * - * Slashes in URI behind mount point. lst1 element with key - * GigabitEthernet0%2F0%2F0%2F0 (GigabitEthernet0/0/0/0) is requested via - * GET HTTP operation. It is tested whether %2F character is replaced with - * simple / in InstanceIdentifier parameter in method - * {@link BrokerFacade#readConfigurationDataBehindMountPoint(MountInstance, InstanceIdentifier)} - * which is called in method {@link RestconfImpl#readConfigurationData} + * Slashes in URI behind mount point. lst1 element with key GigabitEthernet0%2F0%2F0%2F0 (GigabitEthernet0/0/0/0) is + * requested via GET HTTP operation. It is tested whether %2F character is replaced with simple / in + * InstanceIdentifier parameter in method + * {@link BrokerFacade#readConfigurationDataBehindMountPoint(MountInstance, InstanceIdentifier)} which is called in + * method {@link RestconfImpl#readConfigurationData} * * * @throws ParseException */ @Test public void getDataWithSlashesBehindMountPoint() throws UnsupportedEncodingException, URISyntaxException, - ParseException { + ParseException { InstanceIdentifier awaitedInstanceIdentifier = prepareInstanceIdentifierForList(); when( brokerFacade.readConfigurationDataBehindMountPoint(any(MountInstance.class), @@ -446,11 +445,11 @@ public class RestGetOperationTest extends JerseyTest { assertTrue( "module1-behind-mount-point in json wasn't found", prepareXmlRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point", responseBody) - .find()); + .find()); assertTrue( "module2-behind-mount-point in json wasn't found", prepareXmlRegex("module2-behind-mount-point", "2014-02-04", "module:2:behind:mount:point", responseBody) - .find()); + .find()); } @@ -486,7 +485,7 @@ public class RestGetOperationTest extends JerseyTest { assertTrue( "module1-behind-mount-point in json wasn't found", prepareXmlRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point", responseBody) - .find()); + .find()); split = responseBody.split(" paramMap = new MultivaluedHashMap<>(); - paramMap.putSingle( "depth", "1o" ); - UriInfo mockInfo = mock( UriInfo.class ); - when( mockInfo.getQueryParameters( false ) ).thenAnswer( - new Answer>() { - @Override - public MultivaluedMap answer( final InvocationOnMock invocation ) { - return paramMap; - } - } ); + final MultivaluedMap paramMap = new MultivaluedHashMap<>(); + paramMap.putSingle("depth", "1o"); + UriInfo mockInfo = mock(UriInfo.class); + when(mockInfo.getQueryParameters(false)).thenAnswer(new Answer>() { + @Override + public MultivaluedMap answer(final InvocationOnMock invocation) { + return paramMap; + } + }); - getDataWithInvalidDepthParameterTest( mockInfo ); + getDataWithInvalidDepthParameterTest(mockInfo); - paramMap.putSingle( "depth", "0" ); - getDataWithInvalidDepthParameterTest( mockInfo ); + paramMap.putSingle("depth", "0"); + getDataWithInvalidDepthParameterTest(mockInfo); - paramMap.putSingle( "depth", "-1" ); - getDataWithInvalidDepthParameterTest( mockInfo ); + paramMap.putSingle("depth", "-1"); + getDataWithInvalidDepthParameterTest(mockInfo); } - private void getDataWithInvalidDepthParameterTest( final UriInfo uriInfo ) { + private void getDataWithInvalidDepthParameterTest(final UriInfo uriInfo) { try { - restconfImpl.readConfigurationData( "nested-module:depth1-cont", uriInfo ); - fail( "Expected RestconfDocumentedException" ); - } - catch( RestconfDocumentedException e ) { - assertTrue( "Unexpected error message: " + e.getErrors().get( 0 ).getErrorMessage(), - e.getErrors().get( 0 ).getErrorMessage().contains( "depth" ) ); + restconfImpl.readConfigurationData("nested-module:depth1-cont", uriInfo); + fail("Expected RestconfDocumentedException"); + } catch (RestconfDocumentedException e) { + assertTrue("Unexpected error message: " + e.getErrors().get(0).getErrorMessage(), e.getErrors().get(0) + .getErrorMessage().contains("depth")); } } - private void verifyXMLResponse( final Response response, final NodeData nodeData ) { + private void verifyXMLResponse(final Response response, final NodeData nodeData) { - Document doc = TestUtils.loadDocumentFrom( (InputStream) response.getEntity() ); - assertNotNull( "Could not parse XML document", doc ); + Document doc = TestUtils.loadDocumentFrom((InputStream) response.getEntity()); + assertNotNull("Could not parse XML document", doc); - //System.out.println(TestUtils.getDocumentInPrintableForm( doc )); + // System.out.println(TestUtils.getDocumentInPrintableForm( doc )); - verifyContainerElement( doc.getDocumentElement(), nodeData ); + verifyContainerElement(doc.getDocumentElement(), nodeData); } @SuppressWarnings("unchecked") - private void verifyContainerElement( final Element element, final NodeData nodeData ) { + private void verifyContainerElement(final Element element, final NodeData nodeData) { - assertEquals( "Element local name", nodeData.key, element.getNodeName() ); + assertEquals("Element local name", nodeData.key, element.getNodeName()); NodeList childNodes = element.getChildNodes(); - if( nodeData.data == null ) { // empty container - assertTrue( "Expected no child elements for \"" + element.getNodeName() + "\"", - childNodes.getLength() == 0 ); + if (nodeData.data == null) { // empty container + assertTrue("Expected no child elements for \"" + element.getNodeName() + "\"", childNodes.getLength() == 0); return; } - Map expChildMap = Maps.newHashMap(); - for( NodeData expChild: (List)nodeData.data ) { - expChildMap.put( expChild.key.toString(), expChild ); + Map expChildMap = Maps.newHashMap(); + for (NodeData expChild : (List) nodeData.data) { + expChildMap.put(expChild.key.toString(), expChild); } - for( int i = 0; i < childNodes.getLength(); i++ ) { - org.w3c.dom.Node actualChild = childNodes.item( i ); - if( !( actualChild instanceof Element ) ) { + for (int i = 0; i < childNodes.getLength(); i++) { + org.w3c.dom.Node actualChild = childNodes.item(i); + if (!(actualChild instanceof Element)) { continue; } - Element actualElement = (Element)actualChild; - NodeData expChild = expChildMap.remove( actualElement.getNodeName() ); - assertNotNull( "Unexpected child element for parent \"" + element.getNodeName() + - "\": " + actualElement.getNodeName(), expChild ); - - if( expChild.data == null || expChild.data instanceof List ) { - verifyContainerElement( actualElement, expChild ); - } - else { - assertEquals( "Text content for element: " + actualElement.getNodeName(), - expChild.data, actualElement.getTextContent() ); + Element actualElement = (Element) actualChild; + NodeData expChild = expChildMap.remove(actualElement.getNodeName()); + assertNotNull( + "Unexpected child element for parent \"" + element.getNodeName() + "\": " + + actualElement.getNodeName(), expChild); + + if (expChild.data == null || expChild.data instanceof List) { + verifyContainerElement(actualElement, expChild); + } else { + assertEquals("Text content for element: " + actualElement.getNodeName(), expChild.data, + actualElement.getTextContent()); } } - if( !expChildMap.isEmpty() ) { - fail( "Missing elements for parent \"" + element.getNodeName() + - "\": " + expChildMap.keySet() ); + if (!expChildMap.isEmpty()) { + fail("Missing elements for parent \"" + element.getNodeName() + "\": " + expChildMap.keySet()); } } - private NodeData expectContainer( final String name, final NodeData... childData ) { - return new NodeData( name, Lists.newArrayList( childData ) ); + private NodeData expectContainer(final String name, final NodeData... childData) { + return new NodeData(name, Lists.newArrayList(childData)); } - private NodeData expectEmptyContainer( final String name ) { - return new NodeData( name, null ); + private NodeData expectEmptyContainer(final String name) { + return new NodeData(name, null); } - private NodeData expectLeaf( final String name, final Object value ) { - return new NodeData( name, value ); + private NodeData expectLeaf(final String name, final Object value) { + return new NodeData(name, value); } - private QName toNestedQName( final String localName ) { - return QName.create( "urn:nested:module", "2014-06-3", localName ); + private QName toNestedQName(final String localName) { + return QName.create("urn:nested:module", "2014-06-3", localName); } @SuppressWarnings("unchecked") - private CompositeNode toCompositeNode( final NodeData nodeData ) { + private CompositeNode toCompositeNode(final NodeData nodeData) { CompositeNodeBuilder builder = ImmutableCompositeNode.builder(); - builder.setQName( (QName) nodeData.key ); + builder.setQName((QName) nodeData.key); - for( NodeData child: (List)nodeData.data ) { - if( child.data instanceof List ) { - builder.add( toCompositeNode( child ) ); - } - else { - builder.addLeaf( (QName) child.key, child.data ); + for (NodeData child : (List) 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 ) ); + private NodeData toCompositeNodeData(final QName key, final NodeData... childData) { + return new NodeData(key, Lists.newArrayList(childData)); } - private NodeData toSimpleNodeData( final QName key, final Object value ) { - return new NodeData( key, value ); + private NodeData toSimpleNodeData(final QName key, final Object value) { + return new NodeData(key, value); } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestPostOperationTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestPostOperationTest.java index 5b36fd52f7..1442338e2c 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestPostOperationTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestPostOperationTest.java @@ -125,10 +125,12 @@ public class RestPostOperationTest extends JerseyTest { assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput)); List rpcErrors = new ArrayList<>(); - rpcErrors.add( RpcErrors.getRpcError("applicationTag1", "tag1", "info1", ErrorSeverity.ERROR, "message1", ErrorType.RPC, null)); - rpcErrors.add( RpcErrors.getRpcError("applicationTag2", "tag2", "info2", ErrorSeverity.WARNING, "message2", ErrorType.PROTOCOL, null)); + rpcErrors.add(RpcErrors.getRpcError("applicationTag1", "tag1", "info1", ErrorSeverity.ERROR, "message1", + ErrorType.RPC, null)); + rpcErrors.add(RpcErrors.getRpcError("applicationTag2", "tag2", "info2", ErrorSeverity.WARNING, "message2", + ErrorType.PROTOCOL, null)); mockInvokeRpc(null, false, rpcErrors); - assertEquals(500,post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput)); + assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput)); uri = "/operations/test-module:rpc-wrongtest"; assertEquals(400, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput)); @@ -198,8 +200,8 @@ public class RestPostOperationTest extends JerseyTest { builder.errors(errors); } RpcResult rpcResult = builder.build(); - when(brokerFacade.invokeRpc(any(QName.class), any(CompositeNode.class))) - .thenReturn(Futures.> immediateFuture(rpcResult)); + when(brokerFacade.invokeRpc(any(QName.class), any(CompositeNode.class))).thenReturn( + Futures.> immediateFuture(rpcResult)); } private void mockInvokeRpc(CompositeNode result, boolean sucessful) { diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfDocumentedExceptionMapperTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfDocumentedExceptionMapperTest.java index c5c4596189..b8c0270a61 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfDocumentedExceptionMapperTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfDocumentedExceptionMapperTest.java @@ -78,63 +78,61 @@ import org.w3c.dom.NodeList; public class RestconfDocumentedExceptionMapperTest extends JerseyTest { interface ErrorInfoVerifier { - void verifyXML( Node errorInfoNode ); - void verifyJson( JsonElement errorInfoElement ); + void verifyXML(Node errorInfoNode); + + void verifyJson(JsonElement errorInfoElement); } static class ComplexErrorInfoVerifier implements ErrorInfoVerifier { Map expErrorInfo; - public ComplexErrorInfoVerifier( final Map expErrorInfo ) { + public ComplexErrorInfoVerifier(final Map expErrorInfo) { this.expErrorInfo = expErrorInfo; } @Override - public void verifyXML( final Node errorInfoNode ) { + public void verifyXML(final Node errorInfoNode) { - Map mutableExpMap = Maps.newHashMap( expErrorInfo ); + Map mutableExpMap = Maps.newHashMap(expErrorInfo); NodeList childNodes = errorInfoNode.getChildNodes(); - for( int i = 0; i < childNodes.getLength(); i++ ) { - Node child = childNodes.item( i ); - if( child instanceof Element ) { - String expValue = mutableExpMap.remove( child.getNodeName() ); - assertNotNull( "Found unexpected \"error-info\" child node: " + - child.getNodeName(), expValue ); - assertEquals( "Text content for \"error-info\" child node " + - child.getNodeName(), expValue, child.getTextContent() ); + for (int i = 0; i < childNodes.getLength(); i++) { + Node child = childNodes.item(i); + if (child instanceof Element) { + String expValue = mutableExpMap.remove(child.getNodeName()); + assertNotNull("Found unexpected \"error-info\" child node: " + child.getNodeName(), expValue); + assertEquals("Text content for \"error-info\" child node " + child.getNodeName(), expValue, + child.getTextContent()); } } - if( !mutableExpMap.isEmpty() ) { - fail( "Missing \"error-info\" child nodes: " + mutableExpMap ); + if (!mutableExpMap.isEmpty()) { + fail("Missing \"error-info\" child nodes: " + mutableExpMap); } } @Override - public void verifyJson( final JsonElement errorInfoElement ) { + public void verifyJson(final JsonElement errorInfoElement) { - assertTrue( "\"error-info\" Json element is not an Object", - errorInfoElement.isJsonObject() ); + assertTrue("\"error-info\" Json element is not an Object", errorInfoElement.isJsonObject()); Map actualErrorInfo = Maps.newHashMap(); - for( Entry entry: errorInfoElement.getAsJsonObject().entrySet() ) { + for (Entry entry : errorInfoElement.getAsJsonObject().entrySet()) { String leafName = entry.getKey(); JsonElement leafElement = entry.getValue(); - actualErrorInfo.put( leafName, leafElement.getAsString() ); + actualErrorInfo.put(leafName, leafElement.getAsString()); } - Map mutableExpMap = Maps.newHashMap( expErrorInfo ); - for( Entry actual: actualErrorInfo.entrySet() ) { - String expValue = mutableExpMap.remove( actual.getKey() ); - assertNotNull( "Found unexpected \"error-info\" child node: " + - actual.getKey(), expValue ); - assertEquals( "Text content for \"error-info\" child node " + - actual.getKey(), expValue, actual.getValue() ); + Map mutableExpMap = Maps.newHashMap(expErrorInfo); + for (Entry actual : actualErrorInfo.entrySet()) { + String expValue = mutableExpMap.remove(actual.getKey()); + assertNotNull("Found unexpected \"error-info\" child node: " + actual.getKey(), expValue); + assertEquals("Text content for \"error-info\" child node " + actual.getKey(), expValue, + actual.getValue()); } - if( !mutableExpMap.isEmpty() ) { - fail( "Missing \"error-info\" child nodes: " + mutableExpMap ); + if (!mutableExpMap.isEmpty()) { + fail("Missing \"error-info\" child nodes: " + mutableExpMap); } } } @@ -143,27 +141,27 @@ public class RestconfDocumentedExceptionMapperTest extends JerseyTest { String expTextContent; - public SimpleErrorInfoVerifier( final String expErrorInfo ) { + public SimpleErrorInfoVerifier(final String expErrorInfo) { this.expTextContent = expErrorInfo; } - void verifyContent( final String actualContent ) { - assertNotNull( "Actual \"error-info\" text content is null", actualContent ); - assertTrue( "", actualContent.contains( expTextContent ) ); + void verifyContent(final String actualContent) { + assertNotNull("Actual \"error-info\" text content is null", actualContent); + assertTrue("", actualContent.contains(expTextContent)); } @Override - public void verifyXML( final Node errorInfoNode ) { - verifyContent( errorInfoNode.getTextContent() ); + public void verifyXML(final Node errorInfoNode) { + verifyContent(errorInfoNode.getTextContent()); } @Override - public void verifyJson( final JsonElement errorInfoElement ) { - verifyContent( errorInfoElement.getAsString() ); + public void verifyJson(final JsonElement errorInfoElement) { + verifyContent(errorInfoElement.getAsString()); } } - static RestconfService mockRestConf = mock( RestconfService.class ); + static RestconfService mockRestConf = mock(RestconfService.class); static XPath XPATH = XPathFactory.newInstance().newXPath(); static XPathExpression ERROR_LIST; @@ -175,745 +173,650 @@ public class RestconfDocumentedExceptionMapperTest extends JerseyTest { @BeforeClass public static void init() throws Exception { - ControllerContext.getInstance().setGlobalSchema( TestUtils.loadSchemaContext("/modules") ); + ControllerContext.getInstance().setGlobalSchema(TestUtils.loadSchemaContext("/modules")); NamespaceContext nsContext = new NamespaceContext() { @Override - public Iterator getPrefixes( final String namespaceURI ) { + public Iterator getPrefixes(final String namespaceURI) { return null; } @Override - public String getPrefix( final String namespaceURI ) { + public String getPrefix(final String namespaceURI) { return null; } @Override - public String getNamespaceURI( final String prefix ) { - return "ietf-restconf".equals( prefix ) ? Draft02.RestConfModule.NAMESPACE : null; + public String getNamespaceURI(final String prefix) { + return "ietf-restconf".equals(prefix) ? Draft02.RestConfModule.NAMESPACE : null; } }; - XPATH.setNamespaceContext( nsContext ); - ERROR_LIST = XPATH.compile( "ietf-restconf:errors/ietf-restconf:error" ); - ERROR_TYPE = XPATH.compile( "ietf-restconf:error-type" ); - ERROR_TAG = XPATH.compile( "ietf-restconf:error-tag" ); - ERROR_MESSAGE = XPATH.compile( "ietf-restconf:error-message" ); - ERROR_APP_TAG = XPATH.compile( "ietf-restconf:error-app-tag" ); - ERROR_INFO = XPATH.compile( "ietf-restconf:error-info" ); + XPATH.setNamespaceContext(nsContext); + ERROR_LIST = XPATH.compile("ietf-restconf:errors/ietf-restconf:error"); + ERROR_TYPE = XPATH.compile("ietf-restconf:error-type"); + ERROR_TAG = XPATH.compile("ietf-restconf:error-tag"); + ERROR_MESSAGE = XPATH.compile("ietf-restconf:error-message"); + ERROR_APP_TAG = XPATH.compile("ietf-restconf:error-app-tag"); + ERROR_INFO = XPATH.compile("ietf-restconf:error-info"); } @Override @Before public void setUp() throws Exception { - reset( mockRestConf ); + reset(mockRestConf); super.setUp(); } @Override protected Application configure() { ResourceConfig resourceConfig = new ResourceConfig(); - resourceConfig = resourceConfig.registerInstances( mockRestConf, StructuredDataToXmlProvider.INSTANCE, - StructuredDataToJsonProvider.INSTANCE ); - resourceConfig.registerClasses( RestconfDocumentedExceptionMapper.class ); + resourceConfig = resourceConfig.registerInstances(mockRestConf, StructuredDataToXmlProvider.INSTANCE, + StructuredDataToJsonProvider.INSTANCE); + resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class); return resourceConfig; } - void stageMockEx( final RestconfDocumentedException ex ) { - reset( mockRestConf ); - when( mockRestConf.readOperationalData( any( String.class ), any( UriInfo.class ) ) ).thenThrow( ex ); + void stageMockEx(final RestconfDocumentedException ex) { + reset(mockRestConf); + when(mockRestConf.readOperationalData(any(String.class), any(UriInfo.class))).thenThrow(ex); } - void testJsonResponse( final RestconfDocumentedException ex, final Status expStatus, final ErrorType expErrorType, + void testJsonResponse(final RestconfDocumentedException ex, final Status expStatus, final ErrorType expErrorType, final ErrorTag expErrorTag, final String expErrorMessage, final String expErrorAppTag, - final ErrorInfoVerifier errorInfoVerifier ) throws Exception { + final ErrorInfoVerifier errorInfoVerifier) throws Exception { - stageMockEx( ex ); + stageMockEx(ex); - Response resp = target("/operational/foo").request( MediaType.APPLICATION_JSON ).get(); + Response resp = target("/operational/foo").request(MediaType.APPLICATION_JSON).get(); - InputStream stream = verifyResponse( resp, MediaType.APPLICATION_JSON, expStatus ); + InputStream stream = verifyResponse(resp, MediaType.APPLICATION_JSON, expStatus); - verifyJsonResponseBody( stream, expErrorType, expErrorTag, expErrorMessage, - expErrorAppTag, errorInfoVerifier ); + verifyJsonResponseBody(stream, expErrorType, expErrorTag, expErrorMessage, expErrorAppTag, errorInfoVerifier); } @Test public void testToJsonResponseWithMessageOnly() throws Exception { - testJsonResponse( new RestconfDocumentedException( "mock error" ), Status.INTERNAL_SERVER_ERROR, - ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null, null ); + 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: {" + - // " error: [{" + - // " error-tag : \"operation-failed\"" + - // " ,error-type : \"application\"" + - // " ,error-message : \"An error occurred\"" + - // " ,error-info : {" + - // " session-id: \"123\"" + - // " ,address: \"1.2.3.4\"" + - // " }" + - // " }]" + - // " }" + - // "}"; + // String json = + // "{ errors: {" + + // " error: [{" + + // " error-tag : \"operation-failed\"" + + // " ,error-type : \"application\"" + + // " ,error-message : \"An error occurred\"" + + // " ,error-info : {" + + // " session-id: \"123\"" + + // " ,address: \"1.2.3.4\"" + + // " }" + + // " }]" + + // " }" + + // "}"; // - // verifyJsonResponseBody( new java.io.StringBufferInputStream(json ), ErrorType.APPLICATION, - // ErrorTag.OPERATION_FAILED, "An error occurred", null, - // com.google.common.collect.ImmutableMap.of( "session-id", "123", "address", "1.2.3.4" ) ); + // verifyJsonResponseBody( new java.io.StringBufferInputStream(json ), + // ErrorType.APPLICATION, + // ErrorTag.OPERATION_FAILED, "An error occurred", null, + // com.google.common.collect.ImmutableMap.of( "session-id", "123", + // "address", "1.2.3.4" ) ); } @Test public void testToJsonResponseWithInUseErrorTag() throws Exception { - testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.IN_USE ), - Status.CONFLICT, ErrorType.PROTOCOL, - ErrorTag.IN_USE, "mock error", null, null ); + testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.IN_USE), + Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.IN_USE, "mock error", null, null); } @Test public void testToJsonResponseWithInvalidValueErrorTag() throws Exception { - testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.RPC, - ErrorTag.INVALID_VALUE ), - Status.BAD_REQUEST, ErrorType.RPC, - ErrorTag.INVALID_VALUE, "mock error", null, null ); + testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.RPC, ErrorTag.INVALID_VALUE), + Status.BAD_REQUEST, ErrorType.RPC, ErrorTag.INVALID_VALUE, "mock error", null, null); } @Test public void testToJsonResponseWithTooBigErrorTag() throws Exception { - testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.TRANSPORT, - ErrorTag.TOO_BIG ), - Status.REQUEST_ENTITY_TOO_LARGE, ErrorType.TRANSPORT, - ErrorTag.TOO_BIG, "mock error", null, null ); + testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.TRANSPORT, ErrorTag.TOO_BIG), + Status.REQUEST_ENTITY_TOO_LARGE, ErrorType.TRANSPORT, ErrorTag.TOO_BIG, "mock error", null, null); } @Test public void testToJsonResponseWithMissingAttributeErrorTag() throws Exception { - testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.MISSING_ATTRIBUTE ), - Status.BAD_REQUEST, ErrorType.PROTOCOL, - ErrorTag.MISSING_ATTRIBUTE, "mock error", null, null ); + testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE), + Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE, "mock error", null, null); } @Test public void testToJsonResponseWithBadAttributeErrorTag() throws Exception { - testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.BAD_ATTRIBUTE ), - Status.BAD_REQUEST, ErrorType.PROTOCOL, - ErrorTag.BAD_ATTRIBUTE, "mock error", null, null ); + testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE), + Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE, "mock error", null, null); } + @Test public void testToJsonResponseWithUnknownAttributeErrorTag() throws Exception { - testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.UNKNOWN_ATTRIBUTE ), - Status.BAD_REQUEST, ErrorType.PROTOCOL, - ErrorTag.UNKNOWN_ATTRIBUTE, "mock error", null, null ); + testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ATTRIBUTE), + Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ATTRIBUTE, "mock error", null, null); } @Test public void testToJsonResponseWithBadElementErrorTag() throws Exception { - testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.BAD_ELEMENT ), - Status.BAD_REQUEST, - ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT, "mock error", null, null ); + testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT), + Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT, "mock error", null, null); } @Test public void testToJsonResponseWithUnknownElementErrorTag() throws Exception { - testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.UNKNOWN_ELEMENT ), - Status.BAD_REQUEST, ErrorType.PROTOCOL, - ErrorTag.UNKNOWN_ELEMENT, "mock error", null, null ); + testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT), + Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT, "mock error", null, null); } @Test public void testToJsonResponseWithUnknownNamespaceErrorTag() throws Exception { - testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.UNKNOWN_NAMESPACE ), - Status.BAD_REQUEST, ErrorType.PROTOCOL, - ErrorTag.UNKNOWN_NAMESPACE, "mock error", null, null ); + testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE), + Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE, "mock error", null, null); } @Test public void testToJsonResponseWithMalformedMessageErrorTag() throws Exception { - testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.MALFORMED_MESSAGE ), - Status.BAD_REQUEST, ErrorType.PROTOCOL, - ErrorTag.MALFORMED_MESSAGE, "mock error", null, null ); + testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE), + Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, "mock error", null, null); } @Test public void testToJsonResponseWithAccessDeniedErrorTag() throws Exception { - testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.ACCESS_DENIED ), - Status.FORBIDDEN, ErrorType.PROTOCOL, - ErrorTag.ACCESS_DENIED, "mock error", null, null ); + testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.ACCESS_DENIED), + Status.FORBIDDEN, ErrorType.PROTOCOL, ErrorTag.ACCESS_DENIED, "mock error", null, null); } @Test public void testToJsonResponseWithLockDeniedErrorTag() throws Exception { - testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.LOCK_DENIED ), - Status.CONFLICT, ErrorType.PROTOCOL, - ErrorTag.LOCK_DENIED, "mock error", null, null ); + testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.LOCK_DENIED), + Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.LOCK_DENIED, "mock error", null, null); } @Test public void testToJsonResponseWithResourceDeniedErrorTag() throws Exception { - testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.RESOURCE_DENIED ), - Status.CONFLICT, ErrorType.PROTOCOL, - ErrorTag.RESOURCE_DENIED, "mock error", null, null ); + testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.RESOURCE_DENIED), + Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.RESOURCE_DENIED, "mock error", null, null); } @Test public void testToJsonResponseWithRollbackFailedErrorTag() throws Exception { - testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.ROLLBACK_FAILED ), - Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, - ErrorTag.ROLLBACK_FAILED, "mock error", null, null ); + testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.ROLLBACK_FAILED), + Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.ROLLBACK_FAILED, "mock error", null, null); } @Test public void testToJsonResponseWithDataExistsErrorTag() throws Exception { - testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.DATA_EXISTS ), - Status.CONFLICT, ErrorType.PROTOCOL, - ErrorTag.DATA_EXISTS, "mock error", null, null ); + testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS), + Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS, "mock error", null, null); } @Test public void testToJsonResponseWithDataMissingErrorTag() throws Exception { - testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.DATA_MISSING ), - Status.CONFLICT, ErrorType.PROTOCOL, - ErrorTag.DATA_MISSING, "mock error", null, null ); + testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING), + Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, "mock error", null, null); } @Test public void testToJsonResponseWithOperationNotSupportedErrorTag() throws Exception { - testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.OPERATION_NOT_SUPPORTED ), - Status.NOT_IMPLEMENTED, ErrorType.PROTOCOL, - ErrorTag.OPERATION_NOT_SUPPORTED, "mock error", null, null ); + testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, + ErrorTag.OPERATION_NOT_SUPPORTED), Status.NOT_IMPLEMENTED, ErrorType.PROTOCOL, + ErrorTag.OPERATION_NOT_SUPPORTED, "mock error", null, null); } @Test public void testToJsonResponseWithOperationFailedErrorTag() throws Exception { - testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.OPERATION_FAILED ), - Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, - ErrorTag.OPERATION_FAILED, "mock error", null, null ); + testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.OPERATION_FAILED), + Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.OPERATION_FAILED, "mock error", null, null); } @Test public void testToJsonResponseWithPartialOperationErrorTag() throws Exception { - testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.PARTIAL_OPERATION ), - Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, - ErrorTag.PARTIAL_OPERATION, "mock error", null, null ); + testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.PARTIAL_OPERATION), + Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.PARTIAL_OPERATION, "mock error", null, null); } @Test public void testToJsonResponseWithErrorAppTag() throws Exception { - testJsonResponse( new RestconfDocumentedException( new RestconfError( - ErrorType.APPLICATION, ErrorTag.INVALID_VALUE, - "mock error", "mock-app-tag" ) ), - Status.BAD_REQUEST, ErrorType.APPLICATION, - ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", null ); + testJsonResponse(new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, + ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag")), Status.BAD_REQUEST, ErrorType.APPLICATION, + ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", null); } @Test public void testToJsonResponseWithMultipleErrors() throws Exception { - List errorList = Arrays.asList( - new RestconfError( ErrorType.APPLICATION, ErrorTag.LOCK_DENIED, "mock error1" ), - new RestconfError( ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2" ) ); - stageMockEx( new RestconfDocumentedException( errorList ) ); + List errorList = Arrays.asList(new RestconfError(ErrorType.APPLICATION, ErrorTag.LOCK_DENIED, + "mock error1"), new RestconfError(ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2")); + stageMockEx(new RestconfDocumentedException(errorList)); - Response resp = target("/operational/foo").request( MediaType.APPLICATION_JSON ).get(); + Response resp = target("/operational/foo").request(MediaType.APPLICATION_JSON).get(); - InputStream stream = verifyResponse( resp, MediaType.APPLICATION_JSON, Status.CONFLICT ); + InputStream stream = verifyResponse(resp, MediaType.APPLICATION_JSON, Status.CONFLICT); - JsonArray arrayElement = parseJsonErrorArrayElement( stream ); + JsonArray arrayElement = parseJsonErrorArrayElement(stream); - assertEquals( "\"error\" Json array element length", 2, arrayElement.size() ); + assertEquals("\"error\" Json array element length", 2, arrayElement.size()); - verifyJsonErrorNode( arrayElement.get( 0 ), ErrorType.APPLICATION, ErrorTag.LOCK_DENIED, - "mock error1", null, null ); + verifyJsonErrorNode(arrayElement.get(0), ErrorType.APPLICATION, ErrorTag.LOCK_DENIED, "mock error1", null, null); - verifyJsonErrorNode( arrayElement.get( 1 ), ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, - "mock error2", null, null ); + verifyJsonErrorNode(arrayElement.get(1), ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2", null, null); } @Test public void testToJsonResponseWithErrorInfo() throws Exception { String errorInfo = "
1.2.3.4
123"; - testJsonResponse( new RestconfDocumentedException( new RestconfError( - ErrorType.APPLICATION, ErrorTag.INVALID_VALUE, - "mock error", "mock-app-tag", errorInfo ) ), - Status.BAD_REQUEST, ErrorType.APPLICATION, - ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", - new ComplexErrorInfoVerifier( ImmutableMap.of( - "session-id", "123", "address", "1.2.3.4" ) ) ); + testJsonResponse(new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, + ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", errorInfo)), Status.BAD_REQUEST, + ErrorType.APPLICATION, ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", + new ComplexErrorInfoVerifier(ImmutableMap.of("session-id", "123", "address", "1.2.3.4"))); } @Test public void testToJsonResponseWithExceptionCause() throws Exception { - Exception cause = new Exception( "mock exception cause" ); - testJsonResponse( new RestconfDocumentedException( "mock error", cause ), - Status.INTERNAL_SERVER_ERROR, ErrorType.APPLICATION, - ErrorTag.OPERATION_FAILED, "mock error", null, - new SimpleErrorInfoVerifier( cause.getMessage() ) ); + Exception cause = new Exception("mock exception cause"); + testJsonResponse(new RestconfDocumentedException("mock error", cause), Status.INTERNAL_SERVER_ERROR, + ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null, + new SimpleErrorInfoVerifier(cause.getMessage())); } - void testXMLResponse( final RestconfDocumentedException ex, final Status expStatus, final ErrorType expErrorType, - final ErrorTag expErrorTag, final String expErrorMessage, - final String expErrorAppTag, final ErrorInfoVerifier errorInfoVerifier ) throws Exception - { - stageMockEx( ex ); + void testXMLResponse(final RestconfDocumentedException ex, final Status expStatus, final ErrorType expErrorType, + final ErrorTag expErrorTag, final String expErrorMessage, final String expErrorAppTag, + final ErrorInfoVerifier errorInfoVerifier) throws Exception { + stageMockEx(ex); - Response resp = target("/operational/foo").request( MediaType.APPLICATION_XML ).get(); + Response resp = target("/operational/foo").request(MediaType.APPLICATION_XML).get(); - InputStream stream = verifyResponse( resp, MediaType.APPLICATION_XML, expStatus ); + InputStream stream = verifyResponse(resp, MediaType.APPLICATION_XML, expStatus); - verifyXMLResponseBody( stream, expErrorType, expErrorTag, expErrorMessage, - expErrorAppTag, errorInfoVerifier ); + verifyXMLResponseBody(stream, expErrorType, expErrorTag, expErrorMessage, expErrorAppTag, errorInfoVerifier); } @Test public void testToXMLResponseWithMessageOnly() throws Exception { - testXMLResponse( new RestconfDocumentedException( "mock error" ), Status.INTERNAL_SERVER_ERROR, - ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null, null ); + testXMLResponse(new RestconfDocumentedException("mock error"), Status.INTERNAL_SERVER_ERROR, + ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null, null); // To test verification code - // String xml = - // ""+ - // " " + - // " application"+ - // " operation-failed"+ - // " An error occurred"+ - // " " + - // " 123" + - // "
1.2.3.4
" + - // "
" + - // "
" + - // "
"; + // String xml = + // ""+ + // " " + + // " application"+ + // " operation-failed"+ + // " An error occurred"+ + // " " + + // " 123" + + // "
1.2.3.4
" + + // "
" + + // "
" + + // "
"; // - // verifyXMLResponseBody( new java.io.StringBufferInputStream(xml), ErrorType.APPLICATION, - // ErrorTag.OPERATION_FAILED, "An error occurred", null, - // com.google.common.collect.ImmutableMap.of( "session-id", "123", "address", "1.2.3.4" ) ); + // verifyXMLResponseBody( new java.io.StringBufferInputStream(xml), + // ErrorType.APPLICATION, + // ErrorTag.OPERATION_FAILED, "An error occurred", null, + // com.google.common.collect.ImmutableMap.of( "session-id", "123", + // "address", "1.2.3.4" ) ); } @Test public void testToXMLResponseWithInUseErrorTag() throws Exception { - testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.IN_USE ), - Status.CONFLICT, ErrorType.PROTOCOL, - ErrorTag.IN_USE, "mock error", null, null ); + testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.IN_USE), + Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.IN_USE, "mock error", null, null); } @Test public void testToXMLResponseWithInvalidValueErrorTag() throws Exception { - testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.RPC, - ErrorTag.INVALID_VALUE ), - Status.BAD_REQUEST, ErrorType.RPC, - ErrorTag.INVALID_VALUE, "mock error", null, null ); + testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.RPC, ErrorTag.INVALID_VALUE), + Status.BAD_REQUEST, ErrorType.RPC, ErrorTag.INVALID_VALUE, "mock error", null, null); } @Test public void testToXMLResponseWithTooBigErrorTag() throws Exception { - testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.TRANSPORT, - ErrorTag.TOO_BIG ), - Status.REQUEST_ENTITY_TOO_LARGE, ErrorType.TRANSPORT, - ErrorTag.TOO_BIG, "mock error", null, null ); + testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.TRANSPORT, ErrorTag.TOO_BIG), + Status.REQUEST_ENTITY_TOO_LARGE, ErrorType.TRANSPORT, ErrorTag.TOO_BIG, "mock error", null, null); } @Test public void testToXMLResponseWithMissingAttributeErrorTag() throws Exception { - testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.MISSING_ATTRIBUTE ), - Status.BAD_REQUEST, ErrorType.PROTOCOL, - ErrorTag.MISSING_ATTRIBUTE, "mock error", null, null ); + testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE), + Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE, "mock error", null, null); } @Test public void testToXMLResponseWithBadAttributeErrorTag() throws Exception { - testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.BAD_ATTRIBUTE ), - Status.BAD_REQUEST, ErrorType.PROTOCOL, - ErrorTag.BAD_ATTRIBUTE, "mock error", null, null ); + testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE), + Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE, "mock error", null, null); } + @Test public void testToXMLResponseWithUnknownAttributeErrorTag() throws Exception { - testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.UNKNOWN_ATTRIBUTE ), - Status.BAD_REQUEST, ErrorType.PROTOCOL, - ErrorTag.UNKNOWN_ATTRIBUTE, "mock error", null, null ); + testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ATTRIBUTE), + Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ATTRIBUTE, "mock error", null, null); } @Test public void testToXMLResponseWithBadElementErrorTag() throws Exception { - testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.BAD_ELEMENT ), - Status.BAD_REQUEST, ErrorType.PROTOCOL, - ErrorTag.BAD_ELEMENT, "mock error", null, null ); + testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT), + Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT, "mock error", null, null); } @Test public void testToXMLResponseWithUnknownElementErrorTag() throws Exception { - testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.UNKNOWN_ELEMENT ), - Status.BAD_REQUEST, ErrorType.PROTOCOL, - ErrorTag.UNKNOWN_ELEMENT, "mock error", null, null ); + testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT), + Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT, "mock error", null, null); } @Test public void testToXMLResponseWithUnknownNamespaceErrorTag() throws Exception { - testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.UNKNOWN_NAMESPACE ), - Status.BAD_REQUEST, ErrorType.PROTOCOL, - ErrorTag.UNKNOWN_NAMESPACE, "mock error", null, null ); + testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE), + Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE, "mock error", null, null); } @Test public void testToXMLResponseWithMalformedMessageErrorTag() throws Exception { - testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.MALFORMED_MESSAGE ), - Status.BAD_REQUEST, ErrorType.PROTOCOL, - ErrorTag.MALFORMED_MESSAGE, "mock error", null, null ); + testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE), + Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, "mock error", null, null); } @Test public void testToXMLResponseWithAccessDeniedErrorTag() throws Exception { - testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.ACCESS_DENIED ), - Status.FORBIDDEN, ErrorType.PROTOCOL, - ErrorTag.ACCESS_DENIED, "mock error", null, null ); + testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.ACCESS_DENIED), + Status.FORBIDDEN, ErrorType.PROTOCOL, ErrorTag.ACCESS_DENIED, "mock error", null, null); } @Test public void testToXMLResponseWithLockDeniedErrorTag() throws Exception { - testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.LOCK_DENIED ), - Status.CONFLICT, ErrorType.PROTOCOL, - ErrorTag.LOCK_DENIED, "mock error", null, null ); + testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.LOCK_DENIED), + Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.LOCK_DENIED, "mock error", null, null); } @Test public void testToXMLResponseWithResourceDeniedErrorTag() throws Exception { - testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.RESOURCE_DENIED ), - Status.CONFLICT, ErrorType.PROTOCOL, - ErrorTag.RESOURCE_DENIED, "mock error", null, null ); + testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.RESOURCE_DENIED), + Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.RESOURCE_DENIED, "mock error", null, null); } @Test public void testToXMLResponseWithRollbackFailedErrorTag() throws Exception { - testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.ROLLBACK_FAILED ), - Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, - ErrorTag.ROLLBACK_FAILED, "mock error", null, null ); + testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.ROLLBACK_FAILED), + Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.ROLLBACK_FAILED, "mock error", null, null); } @Test public void testToXMLResponseWithDataExistsErrorTag() throws Exception { - testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.DATA_EXISTS ), - Status.CONFLICT, ErrorType.PROTOCOL, - ErrorTag.DATA_EXISTS, "mock error", null, null ); + testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS), + Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS, "mock error", null, null); } @Test public void testToXMLResponseWithDataMissingErrorTag() throws Exception { - testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.DATA_MISSING ), - Status.CONFLICT, ErrorType.PROTOCOL, - ErrorTag.DATA_MISSING, "mock error", null, null ); + testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING), + Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, "mock error", null, null); } @Test public void testToXMLResponseWithOperationNotSupportedErrorTag() throws Exception { - testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.OPERATION_NOT_SUPPORTED ), - Status.NOT_IMPLEMENTED, ErrorType.PROTOCOL, - ErrorTag.OPERATION_NOT_SUPPORTED, "mock error", null, null ); + testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, + ErrorTag.OPERATION_NOT_SUPPORTED), Status.NOT_IMPLEMENTED, ErrorType.PROTOCOL, + ErrorTag.OPERATION_NOT_SUPPORTED, "mock error", null, null); } @Test public void testToXMLResponseWithOperationFailedErrorTag() throws Exception { - testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.OPERATION_FAILED ), - Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, - ErrorTag.OPERATION_FAILED, "mock error", null, null ); + testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.OPERATION_FAILED), + Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.OPERATION_FAILED, "mock error", null, null); } @Test public void testToXMLResponseWithPartialOperationErrorTag() throws Exception { - testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL, - ErrorTag.PARTIAL_OPERATION ), - Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, - ErrorTag.PARTIAL_OPERATION, "mock error", null, null ); + testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.PARTIAL_OPERATION), + Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.PARTIAL_OPERATION, "mock error", null, null); } @Test public void testToXMLResponseWithErrorAppTag() throws Exception { - testXMLResponse( new RestconfDocumentedException( new RestconfError( - ErrorType.APPLICATION, ErrorTag.INVALID_VALUE, - "mock error", "mock-app-tag" ) ), - Status.BAD_REQUEST, ErrorType.APPLICATION, - ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", null ); + testXMLResponse(new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, + ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag")), Status.BAD_REQUEST, ErrorType.APPLICATION, + ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", null); } @Test public void testToXMLResponseWithErrorInfo() throws Exception { String errorInfo = "
1.2.3.4
123"; - testXMLResponse( new RestconfDocumentedException( new RestconfError( - ErrorType.APPLICATION, ErrorTag.INVALID_VALUE, - "mock error", "mock-app-tag", errorInfo ) ), - Status.BAD_REQUEST, ErrorType.APPLICATION, - ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", - new ComplexErrorInfoVerifier( ImmutableMap.of( - "session-id", "123", "address", "1.2.3.4" ) ) ); + testXMLResponse(new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, + ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", errorInfo)), Status.BAD_REQUEST, + ErrorType.APPLICATION, ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", + new ComplexErrorInfoVerifier(ImmutableMap.of("session-id", "123", "address", "1.2.3.4"))); } @Test public void testToXMLResponseWithExceptionCause() throws Exception { - Exception cause = new Exception( "mock exception cause" ); - testXMLResponse( new RestconfDocumentedException( "mock error", cause ), - Status.INTERNAL_SERVER_ERROR, ErrorType.APPLICATION, - ErrorTag.OPERATION_FAILED, "mock error", null, - new SimpleErrorInfoVerifier( cause.getMessage() ) ); + Exception cause = new Exception("mock exception cause"); + testXMLResponse(new RestconfDocumentedException("mock error", cause), Status.INTERNAL_SERVER_ERROR, + ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null, + new SimpleErrorInfoVerifier(cause.getMessage())); } @Test public void testToXMLResponseWithMultipleErrors() throws Exception { - List errorList = Arrays.asList( - new RestconfError( ErrorType.APPLICATION, ErrorTag.LOCK_DENIED, "mock error1" ), - new RestconfError( ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2" ) ); - stageMockEx( new RestconfDocumentedException( errorList ) ); + List errorList = Arrays.asList(new RestconfError(ErrorType.APPLICATION, ErrorTag.LOCK_DENIED, + "mock error1"), new RestconfError(ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2")); + stageMockEx(new RestconfDocumentedException(errorList)); - Response resp = target("/operational/foo").request( MediaType.APPLICATION_XML ).get(); + Response resp = target("/operational/foo").request(MediaType.APPLICATION_XML).get(); - InputStream stream = verifyResponse( resp, MediaType.APPLICATION_XML, Status.CONFLICT ); + InputStream stream = verifyResponse(resp, MediaType.APPLICATION_XML, Status.CONFLICT); - Document doc = parseXMLDocument( stream ); + Document doc = parseXMLDocument(stream); - NodeList children = getXMLErrorList( doc, 2 ); + NodeList children = getXMLErrorList(doc, 2); - verifyXMLErrorNode( children.item( 0 ), ErrorType.APPLICATION, ErrorTag.LOCK_DENIED, - "mock error1", null, null ); + verifyXMLErrorNode(children.item(0), ErrorType.APPLICATION, ErrorTag.LOCK_DENIED, "mock error1", null, null); - verifyXMLErrorNode( children.item( 1 ), ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, - "mock error2", null, null ); + verifyXMLErrorNode(children.item(1), ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2", null, null); } @Test public void testToResponseWithAcceptHeader() throws Exception { - stageMockEx( new RestconfDocumentedException( "mock error" ) ); + stageMockEx(new RestconfDocumentedException("mock error")); - Response resp = target("/operational/foo") - .request().header( "Accept", MediaType.APPLICATION_JSON ).get(); + Response resp = target("/operational/foo").request().header("Accept", MediaType.APPLICATION_JSON).get(); - InputStream stream = verifyResponse( resp, MediaType.APPLICATION_JSON, - Status.INTERNAL_SERVER_ERROR ); + InputStream stream = verifyResponse(resp, MediaType.APPLICATION_JSON, Status.INTERNAL_SERVER_ERROR); - verifyJsonResponseBody( stream, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", - null, null ); + verifyJsonResponseBody(stream, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null, null); } @Test public void testToResponseWithStatusOnly() throws Exception { - // The StructuredDataToJsonProvider should throw a RestconfDocumentedException with no data + // The StructuredDataToJsonProvider should throw a + // RestconfDocumentedException with no data - when( mockRestConf.readOperationalData( any( String.class ), any( UriInfo.class ) ) ) - .thenReturn( new StructuredData( null, null, null ) ); + when(mockRestConf.readOperationalData(any(String.class), any(UriInfo.class))).thenReturn( + new StructuredData(null, null, null)); - Response resp = target("/operational/foo").request( MediaType.APPLICATION_JSON ).get(); + Response resp = target("/operational/foo").request(MediaType.APPLICATION_JSON).get(); - verifyResponse( resp, MediaType.TEXT_PLAIN, Status.NOT_FOUND ); + verifyResponse(resp, MediaType.TEXT_PLAIN, Status.NOT_FOUND); } - InputStream verifyResponse( final Response resp, final String expMediaType, final Status expStatus ) { - assertEquals( "getMediaType", MediaType.valueOf( expMediaType ), resp.getMediaType() ); - assertEquals( "getStatus", expStatus.getStatusCode(), resp.getStatus() ); + InputStream verifyResponse(final Response resp, final String expMediaType, final Status expStatus) { + assertEquals("getMediaType", MediaType.valueOf(expMediaType), resp.getMediaType()); + assertEquals("getStatus", expStatus.getStatusCode(), resp.getStatus()); Object entity = resp.getEntity(); - assertEquals( "Response entity", true, entity instanceof InputStream ); - InputStream stream = (InputStream)entity; + assertEquals("Response entity", true, entity instanceof InputStream); + InputStream stream = (InputStream) entity; return stream; } - void verifyJsonResponseBody( final InputStream stream, final ErrorType expErrorType, final ErrorTag expErrorTag, - final String expErrorMessage, final String expErrorAppTag, - final ErrorInfoVerifier errorInfoVerifier ) throws Exception { + void verifyJsonResponseBody(final InputStream stream, final ErrorType expErrorType, final ErrorTag expErrorTag, + final String expErrorMessage, final String expErrorAppTag, final ErrorInfoVerifier errorInfoVerifier) + throws Exception { - JsonArray arrayElement = parseJsonErrorArrayElement( stream ); + JsonArray arrayElement = parseJsonErrorArrayElement(stream); - assertEquals( "\"error\" Json array element length", 1, arrayElement.size() ); + assertEquals("\"error\" Json array element length", 1, arrayElement.size()); - verifyJsonErrorNode( arrayElement.get( 0 ), expErrorType, expErrorTag, expErrorMessage, - expErrorAppTag, errorInfoVerifier ); + verifyJsonErrorNode(arrayElement.get(0), expErrorType, expErrorTag, expErrorMessage, expErrorAppTag, + errorInfoVerifier); } - private JsonArray parseJsonErrorArrayElement( final InputStream stream ) throws IOException { + private JsonArray parseJsonErrorArrayElement(final InputStream stream) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ByteStreams.copy( stream, bos ); + ByteStreams.copy(stream, bos); - System.out.println("JSON: "+bos.toString()); + System.out.println("JSON: " + bos.toString()); JsonParser parser = new JsonParser(); JsonElement rootElement; try { - rootElement = parser.parse( - new InputStreamReader( new ByteArrayInputStream( bos.toByteArray() ) ) ); - } - catch( Exception e ) { - throw new IllegalArgumentException( "Invalid JSON response:\n" + bos.toString(), e ); + rootElement = parser.parse(new InputStreamReader(new ByteArrayInputStream(bos.toByteArray()))); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid JSON response:\n" + bos.toString(), e); } - assertTrue( "Root element of Json is not an Object", rootElement.isJsonObject() ); + assertTrue("Root element of Json is not an Object", rootElement.isJsonObject()); Set> errorsEntrySet = rootElement.getAsJsonObject().entrySet(); - assertEquals( "Json Object element set count", 1, errorsEntrySet.size() ); + assertEquals("Json Object element set count", 1, errorsEntrySet.size()); Entry errorsEntry = errorsEntrySet.iterator().next(); JsonElement errorsElement = errorsEntry.getValue(); - assertEquals( "First Json element name", "errors", errorsEntry.getKey() ); - assertTrue( "\"errors\" Json element is not an Object", errorsElement.isJsonObject() ); + assertEquals("First Json element name", "errors", errorsEntry.getKey()); + assertTrue("\"errors\" Json element is not an Object", errorsElement.isJsonObject()); Set> errorListEntrySet = errorsElement.getAsJsonObject().entrySet(); - assertEquals( "Root \"errors\" element child count", 1, errorListEntrySet.size() ); + assertEquals("Root \"errors\" element child count", 1, errorListEntrySet.size()); JsonElement errorListElement = errorListEntrySet.iterator().next().getValue(); - assertEquals( "\"errors\" child Json element name", "error", - errorListEntrySet.iterator().next().getKey() ); - assertTrue( "\"error\" Json element is not an Array", errorListElement.isJsonArray() ); + assertEquals("\"errors\" child Json element name", "error", errorListEntrySet.iterator().next().getKey()); + assertTrue("\"error\" Json element is not an Array", errorListElement.isJsonArray()); - // As a final check, make sure there aren't multiple "error" array elements. Unfortunately, - // the call above to getAsJsonObject().entrySet() will out duplicate "error" elements. So + // As a final check, make sure there aren't multiple "error" array + // elements. Unfortunately, + // the call above to getAsJsonObject().entrySet() will out duplicate + // "error" elements. So // we'll use regex on the json string to verify this. - Matcher matcher = Pattern.compile( "\"error\"[ ]*:[ ]*\\[", Pattern.DOTALL ).matcher( bos.toString() ); - assertTrue( "Expected 1 \"error\" element", matcher.find() ); - assertFalse( "Found multiple \"error\" elements", matcher.find() ); + Matcher matcher = Pattern.compile("\"error\"[ ]*:[ ]*\\[", Pattern.DOTALL).matcher(bos.toString()); + assertTrue("Expected 1 \"error\" element", matcher.find()); + assertFalse("Found multiple \"error\" elements", matcher.find()); return errorListElement.getAsJsonArray(); } - void verifyJsonErrorNode( final JsonElement errorEntryElement, final ErrorType expErrorType, final ErrorTag expErrorTag, - final String expErrorMessage, final String expErrorAppTag, - final ErrorInfoVerifier errorInfoVerifier ) { + void verifyJsonErrorNode(final JsonElement errorEntryElement, final ErrorType expErrorType, + final ErrorTag expErrorTag, final String expErrorMessage, final String expErrorAppTag, + final ErrorInfoVerifier errorInfoVerifier) { JsonElement errorInfoElement = null; Map leafMap = Maps.newHashMap(); - for( Entry entry: errorEntryElement.getAsJsonObject().entrySet() ) { + for (Entry entry : errorEntryElement.getAsJsonObject().entrySet()) { String leafName = entry.getKey(); JsonElement leafElement = entry.getValue(); - if( "error-info".equals( leafName ) ) { - assertNotNull( "Found unexpected \"error-info\" element", errorInfoVerifier ); + if ("error-info".equals(leafName)) { + assertNotNull("Found unexpected \"error-info\" element", errorInfoVerifier); errorInfoElement = leafElement; - } - else { - assertTrue( "\"error\" leaf Json element " + leafName + - " is not a Primitive", leafElement.isJsonPrimitive() ); + } else { + assertTrue("\"error\" leaf Json element " + leafName + " is not a Primitive", + leafElement.isJsonPrimitive()); - leafMap.put( leafName, leafElement.getAsString() ); + leafMap.put(leafName, leafElement.getAsString()); } } - assertEquals( "error-type", expErrorType.getErrorTypeTag(), leafMap.remove( "error-type" ) ); - assertEquals( "error-tag", expErrorTag.getTagValue(), leafMap.remove( "error-tag" ) ); + assertEquals("error-type", expErrorType.getErrorTypeTag(), leafMap.remove("error-type")); + assertEquals("error-tag", expErrorTag.getTagValue(), leafMap.remove("error-tag")); - verifyOptionalJsonLeaf( leafMap.remove( "error-message" ), expErrorMessage, "error-message" ); - verifyOptionalJsonLeaf( leafMap.remove( "error-app-tag" ), expErrorAppTag, "error-app-tag" ); + verifyOptionalJsonLeaf(leafMap.remove("error-message"), expErrorMessage, "error-message"); + verifyOptionalJsonLeaf(leafMap.remove("error-app-tag"), expErrorAppTag, "error-app-tag"); - if( !leafMap.isEmpty() ) { - fail( "Found unexpected Json leaf elements for \"error\" element: " + leafMap ); + if (!leafMap.isEmpty()) { + fail("Found unexpected Json leaf elements for \"error\" element: " + leafMap); } - if( errorInfoVerifier != null ) { - assertNotNull( "Missing \"error-info\" element", errorInfoElement ); - errorInfoVerifier.verifyJson( errorInfoElement ); + if (errorInfoVerifier != null) { + assertNotNull("Missing \"error-info\" element", errorInfoElement); + errorInfoVerifier.verifyJson(errorInfoElement); } } - void verifyOptionalJsonLeaf( final String actualValue, final String expValue, final String tagName ) { - if( expValue != null ) { - assertEquals( tagName, expValue, actualValue ); - } - else { - assertNull( "Found unexpected \"error\" leaf entry for: " + tagName, actualValue ); + void verifyOptionalJsonLeaf(final String actualValue, final String expValue, final String tagName) { + if (expValue != null) { + assertEquals(tagName, expValue, actualValue); + } else { + assertNull("Found unexpected \"error\" leaf entry for: " + tagName, actualValue); } } - void verifyXMLResponseBody( final InputStream stream, final ErrorType expErrorType, final ErrorTag expErrorTag, - final String expErrorMessage, final String expErrorAppTag, - final ErrorInfoVerifier errorInfoVerifier ) - throws Exception { + void verifyXMLResponseBody(final InputStream stream, final ErrorType expErrorType, final ErrorTag expErrorTag, + final String expErrorMessage, final String expErrorAppTag, final ErrorInfoVerifier errorInfoVerifier) + throws Exception { - Document doc = parseXMLDocument( stream ); + Document doc = parseXMLDocument(stream); - NodeList children = getXMLErrorList( doc, 1 ); + NodeList children = getXMLErrorList(doc, 1); - verifyXMLErrorNode( children.item( 0 ), expErrorType, expErrorTag, expErrorMessage, - expErrorAppTag, errorInfoVerifier ); + verifyXMLErrorNode(children.item(0), expErrorType, expErrorTag, expErrorMessage, expErrorAppTag, + errorInfoVerifier); } - private Document parseXMLDocument( final InputStream stream ) throws IOException { + private Document parseXMLDocument(final InputStream stream) throws IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setCoalescing(true); @@ -921,60 +824,57 @@ public class RestconfDocumentedExceptionMapperTest extends JerseyTest { factory.setIgnoringComments(true); ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ByteStreams.copy( stream, bos ); + ByteStreams.copy(stream, bos); - System.out.println("XML: "+bos.toString()); + System.out.println("XML: " + bos.toString()); Document doc = null; try { - doc = factory.newDocumentBuilder().parse( new ByteArrayInputStream( bos.toByteArray() ) ); - } - catch( Exception e ) { - throw new IllegalArgumentException( "Invalid XML response:\n" + bos.toString(), e ); + doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream(bos.toByteArray())); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid XML response:\n" + bos.toString(), e); } return doc; } - void verifyXMLErrorNode( final Node errorNode, final ErrorType expErrorType, final ErrorTag expErrorTag, - final String expErrorMessage, final String expErrorAppTag, - final ErrorInfoVerifier errorInfoVerifier ) throws Exception { + void verifyXMLErrorNode(final Node errorNode, final ErrorType expErrorType, final ErrorTag expErrorTag, + final String expErrorMessage, final String expErrorAppTag, final ErrorInfoVerifier errorInfoVerifier) + throws Exception { - String errorType = (String)ERROR_TYPE.evaluate( errorNode, XPathConstants.STRING ); - assertEquals( "error-type", expErrorType.getErrorTypeTag(), errorType ); + String errorType = (String) ERROR_TYPE.evaluate(errorNode, XPathConstants.STRING); + assertEquals("error-type", expErrorType.getErrorTypeTag(), errorType); - String errorTag = (String)ERROR_TAG.evaluate( errorNode, XPathConstants.STRING ); - assertEquals( "error-tag", expErrorTag.getTagValue(), errorTag ); + String errorTag = (String) ERROR_TAG.evaluate(errorNode, XPathConstants.STRING); + assertEquals("error-tag", expErrorTag.getTagValue(), errorTag); - verifyOptionalXMLLeaf( errorNode, ERROR_MESSAGE, expErrorMessage, "error-message" ); - verifyOptionalXMLLeaf( errorNode, ERROR_APP_TAG, expErrorAppTag, "error-app-tag" ); + verifyOptionalXMLLeaf(errorNode, ERROR_MESSAGE, expErrorMessage, "error-message"); + verifyOptionalXMLLeaf(errorNode, ERROR_APP_TAG, expErrorAppTag, "error-app-tag"); - Node errorInfoNode = (Node)ERROR_INFO.evaluate( errorNode, XPathConstants.NODE ); - if( errorInfoVerifier != null ) { - assertNotNull( "Missing \"error-info\" node", errorInfoNode ); + Node errorInfoNode = (Node) ERROR_INFO.evaluate(errorNode, XPathConstants.NODE); + if (errorInfoVerifier != null) { + assertNotNull("Missing \"error-info\" node", errorInfoNode); - errorInfoVerifier.verifyXML( errorInfoNode ); - } - else { - assertNull( "Found unexpected \"error-info\" node", errorInfoNode ); + errorInfoVerifier.verifyXML(errorInfoNode); + } else { + assertNull("Found unexpected \"error-info\" node", errorInfoNode); } } - void verifyOptionalXMLLeaf( final Node fromNode, final XPathExpression xpath, final String expValue, - final String tagName ) throws Exception { - if( expValue != null ) { - String actual = (String)xpath.evaluate( fromNode, XPathConstants.STRING ); - assertEquals( tagName, expValue, actual ); - } - else { - assertNull( "Found unexpected \"error\" leaf entry for: " + tagName, - xpath.evaluate( fromNode, XPathConstants.NODE ) ); + void verifyOptionalXMLLeaf(final Node fromNode, final XPathExpression xpath, final String expValue, + final String tagName) throws Exception { + if (expValue != null) { + String actual = (String) xpath.evaluate(fromNode, XPathConstants.STRING); + assertEquals(tagName, expValue, actual); + } else { + assertNull("Found unexpected \"error\" leaf entry for: " + tagName, + xpath.evaluate(fromNode, XPathConstants.NODE)); } } - NodeList getXMLErrorList( final Node fromNode, final int count ) throws Exception { - NodeList errorList = (NodeList)ERROR_LIST.evaluate( fromNode, XPathConstants.NODESET ); - assertNotNull( "Root errors node is empty", errorList ); - assertEquals( "Root errors node child count", count, errorList.getLength() ); + NodeList getXMLErrorList(final Node fromNode, final int count) throws Exception { + NodeList errorList = (NodeList) ERROR_LIST.evaluate(fromNode, XPathConstants.NODESET); + assertNotNull("Root errors node is empty", errorList); + assertEquals("Root errors node child count", count, errorList.getLength()); return errorList; } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfErrorTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfErrorTest.java index a1b8732554..f0d3fb6822 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfErrorTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfErrorTest.java @@ -1,27 +1,24 @@ /* -* 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 -*/ + * 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.impl.test; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; +import static org.opendaylight.controller.sal.common.util.RpcErrors.getRpcError; import java.util.HashMap; import java.util.Map; - import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.junit.Test; - -import static org.opendaylight.controller.sal.common.util.RpcErrors.getRpcError; - 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; @@ -40,196 +37,166 @@ public class RestconfErrorTest { private final String text; - public Contains( String text ) { + public Contains(String text) { this.text = text; } @Override - public void describeTo( Description desc ) { - desc.appendText( "contains " ).appendValue( text ); + public void describeTo(Description desc) { + desc.appendText("contains ").appendValue(text); } @Override - public boolean matches( Object arg ) { - return arg != null && arg.toString().contains( text ); + public boolean matches(Object arg) { + return arg != null && arg.toString().contains(text); } } @Test - public void testErrorTagValueOf() - { - assertEquals( ErrorTag.IN_USE, - ErrorTag.valueOfCaseInsensitive( ErrorTag.IN_USE.getTagValue() ) ); + public void testErrorTagValueOf() { + assertEquals(ErrorTag.IN_USE, ErrorTag.valueOfCaseInsensitive(ErrorTag.IN_USE.getTagValue())); } @Test - public void testErrorTagValueOfIsLowercase() - { - assertEquals( "in-use", - ErrorTag.IN_USE.getTagValue() ); + public void testErrorTagValueOfIsLowercase() { + assertEquals("in-use", ErrorTag.IN_USE.getTagValue()); } @Test - public void testErrorTypeGetErrorTypeTagIsLowerCase() - { - assertEquals( ErrorType.APPLICATION.name().toLowerCase(), - ErrorType.APPLICATION.getErrorTypeTag() ); + public void testErrorTypeGetErrorTypeTagIsLowerCase() { + assertEquals(ErrorType.APPLICATION.name().toLowerCase(), ErrorType.APPLICATION.getErrorTypeTag()); } @Test - public void testErrorTypeValueOf() - { - assertEquals( ErrorType.APPLICATION, - ErrorType.valueOfCaseInsensitive( ErrorType.APPLICATION.getErrorTypeTag() ) ); + public void testErrorTypeValueOf() { + assertEquals(ErrorType.APPLICATION, ErrorType.valueOfCaseInsensitive(ErrorType.APPLICATION.getErrorTypeTag())); } @Test - public void testErrorTagStatusCodes() - { - Map lookUpMap = new HashMap(); - - lookUpMap.put( "in-use", 409); - lookUpMap.put( "invalid-value", 400); - lookUpMap.put( "too-big", 413); - lookUpMap.put( "missing-attribute", 400); - lookUpMap.put( "bad-attribute", 400); - lookUpMap.put( "unknown-attribute", 400); - lookUpMap.put( "bad-element", 400); - lookUpMap.put( "unknown-element", 400); - lookUpMap.put( "unknown-namespace", 400); - lookUpMap.put( "access-denied", 403); - lookUpMap.put( "lock-denied", 409); - lookUpMap.put( "resource-denied", 409); - lookUpMap.put( "rollback-failed", 500); - lookUpMap.put( "data-exists", 409); - lookUpMap.put( "data-missing", 409); - lookUpMap.put( "operation-not-supported", 501); - lookUpMap.put( "operation-failed", 500); - lookUpMap.put( "partial-operation", 500); - lookUpMap.put( "malformed-message", 400); - - for( ErrorTag tag : ErrorTag.values() ) - { - Integer expectedStatusCode = lookUpMap.get( tag.getTagValue() ); - assertNotNull( "Failed to find " + tag.getTagValue(), expectedStatusCode ); - assertEquals( "Status Code does not match", expectedStatusCode, - Integer.valueOf( tag.getStatusCode() ) ); + public void testErrorTagStatusCodes() { + Map lookUpMap = new HashMap(); + + lookUpMap.put("in-use", 409); + lookUpMap.put("invalid-value", 400); + lookUpMap.put("too-big", 413); + lookUpMap.put("missing-attribute", 400); + lookUpMap.put("bad-attribute", 400); + lookUpMap.put("unknown-attribute", 400); + lookUpMap.put("bad-element", 400); + lookUpMap.put("unknown-element", 400); + lookUpMap.put("unknown-namespace", 400); + lookUpMap.put("access-denied", 403); + lookUpMap.put("lock-denied", 409); + lookUpMap.put("resource-denied", 409); + lookUpMap.put("rollback-failed", 500); + lookUpMap.put("data-exists", 409); + lookUpMap.put("data-missing", 409); + lookUpMap.put("operation-not-supported", 501); + lookUpMap.put("operation-failed", 500); + lookUpMap.put("partial-operation", 500); + lookUpMap.put("malformed-message", 400); + + for (ErrorTag tag : ErrorTag.values()) { + Integer expectedStatusCode = lookUpMap.get(tag.getTagValue()); + assertNotNull("Failed to find " + tag.getTagValue(), expectedStatusCode); + assertEquals("Status Code does not match", expectedStatusCode, Integer.valueOf(tag.getStatusCode())); } } @Test - public void testRestConfDocumentedException_NoCause() - { + public void testRestConfDocumentedException_NoCause() { String expectedMessage = "Message"; ErrorType expectedErrorType = ErrorType.RPC; ErrorTag expectedErrorTag = ErrorTag.IN_USE; - RestconfError e = - new RestconfError( expectedErrorType, - expectedErrorTag, expectedMessage ); + RestconfError e = new RestconfError(expectedErrorType, expectedErrorTag, expectedMessage); - validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag, - null, (String)null, e); + validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag, null, (String) null, e); } @Test - public void testRestConfDocumentedException_WithAppTag() - { + public void testRestConfDocumentedException_WithAppTag() { String expectedMessage = "Message"; ErrorType expectedErrorType = ErrorType.RPC; ErrorTag expectedErrorTag = ErrorTag.IN_USE; String expectedErrorAppTag = "application.tag"; - RestconfError e = - new RestconfError( expectedErrorType, - expectedErrorTag, expectedMessage, expectedErrorAppTag ); + RestconfError e = new RestconfError(expectedErrorType, expectedErrorTag, expectedMessage, expectedErrorAppTag); - validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag, - expectedErrorAppTag, (String)null, e); + validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag, expectedErrorAppTag, (String) null, + e); } @Test - public void testRestConfDocumentedException_WithAppTagErrorInfo() - { + public void testRestConfDocumentedException_WithAppTagErrorInfo() { String expectedMessage = "Message"; ErrorType expectedErrorType = ErrorType.RPC; ErrorTag expectedErrorTag = ErrorTag.IN_USE; String expectedErrorAppTag = "application.tag"; String errorInfo = "session.id"; - RestconfError e = new RestconfError( expectedErrorType, - expectedErrorTag, - expectedMessage, - expectedErrorAppTag, - errorInfo ); + RestconfError e = new RestconfError(expectedErrorType, expectedErrorTag, expectedMessage, expectedErrorAppTag, + errorInfo); - validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag, - expectedErrorAppTag, errorInfo, e); + validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag, expectedErrorAppTag, errorInfo, e); } @Test public void testRestConfErrorWithRpcError() { // All fields set - RpcError rpcError = getRpcError( "mock app-tag", ErrorTag.BAD_ATTRIBUTE.getTagValue(), - "mock error-info", RpcError.ErrorSeverity.ERROR, - "mock error-message", RpcError.ErrorType.PROTOCOL, - new Exception( "mock cause" ) ); + RpcError rpcError = getRpcError("mock app-tag", ErrorTag.BAD_ATTRIBUTE.getTagValue(), "mock error-info", + RpcError.ErrorSeverity.ERROR, "mock error-message", RpcError.ErrorType.PROTOCOL, new Exception( + "mock cause")); - validateRestConfError( "mock error-message", ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE, - "mock app-tag", "mock error-info", - new RestconfError( rpcError ) ); + validateRestConfError("mock error-message", ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE, "mock app-tag", + "mock error-info", new RestconfError(rpcError)); // All fields set except 'info' - expect error-info set to 'cause' - rpcError = getRpcError( "mock app-tag", ErrorTag.BAD_ATTRIBUTE.getTagValue(), - null, RpcError.ErrorSeverity.ERROR, - "mock error-message", RpcError.ErrorType.PROTOCOL, - new Exception( "mock cause" ) ); + rpcError = getRpcError("mock app-tag", ErrorTag.BAD_ATTRIBUTE.getTagValue(), null, + RpcError.ErrorSeverity.ERROR, "mock error-message", RpcError.ErrorType.PROTOCOL, new Exception( + "mock cause")); - validateRestConfError( "mock error-message", ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE, - "mock app-tag", new Contains( "mock cause" ), - new RestconfError( rpcError ) ); + validateRestConfError("mock error-message", ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE, "mock app-tag", + new Contains("mock cause"), new RestconfError(rpcError)); // Some fields set - expect error-info set to ErrorSeverity - rpcError = getRpcError( null, ErrorTag.ACCESS_DENIED.getTagValue(), - null, RpcError.ErrorSeverity.ERROR, - null, RpcError.ErrorType.RPC, null ); + rpcError = getRpcError(null, ErrorTag.ACCESS_DENIED.getTagValue(), null, RpcError.ErrorSeverity.ERROR, null, + RpcError.ErrorType.RPC, null); - validateRestConfError( null, ErrorType.RPC, ErrorTag.ACCESS_DENIED, - null, "error", - new RestconfError( rpcError ) ); + validateRestConfError(null, ErrorType.RPC, ErrorTag.ACCESS_DENIED, null, "error", + new RestconfError(rpcError)); - // 'tag' field not mapped to ErrorTag - expect error-tag set to OPERATION_FAILED - rpcError = getRpcError( null, "not mapped", - null, RpcError.ErrorSeverity.WARNING, - null, RpcError.ErrorType.TRANSPORT, null ); + // 'tag' field not mapped to ErrorTag - expect error-tag set to + // OPERATION_FAILED + rpcError = getRpcError(null, "not mapped", null, RpcError.ErrorSeverity.WARNING, null, + RpcError.ErrorType.TRANSPORT, null); - validateRestConfError( null, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED, - null, "warning", - new RestconfError( rpcError ) ); + validateRestConfError(null, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED, null, + "warning", new RestconfError(rpcError)); // No fields set - edge case - rpcError = getRpcError( null, null, null, null, null, null, null ); + rpcError = getRpcError(null, null, null, null, null, null, null); - validateRestConfError( null, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, - null, (String)null, new RestconfError( rpcError ) ); + validateRestConfError(null, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, null, (String) null, + new RestconfError(rpcError)); } - private void validateRestConfError(String expectedMessage, ErrorType expectedErrorType, - ErrorTag expectedErrorTag, String expectedErrorAppTag, String errorInfo, RestconfError e) { + private void validateRestConfError(String expectedMessage, ErrorType expectedErrorType, ErrorTag expectedErrorTag, + String expectedErrorAppTag, String errorInfo, RestconfError e) { - validateRestConfError( expectedMessage, expectedErrorType, expectedErrorTag, - expectedErrorAppTag, equalTo( errorInfo ), e ); + validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag, expectedErrorAppTag, + equalTo(errorInfo), e); } - private void validateRestConfError(String expectedMessage, ErrorType expectedErrorType, - ErrorTag expectedErrorTag, String expectedErrorAppTag, - Matcher errorInfoMatcher, RestconfError e) { + private void validateRestConfError(String expectedMessage, ErrorType expectedErrorType, ErrorTag expectedErrorTag, + String expectedErrorAppTag, Matcher errorInfoMatcher, RestconfError e) { - assertEquals( "getErrorMessage", expectedMessage, e.getErrorMessage() ); - assertEquals( "getErrorType", expectedErrorType, e.getErrorType() ); - assertEquals( "getErrorTag", expectedErrorTag, e.getErrorTag() ); - assertEquals( "getErrorAppTag", expectedErrorAppTag, e.getErrorAppTag() ); - assertThat( "getErrorInfo", e.getErrorInfo(), errorInfoMatcher ); - e.toString(); // really just checking for NPE etc. Don't care about contents. + assertEquals("getErrorMessage", expectedMessage, e.getErrorMessage()); + assertEquals("getErrorType", expectedErrorType, e.getErrorType()); + assertEquals("getErrorTag", expectedErrorTag, e.getErrorTag()); + assertEquals("getErrorAppTag", expectedErrorAppTag, e.getErrorAppTag()); + assertThat("getErrorInfo", e.getErrorInfo(), errorInfoMatcher); + e.toString(); // really just checking for NPE etc. Don't care about + // contents. } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfImplTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfImplTest.java index e2559f4b70..3794815c89 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfImplTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfImplTest.java @@ -16,7 +16,6 @@ import static org.mockito.Mockito.when; import java.io.FileNotFoundException; import java.util.Set; - import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -40,33 +39,27 @@ public class RestconfImplTest { @BeforeClass public static void init() throws FileNotFoundException { - Set allModules = TestUtils - .loadModulesFrom("/full-versions/yangs"); + Set allModules = TestUtils.loadModulesFrom("/full-versions/yangs"); assertNotNull(allModules); SchemaContext schemaContext = TestUtils.loadSchemaContext(allModules); - controllerContext = spy( ControllerContext.getInstance() ); + controllerContext = spy(ControllerContext.getInstance()); controllerContext.setSchemas(schemaContext); } @Before - public void initMethod() - { + public void initMethod() { restconfImpl = RestconfImpl.getInstance(); - restconfImpl.setControllerContext( controllerContext ); + restconfImpl.setControllerContext(controllerContext); } @Test public void testExample() throws FileNotFoundException { - CompositeNode loadedCompositeNode = TestUtils.readInputToCnSn( - "/parts/ietf-interfaces_interfaces.xml", + CompositeNode loadedCompositeNode = TestUtils.readInputToCnSn("/parts/ietf-interfaces_interfaces.xml", XmlToCompositeNodeProvider.INSTANCE); BrokerFacade brokerFacade = mock(BrokerFacade.class); - when(brokerFacade.readOperationalData(any(InstanceIdentifier.class))) - .thenReturn(loadedCompositeNode); - assertEquals(loadedCompositeNode, - brokerFacade.readOperationalData(null)); + when(brokerFacade.readOperationalData(any(InstanceIdentifier.class))).thenReturn(loadedCompositeNode); + assertEquals(loadedCompositeNode, brokerFacade.readOperationalData(null)); } - } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/TestUtils.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/TestUtils.java index 449b79923e..ed1529540d 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/TestUtils.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/TestUtils.java @@ -147,10 +147,9 @@ public final class TestUtils { /** * - * 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} + * 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} */ public static void normalizeCompositeNode(CompositeNode compositeNode, Set modules, String schemaNodePath) { RestconfImpl restconf = RestconfImpl.getInstance(); @@ -161,9 +160,8 @@ public final class TestUtils { } /** - * 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. + * 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. * */ public static Module resolveModule(String searchedModuleName, Set modules) { @@ -279,8 +277,8 @@ public final class TestUtils { ControllerContext.getInstance().setSchemas(loadSchemaContext(modules)); - messageBodyWriter.writeTo(new StructuredData(compositeNode, dataSchemaNode, null), null, null, null, null, null, - byteArrayOS); + messageBodyWriter.writeTo(new StructuredData(compositeNode, dataSchemaNode, null), null, null, null, null, + null, byteArrayOS); return byteArrayOS.toString(); } @@ -298,7 +296,7 @@ public final class TestUtils { return result.toString(); } - private static Pattern patternForStringsSeparatedByWhiteChars(String ... substrings ) { + private static Pattern patternForStringsSeparatedByWhiteChars(String... substrings) { StringBuilder pattern = new StringBuilder(); pattern.append(".*"); for (String substring : substrings) { @@ -309,7 +307,7 @@ public final class TestUtils { return Pattern.compile(pattern.toString(), Pattern.DOTALL); } - public static boolean containsStringData(String jsonOutput,String ...substrings ) { + public static boolean containsStringData(String jsonOutput, String... substrings) { Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings); Matcher matcher = pattern.matcher(jsonOutput); return matcher.matches(); diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/URITest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/URITest.java index efdb7b240c..18703040ee 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/URITest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/URITest.java @@ -15,10 +15,8 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.google.common.collect.Iterables; - import java.io.FileNotFoundException; import java.util.Set; - import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnInstanceIdentifierTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnInstanceIdentifierTest.java index 5476d71320..0799fdcff8 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnInstanceIdentifierTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnInstanceIdentifierTest.java @@ -15,9 +15,7 @@ import java.io.IOException; import java.net.URISyntaxException; import java.util.List; 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; diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnLeafRefTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnLeafRefTest.java index e5a737e6d5..483d90da0d 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnLeafRefTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnLeafRefTest.java @@ -11,9 +11,7 @@ import static org.junit.Assert.assertEquals; 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; diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/YangAndXmlAndDataSchemaLoader.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/YangAndXmlAndDataSchemaLoader.java index d5759bedb1..efcc3743c6 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/YangAndXmlAndDataSchemaLoader.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/YangAndXmlAndDataSchemaLoader.java @@ -11,7 +11,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.Set; - import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.Module; diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/structures/LstItem.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/structures/LstItem.java index 3617ed9fb0..ae07571ad9 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/structures/LstItem.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/structures/LstItem.java @@ -8,6 +8,7 @@ package org.opendaylight.controller.sal.restconf.impl.test.structures; import static org.junit.Assert.assertFalse; + import java.util.HashMap; import java.util.Map; @@ -57,14 +58,12 @@ public class LstItem { } public void addLfLst(LfLst lfLst) { - assertFalse( "Found multiple leaf list elements for " + lfLst.getName(), - lfLsts.containsKey( lfLst.getName() ) ); + assertFalse("Found multiple leaf list elements for " + lfLst.getName(), lfLsts.containsKey(lfLst.getName())); lfLsts.put(lfLst.getName(), lfLst); } public void addLst(Lst lst) { - assertFalse( "Found multiple list elements for " + lst.getName(), - lsts.containsKey( lst.getName() ) ); + assertFalse("Found multiple list elements for " + lst.getName(), lsts.containsKey(lst.getName())); lsts.put(lst.getName(), lst); } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/websockets/client/WebSocketClient.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/websockets/client/WebSocketClient.java index 845d54ea1f..664aad6578 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/websockets/client/WebSocketClient.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/websockets/client/WebSocketClient.java @@ -23,15 +23,13 @@ import io.netty.handler.codec.http.websocketx.PingWebSocketFrame; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory; import io.netty.handler.codec.http.websocketx.WebSocketVersion; - import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URI; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class WebSocketClient { +public class WebSocketClient { private final URI uri; private Bootstrap bootstrap = new Bootstrap();; @@ -40,51 +38,57 @@ public class WebSocketClient { private Channel clientChannel; private final EventLoopGroup group = new NioEventLoopGroup(); - public WebSocketClient(URI uri,IClientMessageCallback clientMessageCallback) { + public WebSocketClient(URI uri, IClientMessageCallback clientMessageCallback) { this.uri = uri; - clientHandler = new WebSocketClientHandler( - WebSocketClientHandshakerFactory.newHandshaker( - uri, WebSocketVersion.V13, null, false,null),clientMessageCallback); // last null could be replaced with DefaultHttpHeaders + clientHandler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, + WebSocketVersion.V13, null, false, null), clientMessageCallback); // last + // null + // could + // be + // replaced + // with + // DefaultHttpHeaders initialize(); } - private void initialize(){ + + private void initialize() { String protocol = uri.getScheme(); if (!"http".equals(protocol)) { throw new IllegalArgumentException("Unsupported protocol: " + protocol); } - bootstrap.group(group) - .channel(NioSocketChannel.class) - .handler(new ChannelInitializer() { - @Override - public void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); - pipeline.addLast("http-codec", new HttpClientCodec()); - pipeline.addLast("aggregator", new HttpObjectAggregator(8192)); - pipeline.addLast("ws-handler", clientHandler); - } - }); + bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer() { + @Override + public void initChannel(SocketChannel ch) throws Exception { + ChannelPipeline pipeline = ch.pipeline(); + pipeline.addLast("http-codec", new HttpClientCodec()); + pipeline.addLast("aggregator", new HttpObjectAggregator(8192)); + pipeline.addLast("ws-handler", clientHandler); + } + }); } - public void connect() throws InterruptedException{ + + public void connect() throws InterruptedException { System.out.println("WebSocket Client connecting"); - clientChannel = bootstrap.connect(uri.getHost(), uri.getPort()).sync().channel(); + clientChannel = bootstrap.connect(uri.getHost(), uri.getPort()).sync().channel(); clientHandler.handshakeFuture().sync(); } - public void writeAndFlush(String message){ + public void writeAndFlush(String message) { clientChannel.writeAndFlush(new TextWebSocketFrame(message)); } - public void writeAndFlush(Object message){ + + public void writeAndFlush(Object message) { clientChannel.writeAndFlush(message); } - public void ping(){ - clientChannel.writeAndFlush(new PingWebSocketFrame(Unpooled.copiedBuffer(new byte[]{1, 2, 3, 4, 5, 6}))); + public void ping() { + clientChannel.writeAndFlush(new PingWebSocketFrame(Unpooled.copiedBuffer(new byte[] { 1, 2, 3, 4, 5, 6 }))); } public void close(String reasonText) throws InterruptedException { - CloseWebSocketFrame closeWebSocketFrame = new CloseWebSocketFrame(1000,reasonText); + CloseWebSocketFrame closeWebSocketFrame = new CloseWebSocketFrame(1000, reasonText); clientChannel.writeAndFlush(closeWebSocketFrame); // WebSocketClientHandler will close the connection when the server @@ -122,7 +126,7 @@ public class WebSocketClient { @Override public void onMessageReceived(Object message) { if (message instanceof TextWebSocketFrame) { - logger.info("received message {}"+ ((TextWebSocketFrame)message).text()); + logger.info("received message {}" + ((TextWebSocketFrame) message).text()); } } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/websockets/client/WebSocketClientHandler.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/websockets/client/WebSocketClientHandler.java index 0a16e254cc..e07d8c48f0 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/websockets/client/WebSocketClientHandler.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/websockets/client/WebSocketClientHandler.java @@ -18,7 +18,6 @@ import io.netty.handler.codec.http.websocketx.PongWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker; import io.netty.handler.codec.http.websocketx.WebSocketFrame; import io.netty.util.CharsetUtil; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -29,8 +28,7 @@ public class WebSocketClientHandler extends SimpleChannelInboundHandler private ChannelPromise handshakeFuture; private final IClientMessageCallback messageListener; - - public WebSocketClientHandler(WebSocketClientHandshaker handshaker,IClientMessageCallback listener) { + public WebSocketClientHandler(WebSocketClientHandshaker handshaker, IClientMessageCallback listener) { this.handshaker = handshaker; this.messageListener = listener; } @@ -92,4 +90,3 @@ public class WebSocketClientHandler extends SimpleChannelInboundHandler ctx.close(); } } - diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/websockets/test/RestStream.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/websockets/test/RestStream.java index d9ef2ef243..70f0f050dc 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/websockets/test/RestStream.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/websockets/test/RestStream.java @@ -15,12 +15,10 @@ import static org.mockito.Mockito.mock; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.net.URI; - import javax.ws.rs.client.Entity; import javax.ws.rs.core.Application; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.BeforeClass; @@ -55,10 +53,10 @@ public class RestStream extends JerseyTest { @Override protected Application configure() { /* enable/disable Jersey logs to console */ -// enable(TestProperties.LOG_TRAFFIC); -// enable(TestProperties.DUMP_ENTITY); -// enable(TestProperties.RECORD_LOG_LEVEL); -// set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue()); + // enable(TestProperties.LOG_TRAFFIC); + // enable(TestProperties.DUMP_ENTITY); + // enable(TestProperties.RECORD_LOG_LEVEL); + // set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue()); ResourceConfig resourceConfig = new ResourceConfig(); resourceConfig = resourceConfig.registerInstances(restconfImpl, StructuredDataToXmlProvider.INSTANCE, StructuredDataToJsonProvider.INSTANCE, XmlToCompositeNodeProvider.INSTANCE, @@ -72,13 +70,15 @@ public class RestStream extends JerseyTest { Response responseWithStreamName = post(uri, MediaType.APPLICATION_XML, getRpcInput()); String xmlResponse = responseWithStreamName.readEntity(String.class); assertNotNull(xmlResponse); - assertTrue(xmlResponse.contains("ietf-interfaces:interfaces/ietf-interfaces:interface/eth0")); + assertTrue(xmlResponse + .contains("ietf-interfaces:interfaces/ietf-interfaces:interface/eth0")); uri = "/streams/stream/ietf-interfaces:interfaces/ietf-interfaces:interface/eth0"; Response responseWithRedirectionUri = get(uri, MediaType.APPLICATION_XML); final URI websocketServerUri = responseWithRedirectionUri.getLocation(); assertNotNull(websocketServerUri); - assertEquals(websocketServerUri.toString(), "http://localhost:8181/ietf-interfaces:interfaces/ietf-interfaces:interface/eth0"); + assertEquals(websocketServerUri.toString(), + "http://localhost:8181/ietf-interfaces:interfaces/ietf-interfaces:interface/eth0"); } private Response post(String uri, String mediaType, String data) { diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlAugmentedElementToCnSnTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlAugmentedElementToCnSnTest.java index 62159ccad6..5a5a621d93 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlAugmentedElementToCnSnTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlAugmentedElementToCnSnTest.java @@ -10,7 +10,6 @@ package org.opendaylight.controller.sal.restconf.impl.xml.to.cnsn.test; import static org.junit.Assert.assertNotNull; 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; @@ -21,13 +20,12 @@ 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"); + 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) { - CompositeNode compNode = TestUtils.readInputToCnSn(xmlPath, false, - XmlToCompositeNodeProvider.INSTANCE); + CompositeNode compNode = TestUtils.readInputToCnSn(xmlPath, false, XmlToCompositeNodeProvider.INSTANCE); assertNotNull(compNode); Set modules = TestUtils.loadModulesFrom(yangPath); @@ -35,5 +33,4 @@ public class XmlAugmentedElementToCnSnTest { TestUtils.normalizeCompositeNode(compNode, modules, topLevelElementName + ":" + moduleName); } - } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlLeafrefToCnSnTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlLeafrefToCnSnTest.java index e5b0bf507d..6c11bc1861 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlLeafrefToCnSnTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlLeafrefToCnSnTest.java @@ -13,7 +13,6 @@ 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; @@ -30,8 +29,7 @@ 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. + * top level element represents container. second level element is list with two elements. */ @Test public void testXmlDataContainer() { @@ -202,8 +200,7 @@ public class XmlLeafrefToCnSnTest { /** * - * Test case like identity + * Test case like identity */ @Test @@ -214,8 +211,7 @@ public class XmlLeafrefToCnSnTest { /** * - * Test case like identity + * Test case like identity */ @Test public void testIdentityrefDefaultNmspcInParrentElement() { @@ -225,8 +221,7 @@ public class XmlLeafrefToCnSnTest { /** * - * Test case like - * x:identity + * Test case like x:identity */ @Ignore @Test @@ -237,8 +232,7 @@ public class XmlLeafrefToCnSnTest { /** * - * Test case like (without namespace in xml) x:identity - * + * Test case like (without namespace in xml) x:identity */ @Test public void testIdentityrefNoNmspcValueWithPrefix() { @@ -248,8 +242,7 @@ public class XmlLeafrefToCnSnTest { /** * - * Test case like (without namespace in xml) identity - * + * Test case like (without namespace in xml) identity */ @Test public void testIdentityrefNoNmspcValueWithoutPrefix() { @@ -322,8 +315,8 @@ public class XmlLeafrefToCnSnTest { 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) { + private void testIdentityrefToCnSn(final String xmlPath, final String yangPath, final String moduleName, + final String schemaName, final int moduleCount, final String resultLocalName, final String resultNamespace) { CompositeNode compositeNode = TestUtils.readInputToCnSn(xmlPath, false, XmlToCompositeNodeProvider.INSTANCE); assertNotNull(compositeNode); diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlToCnSnTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlToCnSnTest.java index 5cda4a7f52..e2621d635b 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlToCnSnTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlToCnSnTest.java @@ -14,7 +14,6 @@ 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; @@ -57,26 +56,26 @@ public class XmlToCnSnTest extends YangAndXmlAndDataSchemaLoader { } @Test - public void testXmlBlankInput() throws Exception{ - InputStream inputStream = new ByteArrayInputStream( "".getBytes() ); - CompositeNode compositeNode = - XmlToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null, inputStream); + public void testXmlBlankInput() throws Exception { + InputStream inputStream = new ByteArrayInputStream("".getBytes()); + CompositeNode compositeNode = XmlToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null, + inputStream); - assertNull( compositeNode ); + assertNull(compositeNode); } @Test - public void testXmlBlankInputUnmarkableStream() throws Exception{ - InputStream inputStream = new ByteArrayInputStream( "".getBytes() ){ + public void testXmlBlankInputUnmarkableStream() throws Exception { + InputStream inputStream = new ByteArrayInputStream("".getBytes()) { @Override public boolean markSupported() { return false; } }; - CompositeNode compositeNode = - XmlToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null, inputStream); + CompositeNode compositeNode = XmlToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null, + inputStream); - assertNull( compositeNode ); + assertNull(compositeNode); } }