@Context
private Request request;
+ private final ControllerContext controllerContext;
+
+ protected AbstractIdentifierAwareJaxRsProvider(ControllerContext controllerContext) {
+ this.controllerContext = controllerContext;
+ }
+
protected final String getIdentifier() {
return this.uriInfo.getPathParameters(false).getFirst(RestconfConstants.IDENTIFIER);
}
protected InstanceIdentifierContext<?> getInstanceIdentifierContext() {
- return ControllerContext.getInstance().toInstanceIdentifier(getIdentifier());
+ return controllerContext.toInstanceIdentifier(getIdentifier());
}
protected UriInfo getUriInfo() {
return POST.equals(this.request.getMethod());
}
+ protected ControllerContext getControllerContext() {
+ return controllerContext;
+ }
+
Request getRequest() {
return this.request;
}
private static final Logger LOG = LoggerFactory.getLogger(JsonNormalizedNodeBodyReader.class);
+ public JsonNormalizedNodeBodyReader(ControllerContext controllerContext) {
+ super(controllerContext);
+ }
+
@Override
public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
final MediaType mediaType) {
@SuppressWarnings("checkstyle:IllegalCatch")
public static NormalizedNodeContext readFrom(final String uriPath, final InputStream entityStream,
- final boolean isPost) throws RestconfDocumentedException {
+ final boolean isPost, final ControllerContext controllerContext) throws RestconfDocumentedException {
try {
- return readFrom(ControllerContext.getInstance().toInstanceIdentifier(uriPath), entityStream, isPost);
+ return readFrom(controllerContext.toInstanceIdentifier(uriPath), entityStream, isPost);
} catch (final Exception e) {
propagateExceptionAs(e);
return null; // no-op
import java.util.List;
import java.util.Locale;
import java.util.Optional;
+import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nonnull;
import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
implements MessageBodyReader<PatchContext> {
private static final Logger LOG = LoggerFactory.getLogger(JsonToPatchBodyReader.class);
- private String patchId;
+
+ public JsonToPatchBodyReader(ControllerContext controllerContext) {
+ super(controllerContext);
+ }
@Override
public boolean isReadable(final Class<?> type, final Type genericType,
public PatchContext readFrom(final String uriPath, final InputStream entityStream) throws
RestconfDocumentedException {
try {
- return readFrom(ControllerContext.getInstance().toInstanceIdentifier(uriPath), entityStream);
+ return readFrom(getControllerContext().toInstanceIdentifier(uriPath), entityStream);
} catch (final Exception e) {
propagateExceptionAs(e);
return null; // no-op
final JsonReader jsonReader = new JsonReader(new InputStreamReader(nonEmptyInputStreamOptional.get(),
StandardCharsets.UTF_8));
- final List<PatchEntity> resultList = read(jsonReader, path);
+ AtomicReference<String> patchId = new AtomicReference<>();
+ final List<PatchEntity> resultList = read(jsonReader, path, patchId);
jsonReader.close();
- return new PatchContext(path, resultList, this.patchId);
+ return new PatchContext(path, resultList, patchId.get());
}
private static RuntimeException propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
ErrorTag.MALFORMED_MESSAGE, exception);
}
- private List<PatchEntity> read(final JsonReader in, final InstanceIdentifierContext<?> path) throws IOException {
+ private List<PatchEntity> read(final JsonReader in, final InstanceIdentifierContext<?> path,
+ final AtomicReference<String> patchId) throws IOException {
final List<PatchEntity> resultCollection = new ArrayList<>();
final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
path.getSchemaContext());
case END_DOCUMENT:
break;
case NAME:
- parseByName(in.nextName(), edit, in, path, codec, resultCollection);
+ parseByName(in.nextName(), edit, in, path, codec, resultCollection, patchId);
break;
case END_OBJECT:
in.endObject();
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,
+ @Nonnull final AtomicReference<String> patchId) throws IOException {
switch (name) {
case "edit" :
if (in.peek() == JsonToken.BEGIN_ARRAY) {
break;
case "patch-id" :
- this.patchId = in.nextString();
+ patchId.set(in.nextString());
break;
default:
break;
@Override
public Set<Class<?>> getClasses() {
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(NormalizedNodeJsonBodyWriter.class)
singletons.add(brokerFacade);
singletons.add(schemaRetrieval);
singletons.add(new RestconfCompositeWrapper(StatisticsRestconfServiceWrapper.getInstance(), schemaRetrieval));
+ singletons.add(new RestconfDocumentedExceptionMapper(controllerContext));
+ singletons.add(new XmlNormalizedNodeBodyReader(controllerContext));
+ singletons.add(new JsonNormalizedNodeBodyReader(controllerContext));
+ singletons.add(new XmlToPatchBodyReader(controllerContext));
+ singletons.add(new JsonToPatchBodyReader(controllerContext));
// singletons.add(StructuredDataToXmlProvider.INSTANCE);
// singletons.add(StructuredDataToJsonProvider.INSTANCE);
// singletons.add(JsonToCompositeNodeProvider.INSTANCE);
@Context
private HttpHeaders headers;
+ private final ControllerContext controllerContext;
+
+ public RestconfDocumentedExceptionMapper(ControllerContext controllerContext) {
+ this.controllerContext = Preconditions.checkNotNull(controllerContext);
+ }
+
@Override
public Response toResponse(final RestconfDocumentedException exception) {
final int status = errors.iterator().next().getErrorTag().getStatusCode();
- final ControllerContext context = ControllerContext.getInstance();
- final DataNodeContainer errorsSchemaNode = (DataNodeContainer) context.getRestconfModuleErrorsSchemaNode();
+ final DataNodeContainer errorsSchemaNode =
+ (DataNodeContainer) controllerContext.getRestconfModuleErrorsSchemaNode();
if (errorsSchemaNode == null) {
return Response.status(status).type(MediaType.TEXT_PLAIN_TYPE).entity(exception.getMessage()).build();
errContBuild.withChild(listErorsBuilder.build());
final NormalizedNodeContext errContext = new NormalizedNodeContext(new InstanceIdentifierContext<>(null,
- (DataSchemaNode) errorsSchemaNode, null, context.getGlobalSchema()), errContBuild.build());
+ (DataSchemaNode) errorsSchemaNode, null, controllerContext.getGlobalSchema()), errContBuild.build());
Object responseBody;
if (mediaType.getSubtype().endsWith("json")) {
import javax.xml.transform.dom.DOMSource;
import org.opendaylight.netconf.sal.rest.api.Draft02;
import org.opendaylight.netconf.sal.rest.api.RestconfService;
+import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
import org.opendaylight.restconf.common.context.NormalizedNodeContext;
import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
private static final Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
+ public XmlNormalizedNodeBodyReader(ControllerContext controllerContext) {
+ super(controllerContext);
+ }
+
@Override
public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
final MediaType mediaType) {
import javax.xml.transform.dom.DOMSource;
import org.opendaylight.netconf.sal.rest.api.Draft02;
import org.opendaylight.netconf.sal.rest.api.RestconfService;
+import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
private static final Logger LOG = LoggerFactory.getLogger(XmlToPatchBodyReader.class);
+ public XmlToPatchBodyReader(ControllerContext controllerContext) {
+ super(controllerContext);
+ }
+
@Override
public boolean isReadable(final Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType) {
private DOMDataBroker domDataBroker;
private DOMNotificationService domNotification;
+ private ControllerContext controllerContext;
BrokerFacade() {
this.domNotification = service;
}
+ public void setControllerContext(ControllerContext controllerContext) {
+ this.controllerContext = controllerContext;
+ }
+
public static BrokerFacade getInstance() {
return BrokerFacade.INSTANCE;
}
throw new RestconfDocumentedException("Bad value used with with-defaults parameter : " + withDefa);
}
- final SchemaContext ctx = ControllerContext.getInstance().getGlobalSchema();
+ final SchemaContext ctx = controllerContext.getGlobalSchema();
final DataSchemaContextTree baseSchemaCtxTree = DataSchemaContextTree.from(ctx);
final DataSchemaNode baseSchemaNode = baseSchemaCtxTree.getChild(path).getDataSchemaNode();
if (result instanceof ContainerNode) {
}
}
- private static void insertWithPointLeafListPost(final DOMDataReadWriteTransaction rwTransaction,
+ private 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());
- final InstanceIdentifierContext<?> instanceIdentifier =
- ControllerContext.getInstance().toInstanceIdentifier(point);
+ final InstanceIdentifierContext<?> instanceIdentifier = controllerContext.toInstanceIdentifier(point);
int lastItemPosition = 0;
for (final LeafSetEntryNode<?> nodeChild : readLeafList.getValue()) {
if (nodeChild.getIdentifier().equals(instanceIdentifier.getInstanceIdentifier().getLastPathArgument())) {
}
}
- private static void insertWithPointListPost(final DOMDataReadWriteTransaction rwTransaction,
+ private 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());
- final InstanceIdentifierContext<?> instanceIdentifier =
- ControllerContext.getInstance().toInstanceIdentifier(point);
+ final InstanceIdentifierContext<?> instanceIdentifier = controllerContext.toInstanceIdentifier(point);
int lastItemPosition = 0;
for (final MapEntryNode mapEntryNode : readList.getValue()) {
if (mapEntryNode.getIdentifier()
}
}
- private static void insertWithPointLeafListPut(final DOMDataWriteTransaction tx,
+ private void insertWithPointLeafListPut(final DOMDataWriteTransaction tx,
final LogicalDatastoreType datastore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload,
final SchemaContext schemaContext, final String point, final OrderedLeafSetNode<?> readLeafList,
final boolean before) {
tx.delete(datastore, path.getParent());
- final InstanceIdentifierContext<?> instanceIdentifier =
- ControllerContext.getInstance().toInstanceIdentifier(point);
+ final InstanceIdentifierContext<?> instanceIdentifier = controllerContext.toInstanceIdentifier(point);
int index1 = 0;
for (final LeafSetEntryNode<?> nodeChild : readLeafList.getValue()) {
if (nodeChild.getIdentifier().equals(instanceIdentifier.getInstanceIdentifier().getLastPathArgument())) {
}
}
- private static void insertWithPointListPut(final DOMDataWriteTransaction tx, final LogicalDatastoreType datastore,
+ private void insertWithPointListPut(final DOMDataWriteTransaction tx, final LogicalDatastoreType datastore,
final YangInstanceIdentifier path, final NormalizedNode<?, ?> payload, final SchemaContext schemaContext,
final String point, final OrderedMapNode readList, final boolean before) {
tx.delete(datastore, path.getParent());
- final InstanceIdentifierContext<?> instanceIdentifier =
- ControllerContext.getInstance().toInstanceIdentifier(point);
+ final InstanceIdentifierContext<?> instanceIdentifier = controllerContext.toInstanceIdentifier(point);
int index1 = 0;
for (final MapEntryNode mapEntryNode : readList.getValue()) {
if (mapEntryNode.getIdentifier().equals(instanceIdentifier.getInstanceIdentifier().getLastPathArgument())) {
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.io.Closeable;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
+import org.opendaylight.controller.sal.core.api.model.SchemaService;
+import org.opendaylight.mdsal.dom.api.DOMSchemaService;
import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
import org.opendaylight.netconf.sal.rest.api.Draft02;
import org.opendaylight.netconf.sal.rest.api.Draft02.RestConfModule;
import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
import org.opendaylight.restconf.common.util.RestUtil;
import org.opendaylight.yangtools.concepts.Codec;
+import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class ControllerContext implements SchemaContextListener {
+public final class ControllerContext implements SchemaContextListener, Closeable {
// FIXME: this should be in md-sal somewhere
public static final String MOUNT = "yang-ext:mount";
private final AtomicReference<Map<QName, RpcDefinition>> qnameToRpc = new AtomicReference<>(Collections.emptyMap());
- // FIXME; these three should be final
+ private DOMMountPointService mountService;
+ private DOMYangTextSourceProvider yangTextSourceProvider;
+ private ListenerRegistration<SchemaContextListener> listenerRegistration;
private volatile SchemaContext globalSchema;
- private volatile DOMMountPointService mountService;
- private volatile DOMYangTextSourceProvider yangTextSourceProvider;
- private DataNormalizer dataNormalizer;
+ private volatile DataNormalizer dataNormalizer;
+ private ControllerContext(SchemaService schemaService, DOMMountPointService mountService,
+ DOMYangTextSourceProvider yangTextSourceProvider) {
+ this.mountService = mountService;
+ this.yangTextSourceProvider = yangTextSourceProvider;
- public void setGlobalSchema(final SchemaContext globalSchema) {
- this.globalSchema = globalSchema;
- this.dataNormalizer = new DataNormalizer(globalSchema);
+ setGlobalSchema(schemaService.getGlobalContext());
+ listenerRegistration = schemaService.registerSchemaContextListener(this);
}
- public void setMountService(final DOMMountPointService mountService) {
- this.mountService = mountService;
+ // Temporary until the static instance is removed.
+ @Deprecated
+ private ControllerContext() {
}
- public DOMYangTextSourceProvider getYangTextSourceProvider() {
- return yangTextSourceProvider;
- }
+ public static ControllerContext newInstance(SchemaService schemaService, DOMMountPointService mountService,
+ DOMSchemaService domSchemaService) {
+ final DOMYangTextSourceProvider yangTextSourceProvider =
+ (DOMYangTextSourceProvider) domSchemaService.getSupportedExtensions().get(DOMYangTextSourceProvider.class);
- public void setYangTextSourceProvider(DOMYangTextSourceProvider yangTextSourceProvider) {
- this.yangTextSourceProvider = yangTextSourceProvider;
- }
+ INSTANCE.mountService = mountService;
+ INSTANCE.yangTextSourceProvider = yangTextSourceProvider;
- ControllerContext() {
+ INSTANCE.onGlobalContextUpdated(schemaService.getGlobalContext());
+ INSTANCE.listenerRegistration = schemaService.registerSchemaContextListener(INSTANCE);
+ return INSTANCE;
+ //return new ControllerContext(schemaService, mountService, domSchemaServiceExtension);
}
+ @Deprecated
public static ControllerContext getInstance() {
return INSTANCE;
}
+ private void setGlobalSchema(final SchemaContext globalSchema) {
+ this.globalSchema = globalSchema;
+ this.dataNormalizer = new DataNormalizer(globalSchema);
+ }
+
+ public DOMYangTextSourceProvider getYangTextSourceProvider() {
+ return yangTextSourceProvider;
+ }
+
private void checkPreconditions() {
if (this.globalSchema == null) {
throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
}
}
+ @Override
+ public void close() {
+ listenerRegistration.close();
+ }
+
public void setSchemas(final SchemaContext schemas) {
onGlobalContextUpdated(schemas);
}
return ret;
}
- private static String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount)
+ private String toUriString(final Object object, final LeafSchemaNode leafNode, final DOMMountPoint mount)
throws UnsupportedEncodingException {
- final Codec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount);
+ final Codec<Object, Object> codec = RestCodec.from(leafNode.getType(), mount, this);
// FIXME: UrlEncoder looks up a well-known charset, we need something that will use it directly
return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), URI_ENCODING_CHARSET.name());
}
if (targetNode == null && parentNode instanceof Module) {
final RpcDefinition rpc;
if (mountPoint == null) {
- rpc = ControllerContext.getInstance().getRpcDefinition(head, module.getRevision());
+ rpc = getRpcDefinition(head, module.getRevision());
} else {
final String rpcName = toNodeName(head);
- ControllerContext.getInstance();
- rpc = ControllerContext.getRpcDefinition(module, rpcName);
+ rpc = getRpcDefinition(module, rpcName);
}
if (rpc != null) {
return new InstanceIdentifierContext<>(builder.build(), rpc, mountPoint,
if (baseType instanceof LeafrefTypeDefinition) {
typedef = SchemaContextUtil.getBaseTypeForLeafRef((LeafrefTypeDefinition) baseType, schemaContext, node);
}
- final Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
+ final Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint, this);
Object decoded = codec.deserialize(urlDecoded);
String additionalInfo = "";
if (decoded == null) {
public DataNormalizationOperation<?> getRootOperation() {
return this.dataNormalizer.getRootOperation();
}
-
}
private static final Annotation[] EMPTY_ANNOTATIONS = new Annotation[0];
+ private final ControllerContext controllerContext;
+
+ public JSONRestconfServiceImpl(ControllerContext controllerContext) {
+ this.controllerContext = controllerContext;
+ }
+
@SuppressWarnings("checkstyle:IllegalCatch")
@Override
public void put(final String uriPath, final String payload) throws OperationFailedException {
LOG.debug("put: uriPath: {}, payload: {}", uriPath, payload);
final InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
- final NormalizedNodeContext context = JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, false);
+ final NormalizedNodeContext context = JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, false,
+ controllerContext);
LOG.debug("Parsed YangInstanceIdentifier: {}", context.getInstanceIdentifierContext().getInstanceIdentifier());
LOG.debug("Parsed NormalizedNode: {}", context.getData());
LOG.debug("post: uriPath: {}, payload: {}", uriPath, payload);
final InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
- final NormalizedNodeContext context = JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, true);
+ final NormalizedNodeContext context = JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, true,
+ controllerContext);
LOG.debug("Parsed YangInstanceIdentifier: {}", context.getInstanceIdentifierContext().getInstanceIdentifier());
LOG.debug("Parsed NormalizedNode: {}", context.getData());
if (actualInput != null) {
final InputStream entityStream = new ByteArrayInputStream(actualInput.getBytes(StandardCharsets.UTF_8));
final NormalizedNodeContext inputContext =
- JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, true);
+ JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, true, controllerContext);
LOG.debug("Parsed YangInstanceIdentifier: {}", inputContext.getInstanceIdentifierContext()
.getInstanceIdentifier());
final InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
- JsonToPatchBodyReader jsonToPatchBodyReader = new JsonToPatchBodyReader();
+ JsonToPatchBodyReader jsonToPatchBodyReader = new JsonToPatchBodyReader(controllerContext);
final PatchContext context = jsonToPatchBodyReader.readFrom(uriPath, entityStream);
LOG.debug("Parsed YangInstanceIdentifier: {}", context.getInstanceIdentifierContext().getInstanceIdentifier());
}
public static Codec<Object, Object> from(final TypeDefinition<?> typeDefinition,
- final DOMMountPoint mountPoint) {
- return new ObjectCodec(typeDefinition, mountPoint);
+ final DOMMountPoint mountPoint, final ControllerContext controllerContext) {
+ return new ObjectCodec(typeDefinition, mountPoint, controllerContext);
}
@SuppressWarnings("rawtypes")
private static final Logger LOG = LoggerFactory.getLogger(ObjectCodec.class);
public static final Codec LEAFREF_DEFAULT_CODEC = new LeafrefCodecImpl();
+
+ private final ControllerContext controllerContext;
private final Codec instanceIdentifier;
private final Codec identityrefCodec;
private final TypeDefinition<?> type;
- private ObjectCodec(final TypeDefinition<?> typeDefinition, final DOMMountPoint mountPoint) {
+ private ObjectCodec(final TypeDefinition<?> typeDefinition, final DOMMountPoint mountPoint,
+ final ControllerContext controllerContext) {
+ this.controllerContext = controllerContext;
this.type = RestUtil.resolveBaseTypeFrom(typeDefinition);
if (this.type instanceof IdentityrefTypeDefinition) {
- this.identityrefCodec = new IdentityrefCodecImpl(mountPoint);
+ this.identityrefCodec = new IdentityrefCodecImpl(mountPoint, controllerContext);
} else {
this.identityrefCodec = null;
}
if (this.type instanceof InstanceIdentifierTypeDefinition) {
- this.instanceIdentifier = new InstanceIdentifierCodecImpl(mountPoint);
+ this.instanceIdentifier = new InstanceIdentifierCodecImpl(mountPoint, controllerContext);
} else {
this.instanceIdentifier = null;
}
return this.instanceIdentifier.deserialize(input);
} else {
final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
- ControllerContext.getInstance().getGlobalSchema());
+ controllerContext.getGlobalSchema());
return codec.deserialize((String) input);
}
} else {
private static final Logger LOG = LoggerFactory.getLogger(IdentityrefCodecImpl.class);
private final DOMMountPoint mountPoint;
+ private final ControllerContext controllerContext;
- public IdentityrefCodecImpl(final DOMMountPoint mountPoint) {
+ public IdentityrefCodecImpl(final DOMMountPoint mountPoint, ControllerContext controllerContext) {
this.mountPoint = mountPoint;
+ this.controllerContext = controllerContext;
}
@Override
@Override
public QName deserialize(final IdentityValuesDTO data) {
final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
- final Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint);
+ final Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint,
+ controllerContext);
if (module == null) {
LOG.info("Module was not found for namespace {}", valueWithNamespace.getNamespace());
LOG.info("Idenetityref will be translated as NULL for data - {}", String.valueOf(valueWithNamespace));
public static class InstanceIdentifierCodecImpl implements InstanceIdentifierCodec<IdentityValuesDTO> {
private static final Logger LOG = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class);
+
private final DOMMountPoint mountPoint;
+ private final ControllerContext controllerContext;
- public InstanceIdentifierCodecImpl(final DOMMountPoint mountPoint) {
+ public InstanceIdentifierCodecImpl(final DOMMountPoint mountPoint,
+ final ControllerContext controllerContext) {
this.mountPoint = mountPoint;
+ this.controllerContext = controllerContext;
}
@Override
public YangInstanceIdentifier deserialize(final IdentityValuesDTO data) {
final List<PathArgument> result = new ArrayList<>();
final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
- final Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint);
+ final Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint,
+ controllerContext);
if (module == null) {
LOG.info("Module by namespace '{}' of first node in instance-identifier was not found.",
valueWithNamespace.getNamespace());
final List<IdentityValue> identities = data.getValuesWithNamespaces();
for (int i = 0; i < identities.size(); i++) {
final IdentityValue identityValue = identities.get(i);
- URI validNamespace = resolveValidNamespace(identityValue.getNamespace(), this.mountPoint);
+ URI validNamespace = resolveValidNamespace(identityValue.getNamespace(), this.mountPoint,
+ controllerContext);
final DataSchemaNode node = ControllerContext.findInstanceDataChildByNameAndNamespace(
parentContainer, identityValue.getValue(), validNamespace);
if (node == null) {
final DataNodeContainer listNode = (DataNodeContainer) node;
final Map<QName, Object> predicatesMap = new HashMap<>();
for (final Predicate predicate : identityValue.getPredicates()) {
- validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), this.mountPoint);
+ validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), this.mountPoint,
+ controllerContext);
final DataSchemaNode listKey = ControllerContext
.findInstanceDataChildByNameAndNamespace(listNode, predicate.getName().getValue(),
validNamespace);
}
}
- private static Module getModuleByNamespace(final String namespace, final DOMMountPoint mountPoint) {
- final URI validNamespace = resolveValidNamespace(namespace, mountPoint);
+ private static Module getModuleByNamespace(final String namespace, final DOMMountPoint mountPoint,
+ final ControllerContext controllerContext) {
+ final URI validNamespace = resolveValidNamespace(namespace, mountPoint, controllerContext);
Module module = null;
if (mountPoint != null) {
- module = ControllerContext.getInstance().findModuleByNamespace(mountPoint, validNamespace);
+ module = controllerContext.findModuleByNamespace(mountPoint, validNamespace);
} else {
- module = ControllerContext.getInstance().findModuleByNamespace(validNamespace);
+ module = controllerContext.findModuleByNamespace(validNamespace);
}
if (module == null) {
LOG.info("Module for namespace " + validNamespace + " wasn't found.");
return module;
}
- private static URI resolveValidNamespace(final String namespace, final DOMMountPoint mountPoint) {
+ private static URI resolveValidNamespace(final String namespace, final DOMMountPoint mountPoint,
+ final ControllerContext controllerContext) {
URI validNamespace;
if (mountPoint != null) {
- validNamespace = ControllerContext.getInstance().findNamespaceByModuleName(mountPoint, namespace);
+ validNamespace = controllerContext.findNamespaceByModuleName(mountPoint, namespace);
} else {
- validNamespace = ControllerContext.getInstance().findNamespaceByModuleName(namespace);
+ validNamespace = controllerContext.findNamespaceByModuleName(namespace);
}
if (validNamespace == null) {
validNamespace = URI.create(namespace);
.withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
if (!Notificator.existListenerFor(streamName)) {
- Notificator.createListener(pathIdentifier, streamName, outputType);
+ Notificator.createListener(pathIdentifier, streamName, outputType, controllerContext);
}
final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
* @return {@link InstanceIdentifierContext} of location leaf for
* notification
*/
- private static InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
+ private InstanceIdentifierContext<?> prepareIIDSubsStreamOutput() {
final QName qnameBase = QName.create("subscribe:to:notification", "2016-10-28", "notifi");
- final SchemaContext schemaCtx = ControllerContext.getInstance().getGlobalSchema();
+ final SchemaContext schemaCtx = controllerContext.getGlobalSchema();
final DataSchemaNode location = ((ContainerSchemaNode) schemaCtx
.findModule(qnameBase.getModule()).orElse(null)
.getDataChildByName(qnameBase)).getDataChildByName(QName.create(qnameBase, "location"));
* contains list of qnames of notifications
* @return - checked future object
*/
- private static CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
+ private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
final NormalizedNodeContext payload) {
final ContainerNode data = (ContainerNode) payload.getData();
LeafSetNode leafSet = null;
final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
while (iterator.hasNext()) {
final QName valueQName = QName.create((String) iterator.next().getValue());
- final Module module =
- ControllerContext.getInstance().findModuleByNamespace(valueQName.getModule().getNamespace());
+ final Module module = controllerContext.findModuleByNamespace(valueQName.getModule().getNamespace());
Preconditions.checkNotNull(module,
"Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
NotificationDefinition notifiDef = null;
.withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
if (!Notificator.existNotificationListenerFor(streamName)) {
- Notificator.createNotificationListener(paths, streamName, outputType);
+ Notificator.createNotificationListener(paths, streamName, outputType, controllerContext);
}
final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
import java.math.BigInteger;
import org.opendaylight.controller.md.sal.common.util.jmx.AbstractMXBean;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
-import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
-import org.opendaylight.controller.sal.core.api.model.SchemaService;
-import org.opendaylight.mdsal.dom.api.DOMSchemaService;
-import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
import org.opendaylight.netconf.sal.rest.api.RestConnector;
import org.opendaylight.netconf.sal.restconf.impl.jmx.Config;
import org.opendaylight.netconf.sal.restconf.impl.jmx.Delete;
import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
public class RestconfProviderImpl extends AbstractMXBean
implements AutoCloseable, RestConnector, RestConnectorRuntimeMXBean {
private final DOMDataBroker domDataBroker;
- private final SchemaService schemaService;
private final DOMRpcService rpcService;
private final DOMNotificationService notificationService;
- private final DOMMountPointService mountPointService;
private final IpAddress websocketAddress;
private final PortNumber websocketPort;
private final StatisticsRestconfServiceWrapper stats = StatisticsRestconfServiceWrapper.getInstance();
- private final DOMSchemaService domSchemaService;
- private ListenerRegistration<SchemaContextListener> listenerRegistration;
+ private final ControllerContext controllerContext;
private Thread webSocketServerThread;
- public RestconfProviderImpl(DOMDataBroker domDataBroker, SchemaService schemaService, DOMRpcService rpcService,
- DOMNotificationService notificationService, DOMMountPointService mountPointService,
- DOMSchemaService domSchemaService, IpAddress websocketAddress, PortNumber websocketPort) {
+ public RestconfProviderImpl(DOMDataBroker domDataBroker, DOMRpcService rpcService,
+ DOMNotificationService notificationService, ControllerContext controllerContext,
+ IpAddress websocketAddress, PortNumber websocketPort) {
super("Draft02ProviderStatistics", "restconf-connector", null);
this.domDataBroker = Preconditions.checkNotNull(domDataBroker);
- this.schemaService = Preconditions.checkNotNull(schemaService);
this.rpcService = Preconditions.checkNotNull(rpcService);
this.notificationService = Preconditions.checkNotNull(notificationService);
- this.mountPointService = Preconditions.checkNotNull(mountPointService);
this.websocketAddress = Preconditions.checkNotNull(websocketAddress);
this.websocketPort = Preconditions.checkNotNull(websocketPort);
- this.domSchemaService = Preconditions.checkNotNull(domSchemaService);
+ this.controllerContext = Preconditions.checkNotNull(controllerContext);
}
public void start() {
- this.listenerRegistration = schemaService.registerSchemaContextListener(ControllerContext.getInstance());
-
BrokerFacade.getInstance().setDomDataBroker(domDataBroker);
BrokerFacade.getInstance().setRpcService(rpcService);
BrokerFacade.getInstance().setDomNotificationService(notificationService);
-
- ControllerContext.getInstance().setSchemas(schemaService.getGlobalContext());
- ControllerContext.getInstance().setMountService(mountPointService);
- final DOMYangTextSourceProvider domSchemaServiceExtension =
- (DOMYangTextSourceProvider) domSchemaService.getSupportedExtensions()
- .get(DOMYangTextSourceProvider.class);
- ControllerContext.getInstance().setYangTextSourceProvider(domSchemaServiceExtension);
+ BrokerFacade.getInstance().setControllerContext(controllerContext);
this.webSocketServerThread = new Thread(WebSocketServer.createInstance(
new String(websocketAddress.getValue()), websocketPort.getValue()));
public void close() {
BrokerFacade.getInstance().setDomDataBroker(null);
- if (this.listenerRegistration != null) {
- this.listenerRegistration.close();
- }
-
WebSocketServer.destroyInstance();
if (this.webSocketServerThread != null) {
this.webSocketServerThread.interrupt();
private static final Logger LOG = LoggerFactory.getLogger(ListenerAdapter.class);
+ private final ControllerContext controllerContext;
private final YangInstanceIdentifier path;
private final String streamName;
private final NotificationOutputType outputType;
* Type of output on notification (JSON, XML)
*/
ListenerAdapter(final YangInstanceIdentifier path, final String streamName,
- final NotificationOutputType outputType) {
+ final NotificationOutputType outputType, final ControllerContext controllerContext) {
register(this);
this.outputType = Preconditions.checkNotNull(outputType);
this.path = Preconditions.checkNotNull(path);
Preconditions.checkArgument(streamName != null && !streamName.isEmpty());
this.streamName = streamName;
+ this.controllerContext = controllerContext;
}
@Override
* @return Data in printable form.
*/
private String prepareXml() {
- final SchemaContext schemaContext = ControllerContext.getInstance().getGlobalSchema();
+ final SchemaContext schemaContext = controllerContext.getGlobalSchema();
final DataSchemaContextTree dataContextTree = DataSchemaContextTree.from(schemaContext);
final Document doc = createDocument();
final Element notificationElement = basePartDoc(doc);
YangInstanceIdentifier yiid = YangInstanceIdentifier.builder(parentYiid)
.append(normalizedNode.getIdentifier()).build();
- boolean isNodeMixin = ControllerContext.getInstance().isNodeMixin(yiid);
+ boolean isNodeMixin = controllerContext.isNodeMixin(yiid);
boolean isSkippedNonLeaf = getLeafNodesOnly() && !(normalizedNode instanceof LeafNode);
if (!isNodeMixin && !isSkippedNonLeaf) {
Node node = null;
*
* @param doc
* {@link Document}
- * @param path
+ * @param dataPath
* Path to data in data store.
* @param operation
* {@link Operation}
* @return {@link Node} node represented by changed event element.
*/
- private static Node createDataChangeEventElement(final Document doc, final YangInstanceIdentifier path,
+ private Node createDataChangeEventElement(final Document doc, final YangInstanceIdentifier dataPath,
final Operation operation) {
final Element dataChangeEventElement = doc.createElement("data-change-event");
final Element pathElement = doc.createElement("path");
- addPathAsValueToElement(path, pathElement);
+ addPathAsValueToElement(dataPath, pathElement);
dataChangeEventElement.appendChild(pathElement);
final Element operationElement = doc.createElement("operation");
/**
* Adds path as value to element.
*
- * @param path
+ * @param dataPath
* Path to data in data store.
* @param element
* {@link Element}
*/
@SuppressWarnings("rawtypes")
- private static void addPathAsValueToElement(final YangInstanceIdentifier path, final Element element) {
- final YangInstanceIdentifier normalizedPath = ControllerContext.getInstance().toXpathRepresentation(path);
+ private void addPathAsValueToElement(final YangInstanceIdentifier dataPath, final Element element) {
+ final YangInstanceIdentifier normalizedPath = controllerContext.toXpathRepresentation(dataPath);
final StringBuilder textContent = new StringBuilder();
for (final PathArgument pathArgument : normalizedPath.getPathArguments()) {
* @param qualifiedName
* QName
*/
- private static void writeIdentifierWithNamespacePrefix(final Element element, final StringBuilder textContent,
+ private void writeIdentifierWithNamespacePrefix(final Element element, final StringBuilder textContent,
final QName qualifiedName) {
- final Module module = ControllerContext.getInstance().getGlobalSchema().findModule(qualifiedName.getModule())
+ final Module module = controllerContext.getGlobalSchema().findModule(qualifiedName.getModule())
.get();
textContent.append(module.getName());
private static final Logger LOG = LoggerFactory.getLogger(NotificationListenerAdapter.class);
+ private final ControllerContext controllerContext;
private final String streamName;
private final SchemaPath path;
private final String outputType;
* @param outputType
* type of output on notification (JSON, XML)
*/
- NotificationListenerAdapter(final SchemaPath path, final String streamName, final String outputType) {
+ NotificationListenerAdapter(final SchemaPath path, final String streamName, final String outputType,
+ final ControllerContext controllerContext) {
register(this);
this.outputType = Preconditions.checkNotNull(outputType);
this.path = Preconditions.checkNotNull(path);
Preconditions.checkArgument(streamName != null && !streamName.isEmpty());
this.streamName = streamName;
+ this.controllerContext = controllerContext;
}
/**
@Override
@SuppressWarnings("checkstyle:hiddenField")
public void onNotification(final DOMNotification notification) {
- this.schemaContext = ControllerContext.getInstance().getGlobalSchema();
+ this.schemaContext = controllerContext.getGlobalSchema();
this.notification = notification;
final String xml = prepareXml();
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
+import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
* {@link YangInstanceIdentifier} path and stream name.
*/
public static ListenerAdapter createListener(final YangInstanceIdentifier path, final String streamName,
- final NotificationOutputType outputType) {
- final ListenerAdapter listener = new ListenerAdapter(path, streamName, outputType);
+ final NotificationOutputType outputType, final ControllerContext controllerContext) {
+ final ListenerAdapter listener = new ListenerAdapter(path, streamName, outputType, controllerContext);
try {
LOCK.lock();
dataChangeListener.put(streamName, listener);
* @return List of {@link NotificationListenerAdapter} by paths
*/
public static List<NotificationListenerAdapter> createNotificationListener(final List<SchemaPath> paths,
- final String streamName, final String outputType) {
+ final String streamName, final String outputType, final ControllerContext controllerContext) {
final List<NotificationListenerAdapter> listListeners = new ArrayList<>();
for (final SchemaPath path : paths) {
- final NotificationListenerAdapter listener = new NotificationListenerAdapter(path, streamName, outputType);
+ final NotificationListenerAdapter listener =
+ new NotificationListenerAdapter(path, streamName, outputType, controllerContext);
listListeners.add(listener);
}
try {
<argument value="${websocket-address}"/>
</bean>
+ <bean id="controllerContext" class="org.opendaylight.netconf.sal.restconf.impl.ControllerContext"
+ factory-method="newInstance" destroy-method="close">
+ <argument ref="schemaService"/>
+ <argument ref="domMountPointService"/>
+ <argument ref="domSchemaService"/>
+ </bean>
+
<bean id="restconfProviderDraft02" class="org.opendaylight.netconf.sal.restconf.impl.RestconfProviderImpl"
init-method="start" destroy-method="close">
<argument ref="domDataBroker"/>
- <argument ref="schemaService"/>
<argument ref="domRpcService"/>
<argument ref="domNotificationService"/>
- <argument ref="domMountPointService"/>
- <argument ref="domSchemaService"/>
+ <argument ref="controllerContext"/>
<argument ref="webSocketAddress"/>
<argument ref="webSocketPort"/>
</bean>
<!-- JSONRestconfService -->
<bean id="jsonRestconfServiceDraft02"
class="org.opendaylight.netconf.sal.restconf.impl.JSONRestconfServiceImpl"
- destroy-method="close"/>
+ destroy-method="close">
+ <argument ref="controllerContext"/>
+ </bean>
<service ref="jsonRestconfServiceDraft02" odl:type="default"
interface="org.opendaylight.netconf.sal.restconf.api.JSONRestconfService" />
package org.opendaylight.controller.md.sal.rest.common;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+
+import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import java.io.File;
import java.io.FileNotFoundException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.dom.DOMSource;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
+import org.opendaylight.controller.sal.core.api.model.SchemaService;
import org.opendaylight.controller.sal.rest.impl.test.providers.TestJsonBodyWriter;
+import org.opendaylight.mdsal.dom.api.DOMSchemaService;
import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
import org.opendaylight.restconf.common.context.NormalizedNodeContext;
import org.opendaylight.yangtools.util.xml.UntrustedXML;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
throw new UnsupportedOperationException("Test utility class");
}
+ public static ControllerContext newControllerContext(SchemaContext schemaContext) {
+ return newControllerContext(schemaContext, null);
+ }
+
+ public static ControllerContext newControllerContext(SchemaContext schemaContext, DOMMountPoint mountInstance) {
+ if (mountInstance != null) {
+ doReturn(schemaContext).when(mountInstance).getSchemaContext();
+ }
+
+ final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
+ doReturn(Optional.fromNullable(mountInstance)).when(mockMountService)
+ .getMountPoint(any(YangInstanceIdentifier.class));
+
+ SchemaService mockSchemaService = mock(SchemaService.class);
+ doReturn(schemaContext).when(mockSchemaService).getGlobalContext();
+
+ DOMSchemaService mockDomSchemaService = mock(DOMSchemaService.class);
+
+ return ControllerContext.newInstance(mockSchemaService, mockMountService, mockDomSchemaService);
+ }
+
@SuppressWarnings("checkstyle:IllegalCatch")
public static SchemaContext loadSchemaContext(final String yangPath, final SchemaContext schemaContext) {
try {
@SuppressWarnings("checkstyle:IllegalCatch")
public static NormalizedNodeContext loadNormalizedContextFromXmlFile(final String pathToInputFile,
- final String uri) {
- final InstanceIdentifierContext<?> iiContext = ControllerContext.getInstance().toInstanceIdentifier(uri);
+ final String uri, final ControllerContext controllerContext) {
+ final InstanceIdentifierContext<?> iiContext = controllerContext.toInstanceIdentifier(uri);
final InputStream inputStream = TestJsonBodyWriter.class.getResourceAsStream(pathToInputFile);
try {
final Document doc = UntrustedXML.newDocumentBuilder().parse(inputStream);
public void stringToInstanceIdentifierTest() throws Exception {
final SchemaContext schemaContext =
YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/instanceidentifier"));
- ControllerContext.getInstance().setGlobalSchema(schemaContext);
+ ControllerContext controllerContext = TestRestconfUtils.newControllerContext(schemaContext);
final InstanceIdentifierContext<?> instanceIdentifier =
- ControllerContext.getInstance().toInstanceIdentifier(
+ controllerContext.toInstanceIdentifier(
"/iid-value-module:cont-iid/iid-list/%2Fiid-value-module%3Acont-iid%2Fiid-value-module%3A"
+ "values-iid%5Biid-value-module:value-iid='value'%5D");
final YangInstanceIdentifier yiD = instanceIdentifier.getInstanceIdentifier();
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.rest.api.RestconfConstants;
import org.opendaylight.netconf.sal.rest.impl.AbstractIdentifierAwareJaxRsProvider;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
public abstract class AbstractBodyReaderTest {
-
- protected static final ControllerContext CONTROLLER_CONTEXT = ControllerContext.getInstance();
- protected final MediaType mediaType;
private static Field uriField;
private static Field requestField;
- public AbstractBodyReaderTest() throws NoSuchFieldException {
- uriField = AbstractIdentifierAwareJaxRsProvider.class
- .getDeclaredField("uriInfo");
- uriField.setAccessible(true);
- requestField = AbstractIdentifierAwareJaxRsProvider.class
- .getDeclaredField("request");
- requestField.setAccessible(true);
+ static {
+ try {
+ uriField = AbstractIdentifierAwareJaxRsProvider.class
+ .getDeclaredField("uriInfo");
+ uriField.setAccessible(true);
+ requestField = AbstractIdentifierAwareJaxRsProvider.class
+ .getDeclaredField("request");
+ requestField.setAccessible(true);
+ } catch (NoSuchFieldException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ protected final ControllerContext controllerContext;
+ protected final MediaType mediaType;
+
+ protected AbstractBodyReaderTest(SchemaContext schemaContext, DOMMountPoint mountInstance) {
this.mediaType = getMediaType();
+
+ controllerContext = TestRestconfUtils.newControllerContext(schemaContext, mountInstance);
}
protected abstract MediaType getMediaType();
private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = QNameModule.create(
URI.create("instance:identifier:module"), Revision.of("2014-01-17"));
- public TestJsonBodyReader() throws NoSuchFieldException, SecurityException {
- this.jsonBodyReader = new JsonNormalizedNodeBodyReader();
+ public TestJsonBodyReader() {
+ super(schemaContext, null);
+ this.jsonBodyReader = new JsonNormalizedNodeBodyReader(controllerContext);
}
@Override
final Collection<File> testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang");
testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc"));
schemaContext = YangParserTestUtils.parseYangFiles(testFiles);
- CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-import com.google.common.base.Optional;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
import org.junit.BeforeClass;
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.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.rest.impl.JsonNormalizedNodeBodyReader;
-import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.restconf.common.context.NormalizedNodeContext;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = QNameModule.create(
URI.create("instance:identifier:module"), Revision.of("2014-01-17"));
- public TestJsonBodyReaderMountPoint() throws NoSuchFieldException,
- SecurityException {
- this.jsonBodyReader = new JsonNormalizedNodeBodyReader();
+ public TestJsonBodyReaderMountPoint() throws NoSuchFieldException, SecurityException {
+ super(schemaContext, mock(DOMMountPoint.class));
+ this.jsonBodyReader = new JsonNormalizedNodeBodyReader(controllerContext);
}
@Override
final Collection<File> testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang");
testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc"));
schemaContext = YangParserTestUtils.parseYangFiles(testFiles);
-
- final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
- when(mountInstance.getSchemaContext()).thenReturn(schemaContext);
- final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
- when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class)))
- .thenReturn(Optional.of(mountInstance));
-
- ControllerContext.getInstance().setMountService(mockMountService);
- CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
private final NormalizedNodeJsonBodyWriter jsonBodyWriter;
private static SchemaContext schemaContext;
- public TestJsonBodyWriter() throws NoSuchFieldException, SecurityException {
+ public TestJsonBodyWriter() {
+ super(schemaContext, null);
this.jsonBodyWriter = new NormalizedNodeJsonBodyWriter();
- this.jsonBodyReader = new JsonNormalizedNodeBodyReader();
+ this.jsonBodyReader = new JsonNormalizedNodeBodyReader(controllerContext);
}
@Override
final Collection<File> testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang");
testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc"));
schemaContext = YangParserTestUtils.parseYangFiles(testFiles);
- CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
private final JsonToPatchBodyReader jsonToPatchBodyReader;
private static SchemaContext schemaContext;
- public TestJsonPatchBodyReader() throws NoSuchFieldException, SecurityException {
- jsonToPatchBodyReader = new JsonToPatchBodyReader();
+ public TestJsonPatchBodyReader() {
+ super(schemaContext, null);
+ jsonToPatchBodyReader = new JsonToPatchBodyReader(controllerContext);
}
@Override
@BeforeClass
public static void initialization() {
schemaContext = schemaContextLoader("/instanceidentifier/yang", schemaContext);
- CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
-import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-import com.google.common.base.Optional;
import java.io.InputStream;
import javax.ws.rs.core.MediaType;
import org.junit.BeforeClass;
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.restconf.common.errors.RestconfDocumentedException;
import org.opendaylight.restconf.common.patch.PatchContext;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
public class TestJsonPatchBodyReaderMountPoint extends AbstractBodyReaderTest {
private static SchemaContext schemaContext;
private static final String MOUNT_POINT = "instance-identifier-module:cont/yang-ext:mount";
- public TestJsonPatchBodyReaderMountPoint() throws NoSuchFieldException, SecurityException {
- jsonToPatchBodyReader = new JsonToPatchBodyReader();
+ public TestJsonPatchBodyReaderMountPoint() {
+ super(schemaContext, mock(DOMMountPoint.class));
+ jsonToPatchBodyReader = new JsonToPatchBodyReader(controllerContext);
}
@Override
@BeforeClass
public static void initialization() {
schemaContext = schemaContextLoader("/instanceidentifier/yang", schemaContext);
-
- final DOMMountPoint mockMountPoint = mock(DOMMountPoint.class);
- when(mockMountPoint.getSchemaContext()).thenReturn(schemaContext);
- final DOMMountPointService mockMountPointService = mock(DOMMountPointService.class);
- when(mockMountPointService.getMountPoint(any(YangInstanceIdentifier.class)))
- .thenReturn(Optional.of(mockMountPoint));
-
- CONTROLLER_CONTEXT.setMountService(mockMountPointService);
- CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = QNameModule.create(
URI.create("instance:identifier:module"), Revision.of("2014-01-17"));
- public TestXmlBodyReader() throws Exception {
- this.xmlBodyReader = new XmlNormalizedNodeBodyReader();
+ public TestXmlBodyReader() {
+ super(schemaContext, null);
+ this.xmlBodyReader = new XmlNormalizedNodeBodyReader(controllerContext);
}
@Override
testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc"));
testFiles.addAll(TestRestconfUtils.loadFiles("/foo-xml-test/yang"));
schemaContext = YangParserTestUtils.parseYangFiles(testFiles);
- CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-import com.google.common.base.Optional;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
import org.junit.BeforeClass;
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.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.rest.impl.XmlNormalizedNodeBodyReader;
-import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.restconf.common.context.NormalizedNodeContext;
import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
import org.opendaylight.restconf.common.errors.RestconfError;
private static final QNameModule INSTANCE_IDENTIFIER_MODULE_QNAME = QNameModule.create(
URI.create("instance:identifier:module"), Revision.of("2014-01-17"));
- public TestXmlBodyReaderMountPoint() throws Exception {
- this.xmlBodyReader = new XmlNormalizedNodeBodyReader();
+ public TestXmlBodyReaderMountPoint() {
+ super(schemaContext, mock(DOMMountPoint.class));
+ this.xmlBodyReader = new XmlNormalizedNodeBodyReader(controllerContext);
}
@Override
final Collection<File> testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang");
testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc"));
schemaContext = YangParserTestUtils.parseYangFiles(testFiles);
-
- final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
- when(mountInstance.getSchemaContext()).thenReturn(schemaContext);
- final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
- when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class)))
- .thenReturn(Optional.of(mountInstance));
-
- ControllerContext.getInstance().setMountService(mockMountService);
- CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
private final NormalizedNodeXmlBodyWriter xmlBodyWriter;
private static SchemaContext schemaContext;
- public TestXmlBodyWriter() throws NoSuchFieldException, SecurityException {
+ public TestXmlBodyWriter() {
+ super(schemaContext, null);
this.xmlBodyWriter = new NormalizedNodeXmlBodyWriter();
}
final Collection<File> testFiles = TestRestconfUtils.loadFiles("/instanceidentifier/yang");
testFiles.addAll(TestRestconfUtils.loadFiles("/invoke-rpc"));
schemaContext = YangParserTestUtils.parseYangFiles(testFiles);
- CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
final String uri = "invoke-rpc-module:rpc-test";
final String pathToInputFile = "/invoke-rpc/xml/rpc-output.xml";
final NormalizedNodeContext nnContext = TestRestconfUtils
- .loadNormalizedContextFromXmlFile(pathToInputFile, uri);
+ .loadNormalizedContextFromXmlFile(pathToInputFile, uri, controllerContext);
final OutputStream output = new ByteArrayOutputStream();
this.xmlBodyWriter.writeTo(nnContext, null, null, null, this.mediaType, null,
output);
private final XmlToPatchBodyReader xmlToPatchBodyReader;
private static SchemaContext schemaContext;
- public TestXmlPatchBodyReader() throws NoSuchFieldException, SecurityException {
- xmlToPatchBodyReader = new XmlToPatchBodyReader();
+ public TestXmlPatchBodyReader() {
+ super(schemaContext, null);
+ xmlToPatchBodyReader = new XmlToPatchBodyReader(controllerContext);
}
@Override
@BeforeClass
public static void initialization() throws NoSuchFieldException, SecurityException {
schemaContext = schemaContextLoader("/instanceidentifier/yang", schemaContext);
- CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
-import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-import com.google.common.base.Optional;
import java.io.InputStream;
import javax.ws.rs.core.MediaType;
import org.junit.BeforeClass;
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.restconf.common.errors.RestconfDocumentedException;
import org.opendaylight.restconf.common.patch.PatchContext;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
public class TestXmlPatchBodyReaderMountPoint extends AbstractBodyReaderTest {
private static SchemaContext schemaContext;
private static final String MOUNT_POINT = "instance-identifier-module:cont/yang-ext:mount";
- public TestXmlPatchBodyReaderMountPoint() throws NoSuchFieldException, SecurityException {
- xmlToPatchBodyReader = new XmlToPatchBodyReader();
+ public TestXmlPatchBodyReaderMountPoint() {
+ super(schemaContext, mock(DOMMountPoint.class));
+ xmlToPatchBodyReader = new XmlToPatchBodyReader(controllerContext);
}
@Override
@BeforeClass
public static void initialization() throws NoSuchFieldException, SecurityException {
schemaContext = schemaContextLoader("/instanceidentifier/yang", schemaContext);
-
- final DOMMountPoint mockMountPoint = mock(DOMMountPoint.class);
- when(mockMountPoint.getSchemaContext()).thenReturn(schemaContext);
- final DOMMountPointService mockMountPointService = mock(DOMMountPointService.class);
- when(mockMountPointService.getMountPoint(any(YangInstanceIdentifier.class)))
- .thenReturn(Optional.of(mockMountPoint));
-
- CONTROLLER_CONTEXT.setMountService(mockMountPointService);
- CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
import com.google.common.collect.Iterables;
import com.google.common.util.concurrent.CheckedFuture;
import java.io.FileNotFoundException;
-import java.net.URI;
import java.util.List;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import org.junit.Before;
+import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
+import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
public class RestPutListDataTest {
+ private static SchemaContext schemaContextTestModule;
private static BrokerFacade brokerFacade;
private static RestconfImpl restconfImpl;
- private static SchemaContext schemaContextTestModule;
private static final String TEST_MODULE_NS_STRING = "test:module";
- private static final URI TEST_MODULE_NS;
private static final String TEST_MODULE_REVISION = "2014-01-09";
- static {
- TEST_MODULE_NS = URI.create("test:module");
+ @BeforeClass
+ public static void staticSetup() throws FileNotFoundException {
+ schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
}
@Before
public void initialize() throws FileNotFoundException {
- final ControllerContext controllerContext = ControllerContext.getInstance();
- schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
- controllerContext.setSchemas(schemaContextTestModule);
+ final ControllerContext controllerContext = TestRestconfUtils.newControllerContext(schemaContextTestModule);
brokerFacade = mock(BrokerFacade.class);
restconfImpl = RestconfImpl.getInstance();
restconfImpl.setBroker(brokerFacade);
private final JsonNormalizedNodeBodyReader jsonBodyReader;
private static SchemaContext schemaContext;
- public JsonIdentityrefToNnTest() throws NoSuchFieldException,
- SecurityException {
- this.jsonBodyReader = new JsonNormalizedNodeBodyReader();
+ public JsonIdentityrefToNnTest() {
+ super(schemaContext, null);
+ this.jsonBodyReader = new JsonNormalizedNodeBodyReader(controllerContext);
}
@BeforeClass
public static void initialize() {
- schemaContext = schemaContextLoader("/json-to-nn/identityref",
- schemaContext);
- CONTROLLER_CONTEXT.setSchemas(schemaContext);
+ schemaContext = schemaContextLoader("/json-to-nn/identityref", schemaContext);
}
@Test
private final JsonNormalizedNodeBodyReader jsonBodyReader;
private static SchemaContext schemaContext;
- public JsonLeafrefToNnTest() throws NoSuchFieldException, SecurityException {
- this.jsonBodyReader = new JsonNormalizedNodeBodyReader();
+ public JsonLeafrefToNnTest() {
+ super(schemaContext, null);
+ this.jsonBodyReader = new JsonNormalizedNodeBodyReader(controllerContext);
}
@BeforeClass
public static void initialize() {
- schemaContext = schemaContextLoader("/json-to-nn/leafref",
- schemaContext);
- CONTROLLER_CONTEXT.setSchemas(schemaContext);
+ schemaContext = schemaContextLoader("/json-to-nn/leafref", schemaContext);
}
@Test
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import java.io.File;
+import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
+import java.util.Collection;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
+import org.junit.BeforeClass;
import org.junit.Test;
+import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.controller.sal.rest.impl.test.providers.AbstractBodyReaderTest;
import org.opendaylight.netconf.sal.rest.impl.JsonNormalizedNodeBodyReader;
import org.opendaylight.restconf.common.context.NormalizedNodeContext;
import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger LOG = LoggerFactory.getLogger(AbstractBodyReaderTest.class);
- private JsonNormalizedNodeBodyReader jsonBodyReader;
- private SchemaContext schemaContext;
+ private final JsonNormalizedNodeBodyReader jsonBodyReader;
+ private static SchemaContext schemaContext;
- public JsonToNnTest() throws NoSuchFieldException, SecurityException {
+ public JsonToNnTest() {
+ super(schemaContext, null);
+ this.jsonBodyReader = new JsonNormalizedNodeBodyReader(controllerContext);
}
- public static void initialize(final String path, SchemaContext schemaContext) {
- schemaContext = schemaContextLoader(path, schemaContext);
- CONTROLLER_CONTEXT.setSchemas(schemaContext);
+ @BeforeClass
+ public static void initialize() throws FileNotFoundException {
+ final Collection<File> testFiles = TestRestconfUtils.loadFiles("/json-to-nn/simple-list-yang/1");
+ testFiles.addAll(TestRestconfUtils.loadFiles("/json-to-nn/simple-list-yang/3"));
+ testFiles.addAll(TestRestconfUtils.loadFiles("/json-to-nn/simple-list-yang/4"));
+ testFiles.addAll(TestRestconfUtils.loadFiles("/json-to-nn/simple-container-yang"));
+ testFiles.addAll(TestRestconfUtils.loadFiles("/common/augment/yang"));
+ schemaContext = YangParserTestUtils.parseYangFiles(testFiles);
}
@Test
public void simpleListTest() throws Exception {
simpleTest("/json-to-nn/simple-list.json",
- "/json-to-nn/simple-list-yang/1", "lst", "simple-list-yang1");
+ "lst", "simple-list-yang1");
}
@Test
public void simpleContainerTest() throws Exception {
simpleTest("/json-to-nn/simple-container.json",
- "/json-to-nn/simple-container-yang", "cont",
- "simple-container-yang");
+ "cont", "simple-container-yang");
}
@Test
public void multipleItemsInLeafListTest() throws Exception {
-
- initialize("/json-to-nn/simple-list-yang/1", this.schemaContext);
-
final NormalizedNodeContext normalizedNodeContext = prepareNNC(
"/json-to-nn/multiple-leaflist-items.json",
"simple-list-yang1:lst");
@Test
public void multipleItemsInListTest() throws Exception {
- initialize("/json-to-nn/simple-list-yang/3", this.schemaContext);
-
final NormalizedNodeContext normalizedNodeContext = prepareNNC(
"/json-to-nn/multiple-items-in-list.json",
"multiple-items-yang:lst");
@Test
public void nullArrayToSimpleNodeWithNullValueTest() throws Exception {
- initialize("/json-to-nn/simple-list-yang/4", this.schemaContext);
-
final NormalizedNodeContext normalizedNodeContext = prepareNNC(
"/json-to-nn/array-with-null.json", "array-with-null-yang:cont");
assertNotNull(normalizedNodeContext);
@Test
public void incorrectTopLevelElementsTest() throws Exception {
-
- this.jsonBodyReader = new JsonNormalizedNodeBodyReader();
- initialize("/json-to-nn/simple-list-yang/1", this.schemaContext);
mockBodyReader("simple-list-yang1:lst", this.jsonBodyReader, false);
InputStream inputStream = this.getClass().getResourceAsStream(
}
assertNotNull(exception);
assertEquals(
- "Error parsing input: Schema node with name cont was not found under "
+ "Error parsing input: Schema node with name wrong was not found under "
+ "(urn:ietf:params:xml:ns:netconf:base:1.0)data.",
exception.getErrors().get(0).getErrorMessage());
@Test
public void emptyDataReadTest() throws Exception {
-
- initialize("/json-to-nn/simple-list-yang/4", this.schemaContext);
-
final NormalizedNodeContext normalizedNodeContext = prepareNNC(
"/json-to-nn/empty-data.json", "array-with-null-yang:cont");
assertNotNull(normalizedNodeContext);
assertTrue(dataTree.contains("lflst2 45"));
- this.jsonBodyReader = new JsonNormalizedNodeBodyReader();
RestconfDocumentedException exception = null;
mockBodyReader("array-with-null-yang:cont", this.jsonBodyReader, false);
final InputStream inputStream = this.getClass().getResourceAsStream(
@Test
public void testJsonBlankInput() throws Exception {
- initialize("/json-to-nn/simple-list-yang/4", this.schemaContext);
final NormalizedNodeContext normalizedNodeContext = prepareNNC("",
"array-with-null-yang:cont");
assertNull(normalizedNodeContext);
@Test
public void notSupplyNamespaceIfAlreadySupplied()throws Exception {
-
- initialize("/json-to-nn/simple-list-yang/1", this.schemaContext);
-
final String uri = "simple-list-yang1" + ":" + "lst";
final NormalizedNodeContext normalizedNodeContext = prepareNNC(
@Test
public void dataAugmentedTest() throws Exception {
-
- initialize("/common/augment/yang", this.schemaContext);
-
NormalizedNodeContext normalizedNodeContext = prepareNNC(
"/common/augment/json/dataa.json", "main:cont");
assertTrue(dataTree.contains("lf11 lf11 value from b"));
}
- private void simpleTest(final String jsonPath, final String yangPath,
- final String topLevelElementName, final String moduleName) throws Exception {
-
- initialize(yangPath, this.schemaContext);
-
+ private void simpleTest(final String jsonPath, final String topLevelElementName,
+ final String moduleName) throws Exception {
final String uri = moduleName + ":" + topLevelElementName;
final NormalizedNodeContext normalizedNodeContext = prepareNNC(jsonPath, uri);
}
private NormalizedNodeContext prepareNNC(final String jsonPath, final String uri) throws Exception {
- this.jsonBodyReader = new JsonNormalizedNodeBodyReader();
try {
mockBodyReader(uri, this.jsonBodyReader, false);
} catch (NoSuchFieldException | SecurityException
@Test
public void unsupportedDataFormatTest() throws Exception {
- this.jsonBodyReader = new JsonNormalizedNodeBodyReader();
- initialize("/json-to-nn/simple-list-yang/1", this.schemaContext);
mockBodyReader("simple-list-yang1:lst", this.jsonBodyReader, false);
final InputStream inputStream = this.getClass().getResourceAsStream(
@Test
public void invalidUriCharacterInValue() throws Exception {
-
- this.jsonBodyReader = new JsonNormalizedNodeBodyReader();
- initialize("/json-to-nn/simple-list-yang/4", this.schemaContext);
mockBodyReader("array-with-null-yang:cont", this.jsonBodyReader, false);
final InputStream inputStream = this.getClass().getResourceAsStream(
private static SchemaContext schemaContext;
private final NormalizedNodeJsonBodyWriter jsonBodyWriter;
- public NnJsonChoiceCaseTest() throws NoSuchFieldException,
- SecurityException {
+ public NnJsonChoiceCaseTest() {
+ super(schemaContext, null);
jsonBodyWriter = new NormalizedNodeJsonBodyWriter();
}
@BeforeClass
public static void initialization() {
schemaContext = schemaContextLoader("/nn-to-json/choice", schemaContext);
- CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
/**
private String getJson(final String xmlPath) throws Exception {
final String uri = "choice-case-test:cont";
final NormalizedNodeContext testNN = TestRestconfUtils
- .loadNormalizedContextFromXmlFile(xmlPath, uri);
+ .loadNormalizedContextFromXmlFile(xmlPath, uri, controllerContext);
final OutputStream output = new ByteArrayOutputStream();
jsonBodyWriter.writeTo(testNN, null, null, null, mediaType, null,
private static SchemaContext schemaContext;
private final NormalizedNodeJsonBodyWriter jsonBodyWriter;
- public NnToJsonLeafrefType() throws NoSuchFieldException, SecurityException {
+ public NnToJsonLeafrefType() {
+ super(schemaContext, null);
jsonBodyWriter = new NormalizedNodeJsonBodyWriter();
}
@BeforeClass
public static void initialization() {
- schemaContext = schemaContextLoader("/nn-to-json/leafref",
- schemaContext);
- CONTROLLER_CONTEXT.setSchemas(schemaContext);
+ schemaContext = schemaContextLoader("/nn-to-json/leafref", schemaContext);
}
@Test
final String pathToInputFile = xmlDataPath;
final NormalizedNodeContext testNN = TestRestconfUtils
- .loadNormalizedContextFromXmlFile(pathToInputFile, uri);
+ .loadNormalizedContextFromXmlFile(pathToInputFile, uri, controllerContext);
final OutputStream output = new ByteArrayOutputStream();
jsonBodyWriter.writeTo(testNN, null, null, null, mediaType, null,
private static SchemaContext schemaContext;
private final NormalizedNodeJsonBodyWriter xmlBodyWriter;
- public NnToJsonWithAugmentTest() throws NoSuchFieldException,
- SecurityException {
+ public NnToJsonWithAugmentTest() {
+ super(schemaContext, null);
xmlBodyWriter = new NormalizedNodeJsonBodyWriter();
}
@BeforeClass
public static void initialize() {
- schemaContext = schemaContextLoader("/nn-to-json/augmentation",
- schemaContext);
- CONTROLLER_CONTEXT.setSchemas(schemaContext);
+ schemaContext = schemaContextLoader("/nn-to-json/augmentation", schemaContext);
}
@Test
final String pathToInputFile = "/nn-to-json/augmentation/xml/data.xml";
final NormalizedNodeContext testNN = TestRestconfUtils
- .loadNormalizedContextFromXmlFile(pathToInputFile, uri);
+ .loadNormalizedContextFromXmlFile(pathToInputFile, uri, controllerContext);
final OutputStream output = new ByteArrayOutputStream();
xmlBodyWriter
private static SchemaContext schemaContext;
NormalizedNodeXmlBodyWriter xmlBodyWriter;
- public NnInstanceIdentifierToXmlTest() throws NoSuchFieldException,
- SecurityException {
+ public NnInstanceIdentifierToXmlTest() {
+ super(schemaContext, null);
xmlBodyWriter = new NormalizedNodeXmlBodyWriter();
}
@BeforeClass
public static void initialization() throws URISyntaxException {
- schemaContext = schemaContextLoader("/instanceidentifier/yang",
- schemaContext);
- CONTROLLER_CONTEXT.setSchemas(schemaContext);
+ schemaContext = schemaContextLoader("/instanceidentifier/yang", schemaContext);
}
@Test
private final NormalizedNodeXmlBodyWriter xmlBodyWriter;
private static SchemaContext schemaContext;
- public NnToXmlTest() throws NoSuchFieldException, SecurityException {
+ public NnToXmlTest() {
+ super(schemaContext, null);
this.xmlBodyWriter = new NormalizedNodeXmlBodyWriter();
}
@BeforeClass
public static void initialization() {
schemaContext = schemaContextLoader("/nn-to-xml/yang", schemaContext);
- CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
private final NormalizedNodeXmlBodyWriter xmlBodyWriter;
private static SchemaContext schemaContext;
- public NnToXmlWithChoiceTest() throws NoSuchFieldException,
- SecurityException {
+ public NnToXmlWithChoiceTest() {
+ super(schemaContext, null);
xmlBodyWriter = new NormalizedNodeXmlBodyWriter();
}
@BeforeClass
public static void initialization() {
schemaContext = schemaContextLoader("/nn-to-xml/choice", schemaContext);
- CONTROLLER_CONTEXT.setSchemas(schemaContext);
}
@Test
private final NormalizedNodeXmlBodyWriter xmlBodyWriter;
private static SchemaContext schemaContext;
- public NnToXmlWithDataFromSeveralModulesTest() throws NoSuchFieldException,
- SecurityException {
+ public NnToXmlWithDataFromSeveralModulesTest() {
+ super(schemaContext, null);
xmlBodyWriter = new NormalizedNodeXmlBodyWriter();
}
@BeforeClass
public static void initialize() {
- schemaContext = schemaContextLoader(
- "/nn-to-xml/data-of-several-modules/yang", schemaContext);
- CONTROLLER_CONTEXT.setSchemas(schemaContext);
+ schemaContext = schemaContextLoader("/nn-to-xml/data-of-several-modules/yang", schemaContext);
}
@Test
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
-
import java.util.HashMap;
import java.util.concurrent.Future;
import org.junit.Before;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
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.BrokerFacade;
import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.netconf.sal.restconf.impl.PutResult;
private final QName qname = TestUtils.buildQName("interfaces","test:module", "2014-01-09");
private final SchemaPath type = SchemaPath.create(true, this.qname);
private final YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(this.qname).build();
+ private ControllerContext controllerContext;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
+
+ controllerContext = TestRestconfUtils.newControllerContext(
+ TestUtils.loadSchemaContext("/full-versions/test-module", "/modules"));
+
this.brokerFacade.setDomDataBroker(this.domDataBroker);
this.brokerFacade.setDomNotificationService(this.domNotification);
this.brokerFacade.setRpcService(this.mockRpcService);
+ this.brokerFacade.setControllerContext(controllerContext);
+
when(this.domDataBroker.newReadOnlyTransaction()).thenReturn(this.readTransaction);
when(this.domDataBroker.newWriteOnlyTransaction()).thenReturn(this.writeTransaction);
when(this.domDataBroker.newReadWriteTransaction()).thenReturn(this.rwTransaction);
HashMap extensions = new HashMap();
extensions.put(DOMDataTreeChangeService.class, Mockito.mock(DOMDataTreeChangeService.class));
when(this.domDataBroker.getSupportedExtensions()).thenReturn(extensions);
-
- ControllerContext.getInstance()
- .setSchemas(TestUtils.loadSchemaContext("/full-versions/test-module", "/modules"));
}
private static CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> wrapDummyNode(
@Test
public void testRegisterToListenDataChanges() {
final ListenerAdapter listener = Notificator.createListener(this.instanceID, "stream",
- NotificationOutputType.XML);
+ NotificationOutputType.XML, controllerContext);
@SuppressWarnings("unchecked")
final ListenerRegistration<ListenerAdapter> mockRegistration = mock(ListenerRegistration.class);
final String identifier = "create-notification-stream/toaster:toastDone";
final SchemaPath path = SchemaPath.create(true,
QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
- Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML");
+ Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML", controllerContext);
final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
// mock registration
import java.io.FileNotFoundException;
import org.junit.BeforeClass;
import org.junit.Test;
+import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
import org.opendaylight.yangtools.yang.common.QName;
private static final QName CONT_QNAME = QName.create("leafref:module", "2014-04-17", "cont");
private static final QName LST_WITH_LFREF_KEY_QNAME = QName.create(CONT_QNAME, "lst-with-lfref-key");
private static final QName LFREF_KEY_QNAME = QName.create(CONT_QNAME, "lfref-key");
+ private static SchemaContext schemaContext;
-
- private static ControllerContext controllerContext = ControllerContext.getInstance();
+ private final ControllerContext controllerContext = TestRestconfUtils.newControllerContext(schemaContext);
@BeforeClass
public static void initialize() throws FileNotFoundException {
- final SchemaContext schemaContext = TestUtils.loadSchemaContext("/leafref/yang");
+ schemaContext = TestUtils.loadSchemaContext("/leafref/yang");
Module module = TestUtils.findModule(schemaContext.getModules(), "leafref-module");
assertNotNull(module);
module = TestUtils.findModule(schemaContext.getModules(), "referenced-module");
assertNotNull(module);
-
- controllerContext.setGlobalSchema(schemaContext);
}
@Test
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-import com.google.common.base.Optional;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import org.junit.BeforeClass;
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.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.netconf.sal.restconf.impl.RestconfImpl;
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 CONTROLLER_CONTEXT = ControllerContext.getInstance();
+ private static SchemaContext schemaContext;
+
+ private final ControllerContext controllerContext;
+
+ public Bug8072Test() throws FileNotFoundException {
+ final SchemaContext mountPointContext = TestUtils.loadSchemaContext("/full-versions/test-module");
+ final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
+ controllerContext = TestRestconfUtils.newControllerContext(schemaContext, mountInstance);
+ doReturn(mountPointContext).when(mountInstance).getSchemaContext();
+
+ final BrokerFacade brokerFacade = mock(BrokerFacade.class);
+ final RestconfImpl restconfImpl = RestconfImpl.getInstance();
+ restconfImpl.setBroker(brokerFacade);
+ restconfImpl.setControllerContext(controllerContext);
+ }
@BeforeClass
public static void init() throws FileNotFoundException, ReactorException {
- final SchemaContext globalContext = TestUtils.loadSchemaContext("/full-versions/yangs");
- assertEquals(0, globalContext.findModules(EXTERNAL_MODULE_NAME).size());
- final Set<Module> allModules = globalContext.getModules();
+ schemaContext = TestUtils.loadSchemaContext("/full-versions/yangs");
+ assertEquals(0, schemaContext.findModules(EXTERNAL_MODULE_NAME).size());
+ final Set<Module> allModules = schemaContext.getModules();
assertNotNull(allModules);
- CONTROLLER_CONTEXT.setSchemas(globalContext);
}
@Test
public void testIdentityRefFromExternalModule() throws FileNotFoundException, ReactorException {
- initMountService();
- final InstanceIdentifierContext<?> ctx = CONTROLLER_CONTEXT.toInstanceIdentifier(
+ final InstanceIdentifierContext<?> ctx = controllerContext.toInstanceIdentifier(
"simple-nodes:users/yang-ext:mount/test-module:modules/module/test-module:module-type/name");
final Map<QName, Object> keyValues = new HashMap<>();
assertEquals(expectedYII, ctx.getInstanceIdentifier());
}
-
- private void initMountService() throws FileNotFoundException, ReactorException {
- final DOMMountPointService mountService = mock(DOMMountPointService.class);
- CONTROLLER_CONTEXT.setMountService(mountService);
- final BrokerFacade brokerFacade = mock(BrokerFacade.class);
- final RestconfImpl restconfImpl = RestconfImpl.getInstance();
- restconfImpl.setBroker(brokerFacade);
- restconfImpl.setControllerContext(CONTROLLER_CONTEXT);
- final SchemaContext mountPointContext = TestUtils.loadSchemaContext("/full-versions/test-module");
- final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
- when(mountInstance.getSchemaContext()).thenReturn(mountPointContext);
- when(mountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
- }
}
import javax.ws.rs.core.Response;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
-import org.junit.BeforeClass;
+import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
+import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.rest.impl.JsonNormalizedNodeBodyReader;
import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeJsonBodyWriter;
import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeXmlBodyWriter;
public class CodecsExceptionsCatchingTest extends JerseyTest {
- private static RestconfImpl restConf;
- private static ControllerContext controllerContext = ControllerContext.getInstance();
+ private RestconfImpl restConf;
+ private ControllerContext controllerContext;
- @BeforeClass
- public static void init() throws FileNotFoundException, ReactorException {
+ @Before
+ public void init() throws FileNotFoundException, ReactorException {
restConf = RestconfImpl.getInstance();
- controllerContext = ControllerContext.getInstance();
final SchemaContext schemaContext = TestUtils.loadSchemaContext("/decoding-exception/yang");
- controllerContext.setGlobalSchema(schemaContext);
+ controllerContext = TestRestconfUtils.newControllerContext(schemaContext);
restConf.setControllerContext(controllerContext);
}
// 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(controllerContext),
+ new JsonNormalizedNodeBodyReader(controllerContext));
resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
return resourceConfig;
}
final String exceptionMessage = response.readEntity(String.class);
assertTrue(exceptionMessage.contains("invalid-value"));
}
-}
\ No newline at end of file
+}
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.BeforeClass;
+import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.rest.impl.JsonNormalizedNodeBodyReader;
import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeJsonBodyWriter;
import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeXmlBodyWriter;
private NormalizedNode<?, ?> globalPayload;
private static SchemaContext schemaContextModules;
+ private final ControllerContext controllerContext =
+ TestRestconfUtils.newControllerContext(schemaContextModules, null);
+
@Path("/")
public class RestImpl {
public NormalizedNodeContext getData(@Encoded @PathParam("identifier") final String identifier,
@Context final UriInfo uriInfo) {
- final InstanceIdentifierContext<?> iiWithData = ControllerContext.getInstance().toInstanceIdentifier(
- identifier);
+ final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
NormalizedNode<?, ?> data = null;
if (identifier.equals("nested-module:depth1-cont/depth2-cont1")) {
}
public void getDataWithUriDepthParameter(final String mediaType) throws WebApplicationException, IOException {
- ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
Response response;
// Test config with depth 1
final YangInstanceIdentifier path = Mockito.mock(YangInstanceIdentifier.class);
final PathArgument pathValue = NodeIdentifier.create(QName.create("module", "2016-12-14", "localName"));
Mockito.when(path.getLastPathArgument()).thenReturn(pathValue);
- final ListenerAdapter listener = Notificator.createListener(path, "streamName", NotificationOutputType.JSON);
+ final ListenerAdapter listener = Notificator.createListener(path, "streamName", NotificationOutputType.JSON,
+ null);
listener.setQueryParams(Instant.now(), Optional.empty(), Optional.ofNullable(filter), false);
// FIXME: do not use reflection here
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import com.google.common.base.Optional;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
-import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
+import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.netconf.sal.restconf.impl.RestconfImpl;
public class InvokeRpcMethodTest {
- private RestconfImpl restconfImpl = null;
- private static ControllerContext controllerContext = null;
private static UriInfo uriInfo;
+ private static SchemaContext schemaContext;
+ private final RestconfImpl restconfImpl = RestconfImpl.getInstance();
+ private final ControllerContext controllerContext;
+
+ public InvokeRpcMethodTest() {
+ controllerContext = TestRestconfUtils.newControllerContext(schemaContext);
+ restconfImpl.setControllerContext(controllerContext);
+ }
@BeforeClass
public static void init() throws FileNotFoundException, ReactorException {
- final SchemaContext schemaContext = TestUtils.loadSchemaContext("/full-versions/yangs", "/invoke-rpc");
+ schemaContext = TestUtils.loadSchemaContext("/full-versions/yangs", "/invoke-rpc");
final Set<Module> allModules = schemaContext.getModules();
assertNotNull(allModules);
final Module module = TestUtils.resolveModule("invoke-rpc-module", allModules);
assertNotNull(module);
- controllerContext = spy(ControllerContext.getInstance());
- controllerContext.setSchemas(schemaContext);
+
uriInfo = mock(UriInfo.class);
final MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
map.put("prettyPrint", Collections.singletonList("true"));
when(uriInfo.getQueryParameters(any(Boolean.class))).thenReturn(map);
}
- @Before
- public void initMethod() {
- this.restconfImpl = RestconfImpl.getInstance();
- this.restconfImpl.setControllerContext(controllerContext);
- }
-
/**
* Test method invokeRpc in RestconfImpl class tests if composite node as input parameter of method invokeRpc
* (second argument) is wrapped to parent composite node which has QName equals to QName of rpc (resolved from
@Test
@Ignore
public void invokeRpcMethodTest() {
- final ControllerContext contContext = controllerContext;
try {
- contContext.findModuleNameByNamespace(new URI("invoke:rpc:module"));
+ controllerContext.findModuleNameByNamespace(new URI("invoke:rpc:module"));
} catch (final URISyntaxException e) {
assertTrue("Uri wasn't created sucessfuly", false);
}
final BrokerFacade mockedBrokerFacade = mock(BrokerFacade.class);
- final RestconfImpl restconf = RestconfImpl.getInstance();
- restconf.setBroker(mockedBrokerFacade);
- restconf.setControllerContext(contContext);
+ restconfImpl.setBroker(mockedBrokerFacade);
final NormalizedNodeContext payload = prepareDomPayload();
- final NormalizedNodeContext rpcResponse = restconf.invokeRpc("invoke-rpc-module:rpc-test", payload, uriInfo);
+ final NormalizedNodeContext rpcResponse =
+ restconfImpl.invokeRpc("invoke-rpc-module:rpc-test", payload, uriInfo);
assertTrue(rpcResponse != null);
assertTrue(rpcResponse.getData() == null);
}
- private static NormalizedNodeContext prepareDomPayload() {
+ private NormalizedNodeContext prepareDomPayload() {
final SchemaContext schema = controllerContext.getGlobalSchema();
final Module rpcModule = schema.findModules("invoke-rpc-module").iterator().next();
assertNotNull(rpcModule);
final SchemaPath path = SchemaPath.create(true,
QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)make-toast"));
- final SchemaContext schemaContext = controllerContext.getGlobalSchema();
final Module rpcModule = schemaContext.findModules("toaster").iterator().next();
assertNotNull(rpcModule);
final QName rpcQName = QName.create(rpcModule.getQNameModule(), "make-toast");
import static org.mockito.Matchers.same;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
-import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
+import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.netconf.sal.restconf.impl.JSONRestconfServiceImpl;
static final QName TEST_OUTPUT_QNAME = QName.create(TOASTER_MODULE_NS, TOASTER_MODULE_VERSION, "testOutput");
static final QName TEXT_OUT_QNAME = QName.create(TOASTER_MODULE_NS, TOASTER_MODULE_VERSION, "textOut");
- private static BrokerFacade brokerFacade;
+ private static SchemaContext schemaContext;
- private final JSONRestconfServiceImpl service = new JSONRestconfServiceImpl();
+ private final BrokerFacade brokerFacade = mock(BrokerFacade.class);
+ private final DOMMountPoint mockMountPoint = mock(DOMMountPoint.class);
+ private JSONRestconfServiceImpl service;
@BeforeClass
public static void init() throws IOException, ReactorException {
- ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext("/full-versions/yangs"));
- brokerFacade = mock(BrokerFacade.class);
- RestconfImpl.getInstance().setBroker(brokerFacade);
- RestconfImpl.getInstance().setControllerContext(ControllerContext.getInstance());
+ schemaContext = TestUtils.loadSchemaContext("/full-versions/yangs");
}
@Before
- public void setup() {
- reset(brokerFacade);
+ public void setup() throws FileNotFoundException {
+ final SchemaContext mountPointSchemaContext = TestUtils.loadSchemaContext("/full-versions/test-module");
+ final ControllerContext controllerContext =
+ TestRestconfUtils.newControllerContext(schemaContext, mockMountPoint);
+ doReturn(mountPointSchemaContext).when(mockMountPoint).getSchemaContext();
+
+ service = new JSONRestconfServiceImpl(controllerContext);
+ RestconfImpl.getInstance().setBroker(brokerFacade);
+ RestconfImpl.getInstance().setControllerContext(controllerContext);
}
private static String loadData(final String path) throws IOException {
@SuppressWarnings("rawtypes")
@Test
public void testPutBehindMountPoint() throws Exception {
- final DOMMountPoint mockMountPoint = setupTestMountPoint();
final PutResult result = mock(PutResult.class);
when(brokerFacade.commitMountPointDataPut(notNull(DOMMountPoint.class),
notNull(YangInstanceIdentifier.class), notNull(NormalizedNode.class), Mockito.anyString(),
@SuppressWarnings("rawtypes")
@Test
public void testPostBehindMountPoint() throws Exception {
- final DOMMountPoint mockMountPoint = setupTestMountPoint();
doReturn(Futures.immediateCheckedFuture(null)).when(brokerFacade).commitConfigurationDataPost(
notNull(DOMMountPoint.class), notNull(YangInstanceIdentifier.class), notNull(NormalizedNode.class),
Mockito.anyString(), Mockito.anyString());
@SuppressWarnings("rawtypes")
@Test
public void testPatchBehindMountPoint() throws Exception {
- final DOMMountPoint mockMountPoint = setupTestMountPoint();
final PatchStatusContext result = mock(PatchStatusContext.class);
when(brokerFacade.patchConfigurationDataWithinTransaction(notNull(PatchContext.class)))
.thenReturn(result);
new Object[]{INTERFACE_QNAME, NAME_QNAME, "eth0"});
}
- DOMMountPoint setupTestMountPoint() throws FileNotFoundException, ReactorException {
- final SchemaContext schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
- final DOMMountPoint mockMountPoint = mock(DOMMountPoint.class);
- doReturn(schemaContextTestModule).when(mockMountPoint).getSchemaContext();
-
- final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
- doReturn(Optional.of(mockMountPoint))
- .when(mockMountService).getMountPoint(notNull(YangInstanceIdentifier.class));
-
- ControllerContext.getInstance().setMountService(mockMountService);
- return mockMountPoint;
- }
-
void verifyLeafNode(final DataContainerNode<?> parent, final QName leafType, final Object leafValue) {
final java.util.Optional<DataContainerChild<?, ?>> leafChild = parent.getChild(new NodeIdentifier(leafType));
assertEquals(leafType.toString() + " present", true, leafChild.isPresent());
import org.mockito.Mockito;
import org.opendaylight.netconf.sal.rest.api.Draft02;
import org.opendaylight.netconf.sal.rest.api.RestconfService;
-import org.opendaylight.netconf.sal.rest.impl.JsonNormalizedNodeBodyReader;
import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeJsonBodyWriter;
import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeXmlBodyWriter;
-import org.opendaylight.netconf.sal.rest.impl.RestconfDocumentedExceptionMapper;
-import org.opendaylight.netconf.sal.rest.impl.XmlNormalizedNodeBodyReader;
import org.opendaylight.restconf.common.context.NormalizedNodeContext;
public class MediaTypesTest extends JerseyTest {
- private static RestconfService restconfService;
private static String jsonData;
private static String xmlData;
+ private RestconfService restconfService;
+
@BeforeClass
public static void init() throws IOException {
- restconfService = mock(RestconfService.class);
final String jsonPath = RestconfImplTest.class.getResource("/parts/ietf-interfaces_interfaces.json").getPath();
jsonData = TestUtils.loadTextFile(jsonPath);
final InputStream xmlStream =
// enable(TestProperties.LOG_TRAFFIC);
// enable(TestProperties.DUMP_ENTITY);
// enable(TestProperties.RECORD_LOG_LEVEL);
- // set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
+ // set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());'
+ restconfService = mock(RestconfService.class);
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig = resourceConfig.registerInstances(restconfService, new NormalizedNodeJsonBodyWriter(),
- new NormalizedNodeXmlBodyWriter(), new XmlNormalizedNodeBodyReader(), new JsonNormalizedNodeBodyReader());
- resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
+ new NormalizedNodeXmlBodyWriter());
return resourceConfig;
}
private int post(final String uri, final String acceptMediaType, final String contentTypeMediaType,
final String data) {
if (acceptMediaType == null) {
- if ((contentTypeMediaType == null) || (data == null)) {
+ if (contentTypeMediaType == null || data == null) {
return target(uri).request().post(null).getStatus();
}
return target(uri).request().post(Entity.entity(data, contentTypeMediaType)).getStatus();
}
- if ((contentTypeMediaType == null) || (data == null)) {
+ if (contentTypeMediaType == null || data == null) {
return target(uri).request(acceptMediaType).post(null).getStatus();
}
return target(uri).request(acceptMediaType).post(Entity.entity(data, contentTypeMediaType)).getStatus();
@Test
public void serializeExceptionTest() {
- final Codec<Object, Object> codec = RestCodec.from(BaseTypes.bitsTypeBuilder(PATH).build(), null);
+ final Codec<Object, Object> codec = RestCodec.from(BaseTypes.bitsTypeBuilder(PATH).build(), null, null);
final String serializedValue = (String) codec.serialize("incorrect value"); // set
// expected
assertEquals("incorrect value", serializedValue);
public void deserializeExceptionTest() {
final IdentityrefTypeDefinition mockedIidentityrefType = mock(IdentityrefTypeDefinition.class);
- final Codec<Object, Object> codec = RestCodec.from(mockedIidentityrefType, null);
+ final Codec<Object, Object> codec = RestCodec.from(mockedIidentityrefType, null, null);
assertNull(codec.deserialize("incorrect value"));
}
import org.junit.BeforeClass;
import org.junit.Test;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.rest.impl.JsonNormalizedNodeBodyReader;
import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeJsonBodyWriter;
import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeXmlBodyWriter;
import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
public class RestDeleteOperationTest extends JerseyTest {
+ private static SchemaContext schemaContext;
- private static ControllerContext controllerContext;
- private static BrokerFacade brokerFacade;
- private static RestconfImpl restconfImpl;
+ private ControllerContext controllerContext;
+ private BrokerFacade brokerFacade;
+ private RestconfImpl restconfImpl;
@BeforeClass
public static void init() throws FileNotFoundException, ReactorException {
- final SchemaContext schemaContext = TestUtils.loadSchemaContext("/test-config-data/yang1");
+ schemaContext = TestUtils.loadSchemaContext("/test-config-data/yang1");
final Set<Module> allModules = schemaContext.getModules();
assertNotNull(allModules);
-
- controllerContext = ControllerContext.getInstance();
- controllerContext.setSchemas(schemaContext);
- brokerFacade = mock(BrokerFacade.class);
- restconfImpl = RestconfImpl.getInstance();
- restconfImpl.setBroker(brokerFacade);
- restconfImpl.setControllerContext(controllerContext);
}
@Override
// enable(TestProperties.DUMP_ENTITY);
// enable(TestProperties.RECORD_LOG_LEVEL);
// set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
+ controllerContext = TestRestconfUtils.newControllerContext(schemaContext);
+ controllerContext.setSchemas(schemaContext);
+ brokerFacade = mock(BrokerFacade.class);
+ restconfImpl = RestconfImpl.getInstance();
+ restconfImpl.setBroker(brokerFacade);
+ restconfImpl.setControllerContext(controllerContext);
+
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig = resourceConfig.registerInstances(restconfImpl, new NormalizedNodeJsonBodyWriter(),
- new NormalizedNodeXmlBodyWriter(), new XmlNormalizedNodeBodyReader(), new JsonNormalizedNodeBodyReader());
- resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
+ new NormalizedNodeXmlBodyWriter(), new XmlNormalizedNodeBodyReader(controllerContext),
+ new JsonNormalizedNodeBodyReader(controllerContext),
+ new RestconfDocumentedExceptionMapper(controllerContext));
return resourceConfig;
}
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
+import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
public class RestGetAugmentedElementWhenEqualNamesTest {
- private static ControllerContext controllerContext = ControllerContext.getInstance();
+ private static SchemaContext schemaContext;
+
+ private final ControllerContext controllerContext = TestRestconfUtils.newControllerContext(schemaContext);
@Rule
public ExpectedException exception = ExpectedException.none();
@BeforeClass
- public static void init() throws FileNotFoundException, ReactorException {
- final SchemaContext schemaContextTestModule = TestUtils.loadSchemaContext("/common/augment/yang");
- controllerContext.setSchemas(schemaContextTestModule);
+ public static void init() throws FileNotFoundException {
+ schemaContext = TestUtils.loadSchemaContext("/common/augment/yang");
}
@Test
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import java.net.URI;
import org.junit.Test;
import org.mockito.Mockito;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
-import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
+import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.rest.impl.JsonNormalizedNodeBodyReader;
import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeJsonBodyWriter;
import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeXmlBodyWriter;
-import org.opendaylight.netconf.sal.rest.impl.RestconfApplication;
import org.opendaylight.netconf.sal.rest.impl.RestconfDocumentedExceptionMapper;
import org.opendaylight.netconf.sal.rest.impl.XmlNormalizedNodeBodyReader;
import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
}
}
- private static BrokerFacade brokerFacade;
- private static RestconfImpl restconfImpl;
private static SchemaContext schemaContextYangsIetf;
private static SchemaContext schemaContextTestModule;
+ private static SchemaContext schemaContextModules;
+ private static SchemaContext schemaContextBehindMountPoint;
+
@SuppressWarnings("rawtypes")
private static NormalizedNode answerFromGet;
- private static SchemaContext schemaContextModules;
- private static SchemaContext schemaContextBehindMountPoint;
+ private BrokerFacade brokerFacade;
+ private RestconfImpl restconfImpl;
+ private ControllerContext controllerContext;
+ private DOMMountPoint mountInstance;
private static final String RESTCONF_NS = "urn:ietf:params:xml:ns:yang:ietf-restconf";
public static void init() throws Exception {
schemaContextYangsIetf = TestUtils.loadSchemaContext("/full-versions/yangs");
schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
- brokerFacade = mock(BrokerFacade.class);
- restconfImpl = RestconfImpl.getInstance();
- restconfImpl.setBroker(brokerFacade);
- answerFromGet = TestUtils.prepareNormalizedNodeWithIetfInterfacesInterfacesData();
-
schemaContextModules = TestUtils.loadSchemaContext("/modules");
schemaContextBehindMountPoint = TestUtils.loadSchemaContext("/modules/modules-behind-mount-point");
+
+ answerFromGet = TestUtils.prepareNormalizedNodeWithIetfInterfacesInterfacesData();
}
@Override
// enable(TestProperties.DUMP_ENTITY);
// enable(TestProperties.RECORD_LOG_LEVEL);
// set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
+
+ mountInstance = mock(DOMMountPoint.class);
+ controllerContext = TestRestconfUtils.newControllerContext(schemaContextYangsIetf, mountInstance);
+ brokerFacade = mock(BrokerFacade.class);
+ restconfImpl = RestconfImpl.getInstance();
+ restconfImpl.setBroker(brokerFacade);
+ restconfImpl.setControllerContext(controllerContext);
+
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig = resourceConfig.registerInstances(restconfImpl, new NormalizedNodeJsonBodyWriter(),
- new NormalizedNodeXmlBodyWriter(), new XmlNormalizedNodeBodyReader(), new JsonNormalizedNodeBodyReader());
- resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
- resourceConfig.registerClasses(new RestconfApplication().getClasses());
+ new NormalizedNodeXmlBodyWriter(), new XmlNormalizedNodeBodyReader(controllerContext),
+ new JsonNormalizedNodeBodyReader(controllerContext),
+ new RestconfDocumentedExceptionMapper(controllerContext));
return resourceConfig;
}
- private static void setControllerContext(final SchemaContext schemaContext) {
- final ControllerContext controllerContext = ControllerContext.getInstance();
+ private void setControllerContext(final SchemaContext schemaContext) {
controllerContext.setSchemas(schemaContext);
- restconfImpl.setControllerContext(controllerContext);
}
/**
when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class),
Mockito.anyString())).thenReturn(
prepareCnDataForMountPointTest(false));
- final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
- final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
- when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
-
- ControllerContext.getInstance().setMountService(mockMountService);
String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont/cont1";
assertEquals(200, get(uri, MediaType.APPLICATION_XML));
final YangInstanceIdentifier awaitedInstanceIdentifier = prepareInstanceIdentifierForList();
when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), eq(awaitedInstanceIdentifier),
Mockito.anyString())).thenReturn(prepareCnDataForSlashesBehindMountPointTest());
- final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
- when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
- final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
- when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
- ControllerContext.getInstance().setMountService(mockMountService);
+ when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
final String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/"
+ "test-module:cont/lst1/GigabitEthernet0%2F0%2F0%2F0";
when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class),
Mockito.anyString())).thenReturn(
prepareCnDataForMountPointTest(true));
- final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
- when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
- final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
- when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
- ControllerContext.getInstance().setMountService(mockMountService);
+ when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
final String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont";
assertEquals(200, get(uri, MediaType.APPLICATION_XML));
// /modules
@Test
public void getModulesTest() throws Exception {
- final ControllerContext controllerContext = ControllerContext.getInstance();
- controllerContext.setGlobalSchema(schemaContextModules);
- restconfImpl.setControllerContext(controllerContext);
+ setControllerContext(schemaContextModules);
final String uri = "/modules";
}
}
- 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 Exception {
setControllerContext(schemaContextModules);
- final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
- final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
- when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
-
- ControllerContext.getInstance().setMountService(mockMountService);
final String uri = "/operations/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
public void getModulesBehindMountPoint() throws Exception {
setControllerContext(schemaContextModules);
- final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
- final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
- when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
-
- ControllerContext.getInstance().setMountService(mockMountService);
final String uri = "/modules/ietf-interfaces:interfaces/interface/0/yang-ext:mount/";
public void getModuleBehindMountPoint() throws Exception {
setControllerContext(schemaContextModules);
- final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
when(mountInstance.getSchemaContext()).thenReturn(schemaContextBehindMountPoint);
- final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
- when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
-
- ControllerContext.getInstance().setMountService(mockMountService);
final String uri = "/modules/module/ietf-interfaces:interfaces/interface/0/yang-ext:mount/"
+ "module1-behind-mount-point/2014-02-03";
}
@SuppressWarnings("unchecked")
- private static void mockReadOperationalDataMethod() {
+ private void mockReadOperationalDataMethod() {
when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn(answerFromGet);
}
@SuppressWarnings("unchecked")
- private static void mockReadConfigurationDataMethod() {
+ private void mockReadConfigurationDataMethod() {
when(brokerFacade.readConfigurationData(any(YangInstanceIdentifier.class), Mockito.anyString()))
.thenReturn(answerFromGet);
}
}
@SuppressWarnings({"rawtypes", "unchecked"})
- private static void getDataWithInvalidDepthParameterTest(final UriInfo uriInfo) {
+ private void getDataWithInvalidDepthParameterTest(final UriInfo uriInfo) {
try {
final QName qNameDepth1Cont = QName.create("urn:nested:module", "2014-06-3", "depth1-cont");
final YangInstanceIdentifier ii = YangInstanceIdentifier.builder().node(qNameDepth1Cont).build();
import static org.mockito.Mockito.when;
import static org.opendaylight.controller.sal.restconf.impl.test.RestOperationUtils.XML;
-import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
import java.io.IOException;
-import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.text.ParseException;
-import java.util.Set;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
import org.mockito.Mockito;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
-import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
+import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.rest.api.Draft02;
import org.opendaylight.netconf.sal.rest.impl.JsonNormalizedNodeBodyReader;
import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeJsonBodyWriter;
import org.opendaylight.netconf.sal.restconf.impl.RestconfImpl;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
public class RestPostOperationTest extends JerseyTest {
- private static String xmlDataAbsolutePath;
- private static String xmlDataInterfaceAbsolutePath;
- private static String xmlDataRpcInput;
private static String xmlBlockData;
- private static String xmlTestInterface;
private static String xmlData3;
private static String xmlData4;
- private static BrokerFacade brokerFacade;
- private static RestconfImpl restconfImpl;
private static SchemaContext schemaContextYangsIetf;
private static SchemaContext schemaContextTestModule;
private static SchemaContext schemaContext;
- private static DOMMountPointService mountService;
+ private BrokerFacade brokerFacade;
+ private RestconfImpl restconfImpl;
+ private ControllerContext controllerContext;
+ private DOMMountPoint mountInstance;
@BeforeClass
public static void init() throws URISyntaxException, IOException, ReactorException {
schemaContextYangsIetf = TestUtils.loadSchemaContext("/full-versions/yangs");
schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
- brokerFacade = mock(BrokerFacade.class);
- restconfImpl = RestconfImpl.getInstance();
- restconfImpl.setBroker(brokerFacade);
-
schemaContext = TestUtils.loadSchemaContext("/test-config-data/yang1");
- final Set<Module> modules = schemaContext.getModules();
-
loadData();
}
// enable(TestProperties.DUMP_ENTITY);
// enable(TestProperties.RECORD_LOG_LEVEL);
// set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
+
+ mountInstance = mock(DOMMountPoint.class);
+ controllerContext = TestRestconfUtils.newControllerContext(schemaContext, mountInstance);
+ brokerFacade = mock(BrokerFacade.class);
+ restconfImpl = RestconfImpl.getInstance();
+ restconfImpl.setBroker(brokerFacade);
+ restconfImpl.setControllerContext(controllerContext);
+
ResourceConfig resourceConfig = new ResourceConfig();
- resourceConfig = resourceConfig.registerInstances(restconfImpl, new XmlNormalizedNodeBodyReader(),
- new NormalizedNodeXmlBodyWriter(), new JsonNormalizedNodeBodyReader(), new NormalizedNodeJsonBodyWriter());
- resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
+ resourceConfig = resourceConfig.registerInstances(restconfImpl,
+ new XmlNormalizedNodeBodyReader(controllerContext), new NormalizedNodeXmlBodyWriter(),
+ new JsonNormalizedNodeBodyReader(controllerContext), new NormalizedNodeJsonBodyWriter(),
+ new RestconfDocumentedExceptionMapper(controllerContext));
return resourceConfig;
}
- private static void setSchemaControllerContext(final SchemaContext schema) {
- final ControllerContext context = ControllerContext.getInstance();
- context.setSchemas(schema);
- restconfImpl.setControllerContext(context);
+ private void setSchemaControllerContext(final SchemaContext schema) {
+ controllerContext.setSchemas(schema);
}
@SuppressWarnings("unchecked")
@Ignore /// xmlData* need netconf-yang
public void postDataViaUrlMountPoint() throws UnsupportedEncodingException {
setSchemaControllerContext(schemaContextYangsIetf);
- when(
- brokerFacade.commitConfigurationDataPost(any(DOMMountPoint.class), any(YangInstanceIdentifier.class),
- any(NormalizedNode.class), null, null)).thenReturn(mock(CheckedFuture.class));
+ when(brokerFacade.commitConfigurationDataPost(any(DOMMountPoint.class), any(YangInstanceIdentifier.class),
+ any(NormalizedNode.class), null, null)).thenReturn(mock(CheckedFuture.class));
- final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
- final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
- when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
-
- ControllerContext.getInstance().setMountService(mockMountService);
String uri = "/config/ietf-interfaces:interfaces/interface/0/";
assertEquals(204, post(uri, Draft02.MediaTypes.DATA + XML, xmlData4));
@Ignore //jenkins has problem with JerseyTest
// - we expecting problems with singletons ControllerContext as schemaContext holder
public void createConfigurationDataTest() throws UnsupportedEncodingException, ParseException {
- initMocking();
when(brokerFacade.commitConfigurationDataPost((SchemaContext) null, any(YangInstanceIdentifier.class),
any(NormalizedNode.class), null, null))
.thenReturn(mock(CheckedFuture.class));
@Test
public void createConfigurationDataNullTest() throws UnsupportedEncodingException {
- initMocking();
-
when(brokerFacade.commitConfigurationDataPost(any(SchemaContext.class), any(YangInstanceIdentifier.class),
any(NormalizedNode.class), Mockito.anyString(), Mockito.anyString()))
.thenReturn(Futures.<Void, TransactionCommitFailedException>immediateCheckedFuture(null));
assertEquals(204, post(URI_2, Draft02.MediaTypes.DATA + XML, xmlBlockData));
}
- private static void initMocking() {
- final ControllerContext controllerContext = ControllerContext.getInstance();
- controllerContext.setSchemas(schemaContext);
- mountService = mock(DOMMountPointService.class);
- controllerContext.setMountService(mountService);
- brokerFacade = mock(BrokerFacade.class);
- restconfImpl = RestconfImpl.getInstance();
- restconfImpl.setBroker(brokerFacade);
- restconfImpl.setControllerContext(controllerContext);
- }
-
private int post(final String uri, final String mediaType, final String data) {
return target(uri).request(mediaType).post(Entity.entity(data, mediaType)).getStatus();
}
private static void loadData() throws IOException, URISyntaxException {
- InputStream xmlStream = RestconfImplTest.class
- .getResourceAsStream("/parts/ietf-interfaces_interfaces_absolute_path.xml");
- xmlDataAbsolutePath = TestUtils.getDocumentInPrintableForm(TestUtils.loadDocumentFrom(xmlStream));
- 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();
- xmlDataRpcInput = TestUtils.loadTextFile(xmlPathRpcInput);
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();
- xmlTestInterface = TestUtils.loadTextFile(xmlPathTestInterface);
-// cnSnDataOutput = prepareCnSnRpcOutput();
final String data3Input = RestconfImplTest.class.getResource("/full-versions/test-data2/data3.xml").getPath();
xmlData3 = TestUtils.loadTextFile(data3Input);
final String data4Input = RestconfImplTest.class.getResource("/full-versions/test-data2/data7.xml").getPath();
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
+import java.io.FileNotFoundException;
import java.util.HashSet;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import org.junit.Before;
+import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
@RunWith(MockitoJUnitRunner.class)
public class RestPutConfigTest {
+ private static SchemaContext schemaContext;
private RestconfImpl restconfService;
private ControllerContext controllerCx;
- private SchemaContext schemaCx;
@Mock
private BrokerFacade brokerFacade;
+ @BeforeClass
+ public static void staticInit() throws FileNotFoundException {
+ schemaContext = TestRestconfUtils.loadSchemaContext("/test-config-data/yang1/", null);
+ }
+
@Before
public void init() {
this.restconfService = RestconfImpl.getInstance();
- this.controllerCx = ControllerContext.getInstance();
- this.schemaCx = TestRestconfUtils.loadSchemaContext("/test-config-data/yang1/", null);
- this.controllerCx.setSchemas(this.schemaCx);
+ this.controllerCx = TestRestconfUtils.newControllerContext(schemaContext);
this.restconfService.setControllerContext(this.controllerCx);
}
final PutResult result = Mockito.mock(PutResult.class);
final CheckedFuture<Void, TransactionCommitFailedException> checkedFuture =
Futures.immediateCheckedFuture(null);
- Mockito.when(this.brokerFacade.commitConfigurationDataPut(this.schemaCx, yii, data, null, null))
+ Mockito.when(this.brokerFacade.commitConfigurationDataPut(this.schemaContext, yii, data, null, null))
.thenReturn(result);
Mockito.when(result.getFutureOfPutData()).thenReturn(checkedFuture);
Mockito.when(result.getStatus()).thenReturn(Status.OK);
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import com.google.common.base.Optional;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
import java.io.FileNotFoundException;
import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
-import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
+import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.rest.impl.JsonNormalizedNodeBodyReader;
import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeJsonBodyWriter;
import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeXmlBodyWriter;
private static String xmlData2;
private static String xmlData3;
- private static BrokerFacade brokerFacade;
- private static RestconfImpl restconfImpl;
private static SchemaContext schemaContextYangsIetf;
private static SchemaContext schemaContextTestModule;
+ private BrokerFacade brokerFacade;
+ private RestconfImpl restconfImpl;
+ private DOMMountPoint mountInstance;
+
@BeforeClass
public static void init() throws IOException, ReactorException {
schemaContextYangsIetf = TestUtils.loadSchemaContext("/full-versions/yangs");
schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
- final ControllerContext controllerContext = ControllerContext.getInstance();
- controllerContext.setSchemas(schemaContextYangsIetf);
- brokerFacade = mock(BrokerFacade.class);
- restconfImpl = RestconfImpl.getInstance();
- restconfImpl.setBroker(brokerFacade);
- restconfImpl.setControllerContext(controllerContext);
loadData();
}
// enable(TestProperties.DUMP_ENTITY);
// enable(TestProperties.RECORD_LOG_LEVEL);
// set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
+
+ mountInstance = mock(DOMMountPoint.class);
+ final ControllerContext controllerContext =
+ TestRestconfUtils.newControllerContext(schemaContextYangsIetf, mountInstance);
+ brokerFacade = mock(BrokerFacade.class);
+ restconfImpl = RestconfImpl.getInstance();
+ restconfImpl.setBroker(brokerFacade);
+ restconfImpl.setControllerContext(controllerContext);
+
ResourceConfig resourceConfig = new ResourceConfig();
- resourceConfig = resourceConfig.registerInstances(restconfImpl,new XmlNormalizedNodeBodyReader(),
- new NormalizedNodeXmlBodyWriter(), new JsonNormalizedNodeBodyReader(), new NormalizedNodeJsonBodyWriter());
- resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
+ resourceConfig = resourceConfig.registerInstances(restconfImpl,
+ new XmlNormalizedNodeBodyReader(controllerContext), new NormalizedNodeXmlBodyWriter(),
+ new JsonNormalizedNodeBodyReader(controllerContext), new NormalizedNodeJsonBodyWriter(),
+ new RestconfDocumentedExceptionMapper(controllerContext));
return resourceConfig;
}
when(result.getFutureOfPutData()).thenReturn(dummyFuture);
when(result.getStatus()).thenReturn(Status.OK);
- final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
- final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
- when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
-
- ControllerContext.getInstance().setMountService(mockMountService);
String uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont";
assertEquals(200, put(uri, MediaType.APPLICATION_XML, xmlData2));
when(result.getFutureOfPutData()).thenReturn(dummyFuture);
when(result.getStatus()).thenReturn(Status.OK);
- final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
- final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
- when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
-
- ControllerContext.getInstance().setMountService(mockMountService);
final String uri = "/config/ietf-interfaces:interfaces/yang-ext:mount";
assertEquals(200, put(uri, MediaType.APPLICATION_XML, xmlData3));
return target(uri).request(mediaType).put(Entity.entity(data, mediaType)).getStatus();
}
- private static void mockCommitConfigurationDataPutMethod(final boolean noErrors) {
+ private void mockCommitConfigurationDataPutMethod(final boolean noErrors) {
final PutResult putResMock = mock(PutResult.class);
if (noErrors) {
doReturn(putResMock).when(brokerFacade).commitConfigurationDataPut(
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
+import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.rest.api.Draft02;
import org.opendaylight.netconf.sal.rest.api.RestconfService;
import org.opendaylight.netconf.sal.rest.impl.JsonNormalizedNodeBodyReader;
import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
import org.opendaylight.yangtools.util.xml.UntrustedXML;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
static XPathExpression ERROR_APP_TAG;
static XPathExpression ERROR_INFO;
+ private static SchemaContext schemaContext;
+
@BeforeClass
public static void init() throws Exception {
- ControllerContext.getInstance().setGlobalSchema(TestUtils.loadSchemaContext("/modules"));
+ schemaContext = TestUtils.loadSchemaContext("/modules");
final NamespaceContext nsContext = new NamespaceContext() {
@Override
@Override
protected Application configure() {
ResourceConfig resourceConfig = new ResourceConfig();
- resourceConfig = resourceConfig.registerInstances(mockRestConf, new XmlNormalizedNodeBodyReader(),
- new JsonNormalizedNodeBodyReader(), new NormalizedNodeJsonBodyWriter(), new NormalizedNodeXmlBodyWriter());
- resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
+ ControllerContext controllerContext = TestRestconfUtils.newControllerContext(schemaContext);
+ resourceConfig = resourceConfig.registerInstances(mockRestConf,
+ new XmlNormalizedNodeBodyReader(controllerContext), new JsonNormalizedNodeBodyReader(controllerContext),
+ new NormalizedNodeJsonBodyWriter(), new NormalizedNodeXmlBodyWriter(),
+ new RestconfDocumentedExceptionMapper(controllerContext));
return resourceConfig;
}
*/
package org.opendaylight.controller.sal.restconf.impl.test;
+import java.io.FileNotFoundException;
import java.time.Instant;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.ArrayList;
import javax.ws.rs.core.UriInfo;
import org.junit.Assert;
import org.junit.Before;
+import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class RestconfImplNotificationSubscribingTest {
private final String identifier = "data-change-event-subscription/datastore=OPERATIONAL/scope=ONE";
+ private static SchemaContext schemaContext;
+
@Mock
private BrokerFacade broker;
@Mock
private UriInfo uriInfo;
+ private ControllerContext controllerContext;
+
+ @BeforeClass
+ public static void init() throws FileNotFoundException {
+ schemaContext = YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/notifications"));
+ }
+
@Before
public void setup() throws Exception {
MockitoAnnotations.initMocks(this);
this.broker.setDomDataBroker(this.domDataBroker);
RestconfImpl.getInstance().setBroker(this.broker);
- ControllerContext.getInstance()
- .setGlobalSchema(YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/notifications")));
+
+ controllerContext = TestRestconfUtils.newControllerContext(schemaContext);
+ RestconfImpl.getInstance().setControllerContext(controllerContext);
final YangInstanceIdentifier path = Mockito.mock(YangInstanceIdentifier.class);
final PathArgument pathValue = NodeIdentifier.create(QName.create("module", "2016-12-14", "localName"));
Mockito.when(path.getLastPathArgument()).thenReturn(pathValue);
- Notificator.createListener(path, this.identifier, NotificationOutputType.XML);
+ Notificator.createListener(path, this.identifier, NotificationOutputType.XML, controllerContext);
}
@Test
final YangInstanceIdentifier path = Mockito.mock(YangInstanceIdentifier.class);
final PathArgument pathValue = NodeIdentifier.create(QName.create("module", "2016-12-14", "localName"));
Mockito.when(path.getLastPathArgument()).thenReturn(pathValue);
- final ListenerAdapter listener = Notificator.createListener(path, this.identifier, NotificationOutputType.XML);
+ final ListenerAdapter listener = Notificator.createListener(path, this.identifier, NotificationOutputType.XML,
+ controllerContext);
final List<Entry<String, List<String>>> list = new ArrayList<>();
final List<String> time = new ArrayList<>();
subscribe(list);
- ArrayList<DataTreeCandidate> candidates = new ArrayList<DataTreeCandidate>(0);
+ ArrayList<DataTreeCandidate> candidates = new ArrayList<>(0);
Instant startOrig = listener.getStart();
Assert.assertNotNull(startOrig);
listener.onDataTreeChanged(candidates);
import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
+import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.netconf.sal.restconf.impl.RestconfImpl;
*/
public class RestconfImplTest {
- private RestconfImpl restconfImpl = null;
- private static ControllerContext controllerContext = null;
+ private static SchemaContext schemaContext;
+
+ private RestconfImpl restconfImpl;
+ private final ControllerContext controllerContext = TestRestconfUtils.newControllerContext(schemaContext);
@BeforeClass
public static void init() throws FileNotFoundException, ReactorException {
- final SchemaContext schemaContext = TestUtils.loadSchemaContext("/full-versions/yangs");
-
+ schemaContext = TestUtils.loadSchemaContext("/full-versions/yangs");
final Set<Module> allModules = schemaContext.getModules();
assertNotNull(allModules);
-
- controllerContext = ControllerContext.getInstance();
- controllerContext.setSchemas(schemaContext);
}
@Before
// register test notification stream
final SchemaPath path = SchemaPath.create(
true, QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
- Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML");
+ Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML", controllerContext);
final UriInfo uriInfo = mock(UriInfo.class);
final UriBuilder uriBuilder = mock(UriBuilder.class);
import org.mockito.Mockito;
import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.netconf.sal.restconf.impl.RestconfImpl;
public void init() throws FileNotFoundException, ReactorException {
this.restconf = RestconfImpl.getInstance();
this.mockedBrokerFacade = mock(BrokerFacade.class);
- this.controllerContext = ControllerContext.getInstance();
- this.controllerContext.setSchemas(TestUtils.loadSchemaContext("/datastore-and-scope-specification"));
+ this.controllerContext = TestRestconfUtils.newControllerContext(
+ TestUtils.loadSchemaContext("/datastore-and-scope-specification"));
this.restconf.setControllerContext(this.controllerContext);
this.restconf.setBroker(this.mockedBrokerFacade);
}
final String datastoreValue = datastore == null ? "CONFIGURATION" : datastore;
final String scopeValue = scope == null ? "BASE" : scope + "";
Notificator.createListener(iiBuilder.build(), "dummyStreamName/datastore=" + datastoreValue + "/scope="
- + scopeValue, NotificationOutputType.XML);
+ + scopeValue, NotificationOutputType.XML, controllerContext);
final UriInfo mockedUriInfo = mock(UriInfo.class);
@SuppressWarnings("unchecked")
package org.opendaylight.controller.sal.restconf.impl.test;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import java.io.FileNotFoundException;
-import java.util.Set;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
-import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
+import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.netconf.sal.restconf.impl.RestconfImpl;
import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
-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;
public class URITest {
- private static final ControllerContext CONTROLLER_CONTEXT = ControllerContext.getInstance();
+ private static SchemaContext schemaContext;
+ private static SchemaContext mountSchemaContext;
+
+ private final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
+ private final ControllerContext controllerContext =
+ TestRestconfUtils.newControllerContext(schemaContext, mountInstance);
@Rule
public ExpectedException exception = ExpectedException.none();
@BeforeClass
public static void init() throws FileNotFoundException, ReactorException {
- final SchemaContext schemaContext = TestUtils.loadSchemaContext("/full-versions/yangs");
- final Set<Module> allModules = schemaContext.getModules();
- assertNotNull(allModules);
-
- CONTROLLER_CONTEXT.setSchemas(schemaContext);
+ schemaContext = TestUtils.loadSchemaContext("/full-versions/yangs");
+ mountSchemaContext = TestUtils.loadSchemaContext("/test-config-data/yang2");
}
@Test
public void testToInstanceIdentifierList() throws FileNotFoundException {
- InstanceIdentifierContext<?> instanceIdentifier = CONTROLLER_CONTEXT
+ InstanceIdentifierContext<?> instanceIdentifier = controllerContext
.toInstanceIdentifier("simple-nodes:userWithoutClass/foo");
assertEquals(instanceIdentifier.getSchemaNode().getQName().getLocalName(), "userWithoutClass");
- instanceIdentifier = CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes:userWithoutClass/foo");
+ instanceIdentifier = controllerContext.toInstanceIdentifier("simple-nodes:userWithoutClass/foo");
assertEquals(instanceIdentifier.getSchemaNode().getQName().getLocalName(), "userWithoutClass");
- instanceIdentifier = CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes:user/foo/boo");
+ instanceIdentifier = controllerContext.toInstanceIdentifier("simple-nodes:user/foo/boo");
assertEquals(instanceIdentifier.getSchemaNode().getQName().getLocalName(), "user");
- instanceIdentifier = CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes:user//boo");
+ instanceIdentifier = controllerContext.toInstanceIdentifier("simple-nodes:user//boo");
assertEquals(instanceIdentifier.getSchemaNode().getQName().getLocalName(), "user");
}
@Test
public void testToInstanceIdentifierListWithNullKey() {
this.exception.expect(RestconfDocumentedException.class);
- CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes:user/null/boo");
+ controllerContext.toInstanceIdentifier("simple-nodes:user/null/boo");
}
@Test
public void testToInstanceIdentifierListWithMissingKey() {
this.exception.expect(RestconfDocumentedException.class);
- CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes:user/foo");
+ controllerContext.toInstanceIdentifier("simple-nodes:user/foo");
}
@Test
public void testToInstanceIdentifierContainer() throws FileNotFoundException {
final InstanceIdentifierContext<?> instanceIdentifier =
- CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes:users");
+ controllerContext.toInstanceIdentifier("simple-nodes:users");
assertEquals(instanceIdentifier.getSchemaNode().getQName().getLocalName(), "users");
assertTrue(instanceIdentifier.getSchemaNode() instanceof ContainerSchemaNode);
assertEquals(2, ((ContainerSchemaNode) instanceIdentifier.getSchemaNode()).getChildNodes().size());
@Ignore //jenkins has problem with JerseyTest
// - we expecting problems with singletons ControllerContext as schemaContext holder
public void testToInstanceIdentifierChoice() throws FileNotFoundException {
- final InstanceIdentifierContext<?> instanceIdentifier = CONTROLLER_CONTEXT
+ final InstanceIdentifierContext<?> instanceIdentifier = controllerContext
.toInstanceIdentifier("simple-nodes:food/nonalcoholic");
assertEquals(instanceIdentifier.getSchemaNode().getQName().getLocalName(), "nonalcoholic");
}
@Test
public void testToInstanceIdentifierChoiceException() {
this.exception.expect(RestconfDocumentedException.class);
- CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes:food/snack");
+ controllerContext.toInstanceIdentifier("simple-nodes:food/snack");
}
@Test
public void testToInstanceIdentifierCaseException() {
this.exception.expect(RestconfDocumentedException.class);
- CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes:food/sports-arena");
+ controllerContext.toInstanceIdentifier("simple-nodes:food/sports-arena");
}
@Test
public void testToInstanceIdentifierChoiceCaseException() {
this.exception.expect(RestconfDocumentedException.class);
- CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes:food/snack/sports-arena");
+ controllerContext.toInstanceIdentifier("simple-nodes:food/snack/sports-arena");
}
@Test
public void testToInstanceIdentifierWithoutNode() {
this.exception.expect(RestconfDocumentedException.class);
- CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes");
+ controllerContext.toInstanceIdentifier("simple-nodes");
}
@Test
public void testMountPointWithExternModul() throws FileNotFoundException, ReactorException {
initMountService(true);
- final InstanceIdentifierContext<?> instanceIdentifier = CONTROLLER_CONTEXT
+ final InstanceIdentifierContext<?> instanceIdentifier = controllerContext
.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, "
@Test
public void testMountPointWithoutExternModul() throws FileNotFoundException, ReactorException {
initMountService(true);
- final InstanceIdentifierContext<?> instanceIdentifier = CONTROLLER_CONTEXT
+ final InstanceIdentifierContext<?> instanceIdentifier = controllerContext
.toInstanceIdentifier("simple-nodes:users/yang-ext:mount/");
assertTrue(Iterables.isEmpty(instanceIdentifier.getInstanceIdentifier().getPathArguments()));
}
- @Test
- public void testMountPointWithoutMountService() throws FileNotFoundException {
- this.exception.expect(RestconfDocumentedException.class);
-
- CONTROLLER_CONTEXT.setMountService(null);
- CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes:users/yang-ext:mount/test-interface2:class/student/name");
- }
-
@Test
public void testMountPointWithoutMountPointSchema() throws FileNotFoundException, ReactorException {
initMountService(false);
this.exception.expect(RestconfDocumentedException.class);
- CONTROLLER_CONTEXT.toInstanceIdentifier("simple-nodes:users/yang-ext:mount/test-interface2:class");
+ controllerContext.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);
- CONTROLLER_CONTEXT.setMountService(mountService);
final BrokerFacade brokerFacade = mock(BrokerFacade.class);
final RestconfImpl restconfImpl = RestconfImpl.getInstance();
restconfImpl.setBroker(brokerFacade);
- restconfImpl.setControllerContext(CONTROLLER_CONTEXT);
- final SchemaContext schemaContext2 = TestUtils.loadSchemaContext("/test-config-data/yang2");
- final Set<Module> modules2 = schemaContext2.getModules();
+ restconfImpl.setControllerContext(controllerContext);
- final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
if (withSchema) {
- when(mountInstance.getSchemaContext()).thenReturn(schemaContext2);
+ when(mountInstance.getSchemaContext()).thenReturn(mountSchemaContext);
} else {
when(mountInstance.getSchemaContext()).thenReturn(null);
}
- when(mountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
}
}
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
+import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
import org.opendaylight.netconf.sal.rest.impl.JsonNormalizedNodeBodyReader;
import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeJsonBodyWriter;
public class RestStreamTest extends JerseyTest {
- private static BrokerFacade brokerFacade;
- private static RestconfImpl restconfImpl;
private static SchemaContext schemaContextYangsIetf;
+ private BrokerFacade brokerFacade;
+ private RestconfImpl restconfImpl;
+
@BeforeClass
public static void init() throws FileNotFoundException, ReactorException {
schemaContextYangsIetf = TestUtils.loadSchemaContext("/full-versions/yangs");
- final ControllerContext controllerContext = ControllerContext.getInstance();
- controllerContext.setSchemas(schemaContextYangsIetf);
- brokerFacade = mock(BrokerFacade.class);
- restconfImpl = RestconfImpl.getInstance();
- restconfImpl.setBroker(brokerFacade);
- restconfImpl.setControllerContext(controllerContext);
}
@Override
// enable(TestProperties.DUMP_ENTITY);
// enable(TestProperties.RECORD_LOG_LEVEL);
// set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
+
+ final ControllerContext controllerContext = TestRestconfUtils.newControllerContext(schemaContextYangsIetf);
+ brokerFacade = mock(BrokerFacade.class);
+ restconfImpl = RestconfImpl.getInstance();
+ restconfImpl.setBroker(brokerFacade);
+ restconfImpl.setControllerContext(controllerContext);
+
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig = resourceConfig.registerInstances(restconfImpl, new NormalizedNodeJsonBodyWriter(),
- new NormalizedNodeXmlBodyWriter(), new XmlNormalizedNodeBodyReader(), new JsonNormalizedNodeBodyReader());
- resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
+ new NormalizedNodeXmlBodyWriter(), new XmlNormalizedNodeBodyReader(controllerContext),
+ new JsonNormalizedNodeBodyReader(controllerContext),
+ new RestconfDocumentedExceptionMapper(controllerContext));
return resourceConfig;
}
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
+import java.io.FileNotFoundException;
import org.junit.Before;
+import org.junit.BeforeClass;
import org.junit.Test;
import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.restconf.impl.RestCodec.InstanceIdentifierCodecImpl;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public class InstanceIdentifierCodecImplTest {
+ private static SchemaContext schemaContext;
private Codec<IdentityValuesDTO, YangInstanceIdentifier> instanceIdentifierDTO;
private YangInstanceIdentifier instanceIdentifierBadNamespace;
private YangInstanceIdentifier instanceIdentifierOKList;
private YangInstanceIdentifier instanceIdentifierOKLeafList;
- private SchemaContext schemaContext;
+
+ @BeforeClass
+ public static void init() throws FileNotFoundException {
+ schemaContext = YangParserTestUtils.parseYangFiles(
+ TestRestconfUtils.loadFiles("/restconf/parser/deserializer"));
+ }
@Before
public void setUp() throws Exception {
- this.schemaContext =
- YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/restconf/parser/deserializer"));
- this.instanceIdentifierDTO = new InstanceIdentifierCodecImpl(null);
- ControllerContext.getInstance().setGlobalSchema(this.schemaContext);
+ ControllerContext controllerContext = TestRestconfUtils.newControllerContext(schemaContext);
+
+ this.instanceIdentifierDTO = new InstanceIdentifierCodecImpl(null, controllerContext);
final QName baseQName = QName.create("deserializer:test", "2016-06-06", "deserializer-test");
final QName contA = QName.create(baseQName, "contA");
this.instanceIdentifierDTO.deserialize(valuesDTO);
assertNull(deserializedIdentifier);
}
-}
\ No newline at end of file
+}
import java.util.Optional;
import org.json.JSONObject;
import org.junit.Before;
+import org.junit.BeforeClass;
import org.junit.Test;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeIdentifier;
+import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.yang.gen.v1.instance.identifier.patch.module.rev151121.PatchCont;
import org.opendaylight.yang.gen.v1.instance.identifier.patch.module.rev151121.patch.cont.MyList1;
private static YangInstanceIdentifier PATCH_CONT_YIID =
YangInstanceIdentifier.create(new YangInstanceIdentifier.NodeIdentifier(PatchCont.QNAME));
+ private static SchemaContext schemaContext;
+
private DataBroker dataBroker;
private DOMDataBroker domDataBroker;
+ private ControllerContext controllerContext;
+
+ @BeforeClass
+ public static void init() {
+ schemaContext = YangParserTestUtils.parseYangResource(
+ "/instanceidentifier/yang/instance-identifier-patch-module.yang");
+ }
@Before
public void setUp() throws Exception {
dataBroker = getDataBroker();
domDataBroker = getDomBroker();
- SchemaContext sc = YangParserTestUtils.parseYangResource(
- "/instanceidentifier/yang/instance-identifier-patch-module.yang");
- ControllerContext.getInstance().setGlobalSchema(sc);
+ controllerContext = TestRestconfUtils.newControllerContext(schemaContext);
}
class ListenerAdapterTester extends ListenerAdapter {
ListenerAdapterTester(final YangInstanceIdentifier path, final String streamName,
final NotificationOutputTypeGrouping.NotificationOutputType outputType,
final boolean leafNodesOnly) {
- super(path, streamName, outputType);
+ super(path, streamName, outputType, controllerContext);
setQueryParams(EPOCH, Optional.empty(), Optional.empty(), leafNodesOnly);
}
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
+import java.io.FileNotFoundException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import org.junit.Before;
+import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
+import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
public class NotificationListenerTest {
private static final QNameModule MODULE = QNameModule.create(URI.create("notifi:mod"), Revision.of("2016-11-23"));
- private SchemaContext schmeaCtx;
+ private static SchemaContext schemaContext;
+
+ private ControllerContext controllerContext;
+
+ @BeforeClass
+ public static void staticInit() throws FileNotFoundException {
+ schemaContext = TestUtils.loadSchemaContext("/notifications");
+ }
@Before
public void init() throws Exception {
MockitoAnnotations.initMocks(this);
- ControllerContext.getInstance().setGlobalSchema(TestUtils.loadSchemaContext("/notifications"));
- this.schmeaCtx = ControllerContext.getInstance().getGlobalSchema();
+ controllerContext = TestRestconfUtils.newControllerContext(schemaContext);
}
@Test
final List<SchemaPath> paths = new ArrayList<>();
paths.add(schemaPathNotifi);
final List<NotificationListenerAdapter> listNotifi =
- Notificator.createNotificationListener(paths, "stream-name", NotificationOutputType.JSON.toString());
+ Notificator.createNotificationListener(paths, "stream-name", NotificationOutputType.JSON.toString(),
+ controllerContext);
final NotificationListenerAdapter notifi = listNotifi.get(0);
notifi.setNotification(notificationData);
- notifi.setSchemaContext(this.schmeaCtx);
+ notifi.setSchemaContext(schemaContext);
final String result = notifi.prepareJson();
return Preconditions.checkNotNull(result);
}
{
- "cont": {
- "lflst1":[],
- "lflst2":[45]
- }
-}
\ No newline at end of file
+ "array-with-null-yang:cont": {
+ "lflst1":[],
+ "lflst2":[45]
+ }
+}
{
- "cont":{
- "lf1":"module<Name:value lf1",
- "lf2":"module>Name:value lf2"
- }
-}
\ No newline at end of file
+ "array-with-null-yang:cont":{
+ "lf1":"module<Name:value lf1",
+ "lf2":"module>Name:value lf2"
+ }
+}
{
- "multiple-items:lst":[
- {
- "lst1": [
- {
- "lf11":"lf11_1"
- },
- {
- "lflst11":[
- 45
- ]
- },
- {
- "cont11":{
- }
- },
- {
- "lst11":[
- {
- }
- ]
- }
- ]
- }
- ]
-}
\ No newline at end of file
+ "multiple-items-yang:lst":[
+ {
+ "lst1": [
+ {
+ "lf11":"lf11_1"
+ },
+ {
+ "lflst11":[
+ 45
+ ]
+ },
+ {
+ "cont11":{
+ }
+ },
+ {
+ "lst11":[
+ {
+ }
+ ]
+ }
+ ]
+ }
+ ]
+}
{
- "multiple-leaflist:lst": {
- "lflst1":[45,55,66]
- }
-}
\ No newline at end of file
+ "simple-list-yang1:lst": {
+ "lflst1":[45,55,66]
+ }
+}
{
- "cont":{
- "cont1":{
- },
- "lst1": [
- {
- }
- ],
- "lflst1":[
- "lflst1_1",
- "lflst1_2"
- ],
- "lf1":"lf1"
- }
-}
\ No newline at end of file
+ "simple-container-yang:cont":{
+ "cont1":{
+ },
+ "lst1": [
+ {
+ }
+ ],
+ "lflst1":[
+ "lflst1_1",
+ "lflst1_2"
+ ],
+ "lf1":"lf1"
+ }
+}
{
- "simple-list:lst":[
- {
- "cont1":{
- },
- "lst1": [
- {
- }
- ],
- "lflst1":[
- "lflst1_1",
- "lflst1_2"
- ],
- "lf1":"lf1"
- }
- ]
-}
\ No newline at end of file
+ "simple-list-yang1:lst":[
+ {
+ "cont1":{
+ },
+ "lst1": [
+ {
+ }
+ ],
+ "lflst1":[
+ "lflst1_1",
+ "lflst1_2"
+ ],
+ "lf1":"lf1"
+ }
+ ]
+}
{
-
- "cont":[
- {
- },
- {
- }
- ]
-}
\ No newline at end of file
+ "wrong":[
+ {
+ },
+ {
+ }
+ ]
+}
{
- "lst": {
- },
- "lst1":[
- {
- }
- ]
-}
\ No newline at end of file
+ "simple-list-yang1:lst": {
+ },
+ "lst1":[
+ {
+ }
+ ]
+}