Search in sources :

Example 1 with RestRequest

use of org.infinispan.rest.framework.RestRequest in project infinispan by infinispan.

the class ContainerResource method getAllCachesConfigurationTemplates.

private CompletionStage<RestResponse> getAllCachesConfigurationTemplates(RestRequest request) {
    NettyRestResponse.Builder responseBuilder = checkCacheManager(request);
    if (responseBuilder.getHttpStatus() == NOT_FOUND)
        return completedFuture(responseBuilder.build());
    EmbeddedCacheManager cacheManager = invocationHelper.getRestCacheManager().getInstance();
    EmbeddedCacheManager subjectCacheManager = cacheManager.withSubject(request.getSubject());
    Set<String> cacheConfigurationNames = subjectCacheManager.getCacheConfigurationNames();
    List<NamedCacheConfiguration> configurations = cacheConfigurationNames.stream().filter(n -> !internalCacheRegistry.isInternalCache(n)).filter(n -> SecurityActions.getCacheConfigurationFromManager(subjectCacheManager, n).isTemplate()).distinct().map(n -> {
        return getNamedCacheConfiguration(subjectCacheManager, n);
    }).sorted(Comparator.comparing(c -> c.name)).collect(Collectors.toList());
    return asJsonResponseFuture(Json.make(configurations), responseBuilder);
}
Also used : ConfigurationWriter(org.infinispan.commons.configuration.io.ConfigurationWriter) JsonSerialization(org.infinispan.commons.dataconversion.internal.JsonSerialization) InternalCacheRegistry(org.infinispan.registry.InternalCacheRegistry) ResourceHandler(org.infinispan.rest.framework.ResourceHandler) APPLICATION_XML(org.infinispan.commons.dataconversion.MediaType.APPLICATION_XML) ConfigurationBuilder(org.infinispan.configuration.cache.ConfigurationBuilder) NOT_FOUND(io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) GET(org.infinispan.rest.framework.Method.GET) GlobalConfiguration(org.infinispan.configuration.global.GlobalConfiguration) POST(org.infinispan.rest.framework.Method.POST) Cache(org.infinispan.Cache) ConfigurationChanged(org.infinispan.notifications.cachemanagerlistener.annotation.ConfigurationChanged) CompletableFutures(org.infinispan.util.concurrent.CompletableFutures) ConfigurationBuilderHolder(org.infinispan.configuration.parsing.ConfigurationBuilderHolder) Map(java.util.Map) ServerSentEvent(org.infinispan.rest.ServerSentEvent) RestRequest(org.infinispan.rest.framework.RestRequest) Listener(org.infinispan.notifications.Listener) NettyRestResponse(org.infinispan.rest.NettyRestResponse) AuthorizationPermission(org.infinispan.security.AuthorizationPermission) GlobalComponentRegistry(org.infinispan.factories.GlobalComponentRegistry) Set(java.util.Set) InvocationHelper(org.infinispan.rest.InvocationHelper) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) PrivilegedAction(java.security.PrivilegedAction) EventStream(org.infinispan.rest.EventStream) Collectors(java.util.stream.Collectors) ComponentStatus(org.infinispan.lifecycle.ComponentStatus) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) ResourceUtil.addEntityAsJson(org.infinispan.rest.resources.ResourceUtil.addEntityAsJson) LocalTopologyManager(org.infinispan.topology.LocalTopologyManager) OK(io.netty.handler.codec.http.HttpResponseStatus.OK) StringBuilderWriter(org.infinispan.commons.io.StringBuilderWriter) PersistenceManager(org.infinispan.persistence.manager.PersistenceManager) ByteArrayOutputStream(java.io.ByteArrayOutputStream) INTERNAL_SERVER_ERROR(io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR) CompletableFuture(java.util.concurrent.CompletableFuture) NO_CONTENT(io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT) HashSet(java.util.HashSet) MediaType(org.infinispan.commons.dataconversion.MediaType) RestCacheManager(org.infinispan.rest.cachemanager.RestCacheManager) ServerStateManager(org.infinispan.server.core.ServerStateManager) APPLICATION_YAML(org.infinispan.commons.dataconversion.MediaType.APPLICATION_YAML) HealthStatus(org.infinispan.health.HealthStatus) EmbeddedCacheManager(org.infinispan.manager.EmbeddedCacheManager) DELETE(org.infinispan.rest.framework.Method.DELETE) HEAD(org.infinispan.rest.framework.Method.HEAD) MediaTypeUtils.negotiateMediaType(org.infinispan.rest.resources.MediaTypeUtils.negotiateMediaType) ConfigurationChangedEvent(org.infinispan.notifications.cachemanagerlistener.event.ConfigurationChangedEvent) TEXT_EVENT_STREAM(org.infinispan.commons.dataconversion.MediaType.TEXT_EVENT_STREAM) Collections.emptyMap(java.util.Collections.emptyMap) Invocations(org.infinispan.rest.framework.impl.Invocations) Flowable(io.reactivex.rxjava3.core.Flowable) APPLICATION_JSON(org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON) UTF_8(java.nio.charset.StandardCharsets.UTF_8) StringWriter(java.io.StringWriter) ContentSource(org.infinispan.rest.framework.ContentSource) Json(org.infinispan.commons.dataconversion.internal.Json) TEXT_PLAIN(org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN) Security(org.infinispan.security.Security) BackupManager(org.infinispan.server.core.BackupManager) ResourceUtil.asJsonResponseFuture(org.infinispan.rest.resources.ResourceUtil.asJsonResponseFuture) Configuration(org.infinispan.configuration.cache.Configuration) ParserRegistry(org.infinispan.configuration.parsing.ParserRegistry) AuditContext(org.infinispan.security.AuditContext) ClusterHealth(org.infinispan.health.ClusterHealth) CacheHealth(org.infinispan.health.CacheHealth) RestResponse(org.infinispan.rest.framework.RestResponse) Comparator(java.util.Comparator) Collections(java.util.Collections) Health(org.infinispan.health.Health) EmbeddedCacheManager(org.infinispan.manager.EmbeddedCacheManager) NettyRestResponse(org.infinispan.rest.NettyRestResponse)

