Search in sources :

Example 26 with MediaType

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

the class ContainerResource method getConfig.

private CompletionStage<RestResponse> getConfig(RestRequest request) {
    NettyRestResponse.Builder responseBuilder = checkCacheManager(request);
    if (responseBuilder.getHttpStatus() == NOT_FOUND)
        return completedFuture(responseBuilder.build());
    EmbeddedCacheManager embeddedCacheManager = invocationHelper.getRestCacheManager().getInstance().withSubject(request.getSubject());
    GlobalConfiguration globalConfiguration = SecurityActions.getCacheManagerConfiguration(embeddedCacheManager);
    MediaType format = MediaTypeUtils.negotiateMediaType(request, APPLICATION_JSON, APPLICATION_XML);
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (ConfigurationWriter writer = ConfigurationWriter.to(baos).withType(format).build()) {
            parserRegistry.serialize(writer, globalConfiguration, emptyMap());
        }
        responseBuilder.contentType(format);
        responseBuilder.entity(baos.toByteArray());
    } catch (Exception e) {
        responseBuilder.status(HttpResponseStatus.INTERNAL_SERVER_ERROR);
    }
    return completedFuture(responseBuilder.build());
}
Also used : GlobalConfiguration(org.infinispan.configuration.global.GlobalConfiguration) ConfigurationWriter(org.infinispan.commons.configuration.io.ConfigurationWriter) MediaType(org.infinispan.commons.dataconversion.MediaType) MediaTypeUtils.negotiateMediaType(org.infinispan.rest.resources.MediaTypeUtils.negotiateMediaType) ByteArrayOutputStream(java.io.ByteArrayOutputStream) EmbeddedCacheManager(org.infinispan.manager.EmbeddedCacheManager) NettyRestResponse(org.infinispan.rest.NettyRestResponse)

Example 27 with MediaType

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

the class CounterResource method getCounter.

private CompletionStage<RestResponse> getCounter(RestRequest request) throws RestResponseException {
    String counterName = request.variables().get("counterName");
    String accept = request.getAcceptHeader();
    MediaType contentType = accept == null ? MediaType.TEXT_PLAIN : negotiateMediaType(accept);
    EmbeddedCounterManager counterManager = invocationHelper.getCounterManager();
    return counterManager.getConfigurationAsync(counterName).thenCompose(configuration -> {
        if (configuration == null)
            return notFoundResponseFuture();
        NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder().contentType(contentType).header(CACHE_CONTROL.toString(), CacheControl.noCache());
        CompletionStage<Long> response;
        if (configuration.type() == CounterType.WEAK) {
            response = getWeakCounter(counterName, counterManager).thenApply(WeakCounter::getValue);
        } else {
            response = getStrongCounter(counterName, counterManager).thenCompose(StrongCounter::getValue);
        }
        return response.thenApply(v -> responseBuilder.entity(Long.toString(v)).build());
    });
}
Also used : CounterManagerConfigurationBuilder(org.infinispan.counter.configuration.CounterManagerConfigurationBuilder) MediaType(org.infinispan.commons.dataconversion.MediaType) EmbeddedCounterManager(org.infinispan.counter.impl.manager.EmbeddedCounterManager) NettyRestResponse(org.infinispan.rest.NettyRestResponse)

Example 28 with MediaType

use of org.infinispan.commons.dataconversion.MediaType 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 29 with MediaType

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

the class BackupManagerResource method handleRestore.

