Search in sources :

Example 31 with Scope

use of org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.CreateDataChangeEventSubscriptionInput1.Scope in project gravitee-access-management by gravitee-io.

the class ScopesResource method create.

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Create a scope", notes = "User must have the DOMAIN_SCOPE[CREATE] permission on the specified domain " + "or DOMAIN_SCOPE[CREATE] permission on the specified environment " + "or DOMAIN_SCOPE[CREATE] permission on the specified organization")
@ApiResponses({ @ApiResponse(code = 201, message = "Scope successfully created"), @ApiResponse(code = 500, message = "Internal server error") })
public void create(@PathParam("organizationId") String organizationId, @PathParam("environmentId") String environmentId, @PathParam("domain") String domain, @ApiParam(name = "scope", required = true) @Valid @NotNull final NewScope newScope, @Suspended final AsyncResponse response) {
    final User authenticatedUser = getAuthenticatedUser();
    checkAnyPermission(organizationId, environmentId, domain, Permission.DOMAIN_SCOPE, Acl.CREATE).andThen(domainService.findById(domain).switchIfEmpty(Maybe.error(new DomainNotFoundException(domain))).flatMapSingle(irrelevant -> scopeService.create(domain, newScope, authenticatedUser).map(scope -> Response.created(URI.create("/organizations/" + organizationId + "/environments/" + environmentId + "/domains/" + domain + "/scopes/" + scope.getId())).entity(scope).build()))).subscribe(response::resume, response::resume);
}
Also used : Permission(io.gravitee.am.model.permissions.Permission) Maybe(io.reactivex.Maybe) DomainService(io.gravitee.am.service.DomainService) Autowired(org.springframework.beans.factory.annotation.Autowired) AbstractResource(io.gravitee.am.management.handlers.management.api.resources.AbstractResource) NewScope(io.gravitee.am.service.model.NewScope) Valid(javax.validation.Valid) Acl(io.gravitee.am.model.Acl) User(io.gravitee.am.identityprovider.api.User) ScopeService(io.gravitee.am.service.ScopeService) ReferenceType(io.gravitee.am.model.ReferenceType) Observable(io.reactivex.Observable) io.swagger.annotations(io.swagger.annotations) URI(java.net.URI) Scope(io.gravitee.am.model.oauth2.Scope) Page(io.gravitee.am.model.common.Page) Context(javax.ws.rs.core.Context) AsyncResponse(javax.ws.rs.container.AsyncResponse) DomainNotFoundException(io.gravitee.am.service.exception.DomainNotFoundException) NotNull(javax.validation.constraints.NotNull) Suspended(javax.ws.rs.container.Suspended) Collectors(java.util.stream.Collectors) List(java.util.List) MediaType(io.gravitee.common.http.MediaType) javax.ws.rs(javax.ws.rs) Response(javax.ws.rs.core.Response) ResourceContext(javax.ws.rs.container.ResourceContext) Comparator(java.util.Comparator) User(io.gravitee.am.identityprovider.api.User) DomainNotFoundException(io.gravitee.am.service.exception.DomainNotFoundException)

Example 32 with Scope

use of org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.CreateDataChangeEventSubscriptionInput1.Scope in project netconf by opendaylight.

the class RestconfImpl method invokeSalRemoteRpcSubscribeRPC.

private ListenableFuture<DOMRpcResult> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
    final ContainerNode value = (ContainerNode) payload.getData();
    final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
    final Optional<DataContainerChild> path = value.findChildByArg(new NodeIdentifier(QName.create(rpcQName, "path")));
    final Object pathValue = path.isPresent() ? path.get().body() : null;
    if (!(pathValue instanceof YangInstanceIdentifier)) {
        LOG.debug("Instance identifier {} was not normalized correctly", rpcQName);
        throw new RestconfDocumentedException("Instance identifier was not normalized correctly", ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
    }
    final YangInstanceIdentifier pathIdentifier = (YangInstanceIdentifier) pathValue;
    String streamName = (String) CREATE_DATA_SUBSCR;
    NotificationOutputType outputType = null;
    if (!pathIdentifier.isEmpty()) {
        final String fullRestconfIdentifier = DATA_SUBSCR + controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
        LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
        datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
        Scope scope = parseEnumTypeParameter(value, Scope.class, SCOPE_PARAM_NAME);
        scope = scope == null ? Scope.BASE : scope;
        outputType = parseEnumTypeParameter(value, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
        outputType = outputType == null ? NotificationOutputType.XML : outputType;
        streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore + "/scope=" + scope);
    }
    if (Strings.isNullOrEmpty(streamName)) {
        LOG.debug("Path is empty or contains value node which is not Container or List built-in type at {}", pathIdentifier);
        throw new RestconfDocumentedException("Path is empty or contains value node which is not Container or List " + "built-in type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
    }
    final QName outputQname = QName.create(rpcQName, "output");
    final QName streamNameQname = QName.create(rpcQName, "stream-name");
    final ContainerNode output = ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname)).withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
    if (!Notificator.existListenerFor(streamName)) {
        Notificator.createListener(pathIdentifier, streamName, outputType, controllerContext);
    }
    return Futures.immediateFuture(new DefaultDOMRpcResult(output));
}
Also used : DefaultDOMRpcResult(org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult) RestconfDocumentedException(org.opendaylight.restconf.common.errors.RestconfDocumentedException) QName(org.opendaylight.yangtools.yang.common.QName) NotificationOutputType(org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier) Scope(org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.CreateDataChangeEventSubscriptionInput1.Scope) DataContainerChild(org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild) NodeIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier) ContainerNode(org.opendaylight.yangtools.yang.data.api.schema.ContainerNode) LogicalDatastoreType(org.opendaylight.mdsal.common.api.LogicalDatastoreType)

