Search in sources :

Example 51 with MediaType

use of org.infinispan.commons.dataconversion.MediaType in project infinispan by infinispan.

the class CacheResourceV2 method createOrUpdate.

private CompletableFuture<RestResponse> createOrUpdate(RestRequest request) {
    NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder();
    List<String> template = request.parameters().get("template");
    String cacheName = request.variables().get("cacheName");
    EnumSet<AdminFlag> adminFlags = request.getAdminFlags();
    if (request.method() == PUT) {
        if (adminFlags == null) {
            adminFlags = EnumSet.of(AdminFlag.UPDATE);
        } else {
            adminFlags.add(AdminFlag.UPDATE);
        }
    }
    EmbeddedCacheManagerAdmin initialAdmin = invocationHelper.getRestCacheManager().getCacheManagerAdmin(request);
    EmbeddedCacheManagerAdmin administration = adminFlags == null ? initialAdmin : initialAdmin.withFlags(adminFlags);
    if (template != null && !template.isEmpty()) {
        if (request.method() == PUT) {
            return CompletableFuture.completedFuture(responseBuilder.status(BAD_REQUEST).build());
        }
        String templateName = template.iterator().next();
        return CompletableFuture.supplyAsync(() -> {
            administration.createCache(cacheName, templateName);
            responseBuilder.status(OK);
            return responseBuilder.build();
        }, invocationHelper.getExecutor());
    }
    ContentSource contents = request.contents();
    byte[] bytes = contents.rawContent();
    if (bytes == null || bytes.length == 0) {
        if (request.method() == PUT) {
            return CompletableFuture.completedFuture(responseBuilder.status(BAD_REQUEST).build());
        }
        return CompletableFuture.supplyAsync(() -> {
            administration.createCache(cacheName, (String) null);
            responseBuilder.status(OK);
            return responseBuilder.build();
        }, invocationHelper.getExecutor());
    }
    MediaType sourceType = request.contentType() == null ? APPLICATION_JSON : request.contentType();
    if (!sourceType.match(APPLICATION_JSON) && !sourceType.match(APPLICATION_XML) && !sourceType.match(APPLICATION_YAML)) {
        responseBuilder.status(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE);
        return CompletableFuture.completedFuture(responseBuilder.build());
    }
    return CompletableFuture.supplyAsync(() -> {
        try {
            ConfigurationBuilderHolder holder = invocationHelper.getParserRegistry().parse(new String(bytes, UTF_8), sourceType);
            ConfigurationBuilder cfgBuilder = holder.getCurrentConfigurationBuilder() != null ? holder.getCurrentConfigurationBuilder() : new ConfigurationBuilder();
            if (request.method() == PUT) {
                administration.getOrCreateCache(cacheName, cfgBuilder.build());
            } else {
                administration.createCache(cacheName, cfgBuilder.build());
            }
            responseBuilder.status(OK);
        } catch (Throwable t) {
            responseBuilder.status(BAD_REQUEST).entity(t.getMessage());
        }
        return responseBuilder.build();
    }, invocationHelper.getExecutor());
}
Also used : ConfigurationBuilder(org.infinispan.configuration.cache.ConfigurationBuilder) AdminFlag(org.infinispan.commons.api.CacheContainerAdmin.AdminFlag) ConfigurationBuilder(org.infinispan.configuration.cache.ConfigurationBuilder) NettyRestResponse(org.infinispan.rest.NettyRestResponse) ContentSource(org.infinispan.rest.framework.ContentSource) ConfigurationBuilderHolder(org.infinispan.configuration.parsing.ConfigurationBuilderHolder) MediaType(org.infinispan.commons.dataconversion.MediaType) MediaTypeUtils.negotiateMediaType(org.infinispan.rest.resources.MediaTypeUtils.negotiateMediaType) EmbeddedCacheManagerAdmin(org.infinispan.manager.EmbeddedCacheManagerAdmin)

Example 52 with MediaType

use of org.infinispan.commons.dataconversion.MediaType in project infinispan by infinispan.

the class ServerResource method config.

