use of io.undertow.server.handlers.cache.DirectBufferCache in project divolte-collector by divolte.
the class Server method createStaticResourceHandler.
private static HttpHandler createStaticResourceHandler() {
final ResourceManager staticResources = new ClassPathResourceManager(Server.class.getClassLoader(), "static");
// Cache tuning is copied from Undertow unit tests.
final ResourceManager cachedResources = new CachingResourceManager(100, 65536, new DirectBufferCache(1024, 10, 10480), staticResources, (int) Duration.ofDays(1).getSeconds());
final ResourceHandler resourceHandler = new ResourceHandler(cachedResources);
resourceHandler.setWelcomeFiles("index.html");
return resourceHandler;
}
use of io.undertow.server.handlers.cache.DirectBufferCache in project undertow by undertow-io.
the class CachedResource method getContentLength.
@Override
public Long getContentLength() {
// we always use the underlying size unless the data is cached in the buffer cache
// to prevent a mis-match between size on disk and cached size
final DirectBufferCache dataCache = cachingResourceManager.getDataCache();
if (dataCache == null) {
return underlyingResource.getContentLength();
}
final DirectBufferCache.CacheEntry existing = dataCache.get(cacheKey);
if (existing == null || !existing.enabled()) {
return underlyingResource.getContentLength();
}
// we only return the
return (long) existing.size();
}
use of io.undertow.server.handlers.cache.DirectBufferCache in project undertow by undertow-io.
the class FileHandlerStressTestCase method simpleFileStressTest.
@Test
public void simpleFileStressTest() throws IOException, ExecutionException, InterruptedException, URISyntaxException {
ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
try {
Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();
final ResourceHandler handler = new ResourceHandler(new PathResourceManager(rootPath, 10485760));
final CacheHandler cacheHandler = new CacheHandler(new DirectBufferCache(1024, 10, 10480), handler);
final PathHandler path = new PathHandler();
path.addPrefixPath("/path", cacheHandler);
final CanonicalPathHandler root = new CanonicalPathHandler();
root.setNext(path);
DefaultServer.setRootHandler(root);
final List<Future<?>> futures = new ArrayList<>();
for (int i = 0; i < NUM_THREADS; ++i) {
futures.add(executor.submit(new Runnable() {
@Override
public void run() {
TestHttpClient client = new TestHttpClient();
try {
for (int i = 0; i < NUM_REQUESTS; ++i) {
HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/page.html");
HttpResponse result = client.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
final String response = HttpClientUtils.readResponse(result);
Assert.assertTrue(response, response.contains("A web page"));
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
client.getConnectionManager().shutdown();
}
}
}));
}
for (Future<?> future : futures) {
future.get();
}
} finally {
executor.shutdown();
}
}
use of io.undertow.server.handlers.cache.DirectBufferCache in project undertow by undertow-io.
the class CacheHandlerTestCase method testBasicPathBasedCaching.
@Test
public void testBasicPathBasedCaching() throws IOException {
final AtomicInteger responseCount = new AtomicInteger();
final HttpHandler messageHandler = new HttpHandler() {
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
final ResponseCache cache = exchange.getAttachment(ResponseCache.ATTACHMENT_KEY);
if (!cache.tryServeResponse()) {
final String data = "Response " + responseCount.incrementAndGet();
exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, data.length() + "");
exchange.getResponseSender().send(data);
}
}
};
final CacheHandler cacheHandler = new CacheHandler(new DirectBufferCache(100, 10, 1000), messageHandler);
DefaultServer.setRootHandler(cacheHandler);
TestHttpClient client = new TestHttpClient();
try {
HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
// it takes 5 hits to make an entry actually get cached
for (int i = 1; i <= 5; ++i) {
HttpResponse result = client.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
Assert.assertEquals("Response " + i, HttpClientUtils.readResponse(result));
}
HttpResponse result = client.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
Assert.assertEquals("Response 5", HttpClientUtils.readResponse(result));
result = client.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
Assert.assertEquals("Response 5", HttpClientUtils.readResponse(result));
result = client.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
Assert.assertEquals("Response 5", HttpClientUtils.readResponse(result));
get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path2");
result = client.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
Assert.assertEquals("Response 6", HttpClientUtils.readResponse(result));
} finally {
client.getConnectionManager().shutdown();
}
}
use of io.undertow.server.handlers.cache.DirectBufferCache in project wildfly by wildfly.
the class ServletContainerAdd method installRuntimeServices.
void installRuntimeServices(OperationContext context, ModelNode model, String name) throws OperationFailedException {
final ModelNode fullModel = Resource.Tools.readModel(context.readResource(PathAddress.EMPTY_ADDRESS), 2);
final SessionCookieConfig config = SessionCookieDefinition.INSTANCE.getConfig(context, fullModel.get(SessionCookieDefinition.INSTANCE.getPathElement().getKeyValuePair()));
final CrawlerSessionManagerConfig crawlerSessionManagerConfig = CrawlerSessionManagementDefinition.INSTANCE.getConfig(context, fullModel.get(CrawlerSessionManagementDefinition.INSTANCE.getPathElement().getKeyValuePair()));
final boolean persistentSessions = PersistentSessionsDefinition.isEnabled(context, fullModel.get(PersistentSessionsDefinition.INSTANCE.getPathElement().getKeyValuePair()));
final boolean allowNonStandardWrappers = ServletContainerDefinition.ALLOW_NON_STANDARD_WRAPPERS.resolveModelAttribute(context, model).asBoolean();
final boolean proactiveAuth = ServletContainerDefinition.PROACTIVE_AUTHENTICATION.resolveModelAttribute(context, model).asBoolean();
final String bufferCache = ServletContainerDefinition.DEFAULT_BUFFER_CACHE.resolveModelAttribute(context, model).asString();
final boolean disableFileWatchService = ServletContainerDefinition.DISABLE_FILE_WATCH_SERVICE.resolveModelAttribute(context, model).asBoolean();
final boolean disableSessionIdReususe = ServletContainerDefinition.DISABLE_SESSION_ID_REUSE.resolveModelAttribute(context, model).asBoolean();
JSPConfig jspConfig = JspDefinition.INSTANCE.getConfig(context, fullModel.get(JspDefinition.INSTANCE.getPathElement().getKeyValuePair()));
final String stackTracesString = ServletContainerDefinition.STACK_TRACE_ON_ERROR.resolveModelAttribute(context, model).asString();
final ModelNode defaultEncodingValue = ServletContainerDefinition.DEFAULT_ENCODING.resolveModelAttribute(context, model);
final String defaultEncoding = defaultEncodingValue.isDefined() ? defaultEncodingValue.asString() : null;
final boolean useListenerEncoding = ServletContainerDefinition.USE_LISTENER_ENCODING.resolveModelAttribute(context, model).asBoolean();
final boolean ignoreFlush = ServletContainerDefinition.IGNORE_FLUSH.resolveModelAttribute(context, model).asBoolean();
final boolean eagerFilterInit = ServletContainerDefinition.EAGER_FILTER_INIT.resolveModelAttribute(context, model).asBoolean();
final boolean disableCachingForSecuredPages = ServletContainerDefinition.DISABLE_CACHING_FOR_SECURED_PAGES.resolveModelAttribute(context, model).asBoolean();
final int sessionIdLength = ServletContainerDefinition.SESSION_ID_LENGTH.resolveModelAttribute(context, model).asInt();
final int fileCacheMetadataSize = ServletContainerDefinition.FILE_CACHE_METADATA_SIZE.resolveModelAttribute(context, model).asInt();
final int fileCacheMaxFileSize = ServletContainerDefinition.FILE_CACHE_MAX_FILE_SIZE.resolveModelAttribute(context, model).asInt();
final ModelNode fileCacheTtlNode = ServletContainerDefinition.FILE_CACHE_TIME_TO_LIVE.resolveModelAttribute(context, model);
final Integer fileCacheTimeToLive = fileCacheTtlNode.isDefined() ? fileCacheTtlNode.asInt() : null;
final int defaultCookieVersion = ServletContainerDefinition.DEFAULT_COOKIE_VERSION.resolveModelAttribute(context, model).asInt();
final boolean preservePathOnForward = ServletContainerDefinition.PRESERVE_PATH_ON_FORWARD.resolveModelAttribute(context, model).asBoolean();
Boolean directoryListingEnabled = null;
if (model.hasDefined(Constants.DIRECTORY_LISTING)) {
directoryListingEnabled = ServletContainerDefinition.DIRECTORY_LISTING.resolveModelAttribute(context, model).asBoolean();
}
Integer maxSessions = null;
if (model.hasDefined(Constants.MAX_SESSIONS)) {
maxSessions = ServletContainerDefinition.MAX_SESSIONS.resolveModelAttribute(context, model).asInt();
}
final int sessionTimeout = ServletContainerDefinition.DEFAULT_SESSION_TIMEOUT.resolveModelAttribute(context, model).asInt();
WebsocketsDefinition.WebSocketInfo webSocketInfo = WebsocketsDefinition.INSTANCE.getConfig(context, fullModel.get(WebsocketsDefinition.INSTANCE.getPathElement().getKeyValuePair()));
final Map<String, String> mimeMappings = new HashMap<>();
if (fullModel.hasDefined(Constants.MIME_MAPPING)) {
for (final Property mapping : fullModel.get(Constants.MIME_MAPPING).asPropertyList()) {
mimeMappings.put(mapping.getName(), MimeMappingDefinition.VALUE.resolveModelAttribute(context, mapping.getValue()).asString());
}
}
List<String> welcomeFiles = new ArrayList<>();
if (fullModel.hasDefined(Constants.WELCOME_FILE)) {
for (final Property welcome : fullModel.get(Constants.WELCOME_FILE).asPropertyList()) {
welcomeFiles.add(welcome.getName());
}
}
final CapabilityServiceBuilder<?> sb = context.getCapabilityServiceTarget().addCapability(ServletContainerDefinition.SERVLET_CONTAINER_CAPABILITY);
final Consumer<ServletContainerService> sConsumer = sb.provides(ServletContainerDefinition.SERVLET_CONTAINER_CAPABILITY, UndertowService.SERVLET_CONTAINER.append(name));
final Supplier<SessionPersistenceManager> spmSupplier = persistentSessions ? sb.requires(AbstractPersistentSessionManager.SERVICE_NAME) : null;
final Supplier<DirectBufferCache> bcSupplier = bufferCache != null ? sb.requires(BufferCacheService.SERVICE_NAME.append(bufferCache)) : null;
final Supplier<ByteBufferPool> bbpSupplier = webSocketInfo != null ? sb.requiresCapability(Capabilities.CAPABILITY_BYTE_BUFFER_POOL, ByteBufferPool.class, webSocketInfo.getBufferPool()) : null;
final Supplier<XnioWorker> xwSupplier = webSocketInfo != null ? sb.requiresCapability(Capabilities.REF_IO_WORKER, XnioWorker.class, webSocketInfo.getWorker()) : null;
final ServletContainerService container = new ServletContainerService(sConsumer, spmSupplier, bcSupplier, bbpSupplier, xwSupplier, allowNonStandardWrappers, ServletStackTraces.valueOf(stackTracesString.toUpperCase().replace('-', '_')), config, jspConfig, defaultEncoding, useListenerEncoding, ignoreFlush, eagerFilterInit, sessionTimeout, disableCachingForSecuredPages, webSocketInfo != null, webSocketInfo != null && webSocketInfo.isDispatchToWorker(), webSocketInfo != null && webSocketInfo.isPerMessageDeflate(), webSocketInfo == null ? -1 : webSocketInfo.getDeflaterLevel(), mimeMappings, welcomeFiles, directoryListingEnabled, proactiveAuth, sessionIdLength, maxSessions, crawlerSessionManagerConfig, disableFileWatchService, disableSessionIdReususe, fileCacheMetadataSize, fileCacheMaxFileSize, fileCacheTimeToLive, defaultCookieVersion, preservePathOnForward);
sb.setInstance(container);
sb.setInitialMode(ServiceController.Mode.ON_DEMAND);
sb.install();
}
Aggregations