Example 33 with Scope

use of org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.CreateDataChangeEventSubscriptionInput1.Scope in project netconf by opendaylight.

the class RestconfImpl method dataSubs.

/**
 * Register data change listener by stream name.
 *
 * @param identifier
 *            stream name
 * @param uriInfo
 *            uri info
 * @param stop
 *            start-time of getting notification
 * @param start
 *            stop-time of getting notification
 * @param filter
 *            indicate which subset of all possible events are of interest
 * @return {@link URI} of location
 */
private URI dataSubs(final String identifier, final UriInfo uriInfo, final Instant start, final Instant stop, final String filter, final boolean leafNodesOnly, final boolean skipNotificationData) {
    final String streamName = Notificator.createStreamNameFromUri(identifier);
    if (Strings.isNullOrEmpty(streamName)) {
        throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
    }
    final ListenerAdapter listener = Notificator.getListenerFor(streamName);
    if (listener == null) {
        throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
    }
    listener.setQueryParams(start, Optional.ofNullable(stop), Optional.ofNullable(filter), leafNodesOnly, skipNotificationData);
    final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
    final LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class, paramToValues.get(DATASTORE_PARAM_NAME));
    if (datastore == null) {
        throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)", ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
    }
    final Scope scope = parserURIEnumParameter(Scope.class, paramToValues.get(SCOPE_PARAM_NAME));
    if (scope == null) {
        throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)", ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
    }
    broker.registerToListenDataChanges(datastore, scope, listener);
    final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
    final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance(NOTIFICATION_PORT);
    final int notificationPort = webSocketServerInstance.getPort();
    final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme(getWsScheme(uriInfo));
    return uriToWebsocketServerBuilder.replacePath(streamName).build();
}
Also used : ListenerAdapter(org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter) NotificationListenerAdapter(org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter) RestconfDocumentedException(org.opendaylight.restconf.common.errors.RestconfDocumentedException) Scope(org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.CreateDataChangeEventSubscriptionInput1.Scope) WebSocketServer(org.opendaylight.netconf.sal.streams.websockets.WebSocketServer) LogicalDatastoreType(org.opendaylight.mdsal.common.api.LogicalDatastoreType) UriBuilder(javax.ws.rs.core.UriBuilder) DOMMountPoint(org.opendaylight.mdsal.dom.api.DOMMountPoint)

Example 34 with Scope

use of org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.CreateDataChangeEventSubscriptionInput1.Scope in project netconf by opendaylight.

the class CreateStreamUtil method prepareDataChangeNotifiStreamName.

/**
 * Prepare stream name.
 *
 * @param path          Path of element from which data-change-event notifications are going to be generated.
 * @param schemaContext Schema context.
 * @param data          Container with stream settings (RPC create-stream).
 * @return Parsed stream name.
 */