private CompletionStage<RestResponse> config(RestRequest request) {
    NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder();
    MediaType accept = negotiateMediaType(request, APPLICATION_JSON, APPLICATION_XML, APPLICATION_YAML);
    responseBuilder.contentType(accept);
    StringBuilderWriter sw = new StringBuilderWriter();
    try (ConfigurationWriter w = ConfigurationWriter.to(sw).withType(accept).prettyPrint(false).build()) {
        invocationHelper.getServer().serializeConfiguration(w);
    }
    responseBuilder.entity(sw.toString());
    return CompletableFuture.completedFuture(responseBuilder.build());
}
Also used : StringBuilderWriter(org.infinispan.commons.io.StringBuilderWriter) ConfigurationWriter(org.infinispan.commons.configuration.io.ConfigurationWriter) MediaType(org.infinispan.commons.dataconversion.MediaType) MediaTypeUtils.negotiateMediaType(org.infinispan.rest.resources.MediaTypeUtils.negotiateMediaType) NettyRestResponse(org.infinispan.rest.NettyRestResponse)

Example 53 with MediaType

use of org.infinispan.commons.dataconversion.MediaType in project infinispan by infinispan.

the class BaseCacheResource method getCacheValue.

CompletionStage<RestResponse> getCacheValue(RestRequest request) throws RestResponseException {
    String cacheName = request.variables().get("cacheName");
    MediaType keyContentType = request.keyContentType();
    AdvancedCache<?, ?> cache = invocationHelper.getRestCacheManager().getCache(cacheName, request);
    MediaType requestedMediaType = negotiateMediaType(cache, invocationHelper.getEncoderRegistry(), request);
    Object key = getKey(request);
    String cacheControl = request.getCacheControlHeader();
    boolean returnBody = request.method() == GET;
    RestCacheManager<Object> restCacheManager = invocationHelper.getRestCacheManager();
    return restCacheManager.getInternalEntry(cacheName, key, keyContentType, requestedMediaType, request).thenApply(entry -> {
        NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder();
        responseBuilder.status(HttpResponseStatus.NOT_FOUND);
        if (entry instanceof InternalCacheEntry) {
            InternalCacheEntry<Object, Object> ice = (InternalCacheEntry<Object, Object>) entry;
            Long lastMod = CacheOperationsHelper.lastModified(ice);
            Date expires = ice.canExpire() ? new Date(ice.getExpiryTime()) : null;
            OptionalInt minFreshSeconds = CacheOperationsHelper.minFresh(cacheControl);
            if (CacheOperationsHelper.entryFreshEnough(expires, minFreshSeconds)) {
                Metadata meta = ice.getMetadata();
                String etag = calcETAG(ice.getValue());
                String ifNoneMatch = request.getEtagIfNoneMatchHeader();
                String ifMatch = request.getEtagIfMatchHeader();
                String ifUnmodifiedSince = request.getIfUnmodifiedSinceHeader();
                String ifModifiedSince = request.getIfModifiedSinceHeader();
                if (ifNoneMatch != null && ifNoneMatch.equals(etag)) {
                    return responseBuilder.status(HttpResponseStatus.NOT_MODIFIED).build();
                }
                if (ifMatch != null && !ifMatch.equals(etag)) {
                    return responseBuilder.status(HttpResponseStatus.PRECONDITION_FAILED).build();
                }
                if (DateUtils.ifUnmodifiedIsBeforeModificationDate(ifUnmodifiedSince, lastMod)) {
                    return responseBuilder.status(HttpResponseStatus.PRECONDITION_FAILED).build();
                }
                if (DateUtils.isNotModifiedSince(ifModifiedSince, lastMod)) {
                    return responseBuilder.status(HttpResponseStatus.NOT_MODIFIED).build();
                }
                Object value = ice.getValue();
                MediaType configuredMediaType = restCacheManager.getValueConfiguredFormat(cacheName, request);
                writeValue(value, requestedMediaType, configuredMediaType, responseBuilder, returnBody);
                responseBuilder.status(HttpResponseStatus.OK).lastModified(lastMod).eTag(etag).cacheControl(CacheOperationsHelper.calcCacheControl(expires)).expires(expires).timeToLive(meta.lifespan()).maxIdle(meta.maxIdle()).created(ice.getCreated()).lastUsed(ice.getLastUsed());
                List<String> extended = request.parameters().get(EXTENDED_HEADER.getValue());
                RestServerConfiguration restServerConfiguration = invocationHelper.getConfiguration();
                if (extended != null && extended.size() > 0 && CacheOperationsHelper.supportsExtendedHeaders(restServerConfiguration, extended.iterator().next())) {
                    responseBuilder.clusterPrimaryOwner(restCacheManager.getPrimaryOwner(cacheName, key, request)).clusterBackupOwners(restCacheManager.getBackupOwners(cacheName, key, request)).clusterNodeName(restCacheManager.getNodeName()).clusterServerAddress(restCacheManager.getServerAddress());
                }
            }
        }
        return responseBuilder.build();
    });
}
Also used : Metadata(org.infinispan.metadata.Metadata) OptionalInt(java.util.OptionalInt) NettyRestResponse(org.infinispan.rest.NettyRestResponse) Date(java.util.Date) InternalCacheEntry(org.infinispan.container.entries.InternalCacheEntry) MediaType(org.infinispan.commons.dataconversion.MediaType) MediaTypeUtils.negotiateMediaType(org.infinispan.rest.resources.MediaTypeUtils.negotiateMediaType) RestServerConfiguration(org.infinispan.rest.configuration.RestServerConfiguration)

