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());
}
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());
});
}
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();
}
}
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());
}
}
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());
});
}
Aggregations