Organize Imports for Checkstyle compliance.
Checkstyle compliance: line length.
Checkstyle compliance: various types of small changes.
Checkstyle compliant Exception handling.
Checkstyle final clean up & enforcement.
Add the fail on violation flag into the pom.xml .
Change-Id: I81b704c5ed79dead57e5e37c925b4aaa8579444a
Signed-off-by: matus.kubica <matus.kubica@pantheon.tech>
Signed-off-by: Ivan Hrasko <ivan.hrasko@pantheon.tech>
</instructions>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+ </configuration>
+ </plugin>
</plugins>
</build>
<scm>
private final RestConnectorProvider providerDraft18;
/**
- * Init both providers:
+ * Init both providers.
* <ul>
* <li>draft02 - {@link RestconfProviderImpl}
* <li>draft18 - {@link RestConnectorProvider}
* </ul>
*
- * @param port
- * - port for web sockets in provider for draft02
+ * @param port port for web sockets in provider for draft02
*/
public RestconfWrapperProviders(final PortNumber port) {
// Init draft02 provider
}
/**
- * Register both providers, which will use the SAL layer:
+ * Register both providers, which will use the SAL layer.
* <ul>
* <li>draft02 - {@link RestconfProviderImpl}
* <li>draft18 - {@link RestConnectorProvider}
* </ul>
*
* @param broker
- * - {@link Broker}
+ * {@link Broker}
*/
public void registerProviders(final Broker broker) {
// Register draft02 provider
}
/**
- * Register runtime beans from restconf draft02 {@link RestconfProviderImpl}
+ * Register runtime beans from restconf draft02 {@link RestconfProviderImpl}.
*
- * @param runtimeRegistration
- * - for register runtime beans
+ * @param runtimeRegistration for register runtime beans
* @return {@link RestConnectorRuntimeRegistration}
*/
public RestConnectorRuntimeRegistration runtimeRegistration(
import org.osgi.framework.BundleContext;
-public class RestConnectorModule extends org.opendaylight.controller.config.yang.md.sal.rest.connector.AbstractRestConnectorModule {
+public class RestConnectorModule
+ extends org.opendaylight.controller.config.yang.md.sal.rest.connector.AbstractRestConnectorModule {
private static RestConnectorRuntimeRegistration runtimeRegistration;
private BundleContext bundleContext;
- public RestConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
+ public RestConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+ final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
super(identifier, dependencyResolver);
}
- public RestConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, final org.opendaylight.controller.config.yang.md.sal.rest.connector.RestConnectorModule oldModule, final java.lang.AutoCloseable oldInstance) {
+ public RestConnectorModule(
+ final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+ final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,
+ final org.opendaylight.controller.config.yang.md.sal.rest.connector.RestConnectorModule oldModule,
+ final java.lang.AutoCloseable oldInstance) {
super(identifier, dependencyResolver, oldModule, oldInstance);
}
final RestconfWrapperProviders wrapperProviders = new RestconfWrapperProviders(getWebsocketPort());
wrapperProviders.registerProviders(getDomBrokerDependency());
- if(runtimeRegistration != null){
+ if (runtimeRegistration != null) {
runtimeRegistration.close();
}
import org.opendaylight.netconf.sal.restconf.impl.JSONRestconfServiceImpl;
-public class JSONRestconfServiceModule extends org.opendaylight.controller.config.yang.sal.restconf.service.AbstractJSONRestconfServiceModule {
- public JSONRestconfServiceModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
+public class JSONRestconfServiceModule
+ extends org.opendaylight.controller.config.yang.sal.restconf.service.AbstractJSONRestconfServiceModule {
+ public JSONRestconfServiceModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+ org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
super(identifier, dependencyResolver);
}
- public JSONRestconfServiceModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.controller.config.yang.sal.restconf.service.JSONRestconfServiceModule oldModule, java.lang.AutoCloseable oldInstance) {
+ public JSONRestconfServiceModule(
+ org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+ org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,
+ org.opendaylight.controller.config.yang.sal.restconf.service.JSONRestconfServiceModule oldModule,
+ java.lang.AutoCloseable oldInstance) {
super(identifier, dependencyResolver, oldModule, oldInstance);
}
* Do not modify this file unless it is present under src/main directory
*/
package org.opendaylight.controller.config.yang.sal.restconf.service;
-public class JSONRestconfServiceModuleFactory extends org.opendaylight.controller.config.yang.sal.restconf.service.AbstractJSONRestconfServiceModuleFactory {
+public class JSONRestconfServiceModuleFactory
+ extends org.opendaylight.controller.config.yang.sal.restconf.service.AbstractJSONRestconfServiceModuleFactory {
}
* sal-rest-connector
* org.opendaylight.controller.md.sal.rest.common
*
+ * <p>
* Utility class is centralizing all needed validation functionality for a Restconf osgi module.
* All methods have to throw {@link RestconfDocumentedException} only, which is a representation
* for all error situation followed by restconf-netconf specification.
* See also <a href="https://tools.ietf.org/html/draft-bierman-netconf-restconf-02">RESTCONF</a>.
- *
- * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
- *
- * Created: Feb 24, 2015
*/
public class RestconfValidationUtils {
- private RestconfValidationUtils () {
+ private RestconfValidationUtils() {
throw new UnsupportedOperationException("Utility class");
}
*/
public static void checkDocumentedError(final boolean condition, final ErrorType type,
final ErrorTag tag, final String message) {
- if(!condition) {
+ if (!condition) {
throw new RestconfDocumentedException(message, type, tag);
}
}
* @return - T value (same input value)
*/
public static <T> T checkNotNullDocumented(final T value, final String moduleName) {
- if(value == null) {
+ if (value == null) {
final String errMsg = "Module " + moduleName + " was not found.";
throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
}
}
@Override
- public long getSize(final SchemaExportContext t, final Class<?> type, final Type genericType,
+ public long getSize(final SchemaExportContext context, final Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType) {
return -1;
}
@Override
- public void writeTo(final SchemaExportContext t, final Class<?> type, final Type genericType,
+ public void writeTo(final SchemaExportContext context, final Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType,
final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException,
WebApplicationException {
final PrintWriter writer = new PrintWriter(entityStream);
- writer.write(t.getModule().getSource());
+ writer.write(context.getModule().getSource());
}
}
}
@Override
- public long getSize(final SchemaExportContext t, final Class<?> type, final Type genericType,
+ public long getSize(final SchemaExportContext context, final Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType) {
return -1;
}
@Override
- public void writeTo(final SchemaExportContext t, final Class<?> type, final Type genericType,
+ public void writeTo(final SchemaExportContext context, final Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType,
final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException,
WebApplicationException {
try {
- YinExportUtils.writeModuleToOutputStream(t.getSchemaContext(), t.getModule(), entityStream);
+ YinExportUtils.writeModuleToOutputStream(context.getSchemaContext(), context.getModule(), entityStream);
} catch (final XMLStreamException e) {
throw new IllegalStateException(e);
}
import org.opendaylight.restconf.base.services.api.RestconfSchemaService;
/**
+ * Retrieval of the YANG modules which server supports.
+ *
* @deprecated do not use this api. It is replaced by
* {@link RestconfSchemaService}
*/
@Beta
public interface SchemaRetrievalService {
- public static final String YANG_MEDIA_TYPE = "application/yang";
- public static final String YIN_MEDIA_TYPE = "application/yin+xml";
+ String YANG_MEDIA_TYPE = "application/yang";
+ String YIN_MEDIA_TYPE = "application/yin+xml";
@GET
@Produces({YIN_MEDIA_TYPE,YANG_MEDIA_TYPE})
final SchemaContext schemaContext;
final Iterable<String> pathComponents = SLASH_SPLITTER.split(mountAndModule);
final Iterator<String> componentIter = pathComponents.iterator();
- if(!Iterables.contains(pathComponents, MOUNT_ARG)) {
+ if (!Iterables.contains(pathComponents, MOUNT_ARG)) {
schemaContext = salContext.getGlobalSchema();
} else {
final StringBuilder pathBuilder = new StringBuilder();
- while(componentIter.hasNext()) {
+ while (componentIter.hasNext()) {
final String current = componentIter.next();
// It is argument, not last element.
- if(pathBuilder.length() != 0) {
- pathBuilder.append("/");
+ if (pathBuilder.length() != 0) {
+ pathBuilder.append("/");
}
pathBuilder.append(current);
- if(MOUNT_ARG.equals(current)) {
+ if (MOUNT_ARG.equals(current)) {
// We stop right at mountpoint, last two arguments should
// be module name and revision
break;
try {
final Date revision = SimpleDateFormatUtil.getRevisionFormat().parse(revisionStr);
final Module module = schemaContext.findModuleByName(moduleName, revision);
- return new SchemaExportContext(schemaContext, RestconfValidationUtils.checkNotNullDocumented(module, moduleName));
+ return new SchemaExportContext(
+ schemaContext, RestconfValidationUtils.checkNotNullDocumented(module, moduleName));
} catch (final ParseException e) {
throw new RestconfDocumentedException("Supplied revision is not in expected date format YYYY-mm-dd", e);
}
import org.opendaylight.yangtools.yang.common.QName;
/**
+ * Base Draft for Restconf project.
+ *
* @deprecated Do not use old implementation of restconf draft. It will be
* replaced by {@link Rfc8040}.
- *
*/
@Deprecated
public class Draft02 {
- public static interface MediaTypes {
+ public interface MediaTypes {
String API = "application/yang.api";
String DATASTORE = "application/yang.datastore";
String DATA = "application/yang.data";
String STREAM = "application/yang.stream";
}
- public static interface RestConfModule {
+ public interface RestConfModule {
String REVISION = "2013-10-19";
String NAME = "ietf-restconf";
QName ERROR_INFO_QNAME = QName.create(IETF_RESTCONF_QNAME, "error-info");
}
- public static interface Paths {
-
- }
+ public interface Paths {}
}
public interface RestconfConstants {
+ String IDENTIFIER = "identifier";
- public static String IDENTIFIER = "identifier";
}
public interface RestconfNormalizedNodeWriter extends Flushable, Closeable {
- RestconfNormalizedNodeWriter write(final NormalizedNode<?, ?> node) throws IOException;
+ RestconfNormalizedNodeWriter write(NormalizedNode<?, ?> node) throws IOException;
}
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.opendaylight.netconf.sal.rest.api.Draft02.MediaTypes;
-import org.opendaylight.netconf.sal.rest.impl.PATCH;
+import org.opendaylight.netconf.sal.rest.impl.Patch;
import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchStatusContext;
import org.opendaylight.restconf.base.services.api.RestconfOperationsService;
import org.opendaylight.restconf.restful.services.api.RestconfDataService;
import org.opendaylight.restconf.restful.services.api.RestconfInvokeOperationsService;
+import org.opendaylight.restconf.restful.services.api.RestconfStreamsSubscriptionService;
/**
* The URI hierarchy for the RESTCONF resources consists of an entry point
@Path("/")
public interface RestconfService {
- public static final String XML = "+xml";
- public static final String JSON = "+json";
+ String XML = "+xml";
+ String JSON = "+json";
@GET
- public Object getRoot();
+ Object getRoot();
/**
+ * Get all modules supported by controller.
+ *
+ * @param uriInfo URI info
+ * @return {@link NormalizedNodeContext}
* @deprecated do not use this method. It will be replaced by
* {@link RestconfDataService#readData(UriInfo)}
*/
@Path("/modules")
@Produces({ Draft02.MediaTypes.API + JSON, Draft02.MediaTypes.API + XML, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML, MediaType.TEXT_XML })
- public NormalizedNodeContext getModules(@Context UriInfo uriInfo);
+ NormalizedNodeContext getModules(@Context UriInfo uriInfo);
/**
+ * Get all modules supported by mount point.
+ *
+ * @param identifier mount point identifier
+ * @param uriInfo URI info
+ * @return {@link NormalizedNodeContext}
* @deprecated do not use this method. It will be replaced by
* {@link RestconfDataService#readData(String, UriInfo)}
*/
@Path("/modules/{identifier:.+}")
@Produces({ Draft02.MediaTypes.API + JSON, Draft02.MediaTypes.API + XML, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML, MediaType.TEXT_XML })
- public NormalizedNodeContext getModules(@PathParam("identifier") String identifier, @Context UriInfo uriInfo);
+ NormalizedNodeContext getModules(@PathParam("identifier") String identifier, @Context UriInfo uriInfo);
/**
+ * Get module.
+ *
+ * @param identifier path to target
+ * @param uriInfo URI info
+ * @return {@link NormalizedNodeContext}
* @deprecated do not use this method. It will be replaced by
* {@link RestconfDataService#readData(String, UriInfo)}
*/
@Path("/modules/module/{identifier:.+}")
@Produces({ Draft02.MediaTypes.API + JSON, Draft02.MediaTypes.API + XML, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML, MediaType.TEXT_XML })
- public NormalizedNodeContext getModule(@PathParam("identifier") String identifier, @Context UriInfo uriInfo);
+ NormalizedNodeContext getModule(@PathParam("identifier") String identifier, @Context UriInfo uriInfo);
/**
+ * List of rpc or action operations supported by the server.
+ *
+ * @param uriInfo URI information
+ * @return {@link NormalizedNodeContext}
* @deprecated do not use this method. It will be replaced by
* {@link RestconfOperationsService#getOperations(UriInfo)}
*/
@Path("/operations")
@Produces({ Draft02.MediaTypes.API + JSON, Draft02.MediaTypes.API + XML, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML, MediaType.TEXT_XML })
- public NormalizedNodeContext getOperations(@Context UriInfo uriInfo);
+ NormalizedNodeContext getOperations(@Context UriInfo uriInfo);
/**
+ * Valid for mount points. List of operations supported by the server.
+ *
+ * @param identifier path parameter
+ * @param uriInfo URI information
+ * @return {@link NormalizedNodeContext}
* @deprecated do not use this method. It will be replaced by
* {@link RestconfOperationsService#getOperations(String, UriInfo)}
*/
@Path("/operations/{identifier:.+}")
@Produces({ Draft02.MediaTypes.API + JSON, Draft02.MediaTypes.API + XML, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML, MediaType.TEXT_XML })
- public NormalizedNodeContext getOperations(@PathParam("identifier") String identifier, @Context UriInfo uriInfo);
+ NormalizedNodeContext getOperations(@PathParam("identifier") String identifier, @Context UriInfo uriInfo);
/**
+ * Invoke RPC operation.
+ *
+ * @param identifier module name and rpc identifier string for the desired operation
+ * @param payload {@link NormalizedNodeContext} - the body of the operation
+ * @param uriInfo URI info
+ * @return {@link NormalizedNodeContext}
* @deprecated do not use this method. It will be replaced by
* {@link RestconfInvokeOperationsService#invokeRpc(String, NormalizedNodeContext, UriInfo)}
*/
@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 NormalizedNodeContext invokeRpc(@Encoded @PathParam("identifier") String identifier, NormalizedNodeContext payload,
+ NormalizedNodeContext invokeRpc(@Encoded @PathParam("identifier") String identifier, NormalizedNodeContext payload,
@Context UriInfo uriInfo);
+ /**
+ * Invoke RPC with default empty payload.
+ *
+ * @param identifier module name and rpc identifier string for the desired operation
+ * @param noPayload the body of the operation
+ * @param uriInfo URI info
+ * @return {@link NormalizedNodeContext}
+ * @deprecated Method is not used and will be removed
+ */
@POST
@Path("/operations/{identifier:.+}")
@Produces({ 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 })
@Deprecated // method isn't use anywhere
- public NormalizedNodeContext invokeRpc(@Encoded @PathParam("identifier") String identifier,
+ NormalizedNodeContext invokeRpc(@Encoded @PathParam("identifier") String identifier,
@DefaultValue("") String noPayload, @Context UriInfo uriInfo);
/**
+ * Get target data resource from config data store.
+ *
+ * @param identifier path to target
+ * @param uriInfo URI info
+ * @return {@link NormalizedNodeContext}
* @deprecated do not use this method. It will be replaced by
* {@link RestconfDataService#readData(String, UriInfo)}
*/
@Path("/config/{identifier:.+}")
@Produces({ Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML, MediaType.TEXT_XML })
- public NormalizedNodeContext readConfigurationData(@Encoded @PathParam("identifier") String identifier,
+ NormalizedNodeContext readConfigurationData(@Encoded @PathParam("identifier") String identifier,
@Context UriInfo uriInfo);
/**
+ * Get target data resource from operational data store.
+ *
+ * @param identifier path to target
+ * @param uriInfo URI info
+ * @return {@link NormalizedNodeContext}
* @deprecated do not use this method. It will be replaced by
* {@link RestconfDataService#readData(String, UriInfo)}
*/
@Path("/operational/{identifier:.+}")
@Produces({ Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML, MediaType.TEXT_XML })
- public NormalizedNodeContext readOperationalData(@Encoded @PathParam("identifier") String identifier,
+ NormalizedNodeContext readOperationalData(@Encoded @PathParam("identifier") String identifier,
@Context UriInfo uriInfo);
/**
+ * Create or replace the target data resource.
+ *
+ * @param identifier path to target
+ * @param payload data node for put to config DS
+ * @return {@link Response}
* @deprecated do not use this method. It will be replaced by
* {@link RestconfDataService#putData(String, NormalizedNodeContext, UriInfo)}
*/
@Path("/config/{identifier:.+}")
@Consumes({ Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML, MediaType.TEXT_XML })
- public Response updateConfigurationData(@Encoded @PathParam("identifier") String identifier,
+ Response updateConfigurationData(@Encoded @PathParam("identifier") String identifier,
NormalizedNodeContext payload, @Context UriInfo uriInfo);
/**
+ * Create a data resource in target.
+ *
+ * @param identifier path to target
+ * @param payload new data
+ * @param uriInfo URI info
+ * @return {@link Response}
* @deprecated do not use this method. It will be replaced by
* {@link RestconfDataService#postData(String, NormalizedNodeContext, UriInfo)}
*/
@Path("/config/{identifier:.+}")
@Consumes({ Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML, MediaType.TEXT_XML })
- public Response createConfigurationData(@Encoded @PathParam("identifier") String identifier, NormalizedNodeContext payload,
+ Response createConfigurationData(@Encoded @PathParam("identifier") String identifier, NormalizedNodeContext payload,
@Context UriInfo uriInfo);
/**
+ * Create a data resource.
+ *
+ * @param payload new data
+ * @param uriInfo URI info
+ * @return {@link Response}
* @deprecated do not use this method. It will be replaced by
* {@link RestconfDataService#postData(NormalizedNodeContext, UriInfo)}
*/
@Path("/config")
@Consumes({ Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML, MediaType.TEXT_XML })
- public Response createConfigurationData(NormalizedNodeContext payload, @Context UriInfo uriInfo);
+ Response createConfigurationData(NormalizedNodeContext payload, @Context UriInfo uriInfo);
/**
+ * Delete the target data resource.
+ *
+ * @param identifier path to target
+ * @return {@link Response}
* @deprecated do not use this method. It will be replaced by
* {@link RestconfDataService#deleteData(String)}
*/
@Deprecated
@DELETE
@Path("/config/{identifier:.+}")
- public Response deleteConfigurationData(@Encoded @PathParam("identifier") String identifier);
+ Response deleteConfigurationData(@Encoded @PathParam("identifier") String identifier);
+ /**
+ * Subscribe to stream.
+ *
+ * @param identifier stream identifier
+ * @param uriInfo URI info
+ * @return {@link NormalizedNodeContext}
+ * @deprecated do not use this method. It will be replaced by
+ * {@link RestconfStreamsSubscriptionService#subscribeToStream(String, UriInfo)}
+ */
+ @Deprecated
@GET
@Path("/streams/stream/{identifier:.+}")
- public NormalizedNodeContext subscribeToStream(@Encoded @PathParam("identifier") String identifier,
+ NormalizedNodeContext subscribeToStream(@Encoded @PathParam("identifier") String identifier,
@Context UriInfo uriInfo);
/**
+ * Get list of all streams.
+ *
+ * @param uriInfo URI info
+ * @return {@link NormalizedNodeContext}
* @deprecated do not use this method. It will be replaced by
* {@link RestconfDataService#readData(String, UriInfo)}
- */
+ **/
@Deprecated
@GET
@Path("/streams")
@Produces({ Draft02.MediaTypes.API + JSON, Draft02.MediaTypes.API + XML, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML, MediaType.TEXT_XML })
- public NormalizedNodeContext getAvailableStreams(@Context UriInfo uriInfo);
+ NormalizedNodeContext getAvailableStreams(@Context UriInfo uriInfo);
/**
+ * Ordered list of edits that are applied to the target datastore by the server.
+ *
+ * @param identifier path to target
+ * @param context edits
+ * @param uriInfo URI info
+ * @return {@link PatchStatusContext}
* @deprecated do not use this method. It will be replaced by
- * {@link RestconfDataService#patchData(String, PATCHContext, UriInfo)}
+ * {@link RestconfDataService#patchData(String, PatchContext, UriInfo)}
*/
@Deprecated
- @PATCH
+ @Patch
@Path("/config/{identifier:.+}")
@Consumes({MediaTypes.PATCH + JSON, MediaTypes.PATCH + XML})
@Produces({MediaTypes.PATCH_STATUS + JSON, MediaTypes.PATCH_STATUS + XML})
- PATCHStatusContext patchConfigurationData(@Encoded @PathParam("identifier") String identifier, PATCHContext
+ PatchStatusContext patchConfigurationData(@Encoded @PathParam("identifier") String identifier, PatchContext
context, @Context UriInfo uriInfo);
/**
+ * Ordered list of edits that are applied to the datastore by the server.
+ *
+ * @param context edits
+ * @param uriInfo URI info
+ * @return {@link PatchStatusContext}
* @deprecated do not use this method. It will be replaced by
- * {@link RestconfDataService#patchData(PATCHContext, UriInfo)}
+ * {@link RestconfDataService#patchData(PatchContext, UriInfo)}
*/
@Deprecated
- @PATCH
+ @Patch
@Path("/config")
@Consumes({MediaTypes.PATCH + JSON, MediaTypes.PATCH + XML})
@Produces({MediaTypes.PATCH_STATUS + JSON, MediaTypes.PATCH_STATUS + XML})
- PATCHStatusContext patchConfigurationData(PATCHContext context, @Context UriInfo uriInfo);
+ PatchStatusContext patchConfigurationData(PatchContext context, @Context UriInfo uriInfo);
}
import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
/**
+ * JAX-RS Provider.
+ *
* @deprecated This class will be replaced by
* {@link org.opendaylight.restconf.jersey.providers.AbstractIdentifierAwareJaxRsProvider}
*/
* @param writer Back-end writer
* @return A new instance.
*/
- public static DepthAwareNormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer, final int maxDepth) {
+ public static DepthAwareNormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
+ final int maxDepth) {
return forStreamWriter(writer, true, maxDepth);
}
/**
- * Create a new writer backed by a {@link NormalizedNodeStreamWriter}. Unlike the simple {@link #forStreamWriter(NormalizedNodeStreamWriter, int)}
+ * Create a new writer backed by a {@link NormalizedNodeStreamWriter}.
+ * Unlike the simple {@link #forStreamWriter(NormalizedNodeStreamWriter, int)}
* method, this allows the caller to switch off RFC6020 XML compliance, providing better
* throughput. The reason is that the XML mapping rules in RFC6020 require the encoding
* to emit leaf nodes which participate in a list's key first and in the order in which
* @param orderKeyLeaves whether the returned instance should be RFC6020 XML compliant.
* @return A new instance.
*/
- public static DepthAwareNormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer, final boolean
- orderKeyLeaves, final int maxDepth) {
+ public static DepthAwareNormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
+ final boolean orderKeyLeaves, final int maxDepth) {
if (orderKeyLeaves) {
return new OrderedDepthAwareNormalizedNodeWriter(writer, maxDepth);
} else {
* events to the encapsulated {@link NormalizedNodeStreamWriter}.
*
* @param node Node
- * @return
+ * @return DepthAwareNormalizedNodeWriter
* @throws IOException when thrown from the backing writer.
*/
public final DepthAwareNormalizedNodeWriter write(final NormalizedNode<?, ?> node) throws IOException {
return true;
} else if (node instanceof LeafNode) {
final LeafNode<?> nodeAsLeaf = (LeafNode<?>)node;
- if(writer instanceof NormalizedNodeStreamAttributeWriter) {
- ((NormalizedNodeStreamAttributeWriter) writer).leafNode(nodeAsLeaf.getIdentifier(), nodeAsLeaf.getValue(), nodeAsLeaf.getAttributes());
+ if (writer instanceof NormalizedNodeStreamAttributeWriter) {
+ ((NormalizedNodeStreamAttributeWriter) writer)
+ .leafNode(nodeAsLeaf.getIdentifier(), nodeAsLeaf.getValue(), nodeAsLeaf.getAttributes());
} else {
writer.leafNode(nodeAsLeaf.getIdentifier(), nodeAsLeaf.getValue());
}
}
protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
- if(writer instanceof NormalizedNodeStreamAttributeWriter) {
+ if (writer instanceof NormalizedNodeStreamAttributeWriter) {
((NormalizedNodeStreamAttributeWriter) writer)
.startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()), node.getAttributes());
} else {
boolean processedAsCompositeNode = false;
if (node instanceof ContainerNode) {
final ContainerNode n = (ContainerNode) node;
- if(writer instanceof NormalizedNodeStreamAttributeWriter) {
- ((NormalizedNodeStreamAttributeWriter) writer).startContainerNode(n.getIdentifier(), childSizeHint(n.getValue()), n.getAttributes());
+ if (writer instanceof NormalizedNodeStreamAttributeWriter) {
+ ((NormalizedNodeStreamAttributeWriter) writer)
+ .startContainerNode(n.getIdentifier(), childSizeHint(n.getValue()), n.getAttributes());
} else {
writer.startContainerNode(n.getIdentifier(), childSizeHint(n.getValue()));
}
currentDepth++;
processedAsCompositeNode = writeChildren(n.getValue());
currentDepth--;
- }
- else if (node instanceof MapEntryNode) {
- processedAsCompositeNode = writeMapEntryNode((MapEntryNode) node);
- }
- else if (node instanceof UnkeyedListEntryNode) {
+ } else if (node instanceof MapEntryNode) {
+ processedAsCompositeNode = writeMapEntryNode((MapEntryNode) node);
+ } else if (node instanceof UnkeyedListEntryNode) {
final UnkeyedListEntryNode n = (UnkeyedListEntryNode) node;
writer.startUnkeyedListItem(n.getIdentifier(), childSizeHint(n.getValue()));
currentDepth++;
processedAsCompositeNode = writeChildren(n.getValue());
currentDepth--;
- }
- else if (node instanceof ChoiceNode) {
+ } else if (node instanceof ChoiceNode) {
final ChoiceNode n = (ChoiceNode) node;
writer.startChoiceNode(n.getIdentifier(), childSizeHint(n.getValue()));
processedAsCompositeNode = writeChildren(n.getValue());
- }
- else if (node instanceof AugmentationNode) {
+ } else if (node instanceof AugmentationNode) {
final AugmentationNode n = (AugmentationNode) node;
writer.startAugmentationNode(n.getIdentifier());
processedAsCompositeNode = writeChildren(n.getValue());
- }
- else if (node instanceof UnkeyedListNode) {
+ } else if (node instanceof UnkeyedListNode) {
final UnkeyedListNode n = (UnkeyedListNode) node;
writer.startUnkeyedList(n.getIdentifier(), childSizeHint(n.getValue()));
processedAsCompositeNode = writeChildren(n.getValue());
- }
- else if (node instanceof OrderedMapNode) {
+ } else if (node instanceof OrderedMapNode) {
final OrderedMapNode n = (OrderedMapNode) node;
writer.startOrderedMapNode(n.getIdentifier(), childSizeHint(n.getValue()));
processedAsCompositeNode = writeChildren(n.getValue());
- }
- else if (node instanceof MapNode) {
+ } else if (node instanceof MapNode) {
final MapNode n = (MapNode) node;
writer.startMapNode(n.getIdentifier(), childSizeHint(n.getValue()));
processedAsCompositeNode = writeChildren(n.getValue());
- }
- else if (node instanceof LeafSetNode) {
+ } else if (node instanceof LeafSetNode) {
final LeafSetNode<?> n = (LeafSetNode<?>) node;
if (node instanceof OrderedLeafSetNode) {
writer.startOrderedLeafSet(n.getIdentifier(), childSizeHint(n.getValue()));
@Override
protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
final NormalizedNodeStreamWriter writer = getWriter();
- if(writer instanceof NormalizedNodeStreamAttributeWriter) {
- ((NormalizedNodeStreamAttributeWriter) writer).startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()), node.getAttributes());
+ if (writer instanceof NormalizedNodeStreamAttributeWriter) {
+ ((NormalizedNodeStreamAttributeWriter) writer)
+ .startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()), node.getAttributes());
} else {
writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
}
@Provider
@Consumes({ Draft02.MediaTypes.DATA + RestconfService.JSON, Draft02.MediaTypes.OPERATION + RestconfService.JSON,
Rfc8040.MediaTypes.DATA + RestconfConstants.JSON, MediaType.APPLICATION_JSON })
-public class JsonNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsProvider implements MessageBodyReader<NormalizedNodeContext> {
+public class JsonNormalizedNodeBodyReader
+ extends AbstractIdentifierAwareJaxRsProvider implements MessageBodyReader<NormalizedNodeContext> {
- private final static Logger LOG = LoggerFactory.getLogger(JsonNormalizedNodeBodyReader.class);
+ private static final Logger LOG = LoggerFactory.getLogger(JsonNormalizedNodeBodyReader.class);
@Override
public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
return true;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType,
}
}
- private static void propagateExceptionAs(final Exception e) throws RestconfDocumentedException {
- if(e instanceof RestconfDocumentedException) {
- throw (RestconfDocumentedException)e;
- }
-
- if(e instanceof ResultAlreadySetException) {
- LOG.debug("Error parsing json input:", e);
-
- throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. " +
- "Are you creating multiple resources/subresources in POST request?");
- }
-
- LOG.debug("Error parsing json input", e);
-
- throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
- ErrorTag.MALFORMED_MESSAGE, e);
- }
-
+ @SuppressWarnings("checkstyle:IllegalCatch")
public static NormalizedNodeContext readFrom(final String uriPath, final InputStream entityStream,
- final boolean isPost) throws RestconfDocumentedException {
+ final boolean isPost) throws RestconfDocumentedException {
try {
return readFrom(ControllerContext.getInstance().toInstanceIdentifier(uriPath), entityStream, isPost);
}
}
- private static NormalizedNodeContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream,
- final boolean isPost) throws IOException {
+ private static NormalizedNodeContext readFrom(final InstanceIdentifierContext<?> path,
+ final InputStream entityStream, final boolean isPost)
+ throws IOException {
if (entityStream.available() < 1) {
return new NormalizedNodeContext(path, null);
}
final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
final SchemaNode parentSchema;
- if(isPost) {
+ if (isPost) {
// FIXME: We need dispatch for RPC.
parentSchema = path.getSchemaNode();
- } else if(path.getSchemaNode() instanceof SchemaContext) {
+ } else if (path.getSchemaNode() instanceof SchemaContext) {
parentSchema = path.getSchemaContext();
} else {
if (SchemaPath.ROOT.equals(path.getSchemaNode().getPath().getParent())) {
parentSchema = path.getSchemaContext();
} else {
- parentSchema = SchemaContextUtil.findDataSchemaNode(path.getSchemaContext(), path.getSchemaNode().getPath().getParent());
+ parentSchema = SchemaContextUtil
+ .findDataSchemaNode(path.getSchemaContext(), path.getSchemaNode().getPath().getParent());
}
}
return new NormalizedNodeContext(newIIContext, result);
}
+
+ private static void propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
+ if (exception instanceof RestconfDocumentedException) {
+ throw (RestconfDocumentedException)exception;
+ }
+
+ if (exception instanceof ResultAlreadySetException) {
+ LOG.debug("Error parsing json input:", exception);
+
+ throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. "
+ + "Are you creating multiple resources/subresources in POST request?");
+ }
+
+ LOG.debug("Error parsing json input", exception);
+
+ throw new RestconfDocumentedException("Error parsing input: " + exception.getMessage(), ErrorType.PROTOCOL,
+ ErrorTag.MALFORMED_MESSAGE, exception);
+ }
}
package org.opendaylight.netconf.sal.rest.impl;
-import static org.opendaylight.netconf.sal.restconf.impl.PATCHEditOperation.isPatchOperationWithValue;
+import static org.opendaylight.netconf.sal.restconf.impl.PatchEditOperation.isPatchOperationWithValue;
import com.google.common.collect.ImmutableList;
import com.google.gson.stream.JsonReader;
import org.opendaylight.netconf.sal.rest.api.RestconfService;
import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHEntity;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchEntity;
import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
import org.slf4j.LoggerFactory;
/**
+ * Patch reader for JSON.
+ *
* @deprecated This class will be replaced by
- * {@link org.opendaylight.restconf.jersey.providers.JsonToPATCHBodyReader}
+ * {@link org.opendaylight.restconf.jersey.providers.JsonToPatchBodyReader}
*/
@Deprecated
@Provider
@Consumes({Draft02.MediaTypes.PATCH + RestconfService.JSON})
-public class JsonToPATCHBodyReader extends AbstractIdentifierAwareJaxRsProvider
- implements MessageBodyReader<PATCHContext> {
+public class JsonToPatchBodyReader extends AbstractIdentifierAwareJaxRsProvider
+ implements MessageBodyReader<PatchContext> {
- private final static Logger LOG = LoggerFactory.getLogger(JsonToPATCHBodyReader.class);
+ private static final Logger LOG = LoggerFactory.getLogger(JsonToPatchBodyReader.class);
private String patchId;
@Override
return true;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
- public PATCHContext readFrom(final Class<PATCHContext> type, final Type genericType,
+ public PatchContext readFrom(final Class<PatchContext> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType,
final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
throws IOException, WebApplicationException {
}
}
- private static RuntimeException propagateExceptionAs(final Exception e) throws RestconfDocumentedException {
- if (e instanceof RestconfDocumentedException) {
- throw (RestconfDocumentedException)e;
- }
-
- if (e instanceof ResultAlreadySetException) {
- LOG.debug("Error parsing json input:", e);
- throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. ");
- }
-
- throw new RestconfDocumentedException("Error parsing json input: " + e.getMessage(), ErrorType.PROTOCOL,
- ErrorTag.MALFORMED_MESSAGE, e);
- }
-
- public PATCHContext readFrom(final String uriPath, final InputStream entityStream) throws
+ @SuppressWarnings("checkstyle:IllegalCatch")
+ public PatchContext readFrom(final String uriPath, final InputStream entityStream) throws
RestconfDocumentedException {
try {
return readFrom(ControllerContext.getInstance().toInstanceIdentifier(uriPath), entityStream);
}
}
- private PATCHContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream)
+ private PatchContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream)
throws IOException {
if (entityStream.available() < 1) {
- return new PATCHContext(path, null, null);
+ return new PatchContext(path, null, null);
}
final JsonReader jsonReader = new JsonReader(new InputStreamReader(entityStream));
- final List<PATCHEntity> resultList = read(jsonReader, path);
+ final List<PatchEntity> resultList = read(jsonReader, path);
jsonReader.close();
- return new PATCHContext(path, resultList, this.patchId);
+ return new PatchContext(path, resultList, this.patchId);
+ }
+
+ private static RuntimeException propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
+ if (exception instanceof RestconfDocumentedException) {
+ throw (RestconfDocumentedException)exception;
+ }
+
+ if (exception instanceof ResultAlreadySetException) {
+ LOG.debug("Error parsing json input:", exception);
+ throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. ");
+ }
+
+ throw new RestconfDocumentedException("Error parsing json input: " + exception.getMessage(), ErrorType.PROTOCOL,
+ ErrorTag.MALFORMED_MESSAGE, exception);
}
- private List<PATCHEntity> read(final JsonReader in, final InstanceIdentifierContext path) throws IOException {
- final List<PATCHEntity> resultCollection = new ArrayList<>();
+ private List<PatchEntity> read(final JsonReader in, final InstanceIdentifierContext path) throws IOException {
+ final List<PatchEntity> resultCollection = new ArrayList<>();
final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
path.getSchemaContext());
- final JsonToPATCHBodyReader.PatchEdit edit = new JsonToPATCHBodyReader.PatchEdit();
+ final JsonToPatchBodyReader.PatchEdit edit = new JsonToPatchBodyReader.PatchEdit();
while (in.hasNext()) {
switch (in.peek()) {
}
/**
- * Switch value of parsed JsonToken.NAME and read edit definition or patch id
+ * Switch value of parsed JsonToken.NAME and read edit definition or patch id.
+ *
* @param name value of token
* @param edit PatchEdit instance
* @param in JsonReader reader
* @param path InstanceIdentifierContext context
* @param codec StringModuleInstanceIdentifierCodec codec
* @param resultCollection collection of parsed edits
- * @throws IOException
+ * @throws IOException if operation fails
*/
private void parseByName(@Nonnull final String name, @Nonnull final PatchEdit edit,
@Nonnull final JsonReader in, @Nonnull final InstanceIdentifierContext path,
@Nonnull final StringModuleInstanceIdentifierCodec codec,
- @Nonnull final List<PATCHEntity> resultCollection) throws IOException {
+ @Nonnull final List<PatchEntity> resultCollection) throws IOException {
switch (name) {
case "edit" :
if (in.peek() == JsonToken.BEGIN_ARRAY) {
}
/**
- * Read one patch edit object from Json input
+ * Read one patch edit object from Json input.
* @param edit PatchEdit instance to be filled with read data
* @param in JsonReader reader
* @param path InstanceIdentifierContext path context
* @param codec StringModuleInstanceIdentifierCodec codec
- * @throws IOException
+ * @throws IOException if operation fails
*/
private void readEditDefinition(@Nonnull final PatchEdit edit, @Nonnull final JsonReader in,
@Nonnull final InstanceIdentifierContext path,
in.endObject();
// read saved data to normalized node when target schema is already known
- edit.setData(readEditData(new JsonReader(new StringReader(value.toString())), edit.getTargetSchemaNode(), path));
+ edit.setData(readEditData(new JsonReader(
+ new StringReader(value.toString())), edit.getTargetSchemaNode(), path));
}
/**
- * Parse data defined in value node and saves it to buffer
+ * Parse data defined in value node and saves it to buffer.
* @param value Buffer to read value node
* @param in JsonReader reader
- * @throws IOException
+ * @throws IOException if operation fails
*/
private void readValueNode(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
in.beginObject();
}
/**
- * Parse one value object of data and saves it to buffer
+ * Parse one value object of data and saves it to buffer.
* @param value Buffer to read value object
* @param in JsonReader reader
- * @throws IOException
+ * @throws IOException if operation fails
*/
private void readValueObject(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
// read simple leaf value
}
/**
- * Read patch edit data defined in value node to NormalizedNode
+ * Read patch edit data defined in value node to NormalizedNode.
* @param in reader JsonReader reader
* @return NormalizedNode representing data
*/
}
/**
- * Prepare PATCHEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception
+ * Prepare PatchEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception.
* @param edit Instance of PatchEdit
- * @return PATCHEntity
+ * @return PatchEntity Patch entity
*/
- private static PATCHEntity prepareEditOperation(@Nonnull final PatchEdit edit) {
+ private static PatchEntity prepareEditOperation(@Nonnull final PatchEdit edit) {
if ((edit.getOperation() != null) && (edit.getTargetSchemaNode() != null)
&& checkDataPresence(edit.getOperation(), (edit.getData() != null))) {
if (isPatchOperationWithValue(edit.getOperation())) {
targetNode = edit.getTarget();
}
- return new PATCHEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
+ return new PatchEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
} else {
- return new PATCHEntity(edit.getId(), edit.getOperation(), edit.getTarget());
+ return new PatchEntity(edit.getId(), edit.getOperation(), edit.getTarget());
}
}
}
/**
- * Check if data is present when operation requires it and not present when operation data is not allowed
+ * Check if data is present when operation requires it and not present when operation data is not allowed.
* @param operation Name of operation
* @param hasData Data in edit are present/not present
* @return true if data is present when operation requires it or if there are no data when operation does not
- * allow it, false otherwise
+ * allow it, false otherwise
*/
private static boolean checkDataPresence(@Nonnull final String operation, final boolean hasData) {
if (isPatchOperationWithValue(operation)) {
}
/**
- * Helper class representing one patch edit
+ * Helper class representing one patch edit.
*/
private static final class PatchEdit {
private String id;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
/**
+ * Normalized node writer for JSON.
+ *
* @deprecated This class will be replaced by
* {@link org.opendaylight.restconf.jersey.providers.NormalizedNodeJsonBodyWriter}
*/
}
@Override
- public long getSize(final NormalizedNodeContext t, final Class<?> type, final Type genericType,
+ public long getSize(final NormalizedNodeContext context, final Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType) {
return -1;
}
@Override
- public void writeTo(final NormalizedNodeContext t, final Class<?> type, final Type genericType,
+ public void writeTo(final NormalizedNodeContext context, final Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders,
final OutputStream entityStream) throws IOException, WebApplicationException {
- for (final Entry<String, Object> entry : t.getNewHeaders().entrySet()) {
+ for (final Entry<String, Object> entry : context.getNewHeaders().entrySet()) {
httpHeaders.add(entry.getKey(), entry.getValue());
}
- final NormalizedNode<?, ?> data = t.getData();
+ final NormalizedNode<?, ?> data = context.getData();
if (data == null) {
return;
}
@SuppressWarnings("unchecked")
- final InstanceIdentifierContext<SchemaNode> context =
- (InstanceIdentifierContext<SchemaNode>) t.getInstanceIdentifierContext();
+ final InstanceIdentifierContext<SchemaNode> identifierCtx =
+ (InstanceIdentifierContext<SchemaNode>) context.getInstanceIdentifierContext();
- final SchemaPath path = context.getSchemaNode().getPath();
- final JsonWriter jsonWriter = createJsonWriter(entityStream, t.getWriterParameters().isPrettyPrint());
+ final SchemaPath path = identifierCtx.getSchemaNode().getPath();
+ final JsonWriter jsonWriter = createJsonWriter(entityStream, context.getWriterParameters().isPrettyPrint());
jsonWriter.beginObject();
- writeNormalizedNode(jsonWriter,path,context,data, Optional.fromNullable(t.getWriterParameters().getDepth()));
+ writeNormalizedNode(
+ jsonWriter,path,identifierCtx,data, Optional.fromNullable(context.getWriterParameters().getDepth()));
jsonWriter.endObject();
jsonWriter.flush();
}
} else {
path = path.getParent();
- if(data instanceof MapEntryNode) {
+ if (data instanceof MapEntryNode) {
data = ImmutableNodes.mapNodeBuilder(data.getNodeType()).withChild(((MapEntryNode) data)).build();
}
nnWriter = createNormalizedNodeWriter(context,path,jsonWriter, depth);
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
/**
+ * Normalized node writer for XML.
+ *
* @deprecated This class will be replaced by
* {@link org.opendaylight.restconf.jersey.providers.NormalizedNodeXmlBodyWriter}
*/
}
@Override
- public long getSize(final NormalizedNodeContext t, final Class<?> type, final Type genericType,
+ public long getSize(final NormalizedNodeContext context, final Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType) {
return -1;
}
@Override
- public void writeTo(final NormalizedNodeContext t, final Class<?> type, final Type genericType,
+ public void writeTo(final NormalizedNodeContext context, final Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType,
final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException,
WebApplicationException {
- for (final Entry<String, Object> entry : t.getNewHeaders().entrySet()) {
+ for (final Entry<String, Object> entry : context.getNewHeaders().entrySet()) {
httpHeaders.add(entry.getKey(), entry.getValue());
}
- final InstanceIdentifierContext<?> pathContext = t.getInstanceIdentifierContext();
- if (t.getData() == null) {
+ final InstanceIdentifierContext<?> pathContext = context.getInstanceIdentifierContext();
+ if (context.getData() == null) {
return;
}
XMLStreamWriter xmlWriter;
try {
xmlWriter = XML_FACTORY.createXMLStreamWriter(entityStream, StandardCharsets.UTF_8.name());
- if (t.getWriterParameters().isPrettyPrint()) {
+ if (context.getWriterParameters().isPrettyPrint()) {
xmlWriter = new IndentingXMLStreamWriter(xmlWriter);
}
} catch (final XMLStreamException e) {
} catch (final FactoryConfigurationError e) {
throw new IllegalStateException(e);
}
- final NormalizedNode<?, ?> data = t.getData();
+ final NormalizedNode<?, ?> data = context.getData();
final SchemaPath schemaPath = pathContext.getSchemaNode().getPath();
- writeNormalizedNode(xmlWriter, schemaPath, pathContext, data, Optional.fromNullable(t.getWriterParameters().getDepth()));
+ writeNormalizedNode(xmlWriter, schemaPath, pathContext, data,
+ Optional.fromNullable(context.getWriterParameters().getDepth()));
}
private static void writeNormalizedNode(final XMLStreamWriter xmlWriter, final SchemaPath schemaPath,
xmlWriter.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, name.getLocalName(),
name.getNamespace().toString());
xmlWriter.writeDefaultNamespace(name.getNamespace().toString());
- for(final NormalizedNode<?,?> child : data.getValue()) {
+ for (final NormalizedNode<?,?> child : data.getValue()) {
nnWriter.write(child);
}
nnWriter.flush();
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("PATCH")
@Documented
-public @interface PATCH {
+public @interface Patch {
}
\ No newline at end of file
import javax.ws.rs.ext.Provider;
import org.opendaylight.netconf.sal.rest.api.Draft02;
import org.opendaylight.netconf.sal.rest.api.RestconfService;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusEntity;
+import org.opendaylight.netconf.sal.restconf.impl.PatchStatusContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchStatusEntity;
import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
import org.opendaylight.restconf.Rfc8040;
import org.opendaylight.restconf.utils.RestconfConstants;
@Provider
@Produces({Draft02.MediaTypes.PATCH_STATUS + RestconfService.JSON,
Rfc8040.MediaTypes.PATCH_STATUS + RestconfConstants.JSON})
-public class PATCHJsonBodyWriter implements MessageBodyWriter<PATCHStatusContext> {
+public class PatchJsonBodyWriter implements MessageBodyWriter<PatchStatusContext> {
@Override
public boolean isWriteable(final Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType) {
- return type.equals(PATCHStatusContext.class);
+ return type.equals(PatchStatusContext.class);
}
@Override
- public long getSize(final PATCHStatusContext patchStatusContext, final Class<?> type, final Type genericType,
+ public long getSize(final PatchStatusContext patchStatusContext, final Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType) {
return -1;
}
@Override
- public void writeTo(final PATCHStatusContext patchStatusContext, final Class<?> type, final Type genericType,
+ public void writeTo(final PatchStatusContext patchStatusContext, final Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType,
final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream)
throws IOException, WebApplicationException {
jsonWriter.beginObject();
jsonWriter.name("edit");
jsonWriter.beginArray();
- for (final PATCHStatusEntity patchStatusEntity : patchStatusContext.getEditCollection()) {
+ for (final PatchStatusEntity patchStatusEntity : patchStatusContext.getEditCollection()) {
jsonWriter.beginObject();
jsonWriter.name("edit-id").value(patchStatusEntity.getEditId());
if (patchStatusEntity.getEditErrors() != null) {
import javax.xml.stream.XMLStreamWriter;
import org.opendaylight.netconf.sal.rest.api.Draft02;
import org.opendaylight.netconf.sal.rest.api.RestconfService;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusEntity;
+import org.opendaylight.netconf.sal.restconf.impl.PatchStatusContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchStatusEntity;
import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
import org.opendaylight.restconf.Rfc8040;
import org.opendaylight.restconf.utils.RestconfConstants;
@Provider
@Produces({Draft02.MediaTypes.PATCH_STATUS + RestconfService.XML,
Rfc8040.MediaTypes.PATCH_STATUS + RestconfConstants.XML})
-public class PATCHXmlBodyWriter implements MessageBodyWriter<PATCHStatusContext> {
+public class PatchXmlBodyWriter implements MessageBodyWriter<PatchStatusContext> {
private static final XMLOutputFactory XML_FACTORY;
@Override
public boolean isWriteable(final Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType) {
- return type.equals(PATCHStatusContext.class);
+ return type.equals(PatchStatusContext.class);
}
@Override
- public long getSize(final PATCHStatusContext patchStatusContext, Class<?> type, final Type genericType,
+ public long getSize(final PatchStatusContext patchStatusContext, Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType) {
return -1;
}
@Override
- public void writeTo(final PATCHStatusContext patchStatusContext, final Class<?> type, final Type genericType,
+ public void writeTo(final PatchStatusContext patchStatusContext, final Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType,
final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream)
throws IOException, WebApplicationException {
try {
- final XMLStreamWriter xmlWriter = XML_FACTORY.createXMLStreamWriter(entityStream, StandardCharsets.UTF_8.name());
+ final XMLStreamWriter xmlWriter =
+ XML_FACTORY.createXMLStreamWriter(entityStream, StandardCharsets.UTF_8.name());
writeDocument(xmlWriter, patchStatusContext);
} catch (final XMLStreamException e) {
throw new IllegalStateException(e);
}
}
- private static void writeDocument(final XMLStreamWriter writer, final PATCHStatusContext context)
+ private static void writeDocument(final XMLStreamWriter writer, final PatchStatusContext context)
throws XMLStreamException, IOException {
writer.writeStartElement("", "yang-patch-status", "urn:ietf:params:xml:ns:yang:ietf-yang-patch");
writer.writeStartElement("patch-id");
reportErrors(context.getGlobalErrors(), writer);
}
writer.writeStartElement("edit-status");
- for (final PATCHStatusEntity patchStatusEntity : context.getEditCollection()) {
+ for (final PatchStatusEntity patchStatusEntity : context.getEditCollection()) {
writer.writeStartElement("edit");
writer.writeStartElement("edit-id");
writer.writeCharacters(patchStatusEntity.getEditId());
public static final String DQUOTE = "\"";
private static final Pattern PREDICATE_PATTERN = Pattern.compile("\\[(.*?)\\]");
- public final static TypeDefinition<?> resolveBaseTypeFrom(final TypeDefinition<?> type) {
+ public static TypeDefinition<?> resolveBaseTypeFrom(final TypeDefinition<?> type) {
TypeDefinition<?> superType = type;
while (superType.getBaseType() != null) {
superType = superType.getBaseType();
return predicateStartIndex == -1 ? pathPart : pathPart.substring(0, predicateStartIndex);
}
- private static IdentityValue toIdentity(final String xPathPart, final PrefixesMaping prefixMap) {
- final String xPathPartTrimmed = xPathPart.trim();
+ private static IdentityValue toIdentity(final String xpathPart, final PrefixesMaping prefixMap) {
+ final String xPathPartTrimmed = xpathPart.trim();
if (xPathPartTrimmed.isEmpty()) {
return null;
}
}
result.add(new Predicate(null, predicateValue));
} else {
- final IdentityValue identityValue = toIdentity(predicate.substring(0, indexOfEqualityMark), prefixMap);
+ final IdentityValue identityValue =
+ toIdentity(predicate.substring(0, indexOfEqualityMark), prefixMap);
if (identityValue == null || predicateValue == null) {
return null;
}
}
public interface PrefixesMaping {
- public String getNamespace(String prefix);
+ String getNamespace(String prefix);
}
public static class PrefixMapingFromXml implements PrefixesMaping {
@Override
public Set<Class<?>> getClasses() {
- return ImmutableSet.<Class<?>> builder()
+ return ImmutableSet.<Class<?>>builder()
.add(RestconfDocumentedExceptionMapper.class)
.add(XmlNormalizedNodeBodyReader.class)
.add(JsonNormalizedNodeBodyReader.class)
- .add(JsonToPATCHBodyReader.class)
- .add(XmlToPATCHBodyReader.class)
- .add(PATCHJsonBodyWriter.class)
- .add(PATCHXmlBodyWriter.class)
+ .add(JsonToPatchBodyReader.class)
+ .add(XmlToPatchBodyReader.class)
+ .add(PatchJsonBodyWriter.class)
+ .add(PatchXmlBodyWriter.class)
.add(NormalizedNodeJsonBodyWriter.class)
.add(NormalizedNodeXmlBodyWriter.class)
.add(SchemaExportContentYinBodyWriter.class)
import org.opendaylight.netconf.md.sal.rest.schema.SchemaRetrievalService;
import org.opendaylight.netconf.sal.rest.api.RestconfService;
import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchStatusContext;
public class RestconfCompositeWrapper implements RestconfService, SchemaRetrievalService {
}
@Override
- public PATCHStatusContext patchConfigurationData(final String identifier, final PATCHContext payload,
- final UriInfo uriInfo) {
+ public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext payload,
+ final UriInfo uriInfo) {
return this.restconf.patchConfigurationData(identifier, payload, uriInfo);
}
@Override
- public PATCHStatusContext patchConfigurationData(final PATCHContext context, final UriInfo uriInfo) {
+ public PatchStatusContext patchConfigurationData(final PatchContext context, final UriInfo uriInfo) {
return this.restconf.patchConfigurationData(context, uriInfo);
}
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
/**
- * This class just delegates all of the functionality to Yangtools normalized node writer
+ * This class just delegates all of the functionality to Yangtools normalized node writer.
*/
public class RestconfDelegatingNormalizedNodeWriter implements RestconfNormalizedNodeWriter {
private NormalizedNodeWriter delegNNWriter;
return forStreamWriter(writer, true);
}
- public static RestconfDelegatingNormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer, final boolean
- orderKeyLeaves) {
+ public static RestconfDelegatingNormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
+ final boolean orderKeyLeaves) {
return new RestconfDelegatingNormalizedNodeWriter(writer, orderKeyLeaves);
}
@Provider
public class RestconfDocumentedExceptionMapper implements ExceptionMapper<RestconfDocumentedException> {
- private final static Logger LOG = LoggerFactory.getLogger(RestconfDocumentedExceptionMapper.class);
+ private static final Logger LOG = LoggerFactory.getLogger(RestconfDocumentedExceptionMapper.class);
private static final XMLOutputFactory XML_FACTORY;
final List<DataSchemaNode> schemaList = ControllerContext.findInstanceDataChildrenByName(errorsSchemaNode,
Draft02.RestConfModule.ERROR_LIST_SCHEMA_NODE);
final DataSchemaNode errListSchemaNode = Iterables.getFirst(schemaList, null);
- Preconditions.checkState(errListSchemaNode instanceof ListSchemaNode, "Found Error SchemaNode isn't ListSchemaNode");
+ Preconditions.checkState(
+ errListSchemaNode instanceof ListSchemaNode, "Found Error SchemaNode isn't ListSchemaNode");
final CollectionNodeBuilder<MapEntryNode, MapNode> listErorsBuilder = Builders
.mapBuilder((ListSchemaNode) errListSchemaNode);
errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errMsgSchemaNode)
.withValue(error.getErrorMessage()).build());
- if(error.getErrorInfo() != null) {
+ if (error.getErrorInfo() != null) {
// Oddly, error-info is defined as an empty container in the restconf yang. Apparently the
// intention is for implementors to define their own data content so we'll just treat it as a leaf
// with string data.
return errNodeValues.build();
}
- private static Object toJsonResponseBody(final NormalizedNodeContext errorsNode, final DataNodeContainer errorsSchemaNode) {
+ private static Object toJsonResponseBody(final NormalizedNodeContext errorsNode,
+ final DataNodeContainer errorsSchemaNode) {
final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
NormalizedNode<?, ?> data = errorsNode.getData();
final InstanceIdentifierContext<?> context = errorsNode.getInstanceIdentifierContext();
@Override
public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
- if(name.getNodeType().equals(Draft02.RestConfModule.ERROR_INFO_QNAME)) {
+ if (name.getNodeType().equals(Draft02.RestConfModule.ERROR_INFO_QNAME)) {
jsonWriter.name(Draft02.RestConfModule.ERROR_INFO_QNAME.getLocalName());
jsonWriter.value(value.toString());
} else {
}
- private static Object toXMLResponseBody(final NormalizedNodeContext errorsNode, final DataNodeContainer errorsSchemaNode) {
+ private static Object toXMLResponseBody(final NormalizedNodeContext errorsNode,
+ final DataNodeContainer errorsSchemaNode) {
final InstanceIdentifierContext<?> pathContext = errorsNode.getInstanceIdentifierContext();
final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
@Override
public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
- if(name.getNodeType().equals(Draft02.RestConfModule.ERROR_INFO_QNAME)) {
+ if (name.getNodeType().equals(Draft02.RestConfModule.ERROR_INFO_QNAME)) {
String ns = Draft02.RestConfModule.ERROR_INFO_QNAME.getNamespace().toString();
try {
xmlWriter.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX,
nnWriter.write(data);
nnWriter.flush();
}
- }
- catch (final IOException e) {
+ } catch (final IOException e) {
LOG.warn("Error writing error response body.", e);
}
return outStream.toString();
}
- private static void writeRootElement(final XMLStreamWriter xmlWriter, final NormalizedNodeWriter nnWriter, final ContainerNode data)
+ private static void writeRootElement(final XMLStreamWriter xmlWriter, final NormalizedNodeWriter nnWriter,
+ final ContainerNode data)
throws IOException {
try {
final QName name = SchemaContext.NAME;
}
}
- private static void writeDataRoot(final OutputStreamWriter outputWriter, final NormalizedNodeWriter nnWriter, final ContainerNode data) throws IOException {
+ private static void writeDataRoot(final OutputStreamWriter outputWriter, final NormalizedNodeWriter nnWriter,
+ final ContainerNode data) throws IOException {
final Iterator<DataContainerChild<? extends PathArgument, ?>> iterator = data.getValue().iterator();
while (iterator.hasNext()) {
final DataContainerChild<? extends PathArgument, ?> child = iterator.next();
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
/**
+ * Codec for module instance identifiers.
+ *
* @deprecated This class will be replaced by
* {@link org.opendaylight.restconf.jersey.providers.StringModuleInstanceIdentifierCodec}
*/
@Provider
@Consumes({ Draft02.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.OPERATION + RestconfService.XML,
MediaType.APPLICATION_XML, MediaType.TEXT_XML })
-public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsProvider implements MessageBodyReader<NormalizedNodeContext> {
+public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsProvider
+ implements MessageBodyReader<NormalizedNodeContext> {
- private final static Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
+ private static final Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
@Override
public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
return true;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType,
} else {
return readFrom(entityStream);
}
- } catch (final RestconfDocumentedException e){
+ } catch (final RestconfDocumentedException e) {
throw e;
} catch (final Exception e) {
LOG.debug("Error parsing xml input", e);
final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
InstanceIdentifierContext<? extends SchemaNode> outIIContext;
-
// FIXME the factory instance should be cached if the schema context is the same
- final DomToNormalizedNodeParserFactory parserFactory =
- DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, pathContext.getSchemaContext());
+ final DomToNormalizedNodeParserFactory parserFactory = DomToNormalizedNodeParserFactory
+ .getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, pathContext.getSchemaContext());
if (isPost() && !isRpc) {
final Deque<Object> foundSchemaNodes = findPathToSchemaNodeByName(schemaNode, docRootElm, docRootNamespace);
NormalizedNode<?, ?> parsed = null;
if (schemaNode instanceof ContainerSchemaNode) {
- parsed = parserFactory.getContainerNodeParser().parse(Collections.singletonList(doc.getDocumentElement()), (ContainerSchemaNode) schemaNode);
- } else if(schemaNode instanceof ListSchemaNode) {
+ parsed = parserFactory.getContainerNodeParser().parse(Collections.singletonList(doc.getDocumentElement()),
+ (ContainerSchemaNode) schemaNode);
+ } else if (schemaNode instanceof ListSchemaNode) {
final ListSchemaNode casted = (ListSchemaNode) schemaNode;
parsed = parserFactory.getMapEntryNodeParser().parse(elements, casted);
if (isPost()) {
final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
pathContext.getInstanceIdentifier().getPathArguments(), iiToDataList));
- outIIContext = new InstanceIdentifierContext<>(fullIIToData, pathContext.getSchemaNode(), pathContext.getMountPoint(),
+ outIIContext = new InstanceIdentifierContext<>(fullIIToData, pathContext.getSchemaNode(),
+ pathContext.getMountPoint(),
pathContext.getSchemaContext());
return new NormalizedNodeContext(outIIContext, parsed);
return result;
}
- private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent, final DataSchemaNode child) {
+ private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent,
+ final DataSchemaNode child) {
if ((parent instanceof AugmentationTarget) && !(parent instanceof ChoiceSchemaNode)) {
for (final AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
import org.opendaylight.netconf.sal.rest.api.Draft02;
import org.opendaylight.netconf.sal.rest.api.RestconfService;
import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHEditOperation;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHEntity;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchEditOperation;
+import org.opendaylight.netconf.sal.restconf.impl.PatchEntity;
import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
import org.w3c.dom.NodeList;
/**
+ * Yang PATCH Reader for XML.
+ *
* @deprecated This class will be replaced by
- * {@link org.opendaylight.restconf.jersey.providers.XmlToPATCHBodyReader}
+ * {@link org.opendaylight.restconf.jersey.providers.XmlToPatchBodyReader}
*/
@Deprecated
@Provider
@Consumes({Draft02.MediaTypes.PATCH + RestconfService.XML})
-public class XmlToPATCHBodyReader extends AbstractIdentifierAwareJaxRsProvider implements
- MessageBodyReader<PATCHContext> {
+public class XmlToPatchBodyReader extends AbstractIdentifierAwareJaxRsProvider implements
+ MessageBodyReader<PatchContext> {
- private final static Logger LOG = LoggerFactory.getLogger(XmlToPATCHBodyReader.class);
+ private static final Logger LOG = LoggerFactory.getLogger(XmlToPatchBodyReader.class);
@Override
public boolean isReadable(final Class<?> type, final Type genericType,
return true;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
- public PATCHContext readFrom(final Class<PATCHContext> type, final Type genericType,
+ public PatchContext readFrom(final Class<PatchContext> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType,
final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
throws IOException, WebApplicationException {
if (entityStream.available() < 1) {
// represent empty nopayload input
- return new PATCHContext(path, null, null);
+ return new PatchContext(path, null, null);
}
final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
}
}
- private static PATCHContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc) {
- final List<PATCHEntity> resultCollection = new ArrayList<>();
+ private static PatchContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc) {
+ final List<PatchEntity> resultCollection = new ArrayList<>();
final String patchId = doc.getElementsByTagName("patch-id").item(0).getFirstChild().getNodeValue();
final NodeList editNodes = doc.getElementsByTagName("edit");
final DomToNormalizedNodeParserFactory parserFactory =
final Element firstValueElement = values != null ? values.get(0) : null;
// get namespace according to schema node from path context or value
- final String namespace = (firstValueElement == null) ?
- schemaNode.getQName().getNamespace().toString() : firstValueElement.getNamespaceURI();
+ final String namespace = (firstValueElement == null)
+ ? schemaNode.getQName().getNamespace().toString() : firstValueElement.getNamespaceURI();
// find module according to namespace
final Module module = pathContext.getSchemaContext().findModuleByNamespace(
throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL,
ErrorTag.MALFORMED_MESSAGE);
} else {
- if (PATCHEditOperation.isPatchOperationWithValue(operation)) {
+ if (PatchEditOperation.isPatchOperationWithValue(operation)) {
NormalizedNode<?, ?> parsed = null;
if (schemaNode instanceof ContainerSchemaNode) {
parsed = parserFactory.getContainerNodeParser().parse(values, (ContainerSchemaNode) schemaNode);
targetII = targetII.getParent();
}
- resultCollection.add(new PATCHEntity(editId, operation, targetII, parsed));
+ resultCollection.add(new PatchEntity(editId, operation, targetII, parsed));
} else {
- resultCollection.add(new PATCHEntity(editId, operation, targetII));
+ resultCollection.add(new PatchEntity(editId, operation, targetII));
}
}
}
- return new PATCHContext(pathContext, ImmutableList.copyOf(resultCollection), patchId);
+ return new PatchContext(pathContext, ImmutableList.copyOf(resultCollection), patchId);
}
/**
- * Read value nodes
+ * Read value nodes.
+ *
* @param element Element of current edit operation
* @param operation Name of current operation
* @return List of value elements
private static List<Element> readValueNodes(@Nonnull final Element element, @Nonnull final String operation) {
final Node valueNode = element.getElementsByTagName("value").item(0);
- if (PATCHEditOperation.isPatchOperationWithValue(operation) && (valueNode == null)) {
+ if (PatchEditOperation.isPatchOperationWithValue(operation) && (valueNode == null)) {
throw new RestconfDocumentedException("Error parsing input",
ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
}
- if (!PATCHEditOperation.isPatchOperationWithValue(operation) && (valueNode != null)) {
+ if (!PatchEditOperation.isPatchOperationWithValue(operation) && (valueNode != null)) {
throw new RestconfDocumentedException("Error parsing input",
ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
}
}
/**
- * Prepare non-conditional XPath suitable for deserialization
- * with {@link StringModuleInstanceIdentifierCodec}
+ * Prepare non-conditional XPath suitable for deserialization with {@link StringModuleInstanceIdentifierCodec}.
+ *
* @param schemaNode Top schema node
* @param target Edit operation target
* @param value Element with value
}
/**
- * Read value for every list key
+ * Read value for every list key.
+ *
* @param value Value element
* @param keys Iterator of list keys names
* @return Iterator of list keys values
}
/**
- * Append key name - key value pairs for every list key to {@code nonCondXpath}
+ * Append key name - key value pairs for every list key to {@code nonCondXpath}.
+ *
* @param nonCondXpath Builder for creating non-conditional XPath
* @param keyNames Iterator of list keys names
* @param keyValues Iterator of list keys values
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.yangtools.yang.common.OperationFailedException;
+@Deprecated
/**
* @author Thomas Pantelis
*/
-@Deprecated
public interface JSONRestconfService {
/**
* The data tree root path.
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
final class BatchedExistenceCheck {
- private static final AtomicIntegerFieldUpdater<BatchedExistenceCheck> UPDATER = AtomicIntegerFieldUpdater.newUpdater(
- BatchedExistenceCheck.class, "outstanding");
+ private static final AtomicIntegerFieldUpdater<BatchedExistenceCheck> UPDATER =
+ AtomicIntegerFieldUpdater.newUpdater(BatchedExistenceCheck.class, "outstanding");
private final SettableFuture<Entry<YangInstanceIdentifier, ReadFailedException>> future = SettableFuture.create();
}
@Override
- public void onFailure(final Throwable t) {
+ public void onFailure(final Throwable throwable) {
final Exception e;
- if (t instanceof Exception) {
- e = (Exception) t;
+ if (throwable instanceof Exception) {
+ e = (Exception) throwable;
} else {
- e = new ExecutionException(t);
+ e = new ExecutionException(throwable);
}
ret.complete(path, ReadFailedException.MAPPER.apply(e));
import org.slf4j.LoggerFactory;
public class BrokerFacade {
- private final static Logger LOG = LoggerFactory.getLogger(BrokerFacade.class);
+ private static final Logger LOG = LoggerFactory.getLogger(BrokerFacade.class);
+ private static final BrokerFacade INSTANCE = new BrokerFacade();
- private final static BrokerFacade INSTANCE = new BrokerFacade();
private volatile DOMRpcService rpcService;
private volatile ConsumerSession context;
+
private DOMDataBroker domDataBroker;
private DOMNotificationService domNotification;
}
/**
- * Read config data by path
+ * Read config data by path.
*
* @param path
- * - path of data
+ * path of data
* @return read date
*/
public NormalizedNode<?, ?> readConfigurationData(final YangInstanceIdentifier path) {
}
/**
- * Read config data by path
+ * Read config data by path.
*
* @param path
- * - path of data
+ * path of data
* @param withDefa
- * - value of with-defaults parameter
+ * value of with-defaults parameter
* @return read date
*/
public NormalizedNode<?, ?> readConfigurationData(final YangInstanceIdentifier path, final String withDefa) {
* Read config data from mount point by path.
*
* @param mountPoint
- * - mount point for reading data
+ * mount point for reading data
* @param path
- * - path of data
+ * path of data
* @return read data
*/
public NormalizedNode<?, ?> readConfigurationData(final DOMMountPoint mountPoint,
* Read config data from mount point by path.
*
* @param mountPoint
- * - mount point for reading data
+ * mount point for reading data
* @param path
- * - path of data
+ * path of data
* @param withDefa
- * - value of with-defaults parameter
+ * value of with-defaults parameter
* @return read data
*/
public NormalizedNode<?, ?> readConfigurationData(final DOMMountPoint mountPoint, final YangInstanceIdentifier path,
* Read operational data by path.
*
* @param path
- * - path of data
+ * path of data
* @return read data
*/
public NormalizedNode<?, ?> readOperationalData(final YangInstanceIdentifier path) {
* Read operational data from mount point by path.
*
* @param mountPoint
- * - mount point for reading data
+ * mount point for reading data
* @param path
- * - path of data
+ * path of data
* @return read data
*/
public NormalizedNode<?, ?> readOperationalData(final DOMMountPoint mountPoint, final YangInstanceIdentifier path) {
/**
* <b>PUT configuration data</b>
*
+ * <p>
* Prepare result(status) for PUT operation and PUT data via transaction.
* Return wrapped status and future from PUT.
*
* @param globalSchema
- * - used by merge parents (if contains list)
+ * used by merge parents (if contains list)
* @param path
- * - path of node
+ * path of node
* @param payload
- * - input data
+ * input data
* @param point
+ * point
* @param insert
+ * insert
* @return wrapper of status and future of PUT
*/
public PutResult commitConfigurationDataPut(
/**
* <b>PUT configuration data (Mount point)</b>
*
+ * <p>
* Prepare result(status) for PUT operation and PUT data via transaction.
* Return wrapped status and future from PUT.
*
* @param mountPoint
- * - mount point for getting transaction for operation and schema
+ * mount point for getting transaction for operation and schema
* context for merging parents(if contains list)
* @param path
- * - path of node
+ * path of node
* @param payload
- * - input data
+ * input data
* @param point
+ * point
* @param insert
+ * insert
* @return wrapper of status and future of PUT
*/
public PutResult commitMountPointDataPut(
final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
if (domDataBrokerService.isPresent()) {
- final DOMDataReadWriteTransaction newReadWriteTransaction = domDataBrokerService.get().newReadWriteTransaction();
+ final DOMDataReadWriteTransaction newReadWriteTransaction =
+ domDataBrokerService.get().newReadWriteTransaction();
final Status status = readDataViaTransaction(newReadWriteTransaction, CONFIGURATION, path) != null
? Status.OK : Status.CREATED;
final CheckedFuture<Void, TransactionCommitFailedException> future = putDataViaTransaction(
throw new RestconfDocumentedException(errMsg);
}
- public PATCHStatusContext patchConfigurationDataWithinTransaction(final PATCHContext patchContext) throws Exception {
+ public PatchStatusContext patchConfigurationDataWithinTransaction(final PatchContext patchContext)
+ throws Exception {
final DOMMountPoint mountPoint = patchContext.getInstanceIdentifierContext().getMountPoint();
// get new transaction and schema context on server or on mounted device
patchTransaction = optional.get().newReadWriteTransaction();
} else {
// if mount point does not have broker it is not possible to continue and global error is reported
- LOG.error("Http PATCH {} has failed - device {} does not support broker service",
+ LOG.error("Http Patch {} has failed - device {} does not support broker service",
patchContext.getPatchId(), mountPoint.getIdentifier());
- return new PATCHStatusContext(
+ return new PatchStatusContext(
patchContext.getPatchId(),
null,
false,
}
}
- final List<PATCHStatusEntity> editCollection = new ArrayList<>();
+ final List<PatchStatusEntity> editCollection = new ArrayList<>();
List<RestconfError> editErrors;
boolean withoutError = true;
- for (final PATCHEntity patchEntity : patchContext.getData()) {
- final PATCHEditOperation operation = PATCHEditOperation.valueOf(patchEntity.getOperation().toUpperCase());
+ for (final PatchEntity patchEntity : patchContext.getData()) {
+ final PatchEditOperation operation = PatchEditOperation.valueOf(patchEntity.getOperation().toUpperCase());
switch (operation) {
case CREATE:
try {
postDataWithinTransaction(patchTransaction, CONFIGURATION, patchEntity.getTargetNode(),
patchEntity.getNode(), schemaContext);
- editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), true, null));
+ editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
} catch (final RestconfDocumentedException e) {
- LOG.error("Error call http PATCH operation {} on target {}",
+ LOG.error("Error call http Patch operation {} on target {}",
operation,
patchEntity.getTargetNode().toString());
editErrors = new ArrayList<>();
editErrors.addAll(e.getErrors());
- editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), false, editErrors));
+ editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), false, editErrors));
withoutError = false;
}
}
try {
putDataWithinTransaction(patchTransaction, CONFIGURATION, patchEntity
.getTargetNode(), patchEntity.getNode(), schemaContext);
- editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), true, null));
+ editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
} catch (final RestconfDocumentedException e) {
- LOG.error("Error call http PATCH operation {} on target {}",
+ LOG.error("Error call http Patch operation {} on target {}",
operation,
patchEntity.getTargetNode().toString());
editErrors = new ArrayList<>();
editErrors.addAll(e.getErrors());
- editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), false, editErrors));
+ editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), false, editErrors));
withoutError = false;
}
}
try {
deleteDataWithinTransaction(patchTransaction, CONFIGURATION, patchEntity
.getTargetNode());
- editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), true, null));
+ editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
} catch (final RestconfDocumentedException e) {
- LOG.error("Error call http PATCH operation {} on target {}",
+ LOG.error("Error call http Patch operation {} on target {}",
operation,
patchEntity.getTargetNode().toString());
editErrors = new ArrayList<>();
editErrors.addAll(e.getErrors());
- editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), false, editErrors));
+ editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), false, editErrors));
withoutError = false;
}
}
try {
deleteDataWithinTransaction(patchTransaction, CONFIGURATION, patchEntity
.getTargetNode());
- editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), true, null));
+ editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
} catch (final RestconfDocumentedException e) {
- LOG.error("Error call http PATCH operation {} on target {}",
+ LOG.error("Error call http Patch operation {} on target {}",
operation,
patchEntity.getTargetNode().toString());
editErrors = new ArrayList<>();
editErrors.addAll(e.getErrors());
- editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), false, editErrors));
+ editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), false, editErrors));
withoutError = false;
}
}
try {
mergeDataWithinTransaction(patchTransaction, CONFIGURATION, patchEntity.getTargetNode(),
patchEntity.getNode(), schemaContext);
- editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), true, null));
+ editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
} catch (final RestconfDocumentedException e) {
- LOG.error("Error call http PATCH operation {} on target {}",
+ LOG.error("Error call http Patch operation {} on target {}",
operation,
patchEntity.getTargetNode().toString());
editErrors = new ArrayList<>();
editErrors.addAll(e.getErrors());
- editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), false, editErrors));
+ editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), false, editErrors));
withoutError = false;
}
}
break;
default:
- LOG.error("Unsupported http PATCH operation {} on target {}",
+ LOG.error("Unsupported http Patch operation {} on target {}",
operation,
patchEntity.getTargetNode().toString());
break;
// if errors then cancel transaction and return error status
if (!withoutError) {
patchTransaction.cancel();
- return new PATCHStatusContext(patchContext.getPatchId(), ImmutableList.copyOf(editCollection), false, null);
+ return new PatchStatusContext(patchContext.getPatchId(), ImmutableList.copyOf(editCollection), false, null);
}
// if no errors commit transaction
final CountDownLatch waiter = new CountDownLatch(1);
final CheckedFuture<Void, TransactionCommitFailedException> future = patchTransaction.submit();
- final PATCHStatusContextHelper status = new PATCHStatusContextHelper();
+ final PatchStatusContextHelper status = new PatchStatusContextHelper();
Futures.addCallback(future, new FutureCallback<Void>() {
@Override
public void onSuccess(@Nullable final Void result) {
- status.setStatus(new PATCHStatusContext(patchContext.getPatchId(), ImmutableList.copyOf(editCollection),
+ status.setStatus(new PatchStatusContext(patchContext.getPatchId(), ImmutableList.copyOf(editCollection),
true, null));
waiter.countDown();
}
@Override
- public void onFailure(final Throwable t) {
+ public void onFailure(final Throwable throwable) {
// if commit failed it is global error
- LOG.error("Http PATCH {} transaction commit has failed", patchContext.getPatchId());
- status.setStatus(new PATCHStatusContext(patchContext.getPatchId(), ImmutableList.copyOf(editCollection),
+ LOG.error("Http Patch {} transaction commit has failed", patchContext.getPatchId());
+ status.setStatus(new PatchStatusContext(patchContext.getPatchId(), ImmutableList.copyOf(editCollection),
false, ImmutableList.of(
- new RestconfError(ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, t.getMessage()))));
+ new RestconfError(ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, throwable.getMessage()))));
waiter.countDown();
}
});
}
// RPC
- public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(final SchemaPath type, final NormalizedNode<?, ?> input) {
+ public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(final SchemaPath type,
+ final NormalizedNode<?, ?> input) {
checkPreconditions();
if (this.rpcService == null) {
throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
return builder.build();
}
- private void buildMapEntryBuilder(final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
+ private void buildMapEntryBuilder(
+ final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
final MapEntryNode result, final DataSchemaContextTree baseSchemaCtxTree,
final YangInstanceIdentifier actualPath, final boolean trim, final List<QName> keys) {
for (final DataContainerChild<? extends PathArgument, ?> child : result.getValue()) {
for (final DataContainerChild<? extends PathArgument, ?> child : result.getValue()) {
final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
final DataSchemaNode childSchema = baseSchemaCtxTree.getChild(path).getDataSchemaNode();
- if(child instanceof ContainerNode){
+ if (child instanceof ContainerNode) {
final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> builderChild =
Builders.containerBuilder((ContainerSchemaNode) childSchema);
buildCont(builderChild, result, baseSchemaCtxTree, actualPath, trim);
}
/**
- * POST data and submit transaction {@link DOMDataReadWriteTransaction}
+ * POST data and submit transaction {@link DOMDataReadWriteTransaction}.
*/
private CheckedFuture<Void, TransactionCommitFailedException> postDataViaTransaction(
- final DOMDataReadWriteTransaction rWTransaction, final LogicalDatastoreType datastore,
+ final DOMDataReadWriteTransaction rwTransaction, final LogicalDatastoreType datastore,
final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload, final SchemaContext schemaContext,
final String insert, final String point) {
LOG.trace("POST {} via Restconf: {} with payload {}", datastore.name(), path, payload);
- postData(rWTransaction, datastore, path, payload, schemaContext, insert, point);
- return rWTransaction.submit();
+ postData(rwTransaction, datastore, path, payload, schemaContext, insert, point);
+ return rwTransaction.submit();
}
/**
- * POST data and do NOT submit transaction {@link DOMDataReadWriteTransaction}
+ * POST data and do NOT submit transaction {@link DOMDataReadWriteTransaction}.
*/
private void postDataWithinTransaction(
- final DOMDataReadWriteTransaction rWTransaction, final LogicalDatastoreType datastore,
+ final DOMDataReadWriteTransaction rwTransaction, final LogicalDatastoreType datastore,
final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload, final SchemaContext schemaContext) {
- LOG.trace("POST {} within Restconf PATCH: {} with payload {}", datastore.name(), path, payload);
- postData(rWTransaction, datastore, path, payload, schemaContext, null, null);
+ LOG.trace("POST {} within Restconf Patch: {} with payload {}", datastore.name(), path, payload);
+ postData(rwTransaction, datastore, path, payload, schemaContext, null, null);
}
- private void postData(final DOMDataReadWriteTransaction rWTransaction, final LogicalDatastoreType datastore,
+ private void postData(final DOMDataReadWriteTransaction rwTransaction, final LogicalDatastoreType datastore,
final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload,
final SchemaContext schemaContext, final String insert, final String point) {
if (insert == null) {
- makeNormalPost(rWTransaction, datastore, path, payload, schemaContext);
+ makeNormalPost(rwTransaction, datastore, path, payload, schemaContext);
return;
}
final DataSchemaNode schemaNode = checkListAndOrderedType(schemaContext, path);
- checkItemDoesNotExists(rWTransaction, datastore, path);
+ checkItemDoesNotExists(rwTransaction, datastore, path);
switch (insert) {
case "first":
- if(schemaNode instanceof ListSchemaNode){
+ if (schemaNode instanceof ListSchemaNode) {
final OrderedMapNode readList =
(OrderedMapNode) this.readConfigurationData(path.getParent().getParent());
if (readList == null || readList.getValue().isEmpty()) {
- simplePostPut(rWTransaction, datastore, path, payload, schemaContext);
+ simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
} else {
- rWTransaction.delete(datastore, path.getParent().getParent());
- simplePostPut(rWTransaction, datastore, path, payload, schemaContext);
- makeNormalPost(rWTransaction, datastore, path.getParent().getParent(), readList,
+ rwTransaction.delete(datastore, path.getParent().getParent());
+ simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
+ makeNormalPost(rwTransaction, datastore, path.getParent().getParent(), readList,
schemaContext);
}
} else {
final OrderedLeafSetNode<?> readLeafList =
(OrderedLeafSetNode<?>) readConfigurationData(path.getParent());
if (readLeafList == null || readLeafList.getValue().isEmpty()) {
- simplePostPut(rWTransaction, datastore, path, payload, schemaContext);
+ simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
} else {
- rWTransaction.delete(datastore, path.getParent());
- simplePostPut(rWTransaction, datastore, path, payload, schemaContext);
- makeNormalPost(rWTransaction, datastore, path.getParent().getParent(), readLeafList,
+ rwTransaction.delete(datastore, path.getParent());
+ simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
+ makeNormalPost(rwTransaction, datastore, path.getParent().getParent(), readLeafList,
schemaContext);
}
}
break;
case "last":
- simplePostPut(rWTransaction, datastore, path, payload, schemaContext);
+ simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
break;
case "before":
- if(schemaNode instanceof ListSchemaNode){
+ if (schemaNode instanceof ListSchemaNode) {
final OrderedMapNode readList =
(OrderedMapNode) this.readConfigurationData(path.getParent().getParent());
if (readList == null || readList.getValue().isEmpty()) {
- simplePostPut(rWTransaction, datastore, path, payload, schemaContext);
+ simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
} else {
- insertWithPointListPost(rWTransaction, datastore, path, payload, schemaContext, point,
+ insertWithPointListPost(rwTransaction, datastore, path, payload, schemaContext, point,
readList,
true);
}
final OrderedLeafSetNode<?> readLeafList =
(OrderedLeafSetNode<?>) readConfigurationData(path.getParent());
if (readLeafList == null || readLeafList.getValue().isEmpty()) {
- simplePostPut(rWTransaction, datastore, path, payload, schemaContext);
+ simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
} else {
- insertWithPointLeafListPost(rWTransaction, datastore, path, payload, schemaContext, point,
+ insertWithPointLeafListPost(rwTransaction, datastore, path, payload, schemaContext, point,
readLeafList, true);
}
}
final OrderedMapNode readList =
(OrderedMapNode) this.readConfigurationData(path.getParent().getParent());
if (readList == null || readList.getValue().isEmpty()) {
- simplePostPut(rWTransaction, datastore, path, payload, schemaContext);
+ simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
} else {
- insertWithPointListPost(rWTransaction, datastore, path, payload, schemaContext, point,
+ insertWithPointListPost(rwTransaction, datastore, path, payload, schemaContext, point,
readList,
false);
}
final OrderedLeafSetNode<?> readLeafList =
(OrderedLeafSetNode<?>) readConfigurationData(path.getParent());
if (readLeafList == null || readLeafList.getValue().isEmpty()) {
- simplePostPut(rWTransaction, datastore, path, payload, schemaContext);
+ simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
} else {
- insertWithPointLeafListPost(rWTransaction, datastore, path, payload, schemaContext, point,
+ insertWithPointLeafListPost(rwTransaction, datastore, path, payload, schemaContext, point,
readLeafList, false);
}
}
}
}
- private static void insertWithPointLeafListPost(final DOMDataReadWriteTransaction rWTransaction,
+ private static void insertWithPointLeafListPost(final DOMDataReadWriteTransaction rwTransaction,
final LogicalDatastoreType datastore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload,
final SchemaContext schemaContext, final String point, final OrderedLeafSetNode<?> readLeafList,
final boolean before) {
- rWTransaction.delete(datastore, path.getParent().getParent());
+ rwTransaction.delete(datastore, path.getParent().getParent());
final InstanceIdentifierContext<?> instanceIdentifier =
ControllerContext.getInstance().toInstanceIdentifier(point);
- int p = 0;
+ int lastItemPosition = 0;
for (final LeafSetEntryNode<?> nodeChild : readLeafList.getValue()) {
if (nodeChild.getIdentifier().equals(instanceIdentifier.getInstanceIdentifier().getLastPathArgument())) {
break;
}
- p++;
+ lastItemPosition++;
}
if (!before) {
- p++;
+ lastItemPosition++;
}
- int h = 0;
+ int lastInsertedPosition = 0;
final NormalizedNode<?, ?> emptySubtree =
ImmutableNodes.fromInstanceId(schemaContext, path.getParent().getParent());
- rWTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
+ rwTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
for (final LeafSetEntryNode<?> nodeChild : readLeafList.getValue()) {
- if (h == p) {
- checkItemDoesNotExists(rWTransaction, datastore, path);
- simplePostPut(rWTransaction, datastore, path, payload, schemaContext);
+ if (lastInsertedPosition == lastItemPosition) {
+ checkItemDoesNotExists(rwTransaction, datastore, path);
+ simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
}
final YangInstanceIdentifier childPath = path.getParent().getParent().node(nodeChild.getIdentifier());
- checkItemDoesNotExists(rWTransaction, datastore, childPath);
- rWTransaction.put(datastore, childPath, nodeChild);
- h++;
+ checkItemDoesNotExists(rwTransaction, datastore, childPath);
+ rwTransaction.put(datastore, childPath, nodeChild);
+ lastInsertedPosition++;
}
}
- private static void insertWithPointListPost(final DOMDataReadWriteTransaction rWTransaction,
+ private static void insertWithPointListPost(final DOMDataReadWriteTransaction rwTransaction,
final LogicalDatastoreType datastore,
final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload, final SchemaContext schemaContext,
final String point, final MapNode readList, final boolean before) {
- rWTransaction.delete(datastore, path.getParent().getParent());
+ rwTransaction.delete(datastore, path.getParent().getParent());
final InstanceIdentifierContext<?> instanceIdentifier =
ControllerContext.getInstance().toInstanceIdentifier(point);
- int p = 0;
+ int lastItemPosition = 0;
for (final MapEntryNode mapEntryNode : readList.getValue()) {
if (mapEntryNode.getIdentifier()
.equals(instanceIdentifier.getInstanceIdentifier().getLastPathArgument())) {
break;
}
- p++;
+ lastItemPosition++;
}
if (!before) {
- p++;
+ lastItemPosition++;
}
- int h = 0;
+ int lastInsertedPosition = 0;
final NormalizedNode<?, ?> emptySubtree =
ImmutableNodes.fromInstanceId(schemaContext, path.getParent().getParent());
- rWTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
+ rwTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
for (final MapEntryNode mapEntryNode : readList.getValue()) {
- if (h == p) {
- checkItemDoesNotExists(rWTransaction, datastore, path);
- simplePostPut(rWTransaction, datastore, path, payload, schemaContext);
+ if (lastInsertedPosition == lastItemPosition) {
+ checkItemDoesNotExists(rwTransaction, datastore, path);
+ simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
}
final YangInstanceIdentifier childPath = path.getParent().getParent().node(mapEntryNode.getIdentifier());
- checkItemDoesNotExists(rWTransaction, datastore, childPath);
- rWTransaction.put(datastore, childPath, mapEntryNode);
- h++;
+ checkItemDoesNotExists(rwTransaction, datastore, childPath);
+ rwTransaction.put(datastore, childPath, mapEntryNode);
+ lastInsertedPosition++;
}
}
final DataSchemaNode dataSchemaNode = node.getDataSchemaNode();
if (dataSchemaNode instanceof ListSchemaNode) {
- if(!((ListSchemaNode) dataSchemaNode).isUserOrdered()) {
+ if (!((ListSchemaNode) dataSchemaNode).isUserOrdered()) {
throw new RestconfDocumentedException("Insert parameter can be used only with ordered-by user list.");
}
return dataSchemaNode;
}
if (dataSchemaNode instanceof LeafListSchemaNode) {
- if(!((LeafListSchemaNode) dataSchemaNode).isUserOrdered()) {
- throw new RestconfDocumentedException("Insert parameter can be used only with ordered-by user leaf-list.");
+ if (!((LeafListSchemaNode) dataSchemaNode).isUserOrdered()) {
+ throw new RestconfDocumentedException(
+ "Insert parameter can be used only with ordered-by user leaf-list.");
}
return dataSchemaNode;
}
throw new RestconfDocumentedException("Insert parameter can be used only with list or leaf-list");
}
- private static void makeNormalPost(final DOMDataReadWriteTransaction rWTransaction,
+ private static void makeNormalPost(final DOMDataReadWriteTransaction rwTransaction,
final LogicalDatastoreType datastore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload,
final SchemaContext schemaContext) {
final Collection<? extends NormalizedNode<?, ?>> children;
} else if (payload instanceof LeafSetNode) {
children = ((LeafSetNode<?>) payload).getValue();
} else {
- simplePostPut(rWTransaction, datastore, path, payload, schemaContext);
+ simplePostPut(rwTransaction, datastore, path, payload, schemaContext);
return;
}
final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path);
if (children.isEmpty()) {
- rWTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
- ensureParentsByMerge(datastore, path, rWTransaction, schemaContext);
+ rwTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
+ ensureParentsByMerge(datastore, path, rwTransaction, schemaContext);
return;
}
// Kick off batch existence check first...
- final BatchedExistenceCheck check = BatchedExistenceCheck.start(rWTransaction, datastore, path, children);
+ final BatchedExistenceCheck check = BatchedExistenceCheck.start(rwTransaction, datastore, path, children);
// ... now enqueue modifications. This relies on proper ordering of requests, i.e. these will not affect the
// result of the existence checks...
- rWTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
- ensureParentsByMerge(datastore, path, rWTransaction, schemaContext);
+ rwTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
+ ensureParentsByMerge(datastore, path, rwTransaction, schemaContext);
for (final NormalizedNode<?, ?> child : children) {
// FIXME: we really want a create(YangInstanceIdentifier, NormalizedNode) method in the transaction,
// as that would allow us to skip the existence checks
- rWTransaction.put(datastore, path.node(child.getIdentifier()), child);
+ rwTransaction.put(datastore, path.node(child.getIdentifier()), child);
}
// ... finally collect existence checks and abort the transaction if any of them failed.
try {
failure = check.getFailure();
} catch (InterruptedException e) {
- rWTransaction.cancel();
+ rwTransaction.cancel();
throw new RestconfDocumentedException("Could not determine the existence of path " + path, e);
}
if (failure != null) {
- rWTransaction.cancel();
+ rwTransaction.cancel();
final ReadFailedException e = failure.getValue();
if (e == null) {
throw new RestconfDocumentedException("Data already exists for path: " + failure.getKey(),
}
}
- private static void simplePostPut(final DOMDataReadWriteTransaction rWTransaction,
+ private static void simplePostPut(final DOMDataReadWriteTransaction rwTransaction,
final LogicalDatastoreType datastore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload,
final SchemaContext schemaContext) {
- checkItemDoesNotExists(rWTransaction, datastore, path);
- ensureParentsByMerge(datastore, path, rWTransaction, schemaContext);
- rWTransaction.put(datastore, path, payload);
+ checkItemDoesNotExists(rwTransaction, datastore, path);
+ ensureParentsByMerge(datastore, path, rwTransaction, schemaContext);
+ rwTransaction.put(datastore, path, payload);
}
- private static boolean doesItemExist(final DOMDataReadWriteTransaction rWTransaction,
+ private static boolean doesItemExist(final DOMDataReadWriteTransaction rwTransaction,
final LogicalDatastoreType store, final YangInstanceIdentifier path) {
try {
- return rWTransaction.exists(store, path).checkedGet();
+ return rwTransaction.exists(store, path).checkedGet();
} catch (ReadFailedException e) {
- rWTransaction.cancel();
+ rwTransaction.cancel();
throw new RestconfDocumentedException("Could not determine the existence of path " + path,
e, e.getErrorList());
}
/**
* Check if item already exists. Throws error if it does NOT already exist.
- * @param rWTransaction Current transaction
+ * @param rwTransaction Current transaction
* @param store Used datastore
* @param path Path to item to verify its existence
*/
- private static void checkItemExists(final DOMDataReadWriteTransaction rWTransaction,
+ private static void checkItemExists(final DOMDataReadWriteTransaction rwTransaction,
final LogicalDatastoreType store, final YangInstanceIdentifier path) {
- if (!doesItemExist(rWTransaction, store, path)) {
+ if (!doesItemExist(rwTransaction, store, path)) {
final String errMsg = "Operation via Restconf was not executed because data does not exist";
LOG.trace("{}:{}", errMsg, path);
- rWTransaction.cancel();
+ rwTransaction.cancel();
throw new RestconfDocumentedException("Data does not exist for path: " + path, ErrorType.PROTOCOL,
ErrorTag.DATA_MISSING);
}
/**
* Check if item does NOT already exist. Throws error if it already exists.
- * @param rWTransaction Current transaction
+ * @param rwTransaction Current transaction
* @param store Used datastore
* @param path Path to item to verify its existence
*/
- private static void checkItemDoesNotExists(final DOMDataReadWriteTransaction rWTransaction,
+ private static void checkItemDoesNotExists(final DOMDataReadWriteTransaction rwTransaction,
final LogicalDatastoreType store, final YangInstanceIdentifier path) {
- if (doesItemExist(rWTransaction, store, path)) {
+ if (doesItemExist(rwTransaction, store, path)) {
final String errMsg = "Operation via Restconf was not executed because data already exists";
LOG.trace("{}:{}", errMsg, path);
- rWTransaction.cancel();
+ rwTransaction.cancel();
throw new RestconfDocumentedException("Data already exists for path: " + path, ErrorType.PROTOCOL,
ErrorTag.DATA_EXISTS);
}
}
/**
- * PUT data and submit {@link DOMDataReadWriteTransaction}
+ * PUT data and submit {@link DOMDataReadWriteTransaction}.
*
* @param point
+ * point
* @param insert
+ * insert
*/
private CheckedFuture<Void, TransactionCommitFailedException> putDataViaTransaction(
final DOMDataReadWriteTransaction readWriteTransaction, final LogicalDatastoreType datastore,
}
/**
- * PUT data and do NOT submit {@link DOMDataReadWriteTransaction}
- *
- * @param insert
- * @param point
+ * PUT data and do NOT submit {@link DOMDataReadWriteTransaction}.
*/
private void putDataWithinTransaction(
final DOMDataReadWriteTransaction writeTransaction, final LogicalDatastoreType datastore,
final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload, final SchemaContext schemaContext) {
- LOG.trace("Put {} within Restconf PATCH: {} with payload {}", datastore.name(), path, payload);
+ LOG.trace("Put {} within Restconf Patch: {} with payload {}", datastore.name(), path, payload);
putData(writeTransaction, datastore, path, payload, schemaContext, null, null);
}
// FIXME: This is doing correct put for container and list children, not sure if this will work for choice case
- private void putData(final DOMDataReadWriteTransaction rWTransaction, final LogicalDatastoreType datastore,
+ private void putData(final DOMDataReadWriteTransaction rwTransaction, final LogicalDatastoreType datastore,
final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload, final SchemaContext schemaContext,
final String insert, final String point) {
if (insert == null) {
- makePut(rWTransaction, datastore, path, payload, schemaContext);
+ makePut(rwTransaction, datastore, path, payload, schemaContext);
return;
}
final DataSchemaNode schemaNode = checkListAndOrderedType(schemaContext, path);
- checkItemDoesNotExists(rWTransaction, datastore, path);
+ checkItemDoesNotExists(rwTransaction, datastore, path);
switch (insert) {
case "first":
if (schemaNode instanceof ListSchemaNode) {
final OrderedMapNode readList =
(OrderedMapNode) this.readConfigurationData(path.getParent());
if (readList == null || readList.getValue().isEmpty()) {
- simplePut(datastore, path, rWTransaction, schemaContext, payload);
+ simplePut(datastore, path, rwTransaction, schemaContext, payload);
} else {
- rWTransaction.delete(datastore, path.getParent());
- simplePut(datastore, path, rWTransaction, schemaContext, payload);
- makePut(rWTransaction, datastore, path.getParent(), readList, schemaContext);
+ rwTransaction.delete(datastore, path.getParent());
+ simplePut(datastore, path, rwTransaction, schemaContext, payload);
+ makePut(rwTransaction, datastore, path.getParent(), readList, schemaContext);
}
} else {
final OrderedLeafSetNode<?> readLeafList =
(OrderedLeafSetNode<?>) readConfigurationData(path.getParent());
if (readLeafList == null || readLeafList.getValue().isEmpty()) {
- simplePut(datastore, path, rWTransaction, schemaContext, payload);
+ simplePut(datastore, path, rwTransaction, schemaContext, payload);
} else {
- rWTransaction.delete(datastore, path.getParent());
- simplePut(datastore, path, rWTransaction, schemaContext, payload);
- makePut(rWTransaction, datastore, path.getParent(), readLeafList,
+ rwTransaction.delete(datastore, path.getParent());
+ simplePut(datastore, path, rwTransaction, schemaContext, payload);
+ makePut(rwTransaction, datastore, path.getParent(), readLeafList,
schemaContext);
}
}
break;
case "last":
- simplePut(datastore, path, rWTransaction, schemaContext, payload);
+ simplePut(datastore, path, rwTransaction, schemaContext, payload);
break;
case "before":
if (schemaNode instanceof ListSchemaNode) {
final OrderedMapNode readList =
(OrderedMapNode) this.readConfigurationData(path.getParent());
if (readList == null || readList.getValue().isEmpty()) {
- simplePut(datastore, path, rWTransaction, schemaContext, payload);
+ simplePut(datastore, path, rwTransaction, schemaContext, payload);
} else {
- insertWithPointListPut(rWTransaction, datastore, path, payload, schemaContext, point,
+ insertWithPointListPut(rwTransaction, datastore, path, payload, schemaContext, point,
readList, true);
}
} else {
final OrderedLeafSetNode<?> readLeafList =
(OrderedLeafSetNode<?>) readConfigurationData(path.getParent());
if (readLeafList == null || readLeafList.getValue().isEmpty()) {
- simplePut(datastore, path, rWTransaction, schemaContext, payload);
+ simplePut(datastore, path, rwTransaction, schemaContext, payload);
} else {
- insertWithPointLeafListPut(rWTransaction, datastore, path, payload, schemaContext, point,
+ insertWithPointLeafListPut(rwTransaction, datastore, path, payload, schemaContext, point,
readLeafList, true);
}
}
final OrderedMapNode readList =
(OrderedMapNode) this.readConfigurationData(path.getParent());
if (readList == null || readList.getValue().isEmpty()) {
- simplePut(datastore, path, rWTransaction, schemaContext, payload);
+ simplePut(datastore, path, rwTransaction, schemaContext, payload);
} else {
- insertWithPointListPut(rWTransaction, datastore, path, payload, schemaContext, point,
+ insertWithPointListPut(rwTransaction, datastore, path, payload, schemaContext, point,
readList, false);
}
} else {
final OrderedLeafSetNode<?> readLeafList =
(OrderedLeafSetNode<?>) readConfigurationData(path.getParent());
if (readLeafList == null || readLeafList.getValue().isEmpty()) {
- simplePut(datastore, path, rWTransaction, schemaContext, payload);
+ simplePut(datastore, path, rwTransaction, schemaContext, payload);
} else {
- insertWithPointLeafListPut(rWTransaction, datastore, path, payload, schemaContext, point,
+ insertWithPointLeafListPut(rwTransaction, datastore, path, payload, schemaContext, point,
readLeafList, false);
}
}
tx.delete(datastore, path.getParent());
final InstanceIdentifierContext<?> instanceIdentifier =
ControllerContext.getInstance().toInstanceIdentifier(point);
- int p = 0;
+ int index1 = 0;
for (final LeafSetEntryNode<?> nodeChild : readLeafList.getValue()) {
if (nodeChild.getIdentifier().equals(instanceIdentifier.getInstanceIdentifier().getLastPathArgument())) {
break;
}
- p++;
+ index1++;
}
if (!before) {
- p++;
+ index1++;
}
- int h = 0;
+ int index2 = 0;
final NormalizedNode<?, ?> emptySubtree =
ImmutableNodes.fromInstanceId(schemaContext, path.getParent());
tx.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
for (final LeafSetEntryNode<?> nodeChild : readLeafList.getValue()) {
- if (h == p) {
+ if (index2 == index1) {
simplePut(datastore, path, tx, schemaContext, payload);
}
final YangInstanceIdentifier childPath = path.getParent().node(nodeChild.getIdentifier());
tx.put(datastore, childPath, nodeChild);
- h++;
+ index2++;
}
}
tx.delete(datastore, path.getParent());
final InstanceIdentifierContext<?> instanceIdentifier =
ControllerContext.getInstance().toInstanceIdentifier(point);
- int p = 0;
+ int index1 = 0;
for (final MapEntryNode mapEntryNode : readList.getValue()) {
if (mapEntryNode.getIdentifier().equals(instanceIdentifier.getInstanceIdentifier().getLastPathArgument())) {
break;
}
- p++;
+ index1++;
}
if (!before) {
- p++;
+ index1++;
}
- int h = 0;
+ int index2 = 0;
final NormalizedNode<?, ?> emptySubtree =
ImmutableNodes.fromInstanceId(schemaContext, path.getParent());
tx.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
for (final MapEntryNode mapEntryNode : readList.getValue()) {
- if (h == p) {
+ if (index2 == index1) {
simplePut(datastore, path, tx, schemaContext, payload);
}
final YangInstanceIdentifier childPath = path.getParent().node(mapEntryNode.getIdentifier());
tx.put(datastore, childPath, mapEntryNode);
- h++;
+ index2++;
}
}
private static void deleteDataWithinTransaction(final DOMDataWriteTransaction tx,
final LogicalDatastoreType datastore, final YangInstanceIdentifier path) {
- LOG.trace("Delete {} within Restconf PATCH: {}", datastore.name(), path);
+ LOG.trace("Delete {} within Restconf Patch: {}", datastore.name(), path);
tx.delete(datastore, path);
}
private static void mergeDataWithinTransaction(final DOMDataWriteTransaction tx,
final LogicalDatastoreType datastore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload,
final SchemaContext schemaContext) {
- LOG.trace("Merge {} within Restconf PATCH: {} with payload {}", datastore.name(), path, payload);
+ LOG.trace("Merge {} within Restconf Patch: {} with payload {}", datastore.name(), path, payload);
ensureParentsByMerge(datastore, path, tx, schemaContext);
// Since YANG Patch provides the option to specify what kind of operation for each edit,
tx.merge(store, rootNormalizedPath, parentStructure);
}
- private static final class PATCHStatusContextHelper {
- PATCHStatusContext status;
+ private static final class PatchStatusContextHelper {
+ PatchStatusContext status;
- public PATCHStatusContext getStatus() {
+ public PatchStatusContext getStatus() {
return this.status;
}
- public void setStatus(final PATCHStatusContext status) {
+ public void setStatus(final PatchStatusContext status) {
this.status = status;
}
}
return toIdentifier(restconfInstance, true);
}
- private InstanceIdentifierContext<?> toIdentifier(final String restconfInstance, final boolean toMountPointIdentifier) {
+ private InstanceIdentifierContext<?> toIdentifier(final String restconfInstance,
+ final boolean toMountPointIdentifier) {
checkPreconditions();
- if(restconfInstance == null) {
+ if (restconfInstance == null) {
return new InstanceIdentifierContext<>(YangInstanceIdentifier.EMPTY, this.globalSchema, null,
this.globalSchema);
}
final Module latestModule = this.globalSchema.findModuleByName(startModule, null);
if (latestModule == null) {
- throw new RestconfDocumentedException("The module named '" + startModule + "' does not exist.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
+ throw new RestconfDocumentedException("The module named '" + startModule + "' does not exist.",
+ ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
}
- final InstanceIdentifierContext<?> iiWithSchemaNode = collectPathArguments(builder, pathArgs, latestModule, null,
- toMountPointIdentifier);
+ final InstanceIdentifierContext<?> iiWithSchemaNode =
+ collectPathArguments(builder, pathArgs, latestModule, null, toMountPointIdentifier);
if (iiWithSchemaNode == null) {
throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
return list;
}
+
public Module findModuleByName(final String moduleName) {
checkPreconditions();
Preconditions.checkArgument((moduleName != null) && !moduleName.isEmpty());
public Module findModuleByNameAndRevision(final QName module) {
checkPreconditions();
- Preconditions.checkArgument((module != null) && (module.getLocalName() != null) && (module.getRevision() != null));
+ Preconditions
+ .checkArgument((module != null) && (module.getLocalName() != null) && (module.getRevision() != null));
return this.globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
}
public Module findModuleByNameAndRevision(final DOMMountPoint mountPoint, final QName module) {
checkPreconditions();
- Preconditions.checkArgument((module != null) && (module.getLocalName() != null) && (module.getRevision() != null)
+ Preconditions
+ .checkArgument((module != null) && (module.getLocalName() != null) && (module.getRevision() != null)
&& (mountPoint != null));
final SchemaContext schemaContext = mountPoint.getSchemaContext();
if (!(element instanceof AugmentationIdentifier)) {
final QName _nodeType = element.getNodeType();
final DataSchemaNode potentialNode = childByQName(node, _nodeType);
- if (!((element instanceof NodeIdentifier) && (potentialNode instanceof ListSchemaNode)) &&
- !(potentialNode instanceof ChoiceSchemaNode)) {
+ if (!((element instanceof NodeIdentifier) && (potentialNode instanceof ListSchemaNode))
+ && !(potentialNode instanceof ChoiceSchemaNode)) {
builder.append(convertToRestconfIdentifier(element, potentialNode, mount));
if (potentialNode instanceof DataNodeContainer) {
node = (DataNodeContainer) potentialNode;
final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings,
- g -> RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
+ g -> RestConfModule.ERRORS_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
final Set<GroupingDefinition> groupings = restconfModule.getGroupings();
final Iterable<GroupingDefinition> filteredGroups = Iterables.filter(groupings,
- g -> RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
+ g -> RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName()));
final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
final List<DataSchemaNode> instanceDataChildrenByName = findInstanceDataChildrenByName(restconfGrouping,
return null;
}
+
+ private static DataSchemaNode childByQName(final Object container, final QName name) {
+ if (container instanceof ChoiceCaseNode) {
+ return childByQName((ChoiceCaseNode) container, name);
+ } else if (container instanceof ChoiceSchemaNode) {
+ return childByQName((ChoiceSchemaNode) 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 dataNodeChildByQName(final DataNodeContainer container, final QName name) {
final DataSchemaNode ret = container.getDataChildByName(name);
if (ret == null) {
private InstanceIdentifierContext<?> collectPathArguments(final InstanceIdentifierBuilder builder,
final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
final boolean returnJustMountPoint) {
- Preconditions.<List<String>> checkNotNull(strings);
+ Preconditions.<List<String>>checkNotNull(strings);
if (parentNode == null) {
return null;
ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
}
- final Module moduleBehindMountPoint = mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null);
+ final Module moduleBehindMountPoint =
+ mountPointSchema.findModuleByName(moduleNameBehindMountPoint, null);
if (moduleBehindMountPoint == null) {
throw new RestconfDocumentedException("\"" + moduleNameBehindMountPoint
+ "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
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\"."
+ + 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);
}
final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
final HashMap<QName, Object> keyValues = new HashMap<>();
- int i = 0;
+ int index = 0;
for (final QName key : listNode.getKeyDefinition()) {
{
- final String uriKeyValue = uriKeyValues.get(i);
+ final String uriKeyValue = uriKeyValues.get(index);
if (uriKeyValue.equals(NULL_VALUE)) {
throw new RestconfDocumentedException("URI has bad format. List \""
+ listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
}
addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
- i++;
+ index++;
}
}
- consumed = consumed + i;
+ consumed = consumed + index;
builder.nodeWithKey(targetNode.getQName(), keyValues);
} else {
builder.node(targetNode.getQName());
String additionalInfo = "";
if (decoded == null) {
if ((typedef instanceof IdentityrefTypeDefinition)) {
- final SchemaContext schemaContext = mountPoint == null ? this.globalSchema : mountPoint.getSchemaContext();
+ final SchemaContext schemaContext =
+ mountPoint == null ? this.globalSchema : mountPoint.getSchemaContext();
decoded = toQName(schemaContext, urlDecoded, null);
additionalInfo =
"For key which is of type identityref it should be in format module_name:identity_name.";
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 ChoiceSchemaNode) {
- return childByQName((ChoiceSchemaNode) 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());
- }
- }
-
public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) {
try {
return this.dataNormalizer.toNormalized(legacy);
* module.
*/
class FakeContainerSchemaNode implements ContainerSchemaNode {
- static final SchemaPath PATH = SchemaPath.create(true, QName.create(FakeRestconfModule.QNAME, "operations").intern());
+ static final SchemaPath PATH =
+ SchemaPath.create(true, QName.create(FakeRestconfModule.QNAME, "operations").intern());
private final Collection<DataSchemaNode> children;
/**
* Special case only use by GET restconf/operations (since moment of old Yang
* parser and old yang model API removal) to build and use fake leaf like child
- * in container
+ * in container.
*/
final class FakeLeafSchemaNode implements LeafSchemaNode {
private final SchemaPath path;
/**
- * Base values for fake leaf schema node
+ * Base values for fake leaf schema node.
*
* @param qname
- * - qname
+ * qname
*/
FakeLeafSchemaNode(final QName qname) {
this.path = FakeContainerSchemaNode.PATH.createChild(qname);
/**
* Special case only use by GET restconf/operations (since moment of old Yang
* parser and old yang model API removal) to build and use fake module to create
- * new schema context
+ * new schema context.
*/
final class FakeRestconfModule implements Module {
static final QNameModule QNAME;
+
static {
Date date;
try {
private final ImmutableSet<ModuleImport> imports;
/**
- * Instantiate a new fake module
+ * Instantiate a new fake module.
*
* @param neededModules needed import statements
* @param child fake child container
*/
- public FakeRestconfModule(final Collection<Module> neededModules, final ContainerSchemaNode child) {
+ FakeRestconfModule(final Collection<Module> neededModules, final ContainerSchemaNode child) {
this.children = ImmutableList.of(child);
this.imports = ImmutableSet.copyOf(Collections2.transform(neededModules, FakeModuleImport::new));
}
private final List<IdentityValue> elementData = new ArrayList<>();
private final String originValue;
- public IdentityValuesDTO(final String namespace, final String value, final String prefix, final String originValue) {
+ public IdentityValuesDTO(
+ final String namespace, final String value, final String prefix, final String originValue) {
elementData.add(new IdentityValue(namespace, value));
this.originValue = originValue;
}
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
-public class InstanceIdentifierContext <T extends SchemaNode> {
+public class InstanceIdentifierContext<T extends SchemaNode> {
private final YangInstanceIdentifier instanceIdentifier;
private final T schemaNode;
*/
@Deprecated
public class JSONRestconfServiceImpl implements JSONRestconfService, AutoCloseable {
- private final static Logger LOG = LoggerFactory.getLogger(JSONRestconfServiceImpl.class);
+ private static final Logger LOG = LoggerFactory.getLogger(JSONRestconfServiceImpl.class);
private static final Annotation[] EMPTY_ANNOTATIONS = new Annotation[0];
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public void put(final String uriPath, final String payload, final UriInfo uriInfo) throws OperationFailedException {
Preconditions.checkNotNull(payload, "payload can't be null");
}
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public void post(final String uriPath, final String payload, final UriInfo uriInfo)
throws OperationFailedException {
}
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public void delete(final String uriPath) throws OperationFailedException {
LOG.debug("delete: uriPath: {}", uriPath);
}
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public Optional<String> get(final String uriPath, final LogicalDatastoreType datastoreType, final UriInfo uriInfo)
throws OperationFailedException {
try {
NormalizedNodeContext readData;
- if(datastoreType == LogicalDatastoreType.CONFIGURATION) {
+ if (datastoreType == LogicalDatastoreType.CONFIGURATION) {
readData = RestconfImpl.getInstance().readConfigurationData(uriPath, uriInfo);
} else {
readData = RestconfImpl.getInstance().readOperationalData(uriPath, uriInfo);
return result;
} catch (final Exception e) {
- if(!isDataMissing(e)) {
+ if (!isDataMissing(e)) {
propagateExceptionAs(uriPath, e, "GET");
}
}
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
- public Optional<String> invokeRpc(final String uriPath, final Optional<String> input) throws OperationFailedException {
+ public Optional<String> invokeRpc(final String uriPath, final Optional<String> input)
+ throws OperationFailedException {
Preconditions.checkNotNull(uriPath, "uriPath can't be null");
final String actualInput = input.isPresent() ? input.get() : null;
String output = null;
try {
NormalizedNodeContext outputContext;
- if(actualInput != null) {
+ if (actualInput != null) {
final InputStream entityStream = new ByteArrayInputStream(actualInput.getBytes(StandardCharsets.UTF_8));
- final NormalizedNodeContext inputContext = JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, true);
+ final NormalizedNodeContext inputContext =
+ JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, true);
LOG.debug("Parsed YangInstanceIdentifier: {}", inputContext.getInstanceIdentifierContext()
.getInstanceIdentifier());
outputContext = RestconfImpl.getInstance().invokeRpc(uriPath, "", null);
}
- if(outputContext.getData() != null) {
+ if (outputContext.getData() != null) {
output = toJson(outputContext);
}
} catch (final Exception e) {
final NormalizedNodeJsonBodyWriter writer = new NormalizedNodeJsonBodyWriter();
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
writer.writeTo(readData, NormalizedNodeContext.class, null, EMPTY_ANNOTATIONS,
- MediaType.APPLICATION_JSON_TYPE, null, outputStream );
+ MediaType.APPLICATION_JSON_TYPE, null, outputStream);
return outputStream.toString(StandardCharsets.UTF_8.name());
}
- private static boolean isDataMissing(final Exception e) {
+ private static boolean isDataMissing(final Exception exception) {
boolean dataMissing = false;
- if (e instanceof RestconfDocumentedException) {
- final RestconfDocumentedException rde = (RestconfDocumentedException)e;
- if(!rde.getErrors().isEmpty()) {
- if(rde.getErrors().get(0).getErrorTag() == ErrorTag.DATA_MISSING) {
+ if (exception instanceof RestconfDocumentedException) {
+ final RestconfDocumentedException rde = (RestconfDocumentedException)exception;
+ if (!rde.getErrors().isEmpty()) {
+ if (rde.getErrors().get(0).getErrorTag() == ErrorTag.DATA_MISSING) {
dataMissing = true;
}
}
return dataMissing;
}
- private static void propagateExceptionAs(final String uriPath, final Exception e, final String operation) throws OperationFailedException {
- LOG.debug("Error for uriPath: {}", uriPath, e);
+ private static void propagateExceptionAs(final String uriPath, final Exception exception, final String operation)
+ throws OperationFailedException {
+ LOG.debug("Error for uriPath: {}", uriPath, exception);
- if(e instanceof RestconfDocumentedException) {
- throw new OperationFailedException(String.format("%s failed for URI %s", operation, uriPath), e.getCause(),
- toRpcErrors(((RestconfDocumentedException)e).getErrors()));
+ if (exception instanceof RestconfDocumentedException) {
+ throw new OperationFailedException(String.format(
+ "%s failed for URI %s", operation, uriPath), exception.getCause(),
+ toRpcErrors(((RestconfDocumentedException)exception).getErrors()));
}
- throw new OperationFailedException(String.format("%s failed for URI %s", operation, uriPath), e);
+ throw new OperationFailedException(String.format("%s failed for URI %s", operation, uriPath), exception);
}
private static RpcError[] toRpcErrors(final List<RestconfError> from) {
final RpcError[] to = new RpcError[from.size()];
- int i = 0;
- for(final RestconfError e: from) {
- to[i++] = RpcResultBuilder.newError(toRpcErrorType(e.getErrorType()), e.getErrorTag().getTagValue(),
+ int index = 0;
+ for (final RestconfError e: from) {
+ to[index++] = RpcResultBuilder.newError(toRpcErrorType(e.getErrorType()), e.getErrorTag().getTagValue(),
e.getErrorMessage());
}
}
private static ErrorType toRpcErrorType(final RestconfError.ErrorType errorType) {
- switch(errorType) {
+ switch (errorType) {
case TRANSPORT: {
return ErrorType.TRANSPORT;
}
private DataContainerChild<?, ?> processAugmentationNode(final NormalizedNode<?, ?> node, final Integer depth) {
final AugmentationNode augmentationNode = (AugmentationNode) node;
- DataContainerNodeBuilder<AugmentationIdentifier, ? extends DataContainerChild<?, ?>> newAugmentationBuilder = Builders
- .augmentationBuilder().withNodeIdentifier(augmentationNode.getIdentifier());
+ DataContainerNodeBuilder<AugmentationIdentifier, ? extends DataContainerChild<?, ?>> newAugmentationBuilder =
+ Builders.augmentationBuilder().withNodeIdentifier(augmentationNode.getIdentifier());
processDataContainerChild((DataContainerNode<?>) node, depth, newAugmentationBuilder);
private void processDataContainerChild(
final DataContainerNode<?> node,
final Integer depth,
- final DataContainerNodeBuilder<? extends YangInstanceIdentifier.PathArgument, ? extends DataContainerNode<?>> newBuilder) {
+ final DataContainerNodeBuilder<? extends YangInstanceIdentifier.PathArgument,
+ ? extends DataContainerNode<?>> newBuilder) {
for (DataContainerChild<? extends PathArgument, ?> nodeValue : node.getValue()) {
newBuilder.withChild(pruneDataAtDepth(nodeValue, depth - 1));
CollectionNodeBuilder<MapEntryNode, ? extends MapNode> newOrderedMapNodeBuilder) {
if (depth > 1) {
for (MapEntryNode oldMapEntryNode : ((MapNode) node).getValue()) {
- DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> newMapEntryNodeBuilder = Builders
- .mapEntryBuilder().withNodeIdentifier(oldMapEntryNode.getIdentifier());
+ DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> newMapEntryNodeBuilder =
+ Builders.mapEntryBuilder().withNodeIdentifier(oldMapEntryNode.getIdentifier());
for (DataContainerChild<? extends PathArgument, ?> mapEntryNodeValue : oldMapEntryNode.getValue()) {
newMapEntryNodeBuilder.withChild(pruneDataAtDepth(mapEntryNodeValue, depth - 1));
}
}
/**
- * @return
+ * Return headers of {@code NormalizedNodeContext}.
+ *
+ * @return map of headers
*/
public Map<String, Object> getNewHeaders() {
return this.headers;
import java.util.List;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
-public class PATCHContext {
+public class PatchContext {
private final InstanceIdentifierContext<? extends SchemaNode> context;
- private final List<PATCHEntity> data;
+ private final List<PatchEntity> data;
private final String patchId;
- public PATCHContext(final InstanceIdentifierContext<? extends SchemaNode> context,
- final List<PATCHEntity> data, final String patchId) {
+ public PatchContext(final InstanceIdentifierContext<? extends SchemaNode> context,
+ final List<PatchEntity> data, final String patchId) {
this.context = Preconditions.checkNotNull(context);
this.data = Preconditions.checkNotNull(data);
this.patchId = Preconditions.checkNotNull(patchId);
return context;
}
- public List<PATCHEntity> getData() {
+ public List<PatchEntity> getData() {
return data;
}
import javax.annotation.Nonnull;
/**
- *
* Each YANG patch edit specifies one edit operation on the target data
* node. The set of operations is aligned with the NETCONF edit
* operations, but also includes some new operations.
*
*/
-public enum PATCHEditOperation {
+public enum PatchEditOperation {
CREATE, //post
DELETE, //delete
INSERT, //post
* @return true if operation requires value, false otherwise
*/
public static final boolean isPatchOperationWithValue(@Nonnull final String operation) {
- switch (PATCHEditOperation.valueOf(operation.toUpperCase())) {
+ switch (PatchEditOperation.valueOf(operation.toUpperCase())) {
case CREATE:
// fall through
case MERGE:
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-public class PATCHEntity {
+public class PatchEntity {
private final String operation;
private final String editId;
private final NormalizedNode<?,?> node;
/**
- * Constructor to create PATCHEntity for PATCH operations which require value leaf representing data to be present.
- * @param editId Id of PATCH edit
- * @param operation PATCH edit operation
- * @param targetNode Target node for PATCH edit operation
+ * Constructor to create PatchEntity for Patch operations which require value leaf representing data to be present.
+ * @param editId Id of Patch edit
+ * @param operation Patch edit operation
+ * @param targetNode Target node for Patch edit operation
* @param node Data defined by value leaf used by edit operation
*/
- public PATCHEntity(final String editId, final String operation, final YangInstanceIdentifier targetNode, final
- NormalizedNode<?, ?> node) {
+ public PatchEntity(final String editId, final String operation, final YangInstanceIdentifier targetNode,
+ final NormalizedNode<?, ?> node) {
this.editId = Preconditions.checkNotNull(editId);
this.operation = Preconditions.checkNotNull(operation);
this.targetNode = Preconditions.checkNotNull(targetNode);
}
/**
- * Constructor to create PATCHEntity for PATCH operations which do not allow value leaf representing data to be
+ * Constructor to create PatchEntity for Patch operations which do not allow value leaf representing data to be
* present. <code>node</code> is set to <code>null</code> meaning that data are not allowed for edit operation.
- * @param editId Id of PATCH edit
- * @param operation PATCH edit operation
- * @param targetNode Target node for PATCH edit operation
+ * @param editId Id of Patch edit
+ * @param operation Patch edit operation
+ * @param targetNode Target node for Patch edit operation
*/
- public PATCHEntity(final String editId, final String operation, final YangInstanceIdentifier targetNode) {
+ public PatchEntity(final String editId, final String operation, final YangInstanceIdentifier targetNode) {
this.editId = Preconditions.checkNotNull(editId);
this.operation = Preconditions.checkNotNull(operation);
this.targetNode = Preconditions.checkNotNull(targetNode);
import java.util.List;
-public class PATCHStatusContext {
+public class PatchStatusContext {
private final String patchId;
- private final List<PATCHStatusEntity> editCollection;
+ private final List<PatchStatusEntity> editCollection;
private boolean ok;
private List<RestconfError> globalErrors;
- public PATCHStatusContext(final String patchId, final List<PATCHStatusEntity> editCollection,
+ public PatchStatusContext(final String patchId, final List<PatchStatusEntity> editCollection,
final boolean ok, final List<RestconfError> globalErrors) {
this.patchId = patchId;
this.editCollection = editCollection;
return patchId;
}
- public List<PATCHStatusEntity> getEditCollection() {
+ public List<PatchStatusEntity> getEditCollection() {
return editCollection;
}
import java.util.List;
-public class PATCHStatusEntity {
+public class PatchStatusEntity {
private final String editId;
private final List<RestconfError> editErrors;
private final boolean ok;
- public PATCHStatusEntity(final String editId, final boolean ok, final List<RestconfError> editErrors) {
+ public PatchStatusEntity(final String editId, final boolean ok, final List<RestconfError> editErrors) {
this.editId = editId;
this.ok = ok;
this.editErrors = editErrors;
private final CheckedFuture<Void, TransactionCommitFailedException> future;
/**
- * Wrap status and future by constructor - make this immutable
+ * Wrap status and future by constructor - make this immutable.
*
* @param status
- * - status of operations
+ * status of operations
* @param future
- * - result of submit of PUT operation
+ * result of submit of PUT operation
*/
public PutResult(final Status status, final CheckedFuture<Void, TransactionCommitFailedException> future) {
this.status = status;
}
/**
- * Get status
+ * Get status.
*
* @return {@link Status} result
*/
return parseParams(info, false);
}
+ public static WriterParameters parseWriterParameters(final UriInfo uriInfo, final boolean tagged) {
+ return parseParams(uriInfo, tagged);
+ }
+
private static WriterParameters parseParams(final UriInfo info, final boolean tagged) {
final WriterParameters.WriterParametersBuilder wpBuilder = new WriterParameters.WriterParametersBuilder();
wpBuilder.setTagged(tagged);
- if(info == null) {
+ if (info == null) {
return wpBuilder.build();
}
try {
final int depth = Integer.valueOf(param);
if (depth < 1) {
- throw new RestconfDocumentedException(new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
+ throw new RestconfDocumentedException(
+ new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
"Invalid depth parameter: " + depth, null,
"The depth parameter must be an integer > 1 or \"unbounded\""));
}
wpBuilder.setDepth(depth);
} catch (final NumberFormatException e) {
- throw new RestconfDocumentedException(new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
+ throw new RestconfDocumentedException(new RestconfError(
+ RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
"Invalid depth parameter: " + e.getMessage(), null,
"The depth parameter must be an integer > 1 or \"unbounded\""));
}
return wpBuilder.build();
}
- public static WriterParameters parseWriterParameters(final UriInfo uriInfo, final boolean tagged) {
- return parseParams(uriInfo, tagged);
- }
-
}
if (input instanceof IdentityValuesDTO) {
return this.identityrefCodec.deserialize(input);
}
- if(LOG.isDebugEnabled()) {
+ if (LOG.isDebugEnabled()) {
LOG.debug(
- "Value is not instance of IdentityrefTypeDefinition but is {}. Therefore NULL is used as translation of - {}",
+ "Value is not instance of IdentityrefTypeDefinition but is {}. "
+ + "Therefore NULL is used as translation of - {}",
input == null ? "null" : input.getClass(), String.valueOf(input));
}
return null;
return codec.deserialize((String) input);
}
} else {
- final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec = TypeDefinitionAwareCodec
- .from(this.type);
+ final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
+ TypeDefinitionAwareCodec.from(this.type);
if (typeAwarecodec != null) {
if (input instanceof IdentityValuesDTO) {
return typeAwarecodec.deserialize(((IdentityValuesDTO) input).getOriginValue());
} else if (this.type instanceof InstanceIdentifierTypeDefinition) {
return this.instanceIdentifier.serialize(input);
} else {
- final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec = TypeDefinitionAwareCodec
- .from(this.type);
+ final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
+ TypeDefinitionAwareCodec.from(this.type);
if (typeAwarecodec != null) {
return typeAwarecodec.serialize(input);
} else {
- if(LOG.isDebugEnabled()) {
+ if (LOG.isDebugEnabled()) {
LOG.debug("Codec for type \"" + this.type.getQName().getLocalName()
+ "\" is not implemented yet.");
}
for (final PathArgument pathArgument : data.getPathArguments()) {
final IdentityValue identityValue = qNameToIdentityValue(pathArgument.getNodeType());
if ((pathArgument instanceof NodeIdentifierWithPredicates) && (identityValue != null)) {
- final List<Predicate> predicates = keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument)
- .getKeyValues());
+ final List<Predicate> predicates =
+ keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument).getKeyValues());
identityValue.setPredicates(predicates);
} else if ((pathArgument instanceof NodeWithValue) && (identityValue != null)) {
final List<Predicate> predicates = new ArrayList<>();
private static List<Predicate> keyValuesToPredicateList(final Map<QName, Object> keyValues) {
final List<Predicate> result = new ArrayList<>();
- for (final QName qName : keyValues.keySet()) {
- final Object value = keyValues.get(qName);
- result.add(new Predicate(qNameToIdentityValue(qName), String.valueOf(value)));
+ for (final QName qualifiedName : keyValues.keySet()) {
+ final Object value = keyValues.get(qualifiedName);
+ result.add(new Predicate(qNameToIdentityValue(qualifiedName), String.valueOf(value)));
}
return result;
}
- private static IdentityValue qNameToIdentityValue(final QName qName) {
- if (qName != null) {
- return new IdentityValue(qName.getNamespace().toString(), qName.getLocalName());
+ private static IdentityValue qNameToIdentityValue(final QName qualifiedName) {
+ if (qualifiedName != null) {
+ return new IdentityValue(qualifiedName.getNamespace().toString(), qualifiedName.getLocalName());
}
return null;
}
* Unchecked exception to communicate error information, as defined in the ietf restcong draft, to be sent to the
* client.
*
+ * <p>
+ * See also <a href="https://tools.ietf.org/html/draft-bierman-netconf-restconf-02">RESTCONF</a>
+ *
* @author Devin Avery
* @author Thomas Pantelis
- * See also <a href="https://tools.ietf.org/html/draft-bierman-netconf-restconf-02">RESTCONF</a>
*/
public class RestconfDocumentedException extends WebApplicationException {
// FIXME: We override getMessage so supplied message is lost for any public access
// this was lost also in original code.
super(cause);
- if(!errors.isEmpty()) {
+ if (!errors.isEmpty()) {
this.errors = ImmutableList.copyOf(errors);
} else {
this.errors = ImmutableList.of(new RestconfError(RestconfError.ErrorType.APPLICATION,
private static List<RestconfError> convertToRestconfErrors(final Collection<RpcError> rpcErrors) {
final List<RestconfError> errorList = Lists.newArrayList();
- if(rpcErrors != null) {
+ if (rpcErrors != null) {
for (RpcError rpcError : rpcErrors) {
errorList.add(new RestconfError(rpcError));
}
* <b>Note:</b> Enumerations defined within are provided by the ietf restconf draft.
*
* @author Devin Avery
- * See also <a href="https://tools.ietf.org/html/draft-bierman-netconf-restconf-02">RESTCONF</a>.
+ * See also <a href="https://tools.ietf.org/html/draft-bierman-netconf-restconf-02">RESTCONF</a>.
*/
public class RestconfError {
public enum ErrorType {
- /** Errors relating to the transport layer */
+ /**
+ * Errors relating to the transport layer.
+ */
TRANSPORT,
- /** Errors relating to the RPC or notification layer */
+ /**
+ * Errors relating to the RPC or notification layer.
+ */
RPC,
- /** Errors relating to the protocol operation layer. */
+ /**
+ * Errors relating to the protocol operation layer.
+ */
PROTOCOL,
- /** Errors relating to the server application layer. */
+ /**
+ * Errors relating to the server application layer.
+ */
APPLICATION;
public String getErrorTypeTag() {
private final YangInstanceIdentifier errorPath;
/**
- * Constructs a RestConfError
+ * Constructs a RestConfError.
*
* @param errorType
* The enumerated type indicating the layer where the error occurred.
NETCONF_BASE_PAYLOAD_NAME).intern();
private static final QNameModule SAL_REMOTE_AUGMENT;
+
static {
try {
SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
}
/**
- * Valid only for mount point
+ * Valid only for mount point.
*/
@Override
public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
* implementations of schema nodes and module.
*
* @param modules
- * - set of modules for get RPCs from every module
+ * set of modules for get RPCs from every module
* @param mountPoint
- * - mount point, if in use otherwise null
+ * mount point, if in use otherwise null
* @return {@link NormalizedNodeContext}
*/
private static NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
final Splitter splitter = Splitter.on("/").omitEmptyStrings();
final 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) {
LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
throw new RestconfDocumentedException(
resultData, QueryParametersParser.parseWriterParameters(uriInfo));
}
+ @Override
+ public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
+ if (noPayload != null && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
+ throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
+ }
+
+ String identifierEncoded = null;
+ DOMMountPoint mountPoint = null;
+ final SchemaContext schemaContext;
+ if (identifier.contains(ControllerContext.MOUNT)) {
+ // mounted RPC call - look up mount instance.
+ final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
+ mountPoint = mountPointId.getMountPoint();
+ schemaContext = mountPoint.getSchemaContext();
+ final int startOfRemoteRpcName =
+ identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
+ final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
+ identifierEncoded = remoteRpcName;
+
+ } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
+ final String slashErrorMsg = String.format(
+ "Identifier %n%s%ncan\'t contain slash "
+ + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.",
+ identifier);
+ LOG.debug(slashErrorMsg);
+ throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
+ } else {
+ identifierEncoded = identifier;
+ schemaContext = this.controllerContext.getGlobalSchema();
+ }
+
+ final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
+
+ RpcDefinition rpc = null;
+ if (mountPoint == null) {
+ rpc = this.controllerContext.getRpcDefinition(identifierDecoded, null);
+ } else {
+ rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
+ }
+
+ if (rpc == null) {
+ LOG.debug("RPC " + identifierDecoded + " does not exist.");
+ throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
+ }
+
+ if (!rpc.getInput().getChildNodes().isEmpty()) {
+ LOG.debug("RPC " + rpc + " does not need input value.");
+ // FIXME : find a correct Error from specification
+ throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
+ }
+
+ final CheckedFuture<DOMRpcResult, DOMRpcException> response;
+ if (mountPoint != null) {
+ final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
+ if (!mountRpcServices.isPresent()) {
+ throw new RestconfDocumentedException("Rpc service is missing.");
+ }
+ response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
+ } else {
+ response = this.broker.invokeRpc(rpc.getPath(), null);
+ }
+
+ final DOMRpcResult result = checkRpcResponse(response);
+
+ return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
+ result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
+ }
+
private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
if (response == null) {
return null;
return Futures.immediateCheckedFuture(defaultDOMRpcResult);
}
- @Override
- public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
- if (noPayload != null && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
- throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
- }
-
- String identifierEncoded = null;
- DOMMountPoint mountPoint = null;
- final SchemaContext schemaContext;
- if (identifier.contains(ControllerContext.MOUNT)) {
- // mounted RPC call - look up mount instance.
- final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
- mountPoint = mountPointId.getMountPoint();
- schemaContext = mountPoint.getSchemaContext();
- final int startOfRemoteRpcName =
- identifier.lastIndexOf(ControllerContext.MOUNT) + ControllerContext.MOUNT.length() + 1;
- final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
- identifierEncoded = remoteRpcName;
-
- } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
- final String slashErrorMsg = String.format(
- "Identifier %n%s%ncan\'t contain slash "
- + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.",
- identifier);
- LOG.debug(slashErrorMsg);
- throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
- } else {
- identifierEncoded = identifier;
- schemaContext = this.controllerContext.getGlobalSchema();
- }
-
- final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
-
- RpcDefinition rpc = null;
- if (mountPoint == null) {
- rpc = this.controllerContext.getRpcDefinition(identifierDecoded, null);
- } else {
- rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
- }
-
- if (rpc == null) {
- LOG.debug("RPC " + identifierDecoded + " does not exist.");
- throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
- }
-
- if (!rpc.getInput().getChildNodes().isEmpty()) {
- LOG.debug("RPC " + rpc + " does not need input value.");
- // FIXME : find a correct Error from specification
- throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
- }
-
- final CheckedFuture<DOMRpcResult, DOMRpcException> response;
- if (mountPoint != null) {
- final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
- if (!mountRpcServices.isPresent()) {
- throw new RestconfDocumentedException("Rpc service is missing.");
- }
- response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
- } else {
- response = this.broker.invokeRpc(rpc.getPath(), null);
- }
-
- final DOMRpcResult result = checkRpcResponse(response);
-
- return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
- result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
- }
-
private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
final String[] splittedIdentifier = identifierDecoded.split(":");
if (splittedIdentifier.length != 2) {
@Override
public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
- boolean withDefa_used = false;
+ boolean withDefaUsed = false;
String withDefa = null;
for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
switch (entry.getKey()) {
case "with-defaults":
- if (!withDefa_used) {
- withDefa_used = true;
+ if (!withDefaUsed) {
+ withDefaUsed = true;
withDefa = entry.getValue().iterator().next();
} else {
throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
}
break;
+ default:
+ LOG.info("Unknown key : {}.", entry.getKey());
+ break;
}
}
boolean tagged = false;
- if (withDefa_used) {
+ if (withDefaUsed) {
if (withDefa.equals("report-all-tagged")) {
tagged = true;
withDefa = null;
/**
* Validates whether keys in {@code payload} are equal to values of keys in
- * {@code iiWithData} for list schema node
+ * {@code iiWithData} for list schema node.
*
* @throws RestconfDocumentedException
* if key values or key count in payload and URI isn't equal
return createConfigurationData(payload, uriInfo);
}
- // FIXME create RestconfIdetifierHelper and move this method there
- private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
- Preconditions.checkArgument(payload != null);
- Preconditions.checkArgument(payload.getData() != null);
- Preconditions.checkArgument(payload.getData().getNodeType() != null);
- Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
- Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
-
- final QName payloadNodeQname = payload.getData().getNodeType();
- final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
- if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
- return yangIdent;
- }
- final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
- final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
- if (parentSchemaNode instanceof DataNodeContainer) {
- final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
- for (final DataSchemaNode child : cast.getChildNodes()) {
- if (payloadNodeQname.compareTo(child.getQName()) == 0) {
- return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
- }
- }
- }
- if (parentSchemaNode instanceof RpcDefinition) {
- return yangIdent;
- }
- final String errMsg = "Error parsing input: DataSchemaNode has not children ";
- LOG.info(errMsg + yangIdent);
- throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
- }
-
@Override
public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
if (payload == null) {
return responseBuilder.build();
}
+ // FIXME create RestconfIdetifierHelper and move this method there
+ private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
+ Preconditions.checkArgument(payload != null);
+ Preconditions.checkArgument(payload.getData() != null);
+ Preconditions.checkArgument(payload.getData().getNodeType() != null);
+ Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
+ Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
+
+ final QName payloadNodeQname = payload.getData().getNodeType();
+ final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
+ if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
+ return yangIdent;
+ }
+ final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
+ final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
+ if (parentSchemaNode instanceof DataNodeContainer) {
+ final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
+ for (final DataSchemaNode child : cast.getChildNodes()) {
+ if (payloadNodeQname.compareTo(child.getQName()) == 0) {
+ return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
+ }
+ }
+ }
+ if (parentSchemaNode instanceof RpcDefinition) {
+ return yangIdent;
+ }
+ final String errMsg = "Error parsing input: DataSchemaNode has not children ";
+ LOG.info(errMsg + yangIdent);
+ throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
+ }
+
+ @SuppressWarnings("checkstyle:IllegalCatch")
private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint,
final YangInstanceIdentifier normalizedII) {
if (uriInfo == null) {
* Subscribes to some path in schema context (stream) to listen on changes
* on this stream.
*
+ * <p>
* Additional parameters for subscribing to stream are loaded via rpc input
* parameters:
* <ul>
*/
@Override
public NormalizedNodeContext subscribeToStream(final String identifier, final UriInfo uriInfo) {
- boolean startTime_used = false;
- boolean stopTime_used = false;
+ boolean startTimeUsed = false;
+ boolean stopTimeUsed = false;
Instant start = Instant.now();
Instant stop = null;
- boolean filter_used = false;
+ boolean filterUsed = false;
String filter = null;
- boolean leafNodesOnly_used = false;
+ boolean leafNodesOnlyUsed = false;
boolean leafNodesOnly = false;
for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
switch (entry.getKey()) {
case "start-time":
- if (!startTime_used) {
- startTime_used = true;
+ if (!startTimeUsed) {
+ startTimeUsed = true;
start = parseDateFromQueryParam(entry);
} else {
throw new RestconfDocumentedException("Start-time parameter can be used only once.");
}
break;
case "stop-time":
- if (!stopTime_used) {
- stopTime_used = true;
+ if (!stopTimeUsed) {
+ stopTimeUsed = true;
stop = parseDateFromQueryParam(entry);
} else {
throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
}
break;
case "filter":
- if (!filter_used) {
- filter_used = true;
+ if (!filterUsed) {
+ filterUsed = true;
filter = entry.getValue().iterator().next();
} else {
throw new RestconfDocumentedException("Filter parameter can be used only once.");
}
break;
case "odl-leaf-nodes-only":
- if (!leafNodesOnly_used) {
- leafNodesOnly_used = true;
+ if (!leafNodesOnlyUsed) {
+ leafNodesOnlyUsed = true;
leafNodesOnly = Boolean.parseBoolean(entry.getValue().iterator().next());
} else {
throw new RestconfDocumentedException("Odl-leaf-nodes-only parameter can be used only once.");
throw new RestconfDocumentedException("Bad parameter used with notifications: " + entry.getKey());
}
}
- if (!startTime_used && stopTime_used) {
+ if (!startTimeUsed && stopTimeUsed) {
throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
}
URI response = null;
}
/**
+ * Prepare instance identifier.
+ *
* @return {@link InstanceIdentifierContext} of location leaf for
* notification
*/
}
/**
- * Register notification listener by stream name
+ * Register notification listener by stream name.
*
* @param identifier
- * - stream name
+ * stream name
* @param uriInfo
- * - uriInfo
+ * uriInfo
* @param stop
- * - stop-time of getting notification
+ * stop-time of getting notification
* @param start
- * - start-time of getting notification
+ * start-time of getting notification
* @param filter
- * - indicate which subset of all possible events are of interest
+ * indicate which subset of all possible events are of interest
* @return {@link URI} of location
*/
private URI notifStream(final String identifier, final UriInfo uriInfo, final Instant start,
for (final NotificationListenerAdapter listener : listeners) {
this.broker.registerToListenNotification(listener);
- listener.setQueryParams(start, java.util.Optional.ofNullable(stop), java.util.Optional.ofNullable(filter), false);
+ listener.setQueryParams(start,
+ java.util.Optional.ofNullable(stop), java.util.Optional.ofNullable(filter), false);
}
final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
}
/**
- * Register data change listener by stream name
+ * Register data change listener by stream name.
*
* @param identifier
- * - stream name
+ * stream name
* @param uriInfo
- * - uri info
+ * uri info
* @param stop
- * - start-time of getting notification
+ * start-time of getting notification
* @param start
- * - stop-time of getting notification
+ * stop-time of getting notification
* @param filter
- * - indicate which subset of all possible events are of interest
+ * indicate which subset of all possible events are of interest
* @return {@link URI} of location
*/
private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop,
throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
ErrorTag.UNKNOWN_ELEMENT);
}
- listener.setQueryParams(start, java.util.Optional.ofNullable(stop), java.util.Optional.ofNullable(filter), leafNodesOnly);
+ listener.setQueryParams(start, java.util.Optional.ofNullable(stop),
+ java.util.Optional.ofNullable(filter), leafNodesOnly);
final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
final LogicalDatastoreType datastore =
return uriToWebsocketServer;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
- public PATCHStatusContext patchConfigurationData(final String identifier, final PATCHContext context,
- final UriInfo uriInfo) {
+ public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext context,
+ final UriInfo uriInfo) {
if (context == null) {
throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
}
}
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
- public PATCHStatusContext patchConfigurationData(final PATCHContext context, @Context final UriInfo uriInfo) {
+ public PatchStatusContext patchConfigurationData(final PatchContext context, @Context final UriInfo uriInfo) {
if (context == null) {
throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
}
}
/**
- * Load parameter for subscribing to stream from input composite node
+ * Load parameter for subscribing to stream from input composite node.
*
* @param value
* contains value
/**
* Checks whether {@code value} is one of the string representation of
- * enumeration {@code classDescriptor}
+ * enumeration {@code classDescriptor}.
*
* @return enum object if string value of {@code classDescriptor}
* enumeration is equal to {@code value}. Other cases null.
}
/**
- * Prepare stream for notification
+ * Prepare stream for notification.
*
* @param payload
- * - contains list of qnames of notifications
+ * contains list of qnames of notifications
* @return - checked future object
*/
private static CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
final DOMDataBroker domDataBroker = session.getService(DOMDataBroker.class);
BrokerFacade.getInstance().setContext(session);
- BrokerFacade.getInstance().setDomDataBroker( domDataBroker);
+ BrokerFacade.getInstance().setDomDataBroker(domDataBroker);
final SchemaService schemaService = session.getService(SchemaService.class);
this.listenerRegistration = schemaService.registerSchemaContextListener(ControllerContext.getInstance());
BrokerFacade.getInstance().setRpcService(session.getService(DOMRpcService.class));
return this.delegate.invokeRpc(identifier, noPayload, uriInfo);
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
this.configGet.incrementAndGet();
normalizedNodeContext = this.delegate.readConfigurationData(identifier, uriInfo);
if (normalizedNodeContext.getData() != null) {
this.successGetConfig.incrementAndGet();
- }
- else {
+ } else {
this.failureGetConfig.incrementAndGet();
}
} catch (final Exception e) {
return normalizedNodeContext;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
this.operationalGet.incrementAndGet();
normalizedNodeContext = this.delegate.readOperationalData(identifier, uriInfo);
if (normalizedNodeContext.getData() != null) {
this.successGetOperational.incrementAndGet();
- }
- else {
+ } else {
this.failureGetOperational.incrementAndGet();
}
} catch (final Exception e) {
return normalizedNodeContext;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload,
final UriInfo uriInfo) {
response = this.delegate.updateConfigurationData(identifier, payload, uriInfo);
if (response.getStatus() == Status.OK.getStatusCode()) {
this.successPut.incrementAndGet();
- }
- else {
+ } else {
this.failurePut.incrementAndGet();
}
} catch (final Exception e) {
return response;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload,
final UriInfo uriInfo) {
response = this.delegate.createConfigurationData(identifier, payload, uriInfo);
if (response.getStatus() == Status.OK.getStatusCode()) {
this.successPost.incrementAndGet();
- }
- else {
+ } else {
this.failurePost.incrementAndGet();
}
} catch (final Exception e) {
return response;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
this.configPost.incrementAndGet();
response = this.delegate.createConfigurationData(payload, uriInfo);
if (response.getStatus() == Status.OK.getStatusCode()) {
this.successPost.incrementAndGet();
- }
- else {
+ } else {
this.failurePost.incrementAndGet();
}
- }catch (final Exception e) {
+ } catch (final Exception e) {
this.failurePost.incrementAndGet();
throw e;
}
return response;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public Response deleteConfigurationData(final String identifier) {
this.configDelete.incrementAndGet();
response = this.delegate.deleteConfigurationData(identifier);
if (response.getStatus() == Status.OK.getStatusCode()) {
this.successDelete.incrementAndGet();
- }
- else {
+ } else {
this.failureDelete.incrementAndGet();
}
} catch (final Exception e) {
}
@Override
- public PATCHStatusContext patchConfigurationData(final String identifier, final PATCHContext payload,
- final UriInfo uriInfo) {
+ public PatchStatusContext patchConfigurationData(final String identifier, final PatchContext payload,
+ final UriInfo uriInfo) {
return this.delegate.patchConfigurationData(identifier, payload, uriInfo);
}
@Override
- public PATCHStatusContext patchConfigurationData(final PATCHContext payload, final UriInfo uriInfo) {
+ public PatchStatusContext patchConfigurationData(final PatchContext payload, final UriInfo uriInfo) {
return this.delegate.patchConfigurationData(payload, uriInfo);
}
import org.slf4j.LoggerFactory;
/**
- * Features of subscribing part of both notifications
+ * Features of subscribing part of both notifications.
*/
abstract class AbstractCommonSubscriber extends AbstractQueryParams implements BaseListenerInterface {
private ListenerRegistration registration;
/**
- * Creating {@link EventBus}
+ * Creating {@link EventBus}.
*/
protected AbstractCommonSubscriber() {
this.eventBus = new AsyncEventBus(Executors.newSingleThreadExecutor());
* Creates event of type {@link EventType#DEREGISTER}, sets {@link Channel}
* subscriber to the event and posts event into event bus.
*
- * @param subscriber
+ * @param subscriber subscriber channel
*/
public void removeSubscriber(final Channel subscriber) {
LOG.debug("Subscriber {} is removed.", subscriber.remoteAddress());
/**
* Creating and registering {@link EventBusChangeRecorder} of specific
- * listener on {@link EventBus}
+ * listener on {@link EventBus}.
*
* @param listener
- * - specific listener of notifications
+ * specific listener of notifications
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
protected <T extends BaseListenerInterface> void register(final T listener) {
}
/**
- * Post event to event bus
+ * Post event to event bus.
*
* @param event
- * - data of incoming notifications
+ * data of incoming notifications
*/
protected void post(final Event event) {
this.eventBus.post(event);
/**
* Removes all subscribers and unregisters event bus change recorder form
- * event bus
+ * event bus.
*/
protected void unregister() {
this.subscribers.clear();
import org.w3c.dom.Element;
/**
- * Abstract class for processing and preparing data
+ * Abstract class for processing and preparing data.
*
*/
abstract class AbstractNotificationsData {
private String localName;
/**
- * Transaction chain for delete data in DS on close()
+ * Transaction chain for delete data in DS on close().
*
* @param transactionChainHandler
- * - creating new write transaction for delete data on close
+ * creating new write transaction for delete data on close
* @param schemaHandler
- * - for getting schema to deserialize
+ * for getting schema to deserialize
* {@link MonitoringModule#PATH_TO_STREAM_WITHOUT_KEY} to
* {@link YangInstanceIdentifier}
*/
}
/**
- * Delete data in DS
+ * Delete data in DS.
*/
protected void deleteDataInDS() throws Exception {
final DOMDataWriteTransaction wTx = this.transactionChainHandler.get().newWriteOnlyTransaction();
}
/**
- * Set localName of last path element of specific listener
+ * Set localName of last path element of specific listener.
*
* @param localName
- * - local name
+ * local name
*/
protected void setLocalNameOfPath(final String localName) {
this.localName = localName;
}
/**
- * Write normalized node to {@link DOMResult}
+ * Write normalized node to {@link DOMResult}.
*
* @param normalized
- * - data
+ * data
* @param context
- * - actual schema context
+ * actual schema context
* @param schemaPath
- * - schema path of data
+ * schema path of data
* @return {@link DOMResult}
*/
protected DOMResult writeNormalizedNode(final NormalizedNode<?, ?> normalized, final SchemaContext context,
final SchemaPath schemaPath) throws IOException, XMLStreamException {
- final XMLOutputFactory XML_FACTORY = XMLOutputFactory.newFactory();
+ final XMLOutputFactory xmlFactory = XMLOutputFactory.newFactory();
final Document doc = XmlDocumentUtils.getDocument();
final DOMResult result = new DOMResult(doc);
NormalizedNodeWriter normalizedNodeWriter = null;
XMLStreamWriter writer = null;
try {
- writer = XML_FACTORY.createXMLStreamWriter(result);
+ writer = xmlFactory.createXMLStreamWriter(result);
normalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter);
}
/**
- * Generating base element of every notification
+ * Generating base element of every notification.
*
* @param doc
- * - base {@link Document}
+ * base {@link Document}
* @return element of {@link Document}
*/
protected Element basePartDoc(final Document doc) {
}
/**
- * Generating of {@link Document} transforming to string
+ * Generating of {@link Document} transforming to string.
*
* @param doc
- * - {@link Document} with data
+ * {@link Document} with data
* @return - string from {@link Document}
*/
protected String transformDoc(final Document doc) {
import org.xml.sax.InputSource;
/**
- * Features of query parameters part of both notifications
+ * Features of query parameters part of both notifications.
*
*/
abstract class AbstractQueryParams extends AbstractNotificationsData {
// FIXME: BUG-7956: switch to using UntrustedXML
private static final DocumentBuilderFactory DBF;
+
static {
final DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
f.setCoalescing(true);
}
/**
- * Set query parameters for listener
+ * Set query parameters for listener.
*
* @param start
- * - start-time of getting notification
+ * start-time of getting notification
* @param stop
- * - stop-time of getting notification
+ * stop-time of getting notification
* @param filter
- * - indicate which subset of all possible events are of interest
+ * indicate which subset of all possible events are of interest
* @param leafNodesOnly
- * - if true, notifications will contain changes to leaf nodes only
+ * if true, notifications will contain changes to leaf nodes only
*/
- public void setQueryParams(final Instant start, final Optional<Instant> stop, final Optional<String> filter, final boolean leafNodesOnly) {
+ public void setQueryParams(final Instant start, final Optional<Instant> stop, final Optional<String> filter,
+ final boolean leafNodesOnly) {
this.start = Preconditions.checkNotNull(start);
this.stop = stop.orElse(null);
this.filter = filter.orElse(null);
}
/**
- * Check whether this query should only notify about leaf node changes
+ * Check whether this query should only notify about leaf node changes.
*
* @return true if this query should only notify about leaf node changes
*/
}
/**
- * Checking query parameters on specific notification
+ * Checking query parameters on specific notification.
*
- * @param xml
- * - data of notification
- * @param listener
- * - listener of notification
+ * @param xml data of notification
+ * @param listener listener of notification
* @return true if notification meets the requirements of query parameters,
* false otherwise
*/
+ @SuppressWarnings("checkstyle:IllegalCatch")
protected <T extends BaseListenerInterface> boolean checkQueryParams(final String xml, final T listener) {
final Instant now = Instant.now();
if (this.stop != null) {
}
/**
- * Check if is filter used and then prepare and post data do client
+ * Check if is filter used and then prepare and post data do client.
*
- * @param change
- * - data of notification
+ * @param xml data of notification
*/
+ @SuppressWarnings("checkstyle:IllegalCatch")
private boolean checkFilter(final String xml) {
if (this.filter == null) {
return true;
}
/**
- * Parse and evaluate filter value by xml
+ * Parse and evaluate filter value by xml.
*
* @return true or false - depends on filter expression and data of
* notifiaction
- * @throws Exception
+ * @throws Exception if operation fails
*/
private boolean parseFilterParam(final String xml) throws Exception {
final Document docOfXml = DBF.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
/**
* Base interface for both listeners({@link ListenerAdapter},
- * {@link NotificationListenerAdapter})
+ * {@link NotificationListenerAdapter}).
*/
interface BaseListenerInterface extends AutoCloseable {
/**
- * Return all subscribers of listener
+ * Return all subscribers of listener.
*
* @return set of subscribers
*/
boolean hasSubscribers();
/**
- * Get name of stream
+ * Get name of stream.
*
* @return stream name
*/
String getStreamName();
/**
- * Get output type
+ * Get output type.
*
* @return outputType
*/
* @param type
* EventType
*/
- public Event(final EventType type) {
+ Event(final EventType type) {
this.type = type;
}
private final T listener;
/**
- * Event bus change recorder of specific listener of notifications
+ * Event bus change recorder of specific listener of notifications.
*
* @param listener
- * - specific listener
+ * specific listener
*/
EventBusChangeRecorder(final T listener) {
this.listener = listener;
import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
import org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener;
import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
-import org.opendaylight.restconf.parser.builder.YangInstanceIdentifierDeserializer;
import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
/**
* Creates new {@link ListenerAdapter} listener specified by path and stream
- * name and register for subscribing
+ * name and register for subscribing.
*
* @param path
* Path to data in data store.
* @param streamName
* The name of the stream.
* @param outputType
- * - type of output on notification (JSON, XML)
+ * Type of output on notification (JSON, XML)
*/
ListenerAdapter(final YangInstanceIdentifier path, final String streamName,
final NotificationOutputType outputType) {
}
/**
- * Prepare data of notification and data to client
+ * Prepare data of notification and data to client.
*
- * @param xml
+ * @param xml data
*/
private void prepareAndPostData(final String xml) {
final Event event = new Event(EventType.NOTIFY);
/**
* Prepare data in printable form and transform it to String.
*
- * @param change
- * DataChangeEvent
* @return Data in printable form.
*/
private String prepareXml() {
return;
}
for (final Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> entry : data) {
- if (!ControllerContext.getInstance().isNodeMixin(entry.getKey()) &&
- (!getLeafNodesOnly() || entry.getValue() instanceof LeafNode)) {
+ if (!ControllerContext.getInstance().isNodeMixin(entry.getKey())
+ && (!getLeafNodesOnly() || entry.getValue() instanceof LeafNode)) {
final Node node = createCreatedChangedDataChangeEventElement(doc, entry, operation, schemaContext,
dataSchemaContextTree);
element.appendChild(node);
* {@link Element}
* @param textContent
* StringBuilder
- * @param qName
+ * @param qualifiedName
* QName
*/
private static void writeIdentifierWithNamespacePrefix(final Element element, final StringBuilder textContent,
- final QName qName) {
+ final QName qualifiedName) {
final Module module = ControllerContext.getInstance().getGlobalSchema()
- .findModuleByNamespaceAndRevision(qName.getNamespace(), qName.getRevision());
+ .findModuleByNamespaceAndRevision(qualifiedName.getNamespace(), qualifiedName.getRevision());
textContent.append(module.getName());
textContent.append(":");
- textContent.append(qName.getLocalName());
+ textContent.append(qualifiedName.getLocalName());
}
/**
* Consists of three types {@link Operation#CREATED},
* {@link Operation#UPDATED} and {@link Operation#DELETED}.
*/
- private static enum Operation {
+ private enum Operation {
CREATED("created"), UPDATED("updated"), DELETED("deleted");
private final String value;
- private Operation(final String value) {
+ Operation(final String value) {
this.value = value;
}
}
* Set path of listener and stream name, register event bus.
*
* @param path
- * - path of notification
+ * path of notification
* @param streamName
- * - stream name of listener
+ * stream name of listener
* @param outputType
- * - type of output on notification (JSON, XML)
+ * type of output on notification (JSON, XML)
*/
NotificationListenerAdapter(final SchemaPath path, final String streamName, final String outputType) {
super();
}
/**
- * Get outputType of listenere
+ * Get outputType of listener.
*
* @return the outputType
*/
}
/**
- * Get stream name of this listener
+ * Get stream name of this listener.
*
* @return {@link String}
*/
}
/**
- * Get schema path of notification
+ * Get schema path of notification.
*
* @return {@link SchemaPath}
*/
}
/**
- * Prepare data of notification and data to client
+ * Prepare data of notification and data to client.
*
- * @param xml
+ * @param xml data
*/
private void prepareAndPostData(final String xml) {
final Event event = new Event(EventType.NOTIFY);
}
/**
- * Prepare json from notification data
+ * Prepare json from notification data.
*
* @return json as {@link String}
*/
new ConcurrentHashMap<>();
private static final Logger LOG = LoggerFactory.getLogger(Notificator.class);
- private static final Lock lock = new ReentrantLock();
+ private static final Lock LOCK = new ReentrantLock();
private Notificator() {
}
/**
- * Returns list of all stream names
+ * Returns list of all stream names.
*/
public static Set<String> getStreamNames() {
return dataChangeListener.keySet();
/**
* Checks if the listener specified by {@link YangInstanceIdentifier} path exist.
*
- * @param streamName
+ * @param streamName name of the stream
* @return True if the listener exist, false otherwise.
*/
public static boolean existListenerFor(final String streamName) {
* @param streamName
* The name of the stream.
* @param outputType
- * - Spcific type of output for notifications - XML or JSON
+ * Spcific type of output for notifications - XML or JSON
* @return New {@link ListenerAdapter} listener from
* {@link YangInstanceIdentifier} path and stream name.
*/
final NotificationOutputType outputType) {
final ListenerAdapter listener = new ListenerAdapter(path, streamName, outputType);
try {
- lock.lock();
+ LOCK.lock();
dataChangeListener.put(streamName, listener);
} finally {
- lock.unlock();
+ LOCK.unlock();
}
return listener;
}
result = result.substring(1);
}
if (result.endsWith("/")) {
- result = result.substring(0, result.length()-1);
+ result = result.substring(0, result.length() - 1);
}
return result;
}
/**
* Removes all listeners.
*/
+ @SuppressWarnings("checkstyle:IllegalCatch")
public static void removeAllListeners() {
for (final ListenerAdapter listener : dataChangeListener.values()) {
try {
}
}
try {
- lock.lock();
+ LOCK.lock();
dataChangeListener = new ConcurrentHashMap<>();
} finally {
- lock.unlock();
+ LOCK.unlock();
}
}
* @param listener
* ListenerAdapter
*/
+ @SuppressWarnings("checkstyle:IllegalCatch")
private static <T extends BaseListenerInterface> void deleteListener(final T listener) {
if (listener != null) {
try {
LOG.error("Failed to close listener", e);
}
try {
- lock.lock();
+ LOCK.lock();
dataChangeListener.remove(listener.getStreamName());
} finally {
- lock.unlock();
+ LOCK.unlock();
}
}
}
* Check if the listener specified by qnames of request exist.
*
* @param streamName
- * - name of stream
+ * name of stream
* @return True if the listener exist, false otherwise.
*/
public static boolean existNotificationListenerFor(final String streamName) {
}
/**
- * Prepare listener for notification ({@link NotificationDefinition})
+ * Prepare listener for notification ({@link NotificationDefinition}).
*
* @param paths
- * - paths of notifications
+ * paths of notifications
* @param streamName
- * - name of stream (generated by paths)
+ * name of stream (generated by paths)
* @param outputType
- * - type of output for onNotification - XML or JSON
+ * type of output for onNotification - XML or JSON
* @return List of {@link NotificationListenerAdapter} by paths
*/
public static List<NotificationListenerAdapter> createNotificationListener(final List<SchemaPath> paths,
listListeners.add(listener);
}
try {
- lock.lock();
+ LOCK.lock();
notificationListenersByStreamName.put(streamName, listListeners);
} finally {
- lock.unlock();
+ LOCK.unlock();
}
return listListeners;
}
}
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
private static <T extends BaseListenerInterface> void deleteNotificationListener(final T listener) {
if (listener != null) {
try {
LOG.error("Failed to close listener", e);
}
try {
- lock.lock();
+ LOCK.lock();
notificationListenersByStreamName.remove(listener.getStreamName());
} finally {
- lock.unlock();
+ LOCK.unlock();
}
}
}
}
/**
- * Create singleton instance of {@link WebSocketServer}
+ * Create singleton instance of {@link WebSocketServer}.
*
* @param port TCP port used for this server
* @return instance of {@link WebSocketServer}
}
/**
+ * Get the websocket of TCP port.
+ *
* @return websocket TCP port
*/
public int getPort() {
}
/**
- * Get instance of {@link WebSocketServer} created by {@link #createInstance(int)}
+ * Get instance of {@link WebSocketServer} created by {@link #createInstance(int)}.
*
* @return instance of {@link WebSocketServer}
*/
}
/**
- * Destroy the existing instance
+ * Destroy the existing instance.
*/
public static void destroyInstance() {
Preconditions.checkState(instance != null, "createInstance() must be called prior to destroyInstance()");
*/
public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {
- private static final Logger logger = LoggerFactory.getLogger(WebSocketServerHandler.class);
+ private static final Logger LOG = LoggerFactory.getLogger(WebSocketServerHandler.class);
private WebSocketServerHandshaker handshaker;
final ListenerAdapter listener = Notificator.getListenerFor(streamName);
if (listener != null) {
listener.addSubscriber(ctx.channel());
- logger.debug("Subscriber successfully registered.");
+ LOG.debug("Subscriber successfully registered.");
} else {
- logger.error("Listener for stream with name '{}' was not found.", streamName);
+ LOG.error("Listener for stream with name '{}' was not found.", streamName);
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR));
}
} else if (streamName.contains(RestconfImpl.NOTIFICATION_STREAM)) {
if (!listeners.isEmpty() && (listeners != null)) {
for (final NotificationListenerAdapter listener : listeners) {
listener.addSubscriber(ctx.channel());
- logger.debug("Subscriber successfully registered.");
+ LOG.debug("Subscriber successfully registered.");
}
} else {
- logger.error("Listener for stream with name '{}' was not found.", streamName);
+ LOG.error("Listener for stream with name '{}' was not found.", streamName);
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR));
}
}
// Handshake
- final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
+ final WebSocketServerHandshakerFactory wsFactory =
+ new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
null, false);
this.handshaker = wsFactory.newHandshaker(req);
if (this.handshaker == null) {
}
/**
- * Checks response status, send response and close connection if necessary
+ * Checks response status, send response and close connection if necessary.
*
* @param ctx
* ChannelHandlerContext
final ListenerAdapter listener = Notificator.getListenerFor(streamName);
if (listener != null) {
listener.removeSubscriber(ctx.channel());
- logger.debug("Subscriber successfully registered.");
+ LOG.debug("Subscriber successfully registered.");
}
Notificator.removeListenerIfNoSubscriberExists(listener);
} else if (streamName.contains(RestconfImpl.NOTIFICATION_STREAM)) {
@Override
public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
- if ((cause instanceof java.nio.channels.ClosedChannelException) == false) {
- // cause.printStackTrace();
+ if (!(cause instanceof java.nio.channels.ClosedChannelException)) {
+ // LOG.info("Not expected error cause: ", cause.toString());
}
ctx.close();
}
private static final Logger LOG = LoggerFactory.getLogger(RestConnectorProvider.class);
- public static final TransactionChainListener transactionListener = new TransactionChainListener() {
+ public static final TransactionChainListener TRANSACTION_CHAIN_LISTENER = new TransactionChainListener() {
@Override
public void onTransactionChainFailed(final TransactionChain<?, ?> chain,
final AsyncTransaction<?, ?> transaction, final Throwable cause) {
final DOMDataBrokerHandler brokerHandler = new DOMDataBrokerHandler(RestConnectorProvider.dataBroker);
RestConnectorProvider.transactionChainHandler = new TransactionChainHandler(RestConnectorProvider.dataBroker
- .createTransactionChain(RestConnectorProvider.transactionListener));
+ .createTransactionChain(RestConnectorProvider.TRANSACTION_CHAIN_LISTENER));
this.schemaCtxHandler = new SchemaContextHandler(transactionChainHandler);
this.listenerRegistration = schemaService.registerSchemaContextListener(this.schemaCtxHandler);
* After {@link TransactionChain} failed, this updates {@link TransactionChainHandler} with new transaction chain.
*
* @param chain
- * - old {@link TransactionChain}
+ * old {@link TransactionChain}
*/
public static void resetTransactionChainForAdapaters(final TransactionChain<?, ?> chain) {
LOG.trace("Resetting TransactionChain({})", chain);
chain.close();
RestConnectorProvider.transactionChainHandler.update(
Preconditions.checkNotNull(RestConnectorProvider.dataBroker).createTransactionChain(
- RestConnectorProvider.transactionListener)
+ RestConnectorProvider.TRANSACTION_CHAIN_LISTENER)
);
}
import org.opendaylight.netconf.md.sal.rest.schema.SchemaExportContentYangBodyWriter;
import org.opendaylight.netconf.md.sal.rest.schema.SchemaExportContentYinBodyWriter;
import org.opendaylight.netconf.sal.rest.impl.JsonNormalizedNodeBodyReader;
-import org.opendaylight.netconf.sal.rest.impl.PATCHJsonBodyWriter;
-import org.opendaylight.netconf.sal.rest.impl.PATCHXmlBodyWriter;
+import org.opendaylight.netconf.sal.rest.impl.PatchJsonBodyWriter;
+import org.opendaylight.netconf.sal.rest.impl.PatchXmlBodyWriter;
import org.opendaylight.netconf.sal.rest.impl.RestconfDocumentedExceptionMapper;
import org.opendaylight.netconf.sal.rest.impl.XmlNormalizedNodeBodyReader;
import org.opendaylight.restconf.common.wrapper.services.ServicesWrapperImpl;
-import org.opendaylight.restconf.jersey.providers.JsonToPATCHBodyReader;
+import org.opendaylight.restconf.jersey.providers.JsonToPatchBodyReader;
import org.opendaylight.restconf.jersey.providers.NormalizedNodeJsonBodyWriter;
import org.opendaylight.restconf.jersey.providers.NormalizedNodeXmlBodyWriter;
-import org.opendaylight.restconf.jersey.providers.XmlToPATCHBodyReader;
+import org.opendaylight.restconf.jersey.providers.XmlToPatchBodyReader;
public class RestconfApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
- return ImmutableSet.<Class<?>> builder()
+ return ImmutableSet.<Class<?>>builder()
.add(NormalizedNodeJsonBodyWriter.class).add(NormalizedNodeXmlBodyWriter.class)
.add(JsonNormalizedNodeBodyReader.class).add(XmlNormalizedNodeBodyReader.class)
.add(SchemaExportContentYinBodyWriter.class)
- .add(JsonToPATCHBodyReader.class).add(XmlToPATCHBodyReader.class)
- .add(PATCHJsonBodyWriter.class).add(PATCHXmlBodyWriter.class)
+ .add(JsonToPatchBodyReader.class).add(XmlToPatchBodyReader.class)
+ .add(PatchJsonBodyWriter.class).add(PatchXmlBodyWriter.class)
.add(SchemaExportContentYangBodyWriter.class).add(RestconfDocumentedExceptionMapper.class)
.build();
}
import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
/**
- * Base Draft for Restconf project
+ * Base Draft for Restconf project.
* <ul>
* <li>Supported {@link MediaTypes}
* <li>Constants for modules
/**
* Set of application specific media types to identify each of the available
- * resource types
+ * resource types.
*/
public static final class MediaTypes {
}
/**
- * Constants for restconf module
+ * Constants for restconf module.
*
*/
public static final class RestconfModule {
}
/**
- * Constants for ietf-yang-library model
+ * Constants for ietf-yang-library model.
*
*/
public static final class IetfYangLibrary {
}
/**
- * Constants for ietf-restconf-monitoring module
+ * Constants for ietf-restconf-monitoring module.
*
*/
public static final class MonitoringModule {
.intern();
/**
- * Constants for capabilities
+ * Constants for capabilities.
*/
public static final class QueryParams {
package org.opendaylight.restconf.base.services.api;
/**
- * Wrapper for all base services:
+ * Wrapper for all base services.
* <ul>
* <li>{@link RestconfOperationsService}
* <li>{@link RestconfSchemaService}
* List of rpc or action operations supported by the server.
*
* @param uriInfo
- * - URI information
+ * URI information
* @return {@link NormalizedNodeContext}
*/
@GET
@Path("/operations")
@Produces({ Rfc8040.MediaTypes.DATA + RestconfConstants.JSON, Rfc8040.MediaTypes.DATA, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML, MediaType.TEXT_XML })
- public NormalizedNodeContext getOperations(@Context UriInfo uriInfo);
+ NormalizedNodeContext getOperations(@Context UriInfo uriInfo);
/**
* Valid for mount points. List of operations supported by the server.
*
* @param identifier
- * - path parameter
+ * path parameter
* @param uriInfo
- * - URI information
+ * URI information
* @return {@link NormalizedNodeContext}
*/
@GET
@Path("/operations/{identifier:.+}")
@Produces({ Rfc8040.MediaTypes.DATA + RestconfConstants.JSON, Rfc8040.MediaTypes.DATA, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML, MediaType.TEXT_XML })
- public NormalizedNodeContext getOperations(@PathParam("identifier") String identifier, @Context UriInfo uriInfo);
+ NormalizedNodeContext getOperations(@PathParam("identifier") String identifier, @Context UriInfo uriInfo);
}
\ No newline at end of file
* Get schema of specific module.
*
* @param identifier
- * - path parameter
+ * path parameter
* @return {@link SchemaExportContext}
*/
@GET
import org.opendaylight.restconf.utils.RestconfConstants;
/**
- * Service for getting yang library version
+ * Service for getting yang library version.
*
*/
public interface RestconfService {
/**
- * Get yang library version
+ * Get yang library version.
*
* @return {@link NormalizedNodeContext}
*/
@Path("/yang-library-version")
@Produces({ Rfc8040.MediaTypes.DATA + RestconfConstants.JSON, Rfc8040.MediaTypes.DATA, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML, MediaType.TEXT_XML })
- public NormalizedNodeContext getLibraryVersion();
+ NormalizedNodeContext getLibraryVersion();
}
* module.
*/
class FakeContainerSchemaNode implements ContainerSchemaNode {
- static final SchemaPath PATH = SchemaPath.create(true, QName.create(FakeRestconfModule.QNAME, "operations").intern());
+ static final SchemaPath PATH =
+ SchemaPath.create(true, QName.create(FakeRestconfModule.QNAME, "operations").intern());
private final Collection<DataSchemaNode> children;
/**
* Special case only use by GET restconf/operations (since moment of old Yang
* parser and old yang model API removal) to build and use fake leaf like child
- * in container
+ * in container.
*/
final class FakeLeafSchemaNode implements LeafSchemaNode {
private final SchemaPath path;
/**
- * Base values for fake leaf schema node
+ * Base values for fake leaf schema node.
*
* @param qname
- * - qname
+ * qname
*/
FakeLeafSchemaNode(final QName qname) {
this.path = FakeContainerSchemaNode.PATH.createChild(qname);
/**
* Special case only use by GET restconf/operations (since moment of old Yang
* parser and old yang model API removal) to build and use fake module to create
- * new schema context
+ * new schema context.
*/
final class FakeRestconfModule implements Module {
static final QNameModule QNAME;
+
static {
Date date;
try {
private final ImmutableSet<ModuleImport> imports;
/**
- * Instantiate a new fake module
+ * Instantiate a new fake module.
*
* @param neededModules needed import statements
* @param child fake child container
*/
- public FakeRestconfModule(final Collection<Module> neededModules, final ContainerSchemaNode child) {
+ FakeRestconfModule(final Collection<Module> neededModules, final ContainerSchemaNode child) {
this.children = ImmutableList.of(child);
this.imports = ImmutableSet.copyOf(Collections2.transform(neededModules, FakeModuleImport::new));
}
import org.slf4j.LoggerFactory;
/**
- * Implementation of {@link RestconfOperationsService}
+ * Implementation of {@link RestconfOperationsService}.
*
*/
public class RestconfOperationsServiceImpl implements RestconfOperationsService {
private final DOMMountPointServiceHandler domMountPointServiceHandler;
/**
- * Set {@link SchemaContextHandler} for getting actual {@link SchemaContext}
+ * Set {@link SchemaContextHandler} for getting actual {@link SchemaContext}.
*
* @param schemaContextHandler
- * - handling schema context
+ * handling schema context
* @param domMountPointServiceHandler
- * - handling dom mount point service
+ * handling dom mount point service
*/
public RestconfOperationsServiceImpl(final SchemaContextHandler schemaContextHandler,
final DOMMountPointServiceHandler domMountPointServiceHandler) {
* of schema nodes and module.
*
* @param modules
- * - set of modules for get RPCs from every module
+ * set of modules for get RPCs from every module
* @param mountPoint
- * - mount point, if in use otherwise null
+ * mount point, if in use otherwise null
* @return {@link NormalizedNodeContext}
*/
private static NormalizedNodeContext getOperations(final Set<Module> modules, final DOMMountPoint mountPoint) {
* .
*
* @param schemaContextHandler
- * - handling schema context
+ * handling schema context
* @param domMountPointServiceHandler
- * - handling dom mount point service
+ * handling dom mount point service
*/
public RestconfSchemaServiceImpl(final SchemaContextHandler schemaContextHandler,
final DOMMountPointServiceHandler domMountPointServiceHandler) {
private final SoftReference<SchemaContext> schemaContextRef;
/**
- * Create {@link SoftReference} of actual {@link SchemaContext}
+ * Create {@link SoftReference} of actual {@link SchemaContext}.
*
* @param schemaContext
- * - actual {@link SchemaContext}
+ * actual {@link SchemaContext}
*/
public SchemaContextRef(final SchemaContext schemaContext) {
this.schemaContextRef = new SoftReference<SchemaContext>(schemaContext);
}
/**
- * Get {@link SchemaContext} from reference
+ * Get {@link SchemaContext} from reference.
*
* @return {@link SchemaContext}
*/
/**
* Get all modules like {@link Set} of {@link Module} from
- * {@link SchemaContext}
+ * {@link SchemaContext}.
*
* @return {@link Set} of {@link Module}
*/
/**
* Get all modules like {@link Set} of {@link Module} from
- * {@link SchemaContext} of {@link DOMMountPoint}
+ * {@link SchemaContext} of {@link DOMMountPoint}.
*
* @param mountPoint
- * - mount point
+ * mount point
*
* @return {@link Set} of {@link Module}
*/
/**
* Get {@link Module} by ietf-restconf qname from
- * {@link Rfc8040.RestconfModule}
+ * {@link Rfc8040.RestconfModule}.
*
* @return {@link Module}
*/
/**
* Find {@link Module} in {@link SchemaContext} by {@link URI} and
- * {@link Date}
+ * {@link Date}.
*
* @param namespace
- * - namespace of module
+ * namespace of module
* @param revision
- * - revision of module
+ * revision of module
* @return {@link Module}
*/
public Module findModuleByNamespaceAndRevision(final URI namespace, final Date revision) {
/**
* Find {@link Module} in {@link SchemaContext} of {@link DOMMountPoint} by
- * {@link QName} of {@link Module}
+ * {@link QName} of {@link Module}.
*
* @param mountPoint
- * - mount point
+ * mount point
* @param moduleQname
- * - {@link QName} of module
+ * {@link QName} of module
* @return {@link Module}
*/
public Module findModuleInMountPointByQName(final DOMMountPoint mountPoint, final QName moduleQname) {
}
/**
- * Find {@link Module} in {@link SchemaContext} by {@link QName}
+ * Find {@link Module} in {@link SchemaContext} by {@link QName}.
*
* @param moduleQname
- * - {@link QName} of module
+ * {@link QName} of module
* @return {@link Module}
*/
public Module findModuleByQName(final QName moduleQname) {
* and {@link Date} revision.
*
* @param localName
- * - local name of module
+ * local name of module
* @param revision
- * - revision of module
+ * revision of module
* @return {@link Module}
*/
public Module findModuleByNameAndRevision(final String localName, final Date revision) {
import javax.ws.rs.core.UriInfo;
import org.opendaylight.netconf.md.sal.rest.schema.SchemaExportContext;
import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchStatusContext;
import org.opendaylight.restconf.base.services.api.BaseServicesWrapper;
import org.opendaylight.restconf.base.services.api.RestconfOperationsService;
import org.opendaylight.restconf.base.services.api.RestconfSchemaService;
import org.opendaylight.restconf.restful.services.impl.RestconfStreamsSubscriptionServiceImpl;
/**
- * Wrapper for services:
+ * Wrapper for services.
* <ul>
* <li>{@link BaseServicesWrapper}
* <li>{@link TransactionServicesWrapper}
}
@Override
- public PATCHStatusContext patchData(final String identifier, final PATCHContext context, final UriInfo uriInfo) {
+ public PatchStatusContext patchData(final String identifier, final PatchContext context, final UriInfo uriInfo) {
return this.delegRestconfDataService.patchData(identifier, context, uriInfo);
}
@Override
- public PATCHStatusContext patchData(final PATCHContext context, final UriInfo uriInfo) {
+ public PatchStatusContext patchData(final PatchContext context, final UriInfo uriInfo) {
return this.delegRestconfDataService.patchData(context, uriInfo);
}
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
/**
- * Implementation of {@link DOMDataBrokerHandler}
+ * Implementation of {@link DOMDataBrokerHandler}.
*
*/
public class DOMDataBrokerHandler implements Handler<DOMDataBroker> {
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
/**
- * Implementation of {@link DOMMountPointServiceHandler}
+ * Implementation of {@link DOMMountPointServiceHandler}.
*
*/
public class DOMMountPointServiceHandler implements Handler<DOMMountPointService> {
private final DOMMountPointService domMountPointService;
/**
- * Prepare mount point service for Restconf services
+ * Prepare mount point service for Restconf services.
*
* @param domMountPointService
- * - mount point service
+ * mount point service
*/
public DOMMountPointServiceHandler(final DOMMountPointService domMountPointService) {
Preconditions.checkNotNull(domMountPointService);
package org.opendaylight.restconf.handlers;
/**
- * Handler for handling object prepared by provider for Restconf services
+ * Handler for handling object prepared by provider for Restconf services.
*
* @param <T>
- * - specific type go object for handling it
+ * specific type go object for handling it
*/
interface Handler<T> {
/**
- * Get prepared object
+ * Get prepared object.
*
* @return T
*/
T get();
/**
- * Update object
+ * Update object.
*
* @param object
- * - new object to update old object
+ * new object to update old object
*/
default void update(T object) {}
}
private final DOMNotificationService notificationService;
/**
- * Set DOMNotificationService
+ * Set DOMNotificationService.
*
* @param notificationService
- * - DOMNotificationService
+ * DOMNotificationService
*/
public NotificationServiceHandler(final DOMNotificationService notificationService) {
this.notificationService = notificationService;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
/**
- * Implementation of {@link RpcServiceHandler}
+ * Implementation of {@link RpcServiceHandler}.
*
*/
public class RpcServiceHandler implements Handler<DOMRpcService> {
import org.slf4j.LoggerFactory;
/**
- * Implementation of {@link SchemaContextHandler}
+ * Implementation of {@link SchemaContextHandler}.
*
*/
public class SchemaContextHandler implements SchemaContextListenerHandler {
private int moduleSetId;
/**
- * Set module-set-id on initial value - 0
+ * Set module-set-id on initial value - 0.
*
- * @param transactionChainHandler
+ * @param transactionChainHandler Transaction chain handler
*/
public SchemaContextHandler(final TransactionChainHandler transactionChainHandler) {
this.transactionChainHandler = transactionChainHandler;
/**
- * Implementation of {@link TransactionChainHandler}
+ * Implementation of {@link TransactionChainHandler}.
*
*/
public class TransactionChainHandler implements Handler<DOMTransactionChain> {
private DOMTransactionChain transactionChain;
/**
- * Prepare transaction chain service for Restconf services
+ * Prepare transaction chain service for Restconf services.
*
- * @param transactionChain
+ * @param transactionChain Transaction chain
*/
public TransactionChainHandler(final DOMTransactionChain transactionChain) {
Preconditions.checkNotNull(transactionChain);
@Provider
@Consumes({ Rfc8040.MediaTypes.DATA + RestconfConstants.JSON, MediaType.APPLICATION_JSON })
-public class JsonNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsProvider implements MessageBodyReader<NormalizedNodeContext> {
+public class JsonNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsProvider
+ implements MessageBodyReader<NormalizedNodeContext> {
- private final static Logger LOG = LoggerFactory.getLogger(JsonNormalizedNodeBodyReader.class);
+ private static final Logger LOG = LoggerFactory.getLogger(JsonNormalizedNodeBodyReader.class);
@Override
public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
return true;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType,
}
}
- private static void propagateExceptionAs(final Exception e) throws RestconfDocumentedException {
- if(e instanceof RestconfDocumentedException) {
- throw (RestconfDocumentedException)e;
- }
-
- if(e instanceof ResultAlreadySetException) {
- LOG.debug("Error parsing json input:", e);
-
- throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. " +
- "Are you creating multiple resources/subresources in POST request?");
- }
-
- LOG.debug("Error parsing json input", e);
-
- throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
- ErrorTag.MALFORMED_MESSAGE, e);
- }
-
- private static NormalizedNodeContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream,
- final boolean isPost) throws IOException {
+ private static NormalizedNodeContext readFrom(
+ final InstanceIdentifierContext<?> path, final InputStream entityStream, final boolean isPost)
+ throws IOException {
if (entityStream.available() < 1) {
return new NormalizedNodeContext(path, null);
}
final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
final SchemaNode parentSchema;
- if(isPost) {
+ if (isPost) {
parentSchema = path.getSchemaNode();
- } else if(path.getSchemaNode() instanceof SchemaContext) {
+ } else if (path.getSchemaNode() instanceof SchemaContext) {
parentSchema = path.getSchemaContext();
} else {
if (SchemaPath.ROOT.equals(path.getSchemaNode().getPath().getParent())) {
parentSchema = path.getSchemaContext();
} else {
- parentSchema = SchemaContextUtil.findDataSchemaNode(path.getSchemaContext(), path.getSchemaNode().getPath().getParent());
+ parentSchema = SchemaContextUtil
+ .findDataSchemaNode(path.getSchemaContext(), path.getSchemaNode().getPath().getParent());
}
}
return new NormalizedNodeContext(newIIContext, result);
}
+ private static void propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
+ if (exception instanceof RestconfDocumentedException) {
+ throw (RestconfDocumentedException)exception;
+ }
+
+ if (exception instanceof ResultAlreadySetException) {
+ LOG.debug("Error parsing json input:", exception);
+
+ throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. "
+ + "Are you creating multiple resources/subresources in POST request?");
+ }
+
+ LOG.debug("Error parsing json input", exception);
+
+ throw new RestconfDocumentedException("Error parsing input: " + exception.getMessage(), ErrorType.PROTOCOL,
+ ErrorTag.MALFORMED_MESSAGE, exception);
+ }
+
public void injectParams(final UriInfo uriInfo, final Request request) {
setUriInfo(uriInfo);
setRequest(request);
package org.opendaylight.restconf.jersey.providers;
-import static org.opendaylight.netconf.sal.restconf.impl.PATCHEditOperation.isPatchOperationWithValue;
+import static org.opendaylight.netconf.sal.restconf.impl.PatchEditOperation.isPatchOperationWithValue;
import com.google.common.collect.ImmutableList;
import com.google.gson.stream.JsonReader;
import javax.ws.rs.ext.Provider;
import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHEntity;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchEntity;
import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
@Provider
@Consumes({Rfc8040.MediaTypes.PATCH + RestconfConstants.JSON})
-public class JsonToPATCHBodyReader extends AbstractIdentifierAwareJaxRsProvider
- implements MessageBodyReader<PATCHContext> {
+public class JsonToPatchBodyReader extends AbstractIdentifierAwareJaxRsProvider
+ implements MessageBodyReader<PatchContext> {
- private final static Logger LOG = LoggerFactory.getLogger(JsonToPATCHBodyReader.class);
+ private static final Logger LOG = LoggerFactory.getLogger(JsonToPatchBodyReader.class);
private String patchId;
@Override
return true;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
- public PATCHContext readFrom(final Class<PATCHContext> type, final Type genericType,
+ public PatchContext readFrom(final Class<PatchContext> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType,
final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
throws IOException, WebApplicationException {
}
}
- private static RuntimeException propagateExceptionAs(final Exception e) throws RestconfDocumentedException {
- if (e instanceof RestconfDocumentedException) {
- throw (RestconfDocumentedException)e;
+ private PatchContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream)
+ throws IOException {
+ if (entityStream.available() < 1) {
+ return new PatchContext(path, null, null);
}
- if (e instanceof ResultAlreadySetException) {
- LOG.debug("Error parsing json input:", e);
- throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. ");
- }
+ final JsonReader jsonReader = new JsonReader(new InputStreamReader(entityStream));
+ final List<PatchEntity> resultList = read(jsonReader, path);
+ jsonReader.close();
- throw new RestconfDocumentedException("Error parsing json input: " + e.getMessage(), ErrorType.PROTOCOL,
- ErrorTag.MALFORMED_MESSAGE, e);
+ return new PatchContext(path, resultList, patchId);
}
- public PATCHContext readFrom(final String uriPath, final InputStream entityStream) throws
+ @SuppressWarnings("checkstyle:IllegalCatch")
+ public PatchContext readFrom(final String uriPath, final InputStream entityStream) throws
RestconfDocumentedException {
try {
return readFrom(ControllerContext.getInstance().toInstanceIdentifier(uriPath), entityStream);
}
}
- private PATCHContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream)
- throws IOException {
- if (entityStream.available() < 1) {
- return new PATCHContext(path, null, null);
+ private static RuntimeException propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
+ if (exception instanceof RestconfDocumentedException) {
+ throw (RestconfDocumentedException)exception;
}
- final JsonReader jsonReader = new JsonReader(new InputStreamReader(entityStream));
- final List<PATCHEntity> resultList = read(jsonReader, path);
- jsonReader.close();
+ if (exception instanceof ResultAlreadySetException) {
+ LOG.debug("Error parsing json input:", exception);
+ throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. ");
+ }
- return new PATCHContext(path, resultList, patchId);
+ throw new RestconfDocumentedException("Error parsing json input: " + exception.getMessage(), ErrorType.PROTOCOL,
+ ErrorTag.MALFORMED_MESSAGE, exception);
}
- private List<PATCHEntity> read(final JsonReader in, final InstanceIdentifierContext path) throws IOException {
- final List<PATCHEntity> resultCollection = new ArrayList<>();
+ private List<PatchEntity> read(final JsonReader in, final InstanceIdentifierContext path) throws IOException {
+ final List<PatchEntity> resultCollection = new ArrayList<>();
final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
path.getSchemaContext());
- final JsonToPATCHBodyReader.PatchEdit edit = new JsonToPATCHBodyReader.PatchEdit();
+ final JsonToPatchBodyReader.PatchEdit edit = new JsonToPatchBodyReader.PatchEdit();
while (in.hasNext()) {
switch (in.peek()) {
}
/**
- * Switch value of parsed JsonToken.NAME and read edit definition or patch id
+ * Switch value of parsed JsonToken.NAME and read edit definition or patch id.
+ *
* @param name value of token
* @param edit PatchEdit instance
* @param in JsonReader reader
* @param path InstanceIdentifierContext context
* @param codec Draft11StringModuleInstanceIdentifierCodec codec
* @param resultCollection collection of parsed edits
- * @throws IOException
+ * @throws IOException if operation fails
*/
private void parseByName(@Nonnull final String name, @Nonnull final PatchEdit edit,
@Nonnull final JsonReader in, @Nonnull final InstanceIdentifierContext path,
@Nonnull final StringModuleInstanceIdentifierCodec codec,
- @Nonnull final List<PATCHEntity> resultCollection) throws IOException {
+ @Nonnull final List<PatchEntity> resultCollection) throws IOException {
switch (name) {
case "edit" :
if (in.peek() == JsonToken.BEGIN_ARRAY) {
}
/**
- * Read one patch edit object from Json input
+ * Read one patch edit object from Json input.
+ *
* @param edit PatchEdit instance to be filled with read data
* @param in JsonReader reader
* @param path InstanceIdentifierContext path context
* @param codec Draft11StringModuleInstanceIdentifierCodec codec
- * @throws IOException
+ * @throws IOException if operation fails
*/
private void readEditDefinition(@Nonnull final PatchEdit edit, @Nonnull final JsonReader in,
@Nonnull final InstanceIdentifierContext path,
in.endObject();
// read saved data to normalized node when target schema is already known
- edit.setData(readEditData(new JsonReader(new StringReader(value.toString())), edit.getTargetSchemaNode(), path));
+ edit.setData(
+ readEditData(new JsonReader(new StringReader(value.toString())), edit.getTargetSchemaNode(), path));
}
/**
- * Parse data defined in value node and saves it to buffer
+ * Parse data defined in value node and saves it to buffer.
* @param value Buffer to read value node
* @param in JsonReader reader
- * @throws IOException
+ * @throws IOException if operation fails
*/
private void readValueNode(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
in.beginObject();
}
/**
- * Parse one value object of data and saves it to buffer
+ * Parse one value object of data and saves it to buffer.
* @param value Buffer to read value object
* @param in JsonReader reader
- * @throws IOException
+ * @throws IOException if operation fails
*/
private void readValueObject(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
// read simple leaf value
}
/**
- * Read patch edit data defined in value node to NormalizedNode
+ * Read patch edit data defined in value node to NormalizedNode.
* @param in reader JsonReader reader
* @return NormalizedNode representing data
*/
}
/**
- * Prepare PATCHEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception
+ * Prepare PatchEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception.
* @param edit Instance of PatchEdit
- * @return PATCHEntity
+ * @return PatchEntity Patch entity
*/
- private static PATCHEntity prepareEditOperation(@Nonnull final PatchEdit edit) {
+ private static PatchEntity prepareEditOperation(@Nonnull final PatchEdit edit) {
if (edit.getOperation() != null && edit.getTargetSchemaNode() != null
&& checkDataPresence(edit.getOperation(), edit.getData() != null)) {
if (isPatchOperationWithValue(edit.getOperation())) {
targetNode = edit.getTarget();
}
- return new PATCHEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
+ return new PatchEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
} else {
- return new PATCHEntity(edit.getId(), edit.getOperation(), edit.getTarget());
+ return new PatchEntity(edit.getId(), edit.getOperation(), edit.getTarget());
}
}
}
/**
- * Check if data is present when operation requires it and not present when operation data is not allowed
+ * Check if data is present when operation requires it and not present when operation data is not allowed.
* @param operation Name of operation
* @param hasData Data in edit are present/not present
* @return true if data is present when operation requires it or if there are no data when operation does not
- * allow it, false otherwise
+ * allow it, false otherwise
*/
private static boolean checkDataPresence(@Nonnull final String operation, final boolean hasData) {
if (isPatchOperationWithValue(operation)) {
}
/**
- * Helper class representing one patch edit
+ * Helper class representing one patch edit.
*/
private static final class PatchEdit {
private String id;
}
@Override
- public long getSize(final NormalizedNodeContext t,
+ public long getSize(final NormalizedNodeContext context,
final Class<?> type,
final Type genericType,
final Annotation[] annotations,
}
@Override
- public void writeTo(final NormalizedNodeContext t,
+ public void writeTo(final NormalizedNodeContext context,
final Class<?> type,
final Type genericType,
final Annotation[] annotations,
final MediaType mediaType,
final MultivaluedMap<String, Object> httpHeaders,
final OutputStream entityStream) throws IOException, WebApplicationException {
- final NormalizedNode<?, ?> data = t.getData();
+ final NormalizedNode<?, ?> data = context.getData();
if (data == null) {
return;
}
@SuppressWarnings("unchecked")
- final InstanceIdentifierContext<SchemaNode> context =
- (InstanceIdentifierContext<SchemaNode>) t.getInstanceIdentifierContext();
- final SchemaPath path = context.getSchemaNode().getPath();
+ final InstanceIdentifierContext<SchemaNode> identifierCtx =
+ (InstanceIdentifierContext<SchemaNode>) context.getInstanceIdentifierContext();
+ final SchemaPath path = identifierCtx.getSchemaNode().getPath();
final JsonWriter jsonWriter = createJsonWriter(entityStream,
- t.getWriterParameters().isPrettyPrint());
+ context.getWriterParameters().isPrettyPrint());
jsonWriter.beginObject();
- writeNormalizedNode(jsonWriter, path, context, data,
- t.getWriterParameters().getDepth(), t.getWriterParameters().getFields());
+ writeNormalizedNode(jsonWriter, path, identifierCtx, data,
+ context.getWriterParameters().getDepth(), context.getWriterParameters().getFields());
jsonWriter.endObject();
jsonWriter.flush();
}
}
private static void writeChildren(final RestconfNormalizedNodeWriter nnWriter,
- final ContainerNode data) throws IOException {
+ final ContainerNode data) throws IOException {
for (final DataContainerChild<? extends PathArgument, ?> child : data.getValue()) {
nnWriter.write(child);
}
}
@Override
- public long getSize(final NormalizedNodeContext t,
+ public long getSize(final NormalizedNodeContext context,
final Class<?> type,
final Type genericType,
final Annotation[] annotations,
}
@Override
- public void writeTo(final NormalizedNodeContext t,
+ public void writeTo(final NormalizedNodeContext context,
final Class<?> type,
final Type genericType,
final Annotation[] annotations,
final MediaType mediaType,
final MultivaluedMap<String, Object> httpHeaders,
final OutputStream entityStream) throws IOException, WebApplicationException {
- final InstanceIdentifierContext<?> pathContext = t.getInstanceIdentifierContext();
- if (t.getData() == null) {
+ final InstanceIdentifierContext<?> pathContext = context.getInstanceIdentifierContext();
+ if (context.getData() == null) {
return;
}
XMLStreamWriter xmlWriter;
try {
xmlWriter = XML_FACTORY.createXMLStreamWriter(entityStream, StandardCharsets.UTF_8.name());
- if (t.getWriterParameters().isPrettyPrint()) {
+ if (context.getWriterParameters().isPrettyPrint()) {
xmlWriter = new IndentingXMLStreamWriter(xmlWriter);
}
} catch (final XMLStreamException | FactoryConfigurationError e) {
throw new IllegalStateException(e);
}
- final NormalizedNode<?, ?> data = t.getData();
+ final NormalizedNode<?, ?> data = context.getData();
final SchemaPath schemaPath = pathContext.getSchemaNode().getPath();
- writeNormalizedNode(xmlWriter, schemaPath, pathContext, data, t.getWriterParameters().getDepth(),
- t.getWriterParameters().getFields());
+ writeNormalizedNode(xmlWriter, schemaPath, pathContext, data, context.getWriterParameters().getDepth(),
+ context.getWriterParameters().getFields());
}
private static void writeNormalizedNode(final XMLStreamWriter xmlWriter,
* events to the encapsulated {@link NormalizedNodeStreamWriter}.
*
* @param node Node
- * @return
+ * @return {@code ParameterAwareNormalizedNodeWriter}
* @throws IOException when thrown from the backing writer.
*/
public final ParameterAwareNormalizedNodeWriter write(final NormalizedNode<?, ?> node) throws IOException {
processedAsCompositeNode = true;
}
}
- }
- else if (node instanceof MapEntryNode) {
+ } else if (node instanceof MapEntryNode) {
processedAsCompositeNode = writeMapEntryNode((MapEntryNode) node);
- }
- else if (node instanceof UnkeyedListEntryNode) {
+ } else if (node instanceof UnkeyedListEntryNode) {
final UnkeyedListEntryNode n = (UnkeyedListEntryNode) node;
writer.startUnkeyedListItem(n.getIdentifier(), childSizeHint(n.getValue()));
currentDepth++;
processedAsCompositeNode = writeChildren(n.getValue(), false);
currentDepth--;
- }
- else if (node instanceof ChoiceNode) {
+ } else if (node instanceof ChoiceNode) {
final ChoiceNode n = (ChoiceNode) node;
writer.startChoiceNode(n.getIdentifier(), childSizeHint(n.getValue()));
processedAsCompositeNode = writeChildren(n.getValue(), true);
- }
- else if (node instanceof AugmentationNode) {
+ } else if (node instanceof AugmentationNode) {
final AugmentationNode n = (AugmentationNode) node;
writer.startAugmentationNode(n.getIdentifier());
processedAsCompositeNode = writeChildren(n.getValue(), true);
- }
- else if (node instanceof UnkeyedListNode) {
+ } else if (node instanceof UnkeyedListNode) {
final UnkeyedListNode n = (UnkeyedListNode) node;
writer.startUnkeyedList(n.getIdentifier(), childSizeHint(n.getValue()));
processedAsCompositeNode = writeChildren(n.getValue(), false);
- }
- else if (node instanceof OrderedMapNode) {
+ } else if (node instanceof OrderedMapNode) {
final OrderedMapNode n = (OrderedMapNode) node;
writer.startOrderedMapNode(n.getIdentifier(), childSizeHint(n.getValue()));
processedAsCompositeNode = writeChildren(n.getValue(), true);
- }
- else if (node instanceof MapNode) {
+ } else if (node instanceof MapNode) {
final MapNode n = (MapNode) node;
writer.startMapNode(n.getIdentifier(), childSizeHint(n.getValue()));
processedAsCompositeNode = writeChildren(n.getValue(), true);
- }
- else if (node instanceof LeafSetNode) {
+ } else if (node instanceof LeafSetNode) {
final LeafSetNode<?> n = (LeafSetNode<?>) node;
if (node instanceof OrderedLeafSetNode) {
writer.startOrderedLeafSet(n.getIdentifier(), childSizeHint(n.getValue()));
currentDepth++;
// Write all the rest
- final boolean result = writeChildren(Iterables.filter(node.getValue(), new Predicate<NormalizedNode<?, ?>>() {
- @Override
- public boolean apply(final NormalizedNode<?, ?> input) {
- if (input instanceof AugmentationNode) {
- return true;
- }
- if (!qnames.contains(input.getNodeType())) {
- return true;
- }
-
- LOG.debug("Skipping key child {}", input);
- return false;
- }
- }), false);
+ final boolean result =
+ writeChildren(Iterables.filter(node.getValue(), new Predicate<NormalizedNode<?, ?>>() {
+ @Override
+ public boolean apply(final NormalizedNode<?, ?> input) {
+ if (input instanceof AugmentationNode) {
+ return true;
+ }
+ if (!qnames.contains(input.getNodeType())) {
+ return true;
+ }
+
+ LOG.debug("Skipping key child {}", input);
+ return false;
+ }
+ }), false);
currentDepth--;
return result;
}
@Provider
@Consumes({ Rfc8040.MediaTypes.DATA + RestconfConstants.XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML })
-public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsProvider implements MessageBodyReader<NormalizedNodeContext> {
+public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsProvider
+ implements MessageBodyReader<NormalizedNodeContext> {
- private final static Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
+ private static final Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
@Override
public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
return true;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType,
final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
return parse(path,doc);
- } catch (final RestconfDocumentedException e){
+ } catch (final RestconfDocumentedException e) {
throw e;
} catch (final Exception e) {
LOG.debug("Error parsing xml input", e);
final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
InstanceIdentifierContext<? extends SchemaNode> outIIContext;
-
final DomToNormalizedNodeParserFactory parserFactory =
DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER,
pathContext.getSchemaContext());
if (schemaNode instanceof ContainerSchemaNode) {
parsed = parserFactory.getContainerNodeParser().parse(Collections.singletonList(doc.getDocumentElement()),
(ContainerSchemaNode) schemaNode);
- } else if(schemaNode instanceof ListSchemaNode) {
+ } else if (schemaNode instanceof ListSchemaNode) {
final ListSchemaNode casted = (ListSchemaNode) schemaNode;
parsed = parserFactory.getMapEntryNodeParser().parse(elements, casted);
if (isPost()) {
return result;
}
- private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent, final DataSchemaNode child) {
+ private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent,
+ final DataSchemaNode child) {
if ((parent instanceof AugmentationTarget) && !(parent instanceof ChoiceSchemaNode)) {
for (final AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHEditOperation;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHEntity;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchEditOperation;
+import org.opendaylight.netconf.sal.restconf.impl.PatchEntity;
import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
@Provider
@Consumes({Rfc8040.MediaTypes.PATCH + RestconfConstants.XML})
-public class XmlToPATCHBodyReader extends AbstractIdentifierAwareJaxRsProvider implements
- MessageBodyReader<PATCHContext> {
+public class XmlToPatchBodyReader extends AbstractIdentifierAwareJaxRsProvider implements
+ MessageBodyReader<PatchContext> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(XmlToPatchBodyReader.class);
- private final static Logger LOG = LoggerFactory.getLogger(XmlToPATCHBodyReader.class);
@Override
public boolean isReadable(final Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType) {
return true;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
- public PATCHContext readFrom(final Class<PATCHContext> type, final Type genericType,
+ public PatchContext readFrom(final Class<PatchContext> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType,
final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
throws IOException, WebApplicationException {
if (entityStream.available() < 1) {
// represent empty nopayload input
- return new PATCHContext(path, null, null);
+ return new PatchContext(path, null, null);
}
final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
}
}
- private static PATCHContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc) {
- final List<PATCHEntity> resultCollection = new ArrayList<>();
+ private static PatchContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc) {
+ final List<PatchEntity> resultCollection = new ArrayList<>();
final String patchId = doc.getElementsByTagName("patch-id").item(0).getFirstChild().getNodeValue();
final NodeList editNodes = doc.getElementsByTagName("edit");
final DomToNormalizedNodeParserFactory parserFactory =
final Element firstValueElement = values != null ? values.get(0) : null;
// get namespace according to schema node from path context or value
- final String namespace = (firstValueElement == null) ?
- schemaNode.getQName().getNamespace().toString() : firstValueElement.getNamespaceURI();
+ final String namespace = (firstValueElement == null)
+ ? schemaNode.getQName().getNamespace().toString() : firstValueElement.getNamespaceURI();
// find module according to namespace
final Module module = pathContext.getSchemaContext().findModuleByNamespace(
throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL,
ErrorTag.MALFORMED_MESSAGE);
} else {
- if (PATCHEditOperation.isPatchOperationWithValue(operation)) {
+ if (PatchEditOperation.isPatchOperationWithValue(operation)) {
NormalizedNode<?, ?> parsed = null;
if (schemaNode instanceof ContainerSchemaNode) {
parsed = parserFactory.getContainerNodeParser().parse(values, (ContainerSchemaNode) schemaNode);
targetII = targetII.getParent();
}
- resultCollection.add(new PATCHEntity(editId, operation, targetII, parsed));
+ resultCollection.add(new PatchEntity(editId, operation, targetII, parsed));
} else {
- resultCollection.add(new PATCHEntity(editId, operation, targetII));
+ resultCollection.add(new PatchEntity(editId, operation, targetII));
}
}
}
- return new PATCHContext(pathContext, ImmutableList.copyOf(resultCollection), patchId);
+ return new PatchContext(pathContext, ImmutableList.copyOf(resultCollection), patchId);
}
/**
- * Read value nodes
+ * Read value nodes.
+ *
* @param element Element of current edit operation
* @param operation Name of current operation
* @return List of value elements
private static List<Element> readValueNodes(@Nonnull final Element element, @Nonnull final String operation) {
final Node valueNode = element.getElementsByTagName("value").item(0);
- if (PATCHEditOperation.isPatchOperationWithValue(operation) && valueNode == null) {
+ if (PatchEditOperation.isPatchOperationWithValue(operation) && valueNode == null) {
throw new RestconfDocumentedException("Error parsing input",
ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
}
- if (!PATCHEditOperation.isPatchOperationWithValue(operation) && valueNode != null) {
+ if (!PatchEditOperation.isPatchOperationWithValue(operation) && valueNode != null) {
throw new RestconfDocumentedException("Error parsing input",
ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
}
}
/**
- * Prepare non-conditional XPath suitable for deserialization
- * with {@link StringModuleInstanceIdentifierCodec}
+ * Prepare non-conditional XPath suitable for deserialization with {@link StringModuleInstanceIdentifierCodec}.
+ *
* @param schemaNode Top schema node
* @param target Edit operation target
* @param value Element with value
}
/**
- * Read value for every list key
+ * Read value for every list key.
+ *
* @param value Value element
* @param keys Iterator of list keys names
* @return Iterator of list keys values
}
/**
- * Append key name - key value pairs for every list key to {@code nonCondXpath}
+ * Append key name - key value pairs for every list key to {@code nonCondXpath}.
+ *
* @param nonCondXpath Builder for creating non-conditional XPath
* @param keyNames Iterator of list keys names
* @param keyValues Iterator of list keys values
* parsing from data by {@link SchemaContext}.
*
* @param schemaContext
- * - for validate of parsing path arguments
+ * for validate of parsing path arguments
* @param data
- * - path to data
+ * path to data
* @return {@link Iterable} of {@link PathArgument}
*/
public static Iterable<PathArgument> create(final SchemaContext schemaContext, final String data) {
"Identifier must start with character from set 'a-zA-Z_'", variables.getData(), variables.getOffset());
final String preparedPrefix = nextIdentifierFromNextSequence(
ParserBuilderConstants.Deserializer.IDENTIFIER, variables);
- final String prefix, localName;
+ final String prefix;
+ final String localName;
if (allCharsConsumed(variables)) {
return getQNameOfDataSchemaNode(preparedPrefix, variables);
variables.getOffset());
localName = nextIdentifierFromNextSequence(ParserBuilderConstants.Deserializer.IDENTIFIER, variables);
- if (!allCharsConsumed(variables) && (currentChar
- (variables.getOffset(), variables.getData()) == ParserBuilderConstants.Deserializer.EQUAL)) {
+ if (!allCharsConsumed(variables) && (currentChar(
+ variables.getOffset(), variables.getData()) == ParserBuilderConstants.Deserializer.EQUAL)) {
return getQNameOfDataSchemaNode(localName, variables);
} else {
final Module module = moduleForPrefix(prefix, variables.getSchemaContext());
return variables.getOffset() == variables.getData().length();
}
- private final static class MainVarsWrapper {
+ private static final class MainVarsWrapper {
private static final int STARTING_OFFSET = 0;
private final SchemaContext schemaContext;
private DataSchemaContextNode<?> current;
private int offset;
- public MainVarsWrapper(final String data, final DataSchemaContextNode<?> current, final int offset,
+ MainVarsWrapper(final String data, final DataSchemaContextNode<?> current, final int offset,
final SchemaContext schemaContext) {
this.data = data;
this.current = current;
*/
package org.opendaylight.restconf.parser.builder;
-
import com.google.common.base.Preconditions;
import java.net.URI;
import java.util.Iterator;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
/**
- * Serializer for {@link YangInstanceIdentifier} to {@link String} for restconf
- *
+ * Serializer for {@link YangInstanceIdentifier} to {@link String} for restconf.
*/
public final class YangInstanceIdentifierSerializer {
/**
* Method to create String from {@link Iterable} of {@link PathArgument}
- * which are parsing from data by {@link SchemaContext}
+ * which are parsing from data by {@link SchemaContext}.
*
* @param schemaContext
- * - for validate of parsing path arguments
+ * for validate of parsing path arguments
* @param data
- * - path to data
+ * path to data
* @return {@link String}
*/
public static String create(final SchemaContext schemaContext, final YangInstanceIdentifier data) {
}
/**
- * Encode {@link Serializer#DISABLED_CHARS} chars to percent encoded chars
+ * Encode {@link Serializer#DISABLED_CHARS} chars to percent encoded chars.
*
* @param valueOf
- * - string to encode
+ * string to encode
* @return encoded {@link String}
*/
private static String parsePercentEncodeChars(final String valueOf) {
}
/**
- * Add {@link QName} to the serialized string
+ * Add {@link QName} to the serialized string.
*
* @param path
- * - {@link StringBuilder}
+ * {@link StringBuilder}
* @param qname
- * - {@link QName} node
+ * {@link QName} node
* @return {@link StringBuilder}
*/
- private final static StringBuilder appendQName(final StringBuilder path, final QName qname) {
+ private static StringBuilder appendQName(final StringBuilder path, final QName qname) {
path.append(qname.getLocalName());
return path;
}
/**
- * Create prefix of namespace from {@link QName}
+ * Create prefix of namespace from {@link QName}.
*
* @param qname
- * - {@link QName}
+ * {@link QName}
* @return {@link String}
*/
private static String prefixForNamespace(final QName qname, final SchemaContext schemaContext) {
private DataSchemaContextNode<?> current;
- public MainVarsWrapper(final DataSchemaContextNode<?> current) {
+ MainVarsWrapper(final DataSchemaContextNode<?> current) {
this.setCurrent(current);
}
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
-import org.opendaylight.netconf.sal.rest.impl.PATCH;
+import org.opendaylight.netconf.sal.rest.impl.Patch;
import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchStatusContext;
import org.opendaylight.restconf.Rfc8040;
import org.opendaylight.restconf.utils.RestconfConstants;
/**
* The "{+restconf}/data" subtree represents the datastore resource type, which
- * is a collection of configuration data and state data nodes
+ * is a collection of configuration data and state data nodes.
*
*/
public interface RestconfDataService {
* Get target data resource.
*
* @param identifier
- * - path to target
+ * path to target
* @param uriInfo
- * - URI info
+ * URI info
* @return {@link NormalizedNodeContext}
*/
@GET
* Get target data resource from data root.
*
* @param uriInfo
- * - URI info
+ * URI info
* @return {@link NormalizedNodeContext}
*/
@GET
* Create or replace the target data resource.
*
* @param identifier
- * - path to target
+ * path to target
* @param payload
- * - data node for put to config DS
+ * data node for put to config DS
* @return {@link Response}
*/
@PUT
* Create a data resource in target.
*
* @param identifier
- * - path to target
+ * path to target
* @param payload
- * - new data
+ * new data
* @param uriInfo
- * - URI info
+ * URI info
* @return {@link Response}
*/
@POST
* Create a data resource.
*
* @param payload
- * - new data
+ * new data
* @param uriInfo
- * - URI info
+ * URI info
* @return {@link Response}
*/
@POST
* Delete the target data resource.
*
* @param identifier
- * - path to target
+ * path to target
* @return {@link Response}
*/
@DELETE
* server.
*
* @param identifier
- * - path to target
+ * path to target
* @param context
- * - edits
+ * edits
* @param uriInfo
- * - URI info
- * @return {@link PATCHStatusContext}
+ * URI info
+ * @return {@link PatchStatusContext}
*/
- @PATCH
+ @Patch
@Path("/data/{identifier:.+}")
@Consumes({ Rfc8040.MediaTypes.PATCH + RestconfConstants.JSON, Rfc8040.MediaTypes.PATCH + RestconfConstants.XML })
@Produces({ Rfc8040.MediaTypes.PATCH_STATUS + RestconfConstants.JSON,
Rfc8040.MediaTypes.PATCH_STATUS + RestconfConstants.XML })
- PATCHStatusContext patchData(@Encoded @PathParam("identifier") String identifier, PATCHContext context,
- @Context UriInfo uriInfo);
+ PatchStatusContext patchData(@Encoded @PathParam("identifier") String identifier, PatchContext context,
+ @Context UriInfo uriInfo);
/**
* Ordered list of edits that are applied to the datastore by the server.
*
* @param context
- * - edits
+ * edits
* @param uriInfo
- * - URI info
- * @return {@link PATCHStatusContext}
+ * URI info
+ * @return {@link PatchStatusContext}
*/
- @PATCH
+ @Patch
@Path("/data")
@Consumes({ Rfc8040.MediaTypes.PATCH + RestconfConstants.JSON, Rfc8040.MediaTypes.PATCH + RestconfConstants.XML })
@Produces({ Rfc8040.MediaTypes.PATCH_STATUS + RestconfConstants.JSON,
Rfc8040.MediaTypes.PATCH_STATUS + RestconfConstants.XML })
- PATCHStatusContext patchData(PATCHContext context, @Context UriInfo uriInfo);
+ PatchStatusContext patchData(PatchContext context, @Context UriInfo uriInfo);
}
public interface RestconfInvokeOperationsService {
/**
- * Invoke RPC operation
+ * Invoke RPC operation.
*
* @param identifier
- * - module name and rpc identifier string for the desired
+ * module name and rpc identifier string for the desired
* operation
* @param payload
- * - {@link NormalizedNodeContext} - the body of the operation
+ * {@link NormalizedNodeContext} - the body of the operation
* @param uriInfo
- * - URI info
+ * URI info
* @return {@link NormalizedNodeContext}
*/
@POST
import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
/**
- * Subscribing to streams
+ * Subscribing to streams.
*
*/
public interface RestconfStreamsSubscriptionService {
/**
- * Subscribing to receive notification from stream support
+ * Subscribing to receive notification from stream support.
*
* @param identifier
- * - name of stream
+ * name of stream
* @param uriInfo
- * - URI info
+ * URI info
* @return {@link NormalizedNodeContext}
*/
@GET
package org.opendaylight.restconf.restful.services.api;
/**
- * Wrapper for all transaction services:
+ * Wrapper for all transaction services.
* <ul>
* <li>{@link RestconfDataService}
* <li>{@link RestconfInvokeOperationsService}
import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchStatusContext;
import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
import org.opendaylight.netconf.sal.restconf.impl.WriterParameters;
import org.slf4j.LoggerFactory;
/**
- * Implementation of {@link RestconfDataService}
+ * Implementation of {@link RestconfDataService}.
*/
public class RestconfDataServiceImpl implements RestconfDataService {
final InstanceIdentifierContext<?> instanceIdentifier = ParserIdentifier.toInstanceIdentifier(
identifier, schemaContextRef.get(), Optional.of(this.mountPointServiceHandler.get()));
- boolean withDefa_used = false;
+ boolean withDefaUsed = false;
String withDefa = null;
for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
switch (entry.getKey()) {
case "with-defaults":
- if (!withDefa_used) {
- withDefa_used = true;
+ if (!withDefaUsed) {
+ withDefaUsed = true;
withDefa = entry.getValue().iterator().next();
} else {
throw new RestconfDocumentedException("With-defaults parameter can be used only once.");
}
break;
+ default:
+ LOG.info("Unknown key : {}.", entry.getKey());
+ break;
}
}
boolean tagged = false;
- if (withDefa_used) {
+ if (withDefaUsed) {
if ("report-all-tagged".equals(withDefa)) {
tagged = true;
withDefa = null;
public Response putData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
Preconditions.checkNotNull(payload);
- boolean insert_used = false;
- boolean point_used = false;
+ boolean insertUsed = false;
+ boolean pointUsed = false;
String insert = null;
String point = null;
for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
switch (entry.getKey()) {
case "insert":
- if (!insert_used) {
- insert_used = true;
+ if (!insertUsed) {
+ insertUsed = true;
insert = entry.getValue().iterator().next();
} else {
throw new RestconfDocumentedException("Insert parameter can be used only once.");
}
break;
case "point":
- if (!point_used) {
- point_used = true;
+ if (!pointUsed) {
+ pointUsed = true;
point = entry.getValue().iterator().next();
} else {
throw new RestconfDocumentedException("Point parameter can be used only once.");
}
}
- checkQueryParams(insert_used, point_used, insert);
+ checkQueryParams(insertUsed, pointUsed, insert);
final InstanceIdentifierContext<? extends SchemaNode> iid = payload
.getInstanceIdentifierContext();
return PutDataTransactionUtil.putData(payload, ref, transactionNode, insert, point);
}
- private static void checkQueryParams(final boolean insert_used, final boolean point_used, final String insert) {
- if (point_used && !insert_used) {
+ private static void checkQueryParams(final boolean insertUsed, final boolean pointUsed, final String insert) {
+ if (pointUsed && !insertUsed) {
throw new RestconfDocumentedException("Point parameter can't be used without Insert parameter.");
}
- if (point_used && (insert.equals("first") || insert.equals("last"))) {
+ if (pointUsed && (insert.equals("first") || insert.equals("last"))) {
throw new RestconfDocumentedException(
"Point parameter can be used only with 'after' or 'before' values of Insert parameter.");
}
public Response postData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
Preconditions.checkNotNull(payload);
- boolean insert_used = false;
- boolean point_used = false;
+ boolean insertUsed = false;
+ boolean pointUsed = false;
String insert = null;
String point = null;
for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
switch (entry.getKey()) {
case "insert":
- if (!insert_used) {
- insert_used = true;
+ if (!insertUsed) {
+ insertUsed = true;
insert = entry.getValue().iterator().next();
} else {
throw new RestconfDocumentedException("Insert parameter can be used only once.");
}
break;
case "point":
- if (!point_used) {
- point_used = true;
+ if (!pointUsed) {
+ pointUsed = true;
point = entry.getValue().iterator().next();
} else {
throw new RestconfDocumentedException("Point parameter can be used only once.");
}
}
- checkQueryParams(insert_used, point_used, insert);
+ checkQueryParams(insertUsed, pointUsed, insert);
final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
final DOMTransactionChain transactionChain;
}
@Override
- public PATCHStatusContext patchData(final String identifier, final PATCHContext context, final UriInfo uriInfo) {
+ public PatchStatusContext patchData(final String identifier, final PatchContext context, final UriInfo uriInfo) {
return patchData(context, uriInfo);
}
@Override
- public PATCHStatusContext patchData(final PATCHContext context, final UriInfo uriInfo) {
+ public PatchStatusContext patchData(final PatchContext context, final UriInfo uriInfo) {
Preconditions.checkNotNull(context);
final DOMMountPoint mountPoint = context.getInstanceIdentifierContext().getMountPoint();
}
/**
- * Prepare transaction chain to access data of mount point
+ * Prepare transaction chain to access data of mount point.
* @param mountPoint
- * - mount point reference
+ * mount point reference
* @return {@link DOMTransactionChain}
*/
private static DOMTransactionChain transactionChainOfMountPoint(@Nonnull final DOMMountPoint mountPoint) {
final Optional<DOMDataBroker> domDataBrokerService = mountPoint.getService(DOMDataBroker.class);
if (domDataBrokerService.isPresent()) {
- return domDataBrokerService.get().createTransactionChain(RestConnectorProvider.transactionListener);
+ return domDataBrokerService.get().createTransactionChain(RestConnectorProvider.TRANSACTION_CHAIN_LISTENER);
}
final String errMsg = "DOM data broker service isn't available for mount point " + mountPoint.getIdentifier();
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
/**
- * Implementation of {@link RestconfInvokeOperationsService}
+ * Implementation of {@link RestconfInvokeOperationsService}.
*
*/
public class RestconfInvokeOperationsServiceImpl implements RestconfInvokeOperationsService {
}
@Override
- public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
+ public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
+ final UriInfo uriInfo) {
final SchemaContextRef refSchemaCtx = new SchemaContextRef(this.schemaContextHandler.get());
final SchemaPath schemaPath = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
import org.slf4j.LoggerFactory;
/**
- * Implementation of {@link RestconfStreamsSubscriptionService}
+ * Implementation of {@link RestconfStreamsSubscriptionService}.
*
*/
public class RestconfStreamsSubscriptionServiceImpl implements RestconfStreamsSubscriptionService {
* Initialize holder of handlers with holders as parameters.
*
* @param domDataBrokerHandler
- * - handler of {@link DOMDataBroker}
+ * handler of {@link DOMDataBroker}
* @param notificationServiceHandler
- * - handler of {@link DOMNotificationService}
+ * handler of {@link DOMNotificationService}
* @param schemaHandler
- * - handler of {@link SchemaContext}
+ * handler of {@link SchemaContext}
* @param transactionChainHandler
- * - handler of {@link DOMTransactionChain}
+ * handler of {@link DOMTransactionChain}
*/
public RestconfStreamsSubscriptionServiceImpl(final DOMDataBrokerHandler domDataBrokerHandler,
final NotificationServiceHandler notificationServiceHandler, final SchemaContextHandler schemaHandler,
}
/**
- * Holder of all handlers for notifications
+ * Holder of all handlers for notifications.
*/
public final class HandlersHolder {
}
/**
- * Get {@link DOMDataBrokerHandler}
+ * Get {@link DOMDataBrokerHandler}.
*
* @return the domDataBrokerHandler
*/
}
/**
- * Get {@link NotificationServiceHandler}
+ * Get {@link NotificationServiceHandler}.
*
* @return the notificationServiceHandler
*/
}
/**
- * Get {@link TransactionChainHandler}
+ * Get {@link TransactionChainHandler}.
*
* @return the transactionChainHandler
*/
}
/**
- * Get {@link SchemaContextHandler}
+ * Get {@link SchemaContextHandler}.
*
* @return the schemaHandler
*/
}
/**
- * Parser and holder of query paramteres from uriInfo for notifications
+ * Parser and holder of query paramteres from uriInfo for notifications.
*
*/
public static final class NotificationQueryParams {
static NotificationQueryParams fromUriInfo(final UriInfo uriInfo) {
Instant start = null;
- boolean startTime_used = false;
+ boolean startTimeUsed = false;
Instant stop = null;
- boolean stopTime_used = false;
+ boolean stopTimeUsed = false;
String filter = null;
- boolean filter_used = false;
+ boolean filterUsed = false;
for (final Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
switch (entry.getKey()) {
case "start-time":
- if (!startTime_used) {
- startTime_used = true;
+ if (!startTimeUsed) {
+ startTimeUsed = true;
start = SubscribeToStreamUtil.parseDateFromQueryParam(entry);
} else {
throw new RestconfDocumentedException("Start-time parameter can be used only once.");
}
break;
case "stop-time":
- if (!stopTime_used) {
- stopTime_used = true;
+ if (!stopTimeUsed) {
+ stopTimeUsed = true;
stop = SubscribeToStreamUtil.parseDateFromQueryParam(entry);
} else {
throw new RestconfDocumentedException("Stop-time parameter can be used only once.");
}
break;
case "filter":
- if (!filter_used) {
- filter_used = true;
+ if (!filterUsed) {
+ filterUsed = true;
filter = entry.getValue().iterator().next();
}
break;
"Bad parameter used with notifications: " + entry.getKey());
}
}
- if (!startTime_used && stopTime_used) {
+ if (!startTimeUsed && stopTimeUsed) {
throw new RestconfDocumentedException("Stop-time parameter has to be used with start-time parameter.");
}
}
/**
- * Get start-time query parameter
+ * Get start-time query parameter.
*
* @return start-time
*/
}
/**
- * Get stop-time query parameter
+ * Get stop-time query parameter.
*
* @return stop-time
*/
}
/**
- * Get filter query parameter
+ * Get filter query parameter.
*
* @return filter
*/
* from DS - config + state).
*
* @param instanceIdentifier
- * - {@link InstanceIdentifierContext} of data for transaction
+ * {@link InstanceIdentifierContext} of data for transaction
* @param mountPoint
- * - mount point if is present
+ * mount point if is present
* @param transactionChain
- * - transaction chain for creating specific type of transaction
+ * transaction chain for creating specific type of transaction
* in specific operation
*/
public TransactionVarsWrapper(final InstanceIdentifierContext<?> instanceIdentifier, final DOMMountPoint mountPoint,
}
/**
- * Get instance identifier of data
+ * Get instance identifier of data.
*
* @return {@link InstanceIdentifierContext}
*/
}
/**
- * Get mount point
+ * Get mount point.
*
* @return {@link DOMMountPoint}
*/
* Set {@link LogicalDatastoreType} of data for transaction.
*
* @param configuration
- * - {@link LogicalDatastoreType}
+ * {@link LogicalDatastoreType}
*/
public void setLogicalDatastoreType(final LogicalDatastoreType configuration) {
this.configuration = configuration;
/**
* Get transaction chain for creating specific transaction for specific
- * operation
+ * operation.
*
* @return transaction chain
*/
import org.slf4j.LoggerFactory;
/**
- * Util class for streams
+ * Util class for streams.
*
* <ul>
* <li>create stream
}
/**
- * Create stream with POST operation via RPC
+ * Create stream with POST operation via RPC.
*
* @param payload
- * - input of rpc - example in JSON:
+ * input of rpc - example in JSON:
*
* <pre>
* {@code
* </pre>
*
* @param refSchemaCtx
- * - reference to {@link SchemaContext} -
+ * reference to {@link SchemaContext} -
* {@link SchemaContextRef}
* @return {@link CheckedFuture} with {@link DOMRpcResult} - This mean
* output of RPC - example in JSON:
final QName streamNameQname = QName.create(qname, "stream-name");
final NotificationOutputType outputType = prepareOutputType(data);
- if(outputType.equals(NotificationOutputType.JSON)){
+ if (outputType.equals(NotificationOutputType.JSON)) {
streamName = streamName + "/JSON";
}
}
/**
+ * Prepare {@code NotificationOutputType}.
+ *
* @param data
- * - data of notification
+ * data of notification
* @return output type fo notification
*/
private static NotificationOutputType prepareOutputType(final ContainerNode data) {
return outputType = outputType == null ? NotificationOutputType.XML : outputType;
}
- private static String prepareDataChangeNotifiStreamName(final YangInstanceIdentifier path, final SchemaContext schemaContext,
+ private static String prepareDataChangeNotifiStreamName(final YangInstanceIdentifier path,
+ final SchemaContext schemaContext,
final ContainerNode data) {
LogicalDatastoreType ds = parseEnum(data, LogicalDatastoreType.class,
RestconfStreamsConstants.DATASTORE_PARAM_NAME);
return ResolveEnumUtil.resolveEnum(clazz, (String) value);
}
- private static YangInstanceIdentifier preparePath(final ContainerNode data, final QName qName) {
+ private static YangInstanceIdentifier preparePath(final ContainerNode data, final QName qualifiedName) {
final Optional<DataContainerChild<? extends PathArgument, ?>> path = data
- .getChild(new YangInstanceIdentifier.NodeIdentifier(QName.create(qName, "path")));
+ .getChild(new YangInstanceIdentifier.NodeIdentifier(QName.create(qualifiedName, "path")));
Object pathValue = null;
if (path.isPresent()) {
pathValue = path.get().getValue();
}
if (!(pathValue instanceof YangInstanceIdentifier)) {
final String errMsg = "Instance identifier was not normalized correctly ";
- LOG.debug(errMsg + qName);
+ LOG.debug(errMsg + qualifiedName);
throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
}
return (YangInstanceIdentifier) pathValue;
}
/**
- * Create stream with POST operation via RPC
+ * Create stream with POST operation via RPC.
*
* @param notificatinoDefinition
- * - input of RPC
+ * input of RPC
* @param refSchemaCtx
- * - schemaContext
+ * schemaContext
* @param outputType
+ * output type
* @return {@link DOMRpcResult}
*/
public static List<NotificationListenerAdapter> createYangNotifiStream(
final NotificationDefinition notificatinoDefinition, final SchemaContextRef refSchemaCtx,
final String outputType) {
final List<SchemaPath> paths = new ArrayList<>();
- String streamName = RestconfStreamsConstants.CREATE_NOTIFICATION_STREAM + "/";
final QName notificatinoDefinitionQName = notificatinoDefinition.getQName();
final Module module =
refSchemaCtx.findModuleByNamespaceAndRevision(notificatinoDefinitionQName.getModule().getNamespace(),
Preconditions.checkNotNull(notifiDef,
"Notification " + notificatinoDefinitionQName + "doesn't exist in module " + moduleName);
paths.add(notifiDef.getPath());
+ String streamName = RestconfStreamsConstants.CREATE_NOTIFICATION_STREAM + "/";
streamName = streamName + moduleName + ":" + notificatinoDefinitionQName.getLocalName();
if (outputType.equals("JSON")) {
streamName = streamName + "/JSON";
* Delete data from DS via transaction.
*
* @param transactionNode
- * - Wrapper for data of transaction
+ * Wrapper for data of transaction
* @return {@link Response}
*/
public static Response deleteData(final TransactionVarsWrapper transactionNode) {
* Delete data via transaction. Return error if data to delete does not exist.
*
* @param transactionChain
- * - transaction chain
+ * transaction chain
* @param readWriteTx
- * - read and write transaction
+ * read and write transaction
* @param path
- * - path of data to delete
+ * path of data to delete
* @return {@link CheckedFuture}
*/
private static CheckedFuture<Void, TransactionCommitFailedException> submitData(
*/
final class FutureCallbackTx {
- private final static Logger LOG = LoggerFactory.getLogger(FutureCallbackTx.class);
+ private static final Logger LOG = LoggerFactory.getLogger(FutureCallbackTx.class);
private FutureCallbackTx() {
throw new UnsupportedOperationException("Util class");
}
/**
- * Add callback to the future object
+ * Add callback to the future object.
*
* @param listenableFuture
- * - future object
+ * future object
* @param txType
- * - type of operation (READ, POST, PUT, DELETE)
+ * type of operation (READ, POST, PUT, DELETE)
* @param dataFactory
- * - factory setting result
+ * factory setting result
*/
+ @SuppressWarnings("checkstyle:IllegalCatch")
static <T, X extends Exception> void addCallback(final CheckedFuture<T, X> listenableFuture, final String txType,
final FutureDataFactory<T> dataFactory) {
final CountDownLatch responseWaiter = new CountDownLatch(1);
Futures.addCallback(listenableFuture, new FutureCallback<T>() {
@Override
- public void onFailure(final Throwable t) {
+ public void onFailure(final Throwable throwable) {
responseWaiter.countDown();
- handlingLoggerAndValues(t, txType, null, dataFactory);
+ handlingLoggerAndValues(throwable, txType, null, dataFactory);
}
@Override
}
/**
- * Handling logger and result of callback - on success or on failure
+ * Handling logger and result of callback - on success or on failure.
* <ul>
* <li>on success - set result to the factory
* <li>on failure - throw exception
* </ul>
*
- * @param t
- * - exception - if callback is onFailure
+ * @param throwable
+ * exception - if callback is onFailure
* @param txType
- * - type of operation (READ, POST, PUT, DELETE)
+ * type of operation (READ, POST, PUT, DELETE)
* @param result
- * - result of future - if callback is on Success
+ * result of future - if callback is on Success
* @param dataFactory
- * - setter for result - in callback is onSuccess
+ * setter for result - in callback is onSuccess
*/
- protected static <T> void handlingLoggerAndValues(@Nullable final Throwable t, final String txType,
+ protected static <T> void handlingLoggerAndValues(@Nullable final Throwable throwable, final String txType,
final T result, final FutureDataFactory<T> dataFactory) {
- if (t != null) {
+ if (throwable != null) {
dataFactory.setFailureStatus();
- LOG.warn("Transaction({}) FAILED!", txType, t);
- if (t instanceof DOMRpcException) {
+ LOG.warn("Transaction({}) FAILED!", txType, throwable);
+ if (throwable instanceof DOMRpcException) {
final List<RpcError> rpcErrorList = new ArrayList<>();
- rpcErrorList.add(RpcResultBuilder.newError(RpcError.ErrorType.RPC, "operation-failed", t.getMessage()));
+ rpcErrorList.add(
+ RpcResultBuilder.newError(RpcError.ErrorType.RPC, "operation-failed", throwable.getMessage()));
dataFactory.setResult((T) new DefaultDOMRpcResult(rpcErrorList));
} else {
- throw new RestconfDocumentedException(" Transaction(" + txType + ") not committed correctly", t);
+ throw new RestconfDocumentedException(
+ "Transaction(" + txType + ") not committed correctly", throwable);
}
} else {
LOG.trace("Transaction({}) SUCCESSFUL!", txType);
}
/**
- * Check if URI does not contain not allowed parameters for specified operation
+ * Check if URI does not contain not allowed parameters for specified operation.
*
* @param operationType
- * - type of operation (READ, POST, PUT, DELETE...)
+ * type of operation (READ, POST, PUT, DELETE...)
* @param usedParameters
- * - parameters used in URI request
+ * parameters used in URI request
* @param allowedParameters
- * - allowed parameters for operation
+ * allowed parameters for operation
*/
static void checkParametersTypes(@Nonnull final String operationType,
@Nonnull final Set<String> usedParameters,
}
/**
- * Check if URI does not contain value for the same parameter more than once
+ * Check if URI does not contain value for the same parameter more than once.
*
* @param parameterValues
- * - URI parameter values
+ * URI parameter values
* @param parameterName
- * - URI parameter name
+ * URI parameter name
*/
static void checkParameterCount(@Nonnull final List<String> parameterValues, @Nonnull final String parameterName) {
if (parameterValues.size() > 1) {
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHEditOperation;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHEntity;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusEntity;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchEditOperation;
+import org.opendaylight.netconf.sal.restconf.impl.PatchEntity;
+import org.opendaylight.netconf.sal.restconf.impl.PatchStatusContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchStatusEntity;
import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
}
/**
- * Process edit operations of one {@link PATCHContext}.
+ * Process edit operations of one {@link PatchContext}.
* @param context Patch context to be processed
* @param transactionNode Wrapper for transaction
* @param schemaContextRef Soft reference for global schema context
- * @return {@link PATCHStatusContext}
+ * @return {@link PatchStatusContext}
*/
- public static PATCHStatusContext patchData(final PATCHContext context, final TransactionVarsWrapper transactionNode,
+ public static PatchStatusContext patchData(final PatchContext context, final TransactionVarsWrapper transactionNode,
final SchemaContextRef schemaContextRef) {
- final List<PATCHStatusEntity> editCollection = new ArrayList<>();
+ final List<PatchStatusEntity> editCollection = new ArrayList<>();
boolean noError = true;
final DOMDataReadWriteTransaction tx = transactionNode.getTransactionChain().newReadWriteTransaction();
- for (final PATCHEntity patchEntity : context.getData()) {
- final PATCHEditOperation operation = PATCHEditOperation.valueOf(patchEntity.getOperation().toUpperCase());
+ for (final PatchEntity patchEntity : context.getData()) {
+ final PatchEditOperation operation = PatchEditOperation.valueOf(patchEntity.getOperation().toUpperCase());
if (noError) {
switch (operation) {
case CREATE:
try {
createDataWithinTransaction(LogicalDatastoreType.CONFIGURATION,
patchEntity.getTargetNode(), patchEntity.getNode(), tx, schemaContextRef);
- editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), true, null));
+ editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
} catch (final RestconfDocumentedException e) {
- editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(),
+ editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
false, Lists.newArrayList(e.getErrors())));
noError = false;
}
try {
deleteDataWithinTransaction(LogicalDatastoreType.CONFIGURATION, patchEntity.getTargetNode(),
tx);
- editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), true, null));
+ editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
} catch (final RestconfDocumentedException e) {
- editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(),
+ editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
false, Lists.newArrayList(e.getErrors())));
noError = false;
}
try {
mergeDataWithinTransaction(LogicalDatastoreType.CONFIGURATION,
patchEntity.getTargetNode(), patchEntity.getNode(), tx, schemaContextRef);
- editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), true, null));
+ editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
} catch (final RestconfDocumentedException e) {
- editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(),
+ editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
false, Lists.newArrayList(e.getErrors())));
noError = false;
}
try {
replaceDataWithinTransaction(LogicalDatastoreType.CONFIGURATION,
patchEntity.getTargetNode(), patchEntity.getNode(), schemaContextRef, tx);
- editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), true, null));
+ editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
} catch (final RestconfDocumentedException e) {
- editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(),
+ editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
false, Lists.newArrayList(e.getErrors())));
noError = false;
}
try {
removeDataWithinTransaction(LogicalDatastoreType.CONFIGURATION, patchEntity.getTargetNode(),
tx);
- editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(), true, null));
+ editCollection.add(new PatchStatusEntity(patchEntity.getEditId(), true, null));
} catch (final RestconfDocumentedException e) {
- editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(),
+ editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
false, Lists.newArrayList(e.getErrors())));
noError = false;
}
break;
default:
- editCollection.add(new PATCHStatusEntity(patchEntity.getEditId(),
+ editCollection.add(new PatchStatusEntity(patchEntity.getEditId(),
false, Lists.newArrayList(new RestconfError(ErrorType.PROTOCOL,
- ErrorTag.OPERATION_NOT_SUPPORTED, "Not supported Yang PATCH operation"))));
+ ErrorTag.OPERATION_NOT_SUPPORTED, "Not supported Yang Patch operation"))));
noError = false;
break;
}
FutureCallbackTx.addCallback(future, PatchData.PATCH_TX_TYPE, response);
} catch (final RestconfDocumentedException e) {
// if errors occurred during transaction commit then patch failed and global errors are reported
- return new PATCHStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection), false,
+ return new PatchStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection), false,
Lists.newArrayList(e.getErrors()));
}
- return new PATCHStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection), true, null);
+ return new PatchStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection), true, null);
} else {
tx.cancel();
RestConnectorProvider.resetTransactionChainForAdapaters(transactionNode.getTransactionChain());
- return new PATCHStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection),
+ return new PatchStatusContext(context.getPatchId(), ImmutableList.copyOf(editCollection),
false, null);
}
}
private static void createDataWithinTransaction(final LogicalDatastoreType dataStore,
final YangInstanceIdentifier path,
final NormalizedNode<?, ?> payload,
- final DOMDataReadWriteTransaction rWTransaction,
+ final DOMDataReadWriteTransaction rwTransaction,
final SchemaContextRef schemaContextRef) {
- LOG.trace("POST {} within Restconf PATCH: {} with payload {}", dataStore.name(), path, payload);
- createData(payload, schemaContextRef.get(), path, rWTransaction, dataStore, true);
+ LOG.trace("POST {} within Restconf Patch: {} with payload {}", dataStore.name(), path, payload);
+ createData(payload, schemaContextRef.get(), path, rwTransaction, dataStore, true);
}
/**
private static void deleteDataWithinTransaction(final LogicalDatastoreType dataStore,
final YangInstanceIdentifier path,
final DOMDataReadWriteTransaction readWriteTransaction) {
- LOG.trace("Delete {} within Restconf PATCH: {}", dataStore.name(), path);
+ LOG.trace("Delete {} within Restconf Patch: {}", dataStore.name(), path);
checkItemExistsWithinTransaction(readWriteTransaction, dataStore, path);
readWriteTransaction.delete(dataStore, path);
}
final NormalizedNode<?, ?> payload,
final DOMDataReadWriteTransaction writeTransaction,
final SchemaContextRef schemaContextRef) {
- LOG.trace("Merge {} within Restconf PATCH: {} with payload {}", dataStore.name(), path, payload);
+ LOG.trace("Merge {} within Restconf Patch: {} with payload {}", dataStore.name(), path, payload);
TransactionUtil.ensureParentsByMerge(path, schemaContextRef.get(), writeTransaction);
writeTransaction.merge(dataStore, path, payload);
}
private static void removeDataWithinTransaction(final LogicalDatastoreType dataStore,
final YangInstanceIdentifier path,
final DOMDataWriteTransaction writeTransaction) {
- LOG.trace("Remove {} within Restconf PATCH: {}", dataStore.name(), path);
+ LOG.trace("Remove {} within Restconf Patch: {}", dataStore.name(), path);
writeTransaction.delete(dataStore, path);
}
* @param path Path for data to be created
* @param payload Data to be created
* @param schemaContextRef Soft reference for global schema context
- * @param rWTransaction Transaction
+ * @param rwTransaction Transaction
*/
private static void replaceDataWithinTransaction(final LogicalDatastoreType dataStore,
final YangInstanceIdentifier path,
final NormalizedNode<?, ?> payload,
final SchemaContextRef schemaContextRef,
- final DOMDataReadWriteTransaction rWTransaction) {
- LOG.trace("PUT {} within Restconf PATCH: {} with payload {}", dataStore.name(), path, payload);
- createData(payload, schemaContextRef.get(), path, rWTransaction, dataStore, false);
+ final DOMDataReadWriteTransaction rwTransaction) {
+ LOG.trace("PUT {} within Restconf Patch: {} with payload {}", dataStore.name(), path, payload);
+ createData(payload, schemaContextRef.get(), path, rwTransaction, dataStore, false);
}
/**
* @param payload Data to be created
* @param schemaContext Global schema context
* @param path Path for data to be created
- * @param rWTransaction Transaction
+ * @param rwTransaction Transaction
* @param dataStore Datastore to write data to
* @param errorIfExists Enable checking for existence of data (throws error if already exists)
*/
private static void createData(final NormalizedNode<?, ?> payload, final SchemaContext schemaContext,
- final YangInstanceIdentifier path, final DOMDataReadWriteTransaction rWTransaction,
+ final YangInstanceIdentifier path, final DOMDataReadWriteTransaction rwTransaction,
final LogicalDatastoreType dataStore, final boolean errorIfExists) {
if (payload instanceof MapNode) {
final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path);
- rWTransaction.merge(dataStore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
- TransactionUtil.ensureParentsByMerge(path, schemaContext, rWTransaction);
+ rwTransaction.merge(dataStore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
+ TransactionUtil.ensureParentsByMerge(path, schemaContext, rwTransaction);
for (final MapEntryNode child : ((MapNode) payload).getValue()) {
final YangInstanceIdentifier childPath = path.node(child.getIdentifier());
if (errorIfExists) {
- checkItemDoesNotExistsWithinTransaction(rWTransaction, dataStore, childPath);
+ checkItemDoesNotExistsWithinTransaction(rwTransaction, dataStore, childPath);
}
- rWTransaction.put(dataStore, childPath, child);
+ rwTransaction.put(dataStore, childPath, child);
}
} else {
if (errorIfExists) {
- checkItemDoesNotExistsWithinTransaction(rWTransaction, dataStore, path);
+ checkItemDoesNotExistsWithinTransaction(rwTransaction, dataStore, path);
}
- TransactionUtil.ensureParentsByMerge(path, schemaContext, rWTransaction);
- rWTransaction.put(dataStore, path, payload);
+ TransactionUtil.ensureParentsByMerge(path, schemaContext, rwTransaction);
+ rwTransaction.put(dataStore, path, payload);
}
}
/**
* Check if items already exists at specified {@code path}. Throws {@link RestconfDocumentedException} if
* data does NOT already exists.
- * @param rWTransaction Transaction
+ * @param rwTransaction Transaction
* @param store Datastore
* @param path Path to be checked
*/
- public static void checkItemExistsWithinTransaction(final DOMDataReadWriteTransaction rWTransaction,
- final LogicalDatastoreType store, final YangInstanceIdentifier path) {
- final CheckedFuture<Boolean, ReadFailedException> future = rWTransaction.exists(store, path);
+ public static void checkItemExistsWithinTransaction(final DOMDataReadWriteTransaction rwTransaction,
+ final LogicalDatastoreType store, final YangInstanceIdentifier path) {
+ final CheckedFuture<Boolean, ReadFailedException> future = rwTransaction.exists(store, path);
final FutureDataFactory<Boolean> response = new FutureDataFactory<>();
FutureCallbackTx.addCallback(future, PatchData.PATCH_TX_TYPE, response);
/**
* Check if items do NOT already exists at specified {@code path}. Throws {@link RestconfDocumentedException} if
* data already exists.
- * @param rWTransaction Transaction
+ * @param rwTransaction Transaction
* @param store Datastore
* @param path Path to be checked
*/
- public static void checkItemDoesNotExistsWithinTransaction(final DOMDataReadWriteTransaction rWTransaction,
- final LogicalDatastoreType store, final YangInstanceIdentifier path) {
- final CheckedFuture<Boolean, ReadFailedException> future = rWTransaction.exists(store, path);
+ public static void checkItemDoesNotExistsWithinTransaction(final DOMDataReadWriteTransaction rwTransaction,
+ final LogicalDatastoreType store, final YangInstanceIdentifier path) {
+ final CheckedFuture<Boolean, ReadFailedException> future = rwTransaction.exists(store, path);
final FutureDataFactory<Boolean> response = new FutureDataFactory<>();
FutureCallbackTx.addCallback(future, PatchData.PATCH_TX_TYPE, response);
import org.slf4j.LoggerFactory;
/**
- * Util class to post data to DS
+ * Util class to post data to DS.
*
*/
public final class PostDataTransactionUtil {
}
/**
- * Check mount point and prepare variables for post data
+ * Check mount point and prepare variables for post data.
*
* @param uriInfo
*
* @param payload
- * - data
+ * data
* @param transactionNode
- * - wrapper for transaction data
+ * wrapper for transaction data
* @param schemaContextRef
- * - reference to actual {@link SchemaContext}
+ * reference to actual {@link SchemaContext}
* @param point
+ * point
* @param insert
+ * insert
* @return {@link CheckedFuture}
*/
public static Response postData(final UriInfo uriInfo, final NormalizedNodeContext payload,
}
/**
- * Post data by type
+ * Post data by type.
*
* @param path
- * - path
+ * path
* @param data
- * - data
+ * data
* @param transactionNode
- * - wrapper for data to transaction
+ * wrapper for data to transaction
* @param schemaContext
- * - schema context of data
+ * schema context of data
* @param point
- * - query parameter
+ * query parameter
* @param insert
- * - query parameter
+ * query parameter
* @return {@link CheckedFuture}
*/
private static CheckedFuture<Void, TransactionCommitFailedException> submitData(final YangInstanceIdentifier path,
return newReadWriteTransaction.submit();
}
} else {
- final NormalizedNode<?, ?> readData =
- PutDataTransactionUtil.readList(path.getParent(), schemaContext, domTransactionChain, schemaNode);
+ final NormalizedNode<?, ?> readData = PutDataTransactionUtil
+ .readList(path.getParent(), schemaContext, domTransactionChain, schemaNode);
final OrderedLeafSetNode<?> readLeafList = (OrderedLeafSetNode<?>) readData;
if ((readLeafList == null) || readLeafList.getValue().isEmpty()) {
}
}
- private static void insertWithPointLeafListPost(final DOMDataReadWriteTransaction rWTransaction,
+ private static void insertWithPointLeafListPost(final DOMDataReadWriteTransaction rwTransaction,
final LogicalDatastoreType datastore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload,
final SchemaContext schemaContext, final String point, final OrderedLeafSetNode<?> readLeafList,
final boolean before, final DOMTransactionChain domTransactionChain) {
- rWTransaction.delete(datastore, path.getParent().getParent());
+ rwTransaction.delete(datastore, path.getParent().getParent());
final InstanceIdentifierContext<?> instanceIdentifier =
ControllerContext.getInstance().toInstanceIdentifier(point);
- int p = 0;
+ int lastItemPosition = 0;
for (final LeafSetEntryNode<?> nodeChild : readLeafList.getValue()) {
if (nodeChild.getIdentifier().equals(instanceIdentifier.getInstanceIdentifier().getLastPathArgument())) {
break;
}
- p++;
+ lastItemPosition++;
}
if (!before) {
- p++;
+ lastItemPosition++;
}
- int h = 0;
+ int lastInsertedPosition = 0;
final NormalizedNode<?, ?> emptySubtree =
ImmutableNodes.fromInstanceId(schemaContext, path.getParent().getParent());
- rWTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
+ rwTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
for (final LeafSetEntryNode<?> nodeChild : readLeafList.getValue()) {
- if (h == p) {
- TransactionUtil.checkItemDoesNotExists(domTransactionChain, rWTransaction, datastore, path,
+ if (lastInsertedPosition == lastItemPosition) {
+ TransactionUtil.checkItemDoesNotExists(domTransactionChain, rwTransaction, datastore, path,
RestconfDataServiceConstant.PostData.POST_TX_TYPE);
- rWTransaction.put(datastore, path, payload);
+ rwTransaction.put(datastore, path, payload);
}
final YangInstanceIdentifier childPath = path.getParent().getParent().node(nodeChild.getIdentifier());
- TransactionUtil.checkItemDoesNotExists(domTransactionChain, rWTransaction, datastore, childPath,
+ TransactionUtil.checkItemDoesNotExists(domTransactionChain, rwTransaction, datastore, childPath,
RestconfDataServiceConstant.PostData.POST_TX_TYPE);
- rWTransaction.put(datastore, childPath, nodeChild);
- h++;
+ rwTransaction.put(datastore, childPath, nodeChild);
+ lastInsertedPosition++;
}
}
- private static void insertWithPointListPost(final DOMDataReadWriteTransaction rWTransaction,
+ private static void insertWithPointListPost(final DOMDataReadWriteTransaction rwTransaction,
final LogicalDatastoreType datastore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload,
final SchemaContext schemaContext, final String point, final MapNode readList, final boolean before,
final DOMTransactionChain domTransactionChain) {
- rWTransaction.delete(datastore, path.getParent().getParent());
+ rwTransaction.delete(datastore, path.getParent().getParent());
final InstanceIdentifierContext<?> instanceIdentifier =
ControllerContext.getInstance().toInstanceIdentifier(point);
- int p = 0;
+ int lastItemPosition = 0;
for (final MapEntryNode mapEntryNode : readList.getValue()) {
if (mapEntryNode.getIdentifier().equals(instanceIdentifier.getInstanceIdentifier().getLastPathArgument())) {
break;
}
- p++;
+ lastItemPosition++;
}
if (!before) {
- p++;
+ lastItemPosition++;
}
- int h = 0;
+ int lastInsertedPosition = 0;
final NormalizedNode<?, ?> emptySubtree =
ImmutableNodes.fromInstanceId(schemaContext, path.getParent().getParent());
- rWTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
+ rwTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
for (final MapEntryNode mapEntryNode : readList.getValue()) {
- if (h == p) {
- TransactionUtil.checkItemDoesNotExists(domTransactionChain, rWTransaction, datastore, path,
+ if (lastInsertedPosition == lastItemPosition) {
+ TransactionUtil.checkItemDoesNotExists(domTransactionChain, rwTransaction, datastore, path,
RestconfDataServiceConstant.PostData.POST_TX_TYPE);
- rWTransaction.put(datastore, path, payload);
+ rwTransaction.put(datastore, path, payload);
}
final YangInstanceIdentifier childPath = path.getParent().getParent().node(mapEntryNode.getIdentifier());
- TransactionUtil.checkItemDoesNotExists(domTransactionChain, rWTransaction, datastore, childPath,
+ TransactionUtil.checkItemDoesNotExists(domTransactionChain, rwTransaction, datastore, childPath,
RestconfDataServiceConstant.PostData.POST_TX_TYPE);
- rWTransaction.put(datastore, childPath, mapEntryNode);
- h++;
+ rwTransaction.put(datastore, childPath, mapEntryNode);
+ lastInsertedPosition++;
}
}
}
/**
- * Get location from {@link YangInstanceIdentifier} and {@link UriInfo}
+ * Get location from {@link YangInstanceIdentifier} and {@link UriInfo}.
*
* @param uriInfo
- * - uri info
+ * uri info
* @param transactionNode
- * - wrapper for data of transaction
+ * wrapper for data of transaction
* @param schemaContextRef
- * -reference to {@link SchemaContext}
+ * reference to {@link SchemaContext}
* @return {@link URI}
*/
private static URI resolveLocation(final UriInfo uriInfo, final TransactionVarsWrapper transactionNode,
final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
uriBuilder.path("data");
- uriBuilder.path(ParserIdentifier.stringFromYangInstanceIdentifier(transactionNode.getInstanceIdentifier().getInstanceIdentifier(),
+ uriBuilder.path(ParserIdentifier
+ .stringFromYangInstanceIdentifier(transactionNode.getInstanceIdentifier().getInstanceIdentifier(),
schemaContextRef.get()));
return uriBuilder.build();
}
- private static void simplePost(final DOMDataReadWriteTransaction rWTransaction,
+ private static void simplePost(final DOMDataReadWriteTransaction rwTransaction,
final LogicalDatastoreType datastore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload,
final SchemaContext schemaContext, final DOMTransactionChain transactionChain) {
- TransactionUtil.checkItemDoesNotExists(transactionChain, rWTransaction, datastore, path,
+ TransactionUtil.checkItemDoesNotExists(transactionChain, rwTransaction, datastore, path,
RestconfDataServiceConstant.PostData.POST_TX_TYPE);
- TransactionUtil.ensureParentsByMerge(path, schemaContext, rWTransaction);
- rWTransaction.put(datastore, path, payload);
+ TransactionUtil.ensureParentsByMerge(path, schemaContext, rwTransaction);
+ rwTransaction.put(datastore, path, payload);
}
}
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
/**
- * Util class for put data to DS
+ * Util class for put data to DS.
*
*/
public final class PutDataTransactionUtil {
/**
- * Valid input data with {@link SchemaNode}
+ * Valid input data with {@link SchemaNode}.
*
* @param schemaNode
- * - {@link SchemaNode}
+ * {@link SchemaNode}
* @param payload
- * - input data
+ * input data
*/
public static void validInputData(final SchemaNode schemaNode, final NormalizedNodeContext payload) {
if ((schemaNode != null) && (payload.getData() == null)) {
}
/**
- * Valid top level node name
+ * Valid top level node name.
*
* @param path
- * - path of node
+ * path of node
* @param payload
- * - data
+ * data
*/
public static void validTopLevelNodeName(final YangInstanceIdentifier path, final NormalizedNodeContext payload) {
final String payloadName = payload.getData().getNodeType().getLocalName();
/**
* Validates whether keys in {@code payload} are equal to values of keys in
- * {@code iiWithData} for list schema node
+ * {@code iiWithData} for list schema node.
*
* @throws RestconfDocumentedException
* if key values or key count in payload and URI isn't equal
- *
*/
public static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
}
/**
- * Check mount point and prepare variables for put data to DS
+ * Check mount point and prepare variables for put data to DS.
*
* @param payload
- * - data to put
+ * data to put
* @param schemaCtxRef
- * - reference to {@link SchemaContext}
+ * reference to {@link SchemaContext}
* @param transactionNode
- * - wrapper of variables for transaction
+ * wrapper of variables for transaction
* @param point
- * - query parameter
+ * query parameter
* @param insert
- * - query parameter
+ * query parameter
* @return {@link CheckedFuture}
*/
- public static Response putData(final NormalizedNodeContext payload,
- final SchemaContextRef schemaCtxRef, final TransactionVarsWrapper transactionNode, final String insert, final String point) {
+ public static Response putData(final NormalizedNodeContext payload, final SchemaContextRef schemaCtxRef,
+ final TransactionVarsWrapper transactionNode, final String insert, final String point) {
final YangInstanceIdentifier path = payload.getInstanceIdentifierContext().getInstanceIdentifier();
final ResponseFactory responseFactory = new ResponseFactory(
ReadDataTransactionUtil.readData(RestconfDataServiceConstant.ReadData.CONFIG, transactionNode));
}
/**
- * Put data to DS
+ * Put data to DS.
*
* @param path
- * - path of data
+ * path of data
* @param schemaContext
- * - {@link SchemaContext}
+ * {@link SchemaContext}
* @param domTransactionChain
- * - write transaction
+ * write transaction
* @param data
- * - data
+ * data
* @param point
- * - query parameter
+ * query parameter
* @param insert
- * - query parameter
+ * query parameter
* @return {@link CheckedFuture}
*/
private static CheckedFuture<Void, TransactionCommitFailedException> submitData(final YangInstanceIdentifier path,
return makePut(path, schemaContext, newReadWriteTransaction, data);
} else {
newReadWriteTransaction.delete(LogicalDatastoreType.CONFIGURATION, path.getParent());
- simplePut(LogicalDatastoreType.CONFIGURATION, path, newReadWriteTransaction, schemaContext, data);
- listPut(LogicalDatastoreType.CONFIGURATION, path.getParent(), newReadWriteTransaction, schemaContext,
- readList);
+ simplePut(LogicalDatastoreType.CONFIGURATION, path, newReadWriteTransaction,
+ schemaContext, data);
+ listPut(LogicalDatastoreType.CONFIGURATION, path.getParent(), newReadWriteTransaction,
+ schemaContext, readList);
return newReadWriteTransaction.submit();
}
} else {
return makePut(path, schemaContext, newReadWriteTransaction, data);
} else {
newReadWriteTransaction.delete(LogicalDatastoreType.CONFIGURATION, path.getParent());
- simplePut(LogicalDatastoreType.CONFIGURATION, path, newReadWriteTransaction, schemaContext, data);
- listPut(LogicalDatastoreType.CONFIGURATION, path.getParent(), newReadWriteTransaction, schemaContext,
- readLeafList);
+ simplePut(LogicalDatastoreType.CONFIGURATION, path, newReadWriteTransaction,
+ schemaContext, data);
+ listPut(LogicalDatastoreType.CONFIGURATION, path.getParent(), newReadWriteTransaction,
+ schemaContext, readLeafList);
return newReadWriteTransaction.submit();
}
}
if ((readList == null) || readList.getValue().isEmpty()) {
return makePut(path, schemaContext, newReadWriteTransaction, data);
} else {
- insertWithPointListPut(newReadWriteTransaction, LogicalDatastoreType.CONFIGURATION, path, data,
- schemaContext, point, readList, true);
+ insertWithPointListPut(newReadWriteTransaction, LogicalDatastoreType.CONFIGURATION, path,
+ data, schemaContext, point, readList, true);
return newReadWriteTransaction.submit();
}
} else {
if ((readLeafList == null) || readLeafList.getValue().isEmpty()) {
return makePut(path, schemaContext, newReadWriteTransaction, data);
} else {
- insertWithPointLeafListPut(newReadWriteTransaction, LogicalDatastoreType.CONFIGURATION, path, data,
- schemaContext, point, readLeafList, true);
+ insertWithPointLeafListPut(newReadWriteTransaction, LogicalDatastoreType.CONFIGURATION,
+ path, data, schemaContext, point, readLeafList, true);
return newReadWriteTransaction.submit();
}
}
if ((readList == null) || readList.getValue().isEmpty()) {
return makePut(path, schemaContext, newReadWriteTransaction, data);
} else {
- insertWithPointListPut(newReadWriteTransaction, LogicalDatastoreType.CONFIGURATION, path, data,
- schemaContext, point, readList, false);
+ insertWithPointListPut(newReadWriteTransaction, LogicalDatastoreType.CONFIGURATION,
+ path, data, schemaContext, point, readList, false);
return newReadWriteTransaction.submit();
}
} else {
if ((readLeafList == null) || readLeafList.getValue().isEmpty()) {
return makePut(path, schemaContext, newReadWriteTransaction, data);
} else {
- insertWithPointLeafListPut(newReadWriteTransaction, LogicalDatastoreType.CONFIGURATION, path, data,
- schemaContext, point, readLeafList, true);
+ insertWithPointLeafListPut(newReadWriteTransaction, LogicalDatastoreType.CONFIGURATION,
+ path, data, schemaContext, point, readLeafList, true);
return newReadWriteTransaction.submit();
}
}
return readData;
}
- private static void insertWithPointLeafListPut(final DOMDataReadWriteTransaction rWTransaction,
+ private static void insertWithPointLeafListPut(final DOMDataReadWriteTransaction rwTransaction,
final LogicalDatastoreType datastore, final YangInstanceIdentifier path,
final NormalizedNode<?, ?> data, final SchemaContext schemaContext, final String point,
final OrderedLeafSetNode<?> readLeafList, final boolean before) {
- rWTransaction.delete(datastore, path.getParent());
+ rwTransaction.delete(datastore, path.getParent());
final InstanceIdentifierContext<?> instanceIdentifier =
ControllerContext.getInstance().toInstanceIdentifier(point);
- int p = 0;
+ int lastItemPosition = 0;
for (final LeafSetEntryNode<?> nodeChild : readLeafList.getValue()) {
if (nodeChild.getIdentifier().equals(instanceIdentifier.getInstanceIdentifier().getLastPathArgument())) {
break;
}
- p++;
+ lastItemPosition++;
}
if (!before) {
- p++;
+ lastItemPosition++;
}
- int h = 0;
+ int lastInsertedPosition = 0;
final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path.getParent());
- rWTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
+ rwTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
for (final LeafSetEntryNode<?> nodeChild : readLeafList.getValue()) {
- if (h == p) {
- simplePut(datastore, path, rWTransaction, schemaContext, data);
+ if (lastInsertedPosition == lastItemPosition) {
+ simplePut(datastore, path, rwTransaction, schemaContext, data);
}
final YangInstanceIdentifier childPath = path.getParent().node(nodeChild.getIdentifier());
- rWTransaction.put(datastore, childPath, nodeChild);
- h++;
+ rwTransaction.put(datastore, childPath, nodeChild);
+ lastInsertedPosition++;
}
}
writeTx.delete(datastore, path.getParent());
final InstanceIdentifierContext<?> instanceIdentifier =
ControllerContext.getInstance().toInstanceIdentifier(point);
- int p = 0;
+ int lastItemPosition = 0;
for (final MapEntryNode mapEntryNode : readList.getValue()) {
if (mapEntryNode.getIdentifier().equals(instanceIdentifier.getInstanceIdentifier().getLastPathArgument())) {
break;
}
- p++;
+ lastItemPosition++;
}
if (!before) {
- p++;
+ lastItemPosition++;
}
- int h = 0;
+ int lastInsertedPosition = 0;
final NormalizedNode<?, ?> emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path.getParent());
writeTx.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree);
for (final MapEntryNode mapEntryNode : readList.getValue()) {
- if (h == p) {
+ if (lastInsertedPosition == lastItemPosition) {
simplePut(datastore, path, writeTx, schemaContext, data);
}
final YangInstanceIdentifier childPath = path.getParent().node(mapEntryNode.getIdentifier());
writeTx.put(datastore, childPath, mapEntryNode);
- h++;
+ lastInsertedPosition++;
}
}
*
*
* @param identifier
- * - {@link InstanceIdentifierContext}
+ * {@link InstanceIdentifierContext}
* @param uriInfo
- * - URI info
+ * URI info
* @param tagged
- * - set tagged for {@link WriterParameters}
+ * set tagged for {@link WriterParameters}
* @return {@link WriterParameters}
*/
public static @Nonnull WriterParameters parseUriParameters(@Nonnull final InstanceIdentifierContext<?> identifier,
*
*
* @param identifier
- * - {@link InstanceIdentifierContext}
+ * {@link InstanceIdentifierContext}
* @param uriInfo
- * - URI info
+ * URI info
* @return {@link WriterParameters}
*/
public static @Nonnull WriterParameters parseUriParameters(@Nonnull final InstanceIdentifierContext<?> identifier,
* Read specific type of data from data store via transaction.
*
* @param valueOfContent
- * - type of data to read (config, state, all)
+ * type of data to read (config, state, all)
* @param transactionNode
- * - {@link TransactionVarsWrapper} - wrapper for variables
+ * {@link TransactionVarsWrapper} - wrapper for variables
* @return {@link NormalizedNode}
*/
public static @Nullable NormalizedNode<?, ?> readData(@Nonnull final String valueOfContent,
* Read specific type of data from data store via transaction.
*
* @param valueOfContent
- * - type of data to read (config, state, all)
+ * type of data to read (config, state, all)
* @param transactionNode
- * - {@link TransactionVarsWrapper} - wrapper for variables
+ * {@link TransactionVarsWrapper} - wrapper for variables
* @param withDefa
- * - vaule of with-defaults parameter
+ * vaule of with-defaults parameter
* @return {@link NormalizedNode}
*/
public static @Nullable NormalizedNode<?, ?> readData(@Nonnull final String valueOfContent,
}
}
+ /**
+ * Read specific type of data from data store via transaction and if identifier read data from
+ * streams then put streams from actual schema context to datastore.
+ *
+ * @param identifier
+ * identifier of data to read
+ * @param content
+ * type of data to read (config, state, all)
+ * @param transactionNode
+ * {@link TransactionVarsWrapper} - wrapper for variables
+ * @param withDefa
+ * vaule of with-defaults parameter
+ * @param schemaContextRef
+ * schema context
+ * @param uriInfo
+ * uri info
+ * @return {@link NormalizedNode}
+ */
+ public static NormalizedNode<?, ?> readData(final String identifier, final String content,
+ final TransactionVarsWrapper transactionNode, final String withDefa,
+ final SchemaContextRef schemaContextRef, final UriInfo uriInfo) {
+ if (identifier.contains(STREAMS_PATH) && !identifier.contains(STREAM_PATH_PART)) {
+ final DOMDataReadWriteTransaction wTx = transactionNode.getTransactionChain().newReadWriteTransaction();
+ final SchemaContext schemaContext = schemaContextRef.get();
+ final boolean exist = SubscribeToStreamUtil.checkExist(schemaContext, wTx);
+
+ for (final NotificationDefinition notificationDefinition : schemaContextRef.get().getNotifications()) {
+ final List<NotificationListenerAdapter> notifiStreamXML =
+ CreateStreamUtil.createYangNotifiStream(notificationDefinition, schemaContextRef,
+ NotificationOutputType.XML.getName());
+ final List<NotificationListenerAdapter> notifiStreamJSON =
+ CreateStreamUtil.createYangNotifiStream(notificationDefinition, schemaContextRef,
+ NotificationOutputType.JSON.getName());
+ notifiStreamJSON.addAll(notifiStreamXML);
+
+ for (final NotificationListenerAdapter listener : notifiStreamJSON) {
+ final URI uri = SubscribeToStreamUtil.prepareUriByStreamName(uriInfo, listener.getStreamName());
+ final NormalizedNode mapToStreams =
+ RestconfMappingNodeUtil.mapYangNotificationStreamByIetfRestconfMonitoring(
+ listener.getSchemaPath().getLastComponent(), schemaContext.getNotifications(),
+ null, listener.getOutputType(), uri,
+ SubscribeToStreamUtil.getMonitoringModule(schemaContext), exist);
+ SubscribeToStreamUtil.writeDataToDS(schemaContext,
+ listener.getSchemaPath().getLastComponent().getLocalName(), wTx, exist,
+ mapToStreams);
+ }
+ }
+ SubscribeToStreamUtil.submitData(wTx);
+ }
+ return readData(content, transactionNode, withDefa);
+ }
+
private static NormalizedNode<?, ?> prepareDataByParamWithDef(final NormalizedNode<?, ?> result,
final YangInstanceIdentifier path, final String withDefa) {
boolean trim;
* don't, we have to read all data from DS (state + config)
*
* @param transactionNode
- * - {@link TransactionVarsWrapper} - wrapper for variables
+ * {@link TransactionVarsWrapper} - wrapper for variables
* @return {@link NormalizedNode}
*/
private static @Nullable NormalizedNode<?, ?> readDataViaTransaction(
* Read config and state data, then map them.
*
* @param transactionNode
- * - {@link TransactionVarsWrapper} - wrapper for variables
- * @param withDefa
+ * {@link TransactionVarsWrapper} - wrapper for variables
+ * @param withDefa with-defaults parameter
* @return {@link NormalizedNode}
*/
private static @Nullable NormalizedNode<?, ?> readAllData(@Nonnull final TransactionVarsWrapper transactionNode,
* Map data by type of read node.
*
* @param stateDataNode
- * - data node of state data
+ * data node of state data
* @param configDataNode
- * - data node of config data
+ * data node of config data
* @return {@link NormalizedNode}
*/
private static @Nonnull NormalizedNode<?, ?> mapNode(@Nonnull final NormalizedNode<?, ?> stateDataNode,
* Valid of can be data merged together.
*
* @param stateDataNode
- * - data node of state data
+ * data node of state data
* @param configDataNode
- * - data node of config data
+ * data node of config data
*/
private static void validPossibilityOfMergeNodes(@Nonnull final NormalizedNode<?, ?> stateDataNode,
@Nonnull final NormalizedNode<?, ?> configDataNode) {
}
/**
- * Prepare and map data for rpc
+ * Prepare and map data for rpc.
*
* @param configDataNode
- * - data node of config data
+ * data node of config data
* @param stateDataNode
- * - data node of state data
+ * data node of state data
* @return {@link NormalizedNode}
*/
private static @Nonnull NormalizedNode<?, ?> prepareRpcData(@Nonnull final NormalizedNode<?, ?> configDataNode,
* Map node to map entry builder.
*
* @param dataNode
- * - data node
+ * data node
* @param mapEntryBuilder
- * - builder for mapping data
+ * builder for mapping data
*/
private static void mapRpcDataNode(@Nonnull final NormalizedNode<?, ?> dataNode,
@Nonnull final DataContainerNodeBuilder<
}
/**
- * Prepare and map all data from DS
+ * Prepare and map all data from DS.
*
* @param configDataNode
- * - data node of config data
+ * data node of config data
* @param stateDataNode
- * - data node of state data
+ * data node of state data
* @return {@link NormalizedNode}
*/
private static @Nonnull NormalizedNode<?, ?> prepareData(@Nonnull final NormalizedNode<?, ?> configDataNode,
final DataContainerNodeBuilder<AugmentationIdentifier, AugmentationNode> builder = Builders
.augmentationBuilder().withNodeIdentifier(((AugmentationNode) configDataNode).getIdentifier());
- mapValueToBuilder(
- ((AugmentationNode) configDataNode).getValue(), ((AugmentationNode) stateDataNode).getValue(), builder);
+ mapValueToBuilder(((AugmentationNode) configDataNode).getValue(),
+ ((AugmentationNode) stateDataNode).getValue(), builder);
return builder.build();
} else if (configDataNode instanceof ChoiceNode) {
* Map value from container node to builder.
*
* @param configData
- * - collection of config data nodes
+ * collection of config data nodes
* @param stateData
- * - collection of state data nodes
+ * collection of state data nodes
* @param builder
- * - builder
+ * builder
*/
private static <T extends NormalizedNode<? extends PathArgument, ?>> void mapValueToBuilder(
@Nonnull final Collection<T> configData,
* as childs to parent node.
*
* @param configMap
- * - map of config data nodes
+ * map of config data nodes
* @param stateMap
- * - map of state data nodes
+ * map of state data nodes
* @param builder
* - builder
*/
@Nonnull final Map<PathArgument, T> stateMap,
@Nonnull final NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
- y -> builder.addChild(y.getValue()));
+ y -> builder.addChild(y.getValue()));
stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
- y -> builder.addChild(y.getValue()));
+ y -> builder.addChild(y.getValue()));
}
/**
* go one level down with {@code prepareData} method.
*
* @param configMap
- * - immutable config data
+ * immutable config data
* @param stateMap
- * - immutable state data
+ * immutable state data
* @param builder
* - builder
*/
@Nonnull final NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
// it is enough to process only config data because operational contains the same data
configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
- y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
- }
-
- /**
- * Read specific type of data from data store via transaction and if identifier read data from
- * streams then put streams from actual schema context to datastore.
- *
- * @param identifier
- * - identifier of data to read
- * @param content
- * - type of data to read (config, state, all)
- * @param transactionNode
- * - {@link TransactionVarsWrapper} - wrapper for variables
- * @param withDefa
- * - vaule of with-defaults parameter
- * @param schemaContextRef
- * - schema context
- * @param uriInfo
- * - uri info
- * @return {@link NormalizedNode}
- */
- public static NormalizedNode<?, ?> readData(final String identifier, final String content,
- final TransactionVarsWrapper transactionNode, final String withDefa,
- final SchemaContextRef schemaContextRef, final UriInfo uriInfo) {
- if (identifier.contains(STREAMS_PATH) && !identifier.contains(STREAM_PATH_PART)) {
- final DOMDataReadWriteTransaction wTx = transactionNode.getTransactionChain().newReadWriteTransaction();
- final SchemaContext schemaContext = schemaContextRef.get();
- final boolean exist = SubscribeToStreamUtil.checkExist(schemaContext, wTx);
-
- for (final NotificationDefinition notificationDefinition : schemaContextRef.get().getNotifications()) {
- final List<NotificationListenerAdapter> notifiStreamXML =
- CreateStreamUtil.createYangNotifiStream(notificationDefinition, schemaContextRef,
- NotificationOutputType.XML.getName());
- final List<NotificationListenerAdapter> notifiStreamJSON =
- CreateStreamUtil.createYangNotifiStream(notificationDefinition, schemaContextRef,
- NotificationOutputType.JSON.getName());
- notifiStreamJSON.addAll(notifiStreamXML);
-
- for (final NotificationListenerAdapter listener : notifiStreamJSON) {
- final URI uri = SubscribeToStreamUtil.prepareUriByStreamName(uriInfo, listener.getStreamName());
- final NormalizedNode mapToStreams =
- RestconfMappingNodeUtil.mapYangNotificationStreamByIetfRestconfMonitoring(
- listener.getSchemaPath().getLastComponent(), schemaContext.getNotifications(),
- null, listener.getOutputType(), uri,
- SubscribeToStreamUtil.getMonitoringModule(schemaContext), exist);
- SubscribeToStreamUtil.writeDataToDS(schemaContext,
- listener.getSchemaPath().getLastComponent().getLocalName(), wTx, exist,
- mapToStreams);
- }
- }
- SubscribeToStreamUtil.submitData(wTx);
- }
- return readData(content, transactionNode, withDefa);
+ y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
}
}
package org.opendaylight.restconf.restful.utils;
/**
- * Common util class for resolve enum from String
+ * Common util class for resolve enum from String.
*
*/
public final class ResolveEnumUtil {
* Resolve specific type of enum by value.
*
* @param clazz
- * - enum
+ * enum
* @param value
- * - string of enum
+ * string of enum
* @return - enum
*/
public static <T> T resolveEnum(final Class<T> clazz, final String value) {
final class ResponseFactory extends FutureDataFactory<Void> implements Builder<Response> {
private ResponseBuilder responseBuilder;
+
ResponseFactory(final NormalizedNode<?, ?> readData) {
final Status status = prepareStatus(readData);
this.responseBuilder = Response.status(status);
import org.opendaylight.yangtools.yang.common.QNameModule;
/**
- * Constants for RestconfDataService
+ * Constants for RestconfDataService.
*
*/
public final class RestconfDataServiceConstant {
public static final QName NETCONF_BASE_QNAME;
+
static {
try {
NETCONF_BASE_QNAME = QName.create(
}
/**
- * Constants for read data
+ * Constants for read data.
*
*/
public final class ReadData {
}
/**
- * Constants for data to put
+ * Constants for data to put.
*
*/
public final class PutData {
}
/**
- * Constants for data to post
+ * Constants for data to post.
*
*/
public final class PostData {
}
/**
- * Constants for data to delete
+ * Constants for data to delete.
*
*/
public final class DeleteData {
}
/**
- * Constants for data to yang patch
+ * Constants for data to yang patch.
*
*/
public final class PatchData {
- public static final String PATCH_TX_TYPE = "PATCH";
+ public static final String PATCH_TX_TYPE = "Patch";
private PatchData() {
throw new UnsupportedOperationException("Util class.");
import org.slf4j.LoggerFactory;
/**
- * Util class for rpc
+ * Util class for rpc.
*
*/
public class RestconfInvokeOperationsUtil {
}
/**
- * Invoking rpc via mount point
+ * Invoking rpc via mount point.
*
* @param mountPoint
- * - mount point
+ * mount point
* @param data
- * - input data
+ * input data
* @param schemaPath
- * - schema path of data
+ * schema path of data
* @return {@link CheckedFuture}
*/
public static DOMRpcResult invokeRpcViaMountPoint(final DOMMountPoint mountPoint, final NormalizedNode<?, ?> data,
}
/**
- * Invoke rpc
+ * Invoke rpc.
*
* @param data
- * - input data
+ * input data
* @param schemaPath
- * - schema path of data
+ * schema path of data
* @param rpcServiceHandler
- * - rpc service handler to invoke rpc
+ * rpc service handler to invoke rpc
* @return {@link CheckedFuture}
*/
public static DOMRpcResult invokeRpc(final NormalizedNode<?, ?> data, final SchemaPath schemaPath,
}
/**
- * Check the validity of the result
+ * Check the validity of the result.
*
* @param response
- * - response of rpc
+ * response of rpc
* @return {@link DOMRpcResult} result
*/
public static DOMRpcResult checkResponse(final DOMRpcResult response) {
import org.slf4j.LoggerFactory;
/**
- * Constants for streams
+ * Constants for streams.
*
*/
public final class RestconfStreamsConstants {
import org.slf4j.LoggerFactory;
/**
- * Subscribe to stream util class
+ * Subscribe to stream util class.
*
*/
public final class SubscribeToStreamUtil {
/**
* Register listeners by streamName in identifier to listen to yang
* notifications, put or delete info about listener to DS according to
- * ietf-restconf-monitoring
+ * ietf-restconf-monitoring.
*
* @param identifier
- * - identifier as stream name
+ * identifier as stream name
* @param uriInfo
- * - for getting base URI information
+ * for getting base URI information
* @param notificationQueryParams
- * - query parameters of notification
+ * query parameters of notification
* @param handlersHolder
- * - holder of handlers for notifications
+ * holder of handlers for notifications
* @return location for listening
*/
@SuppressWarnings("rawtypes")
listener.setQueryParams(notificationQueryParams.getStart(), notificationQueryParams.getStop(),
notificationQueryParams.getFilter(), false);
listener.setCloseVars(handlersHolder.getTransactionChainHandler(), handlersHolder.getSchemaHandler());
- final NormalizedNode mapToStreams =
- RestconfMappingNodeUtil.mapYangNotificationStreamByIetfRestconfMonitoring(listener.getSchemaPath().getLastComponent(),
+ final NormalizedNode mapToStreams = RestconfMappingNodeUtil
+ .mapYangNotificationStreamByIetfRestconfMonitoring(listener.getSchemaPath().getLastComponent(),
schemaContext.getNotifications(), notificationQueryParams.getStart(),
listener.getOutputType(), uri, getMonitoringModule(schemaContext), exist);
writeDataToDS(schemaContext, listener.getSchemaPath().getLastComponent().getLocalName(), wTx, exist,
}
/**
- * Prepare InstanceIdentifierContext for Location leaf
+ * Prepare InstanceIdentifierContext for Location leaf.
*
* @param schemaHandler
- * - schemaContext handler
+ * schemaContext handler
* @return InstanceIdentifier of Location leaf
*/
public static InstanceIdentifierContext<?> prepareIIDSubsStreamOutput(final SchemaContextHandler schemaHandler) {
/**
* Register listener by streamName in identifier to listen to data change
* notifications, put or delete info about listener to DS according to
- * ietf-restconf-monitoring
+ * ietf-restconf-monitoring.
*
* @param identifier
- * - identifier as stream name
+ * identifier as stream name
* @param uriInfo
- * - for getting base URI information
+ * for getting base URI information
* @param notificationQueryParams
- * - query parameters of notification
+ * query parameters of notification
* @param handlersHolder
- * - holder of handlers for notifications
+ * holder of handlers for notifications
* @return location for listening
*/
@SuppressWarnings("rawtypes")
/**
* Parse input of query parameters - start-time or stop-time - from
- * {@link DateAndTime} format to {@link Instant} format
+ * {@link DateAndTime} format to {@link Instant} format.
*
* @param entry
- * - start-time or stop-time as string in {@link DateAndTime}
+ * start-time or stop-time as string in {@link DateAndTime}
* format
* @return parsed {@link Instant} by entry
*/
}
@SuppressWarnings("rawtypes")
- static void writeDataToDS(final SchemaContext schemaContext, final String name,
- final DOMDataReadWriteTransaction wTx, final boolean exist, final NormalizedNode mapToStreams) {
+ static void writeDataToDS(final SchemaContext schemaContext,
+ final String name, final DOMDataReadWriteTransaction readWriteTransaction,
+ final boolean exist, final NormalizedNode mapToStreams) {
String pathId = "";
if (exist) {
pathId = MonitoringModule.PATH_TO_STREAM_WITHOUT_KEY + name;
} else {
pathId = MonitoringModule.PATH_TO_STREAMS;
}
- wTx.merge(LogicalDatastoreType.OPERATIONAL, IdentifierCodec.deserialize(pathId, schemaContext),
+ readWriteTransaction.merge(LogicalDatastoreType.OPERATIONAL, IdentifierCodec.deserialize(pathId, schemaContext),
mapToStreams);
}
- static void submitData(final DOMDataReadWriteTransaction wTx) {
+ static void submitData(final DOMDataReadWriteTransaction readWriteTransaction) {
try {
- wTx.submit().checkedGet();
+ readWriteTransaction.submit().checkedGet();
} catch (final TransactionCommitFailedException e) {
throw new RestconfDocumentedException("Problem while putting data to DS.", e);
}
}
/**
- * Prepare map of values from URI
+ * Prepare map of values from URI.
*
* @param identifier
- * - URI
+ * URI
* @return {@link Map}
*/
public static Map<String, String> mapValuesFromUri(final String identifier) {
/**
* Register data change listener in dom data broker and set it to listener
- * on stream
+ * on stream.
*
* @param ds
- * - {@link LogicalDatastoreType}
+ * {@link LogicalDatastoreType}
* @param scope
- * - {@link DataChangeScope}
+ * {@link DataChangeScope}
* @param listener
- * - listener on specific stream
+ * listener on specific stream
* @param domDataBroker
- * - data broker for register data change listener
+ * data broker for register data change listener
*/
@SuppressWarnings("deprecation")
private static void registration(final LogicalDatastoreType ds, final DataChangeScope scope,
return port;
}
- static boolean checkExist(final SchemaContext schemaContext, final DOMDataReadWriteTransaction wTx) {
+ static boolean checkExist(final SchemaContext schemaContext,
+ final DOMDataReadWriteTransaction readWriteTransaction) {
boolean exist;
try {
- exist = wTx.exists(LogicalDatastoreType.OPERATIONAL,
+ exist = readWriteTransaction.exists(LogicalDatastoreType.OPERATIONAL,
IdentifierCodec.deserialize(MonitoringModule.PATH_TO_STREAMS, schemaContext)).checkedGet();
} catch (final ReadFailedException e1) {
throw new RestconfDocumentedException("Problem while checking data if exists", e1);
}
/**
- * Parse enum from URI
+ * Parse enum from URI.
*
* @param clazz
- * - enum type
+ * enum type
* @param value
- * - string of enum value
+ * string of enum value
* @return enum
*/
private static <T> T parseURIEnum(final Class<T> clazz, final String value) {
import org.slf4j.LoggerFactory;
/**
- * Util class for common methods of transactions
+ * Util class for common methods of transactions.
*
*/
public final class TransactionUtil {
- private final static Logger LOG = LoggerFactory.getLogger(TransactionUtil.class);
+ private static final Logger LOG = LoggerFactory.getLogger(TransactionUtil.class);
private TransactionUtil() {
throw new UnsupportedOperationException("Util class");
}
/**
- * Merged parents of data
+ * Merged parents of data.
*
* @param path
- * - path of data
+ * path of data
* @param schemaContext
- * - {@link SchemaContext}
+ * {@link SchemaContext}
* @param writeTx
- * - write transaction
+ * write transaction
*/
public static void ensureParentsByMerge(final YangInstanceIdentifier path, final SchemaContext schemaContext,
final DOMDataWriteTransaction writeTx) {
* Check if items already exists at specified {@code path}. Throws {@link RestconfDocumentedException} if
* data does NOT already exists.
* @param transactionChain Transaction chain
- * @param rWTransaction Transaction
+ * @param rwTransaction Transaction
* @param store Datastore
* @param path Path to be checked
* @param operationType Type of operation (READ, POST, PUT, DELETE...)
*/
public static void checkItemExists(final DOMTransactionChain transactionChain,
- final DOMDataReadWriteTransaction rWTransaction,
+ final DOMDataReadWriteTransaction rwTransaction,
final LogicalDatastoreType store, final YangInstanceIdentifier path,
final String operationType) {
- final CheckedFuture<Boolean, ReadFailedException> future = rWTransaction.exists(store, path);
+ final CheckedFuture<Boolean, ReadFailedException> future = rwTransaction.exists(store, path);
final FutureDataFactory<Boolean> response = new FutureDataFactory<>();
FutureCallbackTx.addCallback(future, operationType, response);
if (!response.result) {
// close transaction and reset transaction chain
- rWTransaction.cancel();
+ rwTransaction.cancel();
RestConnectorProvider.resetTransactionChainForAdapaters(transactionChain);
// throw error
* Check if items do NOT already exists at specified {@code path}. Throws {@link RestconfDocumentedException} if
* data already exists.
* @param transactionChain Transaction chain
- * @param rWTransaction Transaction
+ * @param rwTransaction Transaction
* @param store Datastore
* @param path Path to be checked
* @param operationType Type of operation (READ, POST, PUT, DELETE...)
*/
public static void checkItemDoesNotExists(final DOMTransactionChain transactionChain,
- final DOMDataReadWriteTransaction rWTransaction,
+ final DOMDataReadWriteTransaction rwTransaction,
final LogicalDatastoreType store, final YangInstanceIdentifier path,
final String operationType) {
- final CheckedFuture<Boolean, ReadFailedException> future = rWTransaction.exists(store, path);
+ final CheckedFuture<Boolean, ReadFailedException> future = rwTransaction.exists(store, path);
final FutureDataFactory<Boolean> response = new FutureDataFactory<>();
FutureCallbackTx.addCallback(future, operationType, response);
if (response.result) {
// close transaction and reset transaction chain
- rWTransaction.cancel();
+ rwTransaction.cancel();
RestConnectorProvider.resetTransactionChainForAdapaters(transactionChain);
// throw error
package org.opendaylight.restconf.utils.mapping;
/**
- * Util class for constants of mapping node
+ * Util class for constants of mapping node.
*
*/
public final class RestconfMappingNodeConstants {
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
/**
- * Util class for mapping nodes
+ * Util class for mapping nodes.
*
*/
public final class RestconfMappingNodeUtil {
}
/**
- * Map data from modules to {@link NormalizedNode}
+ * Map data from modules to {@link NormalizedNode}.
*
* @param modules
- * - modules for mapping
+ * modules for mapping
* @param ietfYangLibraryModule
- * - ietf-yang-library module
+ * ietf-yang-library module
* @param context
- * - schema context
+ * schema context
* @param moduleSetId
- * - module-set-id of actual set
+ * module-set-id of actual set
* @return mapped data as {@link NormalizedNode}
*/
public static NormalizedNode<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>>
}
/**
- * Map data by the specific module or submodule
+ * Map data by the specific module or submodule.
*
* @param mapBuilder
- * - ordered list builder for children
+ * ordered list builder for children
* @param moduleSch
- * - schema of list for entryMapBuilder
+ * schema of list for entryMapBuilder
* @param isSubmodule
- * - true if module is specified as submodule, false otherwise
+ * true if module is specified as submodule, false otherwise
* @param module
- * - specific module or submodule
+ * specific module or submodule
* @param ietfYangLibraryModule
- * - ietf-yang-library module
+ * ietf-yang-library module
* @param context
- * - schema context
+ * schema context
*/
private static void fillMapByModules(final CollectionNodeBuilder<MapEntryNode, OrderedMapNode> mapBuilder,
final DataSchemaNode moduleSch, final boolean isSubmodule, final Module module,
}
/**
- * Mapping submodules of specific module
+ * Mapping submodules of specific module.
*
* @param module
- * - module with submodules
+ * module with submodules
* @param mapEntryBuilder
- * - mapEntryBuilder of parent for mapping children
+ * mapEntryBuilder of parent for mapping children
* @param ietfYangLibraryModule
- * - ietf-yang-library module
+ * ietf-yang-library module
* @param context
- * - schema context
+ * schema context
*/
private static void addSubmodules(final Module module,
final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder,
}
/**
- * Mapping deviations of specific module
+ * Mapping deviations of specific module.
*
* @param module
- * - module with deviations
+ * module with deviations
* @param mapEntryBuilder
- * - mapEntryBuilder of parent for mapping children
+ * mapEntryBuilder of parent for mapping children
* @param ietfYangLibraryModule
- * - ietf-yang-library module
+ * ietf-yang-library module
* @param context
- * - schema context
+ * schema context
*/
private static void addDeviationList(final Module module,
final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder,
}
/**
- * Mapping features of specific module
+ * Mapping features of specific module.
*
* @param qnameOfFeaturesLeafList
- * - qname of feature leaf-list in ietf-yang-library module
+ * qname of feature leaf-list in ietf-yang-library module
* @param mapEntryBuilder
- * - mapEntryBuilder of parent for mapping children
+ * mapEntryBuilder of parent for mapping children
* @param features
- * - features of specific module
+ * features of specific module
* @param ietfYangLibraryModule
- * - ieat-yang-library module
+ * ieat-yang-library module
*/
private static void addFeatureLeafList(final QName qnameOfFeaturesLeafList,
final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder,
/**
* Mapping common leafs (grouping common-leafs in ietf-yang-library) of
- * specific module
+ * specific module.
*
* @param module
- * - specific module for getting name and revision
+ * specific module for getting name and revision
* @param mapEntryBuilder
- * - mapEntryBuilder of parent for mapping children
+ * mapEntryBuilder of parent for mapping children
* @param ietfYangLibraryModule
- * - ietf-yang-library module
+ * ietf-yang-library module
*/
private static void addCommonLeafs(final Module module,
final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder,
}
/**
- * Mapping data child of grouping module-list by ietf-yang-library
+ * Mapping data child of grouping module-list by ietf-yang-library.
*
* @param specificQName
- * - qname of leaf in module-list grouping
+ * qname of leaf in module-list grouping
* @param mapEntryBuilder
- * - mapEntryBuilder of parent for mapping children
+ * mapEntryBuilder of parent for mapping children
* @param value
- * - value of leaf
+ * value of leaf
* @param ietfYangLibraryModule
- * - ietf-yang-library module
+ * ietf-yang-library module
*/
private static void addChildOfModuleBySpecificModuleOfListChild(final QName specificQName,
final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder,
}
/**
- * Find specific schema in gourping module-lsit
+ * Find specific schema in gourping module-lsit.
*
* @param specificQName
- * - qname of schema
+ * qname of schema
* @param ietfYangLibraryModule
- * - ietf-yang-library module
+ * ietf-yang-library module
* @return schemaNode of specific child
*/
private static DataSchemaNode findSchemaInListOfModulesSchema(final QName specificQName,
}
/**
- * Mapping data child of internal groupings in module-list grouping
+ * Mapping data child of internal groupings in module-list grouping.
*
* @param specifiLeafQName
- * - qnmae of leaf for mapping
+ * qnmae of leaf for mapping
* @param mapEntryBuilder
- * - mapEntryBuilder of parent for mapping children
+ * mapEntryBuilder of parent for mapping children
* @param value
- * - value of leaf
+ * value of leaf
* @param ietfYangLibraryModule
- * - ietf-yang-library module
+ * ietf-yang-library module
*/
private static void addChildOfModuleBySpecificModuleInternal(final QName specifiLeafQName,
final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder,
}
/**
- * Find schema node of leaf by qname in internal groupings of module-list
+ * Find schema node of leaf by qname in internal groupings of module-list.
* grouping
*
* @param qnameOfSchema
- * - qname of leaf
+ * qname of leaf
* @param ietfYangLibraryModule
- * - ietf-yang-library module
+ * ietf-yang-library module
* @return schema node of specific leaf
*/
private static DataSchemaNode findNodeInInternGroupings(final QName qnameOfSchema,
}
/**
- * Mapping childrens of list-module
+ * Mapping childrens of list-module.
*
* @param specifiLeafQName
- * - qname of leaf
+ * qname of leaf
* @param mapEntryBuilder
- * - maptEntryBuilder of parent for mapping children
+ * maptEntryBuilder of parent for mapping children
* @param value
- * - valeu of leaf
+ * valeu of leaf
* @param ietfYangLibraryModule
- * - ietf-yang-library module
+ * ietf-yang-library module
*/
private static void addChildOfModuleBySpecificModule(final QName specifiLeafQName,
final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder,
}
/**
- * Find schema of specific leaf in list-module grouping
+ * Find schema of specific leaf in list-module grouping.
*
* @param qnameOfSchema
- * - qname of leaf
+ * qname of leaf
* @param ietfYangLibraryModule
- * - ietf-yang-library module
+ * ietf-yang-library module
* @return schemaNode of specific leaf
*/
private static DataSchemaNode findNodeInGroupings(final QName qnameOfSchema, final Module ietfYangLibraryModule) {
}
/**
- * Map capabilites by ietf-restconf-monitoring
+ * Map capabilites by ietf-restconf-monitoring.
*
* @param monitoringModule
- * - ietf-restconf-monitoring module
+ * ietf-restconf-monitoring module
* @return mapped capabilites
*/
public static NormalizedNode<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>>
}
/**
- * Map data to leaf-list
+ * Map data to leaf-list.
*
* @param builder
- * - builder of parent for children
+ * builder of parent for children
* @param leafListSchema
+ * leaf list schema
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private static void fillLeafListCapa(final ListNodeBuilder builder, final LeafListSchemaNode leafListSchema) {
}
/**
- * Map value to leaf list entry node
+ * Map value to leaf list entry node.
*
* @param leafListSchema
- * - leaf list schema of leaf list entry
+ * leaf list schema of leaf list entry
* @param value
- * - value of leaf entry
+ * value of leaf entry
* @return entry node
*/
@SuppressWarnings("rawtypes")
}
/**
- * Find specific schema node by qname in parent {@link ContainerSchemaNode}
+ * Find specific schema node by qname in parent {@link ContainerSchemaNode}.
*
* @param parent
- * - schemaNode
+ * schemaNode
* @param childQName
- * - specific qname of child
+ * specific qname of child
* @return schema node of child by qname
*/
private static DataSchemaNode getChildOfCont(final ContainerSchemaNode parent, final QName childQName) {
/**
* Map data of yang notification to normalized node according to
- * ietf-restconf-monitoring
+ * ietf-restconf-monitoring.
*
* @param notifiQName
- * - qname of notification from listener
+ * qname of notification from listener
* @param notifications
- * - list of notifications for find schema of notification by
+ * list of notifications for find schema of notification by
* notifiQName
* @param start
- * - start-time query parameter of notification
+ * start-time query parameter of notification
* @param outputType
- * - output type of notification
+ * output type of notification
* @param uri
- * - location of registered listener for sending data of
+ * location of registered listener for sending data of
* notification
* @param monitoringModule
- * - ietf-restconf-monitoring module
+ * ietf-restconf-monitoring module
* @param existParent
- * - true if data of parent -
+ * true if data of parent -
* ietf-restconf-monitoring:restconf-state/streams - exist in DS
* @return mapped data of notification - map entry node if parent exists,
* container streams with list and map entry node if not
}
/**
- * @param streamEntry
- * @param dataChildByName
- * @param localName
+ * Prepare leaf and fill entry builder.
+ *
+ * @param streamEntry Stream entry
+ * @param leafSchema Leaf schema
+ * @param value Value
*/
private static void prepareLeafAndFillEntryBuilder(
final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamEntry,
/**
* Map data of data change notification to normalized node according to
- * ietf-restconf-monitoring
+ * ietf-restconf-monitoring.
*
* @param path
- * - path of data to listen on
+ * path of data to listen on
* @param start
- * - start-time query parameter of notification
+ * start-time query parameter of notification
* @param outputType
- * - output type of notification
+ * output type of notification
* @param uri
- * - location of registered listener for sending data of
+ * location of registered listener for sending data of
* notification
* @param monitoringModule
- * - ietf-restconf-monitoring module
+ * ietf-restconf-monitoring module
* @param existParent
- * - true if data of parent -
+ * true if data of parent -
* ietf-restconf-monitoring:restconf-state/streams - exist in DS
* @param schemaContext
- * - schemaContext for parsing instance identifier to get schema
+ * schemaContext for parsing instance identifier to get schema
* node of data
* @return mapped data of notification - map entry node if parent exists,
* container streams with list and map entry node if not
package org.opendaylight.restconf.utils.mapping;
/**
- * Util class for mapping entry stream
+ * Util class for mapping entry stream.
*
*/
public final class RestconfMappingStreamConstants {
* All nodes expect of not mixin node are added to current level nodes.
* @param node initial mixin or not-mixin node
* @param level current nodes level
- * @param qName qname of initial node
+ * @param qualifiedName qname of initial node
* @return {@link DataSchemaContextNode}
*/
private static @Nullable DataSchemaContextNode<?> resolveMixinNode(@Nullable final DataSchemaContextNode<?> node,
@Nonnull final Set<QName> level,
- @Nonnull final QName qName) {
+ @Nonnull final QName qualifiedName) {
DataSchemaContextNode<?> currentNode = node;
while (currentNode != null && currentNode.isMixin()) {
- level.add(qName);
- currentNode = currentNode.getChild(qName);
+ level.add(qualifiedName);
+ currentNode = currentNode.getChild(qualifiedName);
}
return currentNode;
import org.slf4j.LoggerFactory;
/**
- * Util class for parsing identifier
- *
+ * Util class for parsing identifier.
*/
public final class ParserIdentifier {
final String mountPointId = pathsIt.next();
final YangInstanceIdentifier mountYangInstanceIdentifier = IdentifierCodec.deserialize(
mountPointId, schemaContext);
- final Optional<DOMMountPoint> mountPoint = mountPointService.get().getMountPoint(mountYangInstanceIdentifier);
+ final Optional<DOMMountPoint> mountPoint =
+ mountPointService.get().getMountPoint(mountYangInstanceIdentifier);
if (!mountPoint.isPresent()) {
throw new RestconfDocumentedException(
final YangInstanceIdentifier deserialize = IdentifierCodec.deserialize(identifier, schemaContext);
final DataSchemaContextNode<?> child = DataSchemaContextTree.from(schemaContext).getChild(deserialize);
- if(child != null){
- return new InstanceIdentifierContext<SchemaNode>(deserialize, child.getDataSchemaNode(), null, schemaContext);
+ if (child != null) {
+ return new InstanceIdentifierContext<SchemaNode>(
+ deserialize, child.getDataSchemaNode(), null, schemaContext);
}
final QName rpcQName = deserialize.getLastPathArgument().getNodeType();
RpcDefinition def = null;
- for (final RpcDefinition rpcDefinition : schemaContext.findModuleByNamespaceAndRevision(rpcQName.getNamespace(), rpcQName.getRevision()).getRpcs()) {
+ for (final RpcDefinition rpcDefinition
+ : schemaContext.findModuleByNamespaceAndRevision(rpcQName.getNamespace(),
+ rpcQName.getRevision()).getRpcs()) {
if (rpcDefinition.getQName().getLocalName().equals(rpcQName.getLocalName())) {
def = rpcDefinition;
break;
}
/**
- * Make {@link String} from {@link YangInstanceIdentifier}
+ * Make {@link String} from {@link YangInstanceIdentifier}.
*
- * @param instanceIdentifier
- * @param schemaContext
- * @return
+ * @param instanceIdentifier Instance identifier
+ * @param schemaContext Schema context
+ * @return Yang instance identifier serialized to String
*/
public static String stringFromYangInstanceIdentifier(final YangInstanceIdentifier instanceIdentifier,
final SchemaContext schemaContext) {
}
/**
- * Make a {@link QName} from identifier
+ * Make a {@link QName} from identifier.
*
* @param identifier
- * - path parameter
+ * path parameter
* @return {@link QName}
*/
public static QName makeQNameFromIdentifier(final String identifier) {
/**
* Parsing {@link Module} module by {@link String} module name and
* {@link Date} revision and from the parsed module create
- * {@link SchemaExportContext}
+ * {@link SchemaExportContext}.
*
* @param schemaContext
- * - {@link SchemaContext}
+ * {@link SchemaContext}
* @param identifier
- * - path parameter
+ * path parameter
* @param domMountPointService
- * - {@link DOMMountPointService}
+ * {@link DOMMountPointService}
* @return {@link SchemaExportContext}
*/
public static SchemaExportContext toSchemaExportContextFromIdentifier(final SchemaContext schemaContext,
/**
* Util class of constants of {@link YangInstanceIdentifierSerializer}
- * and {@link YangInstanceIdentifierDeserializer}
+ * and {@link YangInstanceIdentifierDeserializer}.
*
*/
public final class ParserBuilderConstants {
}
/**
- * Constants for {@link YangInstanceIdentifierSerializer}
+ * Constants for {@link YangInstanceIdentifierSerializer}.
*
*/
public static final class Serializer {
}
/**
- * Constants for {@link YangInstanceIdentifierSerializer}
+ * Constants for {@link YangInstanceIdentifierSerializer}.
*
*/
public static final class Deserializer {
* schema node name.
*
* @param <T>
- * - child of SchemaNode
+ * child of SchemaNode
* @param collection
- * - child of node
+ * child of node
* @param schemaNodeName
- * - schema node name
+ * schema node name
* @return {@link SchemaNode}
*/
public static <T extends SchemaNode> T findSchemaNodeInCollection(final Collection<T> collection,
import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
/**
- * Util class for validations
+ * Util class for validations.
*
*/
public final class RestconfValidation {
* Validation and parsing of revision.
*
* @param revisionDate
- * - iterator
+ * iterator
* @return {@link Date}
*/
public static Date validateAndGetRevision(final Iterator<String> revisionDate) {
* Validation of name.
*
* @param moduleName
- * - iterator
+ * iterator
* @return {@link String}
*/
public static String validateAndGetModulName(final Iterator<String> moduleName) {
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-/**
- * sal-rest-connector org.opendaylight.controller.md.sal.rest.common
- *
- *
- *
- * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
- *
- * Created: Mar 7, 2015
- */
public class TestRestconfUtils {
private static final Logger LOG = LoggerFactory.getLogger(TestRestconfUtils.class);
throw new UnsupportedOperationException("Test utility class");
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
public static SchemaContext loadSchemaContext(final String yangPath, final SchemaContext schemaContext) {
try {
Preconditions.checkArgument(yangPath != null, "Path can not be null.");
throw new AbstractMethodError("Not implemented yet");
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
public static NormalizedNodeContext loadNormalizedContextFromXmlFile(final String pathToInputFile,
final String uri) {
final InstanceIdentifierContext<?> iiContext = ControllerContext.getInstance().toInstanceIdentifier(uri);
+++ /dev/null
-/**
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.sal.rest.impl.draft02.test;
-
-/**
- * sal-rest-connector
- * org.opendaylight.controller.sal.rest.impl.draft02.test
- *
- *
- *
- * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
- *
- * Created: Mar 9, 2015
- */
-public class RestPostOperationTest {
-
-}
import org.opendaylight.netconf.sal.rest.impl.AbstractIdentifierAwareJaxRsProvider;
import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
public abstract class AbstractBodyReaderTest {
- protected final static ControllerContext controllerContext = ControllerContext.getInstance();
+ protected static final ControllerContext CONTROLLER_CONTEXT = ControllerContext.getInstance();
protected final MediaType mediaType;
private static Field uriField;
private static Field requestField;
return TestRestconfUtils.loadSchemaContext(yangPath, schemaContext);
}
- protected static <T extends AbstractIdentifierAwareJaxRsProvider> void mockBodyReader(final String identifier,
- final T normalizedNodeProvider, final boolean isPost) throws Exception {
+ protected static <T extends AbstractIdentifierAwareJaxRsProvider> void mockBodyReader(
+ final String identifier, final T normalizedNodeProvider, final boolean isPost) throws Exception {
final UriInfo uriInfoMock = mock(UriInfo.class);
final MultivaluedMap<String, String> pathParm = new MultivaluedHashMap<>(1);
assertNotNull(nnContext.getInstanceIdentifierContext().getSchemaNode());
}
- protected static void checkPATCHContext(final PATCHContext patchContext) {
+ protected static void checkPatchContext(final PatchContext patchContext) {
assertNotNull(patchContext.getData());
assertNotNull(patchContext.getInstanceIdentifierContext().getInstanceIdentifier());
assertNotNull(patchContext.getInstanceIdentifierContext().getSchemaContext());
assertNotNull(patchContext.getInstanceIdentifierContext().getSchemaNode());
}
- protected static void checkPATCHContextMountPoint(final PATCHContext patchContext) {
- checkPATCHContext(patchContext);
+ protected static void checkPatchContextMountPoint(final PatchContext patchContext) {
+ checkPatchContext(patchContext);
assertNotNull(patchContext.getInstanceIdentifierContext().getMountPoint());
assertNotNull(patchContext.getInstanceIdentifierContext().getMountPoint().getSchemaContext());
}
import com.google.common.base.Optional;
import com.google.common.collect.Sets;
import java.io.File;
-import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URI;
import java.text.ParseException;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
-/**
- * sal-rest-connector
- * org.opendaylight.controller.sal.rest.impl.test.providers
- *
- *
- *
- * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
- *
- * Created: Mar 11, 2015
- */
+
public class TestJsonBodyReader extends AbstractBodyReaderTest {
private final JsonNormalizedNodeBodyReader jsonBodyReader;
}
- public TestJsonBodyReader () throws NoSuchFieldException, SecurityException {
+ public TestJsonBodyReader() throws NoSuchFieldException, SecurityException {
super();
this.jsonBodyReader = new JsonNormalizedNodeBodyReader();
}
}
@BeforeClass
- public static void initialization() throws NoSuchFieldException, SecurityException, FileNotFoundException, SourceException, ReactorException {
+ public static void initialization()
+ throws Exception {
final Collection<File> testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang");
testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc"));
schemaContext = YangParserTestUtils.parseYangSources(testFiles);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
final QName augmentChoice1QName = QName.create(augmentModule.getQNameModule(), "augment-choice1");
final QName augmentChoice2QName = QName.create(augmentChoice1QName, "augment-choice2");
final QName containerQName = QName.create(augmentChoice1QName, "case-choice-case-container1");
- final YangInstanceIdentifier.AugmentationIdentifier augChoice1II = new YangInstanceIdentifier.AugmentationIdentifier(
- Sets.newHashSet(augmentChoice1QName));
- final YangInstanceIdentifier.AugmentationIdentifier augChoice2II = new YangInstanceIdentifier.AugmentationIdentifier(
- Sets.newHashSet(augmentChoice2QName));
+ final YangInstanceIdentifier.AugmentationIdentifier augChoice1II =
+ new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(augmentChoice1QName));
+ final YangInstanceIdentifier.AugmentationIdentifier augChoice2II =
+ new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(augmentChoice2QName));
final YangInstanceIdentifier dataII = YangInstanceIdentifier.of(dataSchemaNode.getQName())
.node(augChoice1II).node(augmentChoice1QName).node(augChoice2II).node(augmentChoice2QName)
.node(containerQName);
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
-/**
- * sal-rest-connector org.opendaylight.controller.sal.rest.impl.test.providers
- *
- *
- *
- * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
- *
- * Created: Mar 11, 2015
- */
public class TestJsonBodyReaderMountPoint extends AbstractBodyReaderTest {
private final JsonNormalizedNodeBodyReader jsonBodyReader;
.thenReturn(Optional.of(mountInstance));
ControllerContext.getInstance().setMountService(mockMountService);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
protected void checkExpectValueNormalizeNodeContext(
final DataSchemaNode dataSchemaNode,
- final NormalizedNodeContext nnContext, final QName qName) {
+ final NormalizedNodeContext nnContext, final QName qualifiedName) {
YangInstanceIdentifier dataNodeIdent = YangInstanceIdentifier
.of(dataSchemaNode.getQName());
final DOMMountPoint mountPoint = nnContext
.getSchemaContext().getDataChildByName(
dataSchemaNode.getQName());
assertNotNull(mountDataSchemaNode);
- if ((qName != null) && (dataSchemaNode instanceof DataNodeContainer)) {
+ if ((qualifiedName != null) && (dataSchemaNode instanceof DataNodeContainer)) {
final DataSchemaNode child = ((DataNodeContainer) dataSchemaNode)
- .getDataChildByName(qName);
+ .getDataChildByName(qualifiedName);
dataNodeIdent = YangInstanceIdentifier.builder(dataNodeIdent)
.node(child.getQName()).build();
assertTrue(nnContext.getInstanceIdentifierContext().getSchemaNode()
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
-/**
- * sal-rest-connector org.opendaylight.controller.sal.rest.impl.test.providers
- *
- *
- *
- * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
- *
- * Created: Mar 12, 2015
- */
public class TestJsonBodyWriter extends AbstractBodyReaderTest {
private final JsonNormalizedNodeBodyReader jsonBodyReader;
final Collection<File> testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang");
testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc"));
schemaContext = YangParserTestUtils.parseYangSources(testFiles);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
import javax.ws.rs.core.MediaType;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.opendaylight.netconf.sal.rest.impl.JsonToPATCHBodyReader;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
+import org.opendaylight.netconf.sal.rest.impl.JsonToPatchBodyReader;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-public class TestJsonPATCHBodyReader extends AbstractBodyReaderTest {
+public class TestJsonPatchBodyReader extends AbstractBodyReaderTest {
- private final JsonToPATCHBodyReader jsonPATCHBodyReader;
+ private final JsonToPatchBodyReader jsonToPatchBodyReader;
private static SchemaContext schemaContext;
- public TestJsonPATCHBodyReader() throws NoSuchFieldException, SecurityException {
+ public TestJsonPatchBodyReader() throws NoSuchFieldException, SecurityException {
super();
- jsonPATCHBodyReader = new JsonToPATCHBodyReader();
+ jsonToPatchBodyReader = new JsonToPatchBodyReader();
}
@Override
@BeforeClass
public static void initialization() {
schemaContext = schemaContextLoader("/instanceidentifier/yang", schemaContext);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
- public void modulePATCHDataTest() throws Exception {
+ public void modulePatchDataTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont/my-list1/leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHdata.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
/**
- * Test of successful PATCH consisting of create and delete PATCH operations.
+ * Test of successful Patch consisting of create and delete Patch operations.
*/
@Test
- public void modulePATCHCreateAndDeleteTest() throws Exception {
+ public void modulePatchCreateAndDeleteTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont/my-list1/leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHdataCreateAndDelete.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
/**
- * Test trying to use PATCH create operation which requires value without value. Test should fail with
+ * Test trying to use Patch create operation which requires value without value. Test should fail with
* {@link RestconfDocumentedException} with error code 400.
*/
@Test
- public void modulePATCHValueMissingNegativeTest() throws Exception {
+ public void modulePatchValueMissingNegativeTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont/my-list1/leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHdataValueMissing.json");
try {
- jsonPATCHBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
+ jsonToPatchBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
fail("Test should return error 400 due to missing value node when attempt to invoke create operation");
} catch (final RestconfDocumentedException e) {
assertEquals("Error code 400 expected", 400, e.getErrors().get(0).getErrorTag().getStatusCode());
}
/**
- * Test trying to use value with PATCH delete operation which does not support value. Test should fail with
+ * Test trying to use value with Patch delete operation which does not support value. Test should fail with
* {@link RestconfDocumentedException} with error code 400.
*/
@Test
- public void modulePATCHValueNotSupportedNegativeTest() throws Exception {
+ public void modulePatchValueNotSupportedNegativeTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont/my-list1/leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHdataValueNotSupported.json");
try {
- jsonPATCHBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
+ jsonToPatchBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
fail("Test should return error 400 due to present value node when attempt to invoke delete operation");
} catch (final RestconfDocumentedException e) {
assertEquals("Error code 400 expected", 400, e.getErrors().get(0).getErrorTag().getStatusCode());
}
/**
- * Test using PATCH when target is completely specified in request URI and thus target leaf contains only '/' sign.
+ * Test using Patch when target is completely specified in request URI and thus target leaf contains only '/' sign.
*/
@Test
- public void modulePATCHCompleteTargetInURITest() throws Exception {
+ public void modulePatchCompleteTargetInURITest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHdataCompleteTargetInURI.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
/**
- * Test of Yang PATCH merge operation on list. Test consists of two edit operations - replace and merge.
+ * Test of Yang Patch merge operation on list. Test consists of two edit operations - replace and merge.
*/
@Test
- public void modulePATCHMergeOperationOnListTest() throws Exception {
+ public void modulePatchMergeOperationOnListTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont/my-list1/leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHMergeOperationOnList.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
/**
- * Test of Yang PATCH merge operation on container. Test consists of two edit operations - create and merge.
+ * Test of Yang Patch merge operation on container. Test consists of two edit operations - create and merge.
*/
@Test
- public void modulePATCHMergeOperationOnContainerTest() throws Exception {
+ public void modulePatchMergeOperationOnContainerTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHMergeOperationOnContainer.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
/**
- * Test reading simple leaf value
+ * Test reading simple leaf value.
*/
@Test
- public void modulePATCHSimpleLeafValueTest() throws Exception {
+ public void modulePatchSimpleLeafValueTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont/my-list1/leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHSimpleLeafValue.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
}
import org.junit.Test;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
-import org.opendaylight.netconf.sal.rest.impl.JsonToPATCHBodyReader;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
+import org.opendaylight.netconf.sal.rest.impl.JsonToPatchBodyReader;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-public class TestJsonPATCHBodyReaderMountPoint extends AbstractBodyReaderTest {
+public class TestJsonPatchBodyReaderMountPoint extends AbstractBodyReaderTest {
- private final JsonToPATCHBodyReader jsonPATCHBodyReader;
+ private final JsonToPatchBodyReader jsonToPatchBodyReader;
private static SchemaContext schemaContext;
private static final String MOUNT_POINT = "instance-identifier-module:cont/yang-ext:mount";
- public TestJsonPATCHBodyReaderMountPoint() throws NoSuchFieldException, SecurityException {
+ public TestJsonPatchBodyReaderMountPoint() throws NoSuchFieldException, SecurityException {
super();
- jsonPATCHBodyReader = new JsonToPATCHBodyReader();
+ jsonToPatchBodyReader = new JsonToPatchBodyReader();
}
@Override
when(mockMountPointService.getMountPoint(any(YangInstanceIdentifier.class)))
.thenReturn(Optional.of(mockMountPoint));
- controllerContext.setMountService(mockMountPointService);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setMountService(mockMountPointService);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
- public void modulePATCHDataTest() throws Exception {
+ public void modulePatchDataTest() throws Exception {
final String uri = MOUNT_POINT + "/instance-identifier-patch-module:patch-cont/my-list1/leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHdata.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContextMountPoint(returnValue);
+ checkPatchContextMountPoint(returnValue);
}
/**
- * Test of successful PATCH consisting of create and delete PATCH operations.
+ * Test of successful Patch consisting of create and delete Patch operations.
*/
@Test
- public void modulePATCHCreateAndDeleteTest() throws Exception {
+ public void modulePatchCreateAndDeleteTest() throws Exception {
final String uri = MOUNT_POINT + "/instance-identifier-patch-module:patch-cont/my-list1/leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHdataCreateAndDelete.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContextMountPoint(returnValue);
+ checkPatchContextMountPoint(returnValue);
}
/**
- * Test trying to use PATCH create operation which requires value without value. Test should fail with
+ * Test trying to use Patch create operation which requires value without value. Test should fail with
* {@link RestconfDocumentedException} with error code 400.
*/
@Test
- public void modulePATCHValueMissingNegativeTest() throws Exception {
+ public void modulePatchValueMissingNegativeTest() throws Exception {
final String uri = MOUNT_POINT + "/instance-identifier-patch-module:patch-cont/my-list1/leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHdataValueMissing.json");
try {
- jsonPATCHBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
+ jsonToPatchBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
fail("Test should return error 400 due to missing value node when attempt to invoke create operation");
} catch (final RestconfDocumentedException e) {
assertEquals("Error code 400 expected", 400, e.getErrors().get(0).getErrorTag().getStatusCode());
}
/**
- * Test trying to use value with PATCH delete operation which does not support value. Test should fail with
+ * Test trying to use value with Patch delete operation which does not support value. Test should fail with
* {@link RestconfDocumentedException} with error code 400.
*/
@Test
- public void modulePATCHValueNotSupportedNegativeTest() throws Exception {
+ public void modulePatchValueNotSupportedNegativeTest() throws Exception {
final String uri = MOUNT_POINT + "/instance-identifier-patch-module:patch-cont/my-list1/leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHdataValueNotSupported.json");
try {
- jsonPATCHBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
+ jsonToPatchBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
fail("Test should return error 400 due to present value node when attempt to invoke delete operation");
} catch (final RestconfDocumentedException e) {
assertEquals("Error code 400 expected", 400, e.getErrors().get(0).getErrorTag().getStatusCode());
}
/**
- * Test using PATCH when target is completely specified in request URI and thus target leaf contains only '/' sign.
+ * Test using Patch when target is completely specified in request URI and thus target leaf contains only '/' sign.
*/
@Test
- public void modulePATCHCompleteTargetInURITest() throws Exception {
+ public void modulePatchCompleteTargetInURITest() throws Exception {
final String uri = MOUNT_POINT + "/instance-identifier-patch-module:patch-cont";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHdataCompleteTargetInURI.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContextMountPoint(returnValue);
+ checkPatchContextMountPoint(returnValue);
}
/**
- * Test of Yang PATCH merge operation on list. Test consists of two edit operations - replace and merge.
+ * Test of Yang Patch merge operation on list. Test consists of two edit operations - replace and merge.
*/
@Test
- public void modulePATCHMergeOperationOnListTest() throws Exception {
+ public void modulePatchMergeOperationOnListTest() throws Exception {
final String uri = MOUNT_POINT + "/instance-identifier-patch-module:patch-cont/my-list1/leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHMergeOperationOnList.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContextMountPoint(returnValue);
+ checkPatchContextMountPoint(returnValue);
}
/**
- * Test of Yang PATCH merge operation on container. Test consists of two edit operations - create and merge.
+ * Test of Yang Patch merge operation on container. Test consists of two edit operations - create and merge.
*/
@Test
- public void modulePATCHMergeOperationOnContainerTest() throws Exception {
+ public void modulePatchMergeOperationOnContainerTest() throws Exception {
final String uri = MOUNT_POINT + "/instance-identifier-patch-module:patch-cont";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHMergeOperationOnContainer.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContextMountPoint(returnValue);
+ checkPatchContextMountPoint(returnValue);
}
/**
- * Test reading simple leaf value
+ * Test reading simple leaf value.
*/
@Test
- public void modulePATCHSimpleLeafValueTest() throws Exception {
+ public void modulePatchSimpleLeafValueTest() throws Exception {
final String uri = MOUNT_POINT + "/instance-identifier-patch-module:patch-cont/my-list1/leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHSimpleLeafValue.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
}
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
-/**
- * sal-rest-connector
- * org.opendaylight.controller.sal.rest.impl.test.providers
- *
- *
- *
- * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
- *
- * Created: Mar 7, 2015
- */
public class TestXmlBodyReader extends AbstractBodyReaderTest {
private final XmlNormalizedNodeBodyReader xmlBodyReader;
}
}
- public TestXmlBodyReader () throws NoSuchFieldException, SecurityException {
+ public TestXmlBodyReader() throws NoSuchFieldException, SecurityException {
super();
this.xmlBodyReader = new XmlNormalizedNodeBodyReader();
}
final Collection<File> testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang");
testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc"));
schemaContext = YangParserTestUtils.parseYangSources(testFiles);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
final QName augmentChoice1QName = QName.create(augmentModule.getQNameModule(), "augment-choice1");
final QName augmentChoice2QName = QName.create(augmentChoice1QName, "augment-choice2");
final QName containerQName = QName.create(augmentChoice1QName, "case-choice-case-container1");
- final YangInstanceIdentifier.AugmentationIdentifier augChoice1II = new YangInstanceIdentifier.AugmentationIdentifier(
- Sets.newHashSet(augmentChoice1QName));
- final YangInstanceIdentifier.AugmentationIdentifier augChoice2II = new YangInstanceIdentifier.AugmentationIdentifier(
- Sets.newHashSet(augmentChoice2QName));
+ final YangInstanceIdentifier.AugmentationIdentifier augChoice1II =
+ new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(augmentChoice1QName));
+ final YangInstanceIdentifier.AugmentationIdentifier augChoice2II =
+ new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(augmentChoice2QName));
final YangInstanceIdentifier dataII = YangInstanceIdentifier.of(dataSchemaNode.getQName())
.node(augChoice1II).node(augmentChoice1QName).node(augChoice2II).node(augmentChoice2QName)
.node(containerQName);
.getLastPathArgument());
assertTrue(contDataNodePotential.isPresent());
final ContainerNode contDataNode = (ContainerNode) contDataNodePotential.get();
- final YangInstanceIdentifier yangLeaf = YangInstanceIdentifier.of(QName.create(contDataNode.getNodeType(), "lf"));
+ final YangInstanceIdentifier yangLeaf =
+ YangInstanceIdentifier.of(QName.create(contDataNode.getNodeType(), "lf"));
final Optional<DataContainerChild<? extends PathArgument, ?>> leafDataNode = contDataNode.getChild(yangLeaf
.getLastPathArgument());
assertTrue(leafDataNode.isPresent());
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
-/**
- * sal-rest-connector org.opendaylight.controller.sal.rest.impl.test.providers
- *
- *
- *
- * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
- *
- * Created: Mar 9, 2015
- */
public class TestXmlBodyReaderMountPoint extends AbstractBodyReaderTest {
private final XmlNormalizedNodeBodyReader xmlBodyReader;
private static SchemaContext schemaContext;
.thenReturn(Optional.of(mountInstance));
ControllerContext.getInstance().setMountService(mockMountService);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
.getLastPathArgument());
assertTrue(contDataNodePotential.isPresent());
final ContainerNode contDataNode = (ContainerNode) contDataNodePotential.get();
- final YangInstanceIdentifier yangLeaf = YangInstanceIdentifier.of(QName.create(contDataNode.getNodeType(), "lf"));
+ final YangInstanceIdentifier yangLeaf =
+ YangInstanceIdentifier.of(QName.create(contDataNode.getNodeType(), "lf"));
final Optional<DataContainerChild<? extends PathArgument, ?>> leafDataNode = contDataNode.getChild(yangLeaf
.getLastPathArgument());
assertTrue(leafDataNode.isPresent());
protected void checkExpectValueNormalizeNodeContext(
final DataSchemaNode dataSchemaNode,
- final NormalizedNodeContext nnContext, final QName qName) {
+ final NormalizedNodeContext nnContext, final QName qualifiedName) {
YangInstanceIdentifier dataNodeIdent = YangInstanceIdentifier
.of(dataSchemaNode.getQName());
final DOMMountPoint mountPoint = nnContext
.getSchemaContext().getDataChildByName(
dataSchemaNode.getQName());
assertNotNull(mountDataSchemaNode);
- if ((qName != null) && (dataSchemaNode instanceof DataNodeContainer)) {
+ if ((qualifiedName != null) && (dataSchemaNode instanceof DataNodeContainer)) {
final DataSchemaNode child = ((DataNodeContainer) dataSchemaNode)
- .getDataChildByName(qName);
+ .getDataChildByName(qualifiedName);
dataNodeIdent = YangInstanceIdentifier.builder(dataNodeIdent)
.node(child.getQName()).build();
assertTrue(nnContext.getInstanceIdentifierContext().getSchemaNode()
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
-/**
- * sal-rest-connector org.opendaylight.controller.sal.rest.impl.test.providers
- *
- *
- *
- * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
- *
- * Created: Mar 12, 2015
- */
public class TestXmlBodyWriter extends AbstractBodyReaderTest {
private final NormalizedNodeXmlBodyWriter xmlBodyWriter;
final Collection<File> testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang");
testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc"));
schemaContext = YangParserTestUtils.parseYangSources(testFiles);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
import javax.ws.rs.core.MediaType;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.opendaylight.netconf.sal.rest.impl.XmlToPATCHBodyReader;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
+import org.opendaylight.netconf.sal.rest.impl.XmlToPatchBodyReader;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-public class TestXmlPATCHBodyReader extends AbstractBodyReaderTest {
+public class TestXmlPatchBodyReader extends AbstractBodyReaderTest {
- private final XmlToPATCHBodyReader xmlPATCHBodyReader;
+ private final XmlToPatchBodyReader xmlToPatchBodyReader;
private static SchemaContext schemaContext;
- public TestXmlPATCHBodyReader() throws NoSuchFieldException, SecurityException {
+ public TestXmlPatchBodyReader() throws NoSuchFieldException, SecurityException {
super();
- xmlPATCHBodyReader = new XmlToPATCHBodyReader();
+ xmlToPatchBodyReader = new XmlToPatchBodyReader();
}
@Override
@BeforeClass
public static void initialization() throws NoSuchFieldException, SecurityException {
schemaContext = schemaContextLoader("/instanceidentifier/yang", schemaContext);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
public void moduleDataTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont/my-list1/leaf1";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdata.xml");
- final PATCHContext returnValue = xmlPATCHBodyReader
+ final PatchContext returnValue = xmlToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
/**
- * Test trying to use PATCH create operation which requires value without value. Error code 400 should be returned.
+ * Test trying to use Patch create operation which requires value without value. Error code 400 should be returned.
*/
@Test
public void moduleDataValueMissingNegativeTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont/my-list1/leaf1";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataValueMissing.xml");
try {
- xmlPATCHBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
+ xmlToPatchBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
fail("Test should return error 400 due to missing value node when attempt to invoke create operation");
} catch (final RestconfDocumentedException e) {
assertEquals("Error code 400 expected", 400, e.getErrors().get(0).getErrorTag().getStatusCode());
}
/**
- * Test trying to use value with PATCH delete operation which does not support value. Error code 400 should be
+ * Test trying to use value with Patch delete operation which does not support value. Error code 400 should be
* returned.
*/
@Test
public void moduleDataNotValueNotSupportedNegativeTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont/my-list1/leaf1";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataValueNotSupported.xml");
try {
- xmlPATCHBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
+ xmlToPatchBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
fail("Test should return error 400 due to present value node when attempt to invoke delete operation");
} catch (final RestconfDocumentedException e) {
assertEquals("Error code 400 expected", 400, e.getErrors().get(0).getErrorTag().getStatusCode());
}
/**
- * Test of Yang PATCH with absolute target path.
+ * Test of Yang Patch with absolute target path.
*/
@Test
public void moduleDataAbsoluteTargetPathTest() throws Exception {
final String uri = "";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataAbsoluteTargetPath.xml");
- final PATCHContext returnValue = xmlPATCHBodyReader
+ final PatchContext returnValue = xmlToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
/**
- * Test using PATCH when target is completely specified in request URI and thus target leaf contains only '/' sign.
+ * Test using Patch when target is completely specified in request URI and thus target leaf contains only '/' sign.
*/
@Test
- public void modulePATCHCompleteTargetInURITest() throws Exception {
+ public void modulePatchCompleteTargetInURITest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataCompleteTargetInURI.xml");
- final PATCHContext returnValue = xmlPATCHBodyReader
+ final PatchContext returnValue = xmlToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
/**
- * Test of Yang PATCH merge operation on list. Test consists of two edit operations - replace and merge.
+ * Test of Yang Patch merge operation on list. Test consists of two edit operations - replace and merge.
*/
@Test
public void moduleDataMergeOperationOnListTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont/my-list1/leaf1";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataMergeOperationOnList.xml");
- final PATCHContext returnValue = xmlPATCHBodyReader
+ final PatchContext returnValue = xmlToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
/**
- * Test of Yang PATCH merge operation on container. Test consists of two edit operations - create and merge.
+ * Test of Yang Patch merge operation on container. Test consists of two edit operations - create and merge.
*/
@Test
public void moduleDataMergeOperationOnContainerTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataMergeOperationOnContainer.xml");
- final PATCHContext returnValue = xmlPATCHBodyReader
+ final PatchContext returnValue = xmlToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
}
import org.junit.Test;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
-import org.opendaylight.netconf.sal.rest.impl.XmlToPATCHBodyReader;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
+import org.opendaylight.netconf.sal.rest.impl.XmlToPatchBodyReader;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-public class TestXmlPATCHBodyReaderMountPoint extends AbstractBodyReaderTest {
+public class TestXmlPatchBodyReaderMountPoint extends AbstractBodyReaderTest {
- private final XmlToPATCHBodyReader xmlPATCHBodyReader;
+ private final XmlToPatchBodyReader xmlToPatchBodyReader;
private static SchemaContext schemaContext;
private static final String MOUNT_POINT = "instance-identifier-module:cont/yang-ext:mount";
- public TestXmlPATCHBodyReaderMountPoint() throws NoSuchFieldException, SecurityException {
+ public TestXmlPatchBodyReaderMountPoint() throws NoSuchFieldException, SecurityException {
super();
- xmlPATCHBodyReader = new XmlToPATCHBodyReader();
+ xmlToPatchBodyReader = new XmlToPatchBodyReader();
}
@Override
when(mockMountPointService.getMountPoint(any(YangInstanceIdentifier.class)))
.thenReturn(Optional.of(mockMountPoint));
- controllerContext.setMountService(mockMountPointService);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setMountService(mockMountPointService);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
public void moduleDataTest() throws Exception {
final String uri = MOUNT_POINT + "/instance-identifier-patch-module:patch-cont/my-list1/leaf1";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdata.xml");
- final PATCHContext returnValue = xmlPATCHBodyReader
+ final PatchContext returnValue = xmlToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContextMountPoint(returnValue);
+ checkPatchContextMountPoint(returnValue);
}
/**
- * Test trying to use PATCH create operation which requires value without value. Error code 400 should be returned.
+ * Test trying to use Patch create operation which requires value without value. Error code 400 should be returned.
*/
@Test
public void moduleDataValueMissingNegativeTest() throws Exception {
final String uri = MOUNT_POINT + "/instance-identifier-patch-module:patch-cont/my-list1/leaf1";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataValueMissing.xml");
try {
- xmlPATCHBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
+ xmlToPatchBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
fail("Test should return error 400 due to missing value node when attempt to invoke create operation");
} catch (final RestconfDocumentedException e) {
assertEquals("Error code 400 expected", 400, e.getErrors().get(0).getErrorTag().getStatusCode());
}
/**
- * Test trying to use value with PATCH delete operation which does not support value. Error code 400 should be
+ * Test trying to use value with Patch delete operation which does not support value. Error code 400 should be
* returned.
*/
@Test
public void moduleDataNotValueNotSupportedNegativeTest() throws Exception {
final String uri = MOUNT_POINT + "/instance-identifier-patch-module:patch-cont/my-list1/leaf1";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataValueNotSupported.xml");
try {
- xmlPATCHBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
+ xmlToPatchBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
fail("Test should return error 400 due to present value node when attempt to invoke delete operation");
} catch (final RestconfDocumentedException e) {
assertEquals("Error code 400 expected", 400, e.getErrors().get(0).getErrorTag().getStatusCode());
}
/**
- * Test of Yang PATCH with absolute target path.
+ * Test of Yang Patch with absolute target path.
*/
@Test
public void moduleDataAbsoluteTargetPathTest() throws Exception {
final String uri = MOUNT_POINT;
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataAbsoluteTargetPath.xml");
- final PATCHContext returnValue = xmlPATCHBodyReader
+ final PatchContext returnValue = xmlToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContextMountPoint(returnValue);
+ checkPatchContextMountPoint(returnValue);
}
/**
- * Test using PATCH when target is completely specified in request URI and thus target leaf contains only '/' sign.
+ * Test using Patch when target is completely specified in request URI and thus target leaf contains only '/' sign.
*/
@Test
- public void modulePATCHCompleteTargetInURITest() throws Exception {
+ public void modulePatchCompleteTargetInURITest() throws Exception {
final String uri = MOUNT_POINT + "/instance-identifier-patch-module:patch-cont";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataCompleteTargetInURI.xml");
- final PATCHContext returnValue = xmlPATCHBodyReader
+ final PatchContext returnValue = xmlToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContextMountPoint(returnValue);
+ checkPatchContextMountPoint(returnValue);
}
/**
- * Test of Yang PATCH merge operation on list. Test consists of two edit operations - replace and merge.
+ * Test of Yang Patch merge operation on list. Test consists of two edit operations - replace and merge.
*/
@Test
public void moduleDataMergeOperationOnListTest() throws Exception {
final String uri = MOUNT_POINT + "/instance-identifier-patch-module:patch-cont/my-list1/leaf1";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataMergeOperationOnList.xml");
- final PATCHContext returnValue = xmlPATCHBodyReader
+ final PatchContext returnValue = xmlToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContextMountPoint(returnValue);
+ checkPatchContextMountPoint(returnValue);
}
/**
- * Test of Yang PATCH merge operation on container. Test consists of two edit operations - create and merge.
+ * Test of Yang Patch merge operation on container. Test consists of two edit operations - create and merge.
*/
@Test
public void moduleDataMergeOperationOnContainerTest() throws Exception {
final String uri = MOUNT_POINT + "/instance-identifier-patch-module:patch-cont";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataMergeOperationOnContainer.xml");
- final PATCHContext returnValue = xmlPATCHBodyReader
+ final PatchContext returnValue = xmlToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContextMountPoint(returnValue);
+ checkPatchContextMountPoint(returnValue);
}
}
public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader {
- static abstract class LeafVerifier {
+ abstract static class LeafVerifier {
Object expectedValue;
JsonToken expectedToken;
static class BooleanVerifier extends LeafVerifier {
- public BooleanVerifier(final boolean expected) {
+ BooleanVerifier(final boolean expected) {
super(expected, JsonToken.BOOLEAN);
}
static class NumberVerifier extends LeafVerifier {
- public NumberVerifier(final Number expected) {
+ NumberVerifier(final Number expected) {
super(expected, JsonToken.NUMBER);
}
reader.endObject();
}
- void verifyLeaf(final JsonReader reader, final String parent, final String name, final String value) throws IOException {
+ void verifyLeaf(final JsonReader reader, final String parent, final String name,
+ final String value) throws IOException {
final String nextName = reader.nextName();
assertEquals("Json reader child key for " + parent, name, nextName);
assertEquals("Json token type for key " + parent, JsonToken.STRING, reader.peek());
assertNull("Error during reading Json output: " + exception, exception);
}
- private static void jsonReadCont(final JsonReader jReader) throws IOException {
- jReader.beginObject();
- assertNotNull("cont1 is missing.", jReader.hasNext());
+ private static void jsonReadCont(final JsonReader jsonReader) throws IOException {
+ jsonReader.beginObject();
+ assertNotNull("cont1 is missing.", jsonReader.hasNext());
// Cont dataFromJson = new Cont(jReader.nextName());
- jReader.nextName();
- jsonReadContElements(jReader);
+ jsonReader.nextName();
+ jsonReadContElements(jsonReader);
- assertFalse("cont shouldn't have other element.", jReader.hasNext());
- jReader.endObject();
+ assertFalse("cont shouldn't have other element.", jsonReader.hasNext());
+ jsonReader.endObject();
// return dataFromJson;
}
- private static void jsonReadContElements(final JsonReader jReader) throws IOException {
- jReader.beginObject();
+ private static void jsonReadContElements(final JsonReader jsonReader) throws IOException {
+ jsonReader.beginObject();
final Map<String, LeafVerifier> expectedMap = Maps.newHashMap();
expectedMap.put("lfnint8Min", new NumberVerifier(Integer.valueOf(-128)));
expectedMap.put("simple-any", new StringVerifier("simple"));
expectedMap.put("empty-any", new StringVerifier(""));
- while (jReader.hasNext()) {
- final String keyName = jReader.nextName();
- final JsonToken peek = jReader.peek();
+ while (jsonReader.hasNext()) {
+ final String keyName = jsonReader.nextName();
+ final JsonToken peek = jsonReader.peek();
final LeafVerifier verifier = expectedMap.remove(keyName);
assertNotNull("Found unexpected leaf: " + keyName, verifier);
assertEquals("Json token type for key " + keyName, expToken, peek);
}
- verifier.verify(jReader, keyName);
+ verifier.verify(jsonReader, keyName);
}
if (!expectedMap.isEmpty()) {
fail("Missing leaf nodes in Json output: " + expectedMap.keySet());
}
- jReader.endObject();
+ jsonReader.endObject();
}
}
/**
* Tests whether no exception is raised if number and values of keys in URI
- * and payload are equal
+ * and payload are equal.
*/
@Test
@Ignore
* Tests whether an exception is raised if key values in URI and payload are
* different.
*
+ * <p>
* The exception should be raised from validation method
* {@code RestconfImpl#validateListEqualityOfListInDataAndUri}
*/
* Tests whether an exception is raised if URI contains less key values then
* payload.
*
+ * <p>
* The exception is raised during {@code InstanceIdentifier} instance is
* built from URI
*/
* Tests whether an exception is raised if URI contains more key values then
* payload.
*
+ * <p>
* The exception should be raised from validation method
* {@code RestconfImpl#validateListEqualityOfListInDataAndUri}
*/
}
}
- private static void verifyException(final RestconfDocumentedException e, final ErrorType errorType,
- final ErrorTag errorTag) {
- final List<RestconfError> errors = e.getErrors();
+ private static void verifyException(final RestconfDocumentedException restDocumentedException,
+ final ErrorType errorType, final ErrorTag errorTag) {
+ final List<RestconfError> errors = restDocumentedException.getErrors();
assertEquals("getErrors() size", 1, errors.size());
assertEquals("RestconfError getErrorType()", errorType, errors.get(0).getErrorType());
assertEquals("RestconfError getErrorTag()", errorTag, errors.get(0).getErrorTag());
public void putListDataTest(final String uriKey1, final String uriKey2, final String payloadKey1,
final Short payloadKey2) {
- final QName lstWithCompositeKey = QName.create(TEST_MODULE_NS_STRING, TEST_MODULE_REVISION, "lst-with-composite-key");
+ final QName lstWithCompositeKey =
+ QName.create(TEST_MODULE_NS_STRING, TEST_MODULE_REVISION, "lst-with-composite-key");
final QName key1 = QName.create(TEST_MODULE_NS_STRING, TEST_MODULE_REVISION, "key1");
final QName key2 = QName.create(TEST_MODULE_NS_STRING, TEST_MODULE_REVISION, "key2");
public static void initialize() {
schemaContext = schemaContextLoader("/json-to-nn/identityref",
schemaContext);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
public static void initialize() {
schemaContext = schemaContextLoader("/json-to-nn/leafref",
schemaContext);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class JsonToNnTest extends AbstractBodyReaderTest {
+ private static final Logger LOG = LoggerFactory.getLogger(AbstractBodyReaderTest.class);
+
private JsonNormalizedNodeBodyReader jsonBodyReader;
private SchemaContext schemaContext;
public static void initialize(final String path, SchemaContext schemaContext) {
schemaContext = schemaContextLoader(path, schemaContext);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
}
assertNotNull(exception);
assertEquals(
- "Error parsing input: Schema node with name cont wasn't found under (urn:ietf:params:xml:ns:netconf:base:1.0)data.",
+ "Error parsing input: Schema node with name cont wasn't found under "
+ + "(urn:ietf:params:xml:ns:netconf:base:1.0)data.",
exception.getErrors().get(0).getErrorMessage());
inputStream = this.getClass().getResourceAsStream(
}
assertNotNull(exception);
assertEquals(
- "Error parsing input: Schema node with name lst1 wasn't found under (urn:ietf:params:xml:ns:netconf:base:1.0)data.",
+ "Error parsing input: Schema node with name lst1 wasn't found under "
+ + "(urn:ietf:params:xml:ns:netconf:base:1.0)data.",
exception.getErrors().get(0).getErrorMessage());
inputStream = this.getClass().getResourceAsStream(
}
assertNotNull(exception);
assertEquals(
- "Error parsing input: Schema node with name lf wasn't found under (urn:ietf:params:xml:ns:netconf:base:1.0)data.",
+ "Error parsing input: Schema node with name lf wasn't found under "
+ + "(urn:ietf:params:xml:ns:netconf:base:1.0)data.",
exception.getErrors().get(0).getErrorMessage());
assertEquals(3, countExceptions);
}
inputStream);
fail("NormalizedNodeContext should not be create because of different namespace");
} catch (final RestconfDocumentedException e) {
+ LOG.warn("Read from InputStream failed. Message: {}. Status: {}", e.getMessage(), e.getStatus());
}
verifyNormaluizedNodeContext(normalizedNodeContext, "lst");
mockBodyReader(uri, this.jsonBodyReader, false);
} catch (NoSuchFieldException | SecurityException
| IllegalArgumentException | IllegalAccessException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
+ LOG.warn("Operation failed due to: {}", e.getMessage());
}
final InputStream inputStream = this.getClass().getResourceAsStream(jsonPath);
this.mediaType, null, inputStream);
} catch (WebApplicationException | IOException e) {
// TODO Auto-generated catch block
- e.printStackTrace();
}
return normalizedNodeContext;
} catch (final RestconfDocumentedException e) {
exception = e;
}
- System.out.println(exception.getErrors().get(0).getErrorMessage());
+ LOG.info(exception.getErrors().get(0).getErrorMessage());
assertTrue(exception.getErrors().get(0).getErrorMessage()
.contains("is not a simple type"));
@BeforeClass
public static void initialization() {
schemaContext = schemaContextLoader("/nn-to-json/choice", schemaContext);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
/**
}
/**
- * Test when element from no first case is used
+ * Test when element from no first case is used.
*/
@Test
public void nodeSchemasNotInFirstCase() throws Exception {
}
/**
- * Test when element in case is list
+ * Test when element in case is list.
*/
@Test
public void nodeSchemaAsList() throws Exception {
}
/**
- * Test when element in case is container
+ * Test when element in case is container.
*/
@Test
public void nodeSchemaAsContainer() throws Exception {
}
/**
- * Test when element in case is leaflist
+ * Test when element in case is leaflist.
*/
@Test
public void nodeSchemaAsLeafList() throws Exception {
assertTrue(json.contains("\"lflst1d_2 val\""));
}
- /**
- *
- */
@Test
public void nodeSchemasInMultipleChoicesTest() throws Exception {
final String json = getJson("/nn-to-json/choice/xml/data_more_choices_same_level.xml");
/**
* Test whether is possible to find data schema for node which is specified
- * as dirrect subnode of choice (case without CASE key word)
+ * as dirrect subnode of choice (case without CASE key word).
*/
@Test
public void nodeSchemasInCaseNotDefinedWithCaseKeyword() throws Exception {
}
/**
- * Test of multiple use of choices
+ * Test of multiple use of choices.
*/
@Test
public void nodeSchemasInThreeChoicesAtSameLevel() throws Exception {
public static void initialization() {
schemaContext = schemaContextLoader("/nn-to-json/leafref",
schemaContext);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
- public void leafrefAbsolutePathToExistingLeafTest()
- throws Exception {
+ public void leafrefAbsolutePathToExistingLeafTest() throws Exception {
final String json = toJson("/nn-to-json/leafref/xml/data_absolut_ref_to_existing_leaf.xml");
validateJson(".*\"lf3\":\\p{Blank}*\"true\".*", json);
}
@Test
- public void leafrefRelativePathToExistingLeafTest()
- throws Exception {
+ public void leafrefRelativePathToExistingLeafTest() throws Exception {
final String json = toJson("/nn-to-json/leafref/xml/data_relativ_ref_to_existing_leaf.xml");
validateJson(".*\"lf2\":\\p{Blank}*\"121\".*", json);
}
@Test
public void leafrefFromLeafListToLeafTest() throws Exception {
final String json = toJson("/nn-to-json/leafref/xml/data_relativ_ref_from_leaflist_to_existing_leaf.xml");
- validateJson(
- ".*\"cont-augment-module\\p{Blank}*:\\p{Blank}*lflst1\":\\p{Blank}*.*\"34[5|6|7]\",*\"34[5|6|7]\",*\"34[5|6|7]\".*",
- json);
+ validateJson(".*\"cont-augment-module\\p{Blank}*:\\p{Blank}*lflst1\":\\p{Blank}*.*\"34[5|6|7]\",*\"34[5|6|7]\","
+ + "*\"34[5|6|7]\".*", json);
}
@Test
public static void initialize() {
schemaContext = schemaContextLoader("/nn-to-json/augmentation",
schemaContext);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
public static void initialization() throws URISyntaxException {
schemaContext = schemaContextLoader("/instanceidentifier/yang",
schemaContext);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
@BeforeClass
public static void initialization() {
schemaContext = schemaContextLoader("/nn-to-xml/yang", schemaContext);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
public void nnAsYangBitsToXmlTest() throws Exception {
final BitsTypeDefinition.Bit mockBit1 = Mockito.mock(BitsTypeDefinition.Bit.class);
Mockito.when(mockBit1.getName()).thenReturn("one");
- Mockito.when(mockBit1.getPosition()).thenReturn(1l);
+ Mockito.when(mockBit1.getPosition()).thenReturn(1L);
final BitsTypeDefinition.Bit mockBit2 = Mockito.mock(BitsTypeDefinition.Bit.class);
Mockito.when(mockBit2.getName()).thenReturn("two");
- Mockito.when(mockBit2.getPosition()).thenReturn(2l);
+ Mockito.when(mockBit2.getPosition()).thenReturn(2L);
final BitsTypeBuilder bitsTypeBuilder = BaseTypes.bitsTypeBuilder(Mockito.mock(SchemaPath.class));
bitsTypeBuilder.addBit(mockBit1);
bitsTypeBuilder.addBit(mockBit2);
public void nnAsYangUnionToXmlTest() throws Exception {
final BitsTypeDefinition.Bit mockBit1 = Mockito.mock(BitsTypeDefinition.Bit.class);
Mockito.when(mockBit1.getName()).thenReturn("first");
- Mockito.when(mockBit1.getPosition()).thenReturn(1l);
+ Mockito.when(mockBit1.getPosition()).thenReturn(1L);
final BitsTypeDefinition.Bit mockBit2 = Mockito.mock(BitsTypeDefinition.Bit.class);
Mockito.when(mockBit2.getName()).thenReturn("second");
- Mockito.when(mockBit2.getPosition()).thenReturn(2l);
+ Mockito.when(mockBit2.getPosition()).thenReturn(2L);
final BitsTypeBuilder bitsTypeBuilder = BaseTypes.bitsTypeBuilder(Mockito.mock(SchemaPath.class));
bitsTypeBuilder.addBit(mockBit1);
@BeforeClass
public static void initialization() {
schemaContext = schemaContextLoader("/nn-to-xml/choice", schemaContext);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
public static void initialize() {
schemaContext = schemaContextLoader(
"/nn-to-xml/data-of-several-modules/yang", schemaContext);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
private static DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> buildContBuilderMod1(
final String uri, final String rev, final String cont, final String contB, final String lf1,
- final String lf1_value) {
+ final String lf1Value) {
final QName contQname = QName.create(uri, rev, cont);
final QName contBQname = QName.create(uri, rev, contB);
final QName lf1Qname = QName.create(contQname, lf1);
dataContainerNodeAttrBuilder.withChild(Builders
.leafBuilder((LeafSchemaNode) schemaLf1_m1)
- .withValue(lf1_value).build());
+ .withValue(lf1Value).build());
final DataSchemaNode contBSchemaNode = ((ContainerSchemaNode) contSchemaNode)
.getDataChildByName(contBQname);
import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchStatusContext;
import org.opendaylight.netconf.sal.restconf.impl.PutResult;
import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
@Mock
private DOMMountPoint mockMountInstance;
@Mock
- private DOMDataReadOnlyTransaction rTransaction;
+ private DOMDataReadOnlyTransaction readTransaction;
@Mock
- private DOMDataWriteTransaction wTransaction;
+ private DOMDataWriteTransaction writeTransaction;
@Mock
private DOMDataReadWriteTransaction rwTransaction;
this.brokerFacade.setDomNotificationService(this.domNotification);
this.brokerFacade.setRpcService(this.mockRpcService);
this.brokerFacade.setContext(this.context);
- when(this.domDataBroker.newReadOnlyTransaction()).thenReturn(this.rTransaction);
- when(this.domDataBroker.newWriteOnlyTransaction()).thenReturn(this.wTransaction);
+ when(this.domDataBroker.newReadOnlyTransaction()).thenReturn(this.readTransaction);
+ when(this.domDataBroker.newWriteOnlyTransaction()).thenReturn(this.writeTransaction);
when(this.domDataBroker.newReadWriteTransaction()).thenReturn(this.rwTransaction);
ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext("/full-versions/test-module"));
private static CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> wrapDummyNode(
final NormalizedNode<?, ?> dummyNode) {
- return Futures.immediateCheckedFuture(Optional.<NormalizedNode<?, ?>> of(dummyNode));
+ return Futures.immediateCheckedFuture(Optional.<NormalizedNode<?, ?>>of(dummyNode));
}
private static CheckedFuture<Boolean, ReadFailedException> wrapExistence(final Boolean exists) {
}
/**
- * Value of this node shouldn't be important for testing purposes
+ * Value of this node shouldn't be important for testing purposes.
*/
private static NormalizedNode<?, ?> createDummyNode(final String namespace, final String date,
final String localName) {
@Test
public void testReadConfigurationData() {
- when(this.rTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
+ when(this.readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
this.dummyNodeInFuture);
final NormalizedNode<?, ?> actualNode = this.brokerFacade.readConfigurationData(this.instanceID);
@Test
public void testReadOperationalData() {
- when(this.rTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
+ when(this.readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
this.dummyNodeInFuture);
final NormalizedNode<?, ?> actualNode = this.brokerFacade.readOperationalData(this.instanceID);
"Master is down. Please try again.");
final ReadFailedException exception503 = new ReadFailedException("Read from transaction failed", error);
doReturn(Futures.immediateFailedCheckedFuture(exception503))
- .when(rTransaction).read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class));
+ .when(readTransaction).read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class));
try {
brokerFacade.readConfigurationData(this.instanceID, "explicit");
fail("This test should fail.");
} catch (final RestconfDocumentedException e) {
assertEquals("getErrorTag", ErrorTag.RESOURCE_DENIED_TRANSPORT, e.getErrors().get(0).getErrorTag());
assertEquals("getErrorType", ErrorType.TRANSPORT, e.getErrors().get(0).getErrorType());
- assertEquals("getErrorMessage", "Master is down. Please try again.", e.getErrors().get(0).getErrorMessage());
+ assertEquals("getErrorMessage", "Master is down. Please try again.",
+ e.getErrors().get(0).getErrorMessage());
}
}
/**
* Prepare conditions to test delete operation. Data to delete exists or does not exist according to value of
* {@code assumeDataExists} parameter.
- * @param assumeDataExists
+ * @param assumeDataExists boolean to assume if data exists
*/
private void prepareDataForDelete(final boolean assumeDataExists) {
when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
}
/**
- * Test PATCH method on the server with no data
+ * Test Patch method on the server with no data.
*/
@Test
@SuppressWarnings("unchecked")
public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
- final PATCHContext patchContext = mock(PATCHContext.class);
+ final PatchContext patchContext = mock(PatchContext.class);
final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
when(this.rwTransaction.submit()).thenReturn(expFuture);
- final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
+ final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
// assert success
- assertTrue("PATCH operation should be successful on server", status.isOk());
+ assertTrue("Patch operation should be successful on server", status.isOk());
}
/**
- * Test PATCH method on mounted device with no data
+ * Test Patch method on mounted device with no data.
*/
@Test
@SuppressWarnings("unchecked")
public void testPatchConfigurationDataWithinTransactionMount() throws Exception {
- final PATCHContext patchContext = mock(PATCHContext.class);
+ final PatchContext patchContext = mock(PatchContext.class);
final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
when(transaction.submit()).thenReturn(expFuture);
- final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
+ final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
// assert success
- assertTrue("PATCH operation should be successful on mounted device", status.isOk());
+ assertTrue("Patch operation should be successful on mounted device", status.isOk());
}
/**
- * Negative test for PATCH operation when mounted device does not support {@link DOMDataBroker service.
- * PATCH operation should fail with global error.
+ * Negative test for Patch operation when mounted device does not support {@link DOMDataBroker service.}
+ * Patch operation should fail with global error.
*/
@Test
@SuppressWarnings("unchecked")
public void testPatchConfigurationDataWithinTransactionMountFail() throws Exception {
- final PATCHContext patchContext = mock(PATCHContext.class);
+ final PatchContext patchContext = mock(PatchContext.class);
final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
when(transaction.submit()).thenReturn(expFuture);
- final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
+ final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
// assert not successful operation with error
assertNotNull(status.getGlobalErrors());
assertEquals(ErrorType.APPLICATION, status.getGlobalErrors().get(0).getErrorType());
assertEquals(ErrorTag.OPERATION_FAILED, status.getGlobalErrors().get(0).getErrorTag());
- assertFalse("PATCH operation should fail on mounted device without Broker", status.isOk());
+ assertFalse("Patch operation should fail on mounted device without Broker", status.isOk());
}
}
private static final QName TYPE_QNAME = QName.create("test:module", "2014-01-09", "type");
private static final QName MODULE_TYPE_QNAME = QName.create("test:module", "2014-01-09", "module-type");
- private static final ControllerContext controllerContext = ControllerContext.getInstance();
+ private static final ControllerContext CONTROLLER_CONTEXT = ControllerContext.getInstance();
@BeforeClass
public static void init() throws FileNotFoundException, ReactorException {
assertNull(globalContext.findModuleByName(EXTERNAL_MODULE_NAME, null));
final Set<Module> allModules = globalContext.getModules();
assertNotNull(allModules);
- controllerContext.setSchemas(globalContext);
+ CONTROLLER_CONTEXT.setSchemas(globalContext);
}
@Test
public void testIdentityRefFromExternalModule() throws FileNotFoundException, ReactorException {
initMountService();
- final InstanceIdentifierContext<?> ctx = controllerContext
- .toInstanceIdentifier("simple-nodes:users/yang-ext:mount/test-module:modules/module/test-module:module-type/name");
+ final InstanceIdentifierContext<?> ctx = CONTROLLER_CONTEXT.toInstanceIdentifier(
+ "simple-nodes:users/yang-ext:mount/test-module:modules/module/test-module:module-type/name");
final Map<QName, Object> keyValues = new HashMap<>();
keyValues.put(NAME_QNAME, "name");
private void initMountService() throws FileNotFoundException, ReactorException {
final DOMMountPointService mountService = mock(DOMMountPointService.class);
- controllerContext.setMountService(mountService);
+ CONTROLLER_CONTEXT.setMountService(mountService);
final BrokerFacade brokerFacade = mock(BrokerFacade.class);
final RestconfImpl restconfImpl = RestconfImpl.getInstance();
restconfImpl.setBroker(brokerFacade);
- restconfImpl.setControllerContext(controllerContext);
+ restconfImpl.setControllerContext(CONTROLLER_CONTEXT);
final SchemaContext mountPointContext = TestUtils.loadSchemaContext("/full-versions/test-module");
final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
when(mountInstance.getSchemaContext()).thenReturn(mountPointContext);
XMLEventReader eventReader;
eventReader = xmlInFactory.createXMLEventReader(new ByteArrayInputStream(xml.getBytes()));
- String aaModulePrefix = null;
- String aModulePrefix = null;
- String iiModulePrefix = null;
+ String augmentAugmentModulePrefix = null;
+ String augmentModulePrefix = null;
+ String instanceIdentifierModulePrefix = null;
while (eventReader.hasNext()) {
final XMLEvent nextEvent = eventReader.nextEvent();
if (nextEvent.isStartElement()) {
final StartElement startElement = (StartElement) nextEvent;
if (startElement.getName().getLocalPart().equals("lf111")) {
- final Iterator<?> prefixes = startElement.getNamespaceContext().getPrefixes("augment:augment:module");
+ final Iterator<?> prefixes =
+ startElement.getNamespaceContext().getPrefixes("augment:augment:module");
- while (prefixes.hasNext() && (aaModulePrefix == null)) {
+ while (prefixes.hasNext() && (augmentAugmentModulePrefix == null)) {
final String prefix = (String) prefixes.next();
if (!prefix.isEmpty()) {
- aaModulePrefix = prefix;
+ augmentAugmentModulePrefix = prefix;
}
}
- aModulePrefix = startElement.getNamespaceContext().getPrefix("augment:module");
- iiModulePrefix = startElement.getNamespaceContext().getPrefix("instance:identifier:module");
+ augmentModulePrefix = startElement.getNamespaceContext().getPrefix("augment:module");
+ instanceIdentifierModulePrefix =
+ startElement.getNamespaceContext().getPrefix("instance:identifier:module");
break;
}
}
}
- assertNotNull(aaModulePrefix);
- assertNotNull(aModulePrefix);
- assertNotNull(iiModulePrefix);
+ assertNotNull(augmentAugmentModulePrefix);
+ assertNotNull(augmentModulePrefix);
+ assertNotNull(instanceIdentifierModulePrefix);
- final String instanceIdentifierValue = "/" + iiModulePrefix + ":cont/" + iiModulePrefix + ":cont1/" + aModulePrefix
- + ":lst11[" + aModulePrefix + ":keyvalue111='value1'][" + aModulePrefix + ":keyvalue112='value2']/"
- + aaModulePrefix + ":lf112";
+ final String instanceIdentifierValue = "/" + instanceIdentifierModulePrefix + ":cont/"
+ + instanceIdentifierModulePrefix + ":cont1/" + augmentModulePrefix + ":lst11[" + augmentModulePrefix
+ + ":keyvalue111='value1'][" + augmentModulePrefix + ":keyvalue112='value2']/"
+ + augmentAugmentModulePrefix + ":lf112";
assertTrue(xml.contains(instanceIdentifierValue));
XMLEventReader eventReader;
eventReader = xmlInFactory.createXMLEventReader(new ByteArrayInputStream(xml.getBytes()));
- String aModuleLfLstPrefix = null;
+ String augmentModuleLfLstPrefix = null;
String iiModulePrefix = null;
while (eventReader.hasNext()) {
final XMLEvent nextEvent = eventReader.nextEvent();
if (nextEvent.isStartElement()) {
final StartElement startElement = (StartElement) nextEvent;
if (startElement.getName().getLocalPart().equals("lf111")) {
- final Iterator<?> prefixes = startElement.getNamespaceContext().getPrefixes("augment:module:leaf:list");
+ final Iterator<?> prefixes =
+ startElement.getNamespaceContext().getPrefixes("augment:module:leaf:list");
- while (prefixes.hasNext() && (aModuleLfLstPrefix == null)) {
+ while (prefixes.hasNext() && (augmentModuleLfLstPrefix == null)) {
final String prefix = (String) prefixes.next();
if (!prefix.isEmpty()) {
- aModuleLfLstPrefix = prefix;
+ augmentModuleLfLstPrefix = prefix;
}
}
iiModulePrefix = startElement.getNamespaceContext().getPrefix("instance:identifier:module");
}
}
- assertNotNull(aModuleLfLstPrefix);
+ assertNotNull(augmentModuleLfLstPrefix);
assertNotNull(iiModulePrefix);
final String instanceIdentifierValue = "/" + iiModulePrefix + ":cont/" + iiModulePrefix + ":cont1/"
- + aModuleLfLstPrefix + ":lflst11[.='lflst11_1']";
+ + augmentModuleLfLstPrefix + ":lflst11[.='lflst11_1']";
assertTrue(xml.contains(instanceIdentifierValue));
final Map<QName, Object> keyValues = new HashMap<>();
keyValues.put(new QName(new URI("augment:module"), "keyvalue111"), "value1");
keyValues.put(new QName(new URI("augment:module"), "keyvalue112"), "value2");
- final NodeIdentifierWithPredicates nodeIdentifierWithPredicates = new NodeIdentifierWithPredicates(qName, keyValues);
+ final NodeIdentifierWithPredicates nodeIdentifierWithPredicates =
+ new NodeIdentifierWithPredicates(qName, keyValues);
pathArguments.add(nodeIdentifierWithPredicates);
pathArguments.add(new NodeIdentifier(new QName(new URI("augment:augment:module"), "lf112")));
// set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig = resourceConfig.registerInstances(restConf, new NormalizedNodeJsonBodyWriter(),
- new NormalizedNodeXmlBodyWriter(), new XmlNormalizedNodeBodyReader(), new JsonNormalizedNodeBodyReader());
+ new NormalizedNodeXmlBodyWriter(), new XmlNormalizedNodeBodyReader(), new JsonNormalizedNodeBodyReader());
resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
return resourceConfig;
}
@Test
@Ignore // TODO RestconfDocumentedExceptionMapper needs be fixed before
- public void StringToNumberConversionError() {
+ public void stringToNumberConversionError() {
final Response response = target("/config/number:cont").request(MediaType.APPLICATION_XML).put(
Entity.entity("<cont xmlns=\"number\"><lf>3f</lf></cont>", MediaType.APPLICATION_XML));
final String exceptionMessage = response.readEntity(String.class);
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class CutDataToCorrectDepthTest extends JerseyTest {
+ private static final Logger LOG = LoggerFactory.getLogger(JerseyTest.class);
+
private static NormalizedNode<?, ?> depth1Cont;
private static NormalizedNode<?, ?> depth2Cont1;
private NormalizedNode<?, ?> globalPayload;
@PUT
@Path("/config/{identifier:.+}")
@Consumes({ "application/json", "application/xml" })
- public void normalizedData(@Encoded @PathParam("identifier") final String identifier, final NormalizedNodeContext payload) throws InterruptedException {
- System.out.println(payload);
- System.out.println(payload.getInstanceIdentifierContext().getInstanceIdentifier());
- System.out.println(payload.getData());
+ public void normalizedData(@Encoded @PathParam("identifier") final String identifier,
+ final NormalizedNodeContext payload) throws InterruptedException {
+ LOG.info("Payload: {}.", payload);
+ LOG.info("Instance identifier of payload: {}.",
+ payload.getInstanceIdentifierContext().getInstanceIdentifier());
+ LOG.info("Data of payload: {}.", payload.getData());
CutDataToCorrectDepthTest.this.globalPayload = payload.getData();
}
"depth2-cont1",
unkeyedEntry("depth2-cont1",
container("depth3-cont1",
- container("depth4-cont1", leaf("depth5-leaf1", "depth5-leaf1-value")),
- leaf("depth4-leaf1", "depth4-leaf1-value")), leaf("depth3-leaf1", "depth3-leaf1-value")));
+ container("depth4-cont1", leaf("depth5-leaf1", "depth5-leaf1-value")),
+ leaf("depth4-leaf1", "depth4-leaf1-value")), leaf("depth3-leaf1", "depth3-leaf1-value")));
final MapNode listAsMap = mapNode(
"depth2-list2",
container(
"depth2-cont2",
container("depth3-cont2",
- container("depth4-cont2", leaf("depth5-leaf2", "depth5-leaf2-value")),
- leaf("depth4-leaf2", "depth4-leaf2-value")), leaf("depth3-leaf2", "depth3-leaf2-value")),
+ container("depth4-cont2", leaf("depth5-leaf2", "depth5-leaf2-value")),
+ leaf("depth4-leaf2", "depth4-leaf2-value")), leaf("depth3-leaf2", "depth3-leaf2-value")),
leaf("depth2-leaf1", "depth2-leaf1-value"));
depth2Cont1 = listAsUnkeyedList;
private void txtDataToNormalizedNode(final Response response, final String mediaType, final String uri) {
final String responseStr = response.readEntity(String.class);
- System.out.println(responseStr);
+ LOG.info("Response entity message: {}.", responseStr);
target(uri).request(mediaType).put(Entity.entity(responseStr, mediaType));
}
}
private static ContainerNode container(final String localName, final DataContainerChild<?, ?>... children) {
- final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder = Builders.containerBuilder();
+ final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
+ Builders.containerBuilder();
for (final DataContainerChild<?, ?> child : children) {
containerBuilder.withChild(child);
}
private static UnkeyedListEntryNode unkeyedEntry(final String localName,
final DataContainerChild<?, ?>... children) {
- final DataContainerNodeAttrBuilder<NodeIdentifier, UnkeyedListEntryNode> builder = Builders.unkeyedListEntryBuilder();
+ final DataContainerNodeAttrBuilder<NodeIdentifier, UnkeyedListEntryNode> builder =
+ Builders.unkeyedListEntryBuilder();
builder.withNodeIdentifier(toIdentifier(localName));
for (final DataContainerChild<?, ?> child : children) {
builder.withChild(child);
private static MapEntryNode mapEntryNode(final String localName, final int keysNumber,
final DataContainerChild<?, ?>... children) {
- final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder = Builders.mapEntryBuilder();
+ final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder =
+ Builders.mapEntryBuilder();
final Map<QName, Object> keys = new HashMap<>();
for (int i = 0; i < keysNumber; i++) {
keys.put(children[i].getNodeType(), children[i].getValue());
leaf("depth3-leaf1", "depth3-leaf1-value"))),
mapNode("depth2-list2",
mapEntryNode("depth2-list2", 2, leaf("depth3-lf1-key", "depth3-lf1-key-value"),
- leaf("depth3-lf2-key", "depth3-lf2-key-value"), leaf("depth3-lf3", "depth3-lf3-value"))),
+ leaf("depth3-lf2-key", "depth3-lf2-key-value"), leaf("depth3-lf3", "depth3-lf3-value"))),
leafList("depth2-lfLst1", "depth2-lflst1-value1", "depth2-lflst1-value2", "depth2-lflst1-value3"),
container(
"depth2-cont2",
container("depth3-cont2",
- container("depth4-cont2", leaf("depth5-leaf2", "depth5-leaf2-value")),
- leaf("depth4-leaf2", "depth4-leaf2-value")), leaf("depth3-leaf2", "depth3-leaf2-value")),
+ container("depth4-cont2", leaf("depth5-leaf2", "depth5-leaf2-value")),
+ leaf("depth4-leaf2", "depth4-leaf2-value")), leaf("depth3-leaf2", "depth3-leaf2-value")),
leaf("depth2-leaf1", "depth2-leaf1-value"));
}
unkeyedList("depth2-cont1", nodeDataDepth3Operational()),
mapNode("depth2-list2",
mapEntryNode("depth2-list2", 2, leaf("depth3-lf1-key", "depth3-lf1-key-value"),
- leaf("depth3-lf2-key", "depth3-lf2-key-value"), leaf("depth3-lf3", "depth3-lf3-value"))),
+ leaf("depth3-lf2-key", "depth3-lf2-key-value"), leaf("depth3-lf3", "depth3-lf3-value"))),
leafList("depth2-lfLst1", "depth2-lflst1-value1", "depth2-lflst1-value2", "depth2-lflst1-value3"),
container(
- "depth2-cont2",
- container("depth3-cont2", container("depth4-cont2"), leaf("depth4-leaf2", "depth4-leaf2-value")),
- leaf("depth3-leaf2", "depth3-leaf2-value")), leaf("depth2-leaf1", "depth2-leaf1-value"));
+ "depth2-cont2",
+ container("depth3-cont2", container("depth4-cont2"), leaf("depth4-leaf2", "depth4-leaf2-value")),
+ leaf("depth3-leaf2", "depth3-leaf2-value")), leaf("depth2-leaf1", "depth2-leaf1-value"));
}
private static ContainerNode nodeDataDepth3() {
return container(
- "depth1-cont",
- unkeyedList("depth2-cont1",
- unkeyedEntry("depth2-cont1", container("depth3-cont1"), leaf("depth3-leaf1", "depth3-leaf1-value"))),
- mapNode("depth2-list2",
- mapEntryNode("depth2-list2", 2, leaf("depth3-lf1-key", "depth3-lf1-key-value"),
- leaf("depth3-lf2-key", "depth3-lf2-key-value"), leaf("depth3-lf3", "depth3-lf3-value"))),
- leafList("depth2-lfLst1", "depth2-lflst1-value1", "depth2-lflst1-value2", "depth2-lflst1-value3"),
- container("depth2-cont2", container("depth3-cont2"), leaf("depth3-leaf2", "depth3-leaf2-value")),
- leaf("depth2-leaf1", "depth2-leaf1-value"));
+ "depth1-cont",
+ unkeyedList("depth2-cont1",
+ unkeyedEntry("depth2-cont1", container("depth3-cont1"), leaf("depth3-leaf1", "depth3-leaf1-value"))),
+ mapNode("depth2-list2",
+ mapEntryNode("depth2-list2", 2, leaf("depth3-lf1-key", "depth3-lf1-key-value"),
+ leaf("depth3-lf2-key", "depth3-lf2-key-value"), leaf("depth3-lf3", "depth3-lf3-value"))),
+ leafList("depth2-lfLst1", "depth2-lflst1-value1", "depth2-lflst1-value2", "depth2-lflst1-value3"),
+ container("depth2-cont2", container("depth3-cont2"), leaf("depth3-leaf2", "depth3-leaf2-value")),
+ leaf("depth2-leaf1", "depth2-leaf1-value"));
}
private static ContainerNode nodeDataDepth2() {
// FIXME: do not use reflection here
final Class<?> superclass = listener.getClass().getSuperclass().getSuperclass();
- Method m = null;
- for (final Method method : superclass.getDeclaredMethods()) {
- if (method.getName().equals("parseFilterParam")) {
- m = method;
+ Method method = null;
+ for (final Method met : superclass.getDeclaredMethods()) {
+ if (met.getName().equals("parseFilterParam")) {
+ method = met;
}
}
- if (m == null) {
+ if (method == null) {
throw new Exception("Methode parseFilterParam doesn't exist in " + superclass.getName());
}
- m.setAccessible(true);
- return (boolean) m.invoke(listener, readFile(xml));
+ method.setAccessible(true);
+ return (boolean) method.invoke(listener, readFile(xml));
}
private static String readFile(final File xml) throws IOException {
- try (final BufferedReader br = new BufferedReader(new FileReader(xml))) {
+ try (BufferedReader br = new BufferedReader(new FileReader(xml))) {
final StringBuilder sb = new StringBuilder();
String line = br.readLine();
}
assertNotNull(rpcInputSchemaNode);
- final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> container = Builders.containerBuilder(rpcInputSchemaNode);
+ final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> container =
+ Builders.containerBuilder(rpcInputSchemaNode);
final QName contQName = QName.create(rpcModule.getQNameModule(), "cont");
final DataSchemaNode contSchemaNode = rpcInputSchemaNode.getDataChildByName(contQName);
assertTrue(contSchemaNode instanceof ContainerSchemaNode);
- final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> contNode = Builders.containerBuilder((ContainerSchemaNode) contSchemaNode);
+ final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> contNode =
+ Builders.containerBuilder((ContainerSchemaNode) contSchemaNode);
final QName lfQName = QName.create(rpcModule.getQNameModule(), "lf");
final DataSchemaNode lfSchemaNode = ((ContainerSchemaNode) contSchemaNode).getDataChildByName(lfQName);
assertTrue(lfSchemaNode instanceof LeafSchemaNode);
- final LeafNode<Object> lfNode = (Builders.leafBuilder((LeafSchemaNode) lfSchemaNode).withValue("any value")).build();
+ final LeafNode<Object> lfNode =
+ (Builders.leafBuilder((LeafSchemaNode) lfSchemaNode).withValue("any value")).build();
contNode.withChild(lfNode);
container.withChild(contNode.build());
- return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpcInputSchemaNode, null, schema), container.build());
+ return new NormalizedNodeContext(
+ new InstanceIdentifierContext<>(null, rpcInputSchemaNode, null, schema), container.build());
}
@Test
fail("Expected an exception to be thrown.");
} catch (final RestconfDocumentedException e) {
verifyRestconfDocumentedException(e, 0, ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED,
- Optional.<String> absent(), Optional.<String> absent());
+ Optional.<String>absent(), Optional.<String>absent());
}
}
- void verifyRestconfDocumentedException(final RestconfDocumentedException e, final int index,
+ void verifyRestconfDocumentedException(final RestconfDocumentedException restDocumentedException, 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);
+ actual = restDocumentedException.getErrors().get(index);
} catch (final ArrayIndexOutOfBoundsException ex) {
fail("RestconfError not found at index " + index);
}
@Test
public void testInvokeRpcWithNoPayloadRpc_FailWithRpcError() {
final List<RpcError> rpcErrors = Arrays.asList(
- RpcResultBuilder.newError( RpcError.ErrorType.TRANSPORT, "bogusTag", "foo" ),
- RpcResultBuilder.newWarning( RpcError.ErrorType.RPC, "in-use", "bar",
- "app-tag", null, null ) );
+ RpcResultBuilder.newError(RpcError.ErrorType.TRANSPORT, "bogusTag", "foo"),
+ RpcResultBuilder.newWarning(RpcError.ErrorType.RPC, "in-use", "bar",
+ "app-tag", null, null));
final DOMRpcResult resutl = new DefaultDOMRpcResult(rpcErrors);
final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(resutl);
fail("Expected an exception to be thrown.");
} catch (final RestconfDocumentedException e) {
verifyRestconfDocumentedException(e, 0, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED, Optional.of("foo"),
- Optional.<String> absent());
+ Optional.<String>absent());
verifyRestconfDocumentedException(e, 1, ErrorType.RPC, ErrorTag.IN_USE, Optional.of("bar"),
Optional.of("app-tag"));
}
final SchemaPath path = SchemaPath.create(true, qname);
final BrokerFacade brokerFacade = mock(BrokerFacade.class);
- when(brokerFacade.invokeRpc(eq(path), any (NormalizedNode.class))).thenReturn(future);
+ when(brokerFacade.invokeRpc(eq(path), any(NormalizedNode.class))).thenReturn(future);
this.restconfImpl.setBroker(brokerFacade);
fail("Expected an exception");
} catch (final RestconfDocumentedException e) {
verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
- Optional.<String> absent(), Optional.<String> absent());
+ Optional.<String>absent(), Optional.<String>absent());
}
}
fail("Expected an exception");
} catch (final RestconfDocumentedException e) {
verifyRestconfDocumentedException(e, 0, ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT,
- Optional.<String> absent(), Optional.<String> absent());
+ Optional.<String>absent(), Optional.<String>absent());
}
}
final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
Builders.containerBuilder(rpcInputSchemaNode);
- final NormalizedNodeContext payload = new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpcInputSchemaNode,
+ final NormalizedNodeContext payload =
+ new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpcInputSchemaNode,
null, schemaContext), containerBuilder.build());
final BrokerFacade brokerFacade = mock(BrokerFacade.class);
fail("Expected an exception.");
} catch (final RestconfDocumentedException e) {
verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
- Optional.<String> absent(), Optional.<String> absent());
+ Optional.<String>absent(), Optional.<String>absent());
}
}
}
/**
- *
* Tests calling of RestConfImpl method invokeRpc. In the method there is searched rpc in remote schema context.
* This rpc is then executed.
- *
* I wasn't able to simulate calling of rpc on remote device therefore this testing method raise method when rpc is
* invoked.
*/
static final String TOASTER_MODULE_NS = "http://netconfcentral.org/ns/toaster";
static final String TOASTER_MODULE_VERSION = "2009-11-20";
- static final QName TOASTER_DONENESS_QNAME = QName.create(TOASTER_MODULE_NS, TOASTER_MODULE_VERSION, "toasterDoneness");
+ static final QName TOASTER_DONENESS_QNAME =
+ QName.create(TOASTER_MODULE_NS, TOASTER_MODULE_VERSION, "toasterDoneness");
static final QName TOASTER_TYPE_QNAME = QName.create(TOASTER_MODULE_NS, TOASTER_MODULE_VERSION, "toasterToastType");
static final QName WHEAT_BREAD_QNAME = QName.create(TOASTER_MODULE_NS, TOASTER_MODULE_VERSION, "wheat-bread");
static final QName MAKE_TOAST_QNAME = QName.create(TOASTER_MODULE_NS, TOASTER_MODULE_VERSION, "make-toast");
}
private static String loadData(final String path) throws IOException {
- return Resources.asCharSource(JSONRestconfServiceImplTest.class.getResource(path), StandardCharsets.UTF_8).read();
+ return Resources.asCharSource(JSONRestconfServiceImplTest.class.getResource(path),
+ StandardCharsets.UTF_8).read();
}
@SuppressWarnings("rawtypes")
Mockito.when(uriInfo.getQueryParameters()).thenReturn(value);
this.service.put(uriPath, payload, uriInfo);
- final ArgumentCaptor<YangInstanceIdentifier> capturedPath = ArgumentCaptor.forClass(YangInstanceIdentifier.class);
+ final ArgumentCaptor<YangInstanceIdentifier> capturedPath =
+ ArgumentCaptor.forClass(YangInstanceIdentifier.class);
final ArgumentCaptor<NormalizedNode> capturedNode = ArgumentCaptor.forClass(NormalizedNode.class);
verify(brokerFacade).commitConfigurationDataPut(notNull(SchemaContext.class), capturedPath.capture(),
capturedNode.capture(), Mockito.anyString(), Mockito.anyString());
Mockito.when(uriInfo.getQueryParameters()).thenReturn(value);
this.service.put(uriPath, payload, uriInfo);
- final ArgumentCaptor<YangInstanceIdentifier> capturedPath = ArgumentCaptor.forClass(YangInstanceIdentifier.class);
+ final ArgumentCaptor<YangInstanceIdentifier> capturedPath =
+ ArgumentCaptor.forClass(YangInstanceIdentifier.class);
final ArgumentCaptor<NormalizedNode> capturedNode = ArgumentCaptor.forClass(NormalizedNode.class);
verify(brokerFacade).commitMountPointDataPut(same(mockMountPoint), capturedPath.capture(),
capturedNode.capture(), Mockito.anyString(), Mockito.anyString());
}
@Test(expected = OperationFailedException.class)
+ @SuppressWarnings("checkstyle:IllegalThrows")
public void testPutFailure() throws Throwable {
final PutResult result = mock(PutResult.class);
Mockito.when(uriInfo.getBaseUriBuilder()).thenReturn(uriBuilder);
this.service.post(uriPath, payload, uriInfo);
- final ArgumentCaptor<YangInstanceIdentifier> capturedPath = ArgumentCaptor.forClass(YangInstanceIdentifier.class);
+ final ArgumentCaptor<YangInstanceIdentifier> capturedPath =
+ ArgumentCaptor.forClass(YangInstanceIdentifier.class);
final ArgumentCaptor<NormalizedNode> capturedNode = ArgumentCaptor.forClass(NormalizedNode.class);
verify(brokerFacade).commitConfigurationDataPost(notNull(SchemaContext.class), capturedPath.capture(),
capturedNode.capture(), Mockito.anyString(), Mockito.anyString());
Mockito.when(uriInfo.getBaseUriBuilder()).thenReturn(uriBuilder);
this.service.post(uriPath, payload, uriInfo);
- final ArgumentCaptor<YangInstanceIdentifier> capturedPath = ArgumentCaptor.forClass(YangInstanceIdentifier.class);
+ final ArgumentCaptor<YangInstanceIdentifier> capturedPath =
+ ArgumentCaptor.forClass(YangInstanceIdentifier.class);
final ArgumentCaptor<NormalizedNode> capturedNode = ArgumentCaptor.forClass(NormalizedNode.class);
verify(brokerFacade).commitConfigurationDataPost(same(mockMountPoint), capturedPath.capture(),
capturedNode.capture(), Mockito.anyString(), Mockito.anyString());
}
@Test(expected = TransactionCommitFailedException.class)
+ @SuppressWarnings("checkstyle:IllegalThrows")
public void testPostFailure() throws Throwable {
doReturn(Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException("mock"))).when(brokerFacade)
.commitConfigurationDataPost(any(SchemaContext.class), any(YangInstanceIdentifier.class),
this.service.delete(uriPath);
- final ArgumentCaptor<YangInstanceIdentifier> capturedPath = ArgumentCaptor.forClass(YangInstanceIdentifier.class);
+ final ArgumentCaptor<YangInstanceIdentifier> capturedPath =
+ ArgumentCaptor.forClass(YangInstanceIdentifier.class);
verify(brokerFacade).commitConfigurationDataDelete(capturedPath.capture());
verifyPath(capturedPath.getValue(), INTERFACES_QNAME, INTERFACE_QNAME,
new Object[]{INTERFACE_QNAME, NAME_QNAME, "eth0"});
}
- @Test(expected=OperationFailedException.class)
+ @Test(expected = OperationFailedException.class)
public void testDeleteFailure() throws Exception {
final String invalidUriPath = "ietf-interfaces:interfaces/invalid";
this.service.get(uriPath, LogicalDatastoreType.CONFIGURATION, uriInfo);
}
- @Test(expected=OperationFailedException.class)
+ @Test(expected = OperationFailedException.class)
public void testGetFailure() throws Exception {
final String invalidUriPath = "/ietf-interfaces:interfaces/invalid";
final UriInfo uriInfo = Mockito.mock(UriInfo.class);
verify(brokerFacade).invokeRpc(eq(path), isNull(NormalizedNode.class));
}
- @Test(expected=OperationFailedException.class)
+ @Test(expected = OperationFailedException.class)
public void testInvokeRpcFailure() throws Exception {
final DOMRpcException exception = new DOMRpcImplementationNotAvailableException("testExeption");
doReturn(Futures.immediateFailedCheckedFuture(exception)).when(brokerFacade).invokeRpc(any(SchemaPath.class),
.withChild(ImmutableNodes.leafNode(DESC_QNAME, "eth interface"))
.build();
- if(datastoreType == LogicalDatastoreType.CONFIGURATION) {
+ if (datastoreType == LogicalDatastoreType.CONFIGURATION) {
doReturn(entryNode).when(brokerFacade).readConfigurationData(notNull(YangInstanceIdentifier.class),
Mockito.anyString());
} else {
assertThat("Missing \"enabled\"", jsonResp, containsString("\"enabled\":true"));
assertThat("Missing \"description\"", jsonResp, containsString("\"description\":\"eth interface\""));
- final ArgumentCaptor<YangInstanceIdentifier> capturedPath = ArgumentCaptor.forClass(YangInstanceIdentifier.class);
+ final ArgumentCaptor<YangInstanceIdentifier> capturedPath =
+ ArgumentCaptor.forClass(YangInstanceIdentifier.class);
if (datastoreType == LogicalDatastoreType.CONFIGURATION) {
verify(brokerFacade).readConfigurationData(capturedPath.capture(), Mockito.anyString());
} else {
doReturn(schemaContextTestModule).when(mockMountPoint).getSchemaContext();
final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
- doReturn(Optional.of(mockMountPoint)).when(mockMountService).getMountPoint(notNull(YangInstanceIdentifier.class));
+ doReturn(Optional.of(mockMountPoint))
+ .when(mockMountService).getMountPoint(notNull(YangInstanceIdentifier.class));
ControllerContext.getInstance().setMountService(mockMountService);
return mockMountPoint;
void verifyPath(final YangInstanceIdentifier path, final Object... expArgs) {
final List<PathArgument> pathArgs = path.getPathArguments();
assertEquals("Arg count for actual path " + path, expArgs.length, pathArgs.size());
- int i = 0;
- for(final PathArgument actual: pathArgs) {
+ int index = 0;
+ for (final PathArgument actual: pathArgs) {
QName expNodeType;
- if(expArgs[i] instanceof Object[]) {
- final Object[] listEntry = (Object[]) expArgs[i];
+ if (expArgs[index] instanceof Object[]) {
+ final Object[] listEntry = (Object[]) expArgs[index];
expNodeType = (QName) listEntry[0];
assertTrue(actual instanceof NodeIdentifierWithPredicates);
final Map<QName, Object> keyValues = ((NodeIdentifierWithPredicates)actual).getKeyValues();
- assertEquals(String.format("Path arg %d keyValues size", i + 1), 1, keyValues.size());
+ assertEquals(String.format("Path arg %d keyValues size", index + 1), 1, keyValues.size());
final QName expKey = (QName) listEntry[1];
- assertEquals(String.format("Path arg %d keyValue for %s", i + 1, expKey), listEntry[2],
+ assertEquals(String.format("Path arg %d keyValue for %s", index + 1, expKey), listEntry[2],
keyValues.get(expKey));
} else {
- expNodeType = (QName) expArgs[i];
+ expNodeType = (QName) expArgs[index];
}
- assertEquals(String.format("Path arg %d node type", i + 1), expNodeType, actual.getNodeType());
- i++;
+ assertEquals(String.format("Path arg %d node type", index + 1), expNodeType, actual.getNodeType());
+ index++;
}
}
restconfService = mock(RestconfService.class);
final String jsonPath = RestconfImplTest.class.getResource("/parts/ietf-interfaces_interfaces.json").getPath();
jsonData = TestUtils.loadTextFile(jsonPath);
- final InputStream xmlStream = RestconfImplTest.class.getResourceAsStream("/parts/ietf-interfaces_interfaces.xml");
+ final InputStream xmlStream =
+ RestconfImplTest.class.getResourceAsStream("/parts/ietf-interfaces_interfaces.xml");
xmlData = TestUtils.getDocumentInPrintableForm(TestUtils.loadDocumentFrom(xmlStream));
}
// set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig = resourceConfig.registerInstances(restconfService, new NormalizedNodeJsonBodyWriter(),
- new NormalizedNodeXmlBodyWriter(), new XmlNormalizedNodeBodyReader(), new JsonNormalizedNodeBodyReader());
+ new NormalizedNodeXmlBodyWriter(), new XmlNormalizedNodeBodyReader(), new JsonNormalizedNodeBodyReader());
resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
return resourceConfig;
}
final String uriPrefix = "/operations/";
final String uriPath = "ietf-interfaces:interfaces";
final String uri = uriPrefix + uriPath;
- when(restconfService.invokeRpc(eq(uriPath), any(NormalizedNodeContext.class), any(UriInfo.class))).thenReturn(null);
+ when(restconfService.invokeRpc(eq(uriPath), any(NormalizedNodeContext.class), any(UriInfo.class)))
+ .thenReturn(null);
post(uri, Draft02.MediaTypes.OPERATION + JSON, Draft02.MediaTypes.OPERATION + JSON, jsonData);
verify(restconfService, times(1)).invokeRpc(eq(uriPath), any(NormalizedNodeContext.class), any(UriInfo.class));
post(uri, Draft02.MediaTypes.OPERATION + XML, Draft02.MediaTypes.OPERATION + XML, xmlData);
return target(uri).request(acceptMediaType).get().getStatus();
}
- private int put(final String uri, final String acceptMediaType, final String contentTypeMediaType, final String data) {
+ private int put(final String uri, final String acceptMediaType, final String contentTypeMediaType,
+ final String data) {
if (acceptMediaType == null) {
return target(uri).request().put(Entity.entity(data, contentTypeMediaType)).getStatus();
}
return target(uri).request(acceptMediaType).put(Entity.entity(data, contentTypeMediaType)).getStatus();
}
- private int post(final String uri, final String acceptMediaType, final String contentTypeMediaType, final String data) {
+ private int post(final String uri, final String acceptMediaType, final String contentTypeMediaType,
+ final String data) {
if (acceptMediaType == null) {
if ((contentTypeMediaType == null) || (data == null)) {
return target(uri).request().post(null).getStatus();
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.restconf.impl.test;
-
-
-/**
- * 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
- */
-public class MultipleEqualNamesForDataNodesTest {
-
-}
// set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig = resourceConfig.registerInstances(restconfImpl, new NormalizedNodeJsonBodyWriter(),
- new NormalizedNodeXmlBodyWriter(), new XmlNormalizedNodeBodyReader(), new JsonNormalizedNodeBodyReader());
+ new NormalizedNodeXmlBodyWriter(), new XmlNormalizedNodeBodyReader(), new JsonNormalizedNodeBodyReader());
resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
return resourceConfig;
}
@Test
public void augmentedNodesInUri() {
- InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier("main:cont/augment-main-a:cont1");
+ InstanceIdentifierContext<?> iiWithData =
+ controllerContext.toInstanceIdentifier("main:cont/augment-main-a:cont1");
assertEquals("ns:augment:main:a", iiWithData.getSchemaNode().getQName().getNamespace().toString());
iiWithData = controllerContext.toInstanceIdentifier("main:cont/augment-main-b:cont1");
assertEquals("ns:augment:main:b", iiWithData.getSchemaNode().getQName().getNamespace().toString());
controllerContext.toInstanceIdentifier("main:cont/cont1");
fail("Expected exception");
} catch (final 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"));
}
}
}
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
-import java.io.FileNotFoundException;
-import java.io.UnsupportedEncodingException;
import java.net.URI;
-import java.net.URISyntaxException;
-import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
private static final String RESTCONF_NS = "urn:ietf:params:xml:ns:yang:ietf-restconf";
@BeforeClass
- public static void init() throws FileNotFoundException, ParseException, ReactorException {
+ public static void init() throws Exception {
schemaContextYangsIetf = TestUtils.loadSchemaContext("/full-versions/yangs");
schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
brokerFacade = mock(BrokerFacade.class);
// set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig = resourceConfig.registerInstances(restconfImpl, new NormalizedNodeJsonBodyWriter(),
- new NormalizedNodeXmlBodyWriter(), new XmlNormalizedNodeBodyReader(), new JsonNormalizedNodeBodyReader());
+ new NormalizedNodeXmlBodyWriter(), new XmlNormalizedNodeBodyReader(), new JsonNormalizedNodeBodyReader());
resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
resourceConfig.registerClasses(new RestconfApplication().getClasses());
return resourceConfig;
* Tests of status codes for "/operational/{identifier}".
*/
@Test
- public void getOperationalStatusCodes() throws UnsupportedEncodingException {
+ public void getOperationalStatusCodes() throws Exception {
setControllerContext(schemaContextYangsIetf);
mockReadOperationalDataMethod();
String uri = "/operational/ietf-interfaces:interfaces/interface/eth0";
* Tests of status codes for "/config/{identifier}".
*/
@Test
- public void getConfigStatusCodes() throws UnsupportedEncodingException {
+ public void getConfigStatusCodes() throws Exception {
setControllerContext(schemaContextYangsIetf);
mockReadConfigurationDataMethod();
String uri = "/config/ietf-interfaces:interfaces/interface/eth0";
*/
@SuppressWarnings("unchecked")
@Test
- public void getDataWithUrlMountPoint() throws UnsupportedEncodingException, URISyntaxException, ParseException {
+ public void getDataWithUrlMountPoint() throws Exception {
when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class),
Mockito.anyString())).thenReturn(
prepareCnDataForMountPointTest(false));
/**
* 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#readConfigurationData(DOMMountPoint, YangInstanceIdentifier)} which is called in
* method {@link RestconfImpl#readConfigurationData}
- *
- * @throws ParseException
*/
@Test
- public void getDataWithSlashesBehindMountPoint() throws ParseException {
+ public void getDataWithSlashesBehindMountPoint() throws Exception {
final YangInstanceIdentifier awaitedInstanceIdentifier = prepareInstanceIdentifierForList();
when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), eq(awaitedInstanceIdentifier),
Mockito.anyString())).thenReturn(prepareCnDataForSlashesBehindMountPointTest());
ControllerContext.getInstance().setMountService(mockMountService);
- final String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont/lst1/GigabitEthernet0%2F0%2F0%2F0";
+ final String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/"
+ + "test-module:cont/lst1/GigabitEthernet0%2F0%2F0%2F0";
assertEquals(200, get(uri, MediaType.APPLICATION_XML));
}
- private static YangInstanceIdentifier prepareInstanceIdentifierForList() throws ParseException {
+ private static YangInstanceIdentifier prepareInstanceIdentifierForList() throws Exception {
final List<PathArgument> parameters = new ArrayList<>();
final QName qNameCont = newTestModuleQName("cont");
return YangInstanceIdentifier.create(parameters);
}
- private static QName newTestModuleQName(final String localPart) throws ParseException {
+ private static QName newTestModuleQName(final String localPart) throws Exception {
final Date revision = SimpleDateFormatUtil.getRevisionFormat().parse("2014-01-09");
final URI uri = URI.create("test:module");
return QName.create(uri, revision, localPart);
}
@Test
- public void getDataMountPointIntoHighestElement() throws UnsupportedEncodingException, URISyntaxException,
- ParseException {
+ public void getDataMountPointIntoHighestElement() throws Exception {
when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class),
Mockito.anyString())).thenReturn(
prepareCnDataForMountPointTest(true));
final YangInstanceIdentifier iid = YangInstanceIdentifier.builder().node(newTestModuleQName("modules"))
.node(moduleQN).nodeWithKey(moduleQN, keyMap).build();
@SuppressWarnings("rawtypes")
- final
- NormalizedNode data = ImmutableMapNodeBuilder.create().withNodeIdentifier(
+ final NormalizedNode data = ImmutableMapNodeBuilder.create().withNodeIdentifier(
new NodeIdentifier(moduleQN)).withChild(ImmutableNodes.mapEntryBuilder()
- .withNodeIdentifier(new NodeIdentifierWithPredicates(moduleQN, keyMap))
- .withChild(ImmutableNodes.leafNode(newTestModuleQName("type"), newTestModuleQName("test-identity")))
- .withChild(ImmutableNodes.leafNode(newTestModuleQName("name"), "foo"))
- .withChild(ImmutableNodes.leafNode(newTestModuleQName("data"), "bar")).build()).build();
+ .withNodeIdentifier(new NodeIdentifierWithPredicates(moduleQN, keyMap))
+ .withChild(ImmutableNodes.leafNode(newTestModuleQName("type"), newTestModuleQName("test-identity")))
+ .withChild(ImmutableNodes.leafNode(newTestModuleQName("name"), "foo"))
+ .withChild(ImmutableNodes.leafNode(newTestModuleQName("data"), "bar")).build()).build();
when(brokerFacade.readConfigurationData(iid, null)).thenReturn(data);
final String uri = "/config/test-module:modules/module/test-module:test-identity/foo";
// /modules
@Test
- public void getModulesTest() throws UnsupportedEncodingException, FileNotFoundException {
+ public void getModulesTest() throws Exception {
final ControllerContext controllerContext = ControllerContext.getInstance();
controllerContext.setGlobalSchema(schemaContextModules);
restconfImpl.setControllerContext(controllerContext);
// /streams/
@Test
@Ignore // FIXME : find why it is fail by in gerrit build
- public void getStreamsTest() throws UnsupportedEncodingException, FileNotFoundException {
+ public void getStreamsTest() throws Exception {
setControllerContext(schemaContextModules);
final String uri = "/streams";
// /modules/module
@Test
- public void getModuleTest() throws FileNotFoundException, UnsupportedEncodingException {
+ public void getModuleTest() throws Exception {
setControllerContext(schemaContextModules);
final String uri = "/modules/module/module2/2014-01-02";
// /operations
@Ignore
@Test
- public void getOperationsTest() throws FileNotFoundException, UnsupportedEncodingException {
+ public void getOperationsTest() throws Exception {
setControllerContext(schemaContextModules);
final String uri = "/operations";
validateOperationsResponseJson(responseBody, "dummy-rpc1-module2", "module2").find());
assertTrue("Json response for /operations dummy-rpc2-module2 is incorrect",
validateOperationsResponseJson(responseBody, "dummy-rpc2-module2", "module2").find());
-
}
private static void validateOperationsResponseXml(final Document responseDoc, final SchemaContext schemaContext) {
}
}
+ private static Matcher validateOperationsResponseXml(final String searchIn, final String rpcName,
+ final String namespace) {
+ final StringBuilder regex = new StringBuilder();
+
+ regex.append("^");
+
+ regex.append(".*<operations");
+ regex.append(".*xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\"");
+ regex.append(".*>");
+
+ regex.append(".*<");
+ regex.append(".*" + rpcName);
+ regex.append(".*" + namespace);
+ regex.append(".*/");
+ regex.append(".*>");
+
+ regex.append(".*</operations.*");
+ regex.append(".*>");
+
+ regex.append(".*");
+ regex.append("$");
+ final Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
+ return ptrn.matcher(searchIn);
+ }
+
// /operations/pathToMountPoint/yang-ext:mount
@Ignore
@Test
- public void getOperationsBehindMountPointTest() throws FileNotFoundException, UnsupportedEncodingException {
+ public void getOperationsBehindMountPointTest() throws Exception {
setControllerContext(schemaContextModules);
final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
assertEquals(200, response.getStatus());
final String responseBody = response.readEntity(String.class);
assertTrue("Json response for /operations/mount_point rpc-behind-module1 is incorrect",
- validateOperationsResponseJson(responseBody, "rpc-behind-module1", "module1-behind-mount-point").find());
+ validateOperationsResponseJson(responseBody, "rpc-behind-module1", "module1-behind-mount-point").find());
assertTrue("Json response for /operations/mount_point rpc-behind-module2 is incorrect",
- validateOperationsResponseJson(responseBody, "rpc-behind-module2", "module2-behind-mount-point").find());
+ validateOperationsResponseJson(responseBody, "rpc-behind-module2", "module2-behind-mount-point").find());
}
}
- private static Matcher validateOperationsResponseXml(final String searchIn, final String rpcName,
- final String namespace) {
- final StringBuilder regex = new StringBuilder();
-
- regex.append("^");
-
- regex.append(".*<operations");
- regex.append(".*xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\"");
- regex.append(".*>");
-
- regex.append(".*<");
- regex.append(".*" + rpcName);
- regex.append(".*" + namespace);
- regex.append(".*/");
- regex.append(".*>");
-
- regex.append(".*</operations.*");
- regex.append(".*>");
-
- regex.append(".*");
- regex.append("$");
- final Pattern ptrn = Pattern.compile(regex.toString(), Pattern.DOTALL);
- return ptrn.matcher(searchIn);
- }
-
// /restconf/modules/pathToMountPoint/yang-ext:mount
@Test
- public void getModulesBehindMountPoint() throws FileNotFoundException, UnsupportedEncodingException {
+ public void getModulesBehindMountPoint() throws Exception {
setControllerContext(schemaContextModules);
final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
// /restconf/modules/module/pathToMountPoint/yang-ext:mount/moduleName/revision
@Test
- public void getModuleBehindMountPoint() throws FileNotFoundException, UnsupportedEncodingException {
+ public void getModuleBehindMountPoint() throws Exception {
setControllerContext(schemaContextModules);
final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
ControllerContext.getInstance().setMountService(mockMountService);
- final String uri = "/modules/module/ietf-interfaces:interfaces/interface/0/yang-ext:mount/module1-behind-mount-point/2014-02-03";
+ final String uri = "/modules/module/ietf-interfaces:interfaces/interface/0/yang-ext:mount/"
+ + "module1-behind-mount-point/2014-02-03";
Response response = target(uri).request("application/yang.api+json").get();
assertEquals(200, response.getStatus());
final HashSet<QName> foundModules = new HashSet<>();
- for(int i=0;i < moduleNodes.getLength();i++) {
+ for (int i = 0; i < moduleNodes.getLength(); i++) {
final org.w3c.dom.Node module = moduleNodes.item(i);
final QName name = assertedModuleXmlToModuleQName(module);
}
private static void assertAllModules(final Set<QName> foundModules, final SchemaContext schemaContext) {
- for(final Module module : schemaContext.getModules()) {
- final QName current = QName.create(module.getQNameModule(),module.getName());
- assertTrue("Module not found in response.",foundModules.contains(current));
+ for (final Module module : schemaContext.getModules()) {
+ final QName current = QName.create(module.getQNameModule(), module.getName());
+ assertTrue("Module not found in response.", foundModules.contains(current));
}
}
final NodeList childNodes = module.getChildNodes();
- for(int i =0;i < childNodes.getLength(); i++) {
+ for (int i = 0; i < childNodes.getLength(); i++) {
final org.w3c.dom.Node child = childNodes.item(i);
assertEquals(RESTCONF_NS, child.getNamespaceURI());
- switch(child.getLocalName()) {
+ switch (child.getLocalName()) {
case "name":
- assertNull("Name element appeared multiple times",name);
+ assertNull("Name element appeared multiple times", name);
name = child.getTextContent().trim();
break;
case "revision":
- assertNull("Revision element appeared multiple times",revision);
+ assertNull("Revision element appeared multiple times", revision);
revision = child.getTextContent().trim();
break;
-
case "namespace":
- assertNull("Namespace element appeared multiple times",namespace);
+ assertNull("Namespace element appeared multiple times", namespace);
namespace = child.getTextContent().trim();
break;
+ default:
+ break;
}
}
assertNotNull("Module namespace was not part of xml",namespace);
assertNotNull("Module identiffier was not part of xml",name);
-
- // TODO Auto-generated method stub
-
return QName.create(namespace,revision,name);
}
}
/**
- container cont {
- container cont1 {
- leaf lf11 {
- type string;
- }
- */
+ * Container structure.
+ *
+ * <p>
+ * container cont {
+ * container cont1 {
+ * leaf lf11 {
+ * type string;
+ * }
+ */
@SuppressWarnings("rawtypes")
- private static NormalizedNode prepareCnDataForMountPointTest(final boolean wrapToCont)
- throws URISyntaxException, ParseException {
+ private static NormalizedNode prepareCnDataForMountPointTest(final boolean wrapToCont) throws Exception {
final String testModuleDate = "2014-01-09";
final ContainerNode contChild = Builders
.containerBuilder()
}
@SuppressWarnings("rawtypes")
- private static NormalizedNode prepareCnDataForSlashesBehindMountPointTest() throws ParseException {
+ private static NormalizedNode prepareCnDataForSlashesBehindMountPointTest() throws Exception {
return ImmutableMapEntryNodeBuilder
.create()
.withNodeIdentifier(
}
/**
- * If includeWhiteChars URI parameter is set to false then no white characters can be included in returned output
- *
- * @throws UnsupportedEncodingException
+ * If includeWhiteChars URI parameter is set to false then no white characters can be included in returned output.
*/
@Test
- public void getDataWithUriIncludeWhiteCharsParameterTest() throws UnsupportedEncodingException {
+ public void getDataWithUriIncludeWhiteCharsParameterTest() throws Exception {
getDataWithUriIncludeWhiteCharsParameter("config");
getDataWithUriIncludeWhiteCharsParameter("operational");
}
- private void getDataWithUriIncludeWhiteCharsParameter(final String target) throws UnsupportedEncodingException {
+ private void getDataWithUriIncludeWhiteCharsParameter(final String target) throws Exception {
mockReadConfigurationDataMethod();
mockReadOperationalDataMethod();
final String uri = "/" + target + "/ietf-interfaces:interfaces/interface/eth0";
}
/**
- * Tests behavior when invalid value of depth URI parameter
+ * Tests behavior when invalid value of depth URI parameter.
*/
@Test
@Ignore
try {
final QName qNameDepth1Cont = QName.create("urn:nested:module", "2014-06-3", "depth1-cont");
final YangInstanceIdentifier ii = YangInstanceIdentifier.builder().node(qNameDepth1Cont).build();
- final NormalizedNode value = (Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(qNameDepth1Cont)).build());
+ final NormalizedNode value =
+ (Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(qNameDepth1Cont)).build());
when(brokerFacade.readConfigurationData(eq(ii))).thenReturn(value);
restconfImpl.readConfigurationData("nested-module:depth1-cont", uriInfo);
fail("Expected RestconfDocumentedException");
@SuppressWarnings("unused")
private void verifyXMLResponse(final Response response, final NodeData nodeData) {
final Document doc = response.readEntity(Document.class);
-// Document doc = TestUtils.loadDocumentFrom((InputStream) response.getEntity());
-// System.out.println();
assertNotNull("Could not parse XML document", doc);
- // System.out.println(TestUtils.getDocumentInPrintableForm( doc ));
-
verifyContainerElement(doc.getDocumentElement(), nodeData);
}
final NodeList childNodes = element.getChildNodes();
if (nodeData.data == null) { // empty container
- assertTrue("Expected no child elements for \"" + element.getLocalName() + "\"", childNodes.getLength() == 0);
+ assertTrue(
+ "Expected no child elements for \"" + element.getLocalName() + "\"", childNodes.getLength() == 0);
return;
}
// set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig = resourceConfig.registerInstances(restconfImpl, new XmlNormalizedNodeBodyReader(),
- new NormalizedNodeXmlBodyWriter(), new JsonNormalizedNodeBodyReader(), new NormalizedNodeJsonBodyWriter());
+ new NormalizedNodeXmlBodyWriter(), new JsonNormalizedNodeBodyReader(), new NormalizedNodeJsonBodyWriter());
resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
return resourceConfig;
}
@SuppressWarnings("unchecked")
@Test
- @Ignore //jenkins has problem with JerseyTest - we expecting problems with singletons ControllerContext as schemaContext holder
+ @Ignore //jenkins has problem with JerseyTest
+ // - we expecting problems with singletons ControllerContext as schemaContext holder
public void createConfigurationDataTest() throws UnsupportedEncodingException, ParseException {
initMocking();
final RpcResult<TransactionStatus> rpcResult = new DummyRpcResult.Builder<TransactionStatus>().result(
any(NormalizedNode.class), null, null))
.thenReturn(mock(CheckedFuture.class));
- final ArgumentCaptor<YangInstanceIdentifier> instanceIdCaptor = ArgumentCaptor.forClass(YangInstanceIdentifier.class);
+ final ArgumentCaptor<YangInstanceIdentifier> instanceIdCaptor =
+ ArgumentCaptor.forClass(YangInstanceIdentifier.class);
@SuppressWarnings("rawtypes")
final ArgumentCaptor<NormalizedNode> compNodeCaptor = ArgumentCaptor.forClass(NormalizedNode.class);
verify(brokerFacade, times(1))
.commitConfigurationDataPost((SchemaContext) null, instanceIdCaptor.capture(), compNodeCaptor.capture(),
null, null);
-// identifier = "[(urn:ietf:params:xml:ns:yang:test-interface?revision=2014-07-01)interfaces, (urn:ietf:params:xml:ns:yang:test-interface?revision=2014-07-01)block]";
+// identifier = "[(urn:ietf:params:xml:ns:yang:test-interface?revision=2014-07-01)interfaces," +
+// "(urn:ietf:params:xml:ns:yang:test-interface?revision=2014-07-01)block]";
assertEquals(identifier, ImmutableList.copyOf(instanceIdCaptor.getValue().getPathArguments()).toString());
}
xmlStream = RestconfImplTest.class
.getResourceAsStream("/parts/ietf-interfaces_interfaces_interface_absolute_path.xml");
xmlDataInterfaceAbsolutePath = TestUtils.getDocumentInPrintableForm(TestUtils.loadDocumentFrom(xmlStream));
- final String xmlPathRpcInput = RestconfImplTest.class.getResource("/full-versions/test-data2/data-rpc-input.xml")
- .getPath();
+ final String xmlPathRpcInput =
+ RestconfImplTest.class.getResource("/full-versions/test-data2/data-rpc-input.xml").getPath();
xmlDataRpcInput = TestUtils.loadTextFile(xmlPathRpcInput);
- final String xmlPathBlockData = RestconfImplTest.class.getResource("/test-config-data/xml/block-data.xml").getPath();
+ final String xmlPathBlockData =
+ RestconfImplTest.class.getResource("/test-config-data/xml/block-data.xml").getPath();
xmlBlockData = TestUtils.loadTextFile(xmlPathBlockData);
- final String xmlPathTestInterface = RestconfImplTest.class.getResource("/test-config-data/xml/test-interface.xml")
- .getPath();
+ final String xmlPathTestInterface =
+ RestconfImplTest.class.getResource("/test-config-data/xml/test-interface.xml").getPath();
xmlTestInterface = TestUtils.loadTextFile(xmlPathTestInterface);
// cnSnDataOutput = prepareCnSnRpcOutput();
final String data3Input = RestconfImplTest.class.getResource("/full-versions/test-data2/data3.xml").getPath();
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-/**
- * sal-rest-connector
- * org.opendaylight.controller.sal.restconf.impl.test
- *
- *
- *
- * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
- *
- * Created: May 14, 2015
- */
@RunWith(MockitoJUnitRunner.class)
public class RestPutConfigTest {
final MapEntryNode data = Mockito.mock(MapEntryNode.class);
final QName qName = QName.create("urn:ietf:params:xml:ns:yang:test-interface", "2014-07-01", "interface");
final QName qNameKey = QName.create("urn:ietf:params:xml:ns:yang:test-interface", "2014-07-01", "name");
- final NodeIdentifierWithPredicates identWithPredicates = new NodeIdentifierWithPredicates(qName, qNameKey, "key");
+ final NodeIdentifierWithPredicates identWithPredicates =
+ new NodeIdentifierWithPredicates(qName, qNameKey, "key");
Mockito.when(data.getNodeType()).thenReturn(qName);
Mockito.when(data.getIdentifier()).thenReturn(identWithPredicates);
final NormalizedNodeContext payload = new NormalizedNodeContext(iiCx, data);
final MapEntryNode data = Mockito.mock(MapEntryNode.class);
final QName qName = QName.create("urn:ietf:params:xml:ns:yang:test-interface", "2014-07-01", "sub-interface");
final QName qNameSubKey = QName.create("urn:ietf:params:xml:ns:yang:test-interface", "2014-07-01", "sub-name");
- final NodeIdentifierWithPredicates identWithPredicates = new NodeIdentifierWithPredicates(qName, qNameSubKey, "subkey");
+ final NodeIdentifierWithPredicates identWithPredicates =
+ new NodeIdentifierWithPredicates(qName, qNameSubKey, "subkey");
Mockito.when(data.getNodeType()).thenReturn(qName);
Mockito.when(data.getIdentifier()).thenReturn(identWithPredicates);
final NormalizedNodeContext payload = new NormalizedNodeContext(iiCx, data);
this.restconfService.updateConfigurationData(identifier, payload, uriInfo);
}
- @Test(expected=RestconfDocumentedException.class)
+ @Test(expected = RestconfDocumentedException.class)
public void testPutConfigDataMissingUriKey() {
final String identifier = "test-interface:interfaces/interface";
this.controllerCx.toInstanceIdentifier(identifier);
}
- @Test(expected=RestconfDocumentedException.class)
+ @Test(expected = RestconfDocumentedException.class)
public void testPutConfigDataDiferentKey() {
final String identifier = "test-interface:interfaces/interface/key";
final InstanceIdentifierContext<?> iiCx = this.controllerCx.toInstanceIdentifier(identifier);
final MapEntryNode data = Mockito.mock(MapEntryNode.class);
final QName qName = QName.create("urn:ietf:params:xml:ns:yang:test-interface", "2014-07-01", "interface");
final QName qNameKey = QName.create("urn:ietf:params:xml:ns:yang:test-interface", "2014-07-01", "name");
- final NodeIdentifierWithPredicates identWithPredicates = new NodeIdentifierWithPredicates(qName, qNameKey, "notSameKey");
+ final NodeIdentifierWithPredicates identWithPredicates =
+ new NodeIdentifierWithPredicates(qName, qNameKey, "notSameKey");
Mockito.when(data.getNodeType()).thenReturn(qName);
Mockito.when(data.getIdentifier()).thenReturn(identWithPredicates);
final NormalizedNodeContext payload = new NormalizedNodeContext(iiCx, data);
private void mockingBrokerPut(final YangInstanceIdentifier yii, final NormalizedNode<?, ?> data) {
final PutResult result = Mockito.mock(PutResult.class);
- final CheckedFuture<Void, TransactionCommitFailedException> checkedFuture = Futures.immediateCheckedFuture(null);
+ final CheckedFuture<Void, TransactionCommitFailedException> checkedFuture =
+ Futures.immediateCheckedFuture(null);
Mockito.when(this.brokerFacade.commitConfigurationDataPut(this.schemaCx, yii, data, null, null))
.thenReturn(result);
Mockito.when(result.getFutureOfPutData()).thenReturn(checkedFuture);
}
private static void loadData() throws IOException {
- final InputStream xmlStream = RestconfImplTest.class.getResourceAsStream("/parts/ietf-interfaces_interfaces.xml");
+ final InputStream xmlStream =
+ RestconfImplTest.class.getResourceAsStream("/parts/ietf-interfaces_interfaces.xml");
xmlData = TestUtils.getDocumentInPrintableForm(TestUtils.loadDocumentFrom(xmlStream));
- final InputStream xmlStream2 = RestconfImplTest.class.getResourceAsStream("/full-versions/test-data2/data2.xml");
+ final InputStream xmlStream2 =
+ RestconfImplTest.class.getResourceAsStream("/full-versions/test-data2/data2.xml");
xmlData2 = TestUtils.getDocumentInPrintableForm(TestUtils.loadDocumentFrom(xmlStream2));
- final InputStream xmlStream3 = RestconfImplTest.class.getResourceAsStream("/full-versions/test-data2/data7.xml");
+ final InputStream xmlStream3 =
+ RestconfImplTest.class.getResourceAsStream("/full-versions/test-data2/data7.xml");
xmlData3 = TestUtils.getDocumentInPrintableForm(TestUtils.loadDocumentFrom(xmlStream3));
}
// set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig = resourceConfig.registerInstances(restconfImpl,new XmlNormalizedNodeBodyReader(),
- new NormalizedNodeXmlBodyWriter(), new JsonNormalizedNodeBodyReader(), new NormalizedNodeJsonBodyWriter());
+ new NormalizedNodeXmlBodyWriter(), new JsonNormalizedNodeBodyReader(), new NormalizedNodeJsonBodyWriter());
resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
return resourceConfig;
}
final String uri = "/config/ietf-interfaces:interfaces/interface/eth0";
- doThrow(OptimisticLockFailedException.class).
- when(brokerFacade).commitConfigurationDataPut(
- any(SchemaContext.class), any(YangInstanceIdentifier.class), any(NormalizedNode.class), null,
- null);
+ doThrow(OptimisticLockFailedException.class).when(brokerFacade).commitConfigurationDataPut(
+ any(SchemaContext.class), any(YangInstanceIdentifier.class), any(NormalizedNode.class), null, null);
assertEquals(500, put(uri, MediaType.APPLICATION_XML, xmlData));
final String uri = "/config/ietf-interfaces:interfaces/interface/eth0";
- doThrow(TransactionCommitFailedException.class).
- when(brokerFacade).commitConfigurationDataPut(
- any(SchemaContext.class), any(YangInstanceIdentifier.class), any(NormalizedNode.class), null,
- null);
+ doThrow(TransactionCommitFailedException.class)
+ .when(brokerFacade).commitConfigurationDataPut(
+ any(SchemaContext.class), any(YangInstanceIdentifier.class), any(NormalizedNode.class), null, null);
assertEquals(500, put(uri, MediaType.APPLICATION_XML, xmlData));
}
String expTextContent;
- public SimpleErrorInfoVerifier(final String expErrorInfo) {
+ SimpleErrorInfoVerifier(final String expErrorInfo) {
expTextContent = expErrorInfo;
}
protected Application configure() {
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig = resourceConfig.registerInstances(mockRestConf, new XmlNormalizedNodeBodyReader(),
- new JsonNormalizedNodeBodyReader(), new NormalizedNodeJsonBodyWriter(), new NormalizedNodeXmlBodyWriter());
+ new JsonNormalizedNodeBodyReader(), new NormalizedNodeJsonBodyWriter(), new NormalizedNodeXmlBodyWriter());
resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
return resourceConfig;
}
@Ignore // FIXME : find why it return "error-type" RPC no expected APPLICATION
public void testToJsonResponseWithMultipleErrors() throws Exception {
- final List<RestconfError> errorList = Arrays.asList(new RestconfError(ErrorType.APPLICATION, ErrorTag.LOCK_DENIED,
- "mock error1"), new RestconfError(ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2"));
+ final 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("mock", null, errorList));
final Response resp = target("/operational/foo").request(MediaType.APPLICATION_JSON).get();
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);
}
@Ignore // FIXME : find why it return error-type as RPC no APPLICATION
public void testToXMLResponseWithMultipleErrors() throws Exception {
- final List<RestconfError> errorList = Arrays.asList(new RestconfError(ErrorType.APPLICATION, ErrorTag.LOCK_DENIED,
- "mock error1"), new RestconfError(ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2"));
+ final 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("mock", null, errorList));
final Response resp = target("/operational/foo").request(MediaType.APPLICATION_XML).get();
errorInfoVerifier);
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
private static JsonArray parseJsonErrorArrayElement(final InputStream stream) throws IOException {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
ByteStreams.copy(stream, bos);
- System.out.println("JSON: " + bos.toString());
+ LOG.info("JSON: " + bos.toString());
final JsonParser parser = new JsonParser();
JsonElement rootElement;
private final String text;
- public Contains(final String text) {
+ Contains(final String text) {
this.text = text;
}
String expectedMessage = "Message";
ErrorType expectedErrorType = ErrorType.RPC;
ErrorTag expectedErrorTag = ErrorTag.IN_USE;
- RestconfError e = new RestconfError(expectedErrorType, expectedErrorTag, expectedMessage);
+ RestconfError error = new RestconfError(expectedErrorType, expectedErrorTag, expectedMessage);
- validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag, null, (String) null, e);
+ validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag, null, (String) null, error);
}
@Test
ErrorTag expectedErrorTag = ErrorTag.IN_USE;
String expectedErrorAppTag = "application.tag";
- RestconfError e = new RestconfError(expectedErrorType, expectedErrorTag, expectedMessage, expectedErrorAppTag);
+ RestconfError error =
+ new RestconfError(expectedErrorType, expectedErrorTag, expectedMessage, expectedErrorAppTag);
validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag, expectedErrorAppTag, (String) null,
- e);
+ error);
}
@Test
String expectedErrorAppTag = "application.tag";
String errorInfo = "<extra><sessionid>session.id</sessionid></extra>";
- RestconfError e = new RestconfError(expectedErrorType, expectedErrorTag, expectedMessage, expectedErrorAppTag,
- errorInfo);
+ RestconfError error =
+ new RestconfError(expectedErrorType, expectedErrorTag, expectedMessage, expectedErrorAppTag, errorInfo);
- validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag, expectedErrorAppTag, errorInfo, e);
+ validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag, expectedErrorAppTag, errorInfo,
+ error);
}
@Test
// All fields set
RpcError rpcError = RpcResultBuilder.newError(
RpcError.ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE.getTagValue(), "mock error-message",
- "mock app-tag", "mock error-info", new Exception( "mock cause" ) );
+ "mock app-tag", "mock error-info", new Exception("mock cause"));
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 = RpcResultBuilder.newError(
RpcError.ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE.getTagValue(), "mock error-message",
- "mock app-tag", null, new Exception( "mock cause" ) );
+ "mock app-tag", null, new Exception("mock cause"));
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 = RpcResultBuilder.newError(
- RpcError.ErrorType.RPC, ErrorTag.ACCESS_DENIED.getTagValue(), null, null, null, null );
+ RpcError.ErrorType.RPC, ErrorTag.ACCESS_DENIED.getTagValue(), null, null, null, null);
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 = RpcResultBuilder.newWarning(
- RpcError.ErrorType.TRANSPORT, "not mapped", null, null, null, null );
+ RpcError.ErrorType.TRANSPORT, "not mapped", null, null, null, null);
validateRestConfError(null, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED, null,
"<severity>warning</severity>", new RestconfError(rpcError));
// No fields set - edge case
- rpcError = RpcResultBuilder.newError( null, null, null, null, null, null );
+ rpcError = RpcResultBuilder.newError(null, null, null, null, null, null);
- validateRestConfError( null, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED,
- null, "<severity>error</severity>", new RestconfError( rpcError ) );
+ validateRestConfError(null, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED,
+ null, "<severity>error</severity>", new RestconfError(rpcError));
}
private static void validateRestConfError(final String expectedMessage, final ErrorType expectedErrorType,
final ErrorTag expectedErrorTag, final String expectedErrorAppTag, final String errorInfo,
- final RestconfError e) {
+ final RestconfError error) {
validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag, expectedErrorAppTag,
- equalTo(errorInfo), e);
+ equalTo(errorInfo), error);
}
private static void validateRestConfError(final String expectedMessage, final ErrorType expectedErrorType,
final ErrorTag expectedErrorTag, final String expectedErrorAppTag, final Matcher<String> errorInfoMatcher,
- final 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
+ final RestconfError error) {
+
+ assertEquals("getErrorMessage", expectedMessage, error.getErrorMessage());
+ assertEquals("getErrorType", expectedErrorType, error.getErrorType());
+ assertEquals("getErrorTag", expectedErrorTag, error.getErrorTag());
+ assertEquals("getErrorAppTag", expectedErrorAppTag, error.getErrorAppTag());
+ assertThat("getErrorInfo", error.getErrorInfo(), errorInfoMatcher);
+ error.toString(); // really just checking for NPE etc. Don't care about
// contents.
}
}
final UriBuilder uriBuilder = UriBuilder.fromPath("http://localhost:8181/" + this.identifier);
Mockito.when(this.uriInfo.getAbsolutePathBuilder()).thenReturn(uriBuilder);
final Set<Entry<String, List<String>>> set = new HashSet<>();
- for(final Entry<String, List<String>> entry : entries){
+ for (final Entry<String, List<String>> entry : entries) {
set.add(entry);
}
Mockito.when(map.entrySet()).thenReturn(set);
import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
/**
- * @See {@link InvokeRpcMethodTest}
- *
+ * See {@link InvokeRpcMethodTest}.
*/
public class RestconfImplTest {
@Test
public void testExample() throws FileNotFoundException, ParseException {
@SuppressWarnings("rawtypes")
- final
- NormalizedNode normalizedNodeData = TestUtils.prepareNormalizedNodeWithIetfInterfacesInterfacesData();
+ final NormalizedNode normalizedNodeData = TestUtils.prepareNormalizedNodeWithIetfInterfacesInterfacesData();
final BrokerFacade brokerFacade = mock(BrokerFacade.class);
when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn(normalizedNodeData);
assertEquals(normalizedNodeData,
}
/**
- * Create notification stream for toaster module
+ * Create notification stream for toaster module.
*/
@Test
public void createNotificationStreamTest() {
}
/**
- * Subscribe for notification stream of toaster module
+ * Subscribe for notification stream of toaster module.
*/
@Test
public void subscribeToNotificationStreamTest() throws Exception {
"number of keys argument have to be divisible by 2 (map)");
final Map<QName, Object> predicate = new HashMap<>();
- int i = 0;
- while (i < keysAndValues.length) {
- predicate.put(QName.create(namespace, revision, keysAndValues[i++]), keysAndValues[i++]);
+ int index = 0;
+ while (index < keysAndValues.length) {
+ predicate.put(QName.create(namespace, revision, keysAndValues[index++]), keysAndValues[index++]);
}
return new NodeIdentifierWithPredicates(QName.create(namespace, revision, localName), predicate);
when(mockedUriInfo.getQueryParameters(eq(false))).thenReturn(mockedMultivaluedMap);
- final UriBuilder uriBuilder = UriBuilder.fromUri("www.whatever.com");
- when(mockedUriInfo.getAbsolutePathBuilder()).thenReturn(uriBuilder);
+ final UriBuilder uriBuilder = UriBuilder.fromUri("www.whatever.com");
+ when(mockedUriInfo.getAbsolutePathBuilder()).thenReturn(uriBuilder);
this.restconf.invokeRpc("sal-remote:create-data-change-event-subscription", prepareDomRpcNode(datastore, scope),
mockedUriInfo);
final Date revDate;
try {
revDate = getRevisionFormat().parse("2014-01-14");
- }
- catch (final ParseException e) {
+ } catch (final ParseException e) {
throw new IllegalStateException(e);
}
final Module rpcSalRemoteModule = schema.findModuleByName("sal-remote", revDate);
final Set<RpcDefinition> setRpcs = rpcSalRemoteModule.getRpcs();
- final QName rpcQName = QName.create(rpcSalRemoteModule.getQNameModule(), "create-data-change-event-subscription");
+ final QName rpcQName =
+ QName.create(rpcSalRemoteModule.getQNameModule(), "create-data-change-event-subscription");
final QName rpcInputQName =
QName.create("urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "2014-01-14", "input");
final RpcDefinition rpcDef = Mockito.mock(RpcDefinition.class);
public class URITest {
- private static final ControllerContext controllerContext = ControllerContext.getInstance();
+ private static final ControllerContext CONTROLLER_CONTEXT = ControllerContext.getInstance();
@Rule
public ExpectedException exception = ExpectedException.none();
final Set<Module> allModules = schemaContext.getModules();
assertNotNull(allModules);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
public void testToInstanceIdentifierList() throws FileNotFoundException {
- InstanceIdentifierContext<?> instanceIdentifier = controllerContext
+ InstanceIdentifierContext<?> instanceIdentifier = CONTROLLER_CONTEXT
.toInstanceIdentifier("simple-nodes:userWithoutClass/foo");
assertEquals(instanceIdentifier.getSchemaNode().getQName().getLocalName(), "userWithoutClass");
- instanceIdentifier = controllerContext.toInstanceIdentifier("simple-nodes:userWithoutClass/foo");
+ instanceIdentifier = CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes:userWithoutClass/foo");
assertEquals(instanceIdentifier.getSchemaNode().getQName().getLocalName(), "userWithoutClass");
- instanceIdentifier = controllerContext.toInstanceIdentifier("simple-nodes:user/foo/boo");
+ instanceIdentifier = CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes:user/foo/boo");
assertEquals(instanceIdentifier.getSchemaNode().getQName().getLocalName(), "user");
- instanceIdentifier = controllerContext.toInstanceIdentifier("simple-nodes:user//boo");
+ instanceIdentifier = CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes:user//boo");
assertEquals(instanceIdentifier.getSchemaNode().getQName().getLocalName(), "user");
}
@Test
public void testToInstanceIdentifierListWithNullKey() {
this.exception.expect(RestconfDocumentedException.class);
- controllerContext.toInstanceIdentifier("simple-nodes:user/null/boo");
+ CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes:user/null/boo");
}
@Test
public void testToInstanceIdentifierListWithMissingKey() {
this.exception.expect(RestconfDocumentedException.class);
- controllerContext.toInstanceIdentifier("simple-nodes:user/foo");
+ CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes:user/foo");
}
@Test
public void testToInstanceIdentifierContainer() throws FileNotFoundException {
- final InstanceIdentifierContext<?> instanceIdentifier = controllerContext.toInstanceIdentifier("simple-nodes:users");
+ final InstanceIdentifierContext<?> instanceIdentifier =
+ CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes:users");
assertEquals(instanceIdentifier.getSchemaNode().getQName().getLocalName(), "users");
assertTrue(instanceIdentifier.getSchemaNode() instanceof ContainerSchemaNode);
assertEquals(2, ((ContainerSchemaNode) instanceIdentifier.getSchemaNode()).getChildNodes().size());
}
@Test
- @Ignore //jenkins has problem with JerseyTest - we expecting problems with singletons ControllerContext as schemaContext holder
+ @Ignore //jenkins has problem with JerseyTest
+ // - we expecting problems with singletons ControllerContext as schemaContext holder
public void testToInstanceIdentifierChoice() throws FileNotFoundException {
- final InstanceIdentifierContext<?> instanceIdentifier = controllerContext
+ final InstanceIdentifierContext<?> instanceIdentifier = CONTROLLER_CONTEXT
.toInstanceIdentifier("simple-nodes:food/nonalcoholic");
assertEquals(instanceIdentifier.getSchemaNode().getQName().getLocalName(), "nonalcoholic");
}
@Test
public void testToInstanceIdentifierChoiceException() {
this.exception.expect(RestconfDocumentedException.class);
- controllerContext.toInstanceIdentifier("simple-nodes:food/snack");
+ CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes:food/snack");
}
@Test
public void testToInstanceIdentifierCaseException() {
this.exception.expect(RestconfDocumentedException.class);
- controllerContext.toInstanceIdentifier("simple-nodes:food/sports-arena");
+ CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes:food/sports-arena");
}
@Test
public void testToInstanceIdentifierChoiceCaseException() {
this.exception.expect(RestconfDocumentedException.class);
- controllerContext.toInstanceIdentifier("simple-nodes:food/snack/sports-arena");
+ CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes:food/snack/sports-arena");
}
@Test
public void testToInstanceIdentifierWithoutNode() {
this.exception.expect(RestconfDocumentedException.class);
- controllerContext.toInstanceIdentifier("simple-nodes");
+ CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes");
}
@Test
public void testMountPointWithExternModul() throws FileNotFoundException, ReactorException {
initMountService(true);
- final InstanceIdentifierContext<?> instanceIdentifier = controllerContext
+ final InstanceIdentifierContext<?> instanceIdentifier = CONTROLLER_CONTEXT
.toInstanceIdentifier("simple-nodes:users/yang-ext:mount/test-interface2:class/student/name");
assertEquals(
- "[(urn:ietf:params:xml:ns:yang:test-interface2?revision=2014-08-01)class, (urn:ietf:params:xml:ns:yang:test-interface2?revision=2014-08-01)student, (urn:ietf:params:xml:ns:yang:test-interface2?revision=2014-08-01)student[{(urn:ietf:params:xml:ns:yang:test-interface2?revision=2014-08-01)name=name}]]",
+ "[(urn:ietf:params:xml:ns:yang:test-interface2?revision=2014-08-01)class, "
+ + "(urn:ietf:params:xml:ns:yang:test-interface2?revision=2014-08-01)student, "
+ + "(urn:ietf:params:xml:ns:yang:test-interface2?revision=2014-08-01)student"
+ + "[{(urn:ietf:params:xml:ns:yang:test-interface2?revision=2014-08-01)name=name}]]",
ImmutableList.copyOf(instanceIdentifier.getInstanceIdentifier().getPathArguments()).toString());
}
@Test
public void testMountPointWithoutExternModul() throws FileNotFoundException, ReactorException {
initMountService(true);
- final InstanceIdentifierContext<?> instanceIdentifier = controllerContext
+ final InstanceIdentifierContext<?> instanceIdentifier = CONTROLLER_CONTEXT
.toInstanceIdentifier("simple-nodes:users/yang-ext:mount/");
assertTrue(Iterables.isEmpty(instanceIdentifier.getInstanceIdentifier().getPathArguments()));
}
public void testMountPointWithoutMountService() throws FileNotFoundException {
this.exception.expect(RestconfDocumentedException.class);
- controllerContext.setMountService(null);
- controllerContext.toInstanceIdentifier("simple-nodes:users/yang-ext:mount/test-interface2:class/student/name");
+ CONTROLLER_CONTEXT.setMountService(null);
+ CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes:users/yang-ext:mount/test-interface2:class/student/name");
}
@Test
initMountService(false);
this.exception.expect(RestconfDocumentedException.class);
- controllerContext.toInstanceIdentifier("simple-nodes:users/yang-ext:mount/test-interface2:class");
+ CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes:users/yang-ext:mount/test-interface2:class");
}
public void initMountService(final boolean withSchema) throws FileNotFoundException, ReactorException {
final DOMMountPointService mountService = mock(DOMMountPointService.class);
- controllerContext.setMountService(mountService);
+ CONTROLLER_CONTEXT.setMountService(mountService);
final BrokerFacade brokerFacade = mock(BrokerFacade.class);
final RestconfImpl restconfImpl = RestconfImpl.getInstance();
restconfImpl.setBroker(brokerFacade);
- restconfImpl.setControllerContext(controllerContext);
+ restconfImpl.setControllerContext(CONTROLLER_CONTEXT);
final SchemaContext schemaContext2 = TestUtils.loadSchemaContext("/test-config-data/yang2");
final Set<Module> modules2 = schemaContext2.getModules();
*/
public interface IClientMessageCallback {
- public void onMessageReceived(Object message);
+ void onMessageReceived(Object message);
}
public class WebSocketClient {
+ private static final Logger LOG = LoggerFactory.getLogger(WebSocketClient.class);
+
private final URI uri;
private final Bootstrap bootstrap = new Bootstrap();
private final WebSocketClientHandler clientHandler;
- private static final Logger logger = LoggerFactory.getLogger(WebSocketClient.class);
private Channel clientChannel;
private final EventLoopGroup group = new NioEventLoopGroup();
public WebSocketClient(final URI uri, final IClientMessageCallback clientMessageCallback) {
this.uri = uri;
clientHandler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri,
- WebSocketVersion.V13, null, false, null), clientMessageCallback); // last
- // null
- // could
- // be
- // replaced
- // with
- // DefaultHttpHeaders
+ WebSocketVersion.V13, null, false, null), clientMessageCallback);
+ // last null could be replaced with DefaultHttpHeaders
initialize();
}
}
public void connect() throws InterruptedException {
- System.out.println("WebSocket Client connecting");
+ LOG.info("WebSocket Client connecting");
clientChannel = bootstrap.connect(uri.getHost(), uri.getPort()).sync().channel();
clientHandler.handshakeFuture().sync();
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
if (input.equals("q")) {
- System.out.print("Would you like to close stream? (Y = yes, empty = yes)\n");
+ LOG.info("Would you like to close stream? (Y = yes, empty = yes)\n");
input = br.readLine();
if (input.equals("yes") || input.isEmpty()) {
webSocketClient.close("opendaylight-inventory:nodes");
@Override
public void onMessageReceived(final Object message) {
if (message instanceof TextWebSocketFrame) {
- logger.info("received message {}" + ((TextWebSocketFrame) message).text());
+ LOG.info("received message {}" + ((TextWebSocketFrame) message).text());
}
}
}
public class WebSocketClientHandler extends SimpleChannelInboundHandler<Object> {
- private static final Logger logger = LoggerFactory.getLogger(WebSocketClientHandler.class.toString());
+ private static final Logger LOG = LoggerFactory.getLogger(WebSocketClientHandler.class.toString());
private final WebSocketClientHandshaker handshaker;
private ChannelPromise handshakeFuture;
private final IClientMessageCallback messageListener;
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
- logger.info("WebSocket Client disconnected!");
+ LOG.info("WebSocket Client disconnected!");
}
@Override
Channel ch = ctx.channel();
if (!handshaker.isHandshakeComplete()) {
handshaker.finishHandshake(ch, (FullHttpResponse) msg);
- logger.info("WebSocket Client connected!");
+ LOG.info("WebSocket Client connected!");
handshakeFuture.setSuccess();
return;
}
WebSocketFrame frame = (WebSocketFrame) msg;
if (frame instanceof PongWebSocketFrame) {
- logger.info("WebSocket Client received pong");
+ LOG.info("WebSocket Client received pong");
} else if (frame instanceof CloseWebSocketFrame) {
- logger.info("WebSocket Client received closing");
+ LOG.info("WebSocket Client received closing");
ch.close();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
- cause.printStackTrace();
+ LOG.info("Cause: {} .", cause.toString());
if (!handshakeFuture.isDone()) {
handshakeFuture.setFailure(cause);
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
-import java.util.logging.Level;
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.glassfish.jersey.test.TestProperties;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
// set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig = resourceConfig.registerInstances(restconfImpl, new NormalizedNodeJsonBodyWriter(),
- new NormalizedNodeXmlBodyWriter(), new XmlNormalizedNodeBodyReader(), new JsonNormalizedNodeBodyReader());
+ new NormalizedNodeXmlBodyWriter(), new XmlNormalizedNodeBodyReader(), new JsonNormalizedNodeBodyReader());
resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
return resourceConfig;
}
final Node streamNameElement = outputElement.getFirstChild();
assertEquals("stream-name",streamNameElement.getLocalName());
- assertEquals("data-change-event-subscription/ietf-interfaces:interfaces/ietf-interfaces:interface/eth0/datastore=CONFIGURATION/scope=BASE",streamNameElement.getTextContent());
+ assertEquals("data-change-event-subscription/ietf-interfaces:interfaces/ietf-interfaces:interface/eth0/"
+ + "datastore=CONFIGURATION/scope=BASE",streamNameElement.getTextContent());
- uri = "/streams/stream/data-change-event-subscription/ietf-interfaces:interfaces/ietf-interfaces:interface/eth0/datastore=CONFIGURATION/scope=BASE";
+ uri = "/streams/stream/data-change-event-subscription/ietf-interfaces:interfaces/ietf-interfaces:interface/"
+ + "eth0/datastore=CONFIGURATION/scope=BASE";
final Response responseWithRedirectionUri = get(uri, MediaType.APPLICATION_XML, null);
final URI websocketServerUri = responseWithRedirectionUri.getLocation();
assertNotNull(websocketServerUri);
- assertTrue(websocketServerUri.toString().matches(".*ws://localhost:[\\d]+/data-change-event-subscription/ietf-interfaces:interfaces/ietf-interfaces:interface/eth0.*"));
+ assertTrue(websocketServerUri.toString().matches(".*ws://localhost:[\\d]+/data-change-event-subscription/"
+ + "ietf-interfaces:interfaces/ietf-interfaces:interface/eth0.*"));
}
private Response post(final String uri, final String mediaType, final String data) {
private static String getRpcInput() {
final StringBuilder sb = new StringBuilder();
sb.append("<input xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote\">");
- sb.append("<path xmlns:int=\"urn:ietf:params:xml:ns:yang:ietf-interfaces\">/int:interfaces/int:interface[int:name='eth0']</path>");
+ sb.append("<path xmlns:int=\"urn:ietf:params:xml:ns:yang:ietf-interfaces\">/"
+ + "int:interfaces/int:interface[int:name='eth0']</path>");
sb.append("</input>");
return sb.toString();
}
/**
* Test write {@link MapNode} with children and write also all its children.
- *
* FIXME
* Although ordered writer is used leaves are not written in expected order.
*
/**
* Test write with {@link MapEntryNode} ordered and write also all its children.
- *
* FIXME
* Although ordered writer is used leaves are not written in expected order.
*
public class NotificationListenerTest {
private static final QNameModule MODULE;
+
static {
try {
MODULE = QNameModule.create(URI.create("notifi:mod"),
return list;
}
- private static ContainerNode mockCont(final QName contQName, final DataContainerChild<? extends PathArgument, ?> child) {
+ private static ContainerNode mockCont(final QName contQName,
+ final DataContainerChild<? extends PathArgument, ?> child) {
final ContainerNode cont = mock(ContainerNode.class);
when(cont.getIdentifier()).thenReturn(NodeIdentifier.create(contQName));
when(cont.getNodeType()).thenReturn(contQName);
import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
/**
- * Unit tests for {@link RestConnectorProvider}
+ * Unit tests for {@link RestConnectorProvider}.
*/
public class RestConnectorProviderTest {
// service under test
/**
* Test for successful registration with {@link RestConnectorProvider#onSessionInitiated(Broker.ProviderSession)}
* when all conditions are satisfied.
+ *
* <p>
* Condition 1: <code>Broker.ProviderSession</code> contains <code>SchemaService</code>
* Condition 2: <code>Broker.ProviderSession</code> contains <code>DOMMountPointService</code>
/**
* Test for successful registration with {@link RestConnectorProvider#onSessionInitiated(Broker.ProviderSession)}
* without <code>DOMMountPointService</code>.
+ *
* <p>
* Condition 1: <code>Broker.ProviderSession</code> contains <code>SchemaService</code>
* Condition 2: <code>Broker.ProviderSession</code> does not contain <code>DOMMountPointService</code>
public class RestconfImplTest {
@Test
- public void RestImplTest() throws Exception {
+ public void restImplTest() throws Exception {
final SchemaContext schemaContext =
YangParserTestUtils.parseYangSources(TestRestconfUtils.loadFiles("/restconf/impl"));
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
/**
- * Unit tests for {@code RestconfSchemaService}
+ * Unit tests for {@code RestconfSchemaService}.
*/
public class RestconfSchemaServiceTest {
private static final String MOUNT_POINT = "mount-point-1:cont" + "/" + RestconfConstants.MOUNT + "/";
when(this.mockContextHandler.get()).thenReturn(this.schemaContextWithMountPoints);
// make test
- final SchemaExportContext exportContext = this.schemaService.getSchema(MOUNT_POINT + TEST_MODULE_BEHIND_MOUNT_POINT);
+ final SchemaExportContext exportContext =
+ this.schemaService.getSchema(MOUNT_POINT + TEST_MODULE_BEHIND_MOUNT_POINT);
// verify
assertNotNull("Export context should not be null", exportContext);
/**
* Try to get schema with wrong (not valid) identifier catching <code>RestconfDocumentedException</code>. Error
* type, error tag and error status code are compared to expected values.
+ *
* <p>
* Not valid identifier contains only revision without module name.
*/
* Try to get schema with wrong (not valid) identifier behind mount point catching
* <code>RestconfDocumentedException</code>. Error type, error tag and error status code are compared to expected
* values.
+ *
* <p>
* Not valid identifier contains only revision without module name.
*/
}
}
- /***
+ /**
* Try to get schema behind mount point with identifier when does not contain revision catching
* <code>RestconfDocumentedException</code>. Error type, error tag and error status code are compared to expected
* values.
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
/**
- * Tests for handling {@link SchemaContext}
+ * Tests for handling {@link SchemaContext}.
*/
public class SchemaContextHandlerTest {
}
/**
- * Testing init of {@link SchemaContextHandler}
+ * Testing init of {@link SchemaContextHandler}.
*/
@Test
public void schemaContextHandlerImplInitTest() {
/**
* Test getting actual {@link SchemaContext}.
+ *
* <p>
* Get <code>SchemaContext</code> from <code>SchemaContextHandler</code> and compare it to actual
* <code>SchemaContext</code>.
/**
* Test updating of {@link SchemaContext}.
+ *
* <p>
* Create new <code>SchemaContext</code>, set it to <code>SchemaContextHandler</code> and check if
* <code>SchemaContextHandler</code> reference to new <code>SchemaContext</code> instead of old one.
import org.opendaylight.netconf.sal.rest.api.RestconfConstants;
import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
import org.opendaylight.restconf.RestConnectorProvider;
import org.opendaylight.restconf.handlers.DOMMountPointServiceHandler;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
abstract class AbstractBodyReaderTest {
- protected final static ControllerContext controllerContext = ControllerContext.getInstance();
+ protected static final ControllerContext CONTROLLER_CONTEXT = ControllerContext.getInstance();
+ protected static final DOMMountPointServiceHandler MOUNT_POINT_SERVICE_HANDLER =
+ mock(DOMMountPointServiceHandler.class);
+
protected final MediaType mediaType;
- protected final static DOMMountPointServiceHandler mountPointServiceHandler = mock(
- DOMMountPointServiceHandler.class);
AbstractBodyReaderTest() throws NoSuchFieldException, IllegalAccessException {
mediaType = getMediaType();
- final Field mountPointServiceHandlerField = RestConnectorProvider.class.
- getDeclaredField("mountPointServiceHandler");
+ final Field mountPointServiceHandlerField =
+ RestConnectorProvider.class.getDeclaredField("mountPointServiceHandler");
mountPointServiceHandlerField.setAccessible(true);
- mountPointServiceHandlerField.set(RestConnectorProvider.class, mountPointServiceHandler);
+ mountPointServiceHandlerField.set(RestConnectorProvider.class, MOUNT_POINT_SERVICE_HANDLER);
}
protected abstract MediaType getMediaType();
assertNotNull(nnContext.getInstanceIdentifierContext().getSchemaNode());
}
- protected static void checkPATCHContext(final PATCHContext patchContext) {
+ protected static void checkPatchContext(final PatchContext patchContext) {
assertNotNull(patchContext.getData());
assertNotNull(patchContext.getInstanceIdentifierContext().getInstanceIdentifier());
assertNotNull(patchContext.getInstanceIdentifierContext().getSchemaContext());
assertNotNull(patchContext.getInstanceIdentifierContext().getSchemaNode());
}
- protected static void checkPATCHContextMountPoint(final PATCHContext patchContext) {
- checkPATCHContext(patchContext);
+ protected static void checkPatchContextMountPoint(final PatchContext patchContext) {
+ checkPatchContext(patchContext);
assertNotNull(patchContext.getInstanceIdentifierContext().getMountPoint());
assertNotNull(patchContext.getInstanceIdentifierContext().getMountPoint().getSchemaContext());
}
final Collection<File> testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang");
testFiles.addAll(TestRestconfUtils.loadFiles("/modules"));
schemaContext = YangParserTestUtils.parseYangSources(testFiles);
- controllerContext.setSchemas(schemaContext);
- when(mountPointServiceHandler.get()).thenReturn(mock(DOMMountPointService.class));
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
+ when(MOUNT_POINT_SERVICE_HANDLER.get()).thenReturn(mock(DOMMountPointService.class));
}
@Test
final QName augmentChoice1QName = QName.create(augmentModule.getQNameModule(), "augment-choice1");
final QName augmentChoice2QName = QName.create(augmentChoice1QName, "augment-choice2");
final QName containerQName = QName.create(augmentChoice1QName, "case-choice-case-container1");
- final YangInstanceIdentifier.AugmentationIdentifier augChoice1II = new YangInstanceIdentifier.AugmentationIdentifier(
- Sets.newHashSet(augmentChoice1QName));
- final YangInstanceIdentifier.AugmentationIdentifier augChoice2II = new YangInstanceIdentifier.AugmentationIdentifier(
- Sets.newHashSet(augmentChoice2QName));
+ final YangInstanceIdentifier.AugmentationIdentifier augChoice1II =
+ new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(augmentChoice1QName));
+ final YangInstanceIdentifier.AugmentationIdentifier augChoice2II =
+ new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(augmentChoice2QName));
final YangInstanceIdentifier dataII = YangInstanceIdentifier.of(dataSchemaNode.getQName()).node(augChoice1II)
.node(augmentChoice1QName).node(augChoice2II).node(augmentChoice2QName).node(containerQName);
final String uri = "instance-identifier-module:cont";
import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.controller.sal.rest.impl.test.providers.TestJsonBodyReader;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-public class JsonPATCHBodyReaderMountPointTest extends AbstractBodyReaderTest {
+public class JsonPatchBodyReaderMountPointTest extends AbstractBodyReaderTest {
- private final JsonToPATCHBodyReader jsonPATCHBodyReader;
- private static SchemaContext schemaContext;
private static final String MOUNT_POINT = "instance-identifier-module:cont/yang-ext:mount/";
+ private static SchemaContext schemaContext;
+ private final JsonToPatchBodyReader jsonToPatchBodyReader;
- public JsonPATCHBodyReaderMountPointTest() throws Exception {
+ public JsonPatchBodyReaderMountPointTest() throws Exception {
super();
- jsonPATCHBodyReader = new JsonToPATCHBodyReader();
+ jsonToPatchBodyReader = new JsonToPatchBodyReader();
}
@Override
final DOMMountPointService mountPointService = mock(DOMMountPointService.class);
final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
- when(mountPointServiceHandler.get()).thenReturn(mountPointService);
+ when(MOUNT_POINT_SERVICE_HANDLER.get()).thenReturn(mountPointService);
when(mountPointService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountPoint));
when(mountPoint.getSchemaContext()).thenReturn(schemaContext);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
- public void modulePATCHDataTest() throws Exception {
+ public void modulePatchDataTest() throws Exception {
final String uri = MOUNT_POINT + "instance-identifier-patch-module:patch-cont/my-list1=leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHdata.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContextMountPoint(returnValue);
+ checkPatchContextMountPoint(returnValue);
}
/**
- * Test of successful PATCH consisting of create and delete PATCH operations.
+ * Test of successful Patch consisting of create and delete Patch operations.
*/
@Test
- public void modulePATCHCreateAndDeleteTest() throws Exception {
+ public void modulePatchCreateAndDeleteTest() throws Exception {
final String uri = MOUNT_POINT + "instance-identifier-patch-module:patch-cont/my-list1=leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHdataCreateAndDelete.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContextMountPoint(returnValue);
+ checkPatchContextMountPoint(returnValue);
}
/**
- * Test trying to use PATCH create operation which requires value without value. Test should fail with
+ * Test trying to use Patch create operation which requires value without value. Test should fail with
* {@link RestconfDocumentedException} with error code 400.
*/
@Test
- public void modulePATCHValueMissingNegativeTest() throws Exception {
+ public void modulePatchValueMissingNegativeTest() throws Exception {
final String uri = MOUNT_POINT + "instance-identifier-patch-module:patch-cont/my-list1=leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHdataValueMissing.json");
try {
- jsonPATCHBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
+ jsonToPatchBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
fail("Test should return error 400 due to missing value node when attempt to invoke create operation");
} catch (final RestconfDocumentedException e) {
assertEquals("Error code 400 expected", 400, e.getErrors().get(0).getErrorTag().getStatusCode());
}
/**
- * Test trying to use value with PATCH delete operation which does not support value. Test should fail with
+ * Test trying to use value with Patch delete operation which does not support value. Test should fail with
* {@link RestconfDocumentedException} with error code 400.
*/
@Test
- public void modulePATCHValueNotSupportedNegativeTest() throws Exception {
+ public void modulePatchValueNotSupportedNegativeTest() throws Exception {
final String uri = MOUNT_POINT + "instance-identifier-patch-module:patch-cont/my-list1=leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHdataValueNotSupported.json");
try {
- jsonPATCHBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
+ jsonToPatchBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
fail("Test should return error 400 due to present value node when attempt to invoke delete operation");
} catch (final RestconfDocumentedException e) {
assertEquals("Error code 400 expected", 400, e.getErrors().get(0).getErrorTag().getStatusCode());
}
/**
- * Test using PATCH when target is completely specified in request URI and thus target leaf contains only '/' sign.
+ * Test using Patch when target is completely specified in request URI and thus target leaf contains only '/' sign.
*/
@Test
- public void modulePATCHCompleteTargetInURITest() throws Exception {
+ public void modulePatchCompleteTargetInURITest() throws Exception {
final String uri = MOUNT_POINT + "instance-identifier-patch-module:patch-cont";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHdataCompleteTargetInURI.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContextMountPoint(returnValue);
+ checkPatchContextMountPoint(returnValue);
}
/**
- * Test of Yang PATCH merge operation on list. Test consists of two edit operations - replace and merge.
+ * Test of Yang Patch merge operation on list. Test consists of two edit operations - replace and merge.
*/
@Test
- public void modulePATCHMergeOperationOnListTest() throws Exception {
+ public void modulePatchMergeOperationOnListTest() throws Exception {
final String uri = MOUNT_POINT + "instance-identifier-patch-module:patch-cont/my-list1=leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHMergeOperationOnList.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContextMountPoint(returnValue);
+ checkPatchContextMountPoint(returnValue);
}
/**
- * Test of Yang PATCH merge operation on container. Test consists of two edit operations - create and merge.
+ * Test of Yang Patch merge operation on container. Test consists of two edit operations - create and merge.
*/
@Test
- public void modulePATCHMergeOperationOnContainerTest() throws Exception {
+ public void modulePatchMergeOperationOnContainerTest() throws Exception {
final String uri = MOUNT_POINT + "instance-identifier-patch-module:patch-cont";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHMergeOperationOnContainer.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContextMountPoint(returnValue);
+ checkPatchContextMountPoint(returnValue);
}
/**
- * Test reading simple leaf value
+ * Test reading simple leaf value.
*/
@Test
- public void modulePATCHSimpleLeafValueTest() throws Exception {
+ public void modulePatchSimpleLeafValueTest() throws Exception {
final String uri = MOUNT_POINT + "instance-identifier-patch-module:patch-cont/my-list1=leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHSimpleLeafValue.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
}
import org.junit.Test;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.controller.sal.rest.impl.test.providers.TestJsonBodyReader;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-public class JsonPATCHBodyReaderTest extends AbstractBodyReaderTest {
+public class JsonPatchBodyReaderTest extends AbstractBodyReaderTest {
- private final JsonToPATCHBodyReader jsonPATCHBodyReader;
+ private final JsonToPatchBodyReader jsonToPatchBodyReader;
private static SchemaContext schemaContext;
- public JsonPATCHBodyReaderTest() throws Exception {
+ public JsonPatchBodyReaderTest() throws Exception {
super();
- jsonPATCHBodyReader = new JsonToPATCHBodyReader();
+ jsonToPatchBodyReader = new JsonToPatchBodyReader();
}
@Override
@BeforeClass
public static void initialization() {
schemaContext = schemaContextLoader("/instanceidentifier/yang", schemaContext);
- when(mountPointServiceHandler.get()).thenReturn(mock(DOMMountPointService.class));
- controllerContext.setSchemas(schemaContext);
+ when(MOUNT_POINT_SERVICE_HANDLER.get()).thenReturn(mock(DOMMountPointService.class));
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
- public void modulePATCHDataTest() throws Exception {
+ public void modulePatchDataTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont/my-list1=leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHdata.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
/**
- * Test of successful PATCH consisting of create and delete PATCH operations.
+ * Test of successful Patch consisting of create and delete Patch operations.
*/
@Test
- public void modulePATCHCreateAndDeleteTest() throws Exception {
+ public void modulePatchCreateAndDeleteTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont/my-list1=leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHdataCreateAndDelete.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
/**
- * Test trying to use PATCH create operation which requires value without value. Test should fail with
+ * Test trying to use Patch create operation which requires value without value. Test should fail with
* {@link RestconfDocumentedException} with error code 400.
*/
@Test
- public void modulePATCHValueMissingNegativeTest() throws Exception {
+ public void modulePatchValueMissingNegativeTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont/my-list1=leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHdataValueMissing.json");
try {
- jsonPATCHBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
+ jsonToPatchBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
fail("Test should return error 400 due to missing value node when attempt to invoke create operation");
} catch (final RestconfDocumentedException e) {
assertEquals("Error code 400 expected", 400, e.getErrors().get(0).getErrorTag().getStatusCode());
}
/**
- * Test trying to use value with PATCH delete operation which does not support value. Test should fail with
+ * Test trying to use value with Patch delete operation which does not support value. Test should fail with
* {@link RestconfDocumentedException} with error code 400.
*/
@Test
- public void modulePATCHValueNotSupportedNegativeTest() throws Exception {
+ public void modulePatchValueNotSupportedNegativeTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont/my-list1=leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHdataValueNotSupported.json");
try {
- jsonPATCHBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
+ jsonToPatchBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
fail("Test should return error 400 due to present value node when attempt to invoke delete operation");
} catch (final RestconfDocumentedException e) {
assertEquals("Error code 400 expected", 400, e.getErrors().get(0).getErrorTag().getStatusCode());
}
/**
- * Test using PATCH when target is completely specified in request URI and thus target leaf contains only '/' sign.
+ * Test using Patch when target is completely specified in request URI and thus target leaf contains only '/' sign.
*/
@Test
- public void modulePATCHCompleteTargetInURITest() throws Exception {
+ public void modulePatchCompleteTargetInURITest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHdataCompleteTargetInURI.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
/**
- * Test of Yang PATCH merge operation on list. Test consists of two edit operations - replace and merge.
+ * Test of Yang Patch merge operation on list. Test consists of two edit operations - replace and merge.
*/
@Test
- public void modulePATCHMergeOperationOnListTest() throws Exception {
+ public void modulePatchMergeOperationOnListTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont/my-list1=leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHMergeOperationOnList.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
/**
- * Test of Yang PATCH merge operation on container. Test consists of two edit operations - create and merge.
+ * Test of Yang Patch merge operation on container. Test consists of two edit operations - create and merge.
*/
@Test
- public void modulePATCHMergeOperationOnContainerTest() throws Exception {
+ public void modulePatchMergeOperationOnContainerTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHMergeOperationOnContainer.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
/**
- * Test reading simple leaf value
+ * Test reading simple leaf value.
*/
@Test
- public void modulePATCHSimpleLeafValueTest() throws Exception {
+ public void modulePatchSimpleLeafValueTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont/my-list1=leaf1";
- mockBodyReader(uri, jsonPATCHBodyReader, false);
+ mockBodyReader(uri, jsonToPatchBodyReader, false);
final InputStream inputStream = TestJsonBodyReader.class
.getResourceAsStream("/instanceidentifier/json/jsonPATCHSimpleLeafValue.json");
- final PATCHContext returnValue = jsonPATCHBodyReader
+ final PatchContext returnValue = jsonToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
}
/**
* Test write {@link MapNode} with children and write also all its children.
* Depth parameter has higher value than maximal children depth.
- *
- *
* FIXME
* Although ordered writer is used leaves are not written in expected order.
*
/**
* Test write with {@link MapEntryNode} ordered and write also all its children.
* Depth parameter has higher value than maximal children depth.
- *
* FIXME
* Although ordered writer is used leaves are not written in expected order.
*
final Collection<File> testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang");
testFiles.addAll(TestRestconfUtils.loadFiles("/modules"));
schemaContext = YangParserTestUtils.parseYangSources(testFiles);
- controllerContext.setSchemas(schemaContext);
- when(mountPointServiceHandler.get()).thenReturn(mock(DOMMountPointService.class));
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
+ when(MOUNT_POINT_SERVICE_HANDLER.get()).thenReturn(mock(DOMMountPointService.class));
}
@Test
final QName augmentChoice1QName = QName.create(augmentModule.getQNameModule(), "augment-choice1");
final QName augmentChoice2QName = QName.create(augmentChoice1QName, "augment-choice2");
final QName containerQName = QName.create(augmentChoice1QName, "case-choice-case-container1");
- final YangInstanceIdentifier.AugmentationIdentifier augChoice1II = new YangInstanceIdentifier.AugmentationIdentifier(
- Sets.newHashSet(augmentChoice1QName));
- final YangInstanceIdentifier.AugmentationIdentifier augChoice2II = new YangInstanceIdentifier.AugmentationIdentifier(
- Sets.newHashSet(augmentChoice2QName));
+ final YangInstanceIdentifier.AugmentationIdentifier augChoice1II =
+ new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(augmentChoice1QName));
+ final YangInstanceIdentifier.AugmentationIdentifier augChoice2II =
+ new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(augmentChoice2QName));
final YangInstanceIdentifier dataII = YangInstanceIdentifier.of(dataSchemaNode.getQName()).node(augChoice1II)
.node(augmentChoice1QName).node(augChoice2II).node(augmentChoice2QName).node(containerQName);
final String uri = "instance-identifier-module:cont";
import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.controller.sal.rest.impl.test.providers.TestXmlBodyReader;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-public class XmlPATCHBodyReaderMountPointTest extends AbstractBodyReaderTest {
+public class XmlPatchBodyReaderMountPointTest extends AbstractBodyReaderTest {
- private final XmlToPATCHBodyReader xmlPATCHBodyReader;
+ private final XmlToPatchBodyReader xmlToPatchBodyReader;
private static SchemaContext schemaContext;
private static final String MOUNT_POINT = "instance-identifier-module:cont/yang-ext:mount/";
- public XmlPATCHBodyReaderMountPointTest() throws Exception {
+ public XmlPatchBodyReaderMountPointTest() throws Exception {
super();
- xmlPATCHBodyReader = new XmlToPATCHBodyReader();
+ xmlToPatchBodyReader = new XmlToPatchBodyReader();
}
@Override
final DOMMountPointService mountPointService = mock(DOMMountPointService.class);
final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
- when(mountPointServiceHandler.get()).thenReturn(mountPointService);
+ when(MOUNT_POINT_SERVICE_HANDLER.get()).thenReturn(mountPointService);
when(mountPointService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountPoint));
when(mountPoint.getSchemaContext()).thenReturn(schemaContext);
- controllerContext.setSchemas(schemaContext);
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
public void moduleDataTest() throws Exception {
final String uri = MOUNT_POINT + "instance-identifier-patch-module:patch-cont/my-list1=leaf1";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdata.xml");
- final PATCHContext returnValue = xmlPATCHBodyReader
+ final PatchContext returnValue = xmlToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContextMountPoint(returnValue);
+ checkPatchContextMountPoint(returnValue);
}
/**
- * Test trying to use PATCH create operation which requires value without value. Error code 400 should be returned.
+ * Test trying to use Patch create operation which requires value without value. Error code 400 should be returned.
*/
@Test
public void moduleDataValueMissingNegativeTest() throws Exception {
final String uri = MOUNT_POINT + "instance-identifier-patch-module:patch-cont/my-list1=leaf1";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataValueMissing.xml");
try {
- xmlPATCHBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
+ xmlToPatchBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
fail("Test should return error 400 due to missing value node when attempt to invoke create operation");
} catch (final RestconfDocumentedException e) {
assertEquals("Error code 400 expected", 400, e.getErrors().get(0).getErrorTag().getStatusCode());
}
/**
- * Test trying to use value with PATCH delete operation which does not support value. Error code 400 should be
+ * Test trying to use value with Patch delete operation which does not support value. Error code 400 should be
* returned.
*/
@Test
public void moduleDataNotValueNotSupportedNegativeTest() throws Exception {
final String uri = MOUNT_POINT + "instance-identifier-patch-module:patch-cont/my-list1=leaf1";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataValueNotSupported.xml");
try {
- xmlPATCHBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
+ xmlToPatchBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
fail("Test should return error 400 due to present value node when attempt to invoke delete operation");
} catch (final RestconfDocumentedException e) {
assertEquals("Error code 400 expected", 400, e.getErrors().get(0).getErrorTag().getStatusCode());
/**
- * Test of Yang PATCH with absolute target path.
+ * Test of Yang Patch with absolute target path.
*/
@Test
public void moduleDataAbsoluteTargetPathTest() throws Exception {
final String uri = MOUNT_POINT;
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataAbsoluteTargetPath.xml");
- final PATCHContext returnValue = xmlPATCHBodyReader
+ final PatchContext returnValue = xmlToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContextMountPoint(returnValue);
+ checkPatchContextMountPoint(returnValue);
}
/**
- * Test using PATCH when target is completely specified in request URI and thus target leaf contains only '/' sign.
+ * Test using Patch when target is completely specified in request URI and thus target leaf contains only '/' sign.
*/
@Test
- public void modulePATCHCompleteTargetInURITest() throws Exception {
+ public void modulePatchCompleteTargetInURITest() throws Exception {
final String uri = MOUNT_POINT + "instance-identifier-patch-module:patch-cont";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataCompleteTargetInURI.xml");
- final PATCHContext returnValue = xmlPATCHBodyReader
+ final PatchContext returnValue = xmlToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContextMountPoint(returnValue);
+ checkPatchContextMountPoint(returnValue);
}
/**
- * Test of Yang PATCH merge operation on list. Test consists of two edit operations - replace and merge.
+ * Test of Yang Patch merge operation on list. Test consists of two edit operations - replace and merge.
*/
@Test
public void moduleDataMergeOperationOnListTest() throws Exception {
final String uri = MOUNT_POINT + "instance-identifier-patch-module:patch-cont/my-list1=leaf1";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataMergeOperationOnList.xml");
- final PATCHContext returnValue = xmlPATCHBodyReader
+ final PatchContext returnValue = xmlToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContextMountPoint(returnValue);
+ checkPatchContextMountPoint(returnValue);
}
/**
- * Test of Yang PATCH merge operation on container. Test consists of two edit operations - create and merge.
+ * Test of Yang Patch merge operation on container. Test consists of two edit operations - create and merge.
*/
@Test
public void moduleDataMergeOperationOnContainerTest() throws Exception {
final String uri = MOUNT_POINT + "instance-identifier-patch-module:patch-cont";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataMergeOperationOnContainer.xml");
- final PATCHContext returnValue = xmlPATCHBodyReader
+ final PatchContext returnValue = xmlToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContextMountPoint(returnValue);
+ checkPatchContextMountPoint(returnValue);
}
}
import org.junit.Test;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.controller.sal.rest.impl.test.providers.TestXmlBodyReader;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-public class XmlPATCHBodyReaderTest extends AbstractBodyReaderTest {
+public class XmlPatchBodyReaderTest extends AbstractBodyReaderTest {
- private final XmlToPATCHBodyReader xmlPATCHBodyReader;
+ private final XmlToPatchBodyReader xmlToPatchBodyReader;
private static SchemaContext schemaContext;
- public XmlPATCHBodyReaderTest() throws Exception {
+ public XmlPatchBodyReaderTest() throws Exception {
super();
- xmlPATCHBodyReader = new XmlToPATCHBodyReader();
+ xmlToPatchBodyReader = new XmlToPatchBodyReader();
}
@Override
@BeforeClass
public static void initialization() {
schemaContext = schemaContextLoader("/instanceidentifier/yang", schemaContext);
- when(mountPointServiceHandler.get()).thenReturn(mock(DOMMountPointService.class));
- controllerContext.setSchemas(schemaContext);
+ when(MOUNT_POINT_SERVICE_HANDLER.get()).thenReturn(mock(DOMMountPointService.class));
+ CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
public void moduleDataTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont/my-list1=leaf1";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdata.xml");
- final PATCHContext returnValue = xmlPATCHBodyReader
+ final PatchContext returnValue = xmlToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
/**
- * Test trying to use PATCH create operation which requires value without value. Error code 400 should be returned.
+ * Test trying to use Patch create operation which requires value without value. Error code 400 should be returned.
*/
@Test
public void moduleDataValueMissingNegativeTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont/my-list1=leaf1";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataValueMissing.xml");
try {
- xmlPATCHBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
+ xmlToPatchBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
fail("Test should return error 400 due to missing value node when attempt to invoke create operation");
} catch (final RestconfDocumentedException e) {
assertEquals("Error code 400 expected", 400, e.getErrors().get(0).getErrorTag().getStatusCode());
}
/**
- * Test trying to use value with PATCH delete operation which does not support value. Error code 400 should be
+ * Test trying to use value with Patch delete operation which does not support value. Error code 400 should be
* returned.
*/
@Test
public void moduleDataNotValueNotSupportedNegativeTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont/my-list1=leaf1";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataValueNotSupported.xml");
try {
- xmlPATCHBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
+ xmlToPatchBodyReader.readFrom(null, null, null, mediaType, null, inputStream);
fail("Test should return error 400 due to present value node when attempt to invoke delete operation");
} catch (final RestconfDocumentedException e) {
assertEquals("Error code 400 expected", 400, e.getErrors().get(0).getErrorTag().getStatusCode());
/**
- * Test of Yang PATCH with absolute target path.
+ * Test of Yang Patch with absolute target path.
*/
@Test
public void moduleDataAbsoluteTargetPathTest() throws Exception {
final String uri = "";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataAbsoluteTargetPath.xml");
- final PATCHContext returnValue = xmlPATCHBodyReader
+ final PatchContext returnValue = xmlToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
/**
- * Test using PATCH when target is completely specified in request URI and thus target leaf contains only '/' sign.
+ * Test using Patch when target is completely specified in request URI and thus target leaf contains only '/' sign.
*/
@Test
- public void modulePATCHCompleteTargetInURITest() throws Exception {
+ public void modulePatchCompleteTargetInURITest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataCompleteTargetInURI.xml");
- final PATCHContext returnValue = xmlPATCHBodyReader
+ final PatchContext returnValue = xmlToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
/**
- * Test of Yang PATCH merge operation on list. Test consists of two edit operations - replace and merge.
+ * Test of Yang Patch merge operation on list. Test consists of two edit operations - replace and merge.
*/
@Test
public void moduleDataMergeOperationOnListTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont/my-list1=leaf1";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataMergeOperationOnList.xml");
- final PATCHContext returnValue = xmlPATCHBodyReader
+ final PatchContext returnValue = xmlToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
/**
- * Test of Yang PATCH merge operation on container. Test consists of two edit operations - create and merge.
+ * Test of Yang Patch merge operation on container. Test consists of two edit operations - create and merge.
*/
@Test
public void moduleDataMergeOperationOnContainerTest() throws Exception {
final String uri = "instance-identifier-patch-module:patch-cont";
- mockBodyReader(uri, xmlPATCHBodyReader, false);
+ mockBodyReader(uri, xmlToPatchBodyReader, false);
final InputStream inputStream = TestXmlBodyReader.class
.getResourceAsStream("/instanceidentifier/xml/xmlPATCHdataMergeOperationOnContainer.xml");
- final PATCHContext returnValue = xmlPATCHBodyReader
+ final PatchContext returnValue = xmlToPatchBodyReader
.readFrom(null, null, null, mediaType, null, inputStream);
- checkPATCHContext(returnValue);
+ checkPatchContext(returnValue);
}
}
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
/**
- * Unit tests for {@link IdentifierCodec} mostly according to examples from draft-ietf-netconf-restconf-13
+ * Unit tests for {@link IdentifierCodec} mostly according to examples from draft-ietf-netconf-restconf-13.
*/
public class IdentifierCodecTest {
/**
* Positive test of deserialization URI <code>String</code> to <code>YangInstanceIdentifier</code> and
- * serialization of <code>YangInstanceIdentifier</code> to <code>String/code> when original <code>String</code>
+ * serialization of <code>YangInstanceIdentifier</code> to <code>String</code> when original <code>String</code>
* URI contains list identifier and leaf identifier.
*/
@Test
/**
* Positive test of deserialization URI <code>String</code> to <code>YangInstanceIdentifier</code> and
- * serialization of <code>YangInstanceIdentifier</code> to <code>String/code> when original <code>String</code>
+ * serialization of <code>YangInstanceIdentifier</code> to <code>String</code> when original <code>String</code>
* URI contains leaf list identifier.
*/
@Test
* expected to be returned.
*/
@Test
- public void codecDeserializeNullTest () {
+ public void codecDeserializeNullTest() {
final YangInstanceIdentifier dataYangII = IdentifierCodec.deserialize(null, this.schemaContext);
assertEquals("Failed codec deserialization test", YangInstanceIdentifier.EMPTY, dataYangII);
}
* expected to be returned.
*/
@Test
- public void codecSerializeEmptyTest () {
+ public void codecSerializeEmptyTest() {
final String serialized = IdentifierCodec.serialize(YangInstanceIdentifier.EMPTY, this.schemaContext);
assertTrue("Failed codec serialization test", serialized.isEmpty());
}
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
/**
- * Unit tests for {@link YangInstanceIdentifierDeserializer}
+ * Unit tests for {@link YangInstanceIdentifierDeserializer}.
*/
public class YangInstanceIdentifierDeserializerTest {
/**
* Test of deserialization <code>String</code> URI with container to
- * <code>Iterable<YangInstanceIdentifier.PathArgument></code>.
+ * {@code Iterable<YangInstanceIdentifier.PathArgument>}.
*/
@Test
public void deserializeContainerTest() {
/**
* Test of deserialization <code>String</code> URI with container containing leaf to
- * <code>Iterable<YangInstanceIdentifier.PathArgument></code>.
+ * {@code Iterable<YangInstanceIdentifier.PathArgument>}.
*/
@Test
public void deserializeContainerWithLeafTest() {
/**
* Test of deserialization <code>String</code> URI with container containing list with leaf list to
- * <code>Iterable<YangInstanceIdentifier.PathArgument></code>.
+ * {@code Iterable<YangInstanceIdentifier.PathArgument>}.
*/
@Test
public void deserializeContainerWithListWithLeafListTest() {
/**
* Test of deserialization <code>String</code> URI containing list with no keys to
- * <code>Iterable<YangInstanceIdentifier.PathArgument></code>.
+ * {@code Iterable<YangInstanceIdentifier.PathArgument>}.
*/
@Test
public void deserializeListWithNoKeysTest() {
/**
* Test of deserialization <code>String</code> URI containing list with one key to
- * <code>Iterable<YangInstanceIdentifier.PathArgument></code>.
+ * {@code Iterable<YangInstanceIdentifier.PathArgument>}.
*/
@Test
public void deserializeListWithOneKeyTest() {
/**
* Test of deserialization <code>String</code> URI containing list with multiple keys to
- * <code>Iterable<YangInstanceIdentifier.PathArgument></code>.
+ * {@code Iterable<YangInstanceIdentifier.PathArgument>}.
*/
@Test
public void deserializeListWithMultipleKeysTest() {
/**
* Test of deserialization <code>String</code> URI containing leaf list to
- * <code>Iterable<YangInstanceIdentifier.PathArgument></code>.
+ * {@code Iterable<YangInstanceIdentifier.PathArgument>}.
*/
@Test
public void deserializeLeafListTest() {
@Test
public void prepareQnameNotValidListNameNegativeTest() {
try {
- YangInstanceIdentifierDeserializer.create(this.schemaContext, "deserializer-test:list-no-key/disabled=false");
+ YangInstanceIdentifierDeserializer
+ .create(this.schemaContext, "deserializer-test:list-no-key/disabled=false");
fail("Test should fail due to unknown child node in list");
} catch (final RestconfDocumentedException e) {
assertEquals("Not expected error type",
@Test
public void deserializeKeysEndsWithComaNegativeTest() {
this.thrown.expect(IllegalArgumentException.class);
- YangInstanceIdentifierDeserializer.create( this.schemaContext,
+ YangInstanceIdentifierDeserializer.create(this.schemaContext,
"deserializer-test:list-multiple-keys=value,100,false,");
}
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
/**
- * Unit tests for {@link YangInstanceIdentifierSerializer}
+ * Unit tests for {@link YangInstanceIdentifierSerializer}.
*/
public class YangInstanceIdentifierSerializerTest {
import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHEntity;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchEntity;
+import org.opendaylight.netconf.sal.restconf.impl.PatchStatusContext;
import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
import org.opendaylight.restconf.RestConnectorProvider;
import org.opendaylight.restconf.common.references.SchemaContextRef;
doReturn(this.readWrite).when(this.domTransactionChain).newReadWriteTransaction();
doReturn(this.write).when(this.domTransactionChain).newWriteOnlyTransaction();
doReturn(this.mountPointService).when(this.mountPointServiceHandler).get();
- doReturn(Optional.of(this.mountPoint)).when(this.mountPointService).getMountPoint(any(YangInstanceIdentifier.class));
+ doReturn(Optional.of(this.mountPoint)).when(this.mountPointService)
+ .getMountPoint(any(YangInstanceIdentifier.class));
doReturn(this.contextRef.get()).when(this.mountPoint).getSchemaContext();
doReturn(Optional.of(this.mountDataBroker)).when(this.mountPoint).getService(DOMDataBroker.class);
- doReturn(this.transactionChain).when(this.mountDataBroker).createTransactionChain(any(TransactionChainListener.class));
+ doReturn(this.transactionChain).when(this.mountDataBroker)
+ .createTransactionChain(any(TransactionChainListener.class));
doReturn(this.read).when(this.transactionChain).newReadOnlyTransaction();
doReturn(this.readWrite).when(this.transactionChain).newReadWriteTransaction();
}
doReturn(new MultivaluedHashMap<String, String>()).when(this.uriInfo).getQueryParameters();
doReturn(Futures.immediateCheckedFuture(Optional.of(this.buildBaseCont))).when(this.read)
.read(LogicalDatastoreType.CONFIGURATION, this.iidBase);
- doReturn(Futures.immediateCheckedFuture(Optional.absent())).when(this.read).read(LogicalDatastoreType.OPERATIONAL, this.iidBase);
+ doReturn(Futures.immediateCheckedFuture(Optional.absent()))
+ .when(this.read).read(LogicalDatastoreType.OPERATIONAL, this.iidBase);
final Response response = this.dataService.readData("example-jukebox:jukebox", this.uriInfo);
assertNotNull(response);
assertEquals(200, response.getStatus());
@Test(expected = RestconfDocumentedException.class)
public void testReadDataNoData() {
doReturn(new MultivaluedHashMap<String, String>()).when(this.uriInfo).getQueryParameters();
- doReturn(Futures.immediateCheckedFuture(Optional.absent())).when(this.read).read(LogicalDatastoreType.CONFIGURATION,
- this.iidBase);
- doReturn(Futures.immediateCheckedFuture(Optional.absent())).when(this.read).read(LogicalDatastoreType.OPERATIONAL,
- this.iidBase);
+ doReturn(Futures.immediateCheckedFuture(Optional.absent()))
+ .when(this.read).read(LogicalDatastoreType.CONFIGURATION, this.iidBase);
+ doReturn(Futures.immediateCheckedFuture(Optional.absent()))
+ .when(this.read).read(LogicalDatastoreType.OPERATIONAL, this.iidBase);
this.dataService.readData("example-jukebox:jukebox", this.uriInfo);
}
/**
- * Read data from config datastore according to content parameter
+ * Read data from config datastore according to content parameter.
*/
@Test
public void testReadDataConfigTest() {
}
/**
- * Read data from operational datastore according to content parameter
+ * Read data from operational datastore according to content parameter.
*/
@Test
public void testReadDataOperationalTest() {
@Test
public void testPutData() {
- final InstanceIdentifierContext<DataSchemaNode> iidContext = new InstanceIdentifierContext<>(this.iidBase, this.schemaNode, null, this.contextRef.get());
+ final InstanceIdentifierContext<DataSchemaNode> iidContext =
+ new InstanceIdentifierContext<>(this.iidBase, this.schemaNode, null, this.contextRef.get());
final NormalizedNodeContext payload = new NormalizedNodeContext(iidContext, this.buildBaseCont);
doReturn(Futures.immediateCheckedFuture(Optional.of(this.buildBaseCont))).when(this.read)
final DOMDataBroker dataBroker = Mockito.mock(DOMDataBroker.class);
final DOMMountPoint mountPoint = Mockito.mock(DOMMountPoint.class);
doReturn(Optional.of(dataBroker)).when(mountPoint).getService(DOMDataBroker.class);
- doReturn(this.transactionChainHandler.get()).when(dataBroker).createTransactionChain(RestConnectorProvider.transactionListener);
- final InstanceIdentifierContext<DataSchemaNode> iidContext = new InstanceIdentifierContext<>(this.iidBase, this.schemaNode, mountPoint, this.contextRef.get());
+ doReturn(this.transactionChainHandler.get()).when(dataBroker)
+ .createTransactionChain(RestConnectorProvider.TRANSACTION_CHAIN_LISTENER);
+ final InstanceIdentifierContext<DataSchemaNode> iidContext =
+ new InstanceIdentifierContext<>(this.iidBase, this.schemaNode, mountPoint, this.contextRef.get());
final NormalizedNodeContext payload = new NormalizedNodeContext(iidContext, this.buildBaseCont);
doReturn(Futures.immediateCheckedFuture(Optional.of(this.buildBaseCont))).when(this.read)
.withValue("name of band")
.build();
final LeafNode<Object> content2 = Builders.leafBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create(this.baseQName, "description")))
- .withValue("band description")
- .build();
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create(this.baseQName, "description")))
+ .withValue("band description")
+ .build();
final MapEntryNode mapEntryNode = Builders.mapEntryBuilder()
.withNodeIdentifier(nodeWithKey)
.withChild(content)
.build();
doReturn(new MultivaluedHashMap<String, String>()).when(this.uriInfo).getQueryParameters();
- final InstanceIdentifierContext<? extends SchemaNode> iidContext = new InstanceIdentifierContext<>(this.iidBase, null, null, this.contextRef.get());
+ final InstanceIdentifierContext<? extends SchemaNode> iidContext =
+ new InstanceIdentifierContext<>(this.iidBase, null, null, this.contextRef.get());
final NormalizedNodeContext payload = new NormalizedNodeContext(iidContext, buildList);
- doReturn(Futures.immediateCheckedFuture(Optional.absent())).when(this.read).read(LogicalDatastoreType.CONFIGURATION, this.iidBase);
+ doReturn(Futures.immediateCheckedFuture(Optional.absent()))
+ .when(this.read).read(LogicalDatastoreType.CONFIGURATION, this.iidBase);
final MapNode data = (MapNode) payload.getData();
- final YangInstanceIdentifier.NodeIdentifierWithPredicates identifier = data.getValue().iterator().next().getIdentifier();
- final YangInstanceIdentifier node = payload.getInstanceIdentifierContext().getInstanceIdentifier().node(identifier);
- doReturn(Futures.immediateCheckedFuture(false)).when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, node);
+ final YangInstanceIdentifier.NodeIdentifierWithPredicates identifier =
+ data.getValue().iterator().next().getIdentifier();
+ final YangInstanceIdentifier node =
+ payload.getInstanceIdentifierContext().getInstanceIdentifier().node(identifier);
+ doReturn(Futures.immediateCheckedFuture(false))
+ .when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, node);
doNothing().when(this.readWrite).put(LogicalDatastoreType.CONFIGURATION, node, payload.getData());
doReturn(Futures.immediateCheckedFuture(null)).when(this.readWrite).submit();
doReturn(UriBuilder.fromUri("http://localhost:8181/restconf/15/")).when(this.uriInfo).getBaseUriBuilder();
public void testDeleteData() {
doNothing().when(this.readWrite).delete(LogicalDatastoreType.CONFIGURATION, this.iidBase);
doReturn(Futures.immediateCheckedFuture(null)).when(this.readWrite).submit();
- doReturn(Futures.immediateCheckedFuture(true)).when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, this.iidBase);
+ doReturn(Futures.immediateCheckedFuture(true))
+ .when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, this.iidBase);
final Response response = this.dataService.deleteData("example-jukebox:jukebox");
assertNotNull(response);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
}
/**
- * Test of deleting data on mount point
+ * Test of deleting data on mount point.
*/
@Test
public void testDeleteDataMountPoint() {
doNothing().when(this.readWrite).delete(LogicalDatastoreType.CONFIGURATION, this.iidBase);
doReturn(Futures.immediateCheckedFuture(null)).when(this.readWrite).submit();
- doReturn(Futures.immediateCheckedFuture(true)).when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, this.iidBase);
- final Response response = this.dataService.deleteData("example-jukebox:jukebox/yang-ext:mount/example-jukebox:jukebox");
+ doReturn(Futures.immediateCheckedFuture(true))
+ .when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, this.iidBase);
+ final Response response =
+ this.dataService.deleteData("example-jukebox:jukebox/yang-ext:mount/example-jukebox:jukebox");
assertNotNull(response);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
}
@Test
public void testPatchData() throws Exception {
- final InstanceIdentifierContext<? extends SchemaNode> iidContext = new InstanceIdentifierContext<>(this.iidBase, this.schemaNode, null, this.contextRef.get());
- final List<PATCHEntity> entity = new ArrayList<>();
+ final InstanceIdentifierContext<? extends SchemaNode> iidContext =
+ new InstanceIdentifierContext<>(this.iidBase, this.schemaNode, null, this.contextRef.get());
+ final List<PatchEntity> entity = new ArrayList<>();
final YangInstanceIdentifier iidleaf = YangInstanceIdentifier.builder(this.iidBase)
.node(this.containerPlayerQname)
.node(this.leafQname)
.build();
- entity.add(new PATCHEntity("create data", "CREATE", this.iidBase, this.buildBaseCont));
- entity.add(new PATCHEntity("replace data", "REPLACE", this.iidBase, this.buildBaseCont));
- entity.add(new PATCHEntity("delete data", "DELETE", iidleaf));
- final PATCHContext patch = new PATCHContext(iidContext, entity, "test patch id");
+ entity.add(new PatchEntity("create data", "CREATE", this.iidBase, this.buildBaseCont));
+ entity.add(new PatchEntity("replace data", "REPLACE", this.iidBase, this.buildBaseCont));
+ entity.add(new PatchEntity("delete data", "DELETE", iidleaf));
+ final PatchContext patch = new PatchContext(iidContext, entity, "test patch id");
doReturn(Futures.immediateCheckedFuture(Optional.of(this.buildBaseCont))).when(this.read)
.read(LogicalDatastoreType.CONFIGURATION, this.iidBase);
doReturn(Futures.immediateCheckedFuture(null)).when(this.write).submit();
doNothing().when(this.readWrite).delete(LogicalDatastoreType.CONFIGURATION, iidleaf);
doReturn(Futures.immediateCheckedFuture(null)).when(this.readWrite).submit();
- doReturn(Futures.immediateCheckedFuture(false)).when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, this.iidBase);
- doReturn(Futures.immediateCheckedFuture(true)).when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, iidleaf);
- final PATCHStatusContext status = this.dataService.patchData(patch, this.uriInfo);
+ doReturn(Futures.immediateCheckedFuture(false))
+ .when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, this.iidBase);
+ doReturn(Futures.immediateCheckedFuture(true))
+ .when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, iidleaf);
+ final PatchStatusContext status = this.dataService.patchData(patch, this.uriInfo);
assertTrue(status.isOk());
assertEquals(3, status.getEditCollection().size());
assertEquals("replace data", status.getEditCollection().get(1).getEditId());
public void testPatchDataMountPoint() throws Exception {
final InstanceIdentifierContext<? extends SchemaNode> iidContext = new InstanceIdentifierContext<>(
this.iidBase, this.schemaNode, this.mountPoint, this.contextRef.get());
- final List<PATCHEntity> entity = new ArrayList<>();
+ final List<PatchEntity> entity = new ArrayList<>();
final YangInstanceIdentifier iidleaf = YangInstanceIdentifier.builder(this.iidBase)
.node(this.containerPlayerQname)
.node(this.leafQname)
.build();
- entity.add(new PATCHEntity("create data", "CREATE", this.iidBase, this.buildBaseCont));
- entity.add(new PATCHEntity("replace data", "REPLACE", this.iidBase, this.buildBaseCont));
- entity.add(new PATCHEntity("delete data", "DELETE", iidleaf));
- final PATCHContext patch = new PATCHContext(iidContext, entity, "test patch id");
+ entity.add(new PatchEntity("create data", "CREATE", this.iidBase, this.buildBaseCont));
+ entity.add(new PatchEntity("replace data", "REPLACE", this.iidBase, this.buildBaseCont));
+ entity.add(new PatchEntity("delete data", "DELETE", iidleaf));
+ final PatchContext patch = new PatchContext(iidContext, entity, "test patch id");
doReturn(Futures.immediateCheckedFuture(Optional.of(this.buildBaseCont))).when(this.read)
.read(LogicalDatastoreType.CONFIGURATION, this.iidBase);
doReturn(Futures.immediateCheckedFuture(null)).when(this.write).submit();
doNothing().when(this.readWrite).delete(LogicalDatastoreType.CONFIGURATION, iidleaf);
doReturn(Futures.immediateCheckedFuture(null)).when(this.readWrite).submit();
- doReturn(Futures.immediateCheckedFuture(false)).when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, this.iidBase);
- doReturn(Futures.immediateCheckedFuture(true)).when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, iidleaf);
+ doReturn(Futures.immediateCheckedFuture(false))
+ .when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, this.iidBase);
+ doReturn(Futures.immediateCheckedFuture(true))
+ .when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, iidleaf);
- final PATCHStatusContext status = this.dataService.patchData(patch, this.uriInfo);
+ final PatchStatusContext status = this.dataService.patchData(patch, this.uriInfo);
assertTrue(status.isOk());
assertEquals(3, status.getEditCollection().size());
assertNull(status.getGlobalErrors());
broker.setAccessible(true);
broker.set(RestConnectorProvider.class, mock(DOMDataBroker.class));
- final InstanceIdentifierContext<? extends SchemaNode> iidContext = new InstanceIdentifierContext<>(this.iidBase, this.schemaNode, null, this.contextRef.get());
- final List<PATCHEntity> entity = new ArrayList<>();
+ final InstanceIdentifierContext<? extends SchemaNode> iidContext =
+ new InstanceIdentifierContext<>(this.iidBase, this.schemaNode, null, this.contextRef.get());
+ final List<PatchEntity> entity = new ArrayList<>();
final YangInstanceIdentifier iidleaf = YangInstanceIdentifier.builder(this.iidBase)
.node(this.containerPlayerQname)
.node(this.leafQname)
.build();
- entity.add(new PATCHEntity("create data", "CREATE", this.iidBase, this.buildBaseCont));
- entity.add(new PATCHEntity("remove data", "REMOVE", iidleaf));
- entity.add(new PATCHEntity("delete data", "DELETE", iidleaf));
- final PATCHContext patch = new PATCHContext(iidContext, entity, "test patch id");
+ entity.add(new PatchEntity("create data", "CREATE", this.iidBase, this.buildBaseCont));
+ entity.add(new PatchEntity("remove data", "REMOVE", iidleaf));
+ entity.add(new PatchEntity("delete data", "DELETE", iidleaf));
+ final PatchContext patch = new PatchContext(iidContext, entity, "test patch id");
doReturn(Futures.immediateCheckedFuture(Optional.of(this.buildBaseCont))).when(this.read)
.read(LogicalDatastoreType.CONFIGURATION, this.iidBase);
doReturn(Futures.immediateCheckedFuture(null)).when(this.write).submit();
doNothing().when(this.readWrite).delete(LogicalDatastoreType.CONFIGURATION, iidleaf);
doReturn(Futures.immediateCheckedFuture(null)).when(this.readWrite).submit();
- doReturn(Futures.immediateCheckedFuture(false)).when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, this.iidBase);
- doReturn(Futures.immediateCheckedFuture(false)).when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, iidleaf);
+ doReturn(Futures.immediateCheckedFuture(false))
+ .when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, this.iidBase);
+ doReturn(Futures.immediateCheckedFuture(false))
+ .when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, iidleaf);
doReturn(true).when(this.readWrite).cancel();
- final PATCHStatusContext status = this.dataService.patchData(patch, this.uriInfo);
+ final PatchStatusContext status = this.dataService.patchData(patch, this.uriInfo);
handler.set(RestConnectorProvider.class, null);
handler.setAccessible(false);
public class RestconfStreamsSubscriptionServiceImplTest {
- private static final String uri = "/restconf/18/data/ietf-restconf-monitoring:restconf-state/streams/stream/"
+ private static final String URI = "/restconf/18/data/ietf-restconf-monitoring:restconf-state/streams/stream/"
+ "toaster:toaster/toasterStatus/datastore=OPERATIONAL/scope=ONE";
private static Field listenersByStreamName;
@Test
public void testSubscribeToStream() throws Exception {
- final UriBuilder uriBuilder = UriBuilder.fromUri(uri);
+ final UriBuilder uriBuilder = UriBuilder.fromUri(URI);
final ListenerAdapter createListener = Notificator.createListener(
IdentifierCodec.deserialize("toaster:toaster/toasterStatus", this.schemaHandler.get()),
"data-change-event-subscription/toaster:toaster/toasterStatus/datastore=OPERATIONAL/scope=ONE",
"data-change-event-subscription/toaster:toaster/toasterStatus/datastore=OPERATIONAL/scope=ONE",
this.uriInfo);
assertEquals(
- "ws://:8181/data-change-event-subscription/toaster:toaster/toasterStatus/datastore=OPERATIONAL/scope=ONE",
- response.getNewHeaders().get("Location").toString());
+ "ws://:8181/data-change-event-subscription/toaster:toaster/toasterStatus/datastore=OPERATIONAL/scope=ONE",
+ response.getNewHeaders().get("Location").toString());
}
@Test(expected = RestconfDocumentedException.class)
public void testSubscribeToStreamMissingDatastoreInPath() {
- final UriBuilder uriBuilder = UriBuilder.fromUri(uri);
+ final UriBuilder uriBuilder = UriBuilder.fromUri(URI);
doReturn(uriBuilder).when(this.uriInfo).getAbsolutePathBuilder();
final RestconfStreamsSubscriptionServiceImpl streamsSubscriptionService =
new RestconfStreamsSubscriptionServiceImpl(this.dataBrokerHandler, this.notificationServiceHandler,
@Test(expected = RestconfDocumentedException.class)
public void testSubscribeToStreamMissingScopeInPath() {
- final UriBuilder uriBuilder = UriBuilder.fromUri(uri);
+ final UriBuilder uriBuilder = UriBuilder.fromUri(URI);
doReturn(uriBuilder).when(this.uriInfo).getAbsolutePathBuilder();
final RestconfStreamsSubscriptionServiceImpl streamsSubscriptionService =
new RestconfStreamsSubscriptionServiceImpl(this.dataBrokerHandler, this.notificationServiceHandler,
import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
/**
- * Unit test for {@link ParametersUtil}
+ * Unit test for {@link ParametersUtil}.
*/
public class ParametersUtilTest {
/**
- * Test when all parameters are allowed
+ * Test when all parameters are allowed.
*/
@Test
public void checkParametersTypesTest() {
}
/**
- * Test when not allowed parameter type is used
+ * Test when not allowed parameter type is used.
*/
@Test
public void checkParametersTypesNegativeTest() {
}
/**
- * Test when parameter is present at most once
+ * Test when parameter is present at most once.
*/
@Test
public void checkParameterCountTest() {
}
/**
- * Test when parameter is present more than once
+ * Test when parameter is present more than once.
*/
@Test
public void checkParameterCountNegativeTest() {
import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHEntity;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusContext;
-import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusEntity;
+import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchEntity;
+import org.opendaylight.netconf.sal.restconf.impl.PatchStatusContext;
+import org.opendaylight.netconf.sal.restconf.impl.PatchStatusEntity;
import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
import org.opendaylight.restconf.RestConnectorProvider;
import org.opendaylight.restconf.common.references.SchemaContextRef;
private DOMTransactionChain transactionChain;
@Mock
- private DOMDataReadWriteTransaction rWTransaction;
+ private DOMDataReadWriteTransaction rwTransaction;
private SchemaContextRef refSchemaCtx;
- private YangInstanceIdentifier iIDCreateAndDelete;
- private YangInstanceIdentifier iIDMerge;
+ private YangInstanceIdentifier instanceIdCreateAndDelete;
+ private YangInstanceIdentifier instanceIdMerge;
private ContainerNode buildBaseContainerForTests;
private YangInstanceIdentifier targetNodeForCreateAndDelete;
private YangInstanceIdentifier targetNodeMerge;
final QName listArtistQName = QName.create(baseQName, "artist");
final QName leafNameQName = QName.create(baseQName, "name");
final YangInstanceIdentifier.NodeIdentifierWithPredicates nodeWithKey =
- new YangInstanceIdentifier.NodeIdentifierWithPredicates(listArtistQName, leafNameQName, "name of artist");
+ new YangInstanceIdentifier.NodeIdentifierWithPredicates(listArtistQName, leafNameQName, "name of artist");
- /** instance identifier for accessing leaf node "gap" */
- this.iIDCreateAndDelete = YangInstanceIdentifier.builder()
+ /* instance identifier for accessing leaf node "gap" */
+ this.instanceIdCreateAndDelete = YangInstanceIdentifier.builder()
.node(baseQName)
.node(containerPlayerQName)
.node(leafGapQName)
.build();
- /** values that are used for creating leaf for testPatchDataCreateAndDelete test */
+ /* values that are used for creating leaf for testPatchDataCreateAndDelete test */
final LeafNode buildGapLeaf = Builders.leafBuilder()
.withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(leafGapQName))
.withValue(0.2)
.withChild(buildPlayerContainer)
.build();
- this.targetNodeForCreateAndDelete = YangInstanceIdentifier.builder(this.iIDCreateAndDelete)
+ this.targetNodeForCreateAndDelete = YangInstanceIdentifier.builder(this.instanceIdCreateAndDelete)
.node(containerPlayerQName)
.node(leafGapQName)
.build();
- /** instance identifier for accessing leaf node "name" in list "artist" */
- this.iIDMerge = YangInstanceIdentifier.builder()
+ /* instance identifier for accessing leaf node "name" in list "artist" */
+ this.instanceIdMerge = YangInstanceIdentifier.builder()
.node(baseQName)
.node(containerLibraryQName)
.node(listArtistQName)
.node(leafNameQName)
.build();
- /** values that are used for creating leaf for testPatchDataReplaceMergeAndRemove test */
+ /* values that are used for creating leaf for testPatchDataReplaceMergeAndRemove test */
final LeafNode<Object> contentName = Builders.leafBuilder()
.withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create(baseQName, "name")))
.withValue("name of artist")
.nodeWithKey(listArtistQName, leafNameQName, "name of artist")
.build();
- /** Mocks */
- doReturn(this.rWTransaction).when(this.transactionChain).newReadWriteTransaction();
- doReturn(Futures.immediateCheckedFuture(null)).when(this.rWTransaction).submit();
+ /* Mocks */
+ doReturn(this.rwTransaction).when(this.transactionChain).newReadWriteTransaction();
+ doReturn(Futures.immediateCheckedFuture(null)).when(this.rwTransaction).submit();
}
@Test
public void testPatchDataReplaceMergeAndRemove() {
doReturn(Futures.immediateCheckedFuture(false)).doReturn(Futures.immediateCheckedFuture(true))
- .when(this.rWTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.targetNodeMerge);
+ .when(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.targetNodeMerge);
- final PATCHEntity entityReplace = new PATCHEntity("edit1", "REPLACE", this.targetNodeMerge, this.buildArtistList);
- final PATCHEntity entityMerge = new PATCHEntity("edit2", "MERGE", this.targetNodeMerge, this.buildArtistList);
- final PATCHEntity entityRemove = new PATCHEntity("edit3", "REMOVE", this.targetNodeMerge);
- final List<PATCHEntity> entities = new ArrayList<>();
+ final PatchEntity entityReplace =
+ new PatchEntity("edit1", "REPLACE", this.targetNodeMerge, this.buildArtistList);
+ final PatchEntity entityMerge = new PatchEntity("edit2", "MERGE", this.targetNodeMerge, this.buildArtistList);
+ final PatchEntity entityRemove = new PatchEntity("edit3", "REMOVE", this.targetNodeMerge);
+ final List<PatchEntity> entities = new ArrayList<>();
entities.add(entityReplace);
entities.add(entityMerge);
entities.add(entityRemove);
final InstanceIdentifierContext<? extends SchemaNode> iidContext =
- new InstanceIdentifierContext<>(this.iIDMerge, null, null, this.refSchemaCtx.get());
- final PATCHContext patchContext = new PATCHContext(iidContext, entities, "patchRMRm");
+ new InstanceIdentifierContext<>(this.instanceIdMerge, null, null, this.refSchemaCtx.get());
+ final PatchContext patchContext = new PatchContext(iidContext, entities, "patchRMRm");
final TransactionVarsWrapper wrapper = new TransactionVarsWrapper(iidContext, null, this.transactionChain);
- final PATCHStatusContext patchStatusContext =
+ final PatchStatusContext patchStatusContext =
PatchDataTransactionUtil.patchData(patchContext, wrapper, this.refSchemaCtx);
- for (final PATCHStatusEntity entity : patchStatusContext.getEditCollection()) {
+ for (final PatchStatusEntity entity : patchStatusContext.getEditCollection()) {
assertTrue(entity.isOk());
}
assertTrue(patchStatusContext.isOk());
@Test
public void testPatchDataCreateAndDelete() throws Exception {
doReturn(Futures.immediateCheckedFuture(false)).doReturn(Futures.immediateCheckedFuture(true))
- .when(this.rWTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.targetNodeForCreateAndDelete);
+ .when(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.targetNodeForCreateAndDelete);
- final PATCHEntity entityCreate =
- new PATCHEntity("edit1", "CREATE", this.targetNodeForCreateAndDelete, this.buildBaseContainerForTests);
- final PATCHEntity entityDelete =
- new PATCHEntity("edit2", "DELETE", this.targetNodeForCreateAndDelete);
- final List<PATCHEntity> entities = new ArrayList<>();
+ final PatchEntity entityCreate =
+ new PatchEntity("edit1", "CREATE", this.targetNodeForCreateAndDelete, this.buildBaseContainerForTests);
+ final PatchEntity entityDelete =
+ new PatchEntity("edit2", "DELETE", this.targetNodeForCreateAndDelete);
+ final List<PatchEntity> entities = new ArrayList<>();
entities.add(entityCreate);
entities.add(entityDelete);
final InstanceIdentifierContext<? extends SchemaNode> iidContext =
- new InstanceIdentifierContext<>(this.iIDCreateAndDelete, null, null, this.refSchemaCtx.get());
- final PATCHContext patchContext = new PATCHContext(iidContext, entities, "patchCD");
+ new InstanceIdentifierContext<>(this.instanceIdCreateAndDelete, null, null, this.refSchemaCtx.get());
+ final PatchContext patchContext = new PatchContext(iidContext, entities, "patchCD");
final TransactionVarsWrapper wrapper = new TransactionVarsWrapper(iidContext, null, this.transactionChain);
- final PATCHStatusContext patchStatusContext = PatchDataTransactionUtil.patchData(patchContext, wrapper, this.refSchemaCtx);
+ final PatchStatusContext patchStatusContext =
+ PatchDataTransactionUtil.patchData(patchContext, wrapper, this.refSchemaCtx);
- for (final PATCHStatusEntity entity : patchStatusContext.getEditCollection()) {
+ for (final PatchStatusEntity entity : patchStatusContext.getEditCollection()) {
assertTrue(entity.isOk());
}
assertTrue(patchStatusContext.isOk());
@Test
public void deleteNonexistentDataTest() {
doReturn(Futures.immediateCheckedFuture(false))
- .when(this.rWTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.targetNodeForCreateAndDelete);
+ .when(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.targetNodeForCreateAndDelete);
- final PATCHEntity entityDelete =
- new PATCHEntity("edit", "DELETE", this.targetNodeForCreateAndDelete);
- final List<PATCHEntity> entities = new ArrayList<>();
+ final PatchEntity entityDelete =
+ new PatchEntity("edit", "DELETE", this.targetNodeForCreateAndDelete);
+ final List<PatchEntity> entities = new ArrayList<>();
entities.add(entityDelete);
final InstanceIdentifierContext<? extends SchemaNode> iidContext =
- new InstanceIdentifierContext<>(this.iIDCreateAndDelete, null, null, this.refSchemaCtx.get());
- final PATCHContext patchContext = new PATCHContext(iidContext, entities, "patchD");
+ new InstanceIdentifierContext<>(this.instanceIdCreateAndDelete, null, null, this.refSchemaCtx.get());
+ final PatchContext patchContext = new PatchContext(iidContext, entities, "patchD");
final TransactionVarsWrapper wrapper = new TransactionVarsWrapper(iidContext, null, this.transactionChain);
- final PATCHStatusContext patchStatusContext = PatchDataTransactionUtil.patchData(patchContext, wrapper, this.refSchemaCtx);
+ final PatchStatusContext patchStatusContext =
+ PatchDataTransactionUtil.patchData(patchContext, wrapper, this.refSchemaCtx);
assertFalse(patchStatusContext.isOk());
assertEquals(RestconfError.ErrorType.PROTOCOL,
@Test
public void testPatchMergePutContainer() throws Exception {
doReturn(Futures.immediateCheckedFuture(false)).doReturn(Futures.immediateCheckedFuture(true))
- .when(this.rWTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.targetNodeForCreateAndDelete);
+ .when(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.targetNodeForCreateAndDelete);
- final PATCHEntity entityMerge =
- new PATCHEntity("edit1", "MERGE", this.targetNodeForCreateAndDelete, this.buildBaseContainerForTests);
- final List<PATCHEntity> entities = new ArrayList<>();
+ final PatchEntity entityMerge =
+ new PatchEntity("edit1", "MERGE", this.targetNodeForCreateAndDelete, this.buildBaseContainerForTests);
+ final List<PatchEntity> entities = new ArrayList<>();
entities.add(entityMerge);
final InstanceIdentifierContext<? extends SchemaNode> iidContext =
- new InstanceIdentifierContext<>(this.iIDCreateAndDelete, null, null, this.refSchemaCtx.get());
- final PATCHContext patchContext = new PATCHContext(iidContext, entities, "patchM");
+ new InstanceIdentifierContext<>(this.instanceIdCreateAndDelete, null, null, this.refSchemaCtx.get());
+ final PatchContext patchContext = new PatchContext(iidContext, entities, "patchM");
final TransactionVarsWrapper wrapper = new TransactionVarsWrapper(iidContext, null, this.transactionChain);
- final PATCHStatusContext patchStatusContext = PatchDataTransactionUtil.patchData(patchContext, wrapper, this.refSchemaCtx);
+ final PatchStatusContext patchStatusContext =
+ PatchDataTransactionUtil.patchData(patchContext, wrapper, this.refSchemaCtx);
- for (final PATCHStatusEntity entity : patchStatusContext.getEditCollection()) {
+ for (final PatchStatusEntity entity : patchStatusContext.getEditCollection()) {
assertTrue(entity.isOk());
}
assertTrue(patchStatusContext.isOk());
@Test
public void testPostContainerData() {
- final InstanceIdentifierContext<? extends SchemaNode> iidContext = new InstanceIdentifierContext<>(this.iid2, null, null, this.schema);
+ final InstanceIdentifierContext<? extends SchemaNode> iidContext =
+ new InstanceIdentifierContext<>(this.iid2, null, null, this.schema);
final NormalizedNodeContext payload = new NormalizedNodeContext(iidContext, this.buildBaseCont);
- doReturn(Futures.immediateCheckedFuture(false)).when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, this.iid2);
- final YangInstanceIdentifier.NodeIdentifier identifier = ((ContainerNode) ((SingletonSet) payload.getData().getValue()).iterator().next()).getIdentifier();
- final YangInstanceIdentifier node = payload.getInstanceIdentifierContext().getInstanceIdentifier().node(identifier);
- doReturn(Futures.immediateCheckedFuture(false)).when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, node);
+ doReturn(Futures.immediateCheckedFuture(false))
+ .when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, this.iid2);
+ final YangInstanceIdentifier.NodeIdentifier identifier =
+ ((ContainerNode) ((SingletonSet) payload.getData().getValue()).iterator().next()).getIdentifier();
+ final YangInstanceIdentifier node =
+ payload.getInstanceIdentifierContext().getInstanceIdentifier().node(identifier);
+ doReturn(Futures.immediateCheckedFuture(false))
+ .when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, node);
doNothing().when(this.readWrite).put(LogicalDatastoreType.CONFIGURATION, node, payload.getData());
doReturn(Futures.immediateCheckedFuture(null)).when(this.readWrite).submit();
- final TransactionVarsWrapper wrapper = new TransactionVarsWrapper(payload.getInstanceIdentifierContext(), null, this.transactionChain);
+ final TransactionVarsWrapper wrapper =
+ new TransactionVarsWrapper(payload.getInstanceIdentifierContext(), null, this.transactionChain);
final Response response =
PostDataTransactionUtil.postData(this.uriInfo, payload, wrapper, this.refSchemaCtx, null, null);
assertEquals(201, response.getStatus());
verify(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, this.iid2);
- verify(this.readWrite).put(LogicalDatastoreType.CONFIGURATION, payload.getInstanceIdentifierContext().getInstanceIdentifier(), payload.getData());
+ verify(this.readWrite).put(LogicalDatastoreType.CONFIGURATION,
+ payload.getInstanceIdentifierContext().getInstanceIdentifier(), payload.getData());
}
@Test
public void testPostListData() {
- final InstanceIdentifierContext<? extends SchemaNode> iidContext = new InstanceIdentifierContext<>(this.iid2, null, null, this.schema);
+ final InstanceIdentifierContext<? extends SchemaNode> iidContext =
+ new InstanceIdentifierContext<>(this.iid2, null, null, this.schema);
final NormalizedNodeContext payload = new NormalizedNodeContext(iidContext, this.buildList);
final MapNode data = (MapNode) payload.getData();
- final YangInstanceIdentifier.NodeIdentifierWithPredicates identifier = data.getValue().iterator().next().getIdentifier();
- final YangInstanceIdentifier node = payload.getInstanceIdentifierContext().getInstanceIdentifier().node(identifier);
- doReturn(Futures.immediateCheckedFuture(false)).when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, node);
+ final YangInstanceIdentifier.NodeIdentifierWithPredicates identifier =
+ data.getValue().iterator().next().getIdentifier();
+ final YangInstanceIdentifier node =
+ payload.getInstanceIdentifierContext().getInstanceIdentifier().node(identifier);
+ doReturn(Futures.immediateCheckedFuture(false))
+ .when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, node);
doNothing().when(this.readWrite).put(LogicalDatastoreType.CONFIGURATION, node, payload.getData());
doReturn(Futures.immediateCheckedFuture(null)).when(this.readWrite).submit();
- final TransactionVarsWrapper wrapper = new TransactionVarsWrapper(payload.getInstanceIdentifierContext(), null, this.transactionChain);
+ final TransactionVarsWrapper wrapper =
+ new TransactionVarsWrapper(payload.getInstanceIdentifierContext(), null, this.transactionChain);
final Response response =
PostDataTransactionUtil.postData(this.uriInfo, payload, wrapper, this.refSchemaCtx, null, null);
assertEquals(201, response.getStatus());
@Test
public void testPostDataFail() {
- final InstanceIdentifierContext<? extends SchemaNode> iidContext = new InstanceIdentifierContext<>(this.iid2, null, null, this.schema);
+ final InstanceIdentifierContext<? extends SchemaNode> iidContext =
+ new InstanceIdentifierContext<>(this.iid2, null, null, this.schema);
final NormalizedNodeContext payload = new NormalizedNodeContext(iidContext, this.buildBaseCont);
- doReturn(Futures.immediateCheckedFuture(false)).when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, this.iid2);
- final YangInstanceIdentifier.NodeIdentifier identifier = ((ContainerNode) ((SingletonSet) payload.getData().getValue()).iterator().next()).getIdentifier();
- final YangInstanceIdentifier node = payload.getInstanceIdentifierContext().getInstanceIdentifier().node(identifier);
- doReturn(Futures.immediateCheckedFuture(false)).when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, node);
+ doReturn(Futures.immediateCheckedFuture(false))
+ .when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, this.iid2);
+ final YangInstanceIdentifier.NodeIdentifier identifier =
+ ((ContainerNode) ((SingletonSet) payload.getData().getValue()).iterator().next()).getIdentifier();
+ final YangInstanceIdentifier node =
+ payload.getInstanceIdentifierContext().getInstanceIdentifier().node(identifier);
+ doReturn(Futures.immediateCheckedFuture(false))
+ .when(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, node);
doNothing().when(this.readWrite).put(LogicalDatastoreType.CONFIGURATION, node,
payload.getData());
- doReturn(Futures.immediateFailedCheckedFuture(new DOMException((short) 414, "Post request failed"))).when(this.readWrite).submit();
- final TransactionVarsWrapper wrapper = new TransactionVarsWrapper(payload.getInstanceIdentifierContext(), null, this.transactionChain);
+ doReturn(Futures.immediateFailedCheckedFuture(new DOMException((short) 414, "Post request failed")))
+ .when(this.readWrite).submit();
+ final TransactionVarsWrapper wrapper =
+ new TransactionVarsWrapper(payload.getInstanceIdentifierContext(), null, this.transactionChain);
final Response response =
PostDataTransactionUtil.postData(this.uriInfo, payload, wrapper, this.refSchemaCtx, null, null);
assertEquals(Response.Status.INTERNAL_SERVER_ERROR, response.getStatusInfo());
verify(this.readWrite).exists(LogicalDatastoreType.CONFIGURATION, this.iid2);
- verify(this.readWrite).put(LogicalDatastoreType.CONFIGURATION, payload.getInstanceIdentifierContext().getInstanceIdentifier(), payload.getData());
+ verify(this.readWrite).put(LogicalDatastoreType.CONFIGURATION,
+ payload.getInstanceIdentifierContext().getInstanceIdentifier(), payload.getData());
}
}
@Test
public void testValidInputData() throws Exception {
- final InstanceIdentifierContext<DataSchemaNode> iidContext = new InstanceIdentifierContext<>(this.iid, this.schemaNode, null, this.schema);
+ final InstanceIdentifierContext<DataSchemaNode> iidContext =
+ new InstanceIdentifierContext<>(this.iid, this.schemaNode, null, this.schema);
final NormalizedNodeContext payload = new NormalizedNodeContext(iidContext, this.buildLeaf);
PutDataTransactionUtil.validInputData(iidContext.getSchemaNode(), payload);
}
@Test
public void testValidTopLevelNodeName() throws Exception {
- InstanceIdentifierContext<DataSchemaNode> iidContext = new InstanceIdentifierContext<>(this.iid, this.schemaNode, null, this.schema);
+ InstanceIdentifierContext<DataSchemaNode> iidContext =
+ new InstanceIdentifierContext<>(this.iid, this.schemaNode, null, this.schema);
NormalizedNodeContext payload = new NormalizedNodeContext(iidContext, this.buildLeaf);
PutDataTransactionUtil.validTopLevelNodeName(iidContext.getInstanceIdentifier(), payload);
@Test(expected = RestconfDocumentedException.class)
public void testValidTopLevelNodeNamePathEmpty() throws Exception {
- final InstanceIdentifierContext<DataSchemaNode> iidContext = new InstanceIdentifierContext<>(this.iid, this.schemaNode, null, this.schema);
+ final InstanceIdentifierContext<DataSchemaNode> iidContext =
+ new InstanceIdentifierContext<>(this.iid, this.schemaNode, null, this.schema);
final NormalizedNodeContext payload = new NormalizedNodeContext(iidContext, this.buildLeaf);
PutDataTransactionUtil.validTopLevelNodeName(YangInstanceIdentifier.EMPTY, payload);
}
@Test(expected = RestconfDocumentedException.class)
public void testValidTopLevelNodeNameWrongTopIdentifier() throws Exception {
- final InstanceIdentifierContext<DataSchemaNode> iidContext = new InstanceIdentifierContext<>(this.iid, this.schemaNode, null, this.schema);
+ final InstanceIdentifierContext<DataSchemaNode> iidContext =
+ new InstanceIdentifierContext<>(this.iid, this.schemaNode, null, this.schema);
final NormalizedNodeContext payload = new NormalizedNodeContext(iidContext, this.buildLeaf);
PutDataTransactionUtil.validTopLevelNodeName(this.iid.getAncestor(1), payload);
}
@Test
public void testValidateListKeysEqualityInPayloadAndUri() throws Exception {
- final InstanceIdentifierContext<DataSchemaNode> iidContext = new InstanceIdentifierContext<>(this.iid3, this.schemaNode3, null, this.schema);
+ final InstanceIdentifierContext<DataSchemaNode> iidContext =
+ new InstanceIdentifierContext<>(this.iid3, this.schemaNode3, null, this.schema);
final NormalizedNodeContext payload = new NormalizedNodeContext(iidContext, this.buildListEntry);
PutDataTransactionUtil.validateListKeysEqualityInPayloadAndUri(payload);
}
@Test
public void testPutContainerData() throws Exception {
- final InstanceIdentifierContext<DataSchemaNode> iidContext = new InstanceIdentifierContext<>(this.iid2, this.schemaNode2, null, this.schema);
+ final InstanceIdentifierContext<DataSchemaNode> iidContext =
+ new InstanceIdentifierContext<>(this.iid2, this.schemaNode2, null, this.schema);
final NormalizedNodeContext payload = new NormalizedNodeContext(iidContext, this.buildBaseCont);
doReturn(this.readWrite).when(this.transactionChain).newReadWriteTransaction();
doReturn(this.read).when(this.transactionChain).newReadOnlyTransaction();
doReturn(this.write).when(this.transactionChain).newWriteOnlyTransaction();
- doReturn(Futures.immediateCheckedFuture(Optional.absent())).when(this.read).read(LogicalDatastoreType.CONFIGURATION, this.iid2);
- doNothing().when(this.write).put(LogicalDatastoreType.CONFIGURATION, payload.getInstanceIdentifierContext().getInstanceIdentifier(),
- payload.getData());
+ doReturn(Futures.immediateCheckedFuture(Optional.absent()))
+ .when(this.read).read(LogicalDatastoreType.CONFIGURATION, this.iid2);
+ doNothing().when(this.write).put(LogicalDatastoreType.CONFIGURATION,
+ payload.getInstanceIdentifierContext().getInstanceIdentifier(), payload.getData());
doReturn(Futures.immediateCheckedFuture(null)).when(this.readWrite).submit();
PutDataTransactionUtil.putData(payload, this.refSchemaCtx,
new TransactionVarsWrapper(payload.getInstanceIdentifierContext(), null, this.transactionChain), null,
null);
- verify(this.read).read(LogicalDatastoreType.CONFIGURATION, payload.getInstanceIdentifierContext().getInstanceIdentifier());
+ verify(this.read).read(LogicalDatastoreType.CONFIGURATION,
+ payload.getInstanceIdentifierContext().getInstanceIdentifier());
verify(this.readWrite).put(LogicalDatastoreType.CONFIGURATION,
payload.getInstanceIdentifierContext().getInstanceIdentifier(), payload.getData());
}
@Test
public void testPutleafData() throws Exception {
- final InstanceIdentifierContext<DataSchemaNode> iidContext = new InstanceIdentifierContext<>(this.iid, this.schemaNode, null, this.schema);
+ final InstanceIdentifierContext<DataSchemaNode> iidContext =
+ new InstanceIdentifierContext<>(this.iid, this.schemaNode, null, this.schema);
final NormalizedNodeContext payload = new NormalizedNodeContext(iidContext, this.buildLeaf);
doReturn(this.readWrite).when(this.transactionChain).newReadWriteTransaction();
doReturn(this.read).when(this.transactionChain).newReadOnlyTransaction();
doReturn(this.write).when(this.transactionChain).newWriteOnlyTransaction();
- doReturn(Futures.immediateCheckedFuture(Optional.absent())).when(this.read).read(LogicalDatastoreType.CONFIGURATION, this.iid);
- doNothing().when(this.write).put(LogicalDatastoreType.CONFIGURATION, payload.getInstanceIdentifierContext().getInstanceIdentifier(),
- payload.getData());
+ doReturn(Futures.immediateCheckedFuture(Optional.absent()))
+ .when(this.read).read(LogicalDatastoreType.CONFIGURATION, this.iid);
+ doNothing().when(this.write).put(LogicalDatastoreType.CONFIGURATION,
+ payload.getInstanceIdentifierContext().getInstanceIdentifier(), payload.getData());
doReturn(Futures.immediateCheckedFuture(null)).when(this.readWrite).submit();
PutDataTransactionUtil.putData(payload, this.refSchemaCtx,
new TransactionVarsWrapper(payload.getInstanceIdentifierContext(), null, this.transactionChain), null,
null);
- verify(this.read).read(LogicalDatastoreType.CONFIGURATION, payload.getInstanceIdentifierContext().getInstanceIdentifier());
+ verify(this.read).read(LogicalDatastoreType.CONFIGURATION,
+ payload.getInstanceIdentifierContext().getInstanceIdentifier());
verify(this.readWrite).put(LogicalDatastoreType.CONFIGURATION,
payload.getInstanceIdentifierContext().getInstanceIdentifier(), payload.getData());
}
@Test
public void testPutListData() throws Exception {
- final InstanceIdentifierContext<DataSchemaNode> iidContext = new InstanceIdentifierContext<>(this.iid2, this.schemaNode2, null, this.schema);
+ final InstanceIdentifierContext<DataSchemaNode> iidContext =
+ new InstanceIdentifierContext<>(this.iid2, this.schemaNode2, null, this.schema);
final NormalizedNodeContext payload = new NormalizedNodeContext(iidContext, this.buildBaseContWithList);
doReturn(this.readWrite).when(this.transactionChain).newReadWriteTransaction();
doReturn(this.read).when(this.transactionChain).newReadOnlyTransaction();
doReturn(this.write).when(this.transactionChain).newWriteOnlyTransaction();
- doReturn(Futures.immediateCheckedFuture(Optional.absent())).when(this.read).read(LogicalDatastoreType.CONFIGURATION, this.iid2);
- doNothing().when(this.write).put(LogicalDatastoreType.CONFIGURATION, payload.getInstanceIdentifierContext().getInstanceIdentifier(),
- payload.getData());
+ doReturn(Futures.immediateCheckedFuture(Optional.absent()))
+ .when(this.read).read(LogicalDatastoreType.CONFIGURATION, this.iid2);
+ doNothing().when(this.write).put(LogicalDatastoreType.CONFIGURATION,
+ payload.getInstanceIdentifierContext().getInstanceIdentifier(), payload.getData());
doReturn(Futures.immediateCheckedFuture(null)).when(this.readWrite).submit();
PutDataTransactionUtil.putData(payload, this.refSchemaCtx,
new TransactionVarsWrapper(payload.getInstanceIdentifierContext(), null, this.transactionChain), null,
}
/**
- * Test of parsing default parameters from URI request
+ * Test of parsing default parameters from URI request.
*/
@Test
public void parseUriParametersDefaultTest() {
}
/**
- * Test of parsing user defined parameters from URI request
+ * Test of parsing user defined parameters from URI request.
*/
@Test
public void parseUriParametersUserDefinedTest() {
public class RestconfInvokeOperationsUtilTest {
- private static final TestData data = new TestData();
+ private static final TestData DATA = new TestData();
private RpcServiceHandler serviceHandler;
@Mock
@Test
public void invokeRpcTest() {
- final DOMRpcResult mockResult = new DefaultDOMRpcResult(data.output, Collections.emptyList());
- doReturn(Futures.immediateCheckedFuture(mockResult)).when(rpcService).invokeRpc(data.rpc, data.input);
- final DOMRpcResult rpcResult = RestconfInvokeOperationsUtil.invokeRpc(data.input, data.rpc, serviceHandler);
+ final DOMRpcResult mockResult = new DefaultDOMRpcResult(DATA.output, Collections.emptyList());
+ doReturn(Futures.immediateCheckedFuture(mockResult)).when(rpcService).invokeRpc(DATA.rpc, DATA.input);
+ final DOMRpcResult rpcResult = RestconfInvokeOperationsUtil.invokeRpc(DATA.input, DATA.rpc, serviceHandler);
Assert.assertTrue(rpcResult.getErrors().isEmpty());
- assertEquals(data.output, rpcResult.getResult());
+ assertEquals(DATA.output, rpcResult.getResult());
}
@Test(expected = RestconfDocumentedException.class)
public void invokeRpcErrorsAndCheckTestTest() {
- final DOMRpcException exception = new DOMRpcImplementationNotAvailableException("No implementation of RPC " + data.errorRpc.toString() + " availible");
- doReturn(Futures.immediateFailedCheckedFuture(exception)).when(rpcService).invokeRpc(data.errorRpc, data.input);
- final DOMRpcResult rpcResult = RestconfInvokeOperationsUtil.invokeRpc(data.input, data.errorRpc, serviceHandler);
+ final DOMRpcException exception = new DOMRpcImplementationNotAvailableException(
+ "No implementation of RPC " + DATA.errorRpc.toString() + " available.");
+ doReturn(Futures.immediateFailedCheckedFuture(exception)).when(rpcService).invokeRpc(DATA.errorRpc, DATA.input);
+ final DOMRpcResult rpcResult =
+ RestconfInvokeOperationsUtil.invokeRpc(DATA.input, DATA.errorRpc, serviceHandler);
assertNull(rpcResult.getResult());
final Collection<RpcError> errorList = rpcResult.getErrors();
assertEquals(1, errorList.size());
final RpcError actual = errorList.iterator().next();
- assertEquals("No implementation of RPC " + data.errorRpc.toString() + " availible", actual.getMessage());
+ assertEquals("No implementation of RPC " + DATA.errorRpc.toString() + " available.", actual.getMessage());
assertEquals("operation-failed", actual.getTag());
assertEquals(RpcError.ErrorType.RPC, actual.getErrorType());
RestconfInvokeOperationsUtil.checkResponse(rpcResult);
@Test
public void invokeRpcViaMountPointTest() {
doReturn(Optional.fromNullable(rpcService)).when(moutPoint).getService(DOMRpcService.class);
- final DOMRpcResult mockResult = new DefaultDOMRpcResult(data.output, Collections.emptyList());
- doReturn(Futures.immediateCheckedFuture(mockResult)).when(rpcService).invokeRpc(data.rpc, data.input);
- final DOMRpcResult rpcResult = RestconfInvokeOperationsUtil.invokeRpcViaMountPoint(moutPoint, data.input, data.rpc);
+ final DOMRpcResult mockResult = new DefaultDOMRpcResult(DATA.output, Collections.emptyList());
+ doReturn(Futures.immediateCheckedFuture(mockResult)).when(rpcService).invokeRpc(DATA.rpc, DATA.input);
+ final DOMRpcResult rpcResult =
+ RestconfInvokeOperationsUtil.invokeRpcViaMountPoint(moutPoint, DATA.input, DATA.rpc);
Assert.assertTrue(rpcResult.getErrors().isEmpty());
- assertEquals(data.output, rpcResult.getResult());
+ assertEquals(DATA.output, rpcResult.getResult());
}
@Test(expected = RestconfDocumentedException.class)
public void invokeRpcMissingMountPointServiceTest() {
doReturn(Optional.absent()).when(moutPoint).getService(DOMRpcService.class);
- final DOMRpcResult mockResult = new DefaultDOMRpcResult(data.output, Collections.emptyList());
- doReturn(Futures.immediateCheckedFuture(mockResult)).when(rpcService).invokeRpc(data.rpc, data.input);
- final DOMRpcResult rpcResult = RestconfInvokeOperationsUtil.invokeRpcViaMountPoint(moutPoint, data.input, data.rpc);
+ final DOMRpcResult mockResult = new DefaultDOMRpcResult(DATA.output, Collections.emptyList());
+ doReturn(Futures.immediateCheckedFuture(mockResult)).when(rpcService).invokeRpc(DATA.rpc, DATA.input);
+ final DOMRpcResult rpcResult =
+ RestconfInvokeOperationsUtil.invokeRpcViaMountPoint(moutPoint, DATA.input, DATA.rpc);
}
@Test
public void checkResponseTest() {
- final DOMRpcResult mockResult = new DefaultDOMRpcResult(data.output, Collections.emptyList());
- doReturn(Futures.immediateCheckedFuture(mockResult)).when(rpcService).invokeRpc(data.rpc, data.input);
- final DOMRpcResult rpcResult = RestconfInvokeOperationsUtil.invokeRpc(data.input, data.rpc, serviceHandler);
+ final DOMRpcResult mockResult = new DefaultDOMRpcResult(DATA.output, Collections.emptyList());
+ doReturn(Futures.immediateCheckedFuture(mockResult)).when(rpcService).invokeRpc(DATA.rpc, DATA.input);
+ final DOMRpcResult rpcResult = RestconfInvokeOperationsUtil.invokeRpc(DATA.input, DATA.rpc, serviceHandler);
Assert.assertTrue(rpcResult.getErrors().isEmpty());
- assertEquals(data.output, rpcResult.getResult());
+ assertEquals(DATA.output, rpcResult.getResult());
assertNotNull(RestconfInvokeOperationsUtil.checkResponse(rpcResult));
}
.withValue("content")
.build();
final LeafNode<Object> content2 = Builders.leafBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create(base, "leaf-content-different")))
+ .withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifier(QName.create(base, "leaf-content-different")))
.withValue("content-different")
.build();
- final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainer = Builders.leafBuilder()
+ final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainer =
+ Builders.leafBuilder()
.withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create(listQname, "identifier")))
.withValue("id")
.build();
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
- * Unit tests for {@link RestconfMappingNodeUtil}
+ * Unit tests for {@link RestconfMappingNodeUtil}.
*/
public class RestconfMappingNodeUtilTest {
+
+ private static final Logger LOG = LoggerFactory.getLogger(RestconfMappingNodeUtilTest.class);
+
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void toStreamEntryNodeTest() throws Exception {
- final YangInstanceIdentifier path =
- ParserIdentifier.toInstanceIdentifier("nested-module:depth1-cont/depth2-leaf1", schemaContextMonitoring, null).getInstanceIdentifier();
+ final YangInstanceIdentifier path = ParserIdentifier.toInstanceIdentifier(
+ "nested-module:depth1-cont/depth2-leaf1", schemaContextMonitoring, null).getInstanceIdentifier();
final Instant start = Instant.now();
final String outputType = "XML";
final URI uri = new URI("uri");
final Map<QName, Object> map =
prepareMap(path.getLastPathArgument().getNodeType().getLocalName(), uri, start, outputType);
- final NormalizedNode mappedData = RestconfMappingNodeUtil.mapDataChangeNotificationStreamByIetfRestconfMonitoring(path, start, outputType, uri,
- monitoringModule, exist, schemaContextMonitoring);
+ final NormalizedNode mappedData =
+ RestconfMappingNodeUtil.mapDataChangeNotificationStreamByIetfRestconfMonitoring(
+ path, start, outputType, uri, monitoringModule, exist, schemaContextMonitoring);
assertNotNull(mappedData);
testData(map, mappedData);
}
}
/**
- * Verify loaded modules
+ * Verify loaded modules.
*
* @param containerNode
- * - modules
+ * modules
*/
private static void verifyLoadedModules(final ContainerNode containerNode) {
case IetfYangLibrary.SPECIFIC_MODULE_REVISION_LEAF:
revision = String.valueOf(((LeafNode) dataContainerChild).getValue());
break;
+ default :
+ LOG.info("Unknown local name '{}' of node.",
+ dataContainerChild.getNodeType().getLocalName());
+ break;
}
}
loadedModules.put(name, revision);
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
/**
- * Unit test for {@link ParserFieldsParameter}
+ * Unit test for {@link ParserFieldsParameter}.
*/
public class ParserFieldsParameterTest {
Mockito.when(this.containerJukebox.getDataChildByName(this.libraryQName)).thenReturn(this.containerLibrary);
Mockito.when(this.augmentedContainerLibrary.getQName()).thenReturn(this.augmentedLibraryQName);
- Mockito.when(this.containerJukebox.getDataChildByName(this.augmentedLibraryQName)).thenReturn(this.augmentedContainerLibrary);
+ Mockito.when(this.containerJukebox.getDataChildByName(this.augmentedLibraryQName))
+ .thenReturn(this.augmentedContainerLibrary);
Mockito.when(this.containerPlayer.getQName()).thenReturn(this.playerQName);
Mockito.when(this.containerJukebox.getDataChildByName(this.playerQName)).thenReturn(this.containerPlayer);
}
/**
- * Test parse fields parameter containing only one child selected
+ * Test parse fields parameter containing only one child selected.
*/
@Test
public void parseFieldsParameterSimplePathTest() {
}
/**
- * Test parse fields parameter containing two child nodes selected
+ * Test parse fields parameter containing two child nodes selected.
*/
@Test
public void parseFieldsParameterDoublePathTest() {
}
/**
- * Test parse fields parameter containing sub-children selected delimited by slash
+ * Test parse fields parameter containing sub-children selected delimited by slash.
*/
@Test
public void parseFieldsParameterSubPathTest() {
}
/**
- * Test parse fields parameter containing sub-children selected delimited by parenthesis
+ * Test parse fields parameter containing sub-children selected delimited by parenthesis.
*/
@Test
public void parseFieldsParameterChildrenPathTest() {
}
/**
- * Test parse fields parameter when augmentation with different namespace is used
+ * Test parse fields parameter when augmentation with different namespace is used.
*/
@Test
public void parseFieldsParameterNamespaceTest() {
}
/**
- * Test parse fields parameter containing not expected character
+ * Test parse fields parameter containing not expected character.
*/
@Test
public void parseFieldsParameterNotExpectedCharacterNegativeTest() {
}
/**
- * Test parse fields parameter with missing closing parenthesis
+ * Test parse fields parameter with missing closing parenthesis.
*/
@Test
public void parseFieldsParameterMissingParenthesisNegativeTest() {
}
/**
- * Test parse fields parameter when not existing child node selected
+ * Test parse fields parameter when not existing child node selected.
*/
@Test
public void parseFieldsParameterMissingChildNodeNegativeTest() {
}
/**
- * Test parse fields parameter with unexpected character after parenthesis
+ * Test parse fields parameter with unexpected character after parenthesis.
*/
@Test
public void parseFieldsParameterAfterParenthesisNegativeTest() {
}
/**
- * Test parse fields parameter with missing semicolon after parenthesis
+ * Test parse fields parameter with missing semicolon after parenthesis.
*/
@Test
public void parseFieldsParameterMissingSemicolonNegativeTest() {
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
/**
- * Unit tests for {@link ParserIdentifier}
+ * Unit tests for {@link ParserIdentifier}.
*/
public class ParserIdentifierTest {
// mount point identifier
// register mount point with null schema context
when(this.mockMountPoint.getSchemaContext()).thenReturn(null);
- when(this.mockMountPointService.getMountPoint(YangInstanceIdentifier.EMPTY)).thenReturn(Optional.of(this.mockMountPoint));
+ when(this.mockMountPointService.getMountPoint(YangInstanceIdentifier.EMPTY))
+ .thenReturn(Optional.of(this.mockMountPoint));
}
/**
- * {@link ParserIdentifier#toInstanceIdentifier(String, SchemaContext)} tests
+ * {@link ParserIdentifier#toInstanceIdentifier(String, SchemaContext)} tests.
*/
/**
@Test
public void toInstanceIdentifierMountPointInvalidIdentifierNegativeTest() {
this.thrown.expect(IllegalArgumentException.class);
- ParserIdentifier.toInstanceIdentifier(INVALID_MOUNT_POINT_IDENT, this.schemaContext, Optional.of(this.mountPointService));
+ ParserIdentifier.toInstanceIdentifier(
+ INVALID_MOUNT_POINT_IDENT, this.schemaContext, Optional.of(this.mountPointService));
}
/**
}
/**
- * {@link ParserIdentifier#makeQNameFromIdentifier(String)} tests
+ * {@link ParserIdentifier#makeQNameFromIdentifier(String)} tests.
*/
/**
}
/**
- * {@link ParserIdentifier#toSchemaExportContextFromIdentifier(SchemaContext, String, DOMMountPointService)} tests
+ * {@link ParserIdentifier#toSchemaExportContextFromIdentifier(SchemaContext, String, DOMMountPointService)} tests.
*/
/**
*/
@Test
public void toSchemaExportContextFromIdentifierTest() {
- final SchemaExportContext exportContext = ParserIdentifier.
- toSchemaExportContextFromIdentifier(this.schemaContext, TEST_MODULE_NAME + "/" + TEST_MODULE_REVISION, null);
+ final SchemaExportContext exportContext = ParserIdentifier.toSchemaExportContextFromIdentifier(
+ this.schemaContext, TEST_MODULE_NAME + "/" + TEST_MODULE_REVISION, null);
assertNotNull("Export context should be parsed", exportContext);
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
/**
- * Unit tests for {@link RestconfSchemaUtil}
+ * Unit tests for {@link RestconfSchemaUtil}.
*/
public class RestconfSchemaUtilTest {
import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
/**
- * Unit test for {@link RestconfValidation}
+ * Unit test for {@link RestconfValidation}.
*/
public class RestconfValidationTest {
- private static final List<String> revisions = Arrays.asList("2014-01-01", "2015-01-01", "2016-01-01");
- private static final List<String> names = Arrays.asList("_module-1", "_module-2", "_module-3");
+ private static final List<String> REVISIONS = Arrays.asList("2014-01-01", "2015-01-01", "2016-01-01");
+ private static final List<String> NAMES = Arrays.asList("_module-1", "_module-2", "_module-3");
/**
* Test of successful validation of module revision.
*/
@Test
public void validateAndGetRevisionTest() {
- Date revision = RestconfValidation.validateAndGetRevision(revisions.iterator());
+ Date revision = RestconfValidation.validateAndGetRevision(REVISIONS.iterator());
assertNotNull("Correct module revision should be validated", revision);
- Calendar c = Calendar.getInstance();
- c.setTime(revision);
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTime(revision);
- assertEquals(2014, c.get(Calendar.YEAR));
- assertEquals(0, c.get(Calendar.MONTH));
- assertEquals(1, c.get(Calendar.DAY_OF_MONTH));
+ assertEquals(2014, calendar.get(Calendar.YEAR));
+ assertEquals(0, calendar.get(Calendar.MONTH));
+ assertEquals(1, calendar.get(Calendar.DAY_OF_MONTH));
}
/**
*/
@Test
public void validateAndGetModulNameTest() {
- String moduleName = RestconfValidation.validateAndGetModulName(names.iterator());
+ String moduleName = RestconfValidation.validateAndGetModulName(NAMES.iterator());
assertNotNull("Correct module name should be validated", moduleName);
assertEquals("_module-1", moduleName);
}
*/
@Test
public void validateAndGetModuleNameNotParsableFirstTest() {
- try {
- RestconfValidation.validateAndGetModulName(
- Arrays.asList("01-not-parsable-as-name-on-firts-char").iterator());
- fail("Test should fail due to not parsable module name on the first character");
- } catch (RestconfDocumentedException e) {
- assertEquals(RestconfError.ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
- assertEquals(RestconfError.ErrorTag.INVALID_VALUE, e.getErrors().get(0).getErrorTag());
- assertEquals(400, e.getErrors().get(0).getErrorTag().getStatusCode());
- }
+ try {
+ RestconfValidation.validateAndGetModulName(
+ Arrays.asList("01-not-parsable-as-name-on-firts-char").iterator());
+ fail("Test should fail due to not parsable module name on the first character");
+ } catch (RestconfDocumentedException e) {
+ assertEquals(RestconfError.ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
+ assertEquals(RestconfError.ErrorTag.INVALID_VALUE, e.getErrors().get(0).getErrorTag());
+ assertEquals(400, e.getErrors().get(0).getErrorTag().getStatusCode());
+ }
}
/**