Example 54 with MediaType

use of org.infinispan.commons.dataconversion.MediaType in project infinispan by infinispan.

the class ServerTaskEngine method invokeTask.

private <T> CompletableFuture<T> invokeTask(TaskContext context, ServerTaskWrapper<T> task) {
    ServerTaskRunner runner;
    switch(task.getExecutionMode()) {
        case ONE_NODE:
            runner = localRunner;
            break;
        default:
            runner = distributedRunner;
            break;
    }
    launderParameters(context);
    MediaType requestMediaType = context.getCache().map(c -> c.getAdvancedCache().getValueDataConversion().getRequestMediaType()).orElse(MediaType.MATCH_ALL);
    context.getCache().ifPresent(c -> context.cache(c.getAdvancedCache().withMediaType(APPLICATION_OBJECT, APPLICATION_OBJECT)));
    return runner.execute(task.getName(), context).thenApply(r -> (T) scriptConversions.convertToRequestType(r, APPLICATION_OBJECT, requestMediaType));
}
Also used : AuthorizationPermission(org.infinispan.security.AuthorizationPermission) GlobalComponentRegistry(org.infinispan.factories.GlobalComponentRegistry) AuthorizationManager(org.infinispan.security.AuthorizationManager) TaskContext(org.infinispan.tasks.TaskContext) CompletableFuture(java.util.concurrent.CompletableFuture) ScriptConversions(org.infinispan.scripting.utils.ScriptConversions) ArrayList(java.util.ArrayList) List(java.util.List) MediaType(org.infinispan.commons.dataconversion.MediaType) EmbeddedCacheManager(org.infinispan.manager.EmbeddedCacheManager) Authorizer(org.infinispan.security.impl.Authorizer) APPLICATION_OBJECT(org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT) Map(java.util.Map) EncoderRegistry(org.infinispan.marshall.core.EncoderRegistry) TaskEngine(org.infinispan.tasks.spi.TaskEngine) SerializationContextRegistry(org.infinispan.marshall.protostream.impl.SerializationContextRegistry) Task(org.infinispan.tasks.Task) BlockingManager(org.infinispan.util.concurrent.BlockingManager) MediaType(org.infinispan.commons.dataconversion.MediaType)

Aggregations

MediaType (org.infinispan.commons.dataconversion.MediaType)54 NettyRestResponse (org.infinispan.rest.NettyRestResponse)13 MediaTypeUtils.negotiateMediaType (org.infinispan.rest.resources.MediaTypeUtils.negotiateMediaType)12 EmbeddedCacheManager (org.infinispan.manager.EmbeddedCacheManager)9 Map (java.util.Map)8 EncoderRegistry (org.infinispan.marshall.core.EncoderRegistry)7 ConfigurationBuilder (org.infinispan.configuration.cache.ConfigurationBuilder)6 List (java.util.List)5 Function (java.util.function.Function)5 AdvancedCache (org.infinispan.AdvancedCache)5 Cache (org.infinispan.Cache)5 DataConversion (org.infinispan.encoding.DataConversion)5 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 CacheException (org.infinispan.commons.CacheException)4 Configuration (org.infinispan.configuration.cache.Configuration)4 IOException (java.io.IOException)3 Collections (java.util.Collections)3 Optional (java.util.Optional)3