Example 2 with RestRequest

use of org.infinispan.rest.framework.RestRequest in project infinispan by infinispan.

the class MediaTypeUtils method negotiateMediaType.

/**
 * Negotiates the {@link MediaType} to be used during the request execution
 *
 * @param cache the {@link AdvancedCache} associated with the request
 * @param restRequest the {@link RestRequest} with the headers
 * @return The negotiated MediaType
 * @throws UnacceptableDataFormatException if no suitable {@link MediaType} could be found.
 */
static MediaType negotiateMediaType(AdvancedCache<?, ?> cache, EncoderRegistry registry, RestRequest restRequest) throws UnacceptableDataFormatException {
    try {
        String accept = restRequest.getAcceptHeader();
        MediaType storageMedia = cache.getValueDataConversion().getStorageMediaType();
        Optional<MediaType> negotiated = MediaType.parseList(accept).filter(media -> registry.isConversionSupported(storageMedia, media)).findFirst();
        return negotiated.map(m -> {
            if (!m.matchesAll())
                return m;
            MediaType storageMediaType = cache.getValueDataConversion().getStorageMediaType();
            if (storageMediaType == null)
                return m;
            if (storageMediaType.equals(MediaType.APPLICATION_OBJECT))
                return TEXT_PLAIN;
            if (storageMediaType.match(MediaType.APPLICATION_PROTOSTREAM))
                return APPLICATION_JSON;
            return m;
        }).orElseThrow(() -> Log.REST.unsupportedDataFormat(accept));
    } catch (EncodingException e) {
        throw new UnacceptableDataFormatException();
    }
}
Also used : Arrays(java.util.Arrays) MediaType(org.infinispan.commons.dataconversion.MediaType) AdvancedCache(org.infinispan.AdvancedCache) APPLICATION_JSON(org.infinispan.commons.dataconversion.MediaType.APPLICATION_JSON) EncodingException(org.infinispan.commons.dataconversion.EncodingException) Optional(java.util.Optional) UnacceptableDataFormatException(org.infinispan.rest.operations.exceptions.UnacceptableDataFormatException) EncoderRegistry(org.infinispan.marshall.core.EncoderRegistry) Log(org.infinispan.rest.logging.Log) RestRequest(org.infinispan.rest.framework.RestRequest) TEXT_PLAIN(org.infinispan.commons.dataconversion.MediaType.TEXT_PLAIN) UnacceptableDataFormatException(org.infinispan.rest.operations.exceptions.UnacceptableDataFormatException) EncodingException(org.infinispan.commons.dataconversion.EncodingException) MediaType(org.infinispan.commons.dataconversion.MediaType)

Example 3 with RestRequest

use of org.infinispan.rest.framework.RestRequest in project infinispan by infinispan.

the class ProtobufResource method createOrReplace.

