src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
NettyRequestExecutor { @SuppressWarnings("unchecked") public CompletableFuture<Void> execute() { Promise<Channel> channelFuture = context.eventLoopGroup().next().newPromise(); executeFuture = createExecutionFuture(channelFuture); context.channelPool().acquire(channelFuture); channelFuture.addListener((GenericFutureListener) this::makeRequestListener); return executeFuture; } NettyRequestExecutor(RequestContext context); @SuppressWarnings("unchecked") CompletableFuture<Void> execute(); }
@Test public void cancelExecuteFuture_channelNotAcquired_failsAcquirePromise() { ArgumentCaptor<Promise> acquireCaptor = ArgumentCaptor.forClass(Promise.class); when(mockChannelPool.acquire(acquireCaptor.capture())).thenAnswer((Answer<Promise>) invocationOnMock -> { return invocationOnMock.getArgumentAt(0, Promise.class); }); CompletableFuture<Void> executeFuture = nettyRequestExecutor.execute(); executeFuture.cancel(true); assertThat(acquireCaptor.getValue().isDone()).isTrue(); assertThat(acquireCaptor.getValue().isSuccess()).isFalse(); } @Test public void cancelExecuteFuture_channelAcquired_submitsRunnable() { EventLoop mockEventLoop = mock(EventLoop.class); Channel mockChannel = mock(Channel.class); when(mockChannel.eventLoop()).thenReturn(mockEventLoop); when(mockChannelPool.acquire(any(Promise.class))).thenAnswer((Answer<Promise>) invocationOnMock -> { Promise p = invocationOnMock.getArgumentAt(0, Promise.class); p.setSuccess(mockChannel); return p; }); CompletableFuture<Void> executeFuture = nettyRequestExecutor.execute(); executeFuture.cancel(true); verify(mockEventLoop).submit(any(Runnable.class)); }
HandlerRemovingChannelPool implements SdkChannelPool { @Override public Future<Void> release(Channel channel) { removePerRequestHandlers(channel); return delegate.release(channel); } HandlerRemovingChannelPool(SdkChannelPool delegate); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); @Override CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics); }
@Test public void release_openChannel_handlerShouldBeRemovedFromChannelPool() { assertHandlersNotRemoved(); handlerRemovingChannelPool.release(mockChannel); assertHandlersRemoved(); } @Test public void release_deregisteredOpenChannel_handlerShouldBeRemovedFromChannelPool() { mockChannel.deregister().awaitUninterruptibly(); assertHandlersNotRemoved(); handlerRemovingChannelPool.release(mockChannel); assertHandlersRemoved(); }
OldConnectionReaperHandler extends ChannelDuplexHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { initialize(ctx); super.handlerAdded(ctx); } OldConnectionReaperHandler(int connectionTtlMillis); @Override void handlerAdded(ChannelHandlerContext ctx); @Override void channelActive(ChannelHandlerContext ctx); @Override void channelRegistered(ChannelHandlerContext ctx); @Override void handlerRemoved(ChannelHandlerContext ctx); }
@Test @SuppressWarnings("unchecked") public void inUseChannelsAreFlaggedToBeClosed() throws Exception { MockChannel channel = new MockChannel(); channel.attr(ChannelAttributeKey.IN_USE).set(true); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); Mockito.when(ctx.channel()).thenReturn(channel); new OldConnectionReaperHandler(1).handlerAdded(ctx); channel.runAllPendingTasks(); Mockito.verify(ctx, new Times(0)).close(); Mockito.verify(ctx, new Times(0)).close(any()); assertThat(channel.attr(ChannelAttributeKey.CLOSE_ON_RELEASE).get()).isTrue(); } @Test public void notInUseChannelsAreClosed() throws Exception { MockChannel channel = new MockChannel(); channel.attr(ChannelAttributeKey.IN_USE).set(false); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); Mockito.when(ctx.channel()).thenReturn(channel); new OldConnectionReaperHandler(1).handlerAdded(ctx); channel.runAllPendingTasks(); Mockito.verify(ctx, new Times(1)).close(); Mockito.verify(ctx, new Times(0)).close(any()); }
HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } HealthCheckedChannelPool(EventLoopGroup eventLoopGroup, NettyConfiguration configuration, SdkChannelPool delegate); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> resultFuture); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); @Override CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics); }
@Test public void acquireCanMakeJustOneCall() throws Exception { stubForIgnoredTimeout(); stubAcquireHealthySequence(true); Future<Channel> acquire = channelPool.acquire(); acquire.get(5, TimeUnit.SECONDS); assertThat(acquire.isDone()).isTrue(); assertThat(acquire.isSuccess()).isTrue(); assertThat(acquire.getNow()).isEqualTo(channels.get(0)); Mockito.verify(downstreamChannelPool, Mockito.times(1)).acquire(any()); } @Test public void acquireCanMakeManyCalls() throws Exception { stubForIgnoredTimeout(); stubAcquireHealthySequence(false, false, false, false, true); Future<Channel> acquire = channelPool.acquire(); acquire.get(5, TimeUnit.SECONDS); assertThat(acquire.isDone()).isTrue(); assertThat(acquire.isSuccess()).isTrue(); assertThat(acquire.getNow()).isEqualTo(channels.get(4)); Mockito.verify(downstreamChannelPool, Mockito.times(5)).acquire(any()); } @Test public void acquireActiveAndKeepAliveTrue_shouldAcquireOnce() throws Exception { stubForIgnoredTimeout(); stubAcquireActiveAndKeepAlive(); Future<Channel> acquire = channelPool.acquire(); acquire.get(5, TimeUnit.SECONDS); assertThat(acquire.isDone()).isTrue(); assertThat(acquire.isSuccess()).isTrue(); assertThat(acquire.getNow()).isEqualTo(channels.get(0)); Mockito.verify(downstreamChannelPool, Mockito.times(1)).acquire(any()); } @Test public void acquire_firstChannelKeepAliveFalse_shouldAcquireAnother() throws Exception { stubForIgnoredTimeout(); stubAcquireTwiceFirstTimeNotKeepAlive(); Future<Channel> acquire = channelPool.acquire(); acquire.get(5, TimeUnit.SECONDS); assertThat(acquire.isDone()).isTrue(); assertThat(acquire.isSuccess()).isTrue(); assertThat(acquire.getNow()).isEqualTo(channels.get(1)); Mockito.verify(downstreamChannelPool, Mockito.times(2)).acquire(any()); } @Test public void badDownstreamAcquiresCausesException() throws Exception { stubForIgnoredTimeout(); stubBadDownstreamAcquire(); Future<Channel> acquire = channelPool.acquire(); try { acquire.get(5, TimeUnit.SECONDS); } catch (ExecutionException e) { } assertThat(acquire.isDone()).isTrue(); assertThat(acquire.isSuccess()).isFalse(); assertThat(acquire.cause()).isInstanceOf(IOException.class); Mockito.verify(downstreamChannelPool, Mockito.times(1)).acquire(any()); } @Test public void slowAcquireTimesOut() throws Exception { stubIncompleteDownstreamAcquire(); Mockito.when(eventLoopGroup.schedule(Mockito.any(Runnable.class), Mockito.eq(10), Mockito.eq(TimeUnit.MILLISECONDS))) .thenAnswer(i -> scheduledFuture); Future<Channel> acquire = channelPool.acquire(); ArgumentCaptor<Runnable> timeoutTask = ArgumentCaptor.forClass(Runnable.class); Mockito.verify(eventLoopGroup).schedule(timeoutTask.capture(), anyLong(), any()); timeoutTask.getValue().run(); try { acquire.get(5, TimeUnit.SECONDS); } catch (ExecutionException e) { } assertThat(acquire.isDone()).isTrue(); assertThat(acquire.isSuccess()).isFalse(); assertThat(acquire.cause()).isInstanceOf(TimeoutException.class); Mockito.verify(downstreamChannelPool, Mockito.times(1)).acquire(any()); }
OneTimeReadTimeoutHandler extends ReadTimeoutHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ctx.pipeline().remove(this); super.channelRead(ctx, msg); } OneTimeReadTimeoutHandler(Duration timeout); @Override void channelRead(ChannelHandlerContext ctx, Object msg); }
@Test public void channelRead_removesSelf() throws Exception { when(context.pipeline()).thenReturn(channelPipeline); handler.channelRead(context, object); verify(channelPipeline, times(1)).remove(eq(handler)); verify(context, times(1)).fireChannelRead(object); }
SharedSdkEventLoopGroup { @SdkTestInternalApi static synchronized int referenceCount() { return referenceCount; } private SharedSdkEventLoopGroup(); @SdkInternalApi static synchronized SdkEventLoopGroup get(); }
@Test public void referenceCountIsInitiallyZero() { assertThat(SharedSdkEventLoopGroup.referenceCount()).isEqualTo(0); }
SharedSdkEventLoopGroup { @SdkInternalApi public static synchronized SdkEventLoopGroup get() { if (sharedSdkEventLoopGroup == null) { sharedSdkEventLoopGroup = SdkEventLoopGroup.builder().build(); } referenceCount++; return SdkEventLoopGroup.create(new ReferenceCountingEventLoopGroup(sharedSdkEventLoopGroup.eventLoopGroup()), sharedSdkEventLoopGroup.channelFactory()); } private SharedSdkEventLoopGroup(); @SdkInternalApi static synchronized SdkEventLoopGroup get(); }
@Test public void sharedEventLoopGroupIsDeallocatedWhenCountReachesZero() { DelegatingEventLoopGroup group1 = (DelegatingEventLoopGroup) SharedSdkEventLoopGroup.get().eventLoopGroup(); DelegatingEventLoopGroup group2 = (DelegatingEventLoopGroup) SharedSdkEventLoopGroup.get().eventLoopGroup(); assertThat(group1.getDelegate()).isEqualTo(group2.getDelegate()); group1.shutdownGracefully(); group2.shutdownGracefully(); assertThat(group1.getDelegate().isShuttingDown()).isTrue(); }
ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void handlerAdded(ChannelHandlerContext ctx) { ChannelPipeline pipeline = ctx.pipeline(); pipeline.addBefore(ctx.name(), null, httpCodecSupplier.get()); HttpRequest connectRequest = connectRequest(); ctx.channel().writeAndFlush(connectRequest).addListener(f -> { if (!f.isSuccess()) { ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Unable to send CONNECT request to proxy", f.cause())); } }); } ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise); @SdkTestInternalApi ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise, Supplier<HttpClientCodec> httpCodecSupplier); @Override void handlerAdded(ChannelHandlerContext ctx); @Override void handlerRemoved(ChannelHandlerContext ctx); @Override void channelRead(ChannelHandlerContext ctx, Object msg); }
@Test public void addedToPipeline_addsCodec() { HttpClientCodec codec = new HttpClientCodec(); Supplier<HttpClientCodec> codecSupplier = () -> codec; when(mockCtx.name()).thenReturn("foo"); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, null, codecSupplier); handler.handlerAdded(mockCtx); verify(mockPipeline).addBefore(eq("foo"), eq(null), eq(codec)); } @Test public void requestWriteFails_failsPromise() { DefaultChannelPromise writePromise = new DefaultChannelPromise(mockChannel, GROUP.next()); writePromise.setFailure(new IOException("boom")); when(mockChannel.writeAndFlush(anyObject())).thenReturn(writePromise); Promise<Channel> promise = GROUP.next().newPromise(); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise); handler.handlerAdded(mockCtx); assertThat(promise.awaitUninterruptibly().isSuccess()).isFalse(); } @Test public void handledAdded_writesRequest() { Promise<Channel> promise = GROUP.next().newPromise(); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise); handler.handlerAdded(mockCtx); ArgumentCaptor<HttpRequest> requestCaptor = ArgumentCaptor.forClass(HttpRequest.class); verify(mockChannel).writeAndFlush(requestCaptor.capture()); String uri = REMOTE_HOST.getHost() + ":" + REMOTE_HOST.getPort(); HttpRequest expectedRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.CONNECT, uri, Unpooled.EMPTY_BUFFER, false); expectedRequest.headers().add(HttpHeaderNames.HOST, uri); assertThat(requestCaptor.getValue()).isEqualTo(expectedRequest); }
ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; if (response.status().code() == 200) { ctx.pipeline().remove(this); initPromise.setSuccess(ctx.channel()); return; } } ctx.pipeline().remove(this); ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Could not connect to proxy")); } ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise); @SdkTestInternalApi ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise, Supplier<HttpClientCodec> httpCodecSupplier); @Override void handlerAdded(ChannelHandlerContext ctx); @Override void handlerRemoved(ChannelHandlerContext ctx); @Override void channelRead(ChannelHandlerContext ctx, Object msg); }
@Test public void unexpectedMessage_failsPromise() { Promise<Channel> promise = GROUP.next().newPromise(); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise); handler.channelRead(mockCtx, new Object()); assertThat(promise.awaitUninterruptibly().isSuccess()).isFalse(); } @Test public void unsuccessfulResponse_failsPromise() { Promise<Channel> promise = GROUP.next().newPromise(); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise); DefaultHttpResponse resp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN); handler.channelRead(mockCtx, resp); assertThat(promise.awaitUninterruptibly().isSuccess()).isFalse(); }
ProxyTunnelInitHandler extends ChannelDuplexHandler { @Override public void handlerRemoved(ChannelHandlerContext ctx) { if (ctx.pipeline().get(HttpClientCodec.class) != null) { ctx.pipeline().remove(HttpClientCodec.class); } } ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise); @SdkTestInternalApi ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise, Supplier<HttpClientCodec> httpCodecSupplier); @Override void handlerAdded(ChannelHandlerContext ctx); @Override void handlerRemoved(ChannelHandlerContext ctx); @Override void channelRead(ChannelHandlerContext ctx, Object msg); }
@Test public void handlerRemoved_removesCodec() { HttpClientCodec codec = new HttpClientCodec(); when(mockPipeline.get(eq(HttpClientCodec.class))).thenReturn(codec); Promise<Channel> promise = GROUP.next().newPromise(); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise); handler.handlerRemoved(mockCtx); verify(mockPipeline).remove(eq(HttpClientCodec.class)); }
BetterFixedChannelPool implements SdkChannelPool { public CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics) { CompletableFuture<Void> delegateMetricResult = delegateChannelPool.collectChannelPoolMetrics(metrics); CompletableFuture<Void> result = new CompletableFuture<>(); doInEventLoop(executor, () -> { try { metrics.reportMetric(HttpMetric.MAX_CONCURRENCY, this.maxConnections); metrics.reportMetric(HttpMetric.PENDING_CONCURRENCY_ACQUIRES, this.pendingAcquireCount); metrics.reportMetric(HttpMetric.LEASED_CONCURRENCY, this.acquiredChannelCount); result.complete(null); } catch (Throwable t) { result.completeExceptionally(t); } }); return CompletableFuture.allOf(result, delegateMetricResult); } private BetterFixedChannelPool(Builder builder); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(final Promise<Channel> promise); CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics); @Override Future<Void> release(Channel channel); @Override Future<Void> release(final Channel channel, final Promise<Void> promise); @Override void close(); static Builder builder(); }
@Test public void delegateChannelPoolMetricFailureIsReported() { Throwable t = new Throwable(); Mockito.when(delegatePool.collectChannelPoolMetrics(any())).thenReturn(CompletableFutureUtils.failedFuture(t)); CompletableFuture<Void> result = channelPool.collectChannelPoolMetrics(MetricCollector.create("test")); waitForCompletion(result); assertThat(result).hasFailedWithThrowableThat().isEqualTo(t); }
NettyUtils { public static <T> AttributeKey<T> getOrCreateAttributeKey(String attr) { if (AttributeKey.exists(attr)) { return AttributeKey.valueOf(attr); } return AttributeKey.newInstance(attr); } private NettyUtils(); static BiConsumer<SuccessT, ? super Throwable> promiseNotifyingBiConsumer( Function<SuccessT, PromiseT> successFunction, Promise<PromiseT> promise); static BiConsumer<SuccessT, ? super Throwable> asyncPromiseNotifyingBiConsumer( BiConsumer<SuccessT, Promise<PromiseT>> successConsumer, Promise<PromiseT> promise); static GenericFutureListener<Future<T>> promiseNotifyingListener(Promise<T> channelPromise); static void doInEventLoop(EventExecutor eventExecutor, Runnable runnable); static void doInEventLoop(EventExecutor eventExecutor, Runnable runnable, Promise<?> promise); static void warnIfNotInEventLoop(EventLoop loop); static AttributeKey<T> getOrCreateAttributeKey(String attr); static final SucceededFuture<?> SUCCEEDED_FUTURE; }
@Test public void testGetOrCreateAttributeKey_calledTwiceWithSameName_returnsSameInstance() { String attr = "NettyUtilsTest.Foo"; AttributeKey<String> fooAttr = NettyUtils.getOrCreateAttributeKey(attr); assertThat(NettyUtils.getOrCreateAttributeKey(attr)).isSameAs(fooAttr); }
ChannelUtils { public static <T> Optional<T> getAttribute(Channel channel, AttributeKey<T> key) { return Optional.ofNullable(channel.attr(key)) .map(Attribute::get); } private ChannelUtils(); @SafeVarargs static void removeIfExists(ChannelPipeline pipeline, Class<? extends ChannelHandler>... handlers); static Optional<T> getAttribute(Channel channel, AttributeKey<T> key); }
@Test public void testGetAttributes() throws Exception { MockChannel channel = null; try { channel = new MockChannel(); channel.attr(MAX_CONCURRENT_STREAMS).set(1L); assertThat(ChannelUtils.getAttribute(channel, MAX_CONCURRENT_STREAMS).get()).isEqualTo(1L); assertThat(ChannelUtils.getAttribute(channel, HTTP2_MULTIPLEXED_CHANNEL_POOL)).isNotPresent(); } finally { Optional.ofNullable(channel).ifPresent(Channel::close); } }
ChannelUtils { @SafeVarargs public static void removeIfExists(ChannelPipeline pipeline, Class<? extends ChannelHandler>... handlers) { for (Class<? extends ChannelHandler> handler : handlers) { if (pipeline.get(handler) != null) { try { pipeline.remove(handler); } catch (NoSuchElementException exception) { } } } } private ChannelUtils(); @SafeVarargs static void removeIfExists(ChannelPipeline pipeline, Class<? extends ChannelHandler>... handlers); static Optional<T> getAttribute(Channel channel, AttributeKey<T> key); }
@Test public void removeIfExists() throws Exception { MockChannel channel = null; try { channel = new MockChannel(); ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast(new ReadTimeoutHandler(1)); pipeline.addLast(new LoggingHandler(LogLevel.DEBUG)); ChannelUtils.removeIfExists(pipeline, ReadTimeoutHandler.class, LoggingHandler.class); assertThat(pipeline.get(ReadTimeoutHandler.class)).isNull(); assertThat(pipeline.get(LoggingHandler.class)).isNull(); } finally { Optional.ofNullable(channel).ifPresent(Channel::close); } }
SocketChannelResolver { @SuppressWarnings("unchecked") public static ChannelFactory<? extends Channel> resolveSocketChannelFactory(EventLoopGroup eventLoopGroup) { if (eventLoopGroup instanceof DelegatingEventLoopGroup) { return resolveSocketChannelFactory(((DelegatingEventLoopGroup) eventLoopGroup).getDelegate()); } if (eventLoopGroup instanceof NioEventLoopGroup) { return NioSocketChannel::new; } if (eventLoopGroup instanceof EpollEventLoopGroup) { return EpollSocketChannel::new; } String socketFqcn = KNOWN_EL_GROUPS.get(eventLoopGroup.getClass().getName()); if (socketFqcn == null) { throw new IllegalArgumentException("Unknown event loop group : " + eventLoopGroup.getClass()); } return invokeSafely(() -> new ReflectiveChannelFactory(Class.forName(socketFqcn))); } private SocketChannelResolver(); @SuppressWarnings("unchecked") static ChannelFactory<? extends Channel> resolveSocketChannelFactory(EventLoopGroup eventLoopGroup); }
@Test public void canDetectFactoryForStandardNioEventLoopGroup() { assertThat(resolveSocketChannelFactory(new NioEventLoopGroup()).newChannel()).isInstanceOf(NioSocketChannel.class); } @Test public void canDetectEpollEventLoopGroupFactory() { assumeTrue(Epoll.isAvailable()); assertThat(resolveSocketChannelFactory(new EpollEventLoopGroup()).newChannel()).isInstanceOf(EpollSocketChannel.class); } @Test public void worksWithDelegateEventLoopGroupsFactory() { assertThat(resolveSocketChannelFactory(new DelegatingEventLoopGroup(new NioEventLoopGroup()) {}).newChannel()).isInstanceOf(NioSocketChannel.class); } @Test public void worksWithOioEventLoopGroupFactory() { assertThat(resolveSocketChannelFactory(new OioEventLoopGroup()).newChannel()).isInstanceOf(OioSocketChannel.class); }
ExceptionHandlingUtils { public static void tryCatch(Runnable executable, Consumer<Throwable> errorNotifier) { try { executable.run(); } catch (Throwable throwable) { errorNotifier.accept(throwable); } } private ExceptionHandlingUtils(); static void tryCatch(Runnable executable, Consumer<Throwable> errorNotifier); static T tryCatchFinally(Callable<T> executable, Consumer<Throwable> errorNotifier, Runnable cleanupExecutable); }
@Test public void tryCatch() { ExceptionHandlingUtils.tryCatch(() -> { }, errorNotifier); verify(errorNotifier, times(0)).accept(any(Throwable.class)); } @Test public void tryCatchExceptionThrows() { ExceptionHandlingUtils.tryCatch(() -> { throw new RuntimeException("helloworld"); }, errorNotifier); verify(errorNotifier).accept(any(Throwable.class)); }
ExceptionHandlingUtils { public static <T> T tryCatchFinally(Callable<T> executable, Consumer<Throwable> errorNotifier, Runnable cleanupExecutable) { try { return executable.call(); } catch (Throwable throwable) { errorNotifier.accept(throwable); } finally { cleanupExecutable.run(); } return null; } private ExceptionHandlingUtils(); static void tryCatch(Runnable executable, Consumer<Throwable> errorNotifier); static T tryCatchFinally(Callable<T> executable, Consumer<Throwable> errorNotifier, Runnable cleanupExecutable); }
@Test public void tryCatchFinallyException() { ExceptionHandlingUtils.tryCatchFinally(() -> "blah", errorNotifier, cleanupExecutor ); verify(errorNotifier, times(0)).accept(any(Throwable.class)); verify(cleanupExecutor).run(); } @Test public void tryCatchFinallyExceptionThrows() { ExceptionHandlingUtils.tryCatchFinally(() -> { throw new RuntimeException("helloworld"); }, errorNotifier, cleanupExecutor ); verify(errorNotifier).accept(any(Throwable.class)); verify(cleanupExecutor).run(); }
Http2GoAwayEventListener extends Http2ConnectionAdapter { @Override public void onGoAwayReceived(int lastStreamId, long errorCode, ByteBuf debugData) { Http2MultiplexedChannelPool channelPool = parentChannel.attr(ChannelAttributeKey.HTTP2_MULTIPLEXED_CHANNEL_POOL).get(); GoAwayException exception = new GoAwayException(errorCode, debugData.retain()); if (channelPool != null) { channelPool.handleGoAway(parentChannel, lastStreamId, exception); } else { log.warn(() -> "GOAWAY received on a connection (" + parentChannel + ") not associated with any multiplexed " + "channel pool."); parentChannel.pipeline().fireExceptionCaught(exception); } } Http2GoAwayEventListener(Channel parentChannel); @Override void onGoAwayReceived(int lastStreamId, long errorCode, ByteBuf debugData); }
@Test public void goAwayWithNoChannelPoolRecordRaisesNoExceptions() throws Exception { when(attribute.get()).thenReturn(null); new Http2GoAwayEventListener(channel).onGoAwayReceived(0, 0, Unpooled.EMPTY_BUFFER); verify(channelPipeline).fireExceptionCaught(isA(GoAwayException.class)); } @Test public void goAwayWithChannelPoolRecordPassesAlongTheFrame() throws Exception { Http2MultiplexedChannelPool record = mock(Http2MultiplexedChannelPool.class); when(attribute.get()).thenReturn(record); new Http2GoAwayEventListener(channel).onGoAwayReceived(0, 0, Unpooled.EMPTY_BUFFER); verify(record).handleGoAway(eq(channel), eq(0), isA(GoAwayException.class)); verifyNoMoreInteractions(record); }
Http2MultiplexedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } Http2MultiplexedChannelPool(ChannelPool connectionPool, EventLoopGroup eventLoopGroup, Duration idleConnectionTimeout); @SdkTestInternalApi Http2MultiplexedChannelPool(ChannelPool connectionPool, EventLoopGroup eventLoopGroup, Set<MultiplexedChannelRecord> connections, Duration idleConnectionTimeout); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel childChannel); @Override Future<Void> release(Channel childChannel, Promise<Void> promise); @Override void close(); @Override CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics); }
@Test public void failedConnectionAcquireNotifiesPromise() throws InterruptedException { IOException exception = new IOException(); ChannelPool connectionPool = mock(ChannelPool.class); when(connectionPool.acquire()).thenReturn(new FailedFuture<>(loopGroup.next(), exception)); ChannelPool pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup.next(), null); Future<Channel> acquirePromise = pool.acquire().await(); assertThat(acquirePromise.isSuccess()).isFalse(); assertThat(acquirePromise.cause()).isEqualTo(exception); }
Http2PingHandler extends SimpleChannelInboundHandler<Http2PingFrame> { @Override public void channelInactive(ChannelHandlerContext ctx) { stop(); ctx.fireChannelInactive(); } Http2PingHandler(int pingTimeoutMillis); @Override void handlerAdded(ChannelHandlerContext ctx); @Override void handlerRemoved(ChannelHandlerContext ctx); @Override void channelInactive(ChannelHandlerContext ctx); }
@Test public void channelInactive_shouldCancelTaskAndForwardToOtherHandlers() { EmbeddedChannel channel = createHttp2Channel(fastChecker); ChannelHandlerContext context = Mockito.mock(ChannelHandlerContext.class); fastChecker.channelInactive(context); Mockito.verify(context).fireChannelInactive(); channel.writeInbound(new DefaultHttp2PingFrame(0, false)); assertThat(channel.runScheduledPendingTasks()).isEqualTo(-1L); }
Http2SettingsFrameHandler extends SimpleChannelInboundHandler<Http2SettingsFrame> { @Override protected void channelRead0(ChannelHandlerContext ctx, Http2SettingsFrame msg) { Long serverMaxStreams = Optional.ofNullable(msg.settings().maxConcurrentStreams()).orElse(Long.MAX_VALUE); channel.attr(MAX_CONCURRENT_STREAMS).set(Math.min(clientMaxStreams, serverMaxStreams)); channel.attr(PROTOCOL_FUTURE).get().complete(Protocol.HTTP2); } Http2SettingsFrameHandler(Channel channel, long clientMaxStreams, AtomicReference<ChannelPool> channelPoolRef); @Override void channelUnregistered(ChannelHandlerContext ctx); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); }
@Test public void channelRead_useServerMaxStreams() { long serverMaxStreams = 50L; Http2SettingsFrame http2SettingsFrame = http2SettingsFrame(serverMaxStreams); handler.channelRead0(context, http2SettingsFrame); assertThat(channel.attr(MAX_CONCURRENT_STREAMS).get()).isEqualTo(serverMaxStreams); assertThat(protocolCompletableFuture).isDone(); assertThat(protocolCompletableFuture.join()).isEqualTo(Protocol.HTTP2); } @Test public void channelRead_useClientMaxStreams() { long serverMaxStreams = 10000L; Http2SettingsFrame http2SettingsFrame = http2SettingsFrame(serverMaxStreams); handler.channelRead0(context, http2SettingsFrame); assertThat(channel.attr(MAX_CONCURRENT_STREAMS).get()).isEqualTo(clientMaxStreams); assertThat(protocolCompletableFuture).isDone(); assertThat(protocolCompletableFuture.join()).isEqualTo(Protocol.HTTP2); }
Http2SettingsFrameHandler extends SimpleChannelInboundHandler<Http2SettingsFrame> { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { channelError(cause, channel, ctx); } Http2SettingsFrameHandler(Channel channel, long clientMaxStreams, AtomicReference<ChannelPool> channelPoolRef); @Override void channelUnregistered(ChannelHandlerContext ctx); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); }
@Test public void exceptionCaught_shouldHandleErrorCloseChannel() throws Exception { Throwable cause = new Throwable(new RuntimeException("BOOM")); handler.exceptionCaught(context, cause); verifyChannelError(cause.getClass()); }
Http2SettingsFrameHandler extends SimpleChannelInboundHandler<Http2SettingsFrame> { @Override public void channelUnregistered(ChannelHandlerContext ctx) { if (!channel.attr(PROTOCOL_FUTURE).get().isDone()) { channelError(new IOException("The channel was closed before the protocol could be determined."), channel, ctx); } } Http2SettingsFrameHandler(Channel channel, long clientMaxStreams, AtomicReference<ChannelPool> channelPoolRef); @Override void channelUnregistered(ChannelHandlerContext ctx); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); }
@Test public void channelUnregistered_ProtocolFutureNotDone_ShouldRaiseError() throws InterruptedException { handler.channelUnregistered(context); verifyChannelError(IOException.class); }
HttpToHttp2OutboundAdapter extends ChannelOutboundHandlerAdapter { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (!(msg instanceof HttpMessage || msg instanceof HttpContent)) { ctx.write(msg, promise); return; } boolean release = true; SimpleChannelPromiseAggregator promiseAggregator = new SimpleChannelPromiseAggregator(promise, ctx.channel(), ctx.executor()); try { boolean endStream = false; if (msg instanceof HttpMessage) { HttpMessage httpMsg = (HttpMessage) msg; Http2Headers http2Headers = HttpConversionUtil.toHttp2Headers(httpMsg, false); endStream = msg instanceof FullHttpMessage && !((FullHttpMessage) msg).content().isReadable(); ctx.write(new DefaultHttp2HeadersFrame(http2Headers), promiseAggregator.newPromise()); } if (!endStream && msg instanceof HttpContent) { boolean isLastContent = false; HttpHeaders trailers = EmptyHttpHeaders.INSTANCE; Http2Headers http2Trailers = EmptyHttp2Headers.INSTANCE; if (msg instanceof LastHttpContent) { isLastContent = true; LastHttpContent lastContent = (LastHttpContent) msg; trailers = lastContent.trailingHeaders(); http2Trailers = HttpConversionUtil.toHttp2Headers(trailers, false); } ByteBuf content = ((HttpContent) msg).content(); endStream = isLastContent && trailers.isEmpty(); release = false; ctx.write(new DefaultHttp2DataFrame(content, endStream), promiseAggregator.newPromise()); if (!trailers.isEmpty()) { ctx.write(new DefaultHttp2HeadersFrame(http2Trailers, true), promiseAggregator.newPromise()); } ctx.flush(); } } catch (Throwable t) { promiseAggregator.setFailure(t); } finally { if (release) { ReferenceCountUtil.release(msg); } promiseAggregator.doneAllocatingPromises(); } } HttpToHttp2OutboundAdapter(); @Override void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise); }
@Test public void aggregatesWritePromises() { when(ctx.executor()).thenReturn(EVENT_LOOP_GROUP.next()); when(ctx.channel()).thenReturn(channel); HttpToHttp2OutboundAdapter adapter = new HttpToHttp2OutboundAdapter(); ChannelPromise writePromise = new DefaultChannelPromise(channel, EVENT_LOOP_GROUP.next()); writeRequest(adapter, writePromise); ArgumentCaptor<ChannelPromise> writePromiseCaptor = ArgumentCaptor.forClass(ChannelPromise.class); verify(ctx, atLeastOnce()).write(any(Object.class), writePromiseCaptor.capture()); List<ChannelPromise> writePromises = writePromiseCaptor.getAllValues(); assertThat(writePromise.isDone()).isFalse(); writePromises.forEach(ChannelPromise::setSuccess); assertThat(writePromise.isDone()).isTrue(); }
MultiplexedChannelRecord { boolean acquireStream(Promise<Channel> promise) { if (claimStream()) { releaseClaimOnFailure(promise); acquireClaimedStream(promise); return true; } return false; } MultiplexedChannelRecord(Channel connection, long maxConcurrencyPerConnection, Duration allowedIdleConnectionTime); Channel getConnection(); }
@Test public void availableStream0_reusableShouldBeFalse() { loopGroup.register(channel).awaitUninterruptibly(); Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next()); channelPromise.setSuccess(channel); MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 0, Duration.ofSeconds(10)); assertThat(record.acquireStream(null)).isFalse(); }
HttpOrHttp2ChannelPool implements SdkChannelPool { @Override public void close() { doInEventLoop(eventLoop, this::close0); } HttpOrHttp2ChannelPool(ChannelPool delegatePool, EventLoopGroup group, int maxConcurrency, NettyConfiguration configuration); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); @Override CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics); }
@Test public void protocolConfigNotStarted_closeSucceeds() { httpOrHttp2ChannelPool.close(); } @Test public void protocolConfigNotStarted_closeClosesDelegatePool() throws InterruptedException { httpOrHttp2ChannelPool.close(); Thread.sleep(500); verify(mockDelegatePool).close(); }
Http2StreamExceptionHandler extends ChannelInboundHandlerAdapter { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (isIoError(cause) && ctx.channel().parent() != null) { Channel parent = ctx.channel().parent(); log.debug(() -> "An I/O error occurred on an Http2 stream, notifying the connection channel " + parent); parent.pipeline().fireExceptionCaught(new Http2ConnectionTerminatingException("An I/O error occurred on an " + "associated Http2 " + "stream " + ctx.channel())); } ctx.fireExceptionCaught(cause); } private Http2StreamExceptionHandler(); static Http2StreamExceptionHandler create(); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); }
@Test public void timeoutException_shouldFireExceptionAndPropagateException() { when(streamChannel.parent()).thenReturn(embeddedParentChannel); handler.exceptionCaught(context, ReadTimeoutException.INSTANCE); assertThat(verifyExceptionHandler.exceptionCaught).isExactlyInstanceOf(Http2ConnectionTerminatingException.class); verify(context).fireExceptionCaught(ReadTimeoutException.INSTANCE); } @Test public void ioException_shouldFireExceptionAndPropagateException() { IOException ioException = new IOException("yolo"); when(streamChannel.parent()).thenReturn(embeddedParentChannel); handler.exceptionCaught(context, ioException); assertThat(verifyExceptionHandler.exceptionCaught).isExactlyInstanceOf(Http2ConnectionTerminatingException.class); verify(context).fireExceptionCaught(ioException); } @Test public void otherException_shouldJustPropagateException() { when(streamChannel.parent()).thenReturn(embeddedParentChannel); RuntimeException otherException = new RuntimeException("test"); handler.exceptionCaught(context, otherException); assertThat(embeddedParentChannel.attr(PING_TRACKER).get()).isNull(); verify(context).fireExceptionCaught(otherException); assertThat(verifyExceptionHandler.exceptionCaught).isNull(); }
LastHttpContentHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof LastHttpContent) { logger.debug(() -> "Received LastHttpContent " + ctx.channel()); ctx.channel().attr(LAST_HTTP_CONTENT_RECEIVED_KEY).set(true); } ctx.fireChannelRead(msg); } @Override void channelRead(ChannelHandlerContext ctx, Object msg); static LastHttpContentHandler create(); }
@Test public void lastHttpContentReceived_shouldSetAttribute() { LastHttpContent lastHttpContent = LastHttpContent.EMPTY_LAST_CONTENT; contentHandler.channelRead(handlerContext, lastHttpContent); assertThat(channel.attr(LAST_HTTP_CONTENT_RECEIVED_KEY).get()).isTrue(); } @Test public void otherContentReceived_shouldNotSetAttribute() { String content = "some content"; contentHandler.channelRead(handlerContext, content); assertThat(channel.attr(LAST_HTTP_CONTENT_RECEIVED_KEY).get()).isFalse(); }
HonorCloseOnReleaseChannelPool implements ChannelPool { @Override public Future<Void> release(Channel channel) { return release(channel, channel.eventLoop().newPromise()); } HonorCloseOnReleaseChannelPool(ChannelPool delegatePool); @Override Future<Channel> acquire(); @Override Future<Channel> acquire(Promise<Channel> promise); @Override Future<Void> release(Channel channel); @Override Future<Void> release(Channel channel, Promise<Void> promise); @Override void close(); }
@Test public void releaseDoesntCloseIfNotFlagged() throws Exception { ChannelPool channelPool = Mockito.mock(ChannelPool.class); MockChannel channel = new MockChannel(); channel.attr(ChannelAttributeKey.CLOSE_ON_RELEASE).set(false); new HonorCloseOnReleaseChannelPool(channelPool).release(channel); channel.runAllPendingTasks(); assertThat(channel.isOpen()).isTrue(); Mockito.verify(channelPool, new Times(0)).release(any()); Mockito.verify(channelPool, new Times(1)).release(any(), any()); } @Test public void releaseClosesIfFlagged() throws Exception { ChannelPool channelPool = Mockito.mock(ChannelPool.class); MockChannel channel = new MockChannel(); channel.attr(ChannelAttributeKey.CLOSE_ON_RELEASE).set(true); new HonorCloseOnReleaseChannelPool(channelPool).release(channel); channel.runAllPendingTasks(); assertThat(channel.isOpen()).isFalse(); Mockito.verify(channelPool, new Times(0)).release(any()); Mockito.verify(channelPool, new Times(1)).release(any(), any()); }
ChannelPipelineInitializer extends AbstractChannelPoolHandler { @Override public void channelCreated(Channel ch) { ch.attr(PROTOCOL_FUTURE).set(new CompletableFuture<>()); ChannelPipeline pipeline = ch.pipeline(); if (sslCtx != null) { SslHandler sslHandler = sslCtx.newHandler(ch.alloc(), poolKey.getHost(), poolKey.getPort()); configureSslEngine(sslHandler.engine()); pipeline.addLast(sslHandler); pipeline.addLast(SslCloseCompletionEventHandler.getInstance()); if (sslProvider == SslProvider.JDK) { ch.config().setOption(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT); } } if (protocol == Protocol.HTTP2) { configureHttp2(ch, pipeline); } else { configureHttp11(ch, pipeline); } if (configuration.reapIdleConnections()) { pipeline.addLast(new IdleConnectionReaperHandler(configuration.idleTimeoutMillis())); } if (configuration.connectionTtlMillis() > 0) { pipeline.addLast(new OldConnectionReaperHandler(configuration.connectionTtlMillis())); } pipeline.addLast(FutureCancelHandler.getInstance()); if (protocol == Protocol.HTTP1_1) { pipeline.addLast(UnusedChannelExceptionHandler.getInstance()); } pipeline.addLast(new LoggingHandler(LogLevel.DEBUG)); } ChannelPipelineInitializer(Protocol protocol, SslContext sslCtx, SslProvider sslProvider, long clientMaxStreams, int clientInitialWindowSize, Duration healthCheckPingPeriod, AtomicReference<ChannelPool> channelPoolRef, NettyConfiguration configuration, URI poolKey); @Override void channelCreated(Channel ch); }
@Test public void channelConfigOptionCheck() throws SSLException { targetUri = URI.create("https: SslContext sslContext = SslContextBuilder.forClient() .sslProvider(SslProvider.JDK) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .build(); AtomicReference<ChannelPool> channelPoolRef = new AtomicReference<>(); NettyConfiguration nettyConfiguration = new NettyConfiguration(GLOBAL_HTTP_DEFAULTS); pipelineInitializer = new ChannelPipelineInitializer(Protocol.HTTP1_1, sslContext, SslProvider.JDK, 100, 1024, Duration.ZERO, channelPoolRef, nettyConfiguration, targetUri); Channel channel = new EmbeddedChannel(); pipelineInitializer.channelCreated(channel); assertThat(channel.config().getOption(ChannelOption.ALLOCATOR), is(UnpooledByteBufAllocator.DEFAULT)); }
StaticKeyManagerFactorySpi extends KeyManagerFactorySpi { @Override protected KeyManager[] engineGetKeyManagers() { return keyManagers; } StaticKeyManagerFactorySpi(KeyManager[] keyManagers); }
@Test public void constructorCreatesArrayCopy() { KeyManager[] keyManagers = IntStream.range(0,8) .mapToObj(i -> mock(KeyManager.class)) .toArray(KeyManager[]::new); KeyManager[] arg = Arrays.copyOf(keyManagers, keyManagers.length); StaticKeyManagerFactorySpi spi = new StaticKeyManagerFactorySpi(arg); for (int i = 0; i < keyManagers.length; ++i) { arg[i] = null; } assertThat(spi.engineGetKeyManagers()).containsExactly(keyManagers); } @Test public void engineGetKeyManagers_returnsProvidedList() { KeyManager[] keyManagers = IntStream.range(0,8) .mapToObj(i -> mock(KeyManager.class)) .toArray(KeyManager[]::new); StaticKeyManagerFactorySpi spi = new StaticKeyManagerFactorySpi(keyManagers); assertThat(spi.engineGetKeyManagers()).containsExactly(keyManagers); }
StaticKeyManagerFactorySpi extends KeyManagerFactorySpi { @Override protected void engineInit(KeyStore ks, char[] password) { throw new UnsupportedOperationException("engineInit not supported by this KeyManagerFactory"); } StaticKeyManagerFactorySpi(KeyManager[] keyManagers); }
@Test(expected = UnsupportedOperationException.class) public void engineInit_storeAndPasswords_throws() { StaticKeyManagerFactorySpi staticKeyManagerFactorySpi = new StaticKeyManagerFactorySpi(new KeyManager[0]); staticKeyManagerFactorySpi.engineInit(null, null); } @Test(expected = UnsupportedOperationException.class) public void engineInit_spec_throws() { StaticKeyManagerFactorySpi staticKeyManagerFactorySpi = new StaticKeyManagerFactorySpi(new KeyManager[0]); staticKeyManagerFactorySpi.engineInit(null); }
LastHttpContentSwallower extends SimpleChannelInboundHandler<HttpObject> { @Override protected void channelRead0(ChannelHandlerContext ctx, HttpObject obj) { if (obj instanceof LastHttpContent) { ctx.read(); } else { ctx.fireChannelRead(obj); } ctx.pipeline().remove(this); } private LastHttpContentSwallower(); static LastHttpContentSwallower getInstance(); }
@Test public void testOtherHttpObjectRead_removesSelfFromPipeline() { HttpObject contentObject = mock(HttpContent.class); lastHttpContentSwallower.channelRead0(mockCtx, contentObject); verify(mockPipeline).remove(eq(lastHttpContentSwallower)); } @Test public void testLastHttpContentRead_removesSelfFromPipeline() { LastHttpContent lastContent = mock(LastHttpContent.class); lastHttpContentSwallower.channelRead0(mockCtx, lastContent); verify(mockPipeline).remove(eq(lastHttpContentSwallower)); } @Test public void testLastHttpContentRead_swallowsObject() { LastHttpContent lastContent = mock(LastHttpContent.class); lastHttpContentSwallower.channelRead0(mockCtx, lastContent); verify(mockCtx, times(0)).fireChannelRead(eq(lastContent)); } @Test public void testOtherHttpObjectRead_doesNotSwallowObject() { HttpContent content = mock(HttpContent.class); lastHttpContentSwallower.channelRead0(mockCtx, content); verify(mockCtx).fireChannelRead(eq(content)); } @Test public void testCallsReadAfterSwallowingContent() { LastHttpContent lastContent = mock(LastHttpContent.class); lastHttpContentSwallower.channelRead0(mockCtx, lastContent); verify(mockCtx).read(); }
RequestAdapter { public HttpRequest adapt(SdkHttpRequest sdkRequest) { HttpMethod method = toNettyHttpMethod(sdkRequest.method()); HttpHeaders headers = new DefaultHttpHeaders(); String uri = encodedPathAndQueryParams(sdkRequest); DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, method, uri, headers); addHeadersToRequest(request, sdkRequest); return request; } RequestAdapter(Protocol protocol); HttpRequest adapt(SdkHttpRequest sdkRequest); }
@Test public void adapt_h1Request_requestIsCorrect() { SdkHttpRequest request = SdkHttpRequest.builder() .uri(URI.create("http: .putRawQueryParameter("foo", "bar") .putRawQueryParameter("bar", "baz") .putHeader("header1", "header1val") .putHeader("header2", "header2val") .method(SdkHttpMethod.GET) .build(); HttpRequest adapted = h1Adapter.adapt(request); assertThat(adapted.method()).isEqualTo(HttpMethod.valueOf("GET")); assertThat(adapted.uri()).isEqualTo("/foo/bar/baz?foo=bar&bar=baz"); assertThat(adapted.protocolVersion()).isEqualTo(HttpVersion.HTTP_1_1); assertThat(adapted.headers().getAll("Host")).containsExactly("localhost:12345"); assertThat(adapted.headers().getAll("header1")).containsExactly("header1val"); assertThat(adapted.headers().getAll("header2")).containsExactly("header2val"); } @Test public void adapt_h2Request_addsSchemeExtension() { SdkHttpRequest request = SdkHttpRequest.builder() .uri(URI.create("http: .putRawQueryParameter("foo", "bar") .putRawQueryParameter("bar", "baz") .putHeader("header1", "header1val") .putHeader("header2", "header2val") .method(SdkHttpMethod.GET) .build(); HttpRequest adapted = h2Adapter.adapt(request); assertThat(adapted.headers().getAll(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text())).containsExactly("http"); } @Test public void adapt_noPathContainsQueryParams() { SdkHttpRequest request = SdkHttpRequest.builder() .host("localhost:12345") .protocol("http") .putRawQueryParameter("foo", "bar") .putRawQueryParameter("bar", "baz") .putHeader("header1", "header1val") .putHeader("header2", "header2val") .method(SdkHttpMethod.GET) .build(); HttpRequest adapted = h1Adapter.adapt(request); assertThat(adapted.method()).isEqualTo(HttpMethod.valueOf("GET")); assertThat(adapted.uri()).isEqualTo("/?foo=bar&bar=baz"); assertThat(adapted.protocolVersion()).isEqualTo(HttpVersion.HTTP_1_1); assertThat(adapted.headers().getAll("Host")).containsExactly("localhost:12345"); } @Test public void adapt_hostHeaderSet() { SdkHttpRequest sdkRequest = SdkHttpRequest.builder() .uri(URI.create("http: .method(SdkHttpMethod.HEAD) .build(); HttpRequest result = h1Adapter.adapt(sdkRequest); List<String> hostHeaders = result.headers() .getAll(HttpHeaderNames.HOST.toString()); assertThat(hostHeaders).containsExactly("localhost:12345"); } @Test public void adapt_standardHttpsPort_omittedInHeader() { SdkHttpRequest sdkRequest = SdkHttpRequest.builder() .uri(URI.create("https: .method(SdkHttpMethod.HEAD) .build(); HttpRequest result = h1Adapter.adapt(sdkRequest); List<String> hostHeaders = result.headers() .getAll(HttpHeaderNames.HOST.toString()); assertThat(hostHeaders).containsExactly("localhost"); } @Test public void adapt_containsQueryParamsRequiringEncoding() { SdkHttpRequest request = SdkHttpRequest.builder() .uri(URI.create("http: .putRawQueryParameter("java", "☕") .putRawQueryParameter("python", "\uD83D\uDC0D") .method(SdkHttpMethod.GET) .build(); HttpRequest adapted = h1Adapter.adapt(request); assertThat(adapted.uri()).isEqualTo("/?java=%E2%98%95&python=%F0%9F%90%8D"); } @Test public void adapt_pathEmpty_setToRoot() { SdkHttpRequest request = SdkHttpRequest.builder() .uri(URI.create("http: .method(SdkHttpMethod.GET) .build(); HttpRequest adapted = h1Adapter.adapt(request); assertThat(adapted.uri()).isEqualTo("/"); } @Test public void adapt_defaultPortUsed() { SdkHttpRequest sdkRequest = SdkHttpRequest.builder() .uri(URI.create("http: .method(SdkHttpMethod.HEAD) .build(); HttpRequest result = h1Adapter.adapt(sdkRequest); List<String> hostHeaders = result.headers() .getAll(HttpHeaderNames.HOST.toString()); assertNotNull(hostHeaders); assertEquals(1, hostHeaders.size()); assertEquals("localhost", hostHeaders.get(0)); sdkRequest = SdkHttpRequest.builder() .uri(URI.create("https: .method(SdkHttpMethod.HEAD) .build(); result = h1Adapter.adapt(sdkRequest); hostHeaders = result.headers() .getAll(HttpHeaderNames.HOST.toString()); assertNotNull(hostHeaders); assertEquals(1, hostHeaders.size()); assertEquals("localhost", hostHeaders.get(0)); } @Test public void adapt_nonStandardHttpPort() { SdkHttpRequest sdkRequest = SdkHttpRequest.builder() .uri(URI.create("http: .method(SdkHttpMethod.HEAD) .build(); HttpRequest result = h1Adapter.adapt(sdkRequest); List<String> hostHeaders = result.headers() .getAll(HttpHeaderNames.HOST.toString()); assertThat(hostHeaders).containsExactly("localhost:8080"); } @Test public void adapt_nonStandardHttpsPort() { SdkHttpRequest sdkRequest = SdkHttpRequest.builder() .uri(URI.create("https: .method(SdkHttpMethod.HEAD) .build(); HttpRequest result = h1Adapter.adapt(sdkRequest); List<String> hostHeaders = result.headers() .getAll(HttpHeaderNames.HOST.toString()); assertThat(hostHeaders).containsExactly("localhost:8443"); }
S3BucketResource implements S3Resource, ToCopyableBuilder<S3BucketResource.Builder, S3BucketResource> { @Override public Builder toBuilder() { return builder() .partition(partition) .region(region) .accountId(accountId) .bucketName(bucketName); } private S3BucketResource(Builder b); static Builder builder(); @Override String type(); @Override Optional<String> partition(); @Override Optional<String> region(); @Override Optional<String> accountId(); String bucketName(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); }
@Test public void toBuilder() { S3BucketResource s3BucketResource = S3BucketResource.builder() .bucketName("bucket") .accountId("account-id") .partition("partition") .region("region") .build() .toBuilder() .build(); assertEquals("bucket", s3BucketResource.bucketName()); assertEquals(Optional.of("account-id"), s3BucketResource.accountId()); assertEquals(Optional.of("partition"), s3BucketResource.partition()); assertEquals(Optional.of("region"), s3BucketResource.region()); assertEquals("bucket_name", s3BucketResource.type()); }
BootstrapProvider { public Bootstrap createBootstrap(String host, int port) { Bootstrap bootstrap = new Bootstrap() .group(sdkEventLoopGroup.eventLoopGroup()) .channelFactory(sdkEventLoopGroup.channelFactory()) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, nettyConfiguration.connectTimeoutMillis()) .remoteAddress(InetSocketAddress.createUnresolved(host, port)); sdkChannelOptions.channelOptions().forEach(bootstrap::option); return bootstrap; } BootstrapProvider(SdkEventLoopGroup sdkEventLoopGroup, NettyConfiguration nettyConfiguration, SdkChannelOptions sdkChannelOptions); Bootstrap createBootstrap(String host, int port); }
@Test public void createBootstrap_usesUnresolvedInetSocketAddress() { Bootstrap bootstrap = bootstrapProvider.createBootstrap("some-awesome-service-1234.amazonaws.com", 443); SocketAddress socketAddress = bootstrap.config().remoteAddress(); assertThat(socketAddress).isInstanceOf(InetSocketAddress.class); InetSocketAddress inetSocketAddress = (InetSocketAddress)socketAddress; assertThat(inetSocketAddress.isUnresolved()).isTrue(); }
StaticKeyManagerFactory extends KeyManagerFactory { public static StaticKeyManagerFactory create(KeyManager[] keyManagers) { return new StaticKeyManagerFactory(keyManagers); } private StaticKeyManagerFactory(KeyManager[] keyManagers); static StaticKeyManagerFactory create(KeyManager[] keyManagers); }
@Test public void createReturnFactoryWithCorrectKeyManagers() { KeyManager[] keyManagers = IntStream.range(0,8) .mapToObj(i -> mock(KeyManager.class)) .toArray(KeyManager[]::new); StaticKeyManagerFactory staticKeyManagerFactory = StaticKeyManagerFactory.create(keyManagers); assertThat(staticKeyManagerFactory.getKeyManagers()) .containsExactly(keyManagers); }
SdkChannelOptions { public Map<ChannelOption, Object> channelOptions() { return Collections.unmodifiableMap(options); } SdkChannelOptions(); SdkChannelOptions putOption(ChannelOption<T> channelOption, T channelOptionValue); Map<ChannelOption, Object> channelOptions(); }
@Test public void defaultSdkSocketOptionPresent() { SdkChannelOptions channelOptions = new SdkChannelOptions(); Map<ChannelOption, Object> expectedOptions = new HashMap<>(); expectedOptions.put(ChannelOption.TCP_NODELAY, Boolean.TRUE); assertEquals(expectedOptions, channelOptions.channelOptions()); }
SdkEventLoopGroup { public static SdkEventLoopGroup create(EventLoopGroup eventLoopGroup, ChannelFactory<? extends Channel> channelFactory) { return new SdkEventLoopGroup(eventLoopGroup, channelFactory); } SdkEventLoopGroup(EventLoopGroup eventLoopGroup, ChannelFactory<? extends Channel> channelFactory); private SdkEventLoopGroup(DefaultBuilder builder); EventLoopGroup eventLoopGroup(); ChannelFactory<? extends Channel> channelFactory(); static SdkEventLoopGroup create(EventLoopGroup eventLoopGroup, ChannelFactory<? extends Channel> channelFactory); static SdkEventLoopGroup create(EventLoopGroup eventLoopGroup); static Builder builder(); }
@Test(expected = IllegalArgumentException.class) public void notProvidingChannelFactory_unknownEventLoopGroup() { SdkEventLoopGroup.create(new DefaultEventLoopGroup()); }
ProxyConfiguration implements ToCopyableBuilder<ProxyConfiguration.Builder, ProxyConfiguration> { @Override public Builder toBuilder() { return new BuilderImpl(this); } private ProxyConfiguration(BuilderImpl builder); String scheme(); String host(); int port(); String username(); String password(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); static Builder builder(); }
@Test public void toBuilder_roundTrip_producesExactCopy() { ProxyConfiguration original = allPropertiesSetConfig(); ProxyConfiguration copy = original.toBuilder().build(); assertThat(copy).isEqualTo(original); } @Test public void toBuilderModified_doesNotModifySource() { ProxyConfiguration original = allPropertiesSetConfig(); ProxyConfiguration modified = setAllPropertiesToRandomValues(original.toBuilder()).build(); assertThat(original).isNotEqualTo(modified); }
CrtRequestExecutor { public CompletableFuture<Void> execute(CrtRequestContext executionContext) { CompletableFuture<Void> requestFuture = createExecutionFuture(executionContext.sdkRequest()); CompletableFuture<HttpClientConnection> httpClientConnectionCompletableFuture = executionContext.crtConnPool().acquireConnection(); httpClientConnectionCompletableFuture.whenComplete((crtConn, throwable) -> { AsyncExecuteRequest asyncRequest = executionContext.sdkRequest(); if (throwable != null) { handleFailure(new IOException("An exception occurred when acquiring connection", throwable), requestFuture, asyncRequest.responseHandler()); return; } AwsCrtAsyncHttpStreamAdapter crtToSdkAdapter = new AwsCrtAsyncHttpStreamAdapter(crtConn, requestFuture, asyncRequest, executionContext.readBufferSize()); HttpRequest crtRequest = toCrtRequest(asyncRequest, crtToSdkAdapter); invokeSafely(() -> { try { crtConn.makeRequest(crtRequest, crtToSdkAdapter).activate(); } catch (IllegalStateException | CrtRuntimeException e) { log.debug(() -> "An exception occurred when making the request", e); handleFailure(new IOException("An exception occurred when making the request", e), requestFuture, asyncRequest.responseHandler()); } }); }); return requestFuture; } CompletableFuture<Void> execute(CrtRequestContext executionContext); }
@Test public void acquireConnectionThrowException_shouldInvokeOnError() { RuntimeException exception = new RuntimeException("error"); CrtRequestContext context = CrtRequestContext.builder() .crtConnPool(connectionManager) .request(AsyncExecuteRequest.builder() .responseHandler(responseHandler) .build()) .build(); CompletableFuture<HttpClientConnection> completableFuture = new CompletableFuture<>(); Mockito.when(connectionManager.acquireConnection()).thenReturn(completableFuture); completableFuture.completeExceptionally(exception); CompletableFuture<Void> executeFuture = requestExecutor.execute(context); ArgumentCaptor<Exception> argumentCaptor = ArgumentCaptor.forClass(Exception.class); Mockito.verify(responseHandler).onError(argumentCaptor.capture()); Exception actualException = argumentCaptor.getValue(); assertThat(actualException).hasMessageContaining("An exception occurred when acquiring connection"); assertThat(actualException).hasCause(exception); assertThat(executeFuture).hasFailedWithThrowableThat().hasCause(exception).isInstanceOf(IOException.class); } @Test public void makeRequestThrowException_shouldInvokeOnError() { CrtRuntimeException exception = new CrtRuntimeException(""); SdkHttpFullRequest request = createRequest(URI.create("http: CrtRequestContext context = CrtRequestContext.builder() .readBufferSize(2000) .crtConnPool(connectionManager) .request(AsyncExecuteRequest.builder() .request(request) .requestContentPublisher(createProvider("")) .responseHandler(responseHandler) .build()) .build(); CompletableFuture<HttpClientConnection> completableFuture = new CompletableFuture<>(); Mockito.when(connectionManager.acquireConnection()).thenReturn(completableFuture); completableFuture.complete(httpClientConnection); Mockito.when(httpClientConnection.makeRequest(Mockito.any(HttpRequest.class), Mockito.any(AwsCrtAsyncHttpStreamAdapter.class))) .thenThrow(exception); CompletableFuture<Void> executeFuture = requestExecutor.execute(context); ArgumentCaptor<Exception> argumentCaptor = ArgumentCaptor.forClass(Exception.class); Mockito.verify(responseHandler).onError(argumentCaptor.capture()); Exception actualException = argumentCaptor.getValue(); assertThat(actualException).hasMessageContaining("An exception occurred when making the request"); assertThat(actualException).hasCause(exception); assertThat(executeFuture).hasFailedWithThrowableThat().hasCause(exception).isInstanceOf(IOException.class); } @Test public void makeRequest_success() { SdkHttpFullRequest request = createRequest(URI.create("http: CrtRequestContext context = CrtRequestContext.builder() .readBufferSize(2000) .crtConnPool(connectionManager) .request(AsyncExecuteRequest.builder() .request(request) .requestContentPublisher(createProvider("")) .responseHandler(responseHandler) .build()) .build(); CompletableFuture<HttpClientConnection> completableFuture = new CompletableFuture<>(); Mockito.when(connectionManager.acquireConnection()).thenReturn(completableFuture); completableFuture.complete(httpClientConnection); CompletableFuture<Void> executeFuture = requestExecutor.execute(context); Mockito.verifyZeroInteractions(responseHandler); } @Test public void cancelRequest_shouldInvokeOnError() { CrtRequestContext context = CrtRequestContext.builder() .crtConnPool(connectionManager) .request(AsyncExecuteRequest.builder() .responseHandler(responseHandler) .build()) .build(); CompletableFuture<HttpClientConnection> completableFuture = new CompletableFuture<>(); Mockito.when(connectionManager.acquireConnection()).thenReturn(completableFuture); CompletableFuture<Void> executeFuture = requestExecutor.execute(context); executeFuture.cancel(true); ArgumentCaptor<Exception> argumentCaptor = ArgumentCaptor.forClass(Exception.class); Mockito.verify(responseHandler).onError(argumentCaptor.capture()); Exception actualException = argumentCaptor.getValue(); assertThat(actualException).hasMessageContaining("The request was cancelled"); assertThat(actualException).isInstanceOf(SdkCancellationException.class); }
S3BucketResource implements S3Resource, ToCopyableBuilder<S3BucketResource.Builder, S3BucketResource> { public static Builder builder() { return new Builder(); } private S3BucketResource(Builder b); static Builder builder(); @Override String type(); @Override Optional<String> partition(); @Override Optional<String> region(); @Override Optional<String> accountId(); String bucketName(); @Override boolean equals(Object o); @Override int hashCode(); @Override Builder toBuilder(); }
@Test(expected = NullPointerException.class) public void buildWithMissingBucketName() { S3BucketResource.builder().build(); }
ApacheHttpClient implements SdkHttpClient { public static Builder builder() { return new DefaultBuilder(); } @SdkTestInternalApi ApacheHttpClient(ConnectionManagerAwareHttpClient httpClient, ApacheHttpRequestConfig requestConfig, AttributeMap resolvedOptions); private ApacheHttpClient(DefaultBuilder builder, AttributeMap resolvedOptions); static Builder builder(); static SdkHttpClient create(); @Override ExecutableHttpRequest prepareRequest(HttpExecuteRequest request); @Override void close(); @Override String clientName(); static final String CLIENT_NAME; }
@Test public void httpRoutePlannerCantBeUsedWithProxy_SystemPropertiesEnabled() { System.setProperty("http.proxyHost", "localhost"); System.setProperty("http.proxyPort", "1234"); assertThatThrownBy(() -> { ApacheHttpClient.builder() .httpRoutePlanner(Mockito.mock(HttpRoutePlanner.class)) .build(); }).isInstanceOf(IllegalArgumentException.class); } @Test public void httpRoutePlannerCantBeUsedWithProxy_SystemPropertiesDisabled() { System.setProperty("http.proxyHost", "localhost"); System.setProperty("http.proxyPort", "1234"); ProxyConfiguration proxyConfig = ProxyConfiguration.builder() .useSystemPropertyValues(Boolean.FALSE) .build(); ApacheHttpClient.builder() .proxyConfiguration(proxyConfig) .httpRoutePlanner(Mockito.mock(HttpRoutePlanner.class)) .build(); } @Test public void credentialProviderCantBeUsedWithProxyCredentials_SystemProperties() { System.setProperty("http.proxyUser", "foo"); System.setProperty("http.proxyPassword", "bar"); assertThatThrownBy(() -> { ApacheHttpClient.builder() .credentialsProvider(Mockito.mock(CredentialsProvider.class)) .build(); }).isInstanceOf(IllegalArgumentException.class); }
IdleConnectionReaper { public synchronized boolean registerConnectionManager(HttpClientConnectionManager manager, long maxIdleTime) { boolean notPreviouslyRegistered = connectionManagers.put(manager, maxIdleTime) == null; setupExecutorIfNecessary(); return notPreviouslyRegistered; } private IdleConnectionReaper(); @SdkTestInternalApi IdleConnectionReaper(Map<HttpClientConnectionManager, Long> connectionManagers, Supplier<ExecutorService> executorServiceSupplier, long sleepPeriod); synchronized boolean registerConnectionManager(HttpClientConnectionManager manager, long maxIdleTime); synchronized boolean deregisterConnectionManager(HttpClientConnectionManager manager); static IdleConnectionReaper getInstance(); }
@Test public void setsUpExecutorIfManagerNotPreviouslyRegistered() { idleConnectionReaper.registerConnectionManager(connectionManager, 1L); verify(executorService).execute(any(Runnable.class)); }
SdkTlsSocketFactory extends SSLConnectionSocketFactory { @Override protected final void prepareSocket(final SSLSocket socket) { String[] supported = socket.getSupportedProtocols(); String[] enabled = socket.getEnabledProtocols(); log.debug(() -> String.format("socket.getSupportedProtocols(): %s, socket.getEnabledProtocols(): %s", Arrays.toString(supported), Arrays.toString(enabled))); List<String> target = new ArrayList<>(); if (supported != null) { TlsProtocol[] values = TlsProtocol.values(); for (TlsProtocol value : values) { String pname = value.getProtocolName(); if (existsIn(pname, supported)) { target.add(pname); } } } if (enabled != null) { for (String pname : enabled) { if (!target.contains(pname)) { target.add(pname); } } } if (target.size() > 0) { String[] enabling = target.toArray(new String[0]); socket.setEnabledProtocols(enabling); log.debug(() -> "TLS protocol enabled for SSL handshake: " + Arrays.toString(enabling)); } } SdkTlsSocketFactory(final SSLContext sslContext, final HostnameVerifier hostnameVerifier); @Override Socket connectSocket( final int connectTimeout, final Socket socket, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context); }
@Test public void preparedSocket_NullProtocols() throws NoSuchAlgorithmException, IOException { SdkTlsSocketFactory f = new SdkTlsSocketFactory(SSLContext.getDefault(), null); try (SSLSocket socket = new TestSSLSocket() { @Override public String[] getSupportedProtocols() { return null; } @Override public String[] getEnabledProtocols() { return null; } @Override public void setEnabledProtocols(String[] protocols) { fail(); } }) { f.prepareSocket(socket); } } @Test public void typical() throws NoSuchAlgorithmException, IOException { SdkTlsSocketFactory f = new SdkTlsSocketFactory(SSLContext.getDefault(), null); try (SSLSocket socket = new TestSSLSocket() { @Override public String[] getSupportedProtocols() { return shuffle(new String[] {"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"}); } @Override public String[] getEnabledProtocols() { return shuffle(new String[] {"SSLv3", "TLSv1"}); } @Override public void setEnabledProtocols(String[] protocols) { assertTrue(Arrays.equals(protocols, new String[] {"TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3"})); } }) { f.prepareSocket(socket); } } @Test public void noTLS() throws NoSuchAlgorithmException, IOException { SdkTlsSocketFactory f = new SdkTlsSocketFactory(SSLContext.getDefault(), null); try (SSLSocket socket = new TestSSLSocket() { @Override public String[] getSupportedProtocols() { return shuffle(new String[] {"SSLv2Hello", "SSLv3"}); } @Override public String[] getEnabledProtocols() { return new String[] {"SSLv3"}; } @Override public void setEnabledProtocols(String[] protocols) { assertTrue(Arrays.equals(protocols, new String[] {"SSLv3"})); } }) { f.prepareSocket(socket); } } @Test public void notIdeal() throws NoSuchAlgorithmException, IOException { SdkTlsSocketFactory f = new SdkTlsSocketFactory(SSLContext.getDefault(), null); try (SSLSocket socket = new TestSSLSocket() { @Override public String[] getSupportedProtocols() { return shuffle(new String[] {"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.1"}); } @Override public String[] getEnabledProtocols() { return shuffle(new String[] {"SSLv3", "TLSv1"}); } @Override public void setEnabledProtocols(String[] protocols) { assertTrue(Arrays.equals(protocols, new String[] {"TLSv1.1", "TLSv1", "SSLv3"})); } }) { f.prepareSocket(socket); } }
ClientConnectionManagerFactory { public static HttpClientConnectionManager wrap(HttpClientConnectionManager orig) { if (orig instanceof Wrapped) { throw new IllegalArgumentException(); } Class<?>[] interfaces; if (orig instanceof ConnPoolControl) { interfaces = new Class<?>[]{ HttpClientConnectionManager.class, ConnPoolControl.class, Wrapped.class}; } else { interfaces = new Class<?>[]{ HttpClientConnectionManager.class, Wrapped.class }; } return (HttpClientConnectionManager) Proxy.newProxyInstance( ClientConnectionManagerFactory.class.getClassLoader(), interfaces, new Handler(orig)); } private ClientConnectionManagerFactory(); static HttpClientConnectionManager wrap(HttpClientConnectionManager orig); }
@Test public void wrapOnce() { HttpClientConnectionManager wrapped = ClientConnectionManagerFactory.wrap(noop); assertTrue(wrapped instanceof Wrapped); } @Test(expected = IllegalArgumentException.class) public void wrapTwice() { HttpClientConnectionManager wrapped = ClientConnectionManagerFactory.wrap(noop); ClientConnectionManagerFactory.wrap(wrapped); }
ProfileUseArnRegionProvider implements UseArnRegionProvider { @Override public Optional<Boolean> resolveUseArnRegion() { return profileFile.get() .profile(profileName) .map(p -> p.properties().get(AWS_USE_ARN_REGION)) .map(StringUtils::safeStringToBoolean); } private ProfileUseArnRegionProvider(Supplier<ProfileFile> profileFile, String profileName); static ProfileUseArnRegionProvider create(); static ProfileUseArnRegionProvider create(ProfileFile profileFile, String profileName); @Override Optional<Boolean> resolveUseArnRegion(); }
@Test public void notSpecified_shouldReturnEmptyOptional() { assertThat(provider.resolveUseArnRegion()).isEqualTo(Optional.empty()); } @Test public void specifiedInConfigFile_shouldResolve() { String configFile = getClass().getResource("UseArnRegionSet_true").getFile(); System.setProperty(AWS_CONFIG_FILE.property(), configFile); assertThat(provider.resolveUseArnRegion()).isEqualTo(Optional.of(TRUE)); } @Test public void configFile_mixedSpace() { String configFile = getClass().getResource("UseArnRegionSet_mixedSpace").getFile(); System.setProperty(AWS_CONFIG_FILE.property(), configFile); assertThat(provider.resolveUseArnRegion()).isEqualTo(Optional.of(FALSE)); } @Test public void unsupportedValue_shouldThrowException() { String configFile = getClass().getResource("UseArnRegionSet_unsupportedValue").getFile(); System.setProperty(AWS_CONFIG_FILE.property(), configFile); assertThatThrownBy(() -> provider.resolveUseArnRegion()).isInstanceOf(IllegalArgumentException.class); } @Test public void commaNoSpace_shouldResolveCorrectly() { String configFile = getClass().getResource("UseArnRegionSet_noSpace").getFile(); System.setProperty(AWS_CONFIG_FILE.property(), configFile); assertThat(provider.resolveUseArnRegion()).isEqualTo(Optional.of(FALSE)); }
ApacheHttpRequestFactory { public HttpRequestBase create(final HttpExecuteRequest request, final ApacheHttpRequestConfig requestConfig) { HttpRequestBase base = createApacheRequest(request, sanitizeUri(request.httpRequest())); addHeadersToRequest(base, request.httpRequest()); addRequestConfig(base, request.httpRequest(), requestConfig); return base; } HttpRequestBase create(final HttpExecuteRequest request, final ApacheHttpRequestConfig requestConfig); }
@Test public void ceateSetsHostHeaderByDefault() { SdkHttpRequest sdkRequest = SdkHttpRequest.builder() .uri(URI.create("http: .method(SdkHttpMethod.HEAD) .build(); HttpExecuteRequest request = HttpExecuteRequest.builder() .request(sdkRequest) .build(); HttpRequestBase result = instance.create(request, requestConfig); Header[] hostHeaders = result.getHeaders(HttpHeaders.HOST); assertNotNull(hostHeaders); assertEquals(1, hostHeaders.length); assertEquals("localhost:12345", hostHeaders[0].getValue()); } @Test public void defaultHttpPortsAreNotInDefaultHostHeader() { SdkHttpRequest sdkRequest = SdkHttpRequest.builder() .uri(URI.create("http: .method(SdkHttpMethod.HEAD) .build(); HttpExecuteRequest request = HttpExecuteRequest.builder() .request(sdkRequest) .build(); HttpRequestBase result = instance.create(request, requestConfig); Header[] hostHeaders = result.getHeaders(HttpHeaders.HOST); assertNotNull(hostHeaders); assertEquals(1, hostHeaders.length); assertEquals("localhost", hostHeaders[0].getValue()); sdkRequest = SdkHttpRequest.builder() .uri(URI.create("https: .method(SdkHttpMethod.HEAD) .build(); request = HttpExecuteRequest.builder() .request(sdkRequest) .build(); result = instance.create(request, requestConfig); hostHeaders = result.getHeaders(HttpHeaders.HOST); assertNotNull(hostHeaders); assertEquals(1, hostHeaders.length); assertEquals("localhost", hostHeaders[0].getValue()); }
ProfileUseArnRegionProvider implements UseArnRegionProvider { public static ProfileUseArnRegionProvider create() { return new ProfileUseArnRegionProvider(ProfileFile::defaultProfileFile, ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow()); } private ProfileUseArnRegionProvider(Supplier<ProfileFile> profileFile, String profileName); static ProfileUseArnRegionProvider create(); static ProfileUseArnRegionProvider create(ProfileFile profileFile, String profileName); @Override Optional<Boolean> resolveUseArnRegion(); }
@Test public void specifiedInOverrideConfig_shouldUse() { ExecutionInterceptor interceptor = Mockito.spy(AbstractExecutionInterceptor.class); String profileFileContent = "[default]\n" + "s3_use_arn_region = true\n"; ProfileFile profileFile = ProfileFile.builder() .type(ProfileFile.Type.CONFIGURATION) .content(new StringInputStream(profileFileContent)) .build(); S3Client s3 = S3Client.builder() .region(Region.US_WEST_2) .credentialsProvider(AnonymousCredentialsProvider.create()) .overrideConfiguration(c -> c.defaultProfileFile(profileFile) .defaultProfileName("default") .addExecutionInterceptor(interceptor) .retryPolicy(r -> r.numRetries(0))) .build(); String arn = "arn:aws:s3:us-banana-46:12345567890:accesspoint:foo"; assertThatThrownBy(() -> s3.getObject(r -> r.bucket(arn).key("bar"))).isInstanceOf(SdkException.class); ArgumentCaptor<Context.BeforeTransmission> context = ArgumentCaptor.forClass(Context.BeforeTransmission.class); Mockito.verify(interceptor).beforeTransmission(context.capture(), any()); String host = context.getValue().httpRequest().host(); assertThat(host).contains("us-banana-46"); }
FormService { public ResponseEntity<?> handleKillThreadPost(Map<String, String> form, TileLayer tl) { String id = form.get("thread_id"); StringBuilder doc = new StringBuilder(); makeHeader(doc); if (seeder.terminateGWCTask(Long.parseLong(id))) { doc.append("<ul><li>Requested to terminate task " + id + ".</li></ul>"); } else { doc.append( "<ul><li>Sorry, either task " + id + " has not started yet, or it is a truncate task that cannot be interrutped.</li></ul>"); } if (tl != null) { doc.append("<p><a href=\"./" + tl.getName() + "\">Go back</a></p>\n"); } return new ResponseEntity<Object>(doc.toString(), getHeaders(), HttpStatus.OK); } ResponseEntity<?> handleKillAllThreadsPost(Map<String, String> form, TileLayer tl); ResponseEntity<?> handleKillThreadPost(Map<String, String> form, TileLayer tl); ResponseEntity<?> handleFormPost(String layer, Map<String, String> params); ResponseEntity<?> handleGet(HttpServletRequest request, String layer); void setTileBreeder(TileBreeder seeder); }
@Test public void testKill() { Map<String, String> form = new HashMap<>(); form.put("kill_thread", "1"); form.put("thread_id", "2"); TileLayer tl = EasyMock.createMock("tl", TileLayer.class); EasyMock.expect(breeder.terminateGWCTask(2)).andReturn(true); EasyMock.expect(tl.getName()).andStubReturn("testLayer"); EasyMock.replay(tl, breeder); ResponseEntity<?> response = service.handleKillThreadPost(form, tl); EasyMock.verify(tl, breeder); assertThat(response, hasProperty("statusCode", equalTo(HttpStatus.OK))); assertThat( response, hasProperty("body", Matchers.containsString("Requested to terminate task 2"))); }
FileManager { List<File> getFiles(String layerName) { String[] pathBuilderCopy = getPathBuilderCopy(); if (replaceLayerName.first) pathBuilderCopy[replaceLayerName.second] = layerName; return getFiles(pathBuilderCopy); } FileManager( File rootDirectory, String pathTemplate, long rowRangeCount, long columnRangeCount); static String normalizePathValue(String value); }
@Test public void testGetFilesByTileRange() throws Exception { String pathTemplate = Utils.buildPath("tiles", "{z}", "tiles-{x}-{y}.sqlite"); FileManager fileManager = new FileManager(getRootDirectory(), pathTemplate, 10, 10); File file1 = createFileInRootDir(Utils.buildPath("tiles", "5", "tiles-0-0.sqlite")); File file2 = createFileInRootDir(Utils.buildPath("tiles", "5", "tiles-10-0.sqlite")); File file3 = createFileInRootDir(Utils.buildPath("tiles", "5", "tiles-0-10.sqlite")); File file4 = createFileInRootDir(Utils.buildPath("tiles", "5", "tiles-10-10.sqlite")); File file5 = createFileInRootDir(Utils.buildPath("tiles", "6", "tiles-10-0.sqlite")); long[][] rangeBounds = new long[][] { {9, 9, 12, 13, 5}, {16, 5, 16, 5, 6} }; TileRange tileRange = new TileRange( "layer", "EPSG:4326", 5, 6, rangeBounds, MimeType.createFromExtension("png"), Collections.emptyMap()); Map<File, List<long[]>> files = fileManager.getFiles(tileRange); assertThat(files, notNullValue()); assertThat(files.size(), is(5)); checkFileExistsAndContainsTiles(files, file1, new long[] {9, 9, 9, 9, 5}); checkFileExistsAndContainsTiles(files, file2, new long[] {10, 9, 12, 9, 5}); checkFileExistsAndContainsTiles(files, file3, new long[] {9, 10, 9, 13, 5}); checkFileExistsAndContainsTiles(files, file4, new long[] {10, 10, 12, 13, 5}); checkFileExistsAndContainsTiles(files, file5, new long[] {16, 5, 16, 5, 6}); } @Test public void testGetLayerAssociatedFilesWithMultipleLevels() throws Exception { String pathTemplate = Utils.buildPath( "tiles", "{format}", "{style}", "zoom-{z}", "{layer}", "ranges-{x}-{y}.sqlite"); File fileAsiaA = createFileInRootDir( Utils.buildPath( "tiles", "png", "default", "zoom-10", "asia", "ranges-0-500.sqlite")); File fileAsiaB = createFileInRootDir( Utils.buildPath( "tiles", "png", "default", "zoom-11", "asia", "ranges-100-500.sqlite")); File fileAsiaC = createFileInRootDir( Utils.buildPath( "tiles", "png", "dark-borders", "zoom-10", "asia", "ranges-0-500.sqlite")); File fileAsiaD = createFileInRootDir( Utils.buildPath( "tiles", "jpeg", "dark-borders", "zoom-10", "asia", "ranges-0-500.sqlite")); File fileAfricaA = createFileInRootDir( Utils.buildPath( "tiles", "png", "default", "zoom-10", "africa", "ranges-0-500.sqlite")); File fileAmericaA = createFileInRootDir( Utils.buildPath( "tiles", "png", "dark-borders", "zoom-10", "america", "ranges-0-500.sqlite")); File fileAmericaB = createFileInRootDir( Utils.buildPath( "tiles", "jpeg", "dark-borders", "zoom-10", "america", "ranges-0-500.sqlite")); File fileEuropeA = createFileInRootDir( Utils.buildPath( "tiles", "gif", "dark-borders", "zoom-15", "europe", "ranges-4000-500.sqlite")); FileManager fileManager = new FileManager(getRootDirectory(), pathTemplate, 500, 500); List<File> asiaFiles = fileManager.getFiles("asia"); assertThat(asiaFiles, containsInAnyOrder(fileAsiaA, fileAsiaB, fileAsiaC, fileAsiaD)); List<File> africaFiles = fileManager.getFiles("africa"); assertThat(africaFiles, containsInAnyOrder(fileAfricaA)); List<File> americaFiles = fileManager.getFiles("america"); assertThat(americaFiles, containsInAnyOrder(fileAmericaA, fileAmericaB)); List<File> europeFiles = fileManager.getFiles("europe"); assertThat(europeFiles, containsInAnyOrder(fileEuropeA)); } @Test public void testGetLayerAssociatedFilesWithNoLayer() throws Exception { String pathTemplate = Utils.buildPath("tiles", "{z}", "tiles-{x}.sqlite"); File fileA = createFileInRootDir(Utils.buildPath("tiles", "10", "tiles-0.sqlite")); File fileB = createFileInRootDir(Utils.buildPath("tiles", "10", "tiles-500.sqlite")); File fileC = createFileInRootDir(Utils.buildPath("tiles", "11", "tiles-0.sqlite")); File fileD = createFileInRootDir(Utils.buildPath("tiles", "11", "tiles-500.sqlite")); FileManager fileManager = new FileManager(getRootDirectory(), pathTemplate, 1000, 1000); List<File> filesA = fileManager.getFiles((String) null); assertThat(filesA, containsInAnyOrder(fileA, fileB, fileC, fileD)); List<File> filesB = fileManager.getFiles("something"); assertThat(filesB, containsInAnyOrder(fileA, fileB, fileC, fileD)); } @Test public void testLayerAssociatedFilesWithOnlyOneLevel() throws Exception { String pathTemplate = "{layer}.sqlite"; File asiaFile = createFileInRootDir("asia.sqlite"); File americaFile = createFileInRootDir("america.sqlite"); File africaFile = createFileInRootDir("africa.sqlite"); File australiaFile = createFileInRootDir("australia.sqlite"); FileManager fileManager = new FileManager(getRootDirectory(), pathTemplate, 1000, 1000); List<File> asiaFiles = fileManager.getFiles("asia"); assertThat(asiaFiles, containsInAnyOrder(asiaFile)); List<File> americaFiles = fileManager.getFiles("america"); assertThat(americaFiles, containsInAnyOrder(americaFile)); List<File> africaFiles = fileManager.getFiles("africa"); assertThat(africaFiles, containsInAnyOrder(africaFile)); List<File> australiaFiles = fileManager.getFiles("australia"); assertThat(australiaFiles, containsInAnyOrder(australiaFile)); } @Test public void testGetGridSetAndLayerAssociatedFiles() throws Exception { String pathTemplate = Utils.buildPath( "tiles", "{grid}", "{format}", "{style}", "zoom-{z}", "{layer}", "ranges-{x}-{y}.sqlite"); File fileAsiaGrid1A = createFileInRootDir( Utils.buildPath( "tiles", "grid1", "png", "default", "zoom-10", "asia", "ranges-0-500.sqlite")); File fileAsiaGrid2B = createFileInRootDir( Utils.buildPath( "tiles", "grid2", "png", "default", "zoom-11", "asia", "ranges-100-500.sqlite")); File fileAsiaGrid3C = createFileInRootDir( Utils.buildPath( "tiles", "grid3", "png", "dark-borders", "zoom-10", "asia", "ranges-0-500.sqlite")); File fileAsiaGrid3D = createFileInRootDir( Utils.buildPath( "tiles", "grid3", "jpeg", "dark-borders", "zoom-10", "asia", "ranges-0-500.sqlite")); File fileAfricaGrid1A = createFileInRootDir( Utils.buildPath( "tiles", "grid1", "png", "default", "zoom-10", "africa", "ranges-0-500.sqlite")); File fileAmericaGrid1A = createFileInRootDir( Utils.buildPath( "tiles", "grid1", "png", "dark-borders", "zoom-10", "america", "ranges-0-500.sqlite")); File fileAmericaGrid2B = createFileInRootDir( Utils.buildPath( "tiles", "grid2", "jpeg", "dark-borders", "zoom-10", "america", "ranges-0-500.sqlite")); File fileEuropeGrid1A = createFileInRootDir( Utils.buildPath( "tiles", "grid1", "gif", "dark-borders", "zoom-15", "europe", "ranges-4000-500.sqlite")); FileManager fileManager = new FileManager(getRootDirectory(), pathTemplate, 500, 500); List<File> asiaFilesGrid1 = fileManager.getFiles("asia", "grid1"); assertThat(asiaFilesGrid1, containsInAnyOrder(fileAsiaGrid1A)); List<File> asiaFilesGrid2 = fileManager.getFiles("asia", "grid2"); assertThat(asiaFilesGrid2, containsInAnyOrder(fileAsiaGrid2B)); List<File> asiaFilesGrid3 = fileManager.getFiles("asia", "grid3"); assertThat(asiaFilesGrid3, containsInAnyOrder(fileAsiaGrid3C, fileAsiaGrid3D)); List<File> africaFilesGrid1 = fileManager.getFiles("africa", "grid1"); assertThat(africaFilesGrid1, containsInAnyOrder(fileAfricaGrid1A)); List<File> americaFilesGrid1 = fileManager.getFiles("america", "grid1"); assertThat(americaFilesGrid1, containsInAnyOrder(fileAmericaGrid1A)); List<File> americaFilesGrid2 = fileManager.getFiles("america", "grid2"); assertThat(americaFilesGrid2, containsInAnyOrder(fileAmericaGrid2B)); List<File> europeFilesGrid1 = fileManager.getFiles("europe", "grid1"); assertThat(europeFilesGrid1, containsInAnyOrder(fileEuropeGrid1A)); }
FileManager { File getFile(TileObject tile) { if (tile.getParametersId() == null && tile.getParameters() != null) { tile.setParametersId(ParametersUtils.getId(tile.getParameters())); } return getFile( tile.getParametersId(), tile.getXYZ(), tile.getLayerName(), tile.getGridSetId(), tile.getBlobFormat(), tile.getParameters()); } FileManager( File rootDirectory, String pathTemplate, long rowRangeCount, long columnRangeCount); static String normalizePathValue(String value); }
@Test public void testPathSeparatorsAreConvertedToOsOnes() { String pathTemplate = "something-{layer}\\{grid-something}-something{grid}\\-el/se{format}/something-{params}"; FileManager fileManager = new FileManager(getRootDirectory(), pathTemplate, 250, 250); File file = fileManager.getFile( "parameters_id", new long[] {0, 0, 0}, "layer_name", "grid_set", "format_name", Collections.emptyMap()); assertThat( file.toString(), is( buildRootFile( "something-layer_name", "null-somethinggrid_set", "-el", "seformat_name", "something-parameters_id") .toString())); } @Test public void testPathTemplateWithTileObject() throws Exception { TileObject tile = TileObject.createCompleteTileObject( "africa", new long[] {7050, 5075, 11}, "wgs84", "jpeg", tuplesToMap(tuple("style", "dark borders"), tuple("background", "blue")), null); String pathTemplate = Utils.buildPath( "{format}-tiles", "{grid}", "{layer}-{style}", "zoom-{z}", "ranges-{x}_{y}.sqlite"); String expectedPath = Utils.buildPath( "jpeg-tiles", "wgs84", "africa-dark_borders", "zoom-11", "ranges-7000_4000.sqlite"); FileManager fileManager = new FileManager(getRootDirectory(), pathTemplate, 2000, 1000); File file = fileManager.getFile(tile); assertThat( file.getCanonicalPath(), is(getRootDirectoryPath() + File.separator + expectedPath)); }
SqliteBlobStore implements BlobStore { void replace(File newFile, String destination) { File destinationFile = new File(configuration.getRootDirectoryFile(), destination); connectionManager.replace(destinationFile, newFile); } protected SqliteBlobStore(SqliteInfo configuration, SqliteConnectionManager connectionManager); @Override void destroy(); }
@Test public void testFileReplaceOperation() throws Exception { File rootDirectoryA = Files.createTempDirectory("gwc-").toFile(); File rootDirectoryB = Files.createTempDirectory("gwc-").toFile(); addFilesToDelete(rootDirectoryA, rootDirectoryB); MbtilesInfo configurationA = getDefaultConfiguration(); configurationA.setRootDirectory(rootDirectoryA.getPath()); MbtilesInfo configurationB = getDefaultConfiguration(); configurationB.setRootDirectory(rootDirectoryB.getPath()); MbtilesBlobStore storeA = new MbtilesBlobStore(configurationA); MbtilesBlobStore storeB = new MbtilesBlobStore(configurationB); addStoresToClean(storeA, storeB); TileObject putTileA = TileObject.createCompleteTileObject( "africa", new long[] {10, 50, 5}, "EPSG:4326", "image/png", null, stringToResource("IMAGE-10-50-5-A")); TileObject putTileB = TileObject.createCompleteTileObject( "africa", new long[] {10, 50, 5}, "EPSG:4326", "image/png", null, stringToResource("IMAGE-10-50-5-B")); storeA.put(putTileA); storeB.put(putTileB); storeA.clear(); storeB.clear(); String relativePath = Utils.buildPath("EPSG_4326", "africa", "image_png", "5", "tiles-0-0.sqlite"); File fileA = new File(rootDirectoryA, relativePath); File fileB = new File(rootDirectoryB, relativePath); assertThat(fileA.exists(), is(true)); assertThat(fileB.exists(), is(true)); storeA.replace(fileB, relativePath); TileObject getTile = TileObject.createQueryTileObject( "africa", new long[] {10, 50, 5}, "EPSG:4326", "image/png", null); assertThat(storeA.get(getTile), is(true)); assertThat(getTile.getBlob(), notNullValue()); assertThat(resourceToString(getTile.getBlob()), is("IMAGE-10-50-5-B")); FileUtils.deleteQuietly(rootDirectoryA); FileUtils.deleteQuietly(rootDirectoryB); } @Test public void testDirectoryReplaceOperation() throws Exception { File rootDirectoryA = Files.createTempDirectory("replace-tests-a-").toFile(); File rootDirectoryB = Files.createTempDirectory("replace-tests-a-").toFile(); addFilesToDelete(rootDirectoryA, rootDirectoryB); MbtilesInfo configurationA = getDefaultConfiguration(); configurationA.setRootDirectory(rootDirectoryA.getPath()); MbtilesInfo configurationB = getDefaultConfiguration(); configurationB.setRootDirectory(rootDirectoryB.getPath()); MbtilesBlobStore storeA = new MbtilesBlobStore(configurationA); MbtilesBlobStore storeB = new MbtilesBlobStore(configurationB); addStoresToClean(storeA, storeB); TileObject putTileA = TileObject.createCompleteTileObject( "africa", new long[] {10, 50, 5}, "EPSG:4326", "image/png", null, stringToResource("IMAGE-10-50-5-A")); TileObject putTileB = TileObject.createCompleteTileObject( "africa", new long[] {10, 50, 5}, "EPSG:4326", "image/png", null, stringToResource("IMAGE-10-50-5-B")); TileObject putTileC = TileObject.createCompleteTileObject( "africa", new long[] {10, 5050, 15}, "EPSG:4326", "image/png", null, stringToResource("IMAGE-15-5050-5-B")); storeA.put(putTileA); storeB.put(putTileB); storeB.put(putTileC); storeA.clear(); storeB.clear(); String relativePathA = Utils.buildPath("EPSG_4326", "africa", "image_png", "5", "tiles-0-0.sqlite"); String relativePathB = Utils.buildPath("EPSG_4326", "africa", "image_png", "15", "tiles-0-5000.sqlite"); File fileA = new File(rootDirectoryA, relativePathA); File fileB = new File(rootDirectoryB, relativePathA); File fileC = new File(rootDirectoryB, relativePathB); assertThat(fileA.exists(), is(true)); assertThat(fileB.exists(), is(true)); assertThat(fileC.exists(), is(true)); storeA.replace(rootDirectoryB); TileObject getTile = TileObject.createQueryTileObject( "africa", new long[] {10, 50, 5}, "EPSG:4326", "image/png", null); assertThat(storeA.get(getTile), is(true)); assertThat(getTile.getBlob(), notNullValue()); assertThat(resourceToString(getTile.getBlob()), is("IMAGE-10-50-5-B")); getTile = TileObject.createQueryTileObject( "africa", new long[] {10, 5050, 15}, "EPSG:4326", "image/png", null); assertThat(storeA.get(getTile), is(true)); assertThat(getTile.getBlob(), notNullValue()); assertThat(resourceToString(getTile.getBlob()), is("IMAGE-15-5050-5-B")); FileUtils.deleteQuietly(rootDirectoryA); FileUtils.deleteQuietly(rootDirectoryB); }
MbtilesBlobStore extends SqliteBlobStore { @Override public boolean delete(TileObject tile) throws StorageException { File file = fileManager.getFile(tile); if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("Tile '%s' mapped to file '%s'.", tile, file)); } if (!file.exists()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( String.format( "Containing file '%s' for tile '%s' doesn't exists.", file, tile)); } return false; } return connectionManager.doWork( file, false, connection -> { MBTilesFile mbtiles = GeoToolsMbtilesUtils.getMBTilesFile(connection, file); MBTilesTile gtTile = new MBTilesTile(tile.getXYZ()[2], tile.getXYZ()[0], tile.getXYZ()[1]); try { byte[] olData = mbtiles.loadTile( tile.getXYZ()[2], tile.getXYZ()[0], tile.getXYZ()[1]) .getData(); if (olData != null) { tile.setBlobSize(olData.length); mbtiles.saveTile(gtTile); listeners.sendTileDeleted(tile); if (useCreateTime) { deleteTileCreateTime( connection, tile.getXYZ()[2], tile.getXYZ()[0], tile.getXYZ()[1]); } if (LOGGER.isDebugEnabled()) { LOGGER.debug( String.format( "Tile '%s' deleted from file '%s'.", tile, file)); } return true; } } catch (Exception exception) { throw Utils.exception( exception, "Error deleting tile '%s' from MBTiles file '%s'.", tile, file); } if (LOGGER.isDebugEnabled()) { LOGGER.debug( String.format("Tile '%s' not found on file '%s'.", tile, file)); } return false; }); } MbtilesBlobStore(MbtilesInfo configuration); MbtilesBlobStore(MbtilesInfo configuration, SqliteConnectionManager connectionManager); @Override void put(TileObject tile); @Override boolean get(final TileObject tile); @Override boolean delete(TileObject tile); @Override synchronized void putLayerMetadata(String layerName, String key, String value); @Override String getLayerMetadata(String layerName, String key); @Override boolean layerExists(String layerName); @Override boolean delete(String layerName); @Override boolean deleteByGridsetId(String layerName, String gridSetId); @Override boolean deleteByParametersId(String layerName, String parametersId); @Override boolean delete(TileRange tileRange); @Override boolean rename(String oldLayerName, String newLayerName); @Override void addListener(BlobStoreListener listener); @Override boolean removeListener(BlobStoreListener listener); @Override void clear(); @Override void destroy(); Map<String, Optional<Map<String, String>>> getParametersMapping(String layerName); }
@Test public void testDeleteLayerOperation() throws Exception { MbtilesInfo configuration = getDefaultConfiguration(); MbtilesBlobStore store = new MbtilesBlobStore(configuration); addStoresToClean(store); File asia1 = createFileInRootDir( Utils.buildPath("grid1", "asia", "image_png", "10", "tiles-0-500.sqlite")); File asia2 = createFileInRootDir( Utils.buildPath( "grid2", "asia", "image_png", "11", "tiles-100-500.sqlite")); File asia3 = createFileInRootDir( Utils.buildPath("grid3", "asia", "image_png", "10", "tiles-0-500.sqlite")); File asia4 = createFileInRootDir( Utils.buildPath("grid3", "asia", "image_jpeg", "10", "tiles-0-500.sqlite")); File africa1 = createFileInRootDir( Utils.buildPath( "grid1", "africa", "image_png", "10", "tiles-0-500.sqlite")); File america1 = createFileInRootDir( Utils.buildPath( "grid1", "america", "image_png", "10", "tiles-0-500.sqlite")); File america2 = createFileInRootDir( Utils.buildPath( "grid2", "america", "image_jpeg", "10", "tiles-0-500.sqlite")); File europe1 = createFileInRootDir( Utils.buildPath( "grid1", "europe", "image_gif", "15", "tiles-4000-500.sqlite")); store.delete("asia"); store.delete("europe"); assertThat(asia1.exists(), is(false)); assertThat(asia2.exists(), is(false)); assertThat(asia3.exists(), is(false)); assertThat(asia4.exists(), is(false)); assertThat(africa1.exists(), is(true)); assertThat(america1.exists(), is(true)); assertThat(america2.exists(), is(true)); assertThat(europe1.exists(), is(false)); } @Test public void testDeleteLayerWithTileRangeEager() throws Exception { MbtilesInfo configuration = getDefaultConfiguration(); configuration.setEagerDelete(true); MbtilesBlobStore store = new MbtilesBlobStore(configuration); addStoresToClean(store); long[][] rangeBounds = new long[][] { {0, 490, 10, 500, 10}, {800, 950, 1005, 1020, 11} }; TileRange tileRange = new TileRange( "asia", "grid1", 10, 11, rangeBounds, MimeType.createFromExtension("png"), Collections.emptyMap()); File asia1 = createFileInRootDir( Utils.buildPath("grid1", "asia", "image_png", "10", "tiles-0-0.sqlite")); File asia2 = createFileInRootDir( Utils.buildPath("grid1", "asia", "image_png", "10", "tiles-0-500.sqlite")); File asia3 = createFileInRootDir( Utils.buildPath("grid1", "asia", "image_png", "10", "tiles-500-0.sqlite")); File asia4 = createFileInRootDir( Utils.buildPath( "grid1", "asia", "image_png", "10", "tiles-500-500.sqlite")); File asia5 = createFileInRootDir( Utils.buildPath( "grid1", "asia", "image_png", "11", "tiles-1000-1000.sqlite")); store.delete(tileRange); assertThat(asia1.exists(), is(false)); assertThat(asia2.exists(), is(false)); assertThat(asia3.exists(), is(true)); assertThat(asia4.exists(), is(true)); assertThat(asia5.exists(), is(false)); }
MbtilesBlobStore extends SqliteBlobStore { @Override public boolean deleteByGridsetId(String layerName, String gridSetId) throws StorageException { boolean deleted = deleteFiles(fileManager.getFiles(layerName, gridSetId)); listeners.sendGridSubsetDeleted(layerName, gridSetId); return deleted; } MbtilesBlobStore(MbtilesInfo configuration); MbtilesBlobStore(MbtilesInfo configuration, SqliteConnectionManager connectionManager); @Override void put(TileObject tile); @Override boolean get(final TileObject tile); @Override boolean delete(TileObject tile); @Override synchronized void putLayerMetadata(String layerName, String key, String value); @Override String getLayerMetadata(String layerName, String key); @Override boolean layerExists(String layerName); @Override boolean delete(String layerName); @Override boolean deleteByGridsetId(String layerName, String gridSetId); @Override boolean deleteByParametersId(String layerName, String parametersId); @Override boolean delete(TileRange tileRange); @Override boolean rename(String oldLayerName, String newLayerName); @Override void addListener(BlobStoreListener listener); @Override boolean removeListener(BlobStoreListener listener); @Override void clear(); @Override void destroy(); Map<String, Optional<Map<String, String>>> getParametersMapping(String layerName); }
@Test public void testDeleteLayerWithGridSetOperation() throws Exception { MbtilesInfo configuration = getDefaultConfiguration(); MbtilesBlobStore store = new MbtilesBlobStore(configuration); addStoresToClean(store); File asia1 = createFileInRootDir( Utils.buildPath("grid1", "asia", "image_png", "10", "tiles-0-500.sqlite")); File asia2 = createFileInRootDir( Utils.buildPath( "grid2", "asia", "image_png", "11", "tiles-100-500.sqlite")); File asia3 = createFileInRootDir( Utils.buildPath("grid3", "asia", "image_png", "10", "tiles-0-500.sqlite")); File asia4 = createFileInRootDir( Utils.buildPath("grid3", "asia", "image_jpeg", "10", "tiles-0-500.sqlite")); File africa1 = createFileInRootDir( Utils.buildPath( "grid1", "africa", "image_png", "10", "tiles-0-500.sqlite")); File america1 = createFileInRootDir( Utils.buildPath( "grid1", "america", "image_png", "10", "tiles-0-500.sqlite")); File america2 = createFileInRootDir( Utils.buildPath( "grid2", "america", "image_jpeg", "10", "tiles-0-500.sqlite")); File europe1 = createFileInRootDir( Utils.buildPath( "grid1", "europe", "image_gif", "15", "tiles-4000-500.sqlite")); store.deleteByGridsetId("asia", "grid3"); store.deleteByGridsetId("america", "grid2"); assertThat(asia1.exists(), is(true)); assertThat(asia2.exists(), is(true)); assertThat(asia3.exists(), is(false)); assertThat(asia4.exists(), is(false)); assertThat(africa1.exists(), is(true)); assertThat(america1.exists(), is(true)); assertThat(america2.exists(), is(false)); assertThat(europe1.exists(), is(true)); }
MbtilesBlobStore extends SqliteBlobStore { @Override public boolean layerExists(String layerName) { return !fileManager.getFiles(layerName).isEmpty(); } MbtilesBlobStore(MbtilesInfo configuration); MbtilesBlobStore(MbtilesInfo configuration, SqliteConnectionManager connectionManager); @Override void put(TileObject tile); @Override boolean get(final TileObject tile); @Override boolean delete(TileObject tile); @Override synchronized void putLayerMetadata(String layerName, String key, String value); @Override String getLayerMetadata(String layerName, String key); @Override boolean layerExists(String layerName); @Override boolean delete(String layerName); @Override boolean deleteByGridsetId(String layerName, String gridSetId); @Override boolean deleteByParametersId(String layerName, String parametersId); @Override boolean delete(TileRange tileRange); @Override boolean rename(String oldLayerName, String newLayerName); @Override void addListener(BlobStoreListener listener); @Override boolean removeListener(BlobStoreListener listener); @Override void clear(); @Override void destroy(); Map<String, Optional<Map<String, String>>> getParametersMapping(String layerName); }
@Test public void testLayerExistsOperation() throws Exception { MbtilesInfo configuration = getDefaultConfiguration(); MbtilesBlobStore store = new MbtilesBlobStore(configuration); addStoresToClean(store); createFileInRootDir( Utils.buildPath("grid1", "europe", "image_png", "10", "tiles-0-0.sqlite")); assertThat(store.layerExists("europe"), is(true)); assertThat(store.layerExists("asia"), is(false)); }
MbtilesBlobStore extends SqliteBlobStore { @Override public boolean rename(String oldLayerName, String newLayerName) throws StorageException { List<File> files = fileManager.getFiles(oldLayerName); if (files.isEmpty()) { return false; } for (File currentFile : files) { String normalizedLayerName = FileManager.normalizePathValue(newLayerName); File newFile = new File(currentFile.getPath().replace(oldLayerName, normalizedLayerName)); connectionManager.rename(currentFile, newFile); } listeners.sendLayerRenamed(oldLayerName, newLayerName); return true; } MbtilesBlobStore(MbtilesInfo configuration); MbtilesBlobStore(MbtilesInfo configuration, SqliteConnectionManager connectionManager); @Override void put(TileObject tile); @Override boolean get(final TileObject tile); @Override boolean delete(TileObject tile); @Override synchronized void putLayerMetadata(String layerName, String key, String value); @Override String getLayerMetadata(String layerName, String key); @Override boolean layerExists(String layerName); @Override boolean delete(String layerName); @Override boolean deleteByGridsetId(String layerName, String gridSetId); @Override boolean deleteByParametersId(String layerName, String parametersId); @Override boolean delete(TileRange tileRange); @Override boolean rename(String oldLayerName, String newLayerName); @Override void addListener(BlobStoreListener listener); @Override boolean removeListener(BlobStoreListener listener); @Override void clear(); @Override void destroy(); Map<String, Optional<Map<String, String>>> getParametersMapping(String layerName); }
@Test public void testRenameOperation() throws Exception { MbtilesInfo configuration = getDefaultConfiguration(); MbtilesBlobStore store = new MbtilesBlobStore(configuration); addStoresToClean(store); File asia1 = createFileInRootDir( Utils.buildPath("grid1", "asia", "image_png", "10", "tiles-0-0.sqlite")); File asia2 = createFileInRootDir( Utils.buildPath("grid1", "asia", "image_png", "10", "tiles-0-500.sqlite")); File europe1 = createFileInRootDir( Utils.buildPath( "grid1", "europe", "image_png", "10", "tiles-500-0.sqlite")); store.rename("asia", "australia"); assertThat(asia1.exists(), is(false)); assertThat(asia2.exists(), is(false)); assertThat(europe1.exists(), is(true)); assertThat( buildRootFile("grid1", "australia", "image_png", "10", "tiles-0-0.sqlite").exists(), is(true)); assertThat( buildRootFile("grid1", "australia", "image_png", "10", "tiles-0-500.sqlite") .exists(), is(true)); }
MbtilesBlobStore extends SqliteBlobStore { @Override public void put(TileObject tile) throws StorageException { File file = fileManager.getFile(tile); if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("Tile '%s' mapped to file '%s'.", tile, file)); } initDatabaseFileIfNeeded(file, tile.getLayerName(), tile.getBlobFormat()); connectionManager.doWork( file, false, connection -> { MBTilesFile mbtiles = GeoToolsMbtilesUtils.getMBTilesFile(connection, file); MBTilesTile gtTile = new MBTilesTile(tile.getXYZ()[2], tile.getXYZ()[0], tile.getXYZ()[1]); try { final boolean gzipped = tileIsGzipped(tile); byte[] bytes; if (gzipped) { try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); GZIPOutputStream gzOut = new GZIPOutputStream(byteStream); ) { bytes = byteStream.toByteArray(); } } else { bytes = Utils.resourceToByteArray(tile.getBlob()); } gtTile.setData(bytes); byte[] olData = null; if (!listeners.isEmpty()) { olData = mbtiles.loadTile( tile.getXYZ()[2], tile.getXYZ()[0], tile.getXYZ()[1]) .getData(); } mbtiles.saveTile(gtTile); if (useCreateTime) { putTileCreateTime( connection, tile.getXYZ()[2], tile.getXYZ()[0], tile.getXYZ()[1], System.currentTimeMillis()); } if (LOGGER.isDebugEnabled()) { LOGGER.debug( String.format("Tile '%s' saved in file '%s'.", tile, file)); } if (listeners.isEmpty()) { return; } if (olData == null) { listeners.sendTileStored(tile); } else { listeners.sendTileUpdated(tile, olData.length); } } catch (Exception exception) { throw Utils.exception( exception, "Error saving tile '%s' in file '%s'.", tile, file); } }); persistParameterMap(tile); } MbtilesBlobStore(MbtilesInfo configuration); MbtilesBlobStore(MbtilesInfo configuration, SqliteConnectionManager connectionManager); @Override void put(TileObject tile); @Override boolean get(final TileObject tile); @Override boolean delete(TileObject tile); @Override synchronized void putLayerMetadata(String layerName, String key, String value); @Override String getLayerMetadata(String layerName, String key); @Override boolean layerExists(String layerName); @Override boolean delete(String layerName); @Override boolean deleteByGridsetId(String layerName, String gridSetId); @Override boolean deleteByParametersId(String layerName, String parametersId); @Override boolean delete(TileRange tileRange); @Override boolean rename(String oldLayerName, String newLayerName); @Override void addListener(BlobStoreListener listener); @Override boolean removeListener(BlobStoreListener listener); @Override void clear(); @Override void destroy(); Map<String, Optional<Map<String, String>>> getParametersMapping(String layerName); }
@Test public void testOpeningDatabaseFileWithMbtilesMetadata() throws Exception { File mbtilesMetadataDirectory = buildRootFile("mbtiles-metadata"); File mbtilesMetadataFile = new File(mbtilesMetadataDirectory, "europe_asia.properties"); String mbtilesMetadata = "attribution=some attribution" + System.lineSeparator() + "bounds=-180,-90,180,90" + System.lineSeparator() + "description=some description" + System.lineSeparator() + "maxZoom=10" + System.lineSeparator() + "minZoom=0" + System.lineSeparator() + "type=base_layer" + System.lineSeparator() + "version=1.0" + System.lineSeparator(); writeToFile(mbtilesMetadataFile, mbtilesMetadata); MbtilesInfo configuration = getDefaultConfiguration(); configuration.setMbtilesMetadataDirectory(mbtilesMetadataDirectory.getPath()); SqliteConnectionManager connectionManager = new SqliteConnectionManager(configuration); MbtilesBlobStore store = new MbtilesBlobStore(configuration, connectionManager); addStoresToClean(store); TileObject putTile = TileObject.createCompleteTileObject( "europe:asia", new long[] {5, 5, 5}, "EPSG:4326", "image/png", null, stringToResource("IMAGE-5-5-5")); store.put(putTile); File file = buildRootFile("EPSG_4326", "europe_asia", "image_png", "5", "tiles-0-0.sqlite"); assertThat(file.exists(), is(true)); connectionManager.executeQuery( file, resultSet -> { List<Utils.Tuple<String, String>> foundMetadata = new ArrayList<>(); while (resultSet.next()) { foundMetadata.add(tuple(resultSet.getString(1), resultSet.getString(2))); } assertThat(foundMetadata.size(), is(10)); assertThat( foundMetadata, containsInAnyOrder( tuple("name", "europe:asia"), tuple("version", "1.0"), tuple("description", "some description"), tuple("attribution", "some attribution"), tuple("type", "base_layer"), tuple("format", "png"), tuple("bounds", "-180.0,-90.0,180.0,90.0"), tuple("minzoom", "5"), tuple("maxzoom", "5"), tuple("json", "null"))); return null; }, "SELECT name, value FROM metadata;"); }
WMSService extends Service { public void setSecurityDispatcher(SecurityDispatcher securityDispatcher) { this.securityDispatcher = securityDispatcher; } protected WMSService(); WMSService(StorageBroker sb, TileLayerDispatcher tld, RuntimeStats stats); WMSService( StorageBroker sb, TileLayerDispatcher tld, RuntimeStats stats, URLMangler urlMangler, GeoWebCacheDispatcher controller); @Override ConveyorTile getConveyor(HttpServletRequest request, HttpServletResponse response); void handleRequest(Conveyor conv); void setFullWMS(String trueFalse); void setProxyRequests(String trueFalse); void setProxyNonTiledRequests(String trueFalse); void setHintsConfig(String hintsConfig); void setUtility(WMSUtilities utility); void setSecurityDispatcher(SecurityDispatcher securityDispatcher); static final String GEOWEBCACHE_WMS_PROXY_REQUEST_WHITELIST; static final String SERVICE_WMS; }
@Test public void testProxyRequestWhitelistWhenNoSecurityFilters() throws Exception { whitelistProperty.setValue("troz"); SecurityDispatcher secDisp = mock(SecurityDispatcher.class); when(secDisp.isSecurityEnabled()).thenReturn(false); GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); service = new WMSService(sb, tld, mock(RuntimeStats.class), new NullURLMangler(), gwcd); service.setSecurityDispatcher(secDisp); String layerName = "mockLayer"; TestLayer tileLayer = mock(TestLayer.class); when(tld.getTileLayer(layerName)).thenReturn(tileLayer); testProxyRequestAllowed(secDisp, layerName, tileLayer, "TROZ"); testProxyRequestPrevented(secDisp, layerName, tileLayer, "GetLegendGraphic"); } @Test public void testProxyRequestWhitelistWithSecurityFilters() throws Exception { whitelistProperty.setValue("troz"); SecurityDispatcher secDisp = mock(SecurityDispatcher.class); when(secDisp.isSecurityEnabled()).thenReturn(true); GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); service = new WMSService(sb, tld, mock(RuntimeStats.class), new NullURLMangler(), gwcd); service.setSecurityDispatcher(secDisp); String layerName = "mockLayer"; TestLayer tileLayer = mock(TestLayer.class); when(tld.getTileLayer(layerName)).thenReturn(tileLayer); testProxyRequestAllowed(secDisp, layerName, tileLayer, "TROZ"); testProxyRequestPrevented(secDisp, layerName, tileLayer, "GetLegendGraphic"); } @Test public void testProxyRequestWhitelistWithSecurityFiltersAppliesFilters() throws Exception { whitelistProperty.setValue("troz"); SecurityDispatcher secDisp = mock(SecurityDispatcher.class); when(secDisp.isSecurityEnabled()).thenReturn(true); GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); service = new WMSService(sb, tld, mock(RuntimeStats.class), new NullURLMangler(), gwcd); service.setSecurityDispatcher(secDisp); String layerName = "mockLayer"; TestLayer tileLayer = mock(TestLayer.class); when(tld.getTileLayer(layerName)).thenReturn(tileLayer); doThrow(new SecurityException()).when(secDisp).checkSecurity(Mockito.any()); testProxyRequestPrevented(secDisp, layerName, tileLayer, "TROZ"); } @Test public void testProxyRequest() throws Exception { SecurityDispatcher secDisp = mock(SecurityDispatcher.class); when(secDisp.isSecurityEnabled()).thenReturn(false); GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); service = new WMSService(sb, tld, mock(RuntimeStats.class), new NullURLMangler(), gwcd); service.setSecurityDispatcher(secDisp); String layerName = "mockLayer"; TestLayer tileLayer = mock(TestLayer.class); when(tld.getTileLayer(layerName)).thenReturn(tileLayer); testProxyRequestAllowed(secDisp, layerName, tileLayer, "TROZ"); } @Test public void testProxyDefaultWhitelistLimitedWhenSecure() throws Exception { SecurityDispatcher secDisp = mock(SecurityDispatcher.class); when(secDisp.isSecurityEnabled()).thenReturn(true); GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); service = new WMSService(sb, tld, mock(RuntimeStats.class), new NullURLMangler(), gwcd); service.setSecurityDispatcher(secDisp); String layerName = "mockLayer"; TestLayer tileLayer = mock(TestLayer.class); when(tld.getTileLayer(layerName)).thenReturn(tileLayer); testProxyRequestPrevented(secDisp, layerName, tileLayer, "TROZ"); } @Test public void testProxyRequestSecuredDefaultAllowGetLegendGraphic() throws Exception { SecurityDispatcher secDisp = mock(SecurityDispatcher.class); when(secDisp.isSecurityEnabled()).thenReturn(true); GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); service = new WMSService(sb, tld, mock(RuntimeStats.class), new NullURLMangler(), gwcd); service.setSecurityDispatcher(secDisp); String layerName = "mockLayer"; TestLayer tileLayer = mock(TestLayer.class); when(tld.getTileLayer(layerName)).thenReturn(tileLayer); testProxyRequestAllowed(secDisp, layerName, tileLayer, "GetLegendGraphic"); } @Test public void testProxyRequestDefaultWhitelistRestrictedByFilter() throws Exception { SecurityDispatcher secDisp = mock(SecurityDispatcher.class); when(secDisp.isSecurityEnabled()).thenReturn(true); GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); String layerName = "mockLayer"; TestLayer tileLayer = mock(TestLayer.class); when(tld.getTileLayer(layerName)).thenReturn(tileLayer); service = new WMSService(sb, tld, mock(RuntimeStats.class), new NullURLMangler(), gwcd); service.setSecurityDispatcher(secDisp); doThrow(new SecurityException()).when(secDisp).checkSecurity(Mockito.any()); testProxyRequestPrevented(secDisp, layerName, tileLayer, "GetLegendGraphic"); }
SwiftTile { public Payload getPayload() { Payload payload = new ByteArrayPayload(data); payload.setContentMetadata(getMetadata()); return payload; } SwiftTile(final TileObject tile); Payload getPayload(); void setExisted(long oldSize); void notifyListeners(BlobStoreListenerList listeners); String toString(); }
@Test public void testGetPayloadMetadataOutputLength() { Long testOutputLengthValue = 5L; ReflectionTestUtils.setField(swiftTile, "outputLength", testOutputLengthValue); Payload testPayload = swiftTile.getPayload(); assertEquals(testOutputLengthValue, testPayload.getContentMetadata().getContentLength()); } @Test public void testGetPayloadMetadataMimeType() { String testBlobFormat = "image/png"; ReflectionTestUtils.setField(swiftTile, "blobFormat", testBlobFormat); Payload testPayload = swiftTile.getPayload(); assertEquals(testBlobFormat, testPayload.getContentMetadata().getContentType()); }
SwiftTile { public void notifyListeners(BlobStoreListenerList listeners) { boolean hasListeners = !listeners.isEmpty(); if (hasListeners && existed) { listeners.sendTileUpdated( layerName, gridSetId, blobFormat, parametersId, x, y, z, outputLength, oldSize); } else if (hasListeners) { listeners.sendTileStored( layerName, gridSetId, blobFormat, parametersId, x, y, z, outputLength); } } SwiftTile(final TileObject tile); Payload getPayload(); void setExisted(long oldSize); void notifyListeners(BlobStoreListenerList listeners); String toString(); }
@Test public void testNotifyListenersWhenEmptyAndExisted() { ReflectionTestUtils.setField(swiftTile, "existed", true); swiftTile.notifyListeners(testListeners); checkListenersNotifications(0, 0); } @Test public void testNotifyListenersWhenEmptyAndNotExisted() { ReflectionTestUtils.setField(swiftTile, "existed", false); swiftTile.notifyListeners(testListeners); checkListenersNotifications(0, 0); } @Test public void testNotifyListenersWhenNotEmptyAndExisted() { ReflectionTestUtils.setField(swiftTile, "existed", true); addListener(); swiftTile.notifyListeners(testListeners); checkListenersNotifications(1, 0); } @Test public void testNotifyListenersWhenNotEmptyAndNotExisted() { ReflectionTestUtils.setField(swiftTile, "existed", false); addListener(); swiftTile.notifyListeners(testListeners); checkListenersNotifications(0, 1); }
SwiftBlobStore implements BlobStore { @Override public void destroy() { try { this.shutDown = true; this.swiftApi.close(); this.blobStoreContext.close(); } catch (IOException e) { log.error("Error closing connection."); log.error(e); } } SwiftBlobStore(SwiftBlobStoreInfo config, TileLayerDispatcher layers); @Override void destroy(); @Override void addListener(BlobStoreListener listener); @Override boolean removeListener(BlobStoreListener listener); @Override void put(TileObject obj); @Override boolean get(TileObject obj); @Override boolean delete(final TileRange tileRange); @Override boolean delete(String layerName); @Override boolean deleteByGridsetId(final String layerName, final String gridSetId); @Override boolean delete(TileObject obj); @Override boolean rename(String oldLayerName, String newLayerName); @Override void clear(); @Nullable @Override String getLayerMetadata(String layerName, String key); @Override void putLayerMetadata(String layerName, String key, String value); @Override boolean layerExists(String layerName); @Override Map<String, Optional<Map<String, String>>> getParametersMapping(String layerName); @Override boolean deleteByParametersId(String layerName, String parametersId); }
@Test public void destroy() { this.swiftBlobStore.destroy(); try { verify(swiftApi, times(1)).close(); verify(blobStoreContext, times(1)).close(); } catch (IOException e) { fail(e.getMessage()); } }
SwiftBlobStore implements BlobStore { @Override public void addListener(BlobStoreListener listener) { listeners.addListener(listener); } SwiftBlobStore(SwiftBlobStoreInfo config, TileLayerDispatcher layers); @Override void destroy(); @Override void addListener(BlobStoreListener listener); @Override boolean removeListener(BlobStoreListener listener); @Override void put(TileObject obj); @Override boolean get(TileObject obj); @Override boolean delete(final TileRange tileRange); @Override boolean delete(String layerName); @Override boolean deleteByGridsetId(final String layerName, final String gridSetId); @Override boolean delete(TileObject obj); @Override boolean rename(String oldLayerName, String newLayerName); @Override void clear(); @Nullable @Override String getLayerMetadata(String layerName, String key); @Override void putLayerMetadata(String layerName, String key, String value); @Override boolean layerExists(String layerName); @Override Map<String, Optional<Map<String, String>>> getParametersMapping(String layerName); @Override boolean deleteByParametersId(String layerName, String parametersId); }
@Test public void addListener() { assertTrue(testListeners.isEmpty()); BlobStoreListener swiftListener = mock(BlobStoreListener.class); this.swiftBlobStore.addListener(swiftListener); ArrayList<BlobStoreListener> blobStoreListenersResult = (ArrayList) testListeners.getListeners(); assertTrue(blobStoreListenersResult.contains(swiftListener)); }
SwiftBlobStore implements BlobStore { @Override public boolean removeListener(BlobStoreListener listener) { return listeners.removeListener(listener); } SwiftBlobStore(SwiftBlobStoreInfo config, TileLayerDispatcher layers); @Override void destroy(); @Override void addListener(BlobStoreListener listener); @Override boolean removeListener(BlobStoreListener listener); @Override void put(TileObject obj); @Override boolean get(TileObject obj); @Override boolean delete(final TileRange tileRange); @Override boolean delete(String layerName); @Override boolean deleteByGridsetId(final String layerName, final String gridSetId); @Override boolean delete(TileObject obj); @Override boolean rename(String oldLayerName, String newLayerName); @Override void clear(); @Nullable @Override String getLayerMetadata(String layerName, String key); @Override void putLayerMetadata(String layerName, String key, String value); @Override boolean layerExists(String layerName); @Override Map<String, Optional<Map<String, String>>> getParametersMapping(String layerName); @Override boolean deleteByParametersId(String layerName, String parametersId); }
@Test public void removeListener() { BlobStoreListener swiftListener = mock(BlobStoreListener.class); this.testListeners.addListener(swiftListener); ArrayList<BlobStoreListener> testListenersList = (ArrayList) testListeners.getListeners(); assertTrue(testListenersList.contains(swiftListener)); this.swiftBlobStore.removeListener(swiftListener); assertTrue(testListeners.isEmpty()); }
SwiftBlobStore implements BlobStore { @Override public void put(TileObject obj) throws StorageException { try { final SwiftTile tile = new SwiftTile(obj); final String key = keyBuilder.forTile(obj); executor.execute(new SwiftUploadTask(key, tile, listeners, objectApi)); log.debug("Added request to upload queue. Queue length is now " + uploadQueue.size()); } catch (IOException e) { throw new StorageException("Could not process tile object for upload."); } } SwiftBlobStore(SwiftBlobStoreInfo config, TileLayerDispatcher layers); @Override void destroy(); @Override void addListener(BlobStoreListener listener); @Override boolean removeListener(BlobStoreListener listener); @Override void put(TileObject obj); @Override boolean get(TileObject obj); @Override boolean delete(final TileRange tileRange); @Override boolean delete(String layerName); @Override boolean deleteByGridsetId(final String layerName, final String gridSetId); @Override boolean delete(TileObject obj); @Override boolean rename(String oldLayerName, String newLayerName); @Override void clear(); @Nullable @Override String getLayerMetadata(String layerName, String key); @Override void putLayerMetadata(String layerName, String key, String value); @Override boolean layerExists(String layerName); @Override Map<String, Optional<Map<String, String>>> getParametersMapping(String layerName); @Override boolean deleteByParametersId(String layerName, String parametersId); }
@Test public void testPutWhenFormatNull() { Resource testResource = createTestResource(3L); TileObject testTileObject = createMockTileObject(testResource); when(testTileObject.getBlobFormat()).thenReturn(null); try { this.swiftBlobStore.put(testTileObject); fail("Null check when tile format is null failed"); } catch (NullPointerException e) { assertThat(e.getMessage(), is("Object Blob Format must not be null.")); } catch (StorageException e) { fail("Should be throwing a NullPointerException.\n" + e); } verify(this.keyBuilder, times(0)).forTile(testTileObject); } @Test public void testPutWhenBlobIsNull() { TileObject testTileObject = createMockTileObject(mock(Resource.class)); when(testTileObject.getBlob()).thenReturn(null); try { this.swiftBlobStore.put(testTileObject); fail("Null check when blob is null failed"); } catch (NullPointerException e) { verify(testTileObject, times(1)).getBlob(); assertThat(e.getMessage(), is("Object Blob must not be null.")); } catch (StorageException e) { fail("Should be throwing a NullPointerException.\n" + e); } verify(this.keyBuilder, times(0)).forTile(testTileObject); } @Test(expected = RuntimeException.class) public void testPutWhenBlobIsAnInvalidMimeType() { Resource testResource = createTestResource(3L); TileObject testTileObject = createMockTileObject(testResource); when(testTileObject.getBlobFormat()).thenReturn("invalid mime type"); try { this.swiftBlobStore.put(testTileObject); fail("Null check for grid check id failed"); } catch (StorageException e) { fail("Should be throwing a RuntimeException caused by a MimeException.\n" + e); } }
SwiftBlobStore implements BlobStore { @Override public boolean get(TileObject obj) throws StorageException { final String key = keyBuilder.forTile(obj); SwiftObject object = this.objectApi.get(key); if (object == null) { return false; } try (Payload in = object.getPayload()) { try (InputStream inStream = in.openStream()) { byte[] bytes = ByteStreams.toByteArray(inStream); obj.setBlobSize(bytes.length); obj.setBlob(new ByteArrayResource(bytes)); obj.setCreated(object.getLastModified().getTime()); } } catch (IOException e) { throw new StorageException("Error getting " + key, e); } return true; } SwiftBlobStore(SwiftBlobStoreInfo config, TileLayerDispatcher layers); @Override void destroy(); @Override void addListener(BlobStoreListener listener); @Override boolean removeListener(BlobStoreListener listener); @Override void put(TileObject obj); @Override boolean get(TileObject obj); @Override boolean delete(final TileRange tileRange); @Override boolean delete(String layerName); @Override boolean deleteByGridsetId(final String layerName, final String gridSetId); @Override boolean delete(TileObject obj); @Override boolean rename(String oldLayerName, String newLayerName); @Override void clear(); @Nullable @Override String getLayerMetadata(String layerName, String key); @Override void putLayerMetadata(String layerName, String key, String value); @Override boolean layerExists(String layerName); @Override Map<String, Optional<Map<String, String>>> getParametersMapping(String layerName); @Override boolean deleteByParametersId(String layerName, String parametersId); }
@Test public void get() { String thePayloadData = "Test Content"; Date lastModified = new Date(); ByteSourcePayload testByteSourcePayload = new ByteSourcePayload( new ByteSource() { @Override public InputStream openStream() { return new ByteArrayInputStream(thePayloadData.getBytes()); } }); SwiftObject swiftObject = mock(SwiftObject.class); when(swiftObject.getLastModified()).thenReturn(lastModified); when(swiftObject.getPayload()).thenReturn(testByteSourcePayload); try { when(objectApi.get("sample/key")).thenReturn(swiftObject); boolean result = this.swiftBlobStore.get(sampleTileObject); verify(keyBuilder, times(1)).forTile(sampleTileObject); verify(objectApi, times(1)).get("sample/key"); verify(swiftObject, times(1)).getPayload(); ByteArrayResource expectedByteArray = new ByteArrayResource(thePayloadData.getBytes()); ByteArrayResource actualByteArray = (ByteArrayResource) sampleTileObject.getBlob(); assertEquals(thePayloadData.length(), sampleTileObject.getBlobSize()); assertArrayEquals(expectedByteArray.getContents(), actualByteArray.getContents()); assertEquals(lastModified.getTime(), sampleTileObject.getCreated()); assertTrue(result); when(objectApi.get("sample/key")).thenReturn(null); result = this.swiftBlobStore.get(sampleTileObject); assertFalse(result); } catch (StorageException e) { fail("A storage exception was not expected to be thrown"); } catch (IOException e) { e.printStackTrace(); } }
SwiftBlobStore implements BlobStore { @Override public boolean deleteByGridsetId(final String layerName, final String gridSetId) { checkNotNull(layerName, "layerName"); checkNotNull(gridSetId, "gridSetId"); final String gridsetPrefix = keyBuilder.forGridset(layerName, gridSetId); boolean deletedSuccessfully = this.deleteByPath(gridsetPrefix); if (deletedSuccessfully) { listeners.sendGridSubsetDeleted(layerName, gridSetId); } return deletedSuccessfully; } SwiftBlobStore(SwiftBlobStoreInfo config, TileLayerDispatcher layers); @Override void destroy(); @Override void addListener(BlobStoreListener listener); @Override boolean removeListener(BlobStoreListener listener); @Override void put(TileObject obj); @Override boolean get(TileObject obj); @Override boolean delete(final TileRange tileRange); @Override boolean delete(String layerName); @Override boolean deleteByGridsetId(final String layerName, final String gridSetId); @Override boolean delete(TileObject obj); @Override boolean rename(String oldLayerName, String newLayerName); @Override void clear(); @Nullable @Override String getLayerMetadata(String layerName, String key); @Override void putLayerMetadata(String layerName, String key, String value); @Override boolean layerExists(String layerName); @Override Map<String, Optional<Map<String, String>>> getParametersMapping(String layerName); @Override boolean deleteByParametersId(String layerName, String parametersId); }
@Test public void deleteByGridsetId() { String testGridSetID = "TestGridSetID"; String testGridsetPrefix = "test/gridset/prefix"; doReturn(testGridsetPrefix) .when(this.keyBuilder) .forGridset(VALID_TEST_LAYER_NAME, testGridSetID); doReturn(false).when(this.swiftBlobStore).deleteByPath(testGridsetPrefix); boolean outcome = this.swiftBlobStore.deleteByGridsetId(VALID_TEST_LAYER_NAME, testGridSetID); verify(this.keyBuilder, times(1)).forGridset(VALID_TEST_LAYER_NAME, testGridSetID); verify(this.swiftBlobStore, times(1)).deleteByPath(testGridsetPrefix); verify(this.testListeners, times(0)) .sendGridSubsetDeleted(VALID_TEST_LAYER_NAME, testGridSetID); assertFalse(outcome); doReturn(true).when(this.swiftBlobStore).deleteByPath(testGridsetPrefix); outcome = this.swiftBlobStore.deleteByGridsetId(VALID_TEST_LAYER_NAME, testGridSetID); verify(this.keyBuilder, times(2)).forGridset(VALID_TEST_LAYER_NAME, testGridSetID); verify(this.swiftBlobStore, times(2)).deleteByPath(testGridsetPrefix); verify(this.testListeners, times(1)) .sendGridSubsetDeleted(VALID_TEST_LAYER_NAME, testGridSetID); assertTrue(outcome); try { this.swiftBlobStore.deleteByGridsetId(null, testGridSetID); fail("Null check for layer name failed"); } catch (NullPointerException e) { verify(this.keyBuilder, times(0)).forGridset(null, testGridSetID); verify(this.testListeners, times(0)).sendGridSubsetDeleted(null, testGridSetID); } try { this.swiftBlobStore.deleteByGridsetId(VALID_TEST_LAYER_NAME, null); fail("Null check for grid check id failed"); } catch (NullPointerException e) { verify(this.keyBuilder, times(0)).forGridset(VALID_TEST_LAYER_NAME, null); verify(this.testListeners, times(0)).sendGridSubsetDeleted(VALID_TEST_LAYER_NAME, null); } }
SwiftBlobStore implements BlobStore { @Override public boolean rename(String oldLayerName, String newLayerName) { log.debug("No need to rename layers, SwiftBlobStore uses layer id as key root"); if (objectApi.get(oldLayerName) != null) { listeners.sendLayerRenamed(oldLayerName, newLayerName); } return true; } SwiftBlobStore(SwiftBlobStoreInfo config, TileLayerDispatcher layers); @Override void destroy(); @Override void addListener(BlobStoreListener listener); @Override boolean removeListener(BlobStoreListener listener); @Override void put(TileObject obj); @Override boolean get(TileObject obj); @Override boolean delete(final TileRange tileRange); @Override boolean delete(String layerName); @Override boolean deleteByGridsetId(final String layerName, final String gridSetId); @Override boolean delete(TileObject obj); @Override boolean rename(String oldLayerName, String newLayerName); @Override void clear(); @Nullable @Override String getLayerMetadata(String layerName, String key); @Override void putLayerMetadata(String layerName, String key, String value); @Override boolean layerExists(String layerName); @Override Map<String, Optional<Map<String, String>>> getParametersMapping(String layerName); @Override boolean deleteByParametersId(String layerName, String parametersId); }
@Test public void rename() { boolean result = this.swiftBlobStore.rename(VALID_TEST_LAYER_NAME, "NewLayerName"); verify(objectApi, times(1)).get(VALID_TEST_LAYER_NAME); verify(this.testListeners, times(0)) .sendLayerRenamed(VALID_TEST_LAYER_NAME, "NewLayerName"); assertTrue(result); when(this.objectApi.get(VALID_TEST_LAYER_NAME)).thenReturn(mock(SwiftObject.class)); result = this.swiftBlobStore.rename(VALID_TEST_LAYER_NAME, "NewLayerName"); verify(objectApi, times(2)).get(VALID_TEST_LAYER_NAME); verify(this.testListeners, times(1)) .sendLayerRenamed(VALID_TEST_LAYER_NAME, "NewLayerName"); assertTrue(result); }
SwiftBlobStore implements BlobStore { @Override public void clear() { throw new UnsupportedOperationException("clear() should not be called"); } SwiftBlobStore(SwiftBlobStoreInfo config, TileLayerDispatcher layers); @Override void destroy(); @Override void addListener(BlobStoreListener listener); @Override boolean removeListener(BlobStoreListener listener); @Override void put(TileObject obj); @Override boolean get(TileObject obj); @Override boolean delete(final TileRange tileRange); @Override boolean delete(String layerName); @Override boolean deleteByGridsetId(final String layerName, final String gridSetId); @Override boolean delete(TileObject obj); @Override boolean rename(String oldLayerName, String newLayerName); @Override void clear(); @Nullable @Override String getLayerMetadata(String layerName, String key); @Override void putLayerMetadata(String layerName, String key, String value); @Override boolean layerExists(String layerName); @Override Map<String, Optional<Map<String, String>>> getParametersMapping(String layerName); @Override boolean deleteByParametersId(String layerName, String parametersId); }
@Test public void clear() { try { this.swiftBlobStore.clear(); fail("This method should not work, it should throw a Unsupported Operation Exception"); } catch (UnsupportedOperationException e) { assertThat(e.getMessage(), is("clear() should not be called")); } }
SwiftBlobStore implements BlobStore { @Nullable @Override public String getLayerMetadata(String layerName, String key) { SwiftObject layer = this.objectApi.get(layerName); if (layer == null) { return null; } if (layer.getMetadata() == null) { return null; } else { return layer.getMetadata().get(key); } } SwiftBlobStore(SwiftBlobStoreInfo config, TileLayerDispatcher layers); @Override void destroy(); @Override void addListener(BlobStoreListener listener); @Override boolean removeListener(BlobStoreListener listener); @Override void put(TileObject obj); @Override boolean get(TileObject obj); @Override boolean delete(final TileRange tileRange); @Override boolean delete(String layerName); @Override boolean deleteByGridsetId(final String layerName, final String gridSetId); @Override boolean delete(TileObject obj); @Override boolean rename(String oldLayerName, String newLayerName); @Override void clear(); @Nullable @Override String getLayerMetadata(String layerName, String key); @Override void putLayerMetadata(String layerName, String key, String value); @Override boolean layerExists(String layerName); @Override Map<String, Optional<Map<String, String>>> getParametersMapping(String layerName); @Override boolean deleteByParametersId(String layerName, String parametersId); }
@Test public void getLayerMetadata() { SwiftObject swiftObject = mock(SwiftObject.class); SwiftObject swiftObjectWithoutMetadata = mock(SwiftObject.class); when(objectApi.get("")).thenReturn(null); when(objectApi.get(INVALID_TEST_LAYER_NAME)).thenReturn(null); when(objectApi.get(VALID_TEST_LAYER_NAME)).thenReturn(swiftObject); when(objectApi.get("valid layer without metadata")).thenReturn(swiftObjectWithoutMetadata); Map<String, String> sampleMetadata = new HashMap<>(); sampleMetadata.put("sample_key", "sample_value"); when(swiftObject.getMetadata()).thenReturn(sampleMetadata); when(swiftObjectWithoutMetadata.getMetadata()).thenReturn(new HashMap<>()); String result = this.swiftBlobStore.getLayerMetadata("", "sample_key"); assertEquals(null, result); result = this.swiftBlobStore.getLayerMetadata(INVALID_TEST_LAYER_NAME, "sample_key"); assertEquals(null, result); result = this.swiftBlobStore.getLayerMetadata( "valid layer name without metadata", "sample_key"); assertEquals(null, result); result = this.swiftBlobStore.getLayerMetadata(VALID_TEST_LAYER_NAME, "sample_key"); verify(objectApi, times(1)).get(VALID_TEST_LAYER_NAME); assertEquals("sample_value", result); result = this.swiftBlobStore.getLayerMetadata(VALID_TEST_LAYER_NAME, ""); verify(objectApi, times(1)).get(""); assertEquals(null, result); }
SwiftBlobStore implements BlobStore { @Override public void putLayerMetadata(String layerName, String key, String value) { SwiftObject layer = this.objectApi.get(layerName); Map<String, String> metaData; if (layer == null) { return; } metaData = layer.getMetadata(); if (metaData == null) { metaData = new HashMap<>(); } metaData.put(key, value); this.objectApi.updateMetadata(layerName, metaData); } SwiftBlobStore(SwiftBlobStoreInfo config, TileLayerDispatcher layers); @Override void destroy(); @Override void addListener(BlobStoreListener listener); @Override boolean removeListener(BlobStoreListener listener); @Override void put(TileObject obj); @Override boolean get(TileObject obj); @Override boolean delete(final TileRange tileRange); @Override boolean delete(String layerName); @Override boolean deleteByGridsetId(final String layerName, final String gridSetId); @Override boolean delete(TileObject obj); @Override boolean rename(String oldLayerName, String newLayerName); @Override void clear(); @Nullable @Override String getLayerMetadata(String layerName, String key); @Override void putLayerMetadata(String layerName, String key, String value); @Override boolean layerExists(String layerName); @Override Map<String, Optional<Map<String, String>>> getParametersMapping(String layerName); @Override boolean deleteByParametersId(String layerName, String parametersId); }
@Test public void putLayerMetadata() { assertNull(this.objectApi.get(VALID_TEST_LAYER_NAME)); swiftBlobStore.putLayerMetadata(VALID_TEST_LAYER_NAME, "test_key", "test_value"); assertNull(this.objectApi.get(VALID_TEST_LAYER_NAME)); SwiftObject layer = mock(SwiftObject.class); when(objectApi.get(VALID_TEST_LAYER_NAME)).thenReturn(layer); swiftBlobStore.putLayerMetadata(VALID_TEST_LAYER_NAME, "test_key", "test_value"); verify(layer, times(1)).getMetadata(); Map<String, String> newMetadata = new HashMap<>(); newMetadata.put("test_key", "test_value"); verify(objectApi, times(1)).updateMetadata(VALID_TEST_LAYER_NAME, newMetadata); Map<String, String> existingMetadata = new HashMap<>(); existingMetadata.put("sample_key", "sample_value"); when(layer.getMetadata()).thenReturn(existingMetadata); swiftBlobStore.putLayerMetadata(VALID_TEST_LAYER_NAME, "test_key", "test_value"); verify(layer, times(2)).getMetadata(); Map<String, String> updatedMetadata = new HashMap<>(); updatedMetadata.put("test_key", "test_value"); updatedMetadata.put("sample_key", "sample_value"); verify(objectApi, times(1)).updateMetadata(VALID_TEST_LAYER_NAME, updatedMetadata); }
SwiftBlobStore implements BlobStore { @Override public boolean layerExists(String layerName) { return this.objectApi.get(layerName) != null; } SwiftBlobStore(SwiftBlobStoreInfo config, TileLayerDispatcher layers); @Override void destroy(); @Override void addListener(BlobStoreListener listener); @Override boolean removeListener(BlobStoreListener listener); @Override void put(TileObject obj); @Override boolean get(TileObject obj); @Override boolean delete(final TileRange tileRange); @Override boolean delete(String layerName); @Override boolean deleteByGridsetId(final String layerName, final String gridSetId); @Override boolean delete(TileObject obj); @Override boolean rename(String oldLayerName, String newLayerName); @Override void clear(); @Nullable @Override String getLayerMetadata(String layerName, String key); @Override void putLayerMetadata(String layerName, String key, String value); @Override boolean layerExists(String layerName); @Override Map<String, Optional<Map<String, String>>> getParametersMapping(String layerName); @Override boolean deleteByParametersId(String layerName, String parametersId); }
@Test public void layerExists() { SwiftObject swiftObject = mock(SwiftObject.class); when(objectApi.get(VALID_TEST_LAYER_NAME)).thenReturn(swiftObject); assertTrue(swiftBlobStore.layerExists(VALID_TEST_LAYER_NAME)); when(objectApi.get("layer which doesn't exist")).thenReturn(null); assertFalse(swiftBlobStore.layerExists("layer which doesn't exist")); }
SwiftBlobStore implements BlobStore { @Override public Map<String, Optional<Map<String, String>>> getParametersMapping(String layerName) { String prefix = keyBuilder.parametersMetadataPrefix(layerName); ListContainerOptions options = new ListContainerOptions(); options.prefix(prefix); Map<String, Optional<Map<String, String>>> paramMapping = new HashMap<>(); for (SwiftObject obj : this.objectApi.list(options)) { paramMapping.put(obj.getName(), Optional.of(obj.getMetadata())); } return paramMapping; } SwiftBlobStore(SwiftBlobStoreInfo config, TileLayerDispatcher layers); @Override void destroy(); @Override void addListener(BlobStoreListener listener); @Override boolean removeListener(BlobStoreListener listener); @Override void put(TileObject obj); @Override boolean get(TileObject obj); @Override boolean delete(final TileRange tileRange); @Override boolean delete(String layerName); @Override boolean deleteByGridsetId(final String layerName, final String gridSetId); @Override boolean delete(TileObject obj); @Override boolean rename(String oldLayerName, String newLayerName); @Override void clear(); @Nullable @Override String getLayerMetadata(String layerName, String key); @Override void putLayerMetadata(String layerName, String key, String value); @Override boolean layerExists(String layerName); @Override Map<String, Optional<Map<String, String>>> getParametersMapping(String layerName); @Override boolean deleteByParametersId(String layerName, String parametersId); }
@Test public void getParametersMapping() { String prefixPath = "sample/prefix/path"; String testObjectName = "test object"; SwiftObject swiftObject = mock(SwiftObject.class); when(swiftObject.getName()).thenReturn(testObjectName); List<SwiftObject> swiftObjects = new ArrayList<>(); swiftObjects.add(swiftObject); ObjectList swiftObjectList = ObjectList.create(swiftObjects, mock(Container.class)); ListContainerOptions options = new ListContainerOptions(); options.prefix(prefixPath); when(this.objectApi.list(options)).thenReturn(swiftObjectList); doReturn(prefixPath).when(this.keyBuilder).parametersMetadataPrefix(VALID_TEST_LAYER_NAME); Map<String, Optional<Map<String, String>>> testResult = swiftBlobStore.getParametersMapping(VALID_TEST_LAYER_NAME); verify(keyBuilder, times(1)).parametersMetadataPrefix(VALID_TEST_LAYER_NAME); verify(objectApi, times(1)).list(options); Map<String, Optional<Map<String, String>>> expectedResult = new HashMap<>(); expectedResult.put(testObjectName, Optional.ofNullable(new HashMap<>())); assertEquals(expectedResult, testResult); Map<String, String> objectMetadata = new HashMap<>(); objectMetadata.put("test_key", "test_value"); when(swiftObject.getMetadata()).thenReturn(objectMetadata); testResult = swiftBlobStore.getParametersMapping(VALID_TEST_LAYER_NAME); verify(keyBuilder, times(2)).parametersMetadataPrefix(VALID_TEST_LAYER_NAME); verify(objectApi, times(2)).list(options); Map<String, Optional<Map<String, String>>> expectedResultWithMetadata = new HashMap<>(); expectedResultWithMetadata.put(testObjectName, Optional.of(objectMetadata)); assertEquals(expectedResultWithMetadata, testResult); }
SwiftBlobStore implements BlobStore { @Override public boolean deleteByParametersId(String layerName, String parametersId) { checkNotNull(layerName, "layerName"); checkNotNull(parametersId, "parametersId"); boolean deletionSuccessful = keyBuilder .forParameters(layerName, parametersId) .stream() .map(path -> this.deleteByPath(path)) .reduce(Boolean::logicalAnd) .orElse(false); if (deletionSuccessful) { listeners.sendParametersDeleted(layerName, parametersId); } return deletionSuccessful; } SwiftBlobStore(SwiftBlobStoreInfo config, TileLayerDispatcher layers); @Override void destroy(); @Override void addListener(BlobStoreListener listener); @Override boolean removeListener(BlobStoreListener listener); @Override void put(TileObject obj); @Override boolean get(TileObject obj); @Override boolean delete(final TileRange tileRange); @Override boolean delete(String layerName); @Override boolean deleteByGridsetId(final String layerName, final String gridSetId); @Override boolean delete(TileObject obj); @Override boolean rename(String oldLayerName, String newLayerName); @Override void clear(); @Nullable @Override String getLayerMetadata(String layerName, String key); @Override void putLayerMetadata(String layerName, String key, String value); @Override boolean layerExists(String layerName); @Override Map<String, Optional<Map<String, String>>> getParametersMapping(String layerName); @Override boolean deleteByParametersId(String layerName, String parametersId); }
@Test public void deleteByParametersId() { String testParametersId = "testParamId"; try { this.swiftBlobStore.deleteByParametersId(null, testParametersId); fail("Null check for layer name failed"); } catch (NullPointerException e) { assertThat(e.getMessage(), is("layerName")); } try { this.swiftBlobStore.deleteByParametersId(VALID_TEST_LAYER_NAME, null); fail("Null check for parameters id failed"); } catch (NullPointerException e) { assertThat(e.getMessage(), is("parametersId")); } Set<String> dummyParamsPrefixes = new HashSet<>(Arrays.asList("prefix/one", "prefix/two")); doReturn(dummyParamsPrefixes) .when(this.keyBuilder) .forParameters(VALID_TEST_LAYER_NAME, testParametersId); doReturn(true).when(this.swiftBlobStore).deleteByPath("prefix/one"); doReturn(true).when(this.swiftBlobStore).deleteByPath("prefix/two"); boolean outcome = this.swiftBlobStore.deleteByParametersId(VALID_TEST_LAYER_NAME, testParametersId); verify(this.swiftBlobStore, times(1)).deleteByPath("prefix/one"); verify(this.swiftBlobStore, times(1)).deleteByPath("prefix/two"); verify(this.testListeners, times(1)) .sendParametersDeleted(VALID_TEST_LAYER_NAME, testParametersId); assertTrue(outcome); doReturn(false).when(this.swiftBlobStore).deleteByPath("prefix/one"); outcome = this.swiftBlobStore.deleteByParametersId(VALID_TEST_LAYER_NAME, testParametersId); verify(this.swiftBlobStore, times(2)).deleteByPath("prefix/one"); verify(this.swiftBlobStore, times(2)).deleteByPath("prefix/two"); verify(this.testListeners, times(1)) .sendParametersDeleted(VALID_TEST_LAYER_NAME, testParametersId); assertFalse(outcome); }
S3BlobStoreConfigProvider implements XMLConfigurationProvider { @Override public XStream getConfiguredXStream(XStream xs) { xs.alias("S3BlobStore", S3BlobStoreInfo.class); xs.registerLocalConverter( S3BlobStoreInfo.class, "maxConnections", EnvironmentNullableIntConverter); xs.registerLocalConverter( S3BlobStoreInfo.class, "proxyPort", EnvironmentNullableIntConverter); xs.registerLocalConverter( S3BlobStoreInfo.class, "useHTTPS", EnvironmentNullableBooleanConverter); xs.registerLocalConverter( S3BlobStoreInfo.class, "useGzip", EnvironmentNullableBooleanConverter); xs.registerLocalConverter(S3BlobStoreInfo.class, "bucket", EnvironmentStringConverter); xs.registerLocalConverter( S3BlobStoreInfo.class, "awsAccessKey", EnvironmentStringConverter); xs.registerLocalConverter( S3BlobStoreInfo.class, "awsSecretKey", EnvironmentStringConverter); xs.registerLocalConverter(S3BlobStoreInfo.class, "prefix", EnvironmentStringConverter); xs.registerLocalConverter(S3BlobStoreInfo.class, "proxyHost", EnvironmentStringConverter); xs.registerLocalConverter( BlobStoreInfo.class, "enabled", EnvironmentNullableBooleanConverter); xs.aliasField("id", S3BlobStoreInfo.class, "name"); return xs; } @Override XStream getConfiguredXStream(XStream xs); @Override boolean canSave(Info i); }
@Test public void testValuesFromEnvironment() { S3BlobStoreConfigProvider provider = new S3BlobStoreConfigProvider(); XStream stream = new XStream(); stream = provider.getConfiguredXStream(stream); Object config = stream.fromXML(getClass().getResourceAsStream("blobstore.xml")); assertTrue(config instanceof S3BlobStoreInfo); S3BlobStoreInfo s3Config = (S3BlobStoreInfo) config; assertEquals("MYBUCKET", s3Config.getBucket()); assertEquals(30, s3Config.getMaxConnections().intValue()); assertEquals(true, s3Config.isEnabled()); }
WMTSService extends Service { @Override public Conveyor getConveyor(HttpServletRequest request, HttpServletResponse response) throws GeoWebCacheException, OWSException { for (WMTSExtension extension : extensions) { Conveyor conveyor = extension.getConveyor(request, response, sb); if (conveyor != null) { return conveyor; } } if (request.getPathInfo() != null && request.getPathInfo().contains("service/wmts/rest")) { return getRestConveyor(request, response); } String[] keys = { "layer", "request", "style", "format", "infoformat", "tilematrixset", "tilematrix", "tilerow", "tilecol", "i", "j" }; String encoding = request.getCharacterEncoding(); Map<String, String> values = ServletUtils.selectedStringsFromMap(request.getParameterMap(), encoding, keys); return getKvpConveyor(request, response, values); } protected WMTSService(); WMTSService( StorageBroker sb, TileLayerDispatcher tld, GridSetBroker gsb, RuntimeStats stats); WMTSService( StorageBroker sb, TileLayerDispatcher tld, GridSetBroker gsb, RuntimeStats stats, URLMangler urlMangler, GeoWebCacheDispatcher controller); @Override Conveyor getConveyor(HttpServletRequest request, HttpServletResponse response); Conveyor getRestConveyor(HttpServletRequest request, HttpServletResponse response); Conveyor getKvpConveyor( HttpServletRequest request, HttpServletResponse response, Map<String, String> values); void handleRequest(Conveyor conv); Collection<WMTSExtension> getExtensions(); void setSecurityDispatcher(SecurityDispatcher secDisp); void setMainConfiguration(ServerConfiguration mainConfiguration); static final String SERVICE_WMTS; static final String SERVICE_PATH; static final String REST_PATH; static final String GET_CAPABILITIES; static final String GET_FEATUREINFO; static final String GET_TILE; }
@Test public void testGetCap() throws Exception { GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); service = new WMTSService(sb, tld, null, mock(RuntimeStats.class)); @SuppressWarnings("unchecked") Map<String, String[]> kvp = new CaseInsensitiveMap(); kvp.put("service", new String[] {"WMTS"}); kvp.put("version", new String[] {"1.0.0"}); kvp.put("request", new String[] {"GetCapabilities"}); HttpServletRequest req = mock(HttpServletRequest.class); MockHttpServletResponse resp = new MockHttpServletResponse(); when(req.getCharacterEncoding()).thenReturn("UTF-8"); when(req.getParameterMap()).thenReturn(kvp); { List<String> gridSetNames = Arrays.asList("GlobalCRS84Pixel", "GlobalCRS84Scale", "EPSG:4326"); TileLayer tileLayer = mockTileLayer( "mockLayer", gridSetNames, Collections.<ParameterFilter>emptyList()); TileLayer tileLayerUn = mockTileLayer( "mockLayerUnadv", gridSetNames, Collections.<ParameterFilter>emptyList(), false); when(tld.getLayerList()).thenReturn(Arrays.asList(tileLayer, tileLayerUn)); StringParameterFilter styles = new StringParameterFilter(); styles.setKey("STYLES"); styles.setValues(Arrays.asList("style-a", "style-b")); when(tileLayer.getParameterFilters()).thenReturn(Collections.singletonList(styles)); LegendInfo legendInfo1 = new LegendInfoBuilder() .withStyleName("style-a-legend") .withWidth(250) .withHeight(500) .withFormat("image/jpeg") .withCompleteUrl( "https: .build(); Map<String, LegendInfo> legends = new HashMap<>(); legends.put("style-a", legendInfo1); LegendInfo legendInfo2 = new LegendInfoBuilder() .withStyleName("styla-b-legend") .withWidth(125) .withHeight(130) .withFormat("image/png") .withCompleteUrl( "https: .withMinScale(5000D) .withMaxScale(10000D) .build(); legends.put("style-b", legendInfo2); when(tileLayer.getLayerLegendsInfo()).thenReturn(legends); MetadataURL metadataURL = new MetadataURL( "some-type", "some-format", new URL("http: when(tileLayer.getMetadataURLs()).thenReturn(Collections.singletonList(metadataURL)); } Conveyor conv = service.getConveyor(req, resp); assertNotNull(conv); final String layerName = conv.getLayerId(); assertNull(layerName); assertEquals(Conveyor.RequestHandler.SERVICE, conv.reqHandler); WMTSGetCapabilities wmsCap = new WMTSGetCapabilities( tld, gridsetBroker, conv.servletReq, "http: "/geowebcache", new NullURLMangler()); wmsCap.writeResponse(conv.servletResp, mock(RuntimeStats.class)); assertTrue(resp.containsHeader("content-disposition")); assertEquals( "inline;filename=wmts-getcapabilities.xml", resp.getHeader("content-disposition")); String result = resp.getContentAsString(); assertTrue(result.contains("mockLayer")); assertFalse(result.contains("mockLayerUnadv")); Document doc = XMLUnit.buildTestDocument(result); Map<String, String> namespaces = new HashMap<>(); namespaces.put("xlink", "http: namespaces.put("xsi", "http: namespaces.put("ows", "http: namespaces.put("wmts", "http: XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(namespaces)); XpathEngine xpath = XMLUnit.newXpathEngine(); assertEquals("1", xpath.evaluate("count( assertEquals( "1", xpath.evaluate( "count( assertEquals( "2", xpath.evaluate("count( assertEquals( "1", xpath.evaluate( "count( doc)); assertEquals( "1", xpath.evaluate( "count( + "[@width='250'][@height='500'][@format='image/jpeg'][@xlink:href='https: doc)); assertEquals( "1", xpath.evaluate( "count( + "[@width='125'][@height='130'][@format='image/png'][@minScaleDenominator='5000.0'][@maxScaleDenominator='10000.0']" + "[@xlink:href='https: doc)); assertEquals( "1", xpath.evaluate( "count( doc)); assertEquals( "1", xpath.evaluate( "count( + "/wmts:OnlineResource[@xlink:href='http: doc)); assertEquals( "1", xpath.evaluate( "count( + "[@format='image/jpeg']" + "[@template='http: + WMTSService.REST_PATH + "/mockLayer/{style}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}?format=image/jpeg'])", doc)); assertEquals( "1", xpath.evaluate( "count( + "[@format='image/png']" + "[@template='http: + WMTSService.REST_PATH + "/mockLayer/{style}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}?format=image/png'])", doc)); assertEquals( "1", xpath.evaluate( "count( + "[@format='text/plain']" + "[@template='http: + WMTSService.REST_PATH + "/mockLayer/{style}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}/{J}/{I}?format=text/plain'])", doc)); assertEquals( "1", xpath.evaluate( "count( + "[@format='text/html']" + "[@template='http: + WMTSService.REST_PATH + "/mockLayer/{style}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}/{J}/{I}?format=text/html'])", doc)); assertEquals( "1", xpath.evaluate( "count( + "[@format='application/vnd.ogc.gml']" + "[@template='http: + WMTSService.REST_PATH + "/mockLayer/{style}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}/{J}/{I}?format=application/vnd.ogc.gml'])", doc)); assertEquals( "1", xpath.evaluate( "count( + WMTSService.SERVICE_PATH + "?SERVICE=wmts&REQUEST=getcapabilities&VERSION=1.0.0'])", doc)); assertEquals( "1", xpath.evaluate( "count( + WMTSService.REST_PATH + "/WMTSCapabilities.xml'])", doc)); } @Test public void testGetCapWithExtensions() throws Exception { List<WMTSExtension> extensions = new ArrayList<>(); extensions.add( new WMTSExtension() { @Override public String[] getSchemaLocations() { return new String[] {"name-space schema-location"}; } @Override public void registerNamespaces(XMLBuilder xml) throws IOException { xml.attribute("xmlns:custom", "custom"); } @Override public void encodedOperationsMetadata(XMLBuilder xml) throws IOException { xml.startElement("custom-metadata"); xml.endElement("custom-metadata"); } @Override public List<OperationMetadata> getExtraOperationsMetadata() throws IOException { return Arrays.asList( new OperationMetadata("ExtraOperation1"), new OperationMetadata("ExtraOperation2", "custom-url")); } @Override public ServiceInformation getServiceInformation() { ServiceInformation serviceInformation = new ServiceInformation(); serviceInformation.setTitle("custom-service"); return serviceInformation; } @Override public Conveyor getConveyor( HttpServletRequest request, HttpServletResponse response, StorageBroker storageBroker) throws GeoWebCacheException, OWSException { return null; } @Override public boolean handleRequest(Conveyor conveyor) throws OWSException { return false; } @Override public void encodeLayer(XMLBuilder xmlBuilder, TileLayer tileLayer) throws IOException { xmlBuilder.simpleElement("extra-layer-metadata", "metadatada", true); } }); extensions.add( new WMTSExtensionImpl() { @Override public ServiceInformation getServiceInformation() { ServiceInformation serviceInformation = new ServiceInformation(); ServiceProvider serviceProvider = new ServiceProvider(); serviceProvider.setProviderName("custom-provider"); serviceInformation.setServiceProvider(serviceProvider); ServiceContact contactInformation = new ServiceContact(); contactInformation.setPositionName("custom-position"); serviceProvider.setServiceContact(contactInformation); return serviceInformation; } }); extensions.add(new WMTSExtensionImpl()); GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); service = new WMTSService(sb, tld, null, mock(RuntimeStats.class)); extensions.forEach(service::addExtension); @SuppressWarnings("unchecked") Map<String, String[]> kvp = new CaseInsensitiveMap(); kvp.put("service", new String[] {"WMTS"}); kvp.put("version", new String[] {"1.0.0"}); kvp.put("request", new String[] {"GetCapabilities"}); HttpServletRequest req = mock(HttpServletRequest.class); MockHttpServletResponse resp = new MockHttpServletResponse(); when(req.getCharacterEncoding()).thenReturn("UTF-8"); when(req.getParameterMap()).thenReturn(kvp); List<String> gridSetNames = Arrays.asList("GlobalCRS84Pixel", "GlobalCRS84Scale", "EPSG:4326"); TileLayer tileLayer = mockTileLayer("mockLayer", gridSetNames, Collections.<ParameterFilter>emptyList()); when(tld.getLayerList()).thenReturn(Collections.singletonList(tileLayer)); Conveyor conv = service.getConveyor(req, resp); assertNotNull(conv); assertEquals(Conveyor.RequestHandler.SERVICE, conv.reqHandler); WMTSGetCapabilities wmsCap = new WMTSGetCapabilities( tld, gridsetBroker, conv.servletReq, "http: "/service/wmts", new NullURLMangler(), extensions); wmsCap.writeResponse(conv.servletResp, mock(RuntimeStats.class)); assertTrue(resp.containsHeader("content-disposition")); assertEquals( "inline;filename=wmts-getcapabilities.xml", resp.getHeader("content-disposition")); String result = resp.getContentAsString(); assertTrue(result.contains("xmlns:custom=\"custom\"")); assertTrue(result.contains("name-space schema-location")); Document doc = XMLUnit.buildTestDocument(result); Map<String, String> namespaces = new HashMap<>(); namespaces.put("xlink", "http: namespaces.put("xsi", "http: namespaces.put("ows", "http: namespaces.put("wmts", "http: XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(namespaces)); XpathEngine xpath = XMLUnit.newXpathEngine(); assertEquals("1", xpath.evaluate("count( assertEquals( "1", xpath.evaluate( "count( assertEquals( "1", xpath.evaluate( "count( assertEquals( "1", xpath.evaluate( "count( doc)); assertEquals( "1", xpath.evaluate( "count( doc)); assertEquals( "1", xpath.evaluate( "count( + "/ows:DCP/ows:HTTP/ows:Get[@xlink:href='http: doc)); assertEquals( "1", xpath.evaluate( "count( doc)); assertEquals( "1", xpath.evaluate( "count( + "/ows:DCP/ows:HTTP/ows:Get[@xlink:href='custom-url?'])", doc)); xpath.evaluate( "count( } @Test public void testGetCapServiceInfo() throws Exception { TileLayerDispatcher tldx = mockTileLayerDispatcher(); GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); service = new WMTSService(sb, tldx, null, mock(RuntimeStats.class)); @SuppressWarnings("unchecked") Map<String, String[]> kvp = new CaseInsensitiveMap(); kvp.put("service", new String[] {"WMTS"}); kvp.put("version", new String[] {"1.0.0"}); kvp.put("request", new String[] {"GetCapabilities"}); HttpServletRequest req = mock(HttpServletRequest.class); MockHttpServletResponse resp = new MockHttpServletResponse(); when(req.getCharacterEncoding()).thenReturn("UTF-8"); when(req.getParameterMap()).thenReturn(kvp); { List<String> gridSetNames = Arrays.asList( "GlobalCRS84Pixel", "GlobalCRS84Scale", "EPSG:4326", "EPSG:900913"); TileLayer tileLayer = mockTileLayer( "mockLayer", gridSetNames, Collections.<ParameterFilter>emptyList()); TileLayer tileLayerUn = mockTileLayer( "mockLayerUnadv", gridSetNames, Collections.<ParameterFilter>emptyList(), false); when(tld.getLayerList()).thenReturn(Arrays.asList(tileLayer, tileLayerUn)); GridSubset wgs84Subset = mock(GridSubset.class); when(wgs84Subset.getOriginalExtent()).thenReturn(new BoundingBox(-42d, -24d, 40d, 50d)); GridSubset googleSubset = mock(GridSubset.class); when(googleSubset.getOriginalExtent()) .thenReturn(new BoundingBox(1_000_000d, 2_000_000d, 1_000_000d, 2_000_000d)); when(tileLayer.getGridSubsetForSRS(SRS.getEPSG4326())).thenReturn(wgs84Subset); when(tileLayer.getGridSubsetForSRS(SRS.getEPSG900913())).thenReturn(googleSubset); } Conveyor conv = service.getConveyor(req, resp); assertNotNull(conv); final String layerName = conv.getLayerId(); assertNull(layerName); assertEquals(Conveyor.RequestHandler.SERVICE, conv.reqHandler); WMTSGetCapabilities wmsCap = new WMTSGetCapabilities( tldx, gridsetBroker, conv.servletReq, "http: "/geowebcache", new NullURLMangler()); wmsCap.writeResponse(conv.servletResp, mock(RuntimeStats.class)); assertTrue(resp.containsHeader("content-disposition")); assertEquals( "inline;filename=wmts-getcapabilities.xml", resp.getHeader("content-disposition")); String result = resp.getContentAsString(); assertTrue(result.contains("ServiceContact")); Document doc = XMLUnit.buildTestDocument(result); Map<String, String> namespaces = new HashMap<String, String>(); namespaces.put("xlink", "http: namespaces.put("xsi", "http: namespaces.put("ows", "http: namespaces.put("wmts", "http: XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(namespaces)); XpathEngine xpath = XMLUnit.newXpathEngine(); assertEquals("John Smith", xpath.evaluate(" } @Test public void testGetCapOneWGS84BBox() throws Exception { GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); service = new WMTSService(sb, tld, null, mock(RuntimeStats.class)); @SuppressWarnings("unchecked") Map<String, String[]> kvp = new CaseInsensitiveMap(); kvp.put("service", new String[] {"WMTS"}); kvp.put("version", new String[] {"1.0.0"}); kvp.put("request", new String[] {"GetCapabilities"}); HttpServletRequest req = mock(HttpServletRequest.class); MockHttpServletResponse resp = new MockHttpServletResponse(); when(req.getCharacterEncoding()).thenReturn("UTF-8"); when(req.getParameterMap()).thenReturn(kvp); { List<String> gridSetNames = Arrays.asList( "GlobalCRS84Pixel", "GlobalCRS84Scale", "EPSG:4326", "EPSG:900913"); TileLayer tileLayer = mockTileLayer( "mockLayer", gridSetNames, Collections.<ParameterFilter>emptyList()); TileLayer tileLayerUn = mockTileLayer( "mockLayerUnadv", gridSetNames, Collections.<ParameterFilter>emptyList(), false); when(tld.getLayerList()).thenReturn(Arrays.asList(tileLayer, tileLayerUn)); GridSubset wgs84Subset = mock(GridSubset.class); when(wgs84Subset.getOriginalExtent()).thenReturn(new BoundingBox(-42d, -24d, 40d, 50d)); GridSubset googleSubset = mock(GridSubset.class); when(googleSubset.getOriginalExtent()) .thenReturn(new BoundingBox(1_000_000d, 2_000_000d, 1_000_000d, 2_000_000d)); when(tileLayer.getGridSubsetForSRS(SRS.getEPSG4326())).thenReturn(wgs84Subset); when(tileLayer.getGridSubsetForSRS(SRS.getEPSG900913())).thenReturn(googleSubset); } Conveyor conv = service.getConveyor(req, resp); assertNotNull(conv); final String layerName = conv.getLayerId(); assertNull(layerName); assertEquals(Conveyor.RequestHandler.SERVICE, conv.reqHandler); WMTSGetCapabilities wmsCap = new WMTSGetCapabilities( tld, gridsetBroker, conv.servletReq, "http: "/geowebcache", new NullURLMangler()); wmsCap.writeResponse(conv.servletResp, mock(RuntimeStats.class)); assertTrue(resp.containsHeader("content-disposition")); assertEquals( "inline;filename=wmts-getcapabilities.xml", resp.getHeader("content-disposition")); String result = resp.getContentAsString(); assertTrue(result.contains("mockLayer")); assertFalse(result.contains("mockLayerUnadv")); Document doc = XMLUnit.buildTestDocument(result); Map<String, String> namespaces = new HashMap<String, String>(); namespaces.put("xlink", "http: namespaces.put("xsi", "http: namespaces.put("ows", "http: namespaces.put("wmts", "http: XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(namespaces)); XpathEngine xpath = XMLUnit.newXpathEngine(); assertEquals("1", xpath.evaluate("count( } @Test public void testGetCapUnboundedStyleFilter() throws Exception { GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); service = new WMTSService(sb, tld, null, mock(RuntimeStats.class)); @SuppressWarnings("unchecked") Map<String, String[]> kvp = new CaseInsensitiveMap(); kvp.put("service", new String[] {"WMTS"}); kvp.put("version", new String[] {"1.0.0"}); kvp.put("request", new String[] {"GetCapabilities"}); HttpServletRequest req = mock(HttpServletRequest.class); MockHttpServletResponse resp = new MockHttpServletResponse(); when(req.getCharacterEncoding()).thenReturn("UTF-8"); when(req.getParameterMap()).thenReturn(kvp); { List<String> gridSetNames = Arrays.asList("GlobalCRS84Pixel", "GlobalCRS84Scale", "EPSG:4326"); ParameterFilter styleFilter = mock(ParameterFilter.class); when(styleFilter.getKey()).thenReturn("STYLES"); when(styleFilter.getDefaultValue()).thenReturn("Foo"); when(styleFilter.getLegalValues()).thenReturn(null); TileLayer tileLayer = mockTileLayer( "mockLayer", gridSetNames, Collections.singletonList(styleFilter)); when(tld.getLayerList()).thenReturn(Arrays.asList(tileLayer)); } Conveyor conv = service.getConveyor(req, resp); assertNotNull(conv); final String layerName = conv.getLayerId(); assertNull(layerName); assertEquals(Conveyor.RequestHandler.SERVICE, conv.reqHandler); WMTSGetCapabilities wmsCap = new WMTSGetCapabilities( tld, gridsetBroker, conv.servletReq, "http: "/geowebcache", new NullURLMangler()); wmsCap.writeResponse(conv.servletResp, mock(RuntimeStats.class)); assertTrue(resp.containsHeader("content-disposition")); assertEquals( "inline;filename=wmts-getcapabilities.xml", resp.getHeader("content-disposition")); String result = resp.getContentAsString(); Document doc = XMLUnit.buildTestDocument(result); Map<String, String> namespaces = new HashMap<String, String>(); namespaces.put("xlink", "http: namespaces.put("xsi", "http: namespaces.put("ows", "http: namespaces.put("wmts", "http: XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(namespaces)); XpathEngine xpath = XMLUnit.newXpathEngine(); assertEquals("1", xpath.evaluate("count( assertEquals( "1", xpath.evaluate( "count( assertEquals( "1", xpath.evaluate("count( assertEquals( "", xpath.evaluate(" } @Test public void testGetCapEmptyStyleFilter() throws Exception { GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); service = new WMTSService(sb, tld, null, mock(RuntimeStats.class)); @SuppressWarnings("unchecked") Map<String, String[]> kvp = new CaseInsensitiveMap(); kvp.put("service", new String[] {"WMTS"}); kvp.put("version", new String[] {"1.0.0"}); kvp.put("request", new String[] {"GetCapabilities"}); HttpServletRequest req = mock(HttpServletRequest.class); MockHttpServletResponse resp = new MockHttpServletResponse(); when(req.getCharacterEncoding()).thenReturn("UTF-8"); when(req.getParameterMap()).thenReturn(kvp); { List<String> gridSetNames = Arrays.asList("GlobalCRS84Pixel", "GlobalCRS84Scale", "EPSG:4326"); ParameterFilter styleFilter = mock(ParameterFilter.class); when(styleFilter.getKey()).thenReturn("STYLES"); when(styleFilter.getDefaultValue()).thenReturn("Foo"); when(styleFilter.getLegalValues()).thenReturn(Collections.<String>emptyList()); TileLayer tileLayer = mockTileLayer( "mockLayer", gridSetNames, Collections.singletonList(styleFilter)); when(tld.getLayerList()).thenReturn(Arrays.asList(tileLayer)); } Conveyor conv = service.getConveyor(req, resp); assertNotNull(conv); final String layerName = conv.getLayerId(); assertNull(layerName); assertEquals(Conveyor.RequestHandler.SERVICE, conv.reqHandler); WMTSGetCapabilities wmsCap = new WMTSGetCapabilities( tld, gridsetBroker, conv.servletReq, "http: "/geowebcache", new NullURLMangler()); wmsCap.writeResponse(conv.servletResp, mock(RuntimeStats.class)); assertTrue(resp.containsHeader("content-disposition")); assertEquals( "inline;filename=wmts-getcapabilities.xml", resp.getHeader("content-disposition")); String result = resp.getContentAsString(); Validator validator = new Validator(result); validator.useXMLSchema(true); validator.assertIsValid(); Document doc = XMLUnit.buildTestDocument(result); Map<String, String> namespaces = new HashMap<String, String>(); namespaces.put("xlink", "http: namespaces.put("xsi", "http: namespaces.put("ows", "http: namespaces.put("wmts", "http: XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(namespaces)); XpathEngine xpath = XMLUnit.newXpathEngine(); assertEquals("1", xpath.evaluate("count( assertEquals( "1", xpath.evaluate( "count( assertEquals( "1", xpath.evaluate("count( assertEquals( "", xpath.evaluate(" } @Test public void testGetCapMultipleStyles() throws Exception { GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); service = new WMTSService(sb, tld, null, mock(RuntimeStats.class)); @SuppressWarnings("unchecked") Map<String, String[]> kvp = new CaseInsensitiveMap(); kvp.put("service", new String[] {"WMTS"}); kvp.put("version", new String[] {"1.0.0"}); kvp.put("request", new String[] {"GetCapabilities"}); HttpServletRequest req = mock(HttpServletRequest.class); MockHttpServletResponse resp = new MockHttpServletResponse(); when(req.getCharacterEncoding()).thenReturn("UTF-8"); when(req.getParameterMap()).thenReturn(kvp); { List<String> gridSetNames = Arrays.asList("GlobalCRS84Pixel", "GlobalCRS84Scale", "EPSG:4326"); ParameterFilter styleFilter = mock(ParameterFilter.class); when(styleFilter.getKey()).thenReturn("STYLES"); when(styleFilter.getDefaultValue()).thenReturn("Foo"); when(styleFilter.getLegalValues()).thenReturn(Arrays.asList("Foo", "Bar", "Baz")); TileLayer tileLayer = mockTileLayer( "mockLayer", gridSetNames, Collections.singletonList(styleFilter)); when(tld.getLayerList()).thenReturn(Arrays.asList(tileLayer)); } Conveyor conv = service.getConveyor(req, resp); assertNotNull(conv); final String layerName = conv.getLayerId(); assertNull(layerName); assertEquals(Conveyor.RequestHandler.SERVICE, conv.reqHandler); WMTSGetCapabilities wmsCap = new WMTSGetCapabilities( tld, gridsetBroker, conv.servletReq, "http: "/geowebcache", new NullURLMangler()); wmsCap.writeResponse(conv.servletResp, mock(RuntimeStats.class)); assertTrue(resp.containsHeader("content-disposition")); assertEquals( "inline;filename=wmts-getcapabilities.xml", resp.getHeader("content-disposition")); String result = resp.getContentAsString(); Document doc = XMLUnit.buildTestDocument(result); Map<String, String> namespaces = new HashMap<String, String>(); namespaces.put("xlink", "http: namespaces.put("xsi", "http: namespaces.put("ows", "http: namespaces.put("wmts", "http: XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(namespaces)); XpathEngine xpath = XMLUnit.newXpathEngine(); assertEquals("1", xpath.evaluate("count( assertEquals( "1", xpath.evaluate( "count( assertEquals( "3", xpath.evaluate( "count( doc)); assertEquals( "1", xpath.evaluate( "count( doc)); assertEquals( "1", xpath.evaluate( "count( doc)); assertEquals( "1", xpath.evaluate( "count( doc)); assertEquals( "1", xpath.evaluate( "count( doc)); } @SuppressWarnings("unchecked") @Test public void testGetCapWithMultipleDimensions() throws Exception { GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); service = new WMTSService(sb, tld, null, mock(RuntimeStats.class)); Map<String, String[]> kvp = new CaseInsensitiveMap(); kvp.put("service", new String[] {"WMTS"}); kvp.put("version", new String[] {"1.0.0"}); kvp.put("request", new String[] {"GetCapabilities"}); HttpServletRequest req = mock(HttpServletRequest.class); MockHttpServletResponse resp = new MockHttpServletResponse(); when(req.getCharacterEncoding()).thenReturn("UTF-8"); when(req.getParameterMap()).thenReturn(kvp); { List<String> gridSetNames = Arrays.asList("GlobalCRS84Pixel", "GlobalCRS84Scale", "EPSG:4326"); ParameterFilter styleFilter = mock(ParameterFilter.class); when(styleFilter.getKey()).thenReturn("STYLES"); when(styleFilter.getDefaultValue()).thenReturn("Foo"); when(styleFilter.getLegalValues()).thenReturn(Arrays.asList("Foo", "Bar", "Baz")); ParameterFilter elevationDimension = mock(ParameterFilter.class); when(elevationDimension.getKey()).thenReturn("elevation"); when(elevationDimension.getDefaultValue()).thenReturn("0"); when(elevationDimension.getLegalValues()) .thenReturn(Arrays.asList("0", "200", "400", "600")); ParameterFilter timeDimension = mock(ParameterFilter.class); when(timeDimension.getKey()).thenReturn("time"); when(timeDimension.getDefaultValue()).thenReturn("2016-02-23T03:00:00.00"); when(timeDimension.getLegalValues()).thenReturn(Collections.<String>emptyList()); TileLayer tileLayer = mockTileLayer( "mockLayer", gridSetNames, Arrays.asList(styleFilter, elevationDimension, timeDimension)); when(tld.getLayerList()).thenReturn(Arrays.asList(tileLayer)); } Conveyor conv = service.getConveyor(req, resp); assertNotNull(conv); final String layerName = conv.getLayerId(); assertNull(layerName); assertEquals(Conveyor.RequestHandler.SERVICE, conv.reqHandler); WMTSGetCapabilities wmsCap = new WMTSGetCapabilities( tld, gridsetBroker, conv.servletReq, "http: "/geowebcache", new NullURLMangler()); wmsCap.writeResponse(conv.servletResp, mock(RuntimeStats.class)); assertTrue(resp.containsHeader("content-disposition")); assertEquals( "inline;filename=wmts-getcapabilities.xml", resp.getHeader("content-disposition")); String result = resp.getContentAsString(); Document doc = XMLUnit.buildTestDocument(result); Map<String, String> namespaces = new HashMap<String, String>(); namespaces.put("xlink", "http: namespaces.put("xsi", "http: namespaces.put("ows", "http: namespaces.put("wmts", "http: XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(namespaces)); XpathEngine xpath = XMLUnit.newXpathEngine(); assertEquals("1", xpath.evaluate("count( assertEquals( "1", xpath.evaluate( "count( assertEquals( "5", xpath.evaluate( "count( + "[contains(@template,'&elevation={elevation}&time={time}')])", doc)); assertEquals( "2", xpath.evaluate( "count( } @SuppressWarnings("unchecked") @Test public void testGetTileWithStyle() throws Exception { GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); service = new WMTSService(sb, tld, null, mock(RuntimeStats.class)); Map<String, String[]> kvp = new CaseInsensitiveMap(); kvp.put("service", new String[] {"WMTS"}); kvp.put("version", new String[] {"1.0.0"}); kvp.put("request", new String[] {"GetTile"}); kvp.put("layer", new String[] {"mockLayer"}); kvp.put("format", new String[] {"image/png"}); kvp.put("TileMatrixSet", new String[] {"GlobalCRS84Pixel"}); kvp.put("TileMatrix", new String[] {"GlobalCRS84Pixel:1"}); kvp.put("TileRow", new String[] {"0"}); kvp.put("TileCol", new String[] {"0"}); kvp.put("Style", new String[] {"Bar"}); HttpServletRequest req = mock(HttpServletRequest.class); MockHttpServletResponse resp = new MockHttpServletResponse(); when(req.getParameterMap()).thenReturn(kvp); { List<String> gridSetNames = Arrays.asList("GlobalCRS84Pixel", "GlobalCRS84Scale", "EPSG:4326"); ParameterFilter styleFilter = mock(ParameterFilter.class); when(styleFilter.getKey()).thenReturn("STYLES"); when(styleFilter.getDefaultValue()).thenReturn("Foo"); when(styleFilter.getLegalValues()).thenReturn(Arrays.asList("Foo", "Bar", "Baz")); TileLayer tileLayer = mockTileLayer( "mockLayer", gridSetNames, Collections.singletonList(styleFilter)); Map<String, String> map = new HashMap<>(); map.put("STYLES", "Bar"); when(tileLayer.getModifiableParameters( (Map) argThat( hasEntry( equalToIgnoringCase("styles"), arrayContaining(equalToIgnoringCase("Bar")))), (String) any())) .thenReturn(Collections.unmodifiableMap(map)); when(tld.getLayerList()).thenReturn(Arrays.asList(tileLayer)); } Conveyor conv = service.getConveyor(req, resp); assertNotNull(conv); final String layerName = conv.getLayerId(); assertEquals("mockLayer", layerName); assertThat(conv, instanceOf(ConveyorTile.class)); ConveyorTile tile = (ConveyorTile) conv; Map<String, String> parameters = tile.getParameters(); assertThat(parameters, hasEntry("STYLES", "Bar")); }
WMSTileFuser { protected void writeResponse(HttpServletResponse response, RuntimeStats stats) throws IOException, OutsideCoverageException, GeoWebCacheException, Exception { determineSourceResolution(); determineCanvasLayout(); createCanvas(); renderCanvas(); scaleRaster(); @SuppressWarnings("PMD.CloseResource") AccountingOutputStream aos = null; RenderedImage finalImage = null; try { finalImage = canvas; response.setStatus(HttpServletResponse.SC_OK); response.setContentType(this.outputFormat.getMimeType()); response.setCharacterEncoding("UTF-8"); @SuppressWarnings("PMD.CloseResource") ServletOutputStream os = response.getOutputStream(); aos = new AccountingOutputStream(os); encoderMap.encode( finalImage, outputFormat, aos, encoderMap.isAggressiveOutputStreamSupported(outputFormat.getMimeType()), null); log.debug("WMS response size: " + aos.getCount() + "bytes."); stats.log(aos.getCount(), CacheResult.WMS); } catch (Exception e) { log.debug("IOException writing untiled response to client: " + e.getMessage(), e); if (aos != null) { IOUtils.closeQuietly(aos); } if (finalImage != null) { ImageUtilities.disposePlanarImageChain(PlanarImage.wrapRenderedImage(finalImage)); } } } protected WMSTileFuser(TileLayerDispatcher tld, StorageBroker sb, HttpServletRequest servReq); @Deprecated protected WMSTileFuser( TileLayer layer, GridSubset gridSubset, BoundingBox bounds, int width, int height); void setApplicationContext(ApplicationContext context); void setHintsConfiguration(String hintsConfig); void setSecurityDispatcher(SecurityDispatcher securityDispatcher); }
@Test public void testWriteResponse() throws Exception { final TileLayer layer = createWMSLayer(); BoundingBox bounds = new BoundingBox(-35.0, 14.0, 55.0, 39); int width = (int) bounds.getWidth() * 25; int height = (int) bounds.getHeight() * 25; layer.getGridSubset(layer.getGridSubsets().iterator().next()); File temp = File.createTempFile("gwc", "wms"); temp.delete(); temp.mkdirs(); try { TileLayerDispatcher dispatcher = new TileLayerDispatcher(gridSetBroker) { @Override public TileLayer getTileLayer(String layerName) throws GeoWebCacheException { return layer; } }; MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("layers", new String[] {"test:layer"}); request.addParameter("srs", new String[] {"EPSG:4326"}); request.addParameter("format", new String[] {"image/png8"}); request.addParameter("width", width + ""); request.addParameter("height", height + ""); request.addParameter("bbox", bounds.toString()); final File imageTile = new File(getClass().getResource("/image.png").toURI()); StorageBroker broker = new DefaultStorageBroker( new FileBlobStore(temp.getAbsolutePath()) { @Override public boolean get(TileObject stObj) throws StorageException { stObj.setBlob(new FileResource(imageTile)); stObj.setCreated((new Date()).getTime()); stObj.setBlobSize(1000); return true; } }, new TransientCache(100, 1024, 2000)); WMSTileFuser tileFuser = new WMSTileFuser(dispatcher, broker, request); tileFuser.setSecurityDispatcher(secDisp); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appContextTest.xml"); tileFuser.setApplicationContext(context); MockHttpServletResponse response = new MockHttpServletResponse(); tileFuser.writeResponse( response, new RuntimeStats(1, Arrays.asList(1), Arrays.asList("desc"))); assertTrue(response.getContentAsString().length() > 0); } finally { temp.delete(); } }
JDBCQuotaStore implements QuotaStore { public void renameLayer(final String oldLayerName, final String newLayerName) throws InterruptedException { tt.execute( new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { String sql = dialect.getRenameLayerStatement(schema, "oldName", "newName"); Map<String, Object> params = new HashMap<String, Object>(); params.put("oldName", oldLayerName); params.put("newName", newLayerName); int updated = jt.update(sql, params); log.info("Updated " + updated + " tile sets after layer rename"); } }); } JDBCQuotaStore(DefaultStorageFinder finder, TilePageCalculator tilePageCalculator); SQLDialect getDialect(); void setDialect(SQLDialect dialect); String getSchema(); void setSchema(String schema); @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") void setDataSource(DataSource dataSource); void initialize(); void createLayer(String layerName); Quota getGloballyUsedQuota(); Quota getUsedQuotaByTileSetId(String tileSetId); Quota getUsedQuotaByLayerName(String layerName); Quota getUsedQuotaByGridsetid(String gridsetId); Quota getUsedQuotaByLayerGridset(String layerName, String gridsetId); Quota getUsedQuotaByParametersId(String parametersId); void deleteLayer(final String layerName); void deleteGridSubset(final String layerName, final String gridSetId); void deleteLayerInternal(final String layerName); void renameLayer(final String oldLayerName, final String newLayerName); Set<TileSet> getTileSets(); void accept(final TileSetVisitor visitor); TileSet getTileSetById(String tileSetId); TilePageCalculator getTilePageCalculator(); void addToQuotaAndTileCounts( final TileSet tileSet, final Quota quotaDiff, final Collection<PageStatsPayload> tileCountDiffs); @SuppressWarnings("unchecked") Future<List<PageStats>> addHitsAndSetAccesTime( final Collection<PageStatsPayload> statsUpdates); long[][] getTilesForPage(TilePage page); TilePage getLeastFrequentlyUsedPage(Set<String> layerNames); TilePage getLeastRecentlyUsedPage(Set<String> layerNames); PageStats setTruncated(final TilePage page); void close(); @Override void deleteParameters(final String layerName, final String parametersId); static final String GLOBAL_QUOTA_NAME; }
@Test public void testRenameLayer() throws InterruptedException { assertEquals(16, countTileSetsByLayerName("topp:states")); store.renameLayer("topp:states", "states_renamed"); assertEquals(0, countTileSetsByLayerName("topp:states")); assertEquals(16, countTileSetsByLayerName("states_renamed")); }
JDBCQuotaStore implements QuotaStore { @Override public void deleteParameters(final String layerName, final String parametersId) { tt.execute( new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { Quota quota = getUsedQuotaByParametersId(parametersId); quota.setBytes(quota.getBytes().negate()); String updateQuota = dialect.getUpdateQuotaStatement(schema, "tileSetId", "bytes"); Map<String, Object> params = new HashMap<String, Object>(); params.put("tileSetId", GLOBAL_QUOTA_NAME); params.put("bytes", new BigDecimal(quota.getBytes())); jt.update(updateQuota, params); String statement = dialect.getLayerParametersDeletionStatement( schema, "layerName", "parametersId"); params = new HashMap<String, Object>(); params.put("layerName", layerName); params.put("parametersId", parametersId); jt.update(statement, params); } }); } JDBCQuotaStore(DefaultStorageFinder finder, TilePageCalculator tilePageCalculator); SQLDialect getDialect(); void setDialect(SQLDialect dialect); String getSchema(); void setSchema(String schema); @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") void setDataSource(DataSource dataSource); void initialize(); void createLayer(String layerName); Quota getGloballyUsedQuota(); Quota getUsedQuotaByTileSetId(String tileSetId); Quota getUsedQuotaByLayerName(String layerName); Quota getUsedQuotaByGridsetid(String gridsetId); Quota getUsedQuotaByLayerGridset(String layerName, String gridsetId); Quota getUsedQuotaByParametersId(String parametersId); void deleteLayer(final String layerName); void deleteGridSubset(final String layerName, final String gridSetId); void deleteLayerInternal(final String layerName); void renameLayer(final String oldLayerName, final String newLayerName); Set<TileSet> getTileSets(); void accept(final TileSetVisitor visitor); TileSet getTileSetById(String tileSetId); TilePageCalculator getTilePageCalculator(); void addToQuotaAndTileCounts( final TileSet tileSet, final Quota quotaDiff, final Collection<PageStatsPayload> tileCountDiffs); @SuppressWarnings("unchecked") Future<List<PageStats>> addHitsAndSetAccesTime( final Collection<PageStatsPayload> statsUpdates); long[][] getTilesForPage(TilePage page); TilePage getLeastFrequentlyUsedPage(Set<String> layerNames); TilePage getLeastRecentlyUsedPage(Set<String> layerNames); PageStats setTruncated(final TilePage page); void close(); @Override void deleteParameters(final String layerName, final String parametersId); static final String GLOBAL_QUOTA_NAME; }
@Test public void testDeleteParameters() throws InterruptedException { String layerName = "topp:states"; TileSet tset1 = new TileSet(layerName, "EPSG:4326", "image/jpeg", paramIds[0]); addToQuotaStore(tset1); TileSet tset2 = new TileSet(layerName, "EPSG:4326", "image/jpeg", paramIds[1]); addToQuotaStore(tset2); Quota tset1Quota = store.getUsedQuotaByTileSetId(tset1.getId()); Quota tset2Quota = store.getUsedQuotaByTileSetId(tset2.getId()); Quota globalQuota = store.getGloballyUsedQuota(); Quota sum = new Quota(); sum.add(tset1Quota); sum.add(tset2Quota); assertEquals(globalQuota.getBytes(), sum.getBytes()); assertThat( store.getTileSets(), containsInAnyOrder( expectedTileSets .stream() .map(Matchers::equalTo) .collect(Collectors.toSet()))); store.deleteParameters("topp:states", paramIds[1]); assertThat( store.getTileSets(), containsInAnyOrder( expectedTileSets .stream() .filter( ts -> !(Objects.equal(ts.getParametersId(), paramIds[1]) && ts.getLayerName().equals(layerName))) .map(Matchers::equalTo) .collect(Collectors.toSet()))); tset1Quota = store.getUsedQuotaByTileSetId(tset1.getId()); tset2Quota = store.getUsedQuotaByTileSetId(tset2.getId()); assertNotNull(tset2Quota); assertEquals(new BigInteger("0"), tset2Quota.getBytes()); globalQuota = store.getGloballyUsedQuota(); assertEquals(tset1Quota.getBytes(), globalQuota.getBytes()); }
JDBCQuotaStore implements QuotaStore { public void deleteLayer(final String layerName) { tt.execute( new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { deleteLayerInternal(layerName); } }); } JDBCQuotaStore(DefaultStorageFinder finder, TilePageCalculator tilePageCalculator); SQLDialect getDialect(); void setDialect(SQLDialect dialect); String getSchema(); void setSchema(String schema); @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") void setDataSource(DataSource dataSource); void initialize(); void createLayer(String layerName); Quota getGloballyUsedQuota(); Quota getUsedQuotaByTileSetId(String tileSetId); Quota getUsedQuotaByLayerName(String layerName); Quota getUsedQuotaByGridsetid(String gridsetId); Quota getUsedQuotaByLayerGridset(String layerName, String gridsetId); Quota getUsedQuotaByParametersId(String parametersId); void deleteLayer(final String layerName); void deleteGridSubset(final String layerName, final String gridSetId); void deleteLayerInternal(final String layerName); void renameLayer(final String oldLayerName, final String newLayerName); Set<TileSet> getTileSets(); void accept(final TileSetVisitor visitor); TileSet getTileSetById(String tileSetId); TilePageCalculator getTilePageCalculator(); void addToQuotaAndTileCounts( final TileSet tileSet, final Quota quotaDiff, final Collection<PageStatsPayload> tileCountDiffs); @SuppressWarnings("unchecked") Future<List<PageStats>> addHitsAndSetAccesTime( final Collection<PageStatsPayload> statsUpdates); long[][] getTilesForPage(TilePage page); TilePage getLeastFrequentlyUsedPage(Set<String> layerNames); TilePage getLeastRecentlyUsedPage(Set<String> layerNames); PageStats setTruncated(final TilePage page); void close(); @Override void deleteParameters(final String layerName, final String parametersId); static final String GLOBAL_QUOTA_NAME; }
@Test public void testDeleteLayer() throws InterruptedException { String layerName = "topp:states2"; TileSet tset = new TileSet(layerName, "EPSG:2163", "image/jpeg", null); addToQuotaStore(tset); Quota oldUsedQuota = store.getUsedQuotaByLayerName(layerName); assertNotNull(oldUsedQuota); Quota globalQuotaBefore = store.getGloballyUsedQuota(); assertTrue(oldUsedQuota.getBytes().longValue() > 0); assertTrue(globalQuotaBefore.getBytes().longValue() > 0); TileSet tileSet = tilePageCalculator.getTileSetsFor(layerName).iterator().next(); TilePage page = new TilePage(tileSet.getId(), 0, 0, (byte) 0); store.addHitsAndSetAccesTime(Collections.singleton(new PageStatsPayload(page))); assertNotNull(store.getTileSetById(tileSet.getId())); Thread.sleep(100); store.deleteLayer(layerName); assertNull(store.getLeastRecentlyUsedPage(Collections.singleton(layerName))); Quota usedQuota = store.getUsedQuotaByLayerName(layerName); assertNotNull(usedQuota); assertEquals(0L, usedQuota.getBytes().longValue()); Quota globalQuotaAfter = store.getGloballyUsedQuota(); assertEquals(0, globalQuotaAfter.getBytes().longValue()); }
JDBCQuotaStore implements QuotaStore { public TileSet getTileSetById(String tileSetId) throws InterruptedException { TileSet result = getTileSetByIdInternal(tileSetId); if (result == null) { throw new IllegalArgumentException("Could not find a tile set with id: " + tileSetId); } return result; } JDBCQuotaStore(DefaultStorageFinder finder, TilePageCalculator tilePageCalculator); SQLDialect getDialect(); void setDialect(SQLDialect dialect); String getSchema(); void setSchema(String schema); @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") void setDataSource(DataSource dataSource); void initialize(); void createLayer(String layerName); Quota getGloballyUsedQuota(); Quota getUsedQuotaByTileSetId(String tileSetId); Quota getUsedQuotaByLayerName(String layerName); Quota getUsedQuotaByGridsetid(String gridsetId); Quota getUsedQuotaByLayerGridset(String layerName, String gridsetId); Quota getUsedQuotaByParametersId(String parametersId); void deleteLayer(final String layerName); void deleteGridSubset(final String layerName, final String gridSetId); void deleteLayerInternal(final String layerName); void renameLayer(final String oldLayerName, final String newLayerName); Set<TileSet> getTileSets(); void accept(final TileSetVisitor visitor); TileSet getTileSetById(String tileSetId); TilePageCalculator getTilePageCalculator(); void addToQuotaAndTileCounts( final TileSet tileSet, final Quota quotaDiff, final Collection<PageStatsPayload> tileCountDiffs); @SuppressWarnings("unchecked") Future<List<PageStats>> addHitsAndSetAccesTime( final Collection<PageStatsPayload> statsUpdates); long[][] getTilesForPage(TilePage page); TilePage getLeastFrequentlyUsedPage(Set<String> layerNames); TilePage getLeastRecentlyUsedPage(Set<String> layerNames); PageStats setTruncated(final TilePage page); void close(); @Override void deleteParameters(final String layerName, final String parametersId); static final String GLOBAL_QUOTA_NAME; }
@Test public void testGetTileSetById() throws Exception { TileSet tileSet = store.getTileSetById(testTileSet.getId()); assertNotNull(tileSet); assertEquals(testTileSet, tileSet); try { store.getTileSetById("NonExistentTileSetId"); fail("Expected IAE"); } catch (IllegalArgumentException e) { assertTrue(true); } }
JDBCQuotaStore implements QuotaStore { public Quota getUsedQuotaByLayerName(String layerName) { String sql = dialect.getUsedQuotaByLayerName(schema, "layerName"); return nonNullQuota( jt.queryForOptionalObject( sql, new DiskQuotaMapper(), Collections.singletonMap("layerName", layerName))); } JDBCQuotaStore(DefaultStorageFinder finder, TilePageCalculator tilePageCalculator); SQLDialect getDialect(); void setDialect(SQLDialect dialect); String getSchema(); void setSchema(String schema); @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") void setDataSource(DataSource dataSource); void initialize(); void createLayer(String layerName); Quota getGloballyUsedQuota(); Quota getUsedQuotaByTileSetId(String tileSetId); Quota getUsedQuotaByLayerName(String layerName); Quota getUsedQuotaByGridsetid(String gridsetId); Quota getUsedQuotaByLayerGridset(String layerName, String gridsetId); Quota getUsedQuotaByParametersId(String parametersId); void deleteLayer(final String layerName); void deleteGridSubset(final String layerName, final String gridSetId); void deleteLayerInternal(final String layerName); void renameLayer(final String oldLayerName, final String newLayerName); Set<TileSet> getTileSets(); void accept(final TileSetVisitor visitor); TileSet getTileSetById(String tileSetId); TilePageCalculator getTilePageCalculator(); void addToQuotaAndTileCounts( final TileSet tileSet, final Quota quotaDiff, final Collection<PageStatsPayload> tileCountDiffs); @SuppressWarnings("unchecked") Future<List<PageStats>> addHitsAndSetAccesTime( final Collection<PageStatsPayload> statsUpdates); long[][] getTilesForPage(TilePage page); TilePage getLeastFrequentlyUsedPage(Set<String> layerNames); TilePage getLeastRecentlyUsedPage(Set<String> layerNames); PageStats setTruncated(final TilePage page); void close(); @Override void deleteParameters(final String layerName, final String parametersId); static final String GLOBAL_QUOTA_NAME; }
@SuppressWarnings("unchecked") @Test public void testGetUsedQuotaByLayerName() throws Exception { String layerName = "topp:states2"; List<TileSet> tileSets; tileSets = new ArrayList<TileSet>(tilePageCalculator.getTileSetsFor(layerName)); Quota expected = new Quota(); for (TileSet tset : tileSets) { Quota quotaDiff = new Quota(10, StorageUnit.MiB); expected.add(quotaDiff); store.addToQuotaAndTileCounts(tset, quotaDiff, Collections.EMPTY_SET); } Quota usedQuotaByLayerName = store.getUsedQuotaByLayerName(layerName); assertEquals(expected.getBytes(), usedQuotaByLayerName.getBytes()); }
JDBCQuotaStore implements QuotaStore { public Quota getUsedQuotaByTileSetId(String tileSetId) { return nonNullQuota(getUsedQuotaByTileSetIdInternal(tileSetId)); } JDBCQuotaStore(DefaultStorageFinder finder, TilePageCalculator tilePageCalculator); SQLDialect getDialect(); void setDialect(SQLDialect dialect); String getSchema(); void setSchema(String schema); @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") void setDataSource(DataSource dataSource); void initialize(); void createLayer(String layerName); Quota getGloballyUsedQuota(); Quota getUsedQuotaByTileSetId(String tileSetId); Quota getUsedQuotaByLayerName(String layerName); Quota getUsedQuotaByGridsetid(String gridsetId); Quota getUsedQuotaByLayerGridset(String layerName, String gridsetId); Quota getUsedQuotaByParametersId(String parametersId); void deleteLayer(final String layerName); void deleteGridSubset(final String layerName, final String gridSetId); void deleteLayerInternal(final String layerName); void renameLayer(final String oldLayerName, final String newLayerName); Set<TileSet> getTileSets(); void accept(final TileSetVisitor visitor); TileSet getTileSetById(String tileSetId); TilePageCalculator getTilePageCalculator(); void addToQuotaAndTileCounts( final TileSet tileSet, final Quota quotaDiff, final Collection<PageStatsPayload> tileCountDiffs); @SuppressWarnings("unchecked") Future<List<PageStats>> addHitsAndSetAccesTime( final Collection<PageStatsPayload> statsUpdates); long[][] getTilesForPage(TilePage page); TilePage getLeastFrequentlyUsedPage(Set<String> layerNames); TilePage getLeastRecentlyUsedPage(Set<String> layerNames); PageStats setTruncated(final TilePage page); void close(); @Override void deleteParameters(final String layerName, final String parametersId); static final String GLOBAL_QUOTA_NAME; }
@SuppressWarnings("unchecked") @Test public void testGetUsedQuotaByTileSetId() throws Exception { String layerName = "topp:states2"; List<TileSet> tileSets; tileSets = new ArrayList<TileSet>(tilePageCalculator.getTileSetsFor(layerName)); Map<String, Quota> expectedById = new HashMap<String, Quota>(); for (TileSet tset : tileSets) { Quota quotaDiff = new Quota(10D * Math.random(), StorageUnit.MiB); store.addToQuotaAndTileCounts(tset, quotaDiff, Collections.EMPTY_SET); store.addToQuotaAndTileCounts(tset, quotaDiff, Collections.EMPTY_SET); Quota tsetQuota = new Quota(quotaDiff); tsetQuota.add(quotaDiff); expectedById.put(tset.getId(), tsetQuota); } for (Map.Entry<String, Quota> expected : expectedById.entrySet()) { BigInteger expectedValaue = expected.getValue().getBytes(); String tsetId = expected.getKey(); assertEquals(expectedValaue, store.getUsedQuotaByTileSetId(tsetId).getBytes()); } }
AzureBlobStoreConfigProvider implements XMLConfigurationProvider { @Override public XStream getConfiguredXStream(XStream xs) { Class<AzureBlobStoreInfo> clazz = AzureBlobStoreInfo.class; xs.alias("AzureBlobStore", clazz); xs.aliasField("id", clazz, "name"); return xs; } @Override XStream getConfiguredXStream(XStream xs); @Override boolean canSave(Info i); }
@Test public void testValuesFromEnvironment() { AzureBlobStoreConfigProvider provider = new AzureBlobStoreConfigProvider(); XStream stream = new XStream(); stream = provider.getConfiguredXStream(stream); Object config = stream.fromXML(getClass().getResourceAsStream("blobstore.xml")); assertTrue(config instanceof AzureBlobStoreInfo); AzureBlobStoreInfo abConfig = (AzureBlobStoreInfo) config; assertEquals("${CONTAINER}", abConfig.getContainer()); assertEquals("myname", abConfig.getAccountName()); assertEquals("${MYKEY}", abConfig.getAccountKey()); assertEquals("30", abConfig.getMaxConnections()); assertEquals(true, abConfig.isEnabled()); }
JDBCQuotaStore implements QuotaStore { public Quota getGloballyUsedQuota() throws InterruptedException { return nonNullQuota(getUsedQuotaByTileSetIdInternal(GLOBAL_QUOTA_NAME)); } JDBCQuotaStore(DefaultStorageFinder finder, TilePageCalculator tilePageCalculator); SQLDialect getDialect(); void setDialect(SQLDialect dialect); String getSchema(); void setSchema(String schema); @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") void setDataSource(DataSource dataSource); void initialize(); void createLayer(String layerName); Quota getGloballyUsedQuota(); Quota getUsedQuotaByTileSetId(String tileSetId); Quota getUsedQuotaByLayerName(String layerName); Quota getUsedQuotaByGridsetid(String gridsetId); Quota getUsedQuotaByLayerGridset(String layerName, String gridsetId); Quota getUsedQuotaByParametersId(String parametersId); void deleteLayer(final String layerName); void deleteGridSubset(final String layerName, final String gridSetId); void deleteLayerInternal(final String layerName); void renameLayer(final String oldLayerName, final String newLayerName); Set<TileSet> getTileSets(); void accept(final TileSetVisitor visitor); TileSet getTileSetById(String tileSetId); TilePageCalculator getTilePageCalculator(); void addToQuotaAndTileCounts( final TileSet tileSet, final Quota quotaDiff, final Collection<PageStatsPayload> tileCountDiffs); @SuppressWarnings("unchecked") Future<List<PageStats>> addHitsAndSetAccesTime( final Collection<PageStatsPayload> statsUpdates); long[][] getTilesForPage(TilePage page); TilePage getLeastFrequentlyUsedPage(Set<String> layerNames); TilePage getLeastRecentlyUsedPage(Set<String> layerNames); PageStats setTruncated(final TilePage page); void close(); @Override void deleteParameters(final String layerName, final String parametersId); static final String GLOBAL_QUOTA_NAME; }
@Test public void testGetGloballyUsedQuota() throws InterruptedException { Quota usedQuota = store.getGloballyUsedQuota(); assertNotNull(usedQuota); assertEquals(0, usedQuota.getBytes().intValue()); String layerName = tilePageCalculator.getLayerNames().iterator().next(); TileSet tileSet = tilePageCalculator.getTileSetsFor(layerName).iterator().next(); Quota quotaDiff = new Quota(BigInteger.valueOf(1000)); Collection<PageStatsPayload> tileCountDiffs = Collections.emptySet(); store.addToQuotaAndTileCounts(tileSet, quotaDiff, tileCountDiffs); usedQuota = store.getGloballyUsedQuota(); assertNotNull(usedQuota); assertEquals(1000, usedQuota.getBytes().intValue()); quotaDiff = new Quota(BigInteger.valueOf(-500)); store.addToQuotaAndTileCounts(tileSet, quotaDiff, tileCountDiffs); usedQuota = store.getGloballyUsedQuota(); assertNotNull(usedQuota); assertEquals(500, usedQuota.getBytes().intValue()); }
JDBCQuotaStore implements QuotaStore { public PageStats setTruncated(final TilePage page) throws InterruptedException { return (PageStats) tt.execute( new TransactionCallback<Object>() { public Object doInTransaction(TransactionStatus status) { if (log.isDebugEnabled()) { log.info("Truncating page " + page); } PageStats stats = getPageStats(page.getKey()); if (stats != null) { stats.setFillFactor(0); int modified = setPageFillFactor(page, stats); if (modified == 0) { return null; } } return stats; } }); } JDBCQuotaStore(DefaultStorageFinder finder, TilePageCalculator tilePageCalculator); SQLDialect getDialect(); void setDialect(SQLDialect dialect); String getSchema(); void setSchema(String schema); @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") void setDataSource(DataSource dataSource); void initialize(); void createLayer(String layerName); Quota getGloballyUsedQuota(); Quota getUsedQuotaByTileSetId(String tileSetId); Quota getUsedQuotaByLayerName(String layerName); Quota getUsedQuotaByGridsetid(String gridsetId); Quota getUsedQuotaByLayerGridset(String layerName, String gridsetId); Quota getUsedQuotaByParametersId(String parametersId); void deleteLayer(final String layerName); void deleteGridSubset(final String layerName, final String gridSetId); void deleteLayerInternal(final String layerName); void renameLayer(final String oldLayerName, final String newLayerName); Set<TileSet> getTileSets(); void accept(final TileSetVisitor visitor); TileSet getTileSetById(String tileSetId); TilePageCalculator getTilePageCalculator(); void addToQuotaAndTileCounts( final TileSet tileSet, final Quota quotaDiff, final Collection<PageStatsPayload> tileCountDiffs); @SuppressWarnings("unchecked") Future<List<PageStats>> addHitsAndSetAccesTime( final Collection<PageStatsPayload> statsUpdates); long[][] getTilesForPage(TilePage page); TilePage getLeastFrequentlyUsedPage(Set<String> layerNames); TilePage getLeastRecentlyUsedPage(Set<String> layerNames); PageStats setTruncated(final TilePage page); void close(); @Override void deleteParameters(final String layerName, final String parametersId); static final String GLOBAL_QUOTA_NAME; }
@Test public void testSetTruncated() throws Exception { String tileSetId = testTileSet.getId(); TilePage page = new TilePage(tileSetId, 0, 0, 2); PageStatsPayload payload = new PageStatsPayload(page); payload.setTileSet(testTileSet); int numHits = 100; payload.setNumHits(numHits); payload.setNumTiles(5); store.addToQuotaAndTileCounts( testTileSet, new Quota(1, StorageUnit.MiB), Collections.singleton(payload)); List<PageStats> stats = store.addHitsAndSetAccesTime(Collections.singleton(payload)).get(); assertTrue(stats.get(0).getFillFactor() > 0f); PageStats pageStats = store.setTruncated(page); assertEquals(0f, pageStats.getFillFactor(), 1e-6f); }
JDBCQuotaStore implements QuotaStore { public TilePage getLeastFrequentlyUsedPage(Set<String> layerNames) throws InterruptedException { return getSinglePage(layerNames, true); } JDBCQuotaStore(DefaultStorageFinder finder, TilePageCalculator tilePageCalculator); SQLDialect getDialect(); void setDialect(SQLDialect dialect); String getSchema(); void setSchema(String schema); @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") void setDataSource(DataSource dataSource); void initialize(); void createLayer(String layerName); Quota getGloballyUsedQuota(); Quota getUsedQuotaByTileSetId(String tileSetId); Quota getUsedQuotaByLayerName(String layerName); Quota getUsedQuotaByGridsetid(String gridsetId); Quota getUsedQuotaByLayerGridset(String layerName, String gridsetId); Quota getUsedQuotaByParametersId(String parametersId); void deleteLayer(final String layerName); void deleteGridSubset(final String layerName, final String gridSetId); void deleteLayerInternal(final String layerName); void renameLayer(final String oldLayerName, final String newLayerName); Set<TileSet> getTileSets(); void accept(final TileSetVisitor visitor); TileSet getTileSetById(String tileSetId); TilePageCalculator getTilePageCalculator(); void addToQuotaAndTileCounts( final TileSet tileSet, final Quota quotaDiff, final Collection<PageStatsPayload> tileCountDiffs); @SuppressWarnings("unchecked") Future<List<PageStats>> addHitsAndSetAccesTime( final Collection<PageStatsPayload> statsUpdates); long[][] getTilesForPage(TilePage page); TilePage getLeastFrequentlyUsedPage(Set<String> layerNames); TilePage getLeastRecentlyUsedPage(Set<String> layerNames); PageStats setTruncated(final TilePage page); void close(); @Override void deleteParameters(final String layerName, final String parametersId); static final String GLOBAL_QUOTA_NAME; }
@Test public void testGetLeastFrequentlyUsedPage() throws Exception { final String layerName = testTileSet.getLayerName(); Set<String> layerNames = Collections.singleton(layerName); TilePage lfuPage; lfuPage = store.getLeastFrequentlyUsedPage(layerNames); assertNull(lfuPage); TilePage page1 = new TilePage(testTileSet.getId(), 0, 1, 2); TilePage page2 = new TilePage(testTileSet.getId(), 1, 1, 2); PageStatsPayload payload1 = new PageStatsPayload(page1, testTileSet); PageStatsPayload payload2 = new PageStatsPayload(page2, testTileSet); payload1.setNumHits(100); payload2.setNumHits(10); Collection<PageStatsPayload> statsUpdates = Arrays.asList(payload1, payload2); store.addHitsAndSetAccesTime(statsUpdates).get(); TilePage leastFrequentlyUsedPage = store.getLeastFrequentlyUsedPage(layerNames); assertEquals(page2, leastFrequentlyUsedPage); payload2.setNumHits(1000); store.addHitsAndSetAccesTime(statsUpdates).get(); leastFrequentlyUsedPage = store.getLeastFrequentlyUsedPage(layerNames); assertEquals(page1, leastFrequentlyUsedPage); }
JDBCQuotaStore implements QuotaStore { public TilePage getLeastRecentlyUsedPage(Set<String> layerNames) throws InterruptedException { return getSinglePage(layerNames, false); } JDBCQuotaStore(DefaultStorageFinder finder, TilePageCalculator tilePageCalculator); SQLDialect getDialect(); void setDialect(SQLDialect dialect); String getSchema(); void setSchema(String schema); @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") void setDataSource(DataSource dataSource); void initialize(); void createLayer(String layerName); Quota getGloballyUsedQuota(); Quota getUsedQuotaByTileSetId(String tileSetId); Quota getUsedQuotaByLayerName(String layerName); Quota getUsedQuotaByGridsetid(String gridsetId); Quota getUsedQuotaByLayerGridset(String layerName, String gridsetId); Quota getUsedQuotaByParametersId(String parametersId); void deleteLayer(final String layerName); void deleteGridSubset(final String layerName, final String gridSetId); void deleteLayerInternal(final String layerName); void renameLayer(final String oldLayerName, final String newLayerName); Set<TileSet> getTileSets(); void accept(final TileSetVisitor visitor); TileSet getTileSetById(String tileSetId); TilePageCalculator getTilePageCalculator(); void addToQuotaAndTileCounts( final TileSet tileSet, final Quota quotaDiff, final Collection<PageStatsPayload> tileCountDiffs); @SuppressWarnings("unchecked") Future<List<PageStats>> addHitsAndSetAccesTime( final Collection<PageStatsPayload> statsUpdates); long[][] getTilesForPage(TilePage page); TilePage getLeastFrequentlyUsedPage(Set<String> layerNames); TilePage getLeastRecentlyUsedPage(Set<String> layerNames); PageStats setTruncated(final TilePage page); void close(); @Override void deleteParameters(final String layerName, final String parametersId); static final String GLOBAL_QUOTA_NAME; }
@Test public void testGetLeastRecentlyUsedPage() throws Exception { MockSystemUtils mockSystemUtils = new MockSystemUtils(); mockSystemUtils.setCurrentTimeMinutes(1000); mockSystemUtils.setCurrentTimeMillis(mockSystemUtils.currentTimeMinutes() * 60 * 1000); SystemUtils.set(mockSystemUtils); final String layerName = testTileSet.getLayerName(); Set<String> layerNames = Collections.singleton(layerName); TilePage leastRecentlyUsedPage; leastRecentlyUsedPage = store.getLeastRecentlyUsedPage(layerNames); assertNull(leastRecentlyUsedPage); TilePage page1 = new TilePage(testTileSet.getId(), 0, 1, 2); TilePage page2 = new TilePage(testTileSet.getId(), 1, 1, 2); PageStatsPayload payload1 = new PageStatsPayload(page1, testTileSet); PageStatsPayload payload2 = new PageStatsPayload(page2, testTileSet); payload1.setLastAccessTime(mockSystemUtils.currentTimeMillis() + 1 * 60 * 1000); payload2.setLastAccessTime(mockSystemUtils.currentTimeMillis() + 2 * 60 * 1000); Collection<PageStatsPayload> statsUpdates = Arrays.asList(payload1, payload2); store.addHitsAndSetAccesTime(statsUpdates).get(); leastRecentlyUsedPage = store.getLeastRecentlyUsedPage(layerNames); assertEquals(page1, leastRecentlyUsedPage); payload1.setLastAccessTime(mockSystemUtils.currentTimeMillis() + 10 * 60 * 1000); store.addHitsAndSetAccesTime(statsUpdates).get(); leastRecentlyUsedPage = store.getLeastRecentlyUsedPage(layerNames); assertEquals(page2, leastRecentlyUsedPage); }
JDBCQuotaStore implements QuotaStore { public long[][] getTilesForPage(TilePage page) throws InterruptedException { TileSet tileSet = getTileSetById(page.getTileSetId()); long[][] gridCoverage = calculator.toGridCoverage(tileSet, page); return gridCoverage; } JDBCQuotaStore(DefaultStorageFinder finder, TilePageCalculator tilePageCalculator); SQLDialect getDialect(); void setDialect(SQLDialect dialect); String getSchema(); void setSchema(String schema); @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") void setDataSource(DataSource dataSource); void initialize(); void createLayer(String layerName); Quota getGloballyUsedQuota(); Quota getUsedQuotaByTileSetId(String tileSetId); Quota getUsedQuotaByLayerName(String layerName); Quota getUsedQuotaByGridsetid(String gridsetId); Quota getUsedQuotaByLayerGridset(String layerName, String gridsetId); Quota getUsedQuotaByParametersId(String parametersId); void deleteLayer(final String layerName); void deleteGridSubset(final String layerName, final String gridSetId); void deleteLayerInternal(final String layerName); void renameLayer(final String oldLayerName, final String newLayerName); Set<TileSet> getTileSets(); void accept(final TileSetVisitor visitor); TileSet getTileSetById(String tileSetId); TilePageCalculator getTilePageCalculator(); void addToQuotaAndTileCounts( final TileSet tileSet, final Quota quotaDiff, final Collection<PageStatsPayload> tileCountDiffs); @SuppressWarnings("unchecked") Future<List<PageStats>> addHitsAndSetAccesTime( final Collection<PageStatsPayload> statsUpdates); long[][] getTilesForPage(TilePage page); TilePage getLeastFrequentlyUsedPage(Set<String> layerNames); TilePage getLeastRecentlyUsedPage(Set<String> layerNames); PageStats setTruncated(final TilePage page); void close(); @Override void deleteParameters(final String layerName, final String parametersId); static final String GLOBAL_QUOTA_NAME; }
@Test public void testGetTilesForPage() throws Exception { TilePage page = new TilePage(testTileSet.getId(), 0, 0, 0); long[][] expected = tilePageCalculator.toGridCoverage(testTileSet, page); long[][] tilesForPage = store.getTilesForPage(page); assertTrue(Arrays.equals(expected[0], tilesForPage[0])); page = new TilePage(testTileSet.getId(), 0, 0, 1); expected = tilePageCalculator.toGridCoverage(testTileSet, page); tilesForPage = store.getTilesForPage(page); assertTrue(Arrays.equals(expected[1], tilesForPage[1])); }
FileUtils { public static boolean renameFile(File src, File dst) { boolean renamed = false; boolean win = System.getProperty("os.name").startsWith("Windows"); if (win && dst.exists()) { if (!dst.delete()) { throw new RuntimeException("Could not delete: " + dst.getPath()); } } Path srcPath = Paths.get(src.toURI()); Path dstPath = Paths.get(dst.toURI()); Path moved = null; try { moved = Files.move(srcPath, dstPath, StandardCopyOption.ATOMIC_MOVE); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug( "An error occurred when executing atomic file renaming. Falling back to the old File.renameTo() method", e); } } if (moved == null || !Files.exists(moved)) { renamed = src.renameTo(dst); } else { renamed = true; } return renamed; } static boolean rmFileCacheDir(File path, ExtensionFileLister extfl); static void traverseDepth(final File path, final FileFilter filter); static boolean renameFile(File src, File dst); static String printFileTree(File dir); static File[] listFilesNullSafe(File layerPath, FileFilter filter); static File[] listFilesNullSafe(File directory); static File[] listFilesNullSafe(File layerPath, FilenameFilter tileFinder); }
@Test public void testFileRenaming() throws Exception { File source = temp.newFile("source.txt"); File destination = temp.newFile("dest" + System.currentTimeMillis() + ".txt"); boolean renameFile = FileUtils.renameFile(source, destination); assertTrue("FileUtils.renameFile returned false", renameFile); assertThat(source, not(FileMatchers.exists())); assertThat(destination, FileMatchers.exists()); } @Test public void testFileNotRenamed() throws Exception { File source = temp.newFile("source.txt"); File destination = temp.newFile("destination.txt"); source.delete(); boolean renameFile = FileUtils.renameFile(source, destination); assertFalse("FileUtils.renameFile returned true", renameFile); assertThat(log.getEntries(), hasItem(message(containsString("File.renameTo()")))); }
ImageMime extends MimeType { public ImageWriter getImageWriter(RenderedImage image) { Iterator<ImageWriter> it = javax.imageio.ImageIO.getImageWritersByFormatName(internalName); ImageWriter writer = it.next(); if (this.internalName.equals(ImageMime.png.internalName) || this.internalName.equals(ImageMime.png8.internalName)) { int bitDepth = image.getSampleModel().getSampleSize(0); if (bitDepth > 1 && bitDepth < 8 && writer.getClass().getName().equals(NATIVE_PNG_WRITER_CLASS_NAME)) { writer = it.next(); } } return writer; } private ImageMime( String mimeType, String fileExtension, String internalName, String format, boolean tiled, boolean alphaChannel, boolean alphaBit); boolean supportsAlphaBit(); boolean supportsAlphaChannel(); ImageWriter getImageWriter(RenderedImage image); RenderedImage preprocess(RenderedImage tile); static final String NATIVE_PNG_WRITER_CLASS_NAME; static final ImageMime png; static final ImageMime jpeg; static final ImageMime gif; static final ImageMime tiff; static final ImageMime png8; static final ImageMime png24; static final ImageMime png_24; static final ImageMime dds; static final ImageMime jpegPng; static final ImageMime jpegPng8; }
@Test public void test4BitPNG() throws IOException, URISyntaxException { URL url = this.getClass().getResource("/images/4bit.png"); RenderedImage tile = ImageIO.read(new File(url.toURI())); ImageWriter writer = ImageMime.png8.getImageWriter(tile); assertNotEquals( "Writer for this image should not be the native version.", writer.getClass().getName(), ImageMime.NATIVE_PNG_WRITER_CLASS_NAME); }
RegexParameterFilter extends CaseNormalizingParameterFilter { @Override public void setNormalize(CaseNormalizer normalize) { super.setNormalize(normalize); this.pat = compile(this.regex, getNormalize().getCase()); } RegexParameterFilter(); synchronized Matcher getMatcher(String value); @Override String apply(String str); @Override @Nullable List<String> getLegalValues(); @Override boolean applies(@Nullable String parameterValue); String getRegex(); void setRegex(@Nullable String regex); @Override void setNormalize(CaseNormalizer normalize); @Override RegexParameterFilter clone(); @Override List<String> getValues(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final String DEFAULT_EXPRESSION; }
@Test public void testToXMLDefaultNormalizer() throws Exception { filter.setNormalize(new CaseNormalizer()); XMLAssert.assertXMLEqual( "<regexParameterFilter>\n" + " <key>TEST</key>\n" + " <defaultValue>Default</defaultValue>\n" + " <normalize/>\n" + " <regex>foo|Bar|BAZ</regex>\n" + "</regexParameterFilter>", xs.toXML(filter)); } @Test public void testToXMLNoneNormalizer() throws Exception { filter.setNormalize(new CaseNormalizer(Case.NONE)); XMLAssert.assertXMLEqual( "<regexParameterFilter>\n" + " <key>TEST</key>\n" + " <defaultValue>Default</defaultValue>\n" + " <normalize>\n" + " <case>NONE</case>\n" + " </normalize>\n" + " <regex>foo|Bar|BAZ</regex>\n" + "</regexParameterFilter>", xs.toXML(filter)); } @Test public void testToXMLUpperCanadianEnglish() throws Exception { filter.setNormalize(new CaseNormalizer(Case.UPPER, Locale.CANADA)); XMLAssert.assertXMLEqual( "<regexParameterFilter>\n" + " <key>TEST</key>\n" + " <defaultValue>Default</defaultValue>\n" + " <normalize>\n" + " <case>UPPER</case>\n" + " <locale>en_CA</locale>\n" + " </normalize>\n" + " <regex>foo|Bar|BAZ</regex>\n" + "</regexParameterFilter>", xs.toXML(filter)); }
WMSGetCapabilities { String generateGetCapabilities(Charset encoding) { StringBuilder str = new StringBuilder(); XMLBuilder xml = new XMLBuilder(str); try { xml.header("1.0", encoding); xml.appendUnescaped( "<!DOCTYPE WMT_MS_Capabilities SYSTEM \"http: if (includeVendorSpecific) { xml.appendUnescaped("[\n"); xml.appendUnescaped("<!ELEMENT VendorSpecificCapabilities (TileSet*) >\n"); xml.appendUnescaped( "<!ELEMENT TileSet (SRS, BoundingBox?, Resolutions, Width, Height, Format, Layers*, Styles*) >\n"); xml.appendUnescaped("<!ELEMENT Resolutions (#PCDATA) >\n"); xml.appendUnescaped("<!ELEMENT Width (#PCDATA) >\n"); xml.appendUnescaped("<!ELEMENT Height (#PCDATA) >\n"); xml.appendUnescaped("<!ELEMENT Layers (#PCDATA) >\n"); xml.appendUnescaped("<!ELEMENT Styles (#PCDATA) >\n"); xml.appendUnescaped("]"); } xml.appendUnescaped(">\n"); xml.indentElement("WMT_MS_Capabilities").attribute("version", "1.1.1"); service(xml); capability(xml); xml.endElement(); } catch (IOException e) { throw new IllegalStateException(e); } return str.toString(); } protected WMSGetCapabilities( TileLayerDispatcher tld, HttpServletRequest servReq, String baseUrl, String contextPath, URLMangler urlMangler); }
@Test public void testEscapeXMLChars() throws Exception { TileLayerDispatcher tld = createMock(TileLayerDispatcher.class); HttpServletRequest servReq = createMock(HttpServletRequest.class); HttpServletResponse response = createMock(HttpServletResponse.class); String baseUrl = "http: String contextPath = "service/"; URLMangler urlMangler = new NullURLMangler(); ServiceInformation servInfo = createMock(ServiceInformation.class); Map<String, String[]> parameterMap = new HashMap<>(); parameterMap.put("SERVICE", new String[] {"WMS"}); parameterMap.put("VERSION", new String[] {"1.1.1"}); parameterMap.put("REQUEST", new String[] {"getcapabilities"}); parameterMap.put("TILED", new String[] {"true"}); expect(servReq.getParameterMap()).andStubReturn(Collections.unmodifiableMap(parameterMap)); expect(servReq.getCharacterEncoding()).andStubReturn("UTF-8"); expect(servInfo.getTitle()).andStubReturn("Title & \"stuff\""); expect(servInfo.getDescription()) .andStubReturn( "This \"description\" contains <characters> which & should be \'escaped\'."); expect(servInfo.getKeywords()).andStubReturn(null); expect(servInfo.getServiceProvider()).andStubReturn(null); expect(servInfo.getFees()).andStubReturn("NONE"); expect(servInfo.getAccessConstraints()).andStubReturn("NONE"); expect(tld.getServiceInformation()).andStubReturn(servInfo); StringParameterFilter stylesParameterFilter = new StringParameterFilter(); stylesParameterFilter.setKey("STYLES"); stylesParameterFilter.setValues(Arrays.asList("style1", "style2")); Map<String, GridSubset> subSets = new HashMap<>(); GridSubset gridSubSet = GridSubsetFactory.createGridSubSet( new GridSetBroker( Collections.singletonList(new DefaultGridsets(true, true))) .get("EPSG:4326")); subSets.put(gridSubSet.getName(), gridSubSet); WMSLayer advertisedLayer = new WMSLayer( "testAdv", null, "style,style2", null, null, subSets, Collections.singletonList(stylesParameterFilter), null, null, false, null); advertisedLayer.setEnabled(true); advertisedLayer.setAdvertised(true); LegendsRawInfo legendsRawInfo = new LegendsRawInfo(); legendsRawInfo.setDefaultWidth(50); legendsRawInfo.setDefaultHeight(100); legendsRawInfo.setDefaultFormat("image/png"); LegendRawInfo legendRawInfo1 = new LegendRawInfo(); legendRawInfo1.setStyle("style1"); legendRawInfo1.setUrl("htp: LegendRawInfo legendRawInfo2 = new LegendRawInfo(); legendRawInfo2.setStyle("style2"); legendRawInfo2.setUrl("htp: legendsRawInfo.addLegendRawInfo(legendRawInfo1); legendsRawInfo.addLegendRawInfo(legendRawInfo2); advertisedLayer.setLegends(legendsRawInfo); TileLayer unAdvertisedLayer = new WMSLayer( "testNotAdv", null, null, null, null, subSets, null, null, null, false, null); unAdvertisedLayer.setEnabled(true); unAdvertisedLayer.setAdvertised(false); expect(tld.getLayerList()).andStubReturn(Arrays.asList(advertisedLayer, unAdvertisedLayer)); replay(tld, servReq, response, servInfo); WMSGetCapabilities capabilities = new WMSGetCapabilities(tld, servReq, baseUrl, contextPath, urlMangler); String xml = capabilities.generateGetCapabilities(StandardCharsets.UTF_8); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); Document document = builder.parse(is); assertThat( document.getDocumentElement(), HasXPath.hasXPath( "/WMT_MS_Capabilities/Service/Title[text()='Title & \"stuff\"']")); assertThat( document.getDocumentElement(), HasXPath.hasXPath( "/WMT_MS_Capabilities/Service/Abstract[text()=" + xpathString( "This \"description\" contains <characters> which & should be \'escaped\'.") + "]")); assertThat(xml, not(containsString("& "))); assertThat(xml, not(containsString("<characters>"))); assertThat(xml, not(containsString("'escaped'"))); assertThat(xml, not(containsString("\"description\""))); assertThat(xml, containsString("testAdv")); assertThat(xml, not(containsString("testNotAdv"))); assertThat( document.getDocumentElement(), HasXPath.hasXPath( "/WMT_MS_Capabilities/Capability/VendorSpecificCapabilities/" + "TileSet[Layers='testAdv']/Styles[not(Style/Name)]")); assertThat( document.getDocumentElement(), HasXPath.hasXPath( "/WMT_MS_Capabilities/Capability/VendorSpecificCapabilities/" + "TileSet/Styles/Style[Name='style1']/LegendURL[@width='50'][@height='100'][Format='image/png']" + "/OnlineResource[@type='simple'][@href='htp: + "format=image/png&width=50&height=100&layer=testAdv&style=style1']")); assertThat( document.getDocumentElement(), HasXPath.hasXPath( "/WMT_MS_Capabilities/Capability/VendorSpecificCapabilities/" + "TileSet/Styles/Style[Name='style2']/LegendURL[@width='50'][@height='100'][Format='image/png']" + "/OnlineResource[@type='simple'][@href='htp: + "format=image/png&width=50&height=100&layer=testAdv&style=style2']")); EasyMock.verify(tld, servReq, response, servInfo); }
ParametersUtils { public static String getKvp(Map<String, String> parameters) { return parameters .entrySet() .stream() .sorted(derivedComparator(Entry::getKey)) .map(e -> String.join("=", encUTF8(e.getKey()), encUTF8(e.getValue()))) .collect(Collectors.joining("&")); } static String getLegacyParametersKvp(Map<String, String> parameters); static String getKvp(Map<String, String> parameters); static Map<String, String> getMap(String kvp); static String getId(Map<String, String> parameters); static String buildKey(String parametersKvp); }
@Test public void testEmptyToKVP() { String result = ParametersUtils.getKvp(Collections.emptyMap()); assertThat(result, isEmptyString()); } @Test public void testSingletonToKVP() { String result = ParametersUtils.getKvp(Collections.singletonMap("test", "blah")); assertThat(result, Matchers.equalTo("test=blah")); } @Test public void testTwoToKVP() { Map<String, String> parameters = new TreeMap<>(); parameters.put("test1", "blah1"); parameters.put("test2", "blah2"); String result = ParametersUtils.getKvp(parameters); assertThat(result, Matchers.equalTo("test1=blah1&test2=blah2")); } @Test public void testTwoToKVPSorting() { Map<String, String> parameters = new TreeMap<>( (s1, s2) -> -s1.compareTo(s2)); parameters.put("test1", "blah1"); parameters.put("test2", "blah2"); String result = ParametersUtils.getKvp(parameters); assertThat( result, Matchers.equalTo("test1=blah1&test2=blah2")); } @Test public void testEqualsToKVP() { Map<String, String> parameters = new TreeMap<>(); parameters.put("=test1", "=blah1"); parameters.put("te=st2", "bl=ah2"); parameters.put("test3=", "blah3="); String result = ParametersUtils.getKvp(parameters); assertThat( result, Matchers.equalTo("%3Dtest1=%3Dblah1&te%3Dst2=bl%3Dah2&test3%3D=blah3%3D")); } @Test public void testAmpToKVP() { Map<String, String> parameters = new TreeMap<>(); parameters.put("&test1", "&blah1"); parameters.put("te&st2", "bl&ah2"); parameters.put("test3&", "blah3&"); String result = ParametersUtils.getKvp(parameters); assertThat( result, Matchers.equalTo("%26test1=%26blah1&te%26st2=bl%26ah2&test3%26=blah3%26")); }
ParametersUtils { public static Map<String, String> getMap(String kvp) { return Arrays.stream(kvp.split("&")) .filter(((Predicate<String>) String::isEmpty).negate()) .map(pair -> pair.split("=", 2)) .collect(Collectors.toMap(p -> decUTF8(p[0]), p -> decUTF8(p[1]))); } static String getLegacyParametersKvp(Map<String, String> parameters); static String getKvp(Map<String, String> parameters); static Map<String, String> getMap(String kvp); static String getId(Map<String, String> parameters); static String buildKey(String parametersKvp); }
@Test public void testEmptyToMap() { Map<String, String> result = ParametersUtils.getMap(""); assertThat(result.entrySet(), empty()); } @Test public void testSingletonToMap() { Map<String, String> result = ParametersUtils.getMap("test=blah"); assertThat(result, hasEntries(entry(equalTo("test"), equalTo("blah")))); } @Test public void testTwoToMap() { Map<String, String> result = ParametersUtils.getMap("test1=blah1&test2=blah2"); assertThat( result, hasEntries( entry(equalTo("test1"), equalTo("blah1")), entry(equalTo("test2"), equalTo("blah2")))); } @Test public void testEqualsToMap() { Map<String, String> result = ParametersUtils.getMap("%3Dtest1=%3Dblah1&te%3Dst2=bl%3Dah2&test3%3D=blah3%3D"); assertThat( result, hasEntries( entry(equalTo("=test1"), equalTo("=blah1")), entry(equalTo("te=st2"), equalTo("bl=ah2")), entry(equalTo("test3="), equalTo("blah3=")))); } @Test public void testAmpToMap() { Map<String, String> result = ParametersUtils.getMap("%26test1=%26blah1&te%26st2=bl%26ah2&test3%26=blah3%26"); assertThat( result, hasEntries( entry(equalTo("&test1"), equalTo("&blah1")), entry(equalTo("te&st2"), equalTo("bl&ah2")), entry(equalTo("test3&"), equalTo("blah3&")))); }
WMSService extends Service { @Override public ConveyorTile getConveyor(HttpServletRequest request, HttpServletResponse response) throws GeoWebCacheException { final String encoding = request.getCharacterEncoding(); final Map requestParameterMap = request.getParameterMap(); String[] keys = {"layers", "request", "tiled", "cached", "metatiled", "width", "height"}; Map<String, String> values = ServletUtils.selectedStringsFromMap(requestParameterMap, encoding, keys); String layers = values.get("layers"); TileLayer tileLayer = null; if (layers != null) { tileLayer = tld.getTileLayer(layers); } String req = values.get("request"); if (req != null && !req.equalsIgnoreCase("getmap")) { if (layers == null || layers.length() == 0) { layers = ServletUtils.stringFromMap(requestParameterMap, encoding, "layer"); values.put("LAYERS", layers); if (layers != null) { tileLayer = tld.getTileLayer(layers); } } Map<String, String> filteringParameters = null; if (tileLayer != null) { filteringParameters = tileLayer.getModifiableParameters(requestParameterMap, encoding); } ConveyorTile tile = new ConveyorTile( sb, layers, null, null, ImageMime.png, filteringParameters, request, response); tile.setHint(req.toLowerCase()); tile.setRequestHandler(ConveyorTile.RequestHandler.SERVICE); return tile; } if (layers == null) { throw new ServiceException("Unable to parse layers parameter from request."); } final boolean tiled = Boolean.valueOf(values.get("tiled")); if (proxyNonTiledRequests && tiled) { ConveyorTile tile = new ConveyorTile(sb, layers, request, response); tile.setHint(req); tile.setRequestHandler(Conveyor.RequestHandler.SERVICE); return tile; } String[] paramKeys = {"format", "srs", "bbox"}; final Map<String, String> paramValues = ServletUtils.selectedStringsFromMap(requestParameterMap, encoding, paramKeys); final Map<String, String> fullParameters = tileLayer.getModifiableParameters(requestParameterMap, encoding); final MimeType mimeType; String format = paramValues.get("format"); try { mimeType = MimeType.createFromFormat(format); } catch (MimeException me) { throw new ServiceException("Unable to determine requested format, " + format); } final SRS srs; { String requestSrs = paramValues.get("srs"); if (requestSrs == null) { throw new ServiceException("No SRS specified"); } srs = SRS.getSRS(requestSrs); } final BoundingBox bbox; { String requestBbox = paramValues.get("bbox"); try { bbox = new BoundingBox(requestBbox); if (bbox == null || !bbox.isSane()) { throw new ServiceException( "The bounding box parameter (" + requestBbox + ") is missing or not sane"); } } catch (NumberFormatException nfe) { throw new ServiceException( "The bounding box parameter (" + requestBbox + ") is invalid"); } } final int tileWidth = Integer.parseInt(values.get("width")); final int tileHeight = Integer.parseInt(values.get("height")); final List<GridSubset> crsMatchingSubsets = tileLayer.getGridSubsetsForSRS(srs); if (crsMatchingSubsets.isEmpty()) { throw new ServiceException( "Unable to match requested SRS " + srs + " to those supported by layer"); } long[] tileIndexTarget = new long[3]; GridSubset gridSubset; { GridSubset bestMatch = findBestMatchingGrid( bbox, crsMatchingSubsets, tileWidth, tileHeight, tileIndexTarget); if (bestMatch == null) { gridSubset = crsMatchingSubsets.get(0); tileIndexTarget = null; } else { gridSubset = bestMatch; } } if (fullWMS) { long[] tileIndex = null; if (tileIndexTarget == null) { try { tileIndex = gridSubset.closestIndex(bbox); } catch (GridMismatchException gme) { } } else { tileIndex = tileIndexTarget; } if (tileIndex == null || gridSubset.getTileWidth() != tileWidth || gridSubset.getTileHeight() != tileHeight || !bbox.equals(gridSubset.boundsFromIndex(tileIndex), 0.02)) { log.debug("Recombinining tiles to respond to WMS request"); ConveyorTile tile = new ConveyorTile(sb, layers, request, response); tile.setHint("getmap"); tile.setRequestHandler(ConveyorTile.RequestHandler.SERVICE); return tile; } } long[] tileIndex = tileIndexTarget == null ? gridSubset.closestIndex(bbox) : tileIndexTarget; gridSubset.checkTileDimensions(tileWidth, tileHeight); return new ConveyorTile( sb, layers, gridSubset.getName(), tileIndex, mimeType, fullParameters, request, response); } protected WMSService(); WMSService(StorageBroker sb, TileLayerDispatcher tld, RuntimeStats stats); WMSService( StorageBroker sb, TileLayerDispatcher tld, RuntimeStats stats, URLMangler urlMangler, GeoWebCacheDispatcher controller); @Override ConveyorTile getConveyor(HttpServletRequest request, HttpServletResponse response); void handleRequest(Conveyor conv); void setFullWMS(String trueFalse); void setProxyRequests(String trueFalse); void setProxyNonTiledRequests(String trueFalse); void setHintsConfig(String hintsConfig); void setUtility(WMSUtilities utility); void setSecurityDispatcher(SecurityDispatcher securityDispatcher); static final String GEOWEBCACHE_WMS_PROXY_REQUEST_WHITELIST; static final String SERVICE_WMS; }
@Test public void testGetCap() throws Exception { GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); service = new WMSService(sb, tld, mock(RuntimeStats.class), new NullURLMangler(), gwcd); @SuppressWarnings("unchecked") Map<String, String[]> kvp = new CaseInsensitiveMap(); kvp.put("service", new String[] {"WMS"}); kvp.put("version", new String[] {"1.1.1"}); kvp.put("request", new String[] {"GetCapabilities"}); HttpServletRequest req = mock(HttpServletRequest.class); MockHttpServletResponse resp = new MockHttpServletResponse(); when(req.getCharacterEncoding()).thenReturn("UTF-8"); when(req.getParameterMap()).thenReturn(kvp); List<String> gridSetNames = Arrays.asList("GlobalCRS84Pixel", "GlobalCRS84Scale", "EPSG:4326"); TileLayer tileLayer = mockTileLayer("mockLayer", gridSetNames); when(tld.getLayerList()).thenReturn(Arrays.asList(tileLayer)); ConveyorTile conv = service.getConveyor(req, resp); assertNotNull(conv); final String layerName = conv.getLayerId(); assertNull(layerName); assertEquals(Conveyor.RequestHandler.SERVICE, conv.reqHandler); WMSGetCapabilities wmsCap = new WMSGetCapabilities( tld, conv.servletReq, "http: "/service/wms", new NullURLMangler()); wmsCap.writeResponse(conv.servletResp); assertTrue(resp.containsHeader("content-disposition")); assertEquals( "inline;filename=wms-getcapabilities.xml", resp.getHeader("content-disposition")); } @Test public void testGetCapEncoding() throws Exception { GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); service = new WMSService(sb, tld, mock(RuntimeStats.class), new NullURLMangler(), gwcd); @SuppressWarnings("unchecked") Map<String, String[]> kvp = new CaseInsensitiveMap(); kvp.put("service", new String[] {"WMS"}); kvp.put("version", new String[] {"1.1.1"}); kvp.put("request", new String[] {"GetCapabilities"}); HttpServletRequest req = mock(HttpServletRequest.class); MockHttpServletResponse resp = new MockHttpServletResponse(); when(req.getCharacterEncoding()).thenReturn("UTF-8"); when(req.getParameterMap()).thenReturn(kvp); List<String> gridSetNames = Arrays.asList("GlobalCRS84Pixel", "GlobalCRS84Scale", "EPSG:4326"); TileLayer tileLayer = mockTileLayer("möcklāyer😎", gridSetNames); when(tld.getLayerList()).thenReturn(Arrays.asList(tileLayer)); ConveyorTile conv = service.getConveyor(req, resp); assertNotNull(conv); assertEquals(Conveyor.RequestHandler.SERVICE, conv.reqHandler); WMSGetCapabilities wmsCap = new WMSGetCapabilities( tld, conv.servletReq, "http: "/service/wms", new NullURLMangler()); wmsCap.writeResponse(conv.servletResp); String capAsString = new String(resp.getContentAsByteArray(), StandardCharsets.UTF_8); assertThat(capAsString, Matchers.containsString("möcklāyer😎")); } @Test public void testGetConveyorWithParameters() throws Exception { GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); service = new WMSService(sb, tld, mock(RuntimeStats.class), new NullURLMangler(), gwcd); String layerName = "mockLayer"; String timeValue = "00:00"; @SuppressWarnings("unchecked") Map<String, String[]> kvp = new CaseInsensitiveMap(); kvp.put("service", new String[] {"WMS"}); kvp.put("version", new String[] {"1.1.1"}); kvp.put("request", new String[] {"GetFeatureInfo"}); kvp.put("layers", new String[] {layerName}); kvp.put("time", new String[] {timeValue}); List<String> mimeFormats = new ArrayList<String>(); mimeFormats.add("image/png"); List<ParameterFilter> parameterFilters = new ArrayList<ParameterFilter>(); RegexParameterFilter filter = new RegexParameterFilter(); filter.setKey("time"); filter.setRegex("\\d{2}:\\d{2}"); parameterFilters.add(filter); TileLayer tileLayer = new WMSLayer( layerName, null, null, layerName, mimeFormats, null, parameterFilters, null, null, true, null); when(tld.getTileLayer(layerName)).thenReturn(tileLayer); HttpServletRequest req = mock(HttpServletRequest.class); MockHttpServletResponse resp = new MockHttpServletResponse(); when(req.getCharacterEncoding()).thenReturn("UTF-8"); when(req.getParameterMap()).thenReturn(kvp); ConveyorTile conv = service.getConveyor(req, resp); assertNotNull(conv); assertEquals(Conveyor.RequestHandler.SERVICE, conv.reqHandler); assertNotNull(conv.getLayerId()); assertEquals(layerName, conv.getLayerId()); assertTrue(!conv.getFilteringParameters().isEmpty()); assertEquals(timeValue, conv.getFilteringParameters().get("TIME")); }
TruncateBboxRequest implements MassTruncateRequest { @Override public boolean doTruncate(StorageBroker sb, TileBreeder breeder) throws StorageException, GeoWebCacheException { final Set<Map<String, String>> allParams = sb.getCachedParameters(layerName); final TileLayer tileLayer = breeder.findTileLayer(layerName); final Collection<MimeType> allFormats = tileLayer.getMimeTypes(); final GridSubset subSet = tileLayer.getGridSubset(gridSetId); final int minZ = Optional.fromNullable(subSet.getMinCachedZoom()).or(subSet.getZoomStart()); final int maxZ = Optional.fromNullable(subSet.getMaxCachedZoom()).or(subSet.getZoomStop()); try { int taskCount = Stream.concat( allParams.stream(), Stream.of( (Map<String, String>) null)) .flatMap( params -> allFormats .stream() .map( format -> new SeedRequest( layerName, bounds, gridSetId, 1, minZ, maxZ, format.getMimeType(), GWCTask.TYPE.TRUNCATE, params))) .map( request -> { try { breeder.seed(layerName, request); return 1; } catch (GeoWebCacheException e) { throw new UncheckedGeoWebCacheException(e); } }) .reduce((x, y) -> x + y) .orElse(0); return taskCount > 0; } catch (UncheckedGeoWebCacheException e) { throw e.getCause(); } } TruncateBboxRequest(String layerName, BoundingBox bounds, String gridSetId); @Override boolean doTruncate(StorageBroker sb, TileBreeder breeder); }
@Test public void testDoTruncate() throws Exception { String layerName = "testLayer"; BoundingBox bbox = new BoundingBox(0.0, 1.0, 10.0, 11.0); String gridSetName = "testGridset"; TruncateBboxRequest request = new TruncateBboxRequest(layerName, bbox, gridSetName); StorageBroker broker = EasyMock.createMock("broker", StorageBroker.class); TileBreeder breeder = EasyMock.createMock("breeder", TileBreeder.class); TileLayer layer = EasyMock.createMock("layer", TileLayer.class); GridSubset subSet = EasyMock.createMock("subSet", GridSubset.class); GWCTask pngStyle1 = EasyMock.createMock("pngStyle1", GWCTask.class); GWCTask pngStyle2 = EasyMock.createMock("pngStyle2", GWCTask.class); GWCTask jpegStyle1 = EasyMock.createMock("jpegStyle1", GWCTask.class); GWCTask jpegStyle2 = EasyMock.createMock("jpegStyle2", GWCTask.class); final Set<Map<String, String>> allParams = new HashSet<>(); allParams.add(Collections.singletonMap("STYLES", "style1")); allParams.add(Collections.singletonMap("STYLES", "style2")); final long[][] coverages = new long[][] {{0, 0, 0, 0, 0}, {0, 0, 1, 1, 1}, {0, 0, 4, 4, 2}}; final int[] metaFactors = new int[] {1, 1}; EasyMock.expect(broker.getCachedParameters(layerName)) .andStubReturn(Collections.unmodifiableSet(allParams)); EasyMock.expect(breeder.findTileLayer(layerName)).andStubReturn(layer); EasyMock.expect(layer.getGridSubset(gridSetName)).andStubReturn(subSet); EasyMock.expect(layer.getMimeTypes()) .andStubReturn(Arrays.asList(ImageMime.png, ImageMime.jpeg)); EasyMock.expect(subSet.getMinCachedZoom()).andStubReturn(0); EasyMock.expect(subSet.getMaxCachedZoom()).andStubReturn(2); EasyMock.expect(subSet.getZoomStart()).andStubReturn(0); EasyMock.expect(subSet.getZoomStop()).andStubReturn(2); EasyMock.expect(subSet.getCoverageIntersections(bbox)).andStubReturn(coverages); EasyMock.expect(layer.getMetaTilingFactors()).andStubReturn(metaFactors); EasyMock.expect(subSet.expandToMetaFactors(coverages, metaFactors)) .andStubReturn(coverages); EasyMock.expect(layer.getName()).andStubReturn(layerName); breeder.seed( eq(layerName), seedRequest( layerName, gridSetName, "image/png", 0, 2, bbox, Collections.singletonMap("STYLES", "style1"))); EasyMock.expectLastCall().once(); breeder.seed( eq(layerName), seedRequest( layerName, gridSetName, "image/png", 0, 2, bbox, Collections.singletonMap("STYLES", "style2"))); EasyMock.expectLastCall().once(); breeder.seed( eq(layerName), seedRequest(layerName, gridSetName, "image/png", 0, 2, bbox, null)); EasyMock.expectLastCall().once(); breeder.seed( eq(layerName), seedRequest( layerName, gridSetName, "image/jpeg", 0, 2, bbox, Collections.singletonMap("STYLES", "style1"))); EasyMock.expectLastCall().once(); breeder.seed( eq(layerName), seedRequest( layerName, gridSetName, "image/jpeg", 0, 2, bbox, Collections.singletonMap("STYLES", "style2"))); EasyMock.expectLastCall().once(); breeder.seed( eq(layerName), seedRequest(layerName, gridSetName, "image/jpeg", 0, 2, bbox, null)); EasyMock.expectLastCall().once(); EasyMock.replay(broker, breeder, layer, subSet); EasyMock.replay(pngStyle1, pngStyle2, jpegStyle1, jpegStyle2); assertThat(request.doTruncate(broker, breeder), is(true)); EasyMock.verify(broker, breeder, layer, subSet); }
LegendInfoBuilder { public LegendInfoBuilder withUrl(String url) { this.url = url; return this; } LegendInfoBuilder withLayerName(String layerName); LegendInfoBuilder withLayerUrl(String layerUrl); LegendInfoBuilder withDefaultWidth(Integer defaultWidth); LegendInfoBuilder withDefaultHeight(Integer defaultHeight); LegendInfoBuilder withDefaultFormat(String defaultFormat); LegendInfoBuilder withStyleName(String styleName); LegendInfoBuilder withWidth(Integer width); LegendInfoBuilder withHeight(Integer height); LegendInfoBuilder withFormat(String format); LegendInfoBuilder withUrl(String url); LegendInfoBuilder withCompleteUrl(String completeUrl); LegendInfoBuilder withMinScale(Double minScale); LegendInfoBuilder withMaxScale(Double maxScale); LegendInfo build(); }
@Test public void testWithUrl() { LegendInfo legendInfo = new LegendInfoBuilder() .withLayerName("layer1") .withLayerUrl("http: .withDefaultWidth(50) .withDefaultHeight(100) .withDefaultFormat("image/png") .withStyleName("style1") .withWidth(150) .withHeight(200) .withFormat("image/gif") .withUrl("http: .build(); assertThat(legendInfo.getWidth(), is(150)); assertThat(legendInfo.getHeight(), is(200)); assertThat(legendInfo.getFormat(), is("image/gif")); assertThat(legendInfo.getStyleName(), is("style1")); assertThat( legendInfo.getLegendUrl(), is( "http: + "service=WMS&request=GetLegendGraphic&format=image/gif&width=150&height=200&layer=layer1&style=style1")); }
LegendInfoBuilder { public LegendInfoBuilder withCompleteUrl(String completeUrl) { this.completeUrl = completeUrl; return this; } LegendInfoBuilder withLayerName(String layerName); LegendInfoBuilder withLayerUrl(String layerUrl); LegendInfoBuilder withDefaultWidth(Integer defaultWidth); LegendInfoBuilder withDefaultHeight(Integer defaultHeight); LegendInfoBuilder withDefaultFormat(String defaultFormat); LegendInfoBuilder withStyleName(String styleName); LegendInfoBuilder withWidth(Integer width); LegendInfoBuilder withHeight(Integer height); LegendInfoBuilder withFormat(String format); LegendInfoBuilder withUrl(String url); LegendInfoBuilder withCompleteUrl(String completeUrl); LegendInfoBuilder withMinScale(Double minScale); LegendInfoBuilder withMaxScale(Double maxScale); LegendInfo build(); }
@Test public void testWithCompleteUrl() { LegendInfo legendInfo = new LegendInfoBuilder() .withLayerName("layer1") .withLayerUrl("http: .withDefaultWidth(50) .withDefaultHeight(100) .withDefaultFormat("image/png") .withStyleName("style1") .withWidth(150) .withHeight(200) .withFormat("image/gif") .withCompleteUrl("http: .build(); assertThat(legendInfo.getWidth(), is(150)); assertThat(legendInfo.getHeight(), is(200)); assertThat(legendInfo.getFormat(), is("image/gif")); assertThat(legendInfo.getStyleName(), is("style1")); assertThat(legendInfo.getLegendUrl(), is("http: }
ListenerCollection { public synchronized void safeForEach(HandlerMethod<Listener> method) throws GeoWebCacheException, IOException { LinkedList<Exception> exceptions = listeners .stream() .map( l -> { try { method.callOn(l); return Optional.<Exception>empty(); } catch (Exception ex) { return Optional.of(ex); } }) .filter(Optional::isPresent) .map(Optional::get) .collect( Collectors.collectingAndThen(Collectors.toList(), LinkedList::new)); if (!exceptions.isEmpty()) { Iterator<Exception> it = exceptions.descendingIterator(); Exception ex = it.next(); while (it.hasNext()) { ex.addSuppressed(it.next()); } if (ex instanceof GeoWebCacheException) { throw (GeoWebCacheException) ex; } else if (ex instanceof IOException) { throw (IOException) ex; } else { throw (RuntimeException) ex; } } } synchronized void add(Listener listener); synchronized void remove(Listener listener); synchronized void safeForEach(HandlerMethod<Listener> method); }
@Test public void testEmpty() throws Exception { ListenerCollection<Runnable> collection = new ListenerCollection<>(); collection.safeForEach( (x) -> { fail("should not be called"); }); }