private static String prepareDataChangeNotifiStreamName(final YangInstanceIdentifier path, final EffectiveModelContext schemaContext, final ContainerNode data) {
    final String datastoreName = extractStringLeaf(data, DATASTORE_NODEID);
    final LogicalDatastoreType datastoreType = datastoreName != null ? LogicalDatastoreType.valueOf(datastoreName) : LogicalDatastoreType.CONFIGURATION;
    final String scopeName = extractStringLeaf(data, SCOPE_NODEID);
    // FIXME: this is not really used
    final Scope scope = scopeName != null ? Scope.forName(scopeName).orElseThrow() : Scope.BASE;
    return RestconfStreamsConstants.DATA_SUBSCRIPTION + "/" + ListenersBroker.createStreamNameFromUri(IdentifierCodec.serialize(path, schemaContext) + "/" + RestconfStreamsConstants.DATASTORE_PARAM_NAME + "=" + datastoreType + "/" + RestconfStreamsConstants.SCOPE_PARAM_NAME + "=" + scope);
}
Also used : Scope(org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.CreateDataChangeEventSubscriptionInput1.Scope) LogicalDatastoreType(org.opendaylight.mdsal.common.api.LogicalDatastoreType)

Example 35 with Scope

use of org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.CreateDataChangeEventSubscriptionInput1.Scope in project netconf by opendaylight.

the class CreateStreamUtil method createDataChangeNotifiStream.

/**
 * Create data-change-event or notification stream with POST operation via RPC.
 *
 * @param payload      Input of RPC - example in JSON (data-change-event stream):
 *                     <pre>
 *                     {@code
 *                         {
 *                             "input": {
 *                                 "path": "/toaster:toaster/toaster:toasterStatus",
 *                                 "sal-remote-augment:datastore": "OPERATIONAL",
 *                                 "sal-remote-augment:scope": "ONE"
 *                             }
 *                         }
 *                     }
 *                     </pre>
 * @param refSchemaCtx Reference to {@link EffectiveModelContext}.
 * @return {@link DOMRpcResult} - Output of RPC - example in JSON:
 *     <pre>
 *     {@code
 *         {
 *             "output": {
 *                 "stream-name": "toaster:toaster/toaster:toasterStatus/datastore=OPERATIONAL/scope=ONE"
 *             }
 *         }
 *     }
 *     </pre>
 */
static DOMRpcResult createDataChangeNotifiStream(final NormalizedNodePayload payload, final EffectiveModelContext refSchemaCtx) {
    // parsing out of container with settings and path
    final ContainerNode data = (ContainerNode) requireNonNull(payload).getData();
    final QName qname = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
    final YangInstanceIdentifier path = preparePath(data, qname);
    // building of stream name
    final StringBuilder streamNameBuilder = new StringBuilder(prepareDataChangeNotifiStreamName(path, requireNonNull(refSchemaCtx), data));
    final NotificationOutputType outputType = prepareOutputType(data);
    if (outputType.equals(NotificationOutputType.JSON)) {
        streamNameBuilder.append('/').append(outputType.getName());
    }
    final String streamName = streamNameBuilder.toString();
    // registration of the listener
    ListenersBroker.getInstance().registerDataChangeListener(path, streamName, outputType);
    // building of output
    final QName outputQname = QName.create(qname, "output");
    final QName streamNameQname = QName.create(qname, "stream-name");
    final ContainerNode output = ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname)).withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
    return new DefaultDOMRpcResult(output);
}
Also used : DefaultDOMRpcResult(org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult) QName(org.opendaylight.yangtools.yang.common.QName) NodeIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier) ContainerNode(org.opendaylight.yangtools.yang.data.api.schema.ContainerNode) NotificationOutputType(org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier)

Aggregations

Scope (io.gravitee.am.model.oauth2.Scope)63 Test (org.junit.Test)43 TestObserver (io.reactivex.observers.TestObserver)25 Event (io.gravitee.am.model.common.event.Event)16 Page (io.gravitee.am.model.common.Page)15 Domain (io.gravitee.am.model.Domain)10 NewScope (io.gravitee.am.service.model.NewScope)9 Autowired (org.springframework.beans.factory.annotation.Autowired)9 AbstractManagementTest (io.gravitee.am.repository.management.AbstractManagementTest)8 Maybe (io.reactivex.Maybe)8 Single (io.reactivex.Single)8 RandomString (io.gravitee.am.common.utils.RandomString)7 ScopeRepository (io.gravitee.am.repository.management.api.ScopeRepository)7 Completable (io.reactivex.Completable)7 JerseySpringTest (io.gravitee.am.management.handlers.management.api.JerseySpringTest)6 ApplicationOAuthSettings (io.gravitee.am.model.application.ApplicationOAuthSettings)6 Observable (io.reactivex.Observable)6 User (io.gravitee.am.identityprovider.api.User)5 ReferenceType (io.gravitee.am.model.ReferenceType)5 ApplicationScopeSettings (io.gravitee.am.model.application.ApplicationScopeSettings)5