private CompletionStage<RestResponse> createOrReplace(RestRequest request, boolean create) {
    String schemaName = checkMandatorySchemaName(request);
    ContentSource contents = request.contents();
    if (contents == null)
        throw new NoDataFoundException("Schema data not sent in the request");
    AdvancedCache<Object, Object> cache = invocationHelper.getRestCacheManager().getCache(ProtobufMetadataManager.PROTOBUF_METADATA_CACHE_NAME, request);
    NettyRestResponse.Builder builder = new NettyRestResponse.Builder();
    CompletableFuture<Object> putSchema;
    if (create) {
        putSchema = cache.putIfAbsentAsync(schemaName, contents.asString()).thenApply(result -> {
            if (result == null) {
                builder.status(HttpResponseStatus.CREATED);
            } else {
                builder.status(HttpResponseStatus.CONFLICT);
            }
            return result;
        });
    } else {
        putSchema = cache.putAsync(schemaName, contents.asString()).thenApply(result -> builder.status(HttpResponseStatus.OK));
    }
    return putSchema.thenCompose(r -> {
        if (isOkOrCreated(builder)) {
            return cache.getAsync(schemaName + ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX);
        } else {
            return CompletableFutures.completedNull();
        }
    }).thenApply(validationError -> {
        if (isOkOrCreated(builder)) {
            ProtoSchema protoSchema = new ProtoSchema();
            protoSchema.name = schemaName;
            if (validationError != null) {
                protoSchema.error = createErrorContent(schemaName, (String) validationError);
            }
            addEntityAsJson(protoSchema, builder);
        }
        return builder.build();
    });
}
Also used : PUT(org.infinispan.rest.framework.Method.PUT) JsonSerialization(org.infinispan.commons.dataconversion.internal.JsonSerialization) InternalCacheEntry(org.infinispan.container.entries.InternalCacheEntry) ResourceHandler(org.infinispan.rest.framework.ResourceHandler) GET(org.infinispan.rest.framework.Method.GET) NoDataFoundException(org.infinispan.rest.operations.exceptions.NoDataFoundException) CompletableFuture(java.util.concurrent.CompletableFuture) POST(org.infinispan.rest.framework.Method.POST) Function(java.util.function.Function) MediaType(org.infinispan.commons.dataconversion.MediaType) RestCacheManager(org.infinispan.rest.cachemanager.RestCacheManager) AdvancedCache(org.infinispan.AdvancedCache) CompletableFutures(org.infinispan.util.concurrent.CompletableFutures) DELETE(org.infinispan.rest.framework.Method.DELETE) ResourceUtil.asJsonResponse(org.infinispan.rest.resources.ResourceUtil.asJsonResponse) RestRequest(org.infinispan.rest.framework.RestRequest) NoKeyException(org.infinispan.rest.operations.exceptions.NoKeyException) Invocations(org.infinispan.rest.framework.impl.Invocations) Flowable(io.reactivex.rxjava3.core.Flowable) NettyRestResponse(org.infinispan.rest.NettyRestResponse) AuthorizationPermission(org.infinispan.security.AuthorizationPermission) ContentSource(org.infinispan.rest.framework.ContentSource) ProtobufMetadataManager(org.infinispan.query.remote.ProtobufMetadataManager) InvocationHelper(org.infinispan.rest.InvocationHelper) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) Json(org.infinispan.commons.dataconversion.internal.Json) Collectors(java.util.stream.Collectors) ProtobufMetadataManagerConstants(org.infinispan.query.remote.client.ProtobufMetadataManagerConstants) CompletionStage(java.util.concurrent.CompletionStage) ResourceUtil.addEntityAsJson(org.infinispan.rest.resources.ResourceUtil.addEntityAsJson) AuditContext(org.infinispan.security.AuditContext) RestResponse(org.infinispan.rest.framework.RestResponse) Comparator(java.util.Comparator) ContentSource(org.infinispan.rest.framework.ContentSource) NoDataFoundException(org.infinispan.rest.operations.exceptions.NoDataFoundException) NettyRestResponse(org.infinispan.rest.NettyRestResponse)

Example 4 with RestRequest

use of org.infinispan.rest.framework.RestRequest in project infinispan by infinispan.

the class SearchAdminResource method runIndexer.

