No changes in function of code, just formatting.
Change-Id: I52bf10a3b84fa61ec35c31145acbbc6b9bf349ec
Signed-off-by: Jozef Gloncak <jgloncak@cisco.com>
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 {
}
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.
* <ul>
* <li><b>/restconf</b> - {@link #getRoot()}
* <ul>
- * <li><b>/config</b> - {@link #readConfigurationData(String)}
- * {@link #updateConfigurationData(String, CompositeNode)}
- * {@link #createConfigurationData(CompositeNode)}
- * {@link #createConfigurationData(String, CompositeNode)}
+ * <li><b>/config</b> - {@link #readConfigurationData(String)} {@link #updateConfigurationData(String, CompositeNode)}
+ * {@link #createConfigurationData(CompositeNode)} {@link #createConfigurationData(String, CompositeNode)}
* {@link #deleteConfigurationData(String)}
* <li><b>/operational</b> - {@link #readOperationalData(String)}
* <li>/modules - {@link #getModules()}
* <ul>
* <li>/module
* </ul>
- * <li><b>/operations</b> - {@link #invokeRpc(String, CompositeNode)}
- * {@link #invokeRpc(String, CompositeNode)}
+ * <li><b>/operations</b> - {@link #invokeRpc(String, CompositeNode)} {@link #invokeRpc(String, CompositeNode)}
* <li>/version (field)
* </ul>
* </ul>
@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:.+}")
@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:.+}")
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.sal.rest.api;
+
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 {
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;
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<QName> foundLists = new HashSet<>();
- Set<DataSchemaNode> parentSchemaChildNodes = parentSchema == null ?
- Collections.<DataSchemaNode>emptySet() : parentSchema.getChildNodes();
-
+ Set<DataSchemaNode> parentSchemaChildNodes = parentSchema == null ? Collections.<DataSchemaNode> 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<SimpleNode<?>> nodeLeafList = parent.getSimpleNodesByName( node.getNodeType() );
- if( nodeLeafList.size() == 1 ) {
- writeName( node, null, writer );
- writeValue( writer, node.getValue() );
- }
- else { // more than 1, write as a json array
- writeName( node, null, writer );
+ private void handleNoSchemaFound(final JsonWriter writer, final Node<?> node, final CompositeNode parent)
+ throws IOException {
+ if (node instanceof SimpleNode<?>) {
+ List<SimpleNode<?>> nodeLeafList = parent.getSimpleNodesByName(node.getNodeType());
+ if (nodeLeafList.size() == 1) {
+ writeName(node, null, writer);
+ writeValue(writer, node.getValue());
+ } else { // more than 1, write as a json array
+ writeName(node, null, writer);
writer.beginArray();
- for( SimpleNode<?> leafNode: nodeLeafList ) {
- writeValue( writer, leafNode.getValue() );
+ 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<CompositeNode> nodeList = parent.getCompositesByName( node.getNodeType() );
- if( nodeList.size() == 1 ) {
- writeContainer( writer, (CompositeNode) node, null );
- }
- else { // more than 1, write as a json array
- writeList( writer, parent, (CompositeNode) node, null );
+ List<CompositeNode> nodeList = parent.getCompositesByName(node.getNodeType());
+ if (nodeList.size() == 1) {
+ writeContainer(writer, (CompositeNode) node, null);
+ } else { // more than 1, write as a json array
+ writeList(writer, parent, (CompositeNode) node, null);
}
}
}
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();
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) {
}
}
- 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('/');
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 {
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) {
@Provider
@Consumes({ Draft02.MediaTypes.DATA + RestconfService.JSON, Draft02.MediaTypes.OPERATION + RestconfService.JSON,
- MediaType.APPLICATION_JSON })
+ MediaType.APPLICATION_JSON })
public enum JsonToCompositeNodeProvider implements MessageBodyReader<CompositeNode> {
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<CompositeNode> type, final Type genericType,
- final Annotation[] annotations, final MediaType mediaType,
- final MultivaluedMap<String, String> httpHeaders,
- final InputStream entityStream)
- throws IOException, WebApplicationException {
+ final Annotation[] annotations, final MediaType mediaType,
+ final MultivaluedMap<String, String> 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);
}
}
}
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;
}
- 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;
throw new UnsupportedFormatException("Root element of Json has to be Object");
}
- Set<Entry<String, JsonElement>> entrySetsOfRootJsonObject =
- rootElement.getAsJsonObject().entrySet();
+ Set<Entry<String, JsonElement>> entrySetsOfRootJsonObject = rootElement.getAsJsonObject().entrySet();
if (entrySetsOfRootJsonObject.size() != 1) {
throw new UnsupportedFormatException("Json Object should contain one element");
}
"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<String, JsonElement> childOfFirstNode : rootObject.entrySet()) {
}
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));
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;
}
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;
}
*/
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<Class<?>> getClasses() {
- return ImmutableSet.<Class<?>>of( RestconfDocumentedExceptionMapper.class );
+ return ImmutableSet.<Class<?>> of(RestconfDocumentedExceptionMapper.class);
}
@Override
return singletons;
}
-
}
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;
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;
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;
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<RestconfDocumentedException> {
- 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
List<MediaType> 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<RestconfError> 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<Node<?>> errorNodes = ImmutableList.<Node<?>> 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<ImmutableCompositeNode> 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 <error-info> 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 <error-info> element.
- String errorInfoWithRoot =
- new StringBuilder( "<error-info xmlns=\"" ).append( NAMESPACE ).append( "\">" )
- .append( errorInfo ).append( "</error-info>" ).toString();
+ String errorInfoWithRoot = new StringBuilder("<error-info xmlns=\"").append(NAMESPACE).append("\">")
+ .append(errorInfo).append("</error-info>").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
// locate the schema.
ImmutableList.Builder<Node<?>> childNodes = ImmutableList.builder();
- for( Entry<QName, List<Node<?>>> entry: compositeNode.entrySet() ) {
- childNodes.addAll( entry.getValue() );
+ for (Entry<QName, List<Node<?>>> 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<ImmutableCompositeNode> builder, final QName qname,
- final String value ) {
- if( !Strings.isNullOrEmpty( value ) ) {
- builder.addLeaf( qname, value );
+ private void addLeaf(final CompositeNodeBuilder<ImmutableCompositeNode> builder, final QName qname,
+ final String value) {
+ if (!Strings.isNullOrEmpty(value)) {
+ builder.addLeaf(qname, value);
}
}
}
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;
@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");
@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<StructuredData> {
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<String, Object> 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<String, Object> httpHeaders, final OutputStream entityStream) throws IOException,
+ WebApplicationException {
CompositeNode data = t.getData();
if (data == null) {
throw new RestconfDocumentedException(Response.Status.NOT_FOUND);
@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<StructuredData> {
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<String, Object> 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<String, Object> httpHeaders, final OutputStream entityStream) throws IOException,
+ WebApplicationException {
CompositeNode data = t.getData();
if (data == null) {
throw new RestconfDocumentedException(Response.Status.NOT_FOUND);
trans.setOutputProperty(OutputKeys.INDENT, "no");
}
} catch (RuntimeException e) {
- throw new RestconfDocumentedException(e.getMessage(), ErrorType.TRANSPORT,
- ErrorTag.OPERATION_FAILED);
+ throw new RestconfDocumentedException(e.getMessage(), ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED);
}
// FIXME: BUG-1281: eliminate the intermediate Document
trans.transform(new DOMSource(domTree), new StreamResult(entityStream));
} catch (TransformerException e) {
LOG.error("Error during translation of Document to OutputStream", e);
- throw new RestconfDocumentedException(e.getMessage(), ErrorType.TRANSPORT,
- ErrorTag.OPERATION_FAILED);
+ throw new RestconfDocumentedException(e.getMessage(), ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED);
}
}
*/
package org.opendaylight.controller.sal.rest.impl;
+import com.google.common.base.Optional;
import javax.activation.UnsupportedDataTypeException;
-
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
import org.opendaylight.yangtools.yang.data.api.codec.LeafrefCodec;
import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
import org.opendaylight.yangtools.yang.model.util.Leafref;
import org.w3c.dom.Document;
-import com.google.common.base.Optional;
-
public class XmlMapper {
private static final LeafrefCodecImpl LEAFREF_DEFAULT_CODEC = new LeafrefCodecImpl(
Optional.<LeafrefTypeDefinition> absent());
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)) {
}
/**
- * 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
* 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
import org.slf4j.LoggerFactory;
public class BrokerFacade implements DataReader<InstanceIdentifier, CompositeNode> {
- 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();
private BrokerFacade() {
}
- public void setContext( final ConsumerSession context ) {
+ public void setContext(final ConsumerSession context) {
this.context = context;
}
- public void setDataService( final DataBrokerService dataService ) {
+ public void setDataService(final DataBrokerService dataService) {
this.dataService = dataService;
}
}
private void checkPreconditions() {
- if( context == null || dataService == null ) {
- throw new RestconfDocumentedException( Status.SERVICE_UNAVAILABLE );
+ if (context == null || dataService == null) {
+ throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
}
}
@Override
- public CompositeNode readConfigurationData( final InstanceIdentifier path ) {
+ public CompositeNode readConfigurationData(final InstanceIdentifier path) {
this.checkPreconditions();
- LOG.trace( "Read Configuration via Restconf: {}", path );
+ LOG.trace("Read Configuration via Restconf: {}", path);
- return dataService.readConfigurationData( path );
+ return dataService.readConfigurationData(path);
}
- public CompositeNode readConfigurationDataBehindMountPoint( final MountInstance mountPoint,
- final InstanceIdentifier path ) {
+ public CompositeNode readConfigurationDataBehindMountPoint(final MountInstance mountPoint,
+ final InstanceIdentifier path) {
this.checkPreconditions();
- LOG.trace( "Read Configuration via Restconf: {}", path );
+ LOG.trace("Read Configuration via Restconf: {}", path);
- return mountPoint.readConfigurationData( path );
+ return mountPoint.readConfigurationData(path);
}
@Override
- public CompositeNode readOperationalData( final InstanceIdentifier path ) {
+ public CompositeNode readOperationalData(final InstanceIdentifier path) {
this.checkPreconditions();
- BrokerFacade.LOG.trace( "Read Operational via Restconf: {}", path );
+ BrokerFacade.LOG.trace("Read Operational via Restconf: {}", path);
- return dataService.readOperationalData( path );
+ return dataService.readOperationalData(path);
}
- public CompositeNode readOperationalDataBehindMountPoint( final MountInstance mountPoint,
- final InstanceIdentifier path ) {
+ public CompositeNode readOperationalDataBehindMountPoint(final MountInstance mountPoint,
+ final InstanceIdentifier path) {
this.checkPreconditions();
- BrokerFacade.LOG.trace( "Read Operational via Restconf: {}", path );
+ BrokerFacade.LOG.trace("Read Operational via Restconf: {}", path);
- return mountPoint.readOperationalData( path );
+ return mountPoint.readOperationalData(path);
}
- public Future<RpcResult<CompositeNode>> invokeRpc( final QName type, final CompositeNode payload ) {
+ public Future<RpcResult<CompositeNode>> invokeRpc(final QName type, final CompositeNode payload) {
this.checkPreconditions();
- return context.rpc( type, payload );
+ return context.rpc(type, payload);
}
- public Future<RpcResult<TransactionStatus>> commitConfigurationDataPut( final InstanceIdentifier path,
- final CompositeNode payload ) {
+ public Future<RpcResult<TransactionStatus>> 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<RpcResult<TransactionStatus>> 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<RpcResult<TransactionStatus>> commitConfigurationDataPost( final InstanceIdentifier path,
- final CompositeNode payload) {
+ public Future<RpcResult<TransactionStatus>> 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<RpcResult<TransactionStatus>> 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<RpcResult<TransactionStatus>> commitConfigurationDataDelete( final InstanceIdentifier path ) {
+ public Future<RpcResult<TransactionStatus>> commitConfigurationDataDelete(final InstanceIdentifier path) {
this.checkPreconditions();
- return deleteDataAtTarget(path,dataService.beginTransaction());
+ return deleteDataAtTarget(path, dataService.beginTransaction());
}
public Future<RpcResult<TransactionStatus>> 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<RpcResult<TransactionStatus>> deleteDataAtTarget(final InstanceIdentifier path,
return transaction.commit();
}
- public void registerToListenDataChanges( final ListenerAdapter listener ) {
+ public void registerToListenDataChanges(final ListenerAdapter listener) {
this.checkPreconditions();
- if( listener.isListening() ) {
+ if (listener.isListening()) {
return;
}
InstanceIdentifier path = listener.getPath();
- final ListenerRegistration<DataChangeListener> registration =
- dataService.registerDataChangeListener( path, listener );
+ final ListenerRegistration<DataChangeListener> registration = dataService.registerDataChangeListener(path,
+ listener);
- listener.setRegistration( registration );
+ listener.setRegistration(registration);
}
}
package org.opendaylight.controller.sal.restconf.impl;
import com.google.common.base.Preconditions;
-
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
-
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
import org.opendaylight.yangtools.yang.data.api.ModifyAction;
import 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;
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;
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();
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;
}
}
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<String> pathArgs = urlPathArgsDecode( SLASH_SPLITTER.split( restconfInstance ) );
- omitFirstAndLastEmptyString( pathArgs );
- if( pathArgs.isEmpty() ) {
+ final List<String> 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<String> omitFirstAndLastEmptyString( final List<String> list ) {
- if( list.isEmpty() ) {
+ private static List<String> omitFirstAndLastEmptyString(final List<String> 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<Module> filter = new Predicate<Module>() {
@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<Module> modules = Iterables.filter( schema.getModules(), filter );
- return this.filterLatestModule( modules );
+ Iterable<Module> modules = Iterables.filter(schema.getModules(), filter);
+ return this.filterLatestModule(modules);
}
- private Module filterLatestModule( final Iterable<Module> modules ) {
+ private Module filterLatestModule(final Iterable<Module> 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<Module> moduleSchemas = globalSchema.findModuleByNamespace( namespace );
- return moduleSchemas == null ? null : this.filterLatestModule( moduleSchemas );
+ final Set<Module> 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<Module> moduleSchemas = mountPointSchema == null ? null :
- mountPointSchema.findModuleByNamespace( namespace );
- return moduleSchemas == null ? null : this.filterLatestModule( moduleSchemas );
+ Set<Module> 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<PathArgument> 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;
return node;
}
- public String toFullRestconfIdentifier( final InstanceIdentifier path ) {
+ public String toFullRestconfIdentifier(final InstanceIdentifier path) {
this.checkPreconditions();
final Iterable<PathArgument> 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<Module> getAllModules( final MountInstance mountPoint ) {
+ public Set<Module> getAllModules(final MountInstance mountPoint) {
this.checkPreconditions();
SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
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;
}
final Predicate<GroupingDefinition> filter = new Predicate<GroupingDefinition>() {
@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);
}
};
final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
- List<DataSchemaNode> instanceDataChildrenByName =
- this.findInstanceDataChildrenByName(restconfGrouping,
- Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
+ List<DataSchemaNode> 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;
}
final Predicate<GroupingDefinition> filter = new Predicate<GroupingDefinition>() {
@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);
}
};
final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
- List<DataSchemaNode> instanceDataChildrenByName =
- this.findInstanceDataChildrenByName(restconfGrouping,
- Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
+ List<DataSchemaNode> 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<DataSchemaNode> instances =
- this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer),
- Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
+ List<DataSchemaNode> 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<DataSchemaNode> instances =
- this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer),
- Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
+ } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
+ List<DataSchemaNode> 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<DataSchemaNode> instances =
- this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer),
- Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
+ } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
+ List<DataSchemaNode> 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<DataSchemaNode> instances =
- this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer),
- Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
+ } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
+ List<DataSchemaNode> 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<DataSchemaNode> instances =
- this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer),
- Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
+ } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
+ List<DataSchemaNode> 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<DataSchemaNode> instances =
- this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer),
- Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
+ } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
+ List<DataSchemaNode> 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;
}
}
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;
}
}
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<String> strings, final DataNodeContainer parentNode, final MountInstance mountPoint,
- final boolean returnJustMountPoint ) {
- Preconditions.<List<String>> checkNotNull( strings );
+ final boolean returnJustMountPoint) {
+ Preconditions.<List<String>> 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<String> subList = strings.subList( 1, strings.size() );
- return this.collectPathArguments( InstanceIdentifier.builder(), subList, moduleBehindMountPoint,
- mount, returnJustMountPoint );
+ List<String> 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<DataSchemaNode> potentialSchemaNodes =
- this.findInstanceDataChildrenByName( parentNode, nodeName );
- if( potentialSchemaNodes.size() > 1 ) {
+ final List<DataSchemaNode> 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<String> uriKeyValues = strings.subList( consumed, consumed + keysSize );
+ final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
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<String> remaining = strings.subList( consumed, strings.size() );
- return this.collectPathArguments( builder, remaining,
- ((DataNodeContainer) targetNode), mountPoint, returnJustMountPoint );
+ if ((targetNode instanceof DataNodeContainer)) {
+ final List<String> 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.<URI> checkNotNull( namespace );
+ public DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
+ final URI namespace) {
+ Preconditions.<URI> checkNotNull(namespace);
- final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName( container, name );
+ final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(container, name);
Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
@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<DataSchemaNode> result = Iterables.filter( potentialSchemaNodes, filter );
- return Iterables.getFirst( result, null );
+ Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
+ return Iterables.getFirst(result, null);
}
- public List<DataSchemaNode> findInstanceDataChildrenByName( final DataNodeContainer container,
- final String name ) {
- Preconditions.<DataNodeContainer> checkNotNull( container );
- Preconditions.<String> checkNotNull( name );
+ public List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
+ Preconditions.<DataNodeContainer> checkNotNull(container);
+ Preconditions.<String> checkNotNull(name);
List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
- this.collectInstanceDataNodeContainers( instantiatedDataNodeContainers, container, name );
+ this.collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
return instantiatedDataNodeContainers;
}
- private void collectInstanceDataNodeContainers( final List<DataSchemaNode> potentialSchemaNodes,
- final DataNodeContainer container, final String name ) {
+ private void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
+ final DataNodeContainer container, final String name) {
Set<DataSchemaNode> childNodes = container.getChildNodes();
Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
@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<DataSchemaNode> nodes = Iterables.filter( childNodes, filter );
+ Iterable<DataSchemaNode> 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<ChoiceNode> choiceNodes = Iterables.<ChoiceNode> filter( container.getChildNodes(),
- ChoiceNode.class );
+ Iterable<ChoiceNode> choiceNodes = Iterables.<ChoiceNode> filter(container.getChildNodes(), ChoiceNode.class);
- final Function<ChoiceNode, Set<ChoiceCaseNode>> choiceFunction =
- new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
+ final Function<ChoiceNode, Set<ChoiceCaseNode>> choiceFunction = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
@Override
- public Set<ChoiceCaseNode> apply( final ChoiceNode node ) {
+ public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
return node.getCases();
}
};
- Iterable<Set<ChoiceCaseNode>> map = Iterables.<ChoiceNode, Set<ChoiceCaseNode>> transform(
- choiceNodes, choiceFunction );
+ Iterable<Set<ChoiceCaseNode>> map = Iterables.<ChoiceNode, Set<ChoiceCaseNode>> transform(choiceNodes,
+ choiceFunction);
- final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat( map );
- for( final ChoiceCaseNode caze : allCases ) {
- this.collectInstanceDataNodeContainers( potentialSchemaNodes, caze, name );
+ final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> 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<QName, Object> map, final DataSchemaNode node,
- final String uriValue, final MountInstance mountPoint ) {
- Preconditions.<String> checkNotNull( uriValue );
- Preconditions.checkArgument( (node instanceof LeafSchemaNode) );
+ private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
+ final MountInstance mountPoint) {
+ Preconditions.<String> checkNotNull(uriValue);
+ Preconditions.checkArgument((node instanceof LeafSchemaNode));
- final String urlDecoded = urlPathArgDecode( uriValue );
+ final String urlDecoded = urlPathArgDecode(uriValue);
final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
- Codec<Object, Object> codec = RestCodec.from( typedef, mountPoint );
+ Codec<Object, Object> 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<? extends Object> baseType = RestUtil.resolveBaseTypeFrom( typedef );
- if( (baseType instanceof IdentityrefTypeDefinition) ) {
- decoded = this.toQName( urlDecoded );
+ if (decoded == null) {
+ TypeDefinition<? extends Object> 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.<String> checkNotNull( str );
- if( str.indexOf( ':' ) != -1 ) {
- final Iterable<String> args = COLON_SPLITTER.split( str );
- if( Iterables.size( args ) == 2 ) {
+ private static String toModuleName(final String str) {
+ Preconditions.<String> checkNotNull(str);
+ if (str.indexOf(':') != -1) {
+ final Iterable<String> 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<String> 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<String> 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<Module> modules = globalSchema.getModules();
final Comparator<Module> comparator = new Comparator<Module>() {
@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<Module> sorted = new ArrayList<Module>( modules );
- Collections.<Module> sort( new ArrayList<Module>( modules ), comparator );
+ List<Module> sorted = new ArrayList<Module>(modules);
+ Collections.<Module> sort(new ArrayList<Module>(modules), comparator);
final Function<Module, QName> transform = new Function<Module, QName>() {
@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<QName> findFirst = new Predicate<QName>() {
@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<QName> namespace = FluentIterable.from( sorted )
- .transform( transform )
- .firstMatch( findFirst );
- return namespace.isPresent() ? QName.create( namespace.get(), node ) : null;
+ Optional<QName> 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<RpcDefinition> _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<String> urlPathArgsDecode( final Iterable<String> strings ) {
+ public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
try {
List<String> decodedPathArgs = new ArrayList<String>();
- 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.<Object> 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.<Object> 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<QName, Object> keyValues = argument.getKeyValues();
StringBuilder builder = new StringBuilder();
- builder.append( "/" );
- builder.append( nodeIdentifier );
- builder.append( "/" );
+ builder.append("/");
+ builder.append(nodeIdentifier);
+ builder.append("/");
List<QName> 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;
}
}
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.<Object> 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.<Object> asList(container, name).toString());
}
}
}
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;
Preconditions.checkNotNull(namespace);
name = new QName(namespace, localName);
}
- if(composite) {
- unwrapped = NodeFactory.createImmutableCompositeNode(name, null, Collections.<Node<?>>emptyList(),null);
+ if (composite) {
+ unwrapped = NodeFactory.createImmutableCompositeNode(name, null, Collections.<Node<?>> emptyList(),
+ null);
} else {
unwrapped = NodeFactory.createImmutableSimpleNode(name, null, null);
}
private final List<IdentityValue> 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;
}
elementData.add(identityValue);
}
-
public List<IdentityValue> getValuesWithNamespaces() {
return Collections.unmodifiableList(elementData);
}
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;
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;
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;
private RestCodec() {
}
- public static final Codec<Object, Object> from(final TypeDefinition<?> typeDefinition, final MountInstance mountPoint) {
+ public static final Codec<Object, Object> from(final TypeDefinition<?> typeDefinition,
+ final MountInstance mountPoint) {
return new ObjectCodec(typeDefinition, mountPoint);
}
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) {
.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 {
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);
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);
@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
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;
}
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();
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());
Map<QName, Object> 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;
}
}
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
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<RestconfError> errors ) {
- this.errors = ImmutableList.copyOf( errors );
- Preconditions.checkArgument( !this.errors.isEmpty(), "RestconfError list can't be empty" );
+ public RestconfDocumentedException(List<RestconfError> 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;
}
return status;
}
-
@Override
public String getMessage() {
return "errors: " + errors + (status != null ? ", status: " + status : "");
/*
-* 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.
*
- * <br><br><b>Note:</b> Enumerations defined within are provided by the ietf restconf draft.
+ * <br>
+ * <br>
+ * <b>Note:</b> 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}
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;
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;
}
}
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, <b>formatted as XML</b>, 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, <b>formatted as XML</b>, 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;
/**
* 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 = "<severity>" + rpcError.getSeverity().toString().toLowerCase() + "</severity>";
}
- else if( rpcError.getSeverity() != null ) {
- errorInfo = "<severity>" + rpcError.getSeverity().toString().toLowerCase() +
- "</severity>";
- }
- }
- else {
+ } else {
errorInfo = rpcError.getInfo();
}
@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 + ", " : "") + "]";
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;
}
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";
final Module restconfModule = this.getRestconfModule();
final List<Node<?>> modulesAsData = new ArrayList<Node<?>>();
- 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<Module> allModules = this.controllerContext.getAllModules();
for (final Module module : allModules) {
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
final List<Node<?>> streamsAsData = new ArrayList<Node<?>>();
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<Module> 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<Node<?>> modulesAsData = new ArrayList<Node<?>>();
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<Module> 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<Module> 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<Module> modules,
- final MountInstance mountPoint,boolean prettyPrint) {
+ final MountInstance mountPoint, boolean prettyPrint) {
final List<Node<?>> operationsAsData = new ArrayList<Node<?>>();
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<RpcDefinition> rpcs = module.getRpcs();
for (final RpcDefinition rpc : rpcs) {
QName rpcQName = rpc.getQName();
- SimpleNode<Object> immutableSimpleNode =
- NodeFactory.<Object>createImmutableSimpleNode(rpcQName, null, null);
+ SimpleNode<Object> immutableSimpleNode = NodeFactory.<Object> createImmutableSimpleNode(rpcQName, null,
+ null);
operationsAsData.add(immutableSimpleNode);
String name = module.getName();
}
}
- 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;
String moduleNameAndRevision = "";
if (mountIndex >= 0) {
moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
- }
- else {
+ } else {
moduleNameAndRevision = identifier;
}
Splitter splitter = Splitter.on("/").omitEmptyStrings();
Iterable<String> split = splitter.split(moduleNameAndRevision);
- final List<String> pathArgs = Lists.<String>newArrayList(split);
+ final List<String> pathArgs = Lists.<String> 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<Node<?>> streamNodeValues = new ArrayList<Node<?>>();
- List<DataSchemaNode> instanceDataChildrenByName =
- this.controllerContext.findInstanceDataChildrenByName(((DataNodeContainer) streamSchemaNode),
- "name");
+ List<DataSchemaNode> instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
+ ((DataNodeContainer) streamSchemaNode), "name");
final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
- streamNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(nameSchemaNode.getQName(), null,
- streamName));
+ streamNodeValues
+ .add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null, streamName));
instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
((DataNodeContainer) streamSchemaNode), "description");
final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
- streamNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(descriptionSchemaNode.getQName(), null,
+ streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(descriptionSchemaNode.getQName(), null,
"DESCRIPTION_PLACEHOLDER"));
instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
((DataNodeContainer) streamSchemaNode), "replay-support");
final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
- streamNodeValues.add(NodeFactory.<Boolean>createImmutableSimpleNode(replaySupportSchemaNode.getQName(), null,
+ streamNodeValues.add(NodeFactory.<Boolean> 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.<String>createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(),
+ streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(),
null, ""));
instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
((DataNodeContainer) streamSchemaNode), "events");
final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
- streamNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(eventsSchemaNode.getQName(),
- null, ""));
+ streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(eventsSchemaNode.getQName(), null, ""));
return NodeFactory.createImmutableCompositeNode(streamSchemaNode.getQName(), null, streamNodeValues);
}
private CompositeNode toModuleCompositeNode(final Module module, final DataSchemaNode moduleSchemaNode) {
final List<Node<?>> moduleNodeValues = new ArrayList<Node<?>>();
- List<DataSchemaNode> instanceDataChildrenByName =
- this.controllerContext.findInstanceDataChildrenByName(((DataNodeContainer) moduleSchemaNode), "name");
+ List<DataSchemaNode> instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
+ ((DataNodeContainer) moduleSchemaNode), "name");
final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
- moduleNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(nameSchemaNode.getQName(),
- null, module.getName()));
+ moduleNodeValues.add(NodeFactory.<String> 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.<String>createImmutableSimpleNode(revisionSchemaNode.getQName(), null,
+ moduleNodeValues.add(NodeFactory.<String> 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.<String>createImmutableSimpleNode(namespaceSchemaNode.getQName(), null,
+ moduleNodeValues.add(NodeFactory.<String> 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.<String>createImmutableSimpleNode(featureSchemaNode.getQName(), null,
+ moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(featureSchemaNode.getQName(), null,
feature.getQName().getLocalName()));
}
}
@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<? extends Object> pathNode = value == null ? null :
- value.getFirstSimpleByName( QName.create(rpc.getQName(), "path") );
+ final SimpleNode<? extends Object> 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);
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<String> streamNameNode = NodeFactory.<String>createImmutableSimpleNode(
+ final SimpleNode<String> streamNameNode = NodeFactory.<String> createImmutableSimpleNode(
QName.create(rpc.getOutput().getQName(), "stream-name"), null, streamName);
final List<Node<?>> output = new ArrayList<Node<?>>();
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) {
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)
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;
}
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) {
}
- 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;
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<CompositeNode> rpcResult) {
if (rpcResult.isSuccessful() == false) {
Collection<RpcError> 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<RestconfError> 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);
}
}
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 extends Node<?>> T pruneDataAtDepth( final T node, final Integer depth ) {
- if( depth == null ) {
+ private <T extends Node<?>> T pruneDataAtDepth(final T node, final Integer depth) {
+ if (depth == null) {
return node;
}
- if( node instanceof CompositeNode ) {
+ if (node instanceof CompositeNode) {
ImmutableList.Builder<Node<?>> newChildNodes = ImmutableList.<Node<?>> 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\""));
}
}
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) {
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();
}
}
/**
- * 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
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<SimpleNode<?>> payloadKeyValues = payload.getSimpleNodesByName(keyDefinition.getLocalName());
if (payloadKeyValues.isEmpty()) {
throw new RestconfDocumentedException("Missing key " + keyDefinition.getLocalName()
- + " in the message body.", ErrorType.PROTOCOL,
- ErrorTag.DATA_MISSING);
+ + " 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;
// 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);
MountInstance mountPoint = iiWithData.getMountPoint();
try {
if (mountPoint != null) {
- Future<RpcResult<TransactionStatus>> future =
- broker.commitConfigurationDataPostBehindMountPoint(
- mountPoint, iiWithData.getInstanceIdentifier(), value);
+ Future<RpcResult<TransactionStatus>> future = broker.commitConfigurationDataPostBehindMountPoint(
+ mountPoint, iiWithData.getInstanceIdentifier(), value);
status = future == null ? null : future.get();
- }
- else {
- Future<RpcResult<TransactionStatus>> future =
- broker.commitConfigurationDataPost(iiWithData.getInstanceIdentifier(), value);
+ } else {
+ Future<RpcResult<TransactionStatus>> 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();
}
@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<TransactionStatus> status = null;
try {
if (mountPoint != null) {
- Future<RpcResult<TransactionStatus>> future =
- broker.commitConfigurationDataPostBehindMountPoint(
- mountPoint, iiWithData.getInstanceIdentifier(), value);
+ Future<RpcResult<TransactionStatus>> future = broker.commitConfigurationDataPostBehindMountPoint(
+ mountPoint, iiWithData.getInstanceIdentifier(), value);
status = future == null ? null : future.get();
- }
- else {
- Future<RpcResult<TransactionStatus>> future =
- broker.commitConfigurationDataPost(iiWithData.getInstanceIdentifier(), value);
+ } else {
+ Future<RpcResult<TransactionStatus>> 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();
}
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();
}
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);
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.<Object>asList(mountPoint, data).toString());
+ } else {
+ throw new IllegalArgumentException("Unhandled parameter types: "
+ + Arrays.<Object> asList(mountPoint, data).toString());
}
}
private Module findModule(final MountInstance mountPoint, final CompositeNodeWrapper data) {
URI namespace = data.getNamespace();
- Preconditions.<URI>checkNotNull(namespace);
+ Preconditions.<URI> checkNotNull(namespace);
Module module = null;
if (mountPoint != null) {
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());
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) {
InstanceIdentifierBuilder iiBuilder = null;
if (iiOriginal == null) {
iiBuilder = InstanceIdentifier.builder();
- }
- else {
+ } else {
iiBuilder = InstanceIdentifier.builder(iiOriginal);
}
if ((schemaOfData instanceof ListSchemaNode)) {
- HashMap<QName,Object> keys = this.resolveKeysFromData(((ListSchemaNode) schemaOfData), data);
+ HashMap<QName, Object> 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<QName,Object> resolveKeysFromData(final ListSchemaNode listNode,
- final CompositeNode dataNode) {
- final HashMap<QName,Object> keyValues = new HashMap<QName, Object>();
+ private HashMap<QName, Object> resolveKeysFromData(final ListSchemaNode listNode, final CompositeNode dataNode) {
+ final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
List<QName> _keyDefinition = listNode.getKeyDefinition();
for (final QName key : _keyDefinition) {
SimpleNode<? extends Object> head = null;
}
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);
}
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) {
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)) {
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);
}
}
return node;
}
- private void normalizeNode(final NodeWrapper<? extends Object> nodeBuilder,
- final DataSchemaNode schema, final QName previousAugment,
- final MountInstance mountPoint) {
+ private void normalizeNode(final NodeWrapper<? extends Object> 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<NodeWrapper<?>> children = compositeNode.getValues();
- for( NodeWrapper<? extends Object> child : children ) {
- child.setNamespace( schema.getQName().getNamespace() );
- if( child instanceof CompositeNodeWrapper ) {
- normalizeAnyXmlNode( (CompositeNodeWrapper)child, schema );
+ for (NodeWrapper<? extends Object> child : children) {
+ child.setNamespace(schema.getQName().getNamespace());
+ if (child instanceof CompositeNodeWrapper) {
+ normalizeAnyXmlNode((CompositeNodeWrapper) child, schema);
}
}
}
- private void normalizeEmptyNode( final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema ) {
+ 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);
}
}
- 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<? extends Object> 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<Object,Object> codec = RestCodec.from(typeDefinition, mountPoint);
+ if (typeDefinition != null) {
+ Codec<Object, Object> 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<NodeWrapper<?>> children = compositeNodeBuilder.getValues();
- checkNodeMultiplicityAccordingToSchema(schema,children);
+ checkNodeMultiplicityAccordingToSchema(schema, children);
for (final NodeWrapper<? extends Object> child : children) {
- final List<DataSchemaNode> potentialSchemaNodes =
- this.controllerContext.findInstanceDataChildrenByName(
- schema, child.getLocalName());
+ final List<DataSchemaNode> 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;
}
}
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<QName> listKeys = listSchemaNode.getKeyDefinition();
for (final QName listKey : listKeys) {
boolean foundKey = false;
}
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);
}
}
}
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<? extends Object> nodeBuilder,
- final DataSchemaNode schema, final QName previousAugment,
- final MountInstance mountPoint) {
+ private QName normalizeNodeName(final NodeWrapper<? extends Object> 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);
}
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.<Object>asList(data).toString());
+ } else {
+ throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> 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.<Object>asList(data).toString());
+ } else {
+ throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> 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.<Object>asList(data).toString());
+ } else {
+ throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
}
}
private TypeDefinition<? extends Object> 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.<Object>asList(node).toString());
+ } else {
+ throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());
}
}
}
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;
return unwrap().setValue(value);
}
-
-
}
* 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
/*
-* 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;
public abstract class AbstractRpcExecutor implements RpcExecutor {
private final RpcDefinition rpcDef;
- public AbstractRpcExecutor( RpcDefinition rpcDef ){
+ public AbstractRpcExecutor(RpcDefinition rpcDef) {
this.rpcDef = rpcDef;
}
}
@Override
- public RpcResult<CompositeNode> invokeRpc( CompositeNode rpcRequest )
- throws RestconfDocumentedException {
+ public RpcResult<CompositeNode> invokeRpc(CompositeNode rpcRequest) throws RestconfDocumentedException {
try {
- return getRpcResult( invokeRpcUnchecked( rpcRequest ) );
- }
- catch( IllegalArgumentException e ) {
- throw new RestconfDocumentedException(
- e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
- }
- catch( UnsupportedOperationException e ) {
- throw new RestconfDocumentedException(
- e.getMessage(), ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED );
- }
- catch( 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<RpcResult<CompositeNode>> invokeRpcUnchecked( CompositeNode rpcRequest );
+ protected abstract Future<RpcResult<CompositeNode>> invokeRpcUnchecked(CompositeNode rpcRequest);
- protected RpcResult<CompositeNode> getRpcResult(
- Future<RpcResult<CompositeNode>> fromFuture ) {
+ protected RpcResult<CompositeNode> getRpcResult(Future<RpcResult<CompositeNode>> 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);
}
}
}
/*
-* 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;
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<RpcResult<CompositeNode>> invokeRpcUnchecked( CompositeNode rpcRequest ) {
- return broker.invokeRpc( getRpcDefinition().getQName(), rpcRequest );
+ protected Future<RpcResult<CompositeNode>> invokeRpcUnchecked(CompositeNode rpcRequest) {
+ return broker.invokeRpc(getRpcDefinition().getQName(), rpcRequest);
}
}
\ No newline at end of file
/*
-* 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
*
*/
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<RpcResult<CompositeNode>> invokeRpcUnchecked( CompositeNode rpcRequest ) {
- return mountPoint.rpc( getRpcDefinition().getQName(), rpcRequest );
+ protected Future<RpcResult<CompositeNode>> invokeRpcUnchecked(CompositeNode rpcRequest) {
+ return mountPoint.rpc(getRpcDefinition().getQName(), rpcRequest);
}
}
\ No newline at end of file
/*
-* 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;
import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
public interface RpcExecutor {
- RpcResult<CompositeNode> invokeRpc( CompositeNode rpcRequest );
+ RpcResult<CompositeNode> invokeRpc(CompositeNode rpcRequest);
RpcDefinition getRpcDefinition();
}
\ No newline at end of file
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;
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;
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;
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 {
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<DataChangeListener> registration;
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.
*/
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());
}
@Override
- public void onDataChanged(
- final DataChangeEvent<InstanceIdentifier, CompositeNode> 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<InstanceIdentifier, CompositeNode> 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);
}
} 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);
}
}
}
/**
- * 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;
* Type of the event.
*/
private enum EventType {
- REGISTER, DEREGISTER, NOTIFY;
+ REGISTER,
+ DEREGISTER,
+ NOTIFY;
}
/**
* DataChangeEvent
* @return Data in printable form.
*/
- private String prepareXmlFrom(
- final DataChangeEvent<InstanceIdentifier, CompositeNode> change) {
+ private String prepareXmlFrom(final DataChangeEvent<InstanceIdentifier, CompositeNode> 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);
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 {
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) {
private void addValuesToDataChangedNotificationEventElement(final Document doc,
final Element dataChangedNotificationEventElement,
final DataChangeEvent<InstanceIdentifier, CompositeNode> 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);
}
/**
* @param operation
* {@link Operation}
*/
- private void addValuesFromDataToElement(final Document doc,
- final Set<InstanceIdentifier> data, final Element element, final Store store,
- final Operation operation) {
+ private void addValuesFromDataToElement(final Document doc, final Set<InstanceIdentifier> 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);
}
}
* @param operation
* {@link Operation}
*/
- private void addValuesFromDataToElement(final Document doc,
- final Map<InstanceIdentifier, CompositeNode> data, final Element element,
- final Store store, final Operation operation) {
+ private void addValuesFromDataToElement(final Document doc, final Map<InstanceIdentifier, CompositeNode> data,
+ final Element element, final Store store, final Operation operation) {
if (data == null || data.isEmpty()) {
return;
}
for (Entry<InstanceIdentifier, CompositeNode> 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);
}
}
* {@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");
* @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.",
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;
}
}
* @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<String, String> prefixes = new HashMap<>();
InstanceIdentifier instanceIdentifier = path;
// 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<QName, Object> predicates = ((NodeIdentifierWithPredicates) pathArgument)
- .getKeyValues();
+ Map<QName, Object> 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("'");
* @param prefixes
* Map of namespaces and prefixes.
*/
- private static void writeIdentifierWithNamespacePrefix(final Element element,
- final StringBuilder textContent, final QName qName, final Map<String, String> prefixes) {
+ private static void writeIdentifierWithNamespacePrefix(final Element element, final StringBuilder textContent,
+ final QName qName, final Map<String, String> 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());
}
}
* @param registration
* ListenerRegistration<DataChangeListener>
*/
- public void setRegistration(
- final ListenerRegistration<DataChangeListener> registration) {
+ public void setRegistration(final ListenerRegistration<DataChangeListener> registration) {
this.registration = registration;
}
}
/**
- * 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<>();
}
/**
- * 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);
}
/**
- * 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
*/
/**
* 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();
* 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;
}
/**
- * 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;
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;
/**
return listenersByStreamName.keySet();
}
-
/**
* Gets {@link ListenerAdapter} specified by stream name.
*
}
/**
- * 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.
}
/**
- * 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.
}
/**
- * 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();
}
/**
- * 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
}
/**
- * 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.
}
/**
- * 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);
}
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;
/**
* 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);
/**
* 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;
}
* 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();
}
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();
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;
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<Object> {
- 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) {
}
/**
- * 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;
}
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());
* @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());
* @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());
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();
}
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<SocketChannel> {
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
import java.io.IOException;
import java.io.StringReader;
import java.util.Map;
import java.util.Set;
-
import javax.ws.rs.WebApplicationException;
-
import org.junit.BeforeClass;
import org.junit.Test;
import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
import org.opendaylight.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
}
/**
- * 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
}
/**
- * 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() {
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
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"));
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
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();
// :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();
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;
}
/**
- * 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
}
/**
- * 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
}
/**
- * 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
}
/**
- * 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() {
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;
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 {
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() {
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();
}
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();
}
}
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();
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;
}
}
TestUtils.normalizeCompositeNode(compositeNode, modules, "simple-data-types:cont");
String jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(compositeNode, modules, dataSchemaNode,
- StructuredDataToJsonProvider.INSTANCE);
+ StructuredDataToJsonProvider.INSTANCE);
assertNotNull(jsonOutput);
private void jsonReadContElements(JsonReader jReader) throws IOException {
jReader.beginObject();
- Map<String,LeafVerifier> 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<String, LeafVerifier> 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();
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());
}
}
}
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;
}
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();
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;
@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();
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;
}
/**
- * 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() {
}
/**
- * 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() {
@Test
public void incorrectTopLevelElementTest() throws WebApplicationException, IOException {
String jsonOutput = null;
- jsonOutput = TestUtils
- .writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(),
- Collections.<Module>emptySet(), prepareDataSchemaNode(),
- StructuredDataToJsonProvider.INSTANCE);
+ jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(),
+ Collections.<Module> 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() {
}
/**
- * 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() {
}
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\"", ":", "\\["));
}
}
import java.net.URISyntaxException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-
import javax.ws.rs.WebApplicationException;
-
import org.junit.BeforeClass;
import org.junit.Test;
import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
import 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;
/**
*
- * 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 {
@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);
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;
boolean nullPointerExceptionRaised = false;
try {
- TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(),
- Collections.<Module>emptySet(), prepareDataSchemaNode(), StructuredDataToXmlProvider.INSTANCE);
+ TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(), Collections.<Module> emptySet(),
+ prepareDataSchemaNode(), StructuredDataToXmlProvider.INSTANCE);
} catch (WebApplicationException | IOException e) {
LOG.error("WebApplicationException or IOException was raised");
} catch (NullPointerException e) {
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+import com.google.common.base.Optional;
+import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.List;
-
import javax.ws.rs.WebApplicationException;
import javax.xml.transform.TransformerFactoryConfigurationError;
-
import org.junit.BeforeClass;
import org.junit.Test;
import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
import org.opendaylight.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 {
serializeToXml(prepareLeafrefData(), "<lfBoolean>true</lfBoolean>", "<lfLfref>true</lfLfref>");
}
-
@Test
public void snAsYangStringToXmlTest() {
serializeToXml(
- prepareCnStructForYangData(TypeDefinitionAwareCodec.from(StringType.getInstance()).deserialize("lfStr value"),
- "lfStr"), "<lfStr>lfStr value</lfStr>");
+ prepareCnStructForYangData(
+ TypeDefinitionAwareCodec.from(StringType.getInstance()).deserialize("lfStr value"), "lfStr"),
+ "<lfStr>lfStr value</lfStr>");
}
@Test
public void snAsYangInt8ToXmlTest() {
String elName = "lfInt8";
serializeToXml(
- prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int8.getInstance()).deserialize("14"), elName), "<"
- + elName + ">14</" + elName + ">");
+ prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int8.getInstance()).deserialize("14"), elName),
+ "<" + elName + ">14</" + elName + ">");
}
@Test
public void snAsYangInt16ToXmlTest() {
String elName = "lfInt16";
serializeToXml(
- prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int16.getInstance()).deserialize("3000"), elName),
- "<" + elName + ">3000</" + elName + ">");
+ prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int16.getInstance()).deserialize("3000"),
+ elName), "<" + elName + ">3000</" + elName + ">");
}
@Test
public void snAsYangInt32ToXmlTest() {
String elName = "lfInt32";
serializeToXml(
- prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int32.getInstance()).deserialize("201234"), elName),
- "<" + elName + ">201234</" + elName + ">");
+ prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int32.getInstance()).deserialize("201234"),
+ elName), "<" + elName + ">201234</" + elName + ">");
}
@Test
public void snAsYangInt64ToXmlTest() {
String elName = "lfInt64";
serializeToXml(
- prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int64.getInstance()).deserialize("5123456789"),
- elName), "<" + elName + ">5123456789</" + elName + ">");
+ prepareCnStructForYangData(
+ TypeDefinitionAwareCodec.from(Int64.getInstance()).deserialize("5123456789"), elName), "<"
+ + elName + ">5123456789</" + elName + ">");
}
@Test
public void snAsYangUint8ToXmlTest() {
String elName = "lfUint8";
serializeToXml(
- prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint8.getInstance()).deserialize("200"), elName),
- "<" + elName + ">200</" + elName + ">");
+ prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint8.getInstance()).deserialize("200"),
+ elName), "<" + elName + ">200</" + elName + ">");
}
@Test
public void snAsYangUint16ToXmlTest() {
String elName = "lfUint16";
serializeToXml(
- prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint16.getInstance()).deserialize("4000"), elName),
- "<" + elName + ">4000</" + elName + ">");
+ prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint16.getInstance()).deserialize("4000"),
+ elName), "<" + elName + ">4000</" + elName + ">");
}
@Test
public void snAsYangUint32ToXmlTest() {
String elName = "lfUint32";
serializeToXml(
- prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint32.getInstance()).deserialize("4123456789"),
- elName), "<" + elName + ">4123456789</" + elName + ">");
+ prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint32.getInstance())
+ .deserialize("4123456789"), elName), "<" + elName + ">4123456789</" + elName + ">");
}
@Test
public void snAsYangUint64ToXmlTest() {
String elName = "lfUint64";
serializeToXml(
- prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint64.getInstance()).deserialize("5123456789"),
- elName), "<" + elName + ">5123456789</" + elName + ">");
+ prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint64.getInstance())
+ .deserialize("5123456789"), elName), "<" + elName + ">5123456789</" + elName + ">");
}
@Test
String elName = "lfBinary";
serializeToXml(
prepareCnStructForYangData(
- TypeDefinitionAwareCodec.from(BinaryType.getInstance())
- .deserialize("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567"),
- elName), "<" + elName + ">ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567</"
- + elName + ">");
+ TypeDefinitionAwareCodec.from(BinaryType.getInstance()).deserialize(
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567"), elName), "<" + elName
+ + ">ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567</" + elName + ">");
}
@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<BitsTypeDefinition.Bit> 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<BitsTypeDefinition.Bit> 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 + ">", "<" + elName + ">two one</" + elName + ">");
+ prepareCnStructForYangData(
+ TypeDefinitionAwareCodec.from(BitsType.create(mock(SchemaPath.class), bitList)).deserialize(
+ "one two"), elName), "<" + elName + ">one two</" + elName + ">", "<" + elName
+ + ">two one</" + elName + ">");
}
@Test
public void snAsYangEnumerationToXmlTest() {
- EnumTypeDefinition.EnumPair mockEnum = mock( EnumTypeDefinition.EnumPair.class );
- when( mockEnum.getName() ).thenReturn( "enum2" );
- List<EnumPair> enumList = Lists.newArrayList( mockEnum );
+ EnumTypeDefinition.EnumPair mockEnum = mock(EnumTypeDefinition.EnumPair.class);
+ when(mockEnum.getName()).thenReturn("enum2");
+ List<EnumPair> enumList = Lists.newArrayList(mockEnum);
String elName = "lfEnumeration";
serializeToXml(
- prepareCnStructForYangData(TypeDefinitionAwareCodec.from(
- EnumerationType.create( mock( SchemaPath.class ), enumList,
- Optional.<EnumTypeDefinition.EnumPair>absent() ) )
- .deserialize("enum2"),
- elName), "<" + elName + ">enum2</" + elName + ">");
+ prepareCnStructForYangData(
+ TypeDefinitionAwareCodec.from(
+ EnumerationType.create(mock(SchemaPath.class), enumList,
+ Optional.<EnumTypeDefinition.EnumPair> absent())).deserialize("enum2"), elName),
+ "<" + elName + ">enum2</" + elName + ">");
}
@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</" + elName + ">");
+ prepareCnStructForYangData(TypeDefinitionAwareCodec.from(BooleanType.getInstance()).deserialize("str"),
+ elName), "<" + elName + ">false</" + elName + ">");
serializeToXml(
- prepareCnStructForYangData(TypeDefinitionAwareCodec.from(BooleanType.getInstance()).deserialize("true"), elName),
- "<" + elName + ">true</" + elName + ">");
+ prepareCnStructForYangData(
+ TypeDefinitionAwareCodec.from(BooleanType.getInstance()).deserialize("true"), elName), "<"
+ + elName + ">true</" + elName + ">");
}
@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<BitsTypeDefinition.Bit> 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<BitsTypeDefinition.Bit> bitList = Lists.newArrayList(mockBit1, mockBit2);
- List<TypeDefinition<?>> types = Lists.<TypeDefinition<?>>newArrayList(
- Int8.getInstance(),
- BitsType.create( mock( SchemaPath.class ) , bitList ),
- BooleanType.getInstance() );
- UnionType unionType = UnionType.create( types );
+ List<TypeDefinition<?>> types = Lists.<TypeDefinition<?>> 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</" + elName + ">");
+ serializeToXml(prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(int8), elName),
+ "<" + elName + ">15</" + elName + ">");
String bits = "first second";
- serializeToXml(
- prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(bits), elName), "<"
- + elName + ">first second</" + elName + ">");
+ serializeToXml(prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(bits), elName),
+ "<" + elName + ">first second</" + elName + ">");
String bool = "str";
- serializeToXml(
- prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(bool), elName), "<"
- + elName + ">str</" + elName + ">");
+ serializeToXml(prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(bool), elName),
+ "<" + elName + ">str</" + elName + ">");
}
private void serializeToXml(final CompositeNode compositeNode, final String... xmlRepresentation)
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;
/**
*
- * 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 {
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;
@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
String output = TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCnSn(), modules, schemaContext,
StructuredDataToXmlProvider.INSTANCE);
-// String output =
-// String.format("<data>" +
-// "\n<cont_m1>" +
-// "\n\t<lf1_m1>" +
-// "\n\t\tlf1 m1 value" +
-// "\n\t</lf1_m1>" +
-// "\n</cont_m1>" +
-// "\n<cont_m2>" +
-// "\n\t<lf1_m2>" +
-// "\n\t\tlf1 m2 value" +
-// "\n\t</lf1_m2>" +
-// "\n</cont_m2>" +
-// "\n</data>");
+ // String output =
+ // String.format("<data>" +
+ // "\n<cont_m1>" +
+ // "\n\t<lf1_m1>" +
+ // "\n\t\tlf1 m1 value" +
+ // "\n\t</lf1_m1>" +
+ // "\n</cont_m1>" +
+ // "\n<cont_m2>" +
+ // "\n\t<lf1_m2>" +
+ // "\n\t\tlf1 m2 value" +
+ // "\n\t</lf1_m2>" +
+ // "\n</cont_m2>" +
+ // "\n</data>");
StringBuilder regex = new StringBuilder();
regex.append("^");
regex.append(".*xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"");
regex.append(".*>");
-
regex.append(".*<contB_m1.*\\/>");
regex.append(".*xmlns=\"module:one\"");
regex.append(".*>");
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;
}
/**
- * 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() {
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;
}
/**
- * 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() {
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 {
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() {
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"));
}
@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 <b>stay unchanged</b> if concrete values are
- * present in composite or simple node and if the method for update is
- * called.
+ * Tests whether namespace <b>stay unchanged</b> if concrete values are present in composite or simple node and if
+ * the method for update is called.
*
*/
@Test
}
- 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);
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"));
}
*/
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;
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<CompositeNode> expResult = mock( RpcResult.class );
- Future<RpcResult<CompositeNode>> future = Futures.immediateFuture( expResult );
- when( mockConsumerSession.rpc( qname, dataNode ) ).thenReturn( future );
+ RpcResult<CompositeNode> expResult = mock(RpcResult.class);
+ Future<RpcResult<CompositeNode>> future = Futures.immediateFuture(expResult);
+ when(mockConsumerSession.rpc(qname, dataNode)).thenReturn(future);
- Future<RpcResult<CompositeNode>> actualFuture = brokerFacade.invokeRpc( qname, dataNode );
- assertNotNull( "Future is null", actualFuture );
+ Future<RpcResult<CompositeNode>> actualFuture = brokerFacade.invokeRpc(qname, dataNode);
+ assertNotNull("Future is null", actualFuture);
RpcResult<CompositeNode> 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<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture( null );
+ Future<RpcResult<TransactionStatus>> 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<RpcResult<TransactionStatus>> actualFuture =
- brokerFacade.commitConfigurationDataPut( instanceID, dataNode );
+ Future<RpcResult<TransactionStatus>> 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<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture( null );
+ Future<RpcResult<TransactionStatus>> 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<RpcResult<TransactionStatus>> actualFuture =
- brokerFacade.commitConfigurationDataPutBehindMountPoint(
- mockMountInstance, instanceID, dataNode );
+ Future<RpcResult<TransactionStatus>> 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<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture( null );
+ Future<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture(null);
- Map<InstanceIdentifier, CompositeNode> nodeMap =
- new ImmutableMap.Builder<InstanceIdentifier,CompositeNode>()
- .put( instanceID, dataNode ).build();
+ Map<InstanceIdentifier, CompositeNode> nodeMap = new ImmutableMap.Builder<InstanceIdentifier, CompositeNode>()
+ .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<RpcResult<TransactionStatus>> actualFuture =
- brokerFacade.commitConfigurationDataPost( instanceID, dataNode );
+ Future<RpcResult<TransactionStatus>> 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<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture( null );
+ Future<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture(null);
- Map<InstanceIdentifier, CompositeNode> nodeMap =
- new ImmutableMap.Builder<InstanceIdentifier,CompositeNode>()
- .put( instanceID, dataNode ).build();
+ Map<InstanceIdentifier, CompositeNode> nodeMap = new ImmutableMap.Builder<InstanceIdentifier, CompositeNode>()
+ .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<RpcResult<TransactionStatus>> actualFuture =
- brokerFacade.commitConfigurationDataPostBehindMountPoint( mockMountInstance,
- instanceID, dataNode );
+ Future<RpcResult<TransactionStatus>> 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<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture( null );
+ Future<RpcResult<TransactionStatus>> 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<RpcResult<TransactionStatus>> actualFuture =
- brokerFacade.commitConfigurationDataDelete( instanceID );
+ Future<RpcResult<TransactionStatus>> 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<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture( null );
+ Future<RpcResult<TransactionStatus>> 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<RpcResult<TransactionStatus>> actualFuture =
- brokerFacade.commitConfigurationDataDeleteBehindMountPoint(
- mockMountInstance, instanceID );
+ Future<RpcResult<TransactionStatus>> 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<DataChangeListener> mockRegistration = mock( ListenerRegistration.class );
- when( dataBroker.registerDataChangeListener( instanceID, listener ) )
- .thenReturn( mockRegistration );
+ ListenerRegistration<DataChangeListener> 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);
}
}
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;
resourceConfig = resourceConfig.registerInstances(restConf, StructuredDataToXmlProvider.INSTANCE,
StructuredDataToJsonProvider.INSTANCE, XmlToCompositeNodeProvider.INSTANCE,
JsonToCompositeNodeProvider.INSTANCE);
- resourceConfig.registerClasses( RestconfDocumentedExceptionMapper.class );
+ resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
return resourceConfig;
}
result = builder.result;
}
-
@Override
public boolean cancel(final boolean mayInterruptIfRunning) {
return cancel;
}
@Override
- public RpcResult<T> get(final long timeout, final TimeUnit unit) throws InterruptedException,
- ExecutionException, TimeoutException {
+ public RpcResult<T> get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException,
+ TimeoutException {
return result;
}
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;
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;
private static ControllerContext controllerContext = null;
private static UriInfo uriInfo;
-
@BeforeClass
public static void init() throws FileNotFoundException {
- Set<Module> allModules = new HashSet<Module>( TestUtils
- .loadModulesFrom("/full-versions/yangs") );
- allModules.addAll( TestUtils.loadModulesFrom("/invoke-rpc") );
+ Set<Module> allModules = new HashSet<Module>(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<String, String> map = new MultivaluedHashMap<>();
}
@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() {
CompositeNode payload = preparePayload();
- when(mockedBrokerFacade.invokeRpc(any(QName.class), any(CompositeNode.class)))
- .thenReturn( Futures.<RpcResult<CompositeNode>>immediateFuture(
- Rpcs.<CompositeNode>getRpcResult( true ) ) );
+ when(mockedBrokerFacade.invokeRpc(any(QName.class), any(CompositeNode.class))).thenReturn(
+ Futures.<RpcResult<CompositeNode>> immediateFuture(Rpcs.<CompositeNode> 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);
}
@Test
public void testInvokeRpcWithNoPayloadRpc_FailNoErrors() {
- RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode>getRpcResult( false );
+ RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode> 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.<RpcResult<CompositeNode>>immediateFuture( rpcResult ) );
+ when(
+ brokerFacade.invokeRpc(
+ eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")),
+ any(CompositeNode.class))).thenReturn(
+ Futures.<RpcResult<CompositeNode>> 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.<String>absent(), Optional.<String>absent() );
+ } catch (RestconfDocumentedException e) {
+ verifyRestconfDocumentedException(e, 0, ErrorType.RPC, ErrorTag.OPERATION_FAILED,
+ Optional.<String> absent(), Optional.<String> absent());
}
}
- void verifyRestconfDocumentedException( final RestconfDocumentedException e, final int index,
- final ErrorType expErrorType, final ErrorTag expErrorTag,
- final Optional<String> expErrorMsg,
- final Optional<String> expAppTag ) {
+ void verifyRestconfDocumentedException(final RestconfDocumentedException e, final int index,
+ final ErrorType expErrorType, final ErrorTag expErrorTag, final Optional<String> expErrorMsg,
+ final Optional<String> 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<RpcError> 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<RpcError> 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<CompositeNode> rpcResult = Rpcs.<CompositeNode>getRpcResult( false, rpcErrors );
+ RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode> 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.<RpcResult<CompositeNode>>immediateFuture( rpcResult ) );
+ when(
+ brokerFacade.invokeRpc(
+ eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")),
+ any(CompositeNode.class))).thenReturn(
+ Futures.<RpcResult<CompositeNode>> 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.<String>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.<String> absent());
+ verifyRestconfDocumentedException(e, 1, ErrorType.RPC, ErrorTag.IN_USE, Optional.of("bar"),
+ Optional.of("app-tag"));
}
}
@Test
public void testInvokeRpcWithNoPayload_Success() {
- RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode>getRpcResult( true );
+ RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode> 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.<RpcResult<CompositeNode>>immediateFuture( rpcResult ) );
+ when(
+ brokerFacade.invokeRpc(
+ eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")),
+ any(CompositeNode.class))).thenReturn(
+ Futures.<RpcResult<CompositeNode>> 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.<String>absent(), Optional.<String>absent() );
+ verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
+ Optional.<String> absent(), Optional.<String> 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.<String>absent(), Optional.<String>absent() );
+ } catch (RestconfDocumentedException e) {
+ verifyRestconfDocumentedException(e, 0, ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT,
+ Optional.<String> absent(), Optional.<String> absent());
}
}
@Test
public void testInvokeRpcMethodWithInput() {
- RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode>getRpcResult( true );
+ RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode> 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.<RpcResult<CompositeNode>>immediateFuture( rpcResult ) );
+ when(
+ brokerFacade.invokeRpc(
+ eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)make-toast")),
+ any(CompositeNode.class))).thenReturn(
+ Futures.<RpcResult<CompositeNode>> 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.<String>absent(), Optional.<String>absent() );
+ } catch (RestconfDocumentedException e) {
+ verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
+ Optional.<String> absent(), Optional.<String> absent());
}
}
@Test
public void testInvokeRpcWithNoPayloadWithOutput_Success() {
- CompositeNode compositeNode = mock( CompositeNode.class );
- RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode>getRpcResult( true, compositeNode,
- Collections.<RpcError>emptyList() );
+ CompositeNode compositeNode = mock(CompositeNode.class);
+ RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode> getRpcResult(true, compositeNode,
+ Collections.<RpcError> 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.<RpcResult<CompositeNode>>immediateFuture( rpcResult ) );
+ any(CompositeNode.class))).thenReturn(
+ Futures.<RpcResult<CompositeNode>> 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<CompositeNode> rpcResult = Rpcs.<CompositeNode>getRpcResult( true );
+ public void testMountedRpcCallNoPayload_Success() throws Exception {
+ RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode> getRpcResult(true);
- ListenableFuture<RpcResult<CompositeNode>> mockListener = mock( ListenableFuture.class );
- when( mockListener.get() ).thenReturn( rpcResult );
+ ListenableFuture<RpcResult<CompositeNode>> 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.
}
}
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
*/
@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<CompositeNode> messageBodyReader) {
+ private void multipleEqualNameDataNodeTest(String path, ErrorType errorType, ErrorTag errorTag,
+ MessageBodyReader<CompositeNode> messageBodyReader) {
try {
- CompositeNode compositeNode = TestUtils.readInputToCnSn(path, false,messageBodyReader);
+ CompositeNode compositeNode = TestUtils.readInputToCnSn(path, false, messageBodyReader);
assertNotNull(compositeNode);
Set<Module> modules = null;
import java.net.URI;
import java.net.URISyntaxException;
-
import org.junit.BeforeClass;
import org.junit.Test;
import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
dataLoad("/normalize-node/yang/");
}
- @Test(expected=RestconfDocumentedException.class)
+ @Test(expected = RestconfDocumentedException.class)
public void namespaceNotNullAndInvalidNamespaceAndNoModuleNameTest() {
TestUtils.normalizeCompositeNode(prepareCnSn("wrongnamespace"), modules, schemaNodePath);
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;
@Test
public void serializeExceptionTest() {
- Codec<Object, Object> codec = RestCodec.from(BitsType.create(PATH, Collections.<Bit>emptyList()), null);
+ Codec<Object, Object> codec = RestCodec.from(BitsType.create(PATH, Collections.<Bit> emptyList()), null);
String serializedValue = (String) codec.serialize("incorrect value"); // set
// expected
assertEquals("incorrect value", serializedValue);
@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);
}
private Future<RpcResult<TransactionStatus>> createFuture(TransactionStatus statusName) {
- RpcResult<TransactionStatus> rpcResult = new DummyRpcResult.Builder<TransactionStatus>().result(statusName).build();
+ RpcResult<TransactionStatus> rpcResult = new DummyRpcResult.Builder<TransactionStatus>().result(statusName)
+ .build();
return new DummyFuture.Builder<TransactionStatus>().rpcResult(rpcResult).build();
}
import static org.junit.Assert.fail;
import java.io.FileNotFoundException;
-
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
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"));
}
}
}
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;
}
resourceConfig = resourceConfig.registerInstances(restconfImpl, StructuredDataToXmlProvider.INSTANCE,
StructuredDataToJsonProvider.INSTANCE, XmlToCompositeNodeProvider.INSTANCE,
JsonToCompositeNodeProvider.INSTANCE);
- resourceConfig.registerClasses( RestconfDocumentedExceptionMapper.class );
+ resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
return resourceConfig;
}
/**
* 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),
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());
}
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("<module");
assertEquals("<module element is returned more then once", 2, split.length);
.find());
}
- private Matcher prepareJsonRegex(final String module, final String revision, final String namespace, final String searchIn) {
+ private Matcher prepareJsonRegex(final String module, final String revision, final String namespace,
+ final String searchIn) {
StringBuilder regex = new StringBuilder();
regex.append("^");
}
- private Matcher prepareXmlRegex(final String module, final String revision, final String namespace, final String searchIn) {
+ private Matcher prepareXmlRegex(final String module, final String revision, final String namespace,
+ final String searchIn) {
StringBuilder regex = new StringBuilder();
regex.append("^");
return ptrn.matcher(searchIn);
}
- private void prepareMockForModulesTest(final ControllerContext mockedControllerContext) throws FileNotFoundException {
+ private void prepareMockForModulesTest(final ControllerContext mockedControllerContext)
+ throws FileNotFoundException {
SchemaContext schemaContext = TestUtils.loadSchemaContext("/modules");
mockedControllerContext.setGlobalSchema(schemaContext);
// when(mockedControllerContext.getGlobalSchema()).thenReturn(schemaContext);
}
/**
- * If includeWhiteChars URI parameter is set to false then no white
- * characters can be included in returned output
+ * If includeWhiteChars URI parameter is set to false then no white characters can be included in returned output
+ *
* @throws UnsupportedEncodingException
*/
@Test
getDataWithUriIncludeWhiteCharsParameter("operational");
}
-
private void getDataWithUriIncludeWhiteCharsParameter(String target) throws UnsupportedEncodingException {
mockReadConfigurationDataMethod();
- String uri = "/"+target+"/ietf-interfaces:interfaces/interface/eth0";
+ String uri = "/" + target + "/ietf-interfaces:interfaces/interface/eth0";
Response response = target(uri).queryParam("prettyPrint", "false").request("application/xml").get();
String xmlData = response.readEntity(String.class);
@Test
public void getDataWithUriDepthParameterTest() throws UnsupportedEncodingException {
- ControllerContext.getInstance().setGlobalSchema( schemaContextModules );
-
- CompositeNode depth1Cont = toCompositeNode(
- toCompositeNodeData( toNestedQName( "depth1-cont" ),
- toCompositeNodeData( toNestedQName( "depth2-cont1" ),
- toCompositeNodeData( toNestedQName( "depth3-cont1" ),
- toCompositeNodeData( toNestedQName( "depth4-cont1" ),
- toSimpleNodeData( toNestedQName( "depth5-leaf1" ), "depth5-leaf1-value" )
- ),
- toSimpleNodeData( toNestedQName( "depth4-leaf1" ), "depth4-leaf1-value" )
- ),
- toSimpleNodeData( toNestedQName( "depth3-leaf1" ), "depth3-leaf1-value" )
- ),
- toCompositeNodeData( toNestedQName( "depth2-cont2" ),
- toCompositeNodeData( toNestedQName( "depth3-cont2" ),
- toCompositeNodeData( toNestedQName( "depth4-cont2" ),
- toSimpleNodeData( toNestedQName( "depth5-leaf2" ), "depth5-leaf2-value" )
- ),
- toSimpleNodeData( toNestedQName( "depth4-leaf2" ), "depth4-leaf2-value" )
- ),
- toSimpleNodeData( toNestedQName( "depth3-leaf2" ), "depth3-leaf2-value" )
- ),
- toSimpleNodeData( toNestedQName( "depth2-leaf1" ), "depth2-leaf1-value" )
- ) );
-
- when( brokerFacade.readConfigurationData( any( InstanceIdentifier.class ) ) )
- .thenReturn( depth1Cont );
+ ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
+
+ CompositeNode depth1Cont = toCompositeNode(toCompositeNodeData(
+ toNestedQName("depth1-cont"),
+ toCompositeNodeData(
+ toNestedQName("depth2-cont1"),
+ toCompositeNodeData(
+ toNestedQName("depth3-cont1"),
+ toCompositeNodeData(toNestedQName("depth4-cont1"),
+ toSimpleNodeData(toNestedQName("depth5-leaf1"), "depth5-leaf1-value")),
+ toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")),
+ toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value")),
+ toCompositeNodeData(
+ toNestedQName("depth2-cont2"),
+ toCompositeNodeData(
+ toNestedQName("depth3-cont2"),
+ toCompositeNodeData(toNestedQName("depth4-cont2"),
+ toSimpleNodeData(toNestedQName("depth5-leaf2"), "depth5-leaf2-value")),
+ toSimpleNodeData(toNestedQName("depth4-leaf2"), "depth4-leaf2-value")),
+ toSimpleNodeData(toNestedQName("depth3-leaf2"), "depth3-leaf2-value")),
+ toSimpleNodeData(toNestedQName("depth2-leaf1"), "depth2-leaf1-value")));
+
+ when(brokerFacade.readConfigurationData(any(InstanceIdentifier.class))).thenReturn(depth1Cont);
// Test config with depth 1
- Response response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "1" )
- .request( "application/xml" ).get();
+ Response response = target("/config/nested-module:depth1-cont").queryParam("depth", "1")
+ .request("application/xml").get();
- verifyXMLResponse( response, expectEmptyContainer( "depth1-cont" ) );
+ verifyXMLResponse(response, expectEmptyContainer("depth1-cont"));
// Test config with depth 2
- response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "2" )
- .request( "application/xml" ).get();
+ response = target("/config/nested-module:depth1-cont").queryParam("depth", "2").request("application/xml")
+ .get();
- // String xml="<depth1-cont><depth2-cont1/><depth2-cont2/><depth2-leaf1>depth2-leaf1-value</depth2-leaf1></depth1-cont>";
- // Response mr=mock(Response.class);
- // when(mr.getEntity()).thenReturn( new java.io.StringBufferInputStream(xml) );
+ // String
+ // xml="<depth1-cont><depth2-cont1/><depth2-cont2/><depth2-leaf1>depth2-leaf1-value</depth2-leaf1></depth1-cont>";
+ // Response mr=mock(Response.class);
+ // when(mr.getEntity()).thenReturn( new
+ // java.io.StringBufferInputStream(xml) );
- verifyXMLResponse( response,
- expectContainer( "depth1-cont",
- expectEmptyContainer( "depth2-cont1" ),
- expectEmptyContainer( "depth2-cont2" ),
- expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
- ) );
+ verifyXMLResponse(
+ response,
+ expectContainer("depth1-cont", expectEmptyContainer("depth2-cont1"),
+ expectEmptyContainer("depth2-cont2"), expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
// Test config with depth 3
- response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "3" )
- .request( "application/xml" ).get();
-
- verifyXMLResponse( response,
- expectContainer( "depth1-cont",
- expectContainer( "depth2-cont1",
- expectEmptyContainer( "depth3-cont1" ),
- expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
- ),
- expectContainer( "depth2-cont2",
- expectEmptyContainer( "depth3-cont2" ),
- expectLeaf( "depth3-leaf2", "depth3-leaf2-value" )
- ),
- expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
- ) );
+ response = target("/config/nested-module:depth1-cont").queryParam("depth", "3").request("application/xml")
+ .get();
+
+ verifyXMLResponse(
+ response,
+ expectContainer(
+ "depth1-cont",
+ expectContainer("depth2-cont1", expectEmptyContainer("depth3-cont1"),
+ expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
+ expectContainer("depth2-cont2", expectEmptyContainer("depth3-cont2"),
+ expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
+ expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
// Test config with depth 4
- response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "4" )
- .request( "application/xml" ).get();
-
- verifyXMLResponse( response,
- expectContainer( "depth1-cont",
- expectContainer( "depth2-cont1",
- expectContainer( "depth3-cont1",
- expectEmptyContainer( "depth4-cont1" ),
- expectLeaf( "depth4-leaf1", "depth4-leaf1-value" )
- ),
- expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
- ),
- expectContainer( "depth2-cont2",
- expectContainer( "depth3-cont2",
- expectEmptyContainer( "depth4-cont2" ),
- expectLeaf( "depth4-leaf2", "depth4-leaf2-value" )
- ),
- expectLeaf( "depth3-leaf2", "depth3-leaf2-value" )
- ),
- expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
- ) );
+ response = target("/config/nested-module:depth1-cont").queryParam("depth", "4").request("application/xml")
+ .get();
+
+ verifyXMLResponse(
+ response,
+ expectContainer(
+ "depth1-cont",
+ expectContainer(
+ "depth2-cont1",
+ expectContainer("depth3-cont1", expectEmptyContainer("depth4-cont1"),
+ expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
+ expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
+ expectContainer(
+ "depth2-cont2",
+ expectContainer("depth3-cont2", expectEmptyContainer("depth4-cont2"),
+ expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
+ expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
+ expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
// Test config with depth 5
- response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "5" )
- .request( "application/xml" ).get();
-
- verifyXMLResponse( response,
- expectContainer( "depth1-cont",
- expectContainer( "depth2-cont1",
- expectContainer( "depth3-cont1",
- expectContainer( "depth4-cont1",
- expectLeaf( "depth5-leaf1", "depth5-leaf1-value" )
- ),
- expectLeaf( "depth4-leaf1", "depth4-leaf1-value" )
- ),
- expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
- ),
- expectContainer( "depth2-cont2",
- expectContainer( "depth3-cont2",
- expectContainer( "depth4-cont2",
- expectLeaf( "depth5-leaf2", "depth5-leaf2-value" )
- ),
- expectLeaf( "depth4-leaf2", "depth4-leaf2-value" )
- ),
- expectLeaf( "depth3-leaf2", "depth3-leaf2-value" )
- ),
- expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
- ) );
+ response = target("/config/nested-module:depth1-cont").queryParam("depth", "5").request("application/xml")
+ .get();
+
+ verifyXMLResponse(
+ response,
+ expectContainer(
+ "depth1-cont",
+ expectContainer(
+ "depth2-cont1",
+ expectContainer(
+ "depth3-cont1",
+ expectContainer("depth4-cont1",
+ expectLeaf("depth5-leaf1", "depth5-leaf1-value")),
+ expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
+ expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
+ expectContainer(
+ "depth2-cont2",
+ expectContainer(
+ "depth3-cont2",
+ expectContainer("depth4-cont2",
+ expectLeaf("depth5-leaf2", "depth5-leaf2-value")),
+ expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
+ expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
+ expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
// Test config with depth unbounded
- response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "unbounded" )
- .request( "application/xml" ).get();
-
- verifyXMLResponse( response,
- expectContainer( "depth1-cont",
- expectContainer( "depth2-cont1",
- expectContainer( "depth3-cont1",
- expectContainer( "depth4-cont1",
- expectLeaf( "depth5-leaf1", "depth5-leaf1-value" )
- ),
- expectLeaf( "depth4-leaf1", "depth4-leaf1-value" )
- ),
- expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
- ),
- expectContainer( "depth2-cont2",
- expectContainer( "depth3-cont2",
- expectContainer( "depth4-cont2",
- expectLeaf( "depth5-leaf2", "depth5-leaf2-value" )
- ),
- expectLeaf( "depth4-leaf2", "depth4-leaf2-value" )
- ),
- expectLeaf( "depth3-leaf2", "depth3-leaf2-value" )
- ),
- expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
- ) );
+ response = target("/config/nested-module:depth1-cont").queryParam("depth", "unbounded")
+ .request("application/xml").get();
+
+ verifyXMLResponse(
+ response,
+ expectContainer(
+ "depth1-cont",
+ expectContainer(
+ "depth2-cont1",
+ expectContainer(
+ "depth3-cont1",
+ expectContainer("depth4-cont1",
+ expectLeaf("depth5-leaf1", "depth5-leaf1-value")),
+ expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
+ expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
+ expectContainer(
+ "depth2-cont2",
+ expectContainer(
+ "depth3-cont2",
+ expectContainer("depth4-cont2",
+ expectLeaf("depth5-leaf2", "depth5-leaf2-value")),
+ expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
+ expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
+ expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
// Test operational
- CompositeNode depth2Cont1 = toCompositeNode(
- toCompositeNodeData( toNestedQName( "depth2-cont1" ),
- toCompositeNodeData( toNestedQName( "depth3-cont1" ),
- toCompositeNodeData( toNestedQName( "depth4-cont1" ),
- toSimpleNodeData( toNestedQName( "depth5-leaf1" ), "depth5-leaf1-value" )
- ),
- toSimpleNodeData( toNestedQName( "depth4-leaf1" ), "depth4-leaf1-value" )
- ),
- toSimpleNodeData( toNestedQName( "depth3-leaf1" ), "depth3-leaf1-value" )
- ) );
-
- when( brokerFacade.readOperationalData( any( InstanceIdentifier.class ) ) )
- .thenReturn( depth2Cont1 );
-
- response = target( "/operational/nested-module:depth1-cont/depth2-cont1" )
- .queryParam( "depth", "3" ).request( "application/xml" ).get();
-
- verifyXMLResponse( response,
- expectContainer( "depth2-cont1",
- expectContainer( "depth3-cont1",
- expectEmptyContainer( "depth4-cont1" ),
- expectLeaf( "depth4-leaf1", "depth4-leaf1-value" )
- ),
- expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
- ) );
+ CompositeNode depth2Cont1 = toCompositeNode(toCompositeNodeData(
+ toNestedQName("depth2-cont1"),
+ toCompositeNodeData(
+ toNestedQName("depth3-cont1"),
+ toCompositeNodeData(toNestedQName("depth4-cont1"),
+ toSimpleNodeData(toNestedQName("depth5-leaf1"), "depth5-leaf1-value")),
+ toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")),
+ toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value")));
+
+ when(brokerFacade.readOperationalData(any(InstanceIdentifier.class))).thenReturn(depth2Cont1);
+
+ response = target("/operational/nested-module:depth1-cont/depth2-cont1").queryParam("depth", "3")
+ .request("application/xml").get();
+
+ verifyXMLResponse(
+ response,
+ expectContainer(
+ "depth2-cont1",
+ expectContainer("depth3-cont1", expectEmptyContainer("depth4-cont1"),
+ expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
+ expectLeaf("depth3-leaf1", "depth3-leaf1-value")));
}
@Test
public void getDataWithInvalidDepthParameterTest() {
- ControllerContext.getInstance().setGlobalSchema( schemaContextModules );
+ ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
- final MultivaluedMap<String,String> paramMap = new MultivaluedHashMap<>();
- paramMap.putSingle( "depth", "1o" );
- UriInfo mockInfo = mock( UriInfo.class );
- when( mockInfo.getQueryParameters( false ) ).thenAnswer(
- new Answer<MultivaluedMap<String,String>>() {
- @Override
- public MultivaluedMap<String, String> answer( final InvocationOnMock invocation ) {
- return paramMap;
- }
- } );
+ final MultivaluedMap<String, String> paramMap = new MultivaluedHashMap<>();
+ paramMap.putSingle("depth", "1o");
+ UriInfo mockInfo = mock(UriInfo.class);
+ when(mockInfo.getQueryParameters(false)).thenAnswer(new Answer<MultivaluedMap<String, String>>() {
+ @Override
+ public MultivaluedMap<String, String> 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<String,NodeData> expChildMap = Maps.newHashMap();
- for( NodeData expChild: (List<NodeData>)nodeData.data ) {
- expChildMap.put( expChild.key.toString(), expChild );
+ Map<String, NodeData> expChildMap = Maps.newHashMap();
+ for (NodeData expChild : (List<NodeData>) 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<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
- builder.setQName( (QName) nodeData.key );
+ builder.setQName((QName) nodeData.key);
- for( NodeData child: (List<NodeData>)nodeData.data ) {
- if( child.data instanceof List ) {
- builder.add( toCompositeNode( child ) );
- }
- else {
- builder.addLeaf( (QName) child.key, child.data );
+ for (NodeData child : (List<NodeData>) nodeData.data) {
+ if (child.data instanceof List) {
+ builder.add(toCompositeNode(child));
+ } else {
+ builder.addLeaf((QName) child.key, child.data);
}
}
return builder.toInstance();
}
- private NodeData toCompositeNodeData( final QName key, final NodeData... childData ) {
- return new NodeData( key, Lists.newArrayList( childData ) );
+ 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);
}
}
assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
List<RpcError> 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));
builder.errors(errors);
}
RpcResult<CompositeNode> rpcResult = builder.build();
- when(brokerFacade.invokeRpc(any(QName.class), any(CompositeNode.class)))
- .thenReturn(Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
+ when(brokerFacade.invokeRpc(any(QName.class), any(CompositeNode.class))).thenReturn(
+ Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
}
private void mockInvokeRpc(CompositeNode result, boolean sucessful) {
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<String, String> expErrorInfo;
- public ComplexErrorInfoVerifier( final Map<String, String> expErrorInfo ) {
+ public ComplexErrorInfoVerifier(final Map<String, String> expErrorInfo) {
this.expErrorInfo = expErrorInfo;
}
@Override
- public void verifyXML( final Node errorInfoNode ) {
+ public void verifyXML(final Node errorInfoNode) {
- Map<String, String> mutableExpMap = Maps.newHashMap( expErrorInfo );
+ Map<String, String> 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<String, String> actualErrorInfo = Maps.newHashMap();
- for( Entry<String, JsonElement> entry: errorInfoElement.getAsJsonObject().entrySet() ) {
+ for (Entry<String, JsonElement> entry : errorInfoElement.getAsJsonObject().entrySet()) {
String leafName = entry.getKey();
JsonElement leafElement = entry.getValue();
- actualErrorInfo.put( leafName, leafElement.getAsString() );
+ actualErrorInfo.put(leafName, leafElement.getAsString());
}
- Map<String, String> mutableExpMap = Maps.newHashMap( expErrorInfo );
- for( Entry<String,String> 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<String, String> mutableExpMap = Maps.newHashMap(expErrorInfo);
+ for (Entry<String, String> 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);
}
}
}
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;
@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<RestconfError> 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<RestconfError> 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 = "<address>1.2.3.4</address> <session-id>123</session-id>";
- 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 =
- // "<errors xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\">"+
- // " <error>" +
- // " <error-type>application</error-type>"+
- // " <error-tag>operation-failed</error-tag>"+
- // " <error-message>An error occurred</error-message>"+
- // " <error-info>" +
- // " <session-id>123</session-id>" +
- // " <address>1.2.3.4</address>" +
- // " </error-info>" +
- // " </error>" +
- // "</errors>";
+ // String xml =
+ // "<errors xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\">"+
+ // " <error>" +
+ // " <error-type>application</error-type>"+
+ // " <error-tag>operation-failed</error-tag>"+
+ // " <error-message>An error occurred</error-message>"+
+ // " <error-info>" +
+ // " <session-id>123</session-id>" +
+ // " <address>1.2.3.4</address>" +
+ // " </error-info>" +
+ // " </error>" +
+ // "</errors>";
//
- // 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 = "<address>1.2.3.4</address> <session-id>123</session-id>";
- 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<RestconfError> 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<RestconfError> 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<Entry<String, JsonElement>> errorsEntrySet = rootElement.getAsJsonObject().entrySet();
- assertEquals( "Json Object element set count", 1, errorsEntrySet.size() );
+ assertEquals("Json Object element set count", 1, errorsEntrySet.size());
Entry<String, JsonElement> 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<Entry<String, JsonElement>> 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<String, String> leafMap = Maps.newHashMap();
- for( Entry<String, JsonElement> entry: errorEntryElement.getAsJsonObject().entrySet() ) {
+ for (Entry<String, JsonElement> 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);
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;
}
}
/*
-* 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;
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<String,Integer> lookUpMap = new HashMap<String,Integer>();
-
- 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<String, Integer> lookUpMap = new HashMap<String, Integer>();
+
+ 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 = "<extra><sessionid>session.id</sessionid></extra>";
- 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, "<severity>error</severity>",
- new RestconfError( rpcError ) );
+ validateRestConfError(null, ErrorType.RPC, ErrorTag.ACCESS_DENIED, null, "<severity>error</severity>",
+ 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, "<severity>warning</severity>",
- new RestconfError( rpcError ) );
+ validateRestConfError(null, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED, null,
+ "<severity>warning</severity>", 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<String> errorInfoMatcher, RestconfError e) {
+ private void validateRestConfError(String expectedMessage, ErrorType expectedErrorType, ErrorTag expectedErrorTag,
+ String expectedErrorAppTag, Matcher<String> 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.
}
}
import java.io.FileNotFoundException;
import java.util.Set;
-
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@BeforeClass
public static void init() throws FileNotFoundException {
- Set<Module> allModules = TestUtils
- .loadModulesFrom("/full-versions/yangs");
+ Set<Module> 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));
}
-
}
/**
*
- * 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<Module> modules, String schemaNodePath) {
RestconfImpl restconf = RestconfImpl.getInstance();
}
/**
- * 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<Module> modules) {
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();
}
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) {
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();
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;
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;
import java.io.IOException;
import java.net.URISyntaxException;
-
import javax.ws.rs.WebApplicationException;
-
import org.junit.BeforeClass;
import org.junit.Test;
import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
import 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;
package org.opendaylight.controller.sal.restconf.impl.test.structures;
import static org.junit.Assert.assertFalse;
+
import java.util.HashMap;
import java.util.Map;
}
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);
}
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();;
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<SocketChannel>() {
- @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<SocketChannel>() {
+ @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
@Override
public void onMessageReceived(Object message) {
if (message instanceof TextWebSocketFrame) {
- logger.info("received message {}"+ ((TextWebSocketFrame)message).text());
+ logger.info("received message {}" + ((TextWebSocketFrame) message).text());
}
}
}
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;
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;
}
ctx.close();
}
}
-
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;
@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,
Response responseWithStreamName = post(uri, MediaType.APPLICATION_XML, getRpcInput());
String xmlResponse = responseWithStreamName.readEntity(String.class);
assertNotNull(xmlResponse);
- assertTrue(xmlResponse.contains("<stream-name>ietf-interfaces:interfaces/ietf-interfaces:interface/eth0</stream-name>"));
+ assertTrue(xmlResponse
+ .contains("<stream-name>ietf-interfaces:interfaces/ietf-interfaces:interface/eth0</stream-name>"));
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) {
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;
@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<Module> modules = TestUtils.loadModulesFrom(yangPath);
TestUtils.normalizeCompositeNode(compNode, modules, topLevelElementName + ":" + moduleName);
}
-
}
import java.util.List;
import java.util.Set;
-
import org.junit.Ignore;
import org.junit.Test;
import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
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() {
/**
*
- * Test case like <lf11 xmlns="namespace1"
- * xmlns:x="namespace">identity</lf11>
+ * Test case like <lf11 xmlns="namespace1" xmlns:x="namespace">identity</lf11>
*/
@Test
/**
*
- * Test case like <cont1 xmlns="namespace1"> <lf11
- * xmlns:x="namespace">identity</lf11> </cont1>
+ * Test case like <cont1 xmlns="namespace1"> <lf11 xmlns:x="namespace">identity</lf11> </cont1>
*/
@Test
public void testIdentityrefDefaultNmspcInParrentElement() {
/**
*
- * Test case like <cont1 xmlns="namespace1" xmlns:x="namespace">
- * <lf11>x:identity</lf11> </cont1>
+ * Test case like <cont1 xmlns="namespace1" xmlns:x="namespace"> <lf11>x:identity</lf11> </cont1>
*/
@Ignore
@Test
/**
*
- * Test case like (without namespace in xml) <cont1> <lf11>x:identity</lf11>
- * </cont1>
+ * Test case like (without namespace in xml) <cont1> <lf11>x:identity</lf11> </cont1>
*/
@Test
public void testIdentityrefNoNmspcValueWithPrefix() {
/**
*
- * Test case like (without namespace in xml) <cont1> <lf11>identity</lf11>
- * </cont1>
+ * Test case like (without namespace in xml) <cont1> <lf11>identity</lf11> </cont1>
*/
@Test
public void testIdentityrefNoNmspcValueWithoutPrefix() {
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);
import java.io.ByteArrayInputStream;
import java.io.InputStream;
-
import org.junit.BeforeClass;
import org.junit.Test;
import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
}
@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);
}
}