static CompletionStage<RestResponse> handleRestore(String name, RestRequest request, BackupManager backupManager, TriFunction<String, Path, Json, CompletionStage<Void>> function) {
    BackupManager.Status existingStatus = backupManager.getRestoreStatus(name);
    if (existingStatus != BackupManager.Status.NOT_FOUND)
        return responseFuture(CONFLICT);
    Path path;
    Json resourcesJson = Json.object();
    MediaType contentType = request.contentType();
    boolean uploadedBackup = contentType.match(MediaType.MULTIPART_FORM_DATA);
    try {
        if (uploadedBackup) {
            FullHttpRequest nettyRequest = ((NettyRestRequest) request).getFullHttpRequest();
            DefaultHttpDataFactory factory = new DefaultHttpDataFactory(true);
            InterfaceHttpPostRequestDecoder decoder = new HttpPostMultipartRequestDecoder(factory, nettyRequest);
            DiskFileUpload backup = (DiskFileUpload) decoder.getBodyHttpData("backup");
            path = backup.getFile().toPath();
            DiskAttribute resources = (DiskAttribute) decoder.getBodyHttpData("resources");
            if (resources != null)
                resourcesJson = Json.read(resources.getString());
        } else if (contentType.match(MediaType.APPLICATION_JSON)) {
            // Attempt to parse body as json
            Json json = Json.read(request.contents().asString());
            Json resources = json.at(RESOURCES_KEY);
            if (resources != null)
                resourcesJson = resources;
            Json backupPath = json.at(LOCATION_KEY);
            if (backupPath == null)
                return responseFuture(BAD_REQUEST, "Required json attribute 'backup-location' not found");
            path = Paths.get(backupPath.asString());
        } else {
            return responseFuture(UNSUPPORTED_MEDIA_TYPE);
        }
        function.apply(name, path, resourcesJson).whenComplete((Void, t) -> {
            if (t != null) {
                LOG.error(t);
            }
            if (uploadedBackup) {
                try {
                    Files.delete(path);
                } catch (IOException e) {
                    LOG.warnf(e, "Unable to delete uploaded backup file '%s'", path);
                }
            }
        });
        return responseFuture(ACCEPTED);
    } catch (IOException e) {
        LOG.error(e);
        return responseFuture(INTERNAL_SERVER_ERROR, e.getMessage());
    }
}
Also used : Path(java.nio.file.Path) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) Json(org.infinispan.commons.dataconversion.internal.Json) IOException(java.io.IOException) BackupManager(org.infinispan.server.core.BackupManager) DiskAttribute(io.netty.handler.codec.http.multipart.DiskAttribute) InterfaceHttpPostRequestDecoder(io.netty.handler.codec.http.multipart.InterfaceHttpPostRequestDecoder) DiskFileUpload(io.netty.handler.codec.http.multipart.DiskFileUpload) DefaultHttpDataFactory(io.netty.handler.codec.http.multipart.DefaultHttpDataFactory) HttpPostMultipartRequestDecoder(io.netty.handler.codec.http.multipart.HttpPostMultipartRequestDecoder) MediaType(org.infinispan.commons.dataconversion.MediaType) NettyRestRequest(org.infinispan.rest.NettyRestRequest)

Example 30 with MediaType

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

the class BaseCacheResource method deleteCacheValue.

CompletionStage<RestResponse> deleteCacheValue(RestRequest request) throws RestResponseException {
    String cacheName = request.variables().get("cacheName");
    Object key = getKey(request);
    MediaType keyContentType = request.keyContentType();
    RestCacheManager<Object> restCacheManager = invocationHelper.getRestCacheManager();
    AdvancedCache<Object, Object> cache = restCacheManager.getCache(cacheName, keyContentType, MediaType.MATCH_ALL, request);
    return restCacheManager.getPrivilegedInternalEntry(cache, key, true).thenCompose(entry -> {
        NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder();
        responseBuilder.status(HttpResponseStatus.NOT_FOUND);
        if (entry instanceof InternalCacheEntry) {
            InternalCacheEntry<Object, Object> ice = (InternalCacheEntry<Object, Object>) entry;
            String etag = calcETAG(ice.getValue());
            String clientEtag = request.getEtagIfNoneMatchHeader();
            if (clientEtag == null || clientEtag.equals(etag)) {
                responseBuilder.status(HttpResponseStatus.NO_CONTENT);
                return restCacheManager.remove(cacheName, key, keyContentType, request).thenApply(v -> responseBuilder.build());
            } else {
                // ETags don't match, so preconditions failed
                responseBuilder.status(HttpResponseStatus.PRECONDITION_FAILED);
            }
        }
        return CompletableFuture.completedFuture(responseBuilder.build());
    });
}
Also used : InternalCacheEntry(org.infinispan.container.entries.InternalCacheEntry) MediaType(org.infinispan.commons.dataconversion.MediaType) MediaTypeUtils.negotiateMediaType(org.infinispan.rest.resources.MediaTypeUtils.negotiateMediaType) NettyRestResponse(org.infinispan.rest.NettyRestResponse)

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