private CompletionStage<RestResponse> runIndexer(RestRequest request, Function<Indexer, CompletionStage<Void>> op, boolean supportAsync) {
    NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder();
    List<String> mode = request.parameters().get("mode");
    boolean asyncParams = mode != null && !mode.isEmpty() && mode.iterator().next().equalsIgnoreCase("async");
    boolean async = asyncParams && supportAsync;
    AdvancedCache<?, ?> cache = lookupIndexedCache(request, responseBuilder);
    int status = responseBuilder.getStatus();
    if (status < OK.code() || status >= MULTIPLE_CHOICES.code()) {
        return completedFuture(responseBuilder.build());
    }
    responseBuilder.status(NO_CONTENT);
    Indexer indexer = ComponentRegistryUtils.getIndexer(cache);
    if (async) {
        try {
            LOG.asyncMassIndexerStarted();
            op.apply(indexer).whenComplete((v, e) -> {
                if (e == null) {
                    LOG.asyncMassIndexerSuccess();
                } else {
                    LOG.errorExecutingMassIndexer(e.getCause());
                }
            });
        } catch (Exception e) {
            responseBuilder.status(INTERNAL_SERVER_ERROR).entity("Error executing the MassIndexer " + e.getCause());
        }
        return CompletableFuture.completedFuture(responseBuilder.build());
    }
    return op.apply(indexer).exceptionally(e -> {
        if (e instanceof MassIndexerAlreadyStartedException) {
            responseBuilder.status(BAD_REQUEST).entity("MassIndexer already started");
        } else {
            responseBuilder.status(INTERNAL_SERVER_ERROR).entity("Error executing the MassIndexer " + e.getCause());
        }
        return null;
    }).thenApply(v -> responseBuilder.build());
}
Also used : SearchStatisticsSnapshot(org.infinispan.query.core.stats.SearchStatisticsSnapshot) ResourceHandler(org.infinispan.rest.framework.ResourceHandler) LogFactory(org.infinispan.util.logging.LogFactory) INTERNAL_SERVER_ERROR(io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR) NOT_FOUND(io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) GET(org.infinispan.rest.framework.Method.GET) CompletableFuture(java.util.concurrent.CompletableFuture) POST(org.infinispan.rest.framework.Method.POST) MULTIPLE_CHOICES(io.netty.handler.codec.http.HttpResponseStatus.MULTIPLE_CHOICES) Function(java.util.function.Function) BAD_REQUEST(io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST) NO_CONTENT(io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT) Indexer(org.infinispan.query.Indexer) AdvancedCache(org.infinispan.AdvancedCache) ResourceUtil.asJsonResponse(org.infinispan.rest.resources.ResourceUtil.asJsonResponse) InfinispanQueryStatisticsInfo(org.infinispan.query.impl.InfinispanQueryStatisticsInfo) Log(org.infinispan.rest.logging.Log) RestRequest(org.infinispan.rest.framework.RestRequest) Invocations(org.infinispan.rest.framework.impl.Invocations) CacheException(org.infinispan.commons.CacheException) MassIndexerAlreadyStartedException(org.infinispan.query.impl.massindex.MassIndexerAlreadyStartedException) NettyRestResponse(org.infinispan.rest.NettyRestResponse) InvocationHelper(org.infinispan.rest.InvocationHelper) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) SearchStatistics(org.infinispan.query.core.stats.SearchStatistics) Security(org.infinispan.security.Security) ResourceUtil.asJsonResponseFuture(org.infinispan.rest.resources.ResourceUtil.asJsonResponseFuture) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) Configuration(org.infinispan.configuration.cache.Configuration) RestResponse(org.infinispan.rest.framework.RestResponse) ComponentRegistryUtils(org.infinispan.query.impl.ComponentRegistryUtils) OK(io.netty.handler.codec.http.HttpResponseStatus.OK) Search(org.infinispan.query.Search) Indexer(org.infinispan.query.Indexer) MassIndexerAlreadyStartedException(org.infinispan.query.impl.massindex.MassIndexerAlreadyStartedException) NettyRestResponse(org.infinispan.rest.NettyRestResponse) CacheException(org.infinispan.commons.CacheException) MassIndexerAlreadyStartedException(org.infinispan.query.impl.massindex.MassIndexerAlreadyStartedException)

Example 5 with RestRequest

use of org.infinispan.rest.framework.RestRequest in project infinispan by infinispan.

the class XSiteResource method statusOperation.

private <T> CompletionStage<RestResponse> statusOperation(RestRequest request, Function<XSiteAdminOperations, T> op) {
    NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder();
    Optional<XSiteAdminOperations> xsiteAdmin = getXSiteAdmin(request, responseBuilder);
    return xsiteAdmin.<CompletionStage<RestResponse>>map(ops -> supplyAsync(() -> {
        T result = Security.doAs(request.getSubject(), (PrivilegedAction<T>) () -> op.apply(ops));
        return addEntityAsJson(Json.make(result), responseBuilder).build();
    }, invocationHelper.getExecutor())).orElseGet(() -> completedFuture(responseBuilder.build()));
}
Also used : PUT(org.infinispan.rest.framework.Method.PUT) JsonSerialization(org.infinispan.commons.dataconversion.internal.JsonSerialization) AbstractMixedSiteStatus(org.infinispan.xsite.status.AbstractMixedSiteStatus) OnlineSiteStatus(org.infinispan.xsite.status.OnlineSiteStatus) ResourceHandler(org.infinispan.rest.framework.ResourceHandler) ContainerMixedSiteStatus(org.infinispan.xsite.status.ContainerMixedSiteStatus) INTERNAL_SERVER_ERROR(io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR) NOT_FOUND(io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) BiFunction(java.util.function.BiFunction) GET(org.infinispan.rest.framework.Method.GET) TakeOfflineConfiguration(org.infinispan.configuration.cache.TakeOfflineConfiguration) POST(org.infinispan.rest.framework.Method.POST) Cache(org.infinispan.Cache) Function(java.util.function.Function) BAD_REQUEST(io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST) NO_CONTENT(io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT) MediaType(org.infinispan.commons.dataconversion.MediaType) EmbeddedCacheManager(org.infinispan.manager.EmbeddedCacheManager) CompletableFuture.supplyAsync(java.util.concurrent.CompletableFuture.supplyAsync) Map(java.util.Map) RestRequest(org.infinispan.rest.framework.RestRequest) Address(org.infinispan.remoting.transport.Address) Invocations(org.infinispan.rest.framework.impl.Invocations) NettyRestResponse(org.infinispan.rest.NettyRestResponse) XSiteAdminOperations(org.infinispan.xsite.XSiteAdminOperations) AuthorizationPermission(org.infinispan.security.AuthorizationPermission) SiteStatus(org.infinispan.xsite.status.SiteStatus) Util(org.infinispan.commons.util.Util) InvocationHelper(org.infinispan.rest.InvocationHelper) Json(org.infinispan.commons.dataconversion.internal.Json) PrivilegedAction(java.security.PrivilegedAction) Collectors(java.util.stream.Collectors) OfflineSiteStatus(org.infinispan.xsite.status.OfflineSiteStatus) Security(org.infinispan.security.Security) JsonUtils(org.infinispan.commons.dataconversion.internal.JsonUtils) NOT_MODIFIED(io.netty.handler.codec.http.HttpResponseStatus.NOT_MODIFIED) CompletionStage(java.util.concurrent.CompletionStage) ResourceUtil.addEntityAsJson(org.infinispan.rest.resources.ResourceUtil.addEntityAsJson) AuditContext(org.infinispan.security.AuditContext) Entry(java.util.Map.Entry) Optional(java.util.Optional) RestResponse(org.infinispan.rest.framework.RestResponse) GlobalXSiteAdminOperations(org.infinispan.xsite.GlobalXSiteAdminOperations) OK(io.netty.handler.codec.http.HttpResponseStatus.OK) PUT(org.infinispan.rest.framework.Method.PUT) GET(org.infinispan.rest.framework.Method.GET) POST(org.infinispan.rest.framework.Method.POST) BAD_REQUEST(io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST) NO_CONTENT(io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT) NettyRestResponse(org.infinispan.rest.NettyRestResponse) RestResponse(org.infinispan.rest.framework.RestResponse) XSiteAdminOperations(org.infinispan.xsite.XSiteAdminOperations) GlobalXSiteAdminOperations(org.infinispan.xsite.GlobalXSiteAdminOperations) NettyRestResponse(org.infinispan.rest.NettyRestResponse)

Aggregations

RestRequest (org.infinispan.rest.framework.RestRequest)8 CompletionStage (java.util.concurrent.CompletionStage)7 InvocationHelper (org.infinispan.rest.InvocationHelper)7 NettyRestResponse (org.infinispan.rest.NettyRestResponse)7 GET (org.infinispan.rest.framework.Method.GET)7 POST (org.infinispan.rest.framework.Method.POST)7 ResourceHandler (org.infinispan.rest.framework.ResourceHandler)7 RestResponse (org.infinispan.rest.framework.RestResponse)7 Invocations (org.infinispan.rest.framework.impl.Invocations)7 HttpResponseStatus (io.netty.handler.codec.http.HttpResponseStatus)6 NO_CONTENT (io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT)6 CompletableFuture (java.util.concurrent.CompletableFuture)6 CompletableFuture.completedFuture (java.util.concurrent.CompletableFuture.completedFuture)6 Collectors (java.util.stream.Collectors)6 Json (org.infinispan.commons.dataconversion.internal.Json)6 AuditContext (org.infinispan.security.AuditContext)6 AuthorizationPermission (org.infinispan.security.AuthorizationPermission)6 List (java.util.List)5 MediaType (org.infinispan.commons.dataconversion.MediaType)5 Configuration (org.infinispan.configuration.cache.Configuration)5