method2testcases
stringlengths 118
6.63k
|
---|
### Question:
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); }### Answer:
@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(); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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); } |
### Question:
SharedSdkEventLoopGroup { @SdkTestInternalApi static synchronized int referenceCount() { return referenceCount; } private SharedSdkEventLoopGroup(); @SdkInternalApi static synchronized SdkEventLoopGroup get(); }### Answer:
@Test public void referenceCountIsInitiallyZero() { assertThat(SharedSdkEventLoopGroup.referenceCount()).isEqualTo(0); } |
### Question:
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(); }### Answer:
@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(); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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(); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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; }### Answer:
@Test public void testGetOrCreateAttributeKey_calledTwiceWithSameName_returnsSameInstance() { String attr = "NettyUtilsTest.Foo"; AttributeKey<String> fooAttr = NettyUtils.getOrCreateAttributeKey(attr); assertThat(NettyUtils.getOrCreateAttributeKey(attr)).isSameAs(fooAttr); } |
### Question:
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); }### Answer:
@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); } } |
### Question:
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); }### Answer:
@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); } } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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(); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@Test public void exceptionCaught_shouldHandleErrorCloseChannel() throws Exception { Throwable cause = new Throwable(new RuntimeException("BOOM")); handler.exceptionCaught(context, cause); verifyChannelError(cause.getClass()); } |
### Question:
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); }### Answer:
@Test public void channelUnregistered_ProtocolFutureNotDone_ShouldRaiseError() throws InterruptedException { handler.channelUnregistered(context); verifyChannelError(IOException.class); } |
### Question:
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); }### Answer:
@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(); } |
### Question:
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(); }### Answer:
@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(); } |
### Question:
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); }### Answer:
@Test public void protocolConfigNotStarted_closeSucceeds() { httpOrHttp2ChannelPool.close(); }
@Test public void protocolConfigNotStarted_closeClosesDelegatePool() throws InterruptedException { httpOrHttp2ChannelPool.close(); Thread.sleep(500); verify(mockDelegatePool).close(); } |
### Question:
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); }### Answer:
@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(); } |
### Question:
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(); }### Answer:
@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(); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
StaticKeyManagerFactorySpi extends KeyManagerFactorySpi { @Override protected KeyManager[] engineGetKeyManagers() { return keyManagers; } StaticKeyManagerFactorySpi(KeyManager[] keyManagers); }### Answer:
@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); } |
### Question:
StaticKeyManagerFactorySpi extends KeyManagerFactorySpi { @Override protected void engineInit(KeyStore ks, char[] password) { throw new UnsupportedOperationException("engineInit not supported by this KeyManagerFactory"); } StaticKeyManagerFactorySpi(KeyManager[] keyManagers); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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(); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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(); } |
### Question:
StaticKeyManagerFactory extends KeyManagerFactory { public static StaticKeyManagerFactory create(KeyManager[] keyManagers) { return new StaticKeyManagerFactory(keyManagers); } private StaticKeyManagerFactory(KeyManager[] keyManagers); static StaticKeyManagerFactory create(KeyManager[] keyManagers); }### Answer:
@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); } |
### Question:
SdkChannelOptions { public Map<ChannelOption, Object> channelOptions() { return Collections.unmodifiableMap(options); } SdkChannelOptions(); SdkChannelOptions putOption(ChannelOption<T> channelOption, T channelOptionValue); Map<ChannelOption, Object> channelOptions(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void notProvidingChannelFactory_unknownEventLoopGroup() { SdkEventLoopGroup.create(new DefaultEventLoopGroup()); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@Test(expected = NullPointerException.class) public void buildWithMissingBucketName() { S3BucketResource.builder().build(); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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(); }### Answer:
@Test public void setsUpExecutorIfManagerNotPreviouslyRegistered() { idleConnectionReaper.registerConnectionManager(connectionManager, 1L); verify(executorService).execute(any(Runnable.class)); } |
### Question:
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); }### Answer:
@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); } } |
### Question:
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); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@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"); } |
### Question:
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); }### Answer:
@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"))); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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); }### Answer:
@Test public void destroy() { this.swiftBlobStore.destroy(); try { verify(swiftApi, times(1)).close(); verify(blobStoreContext, times(1)).close(); } catch (IOException e) { fail(e.getMessage()); } } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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); } } |
### Question:
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); }### Answer:
@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(); } } |
### Question:
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); }### Answer:
@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); } } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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")); } } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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")); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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(); } } |
### Question:
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; }### Answer:
@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")); } |
### Question:
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; }### Answer:
@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()); } |
### Question:
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; }### Answer:
@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); } } |
### Question:
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; }### Answer:
@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()); } |
### Question:
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; }### Answer:
@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()); } } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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; }### Answer:
@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()); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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; }### Answer:
@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])); } |
### Question:
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); }### Answer:
@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()")))); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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; }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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")); } |
### Question:
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); }### Answer:
@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&")))); } |
### Question:
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(); }### Answer:
@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")); } |
### Question:
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(); }### Answer:
@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: } |
### Question:
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); }### Answer:
@Test public void testEmpty() throws Exception { ListenerCollection<Runnable> collection = new ListenerCollection<>(); collection.safeForEach( (x) -> { fail("should not be called"); }); } |
### Question:
ListenerCollection { public synchronized void remove(Listener listener) { listeners.remove(listener); } synchronized void add(Listener listener); synchronized void remove(Listener listener); synchronized void safeForEach(HandlerMethod<Listener> method); }### Answer:
@Test public void testRemove() throws Exception { ListenerCollection<Runnable> collection = new ListenerCollection<>(); IMocksControl control = EasyMock.createControl(); Runnable l1 = control.createMock("l1", Runnable.class); Runnable l2 = control.createMock("l2", Runnable.class); control.checkOrder(true); l2.run(); EasyMock.expectLastCall().once(); control.replay(); collection.add(l1); collection.add(l2); collection.remove(l1); collection.safeForEach(Runnable::run); control.verify(); } |
### Question:
XMLConfiguration implements TileLayerConfiguration,
InitializingBean,
DefaultingConfiguration,
ServerConfiguration,
BlobStoreConfiguration,
GridSetConfiguration { public boolean canSave(TileLayer tl) { if (tl.isTransientLayer()) { return false; } return canSaveIfNotTransient(tl); } XMLConfiguration(
final ApplicationContextProvider appCtx, final ConfigurationResourceProvider inFac); XMLConfiguration(
final ApplicationContextProvider appCtx,
final String configFileDirectory,
final DefaultStorageFinder storageDirFinder); XMLConfiguration(
final ApplicationContextProvider appCtx, final DefaultStorageFinder storageDirFinder); XMLConfiguration(
final ApplicationContextProvider appCtx, final String configFileDirectory); void setTemplate(String template); String getConfigLocation(); Boolean isRuntimeStatsEnabled(); void setRuntimeStatsEnabled(Boolean isEnabled); synchronized ServiceInformation getServiceInformation(); void setServiceInformation(ServiceInformation serviceInfo); @Override void setDefaultValues(TileLayer layer); XStream getConfiguredXStream(XStream xs); static XStream getConfiguredXStream(XStream xs, WebApplicationContext context); XStream getConfiguredXStreamWithContext(
XStream xs, ContextualConfigurationProvider.Context providerContext); static XStream getConfiguredXStreamWithContext(
XStream xs,
WebApplicationContext context,
ContextualConfigurationProvider.Context providerContext); boolean canSave(TileLayer tl); synchronized void addLayer(TileLayer tl); synchronized void modifyLayer(TileLayer tl); void renameLayer(String oldName, String newName); synchronized void removeLayer(final String layerName); void afterPropertiesSet(); String getIdentifier(); void setRelativePath(String relPath); void setAbsolutePath(String absPath); Collection<TileLayer> getLayers(); Optional<TileLayer> getLayer(String layerName); @Deprecated @Nullable TileLayer getTileLayer(String layerName); @Deprecated @Nullable TileLayer getTileLayerById(String layerId); boolean containsLayer(String layerId); int getLayerCount(); Set<String> getLayerNames(); String getVersion(); @Override Boolean isFullWMS(); @Override void setFullWMS(Boolean isFullWMS); @Override List<BlobStoreInfo> getBlobStores(); @Override synchronized void addBlobStore(BlobStoreInfo info); @Override synchronized void removeBlobStore(String name); @Override synchronized void modifyBlobStore(BlobStoreInfo info); @Override int getBlobStoreCount(); @Override Set<String> getBlobStoreNames(); @Override Optional<BlobStoreInfo> getBlobStore(String name); @Override boolean canSave(BlobStoreInfo info); @Override void renameBlobStore(String oldName, String newName); @Override boolean containsBlobStore(String name); @Override void addBlobStoreListener(BlobStoreConfigurationListener listener); @Override void removeBlobStoreListener(BlobStoreConfigurationListener listener); @Override LockProvider getLockProvider(); @Override void setLockProvider(LockProvider lockProvider); @Override Boolean isWmtsCiteCompliant(); void setWmtsCiteCompliant(Boolean wmtsCiteStrictCompliant); @Override Integer getBackendTimeout(); @Override void setBackendTimeout(Integer backendTimeout); @Override Boolean isCacheBypassAllowed(); @Override void setCacheBypassAllowed(Boolean cacheBypassAllowed); @Override String getLocation(); @Override synchronized void addGridSet(GridSet gridSet); @Override synchronized void removeGridSet(String gridSetName); @Override Optional<GridSet> getGridSet(String name); @Override Collection<GridSet> getGridSets(); @Override synchronized void modifyGridSet(GridSet gridSet); @Override void renameGridSet(String oldName, String newName); @Override boolean canSave(GridSet gridset); @Autowired @Override void setGridSetBroker(@Qualifier("gwcGridSetBroker") GridSetBroker broker); @Override void deinitialize(); static final String DEFAULT_CONFIGURATION_FILE_NAME; }### Answer:
@Test public void testNotAddLayer() throws Exception { TileLayer tl = mock(WMSLayer.class); when(tl.getName()).thenReturn("testLayer"); when(tl.isTransientLayer()).thenReturn(true); assertFalse(config.canSave(tl)); } |
### Question:
XMLConfiguration implements TileLayerConfiguration,
InitializingBean,
DefaultingConfiguration,
ServerConfiguration,
BlobStoreConfiguration,
GridSetConfiguration { @Override public List<BlobStoreInfo> getBlobStores() { return Collections.unmodifiableList( getGwcConfig() .getBlobStores() .stream() .map( (info) -> { return (BlobStoreInfo) info.clone(); }) .collect(Collectors.toList())); } XMLConfiguration(
final ApplicationContextProvider appCtx, final ConfigurationResourceProvider inFac); XMLConfiguration(
final ApplicationContextProvider appCtx,
final String configFileDirectory,
final DefaultStorageFinder storageDirFinder); XMLConfiguration(
final ApplicationContextProvider appCtx, final DefaultStorageFinder storageDirFinder); XMLConfiguration(
final ApplicationContextProvider appCtx, final String configFileDirectory); void setTemplate(String template); String getConfigLocation(); Boolean isRuntimeStatsEnabled(); void setRuntimeStatsEnabled(Boolean isEnabled); synchronized ServiceInformation getServiceInformation(); void setServiceInformation(ServiceInformation serviceInfo); @Override void setDefaultValues(TileLayer layer); XStream getConfiguredXStream(XStream xs); static XStream getConfiguredXStream(XStream xs, WebApplicationContext context); XStream getConfiguredXStreamWithContext(
XStream xs, ContextualConfigurationProvider.Context providerContext); static XStream getConfiguredXStreamWithContext(
XStream xs,
WebApplicationContext context,
ContextualConfigurationProvider.Context providerContext); boolean canSave(TileLayer tl); synchronized void addLayer(TileLayer tl); synchronized void modifyLayer(TileLayer tl); void renameLayer(String oldName, String newName); synchronized void removeLayer(final String layerName); void afterPropertiesSet(); String getIdentifier(); void setRelativePath(String relPath); void setAbsolutePath(String absPath); Collection<TileLayer> getLayers(); Optional<TileLayer> getLayer(String layerName); @Deprecated @Nullable TileLayer getTileLayer(String layerName); @Deprecated @Nullable TileLayer getTileLayerById(String layerId); boolean containsLayer(String layerId); int getLayerCount(); Set<String> getLayerNames(); String getVersion(); @Override Boolean isFullWMS(); @Override void setFullWMS(Boolean isFullWMS); @Override List<BlobStoreInfo> getBlobStores(); @Override synchronized void addBlobStore(BlobStoreInfo info); @Override synchronized void removeBlobStore(String name); @Override synchronized void modifyBlobStore(BlobStoreInfo info); @Override int getBlobStoreCount(); @Override Set<String> getBlobStoreNames(); @Override Optional<BlobStoreInfo> getBlobStore(String name); @Override boolean canSave(BlobStoreInfo info); @Override void renameBlobStore(String oldName, String newName); @Override boolean containsBlobStore(String name); @Override void addBlobStoreListener(BlobStoreConfigurationListener listener); @Override void removeBlobStoreListener(BlobStoreConfigurationListener listener); @Override LockProvider getLockProvider(); @Override void setLockProvider(LockProvider lockProvider); @Override Boolean isWmtsCiteCompliant(); void setWmtsCiteCompliant(Boolean wmtsCiteStrictCompliant); @Override Integer getBackendTimeout(); @Override void setBackendTimeout(Integer backendTimeout); @Override Boolean isCacheBypassAllowed(); @Override void setCacheBypassAllowed(Boolean cacheBypassAllowed); @Override String getLocation(); @Override synchronized void addGridSet(GridSet gridSet); @Override synchronized void removeGridSet(String gridSetName); @Override Optional<GridSet> getGridSet(String name); @Override Collection<GridSet> getGridSets(); @Override synchronized void modifyGridSet(GridSet gridSet); @Override void renameGridSet(String oldName, String newName); @Override boolean canSave(GridSet gridset); @Autowired @Override void setGridSetBroker(@Qualifier("gwcGridSetBroker") GridSetBroker broker); @Override void deinitialize(); static final String DEFAULT_CONFIGURATION_FILE_NAME; }### Answer:
@Test public void testNoBlobStores() throws Exception { assertNotNull(config.getBlobStores()); assertTrue(config.getBlobStores().isEmpty()); } |
### Question:
CompositeBlobStore implements BlobStore, BlobStoreConfigurationListener { public static StoreSuitabilityCheck getStoreSuitabilityCheck() { return storeSuitability.get(); } CompositeBlobStore(
TileLayerDispatcher layers,
DefaultStorageFinder defaultStorageFinder,
ServerConfiguration serverConfiguration,
BlobStoreAggregator blobStoreAggregator); static StoreSuitabilityCheck getStoreSuitabilityCheck(); @Override boolean delete(String layerName); @Override boolean deleteByGridsetId(String layerName, String gridSetId); @Override boolean delete(TileObject obj); @Override boolean delete(TileRange obj); @Override boolean get(TileObject obj); @Override void put(TileObject obj); @Deprecated @Override void clear(); @Override synchronized void destroy(); @Override void addListener(BlobStoreListener listener); @Override boolean removeListener(BlobStoreListener listener); @Override boolean rename(String oldLayerName, String newLayerName); @Override String getLayerMetadata(String layerName, String key); @Override void putLayerMetadata(String layerName, String key, String value); @Override boolean layerExists(String layerName); void setBlobStores(Iterable<? extends BlobStoreInfo> configs); @Override boolean deleteByParametersId(String layerName, String parametersId); @Override Set<Map<String, String>> getParameters(String layerName); @Override Set<String> getParameterIds(String layerName); Map<String, Optional<Map<String, String>>> getParametersMapping(String layerName); @Override void handleAddBlobStore(BlobStoreInfo newBlobStore); @Override void handleRemoveBlobStore(BlobStoreInfo removedBlobStore); @Override void handleModifyBlobStore(BlobStoreInfo modifiedBlobStore); @Override void handleRenameBlobStore(String oldName, BlobStoreInfo modifiedBlobStore); static void checkSuitability(String location, final boolean exists, boolean empty); static final String DEFAULT_STORE_DEFAULT_ID; }### Answer:
@Test public void testSuitabilityOnStartup() throws Exception { assertThat( CompositeBlobStore.getStoreSuitabilityCheck(), equalTo(CompositeBlobStore.StoreSuitabilityCheck.EXISTING)); final BlobStoreInfo info = mock(BlobStoreInfo.class); when(info.getName()).thenReturn("testStore"); when(info.isEnabled()).thenReturn(true); BlobStore subStore = mock(BlobStore.class); when(info.createInstance(Mockito.any(), Mockito.any())) .thenAnswer( invocation -> { assertThat( CompositeBlobStore.getStoreSuitabilityCheck(), equalTo(CompositeBlobStore.StoreSuitabilityCheck.NONE)); return subStore; }); configs.add(info); store = create(); verify(info).createInstance(Mockito.any(), Mockito.any()); assertThat( CompositeBlobStore.getStoreSuitabilityCheck(), equalTo(CompositeBlobStore.StoreSuitabilityCheck.EXISTING)); }
@Test public void testNonDefaultSuitabilityOnStartup() throws Exception { suitability.setValue(CompositeBlobStore.StoreSuitabilityCheck.EMPTY); assertThat( CompositeBlobStore.getStoreSuitabilityCheck(), equalTo(CompositeBlobStore.StoreSuitabilityCheck.EMPTY)); final BlobStoreInfo info = mock(BlobStoreInfo.class); when(info.getName()).thenReturn("testStore"); when(info.isEnabled()).thenReturn(true); BlobStore subStore = mock(BlobStore.class); when(info.createInstance(Mockito.any(), Mockito.any())) .thenAnswer( invocation -> { assertThat( CompositeBlobStore.getStoreSuitabilityCheck(), equalTo(CompositeBlobStore.StoreSuitabilityCheck.NONE)); return subStore; }); configs.add(info); store = create(); verify(info).createInstance(Mockito.any(), Mockito.any()); assertThat( CompositeBlobStore.getStoreSuitabilityCheck(), equalTo(CompositeBlobStore.StoreSuitabilityCheck.EMPTY)); } |
### Question:
GeoWebCacheExtensions implements ApplicationContextAware, ApplicationListener { @SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD") public void setApplicationContext(ApplicationContext context) throws BeansException { GeoWebCacheExtensions.context = context; extensionsCache.clear(); } @SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD") void setApplicationContext(ApplicationContext context); @SuppressWarnings("unchecked") static final List<T> extensions(
Class<T> extensionPoint, ApplicationContext context); static String[] getBeansNamesOrderedByPriority(Class<T> extensionType); static final List<T> extensions(Class<T> extensionPoint); static List<T> configurations(
Class<T> extensionPoint, ApplicationContext context); static List<T> configurations(Class<T> extensionPoint); static void reinitialize(ApplicationContext context); static final Object bean(String name); static final Object bean(String name, ApplicationContext context); static final T bean(Class<T> type); static final T bean(Class<T> type, ApplicationContext context); void onApplicationEvent(ApplicationEvent event); static String getProperty(String propertyName); static String getProperty(String propertyName, ApplicationContext context); static String getProperty(String propertyName, ServletContext context); }### Answer:
@Test public void testSetApplicationContext() { ApplicationContext appContext1 = createMock(ApplicationContext.class); ApplicationContext appContext2 = createMock(ApplicationContext.class); GeoWebCacheExtensions gse = new GeoWebCacheExtensions(); gse.setApplicationContext(appContext1); GeoWebCacheExtensions.extensionsCache.put( GeoWebCacheExtensionsTest.class, new String[] {"fake"}); assertSame(appContext1, GeoWebCacheExtensions.context); gse.setApplicationContext(appContext2); assertSame(appContext2, GeoWebCacheExtensions.context); assertEquals(0, GeoWebCacheExtensions.extensionsCache.size()); } |
### Question:
GeoWebCacheExtensions implements ApplicationContextAware, ApplicationListener { @SuppressWarnings("unchecked") public static final <T> List<T> extensions( Class<T> extensionPoint, ApplicationContext context) { String[] names; if (GeoWebCacheExtensions.context == context) { names = extensionsCache.get(extensionPoint); } else { names = null; } if (names == null) { checkContext(context); if (context != null) { try { names = getBeansNamesOrderedByPriority(extensionPoint, context); if (GeoWebCacheExtensions.context == context) { extensionsCache.put(extensionPoint, names); } } catch (Exception e) { LOGGER.error("bean lookup error", e); return Collections.emptyList(); } } else { return Collections.emptyList(); } } List<T> result = new ArrayList<T>(names.length); for (String name : names) { T bean = (T) context.getBean(name); result.add(bean); } return result; } @SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD") void setApplicationContext(ApplicationContext context); @SuppressWarnings("unchecked") static final List<T> extensions(
Class<T> extensionPoint, ApplicationContext context); static String[] getBeansNamesOrderedByPriority(Class<T> extensionType); static final List<T> extensions(Class<T> extensionPoint); static List<T> configurations(
Class<T> extensionPoint, ApplicationContext context); static List<T> configurations(Class<T> extensionPoint); static void reinitialize(ApplicationContext context); static final Object bean(String name); static final Object bean(String name, ApplicationContext context); static final T bean(Class<T> type); static final T bean(Class<T> type, ApplicationContext context); void onApplicationEvent(ApplicationEvent event); static String getProperty(String propertyName); static String getProperty(String propertyName, ApplicationContext context); static String getProperty(String propertyName, ServletContext context); }### Answer:
@Test public void testExtensions() { ApplicationContext appContext = createMock(ApplicationContext.class); GeoWebCacheExtensions gse = new GeoWebCacheExtensions(); gse.setApplicationContext(appContext); Map<String, GeoWebCacheExtensionsTest> beans = new HashMap<>(); beans.put("testKey", this); beans.put("fakeKey", null); assertEquals(0, GeoWebCacheExtensions.extensionsCache.size()); expect(appContext.getBeansOfType(GeoWebCacheExtensionsTest.class)).andReturn(beans); expect(appContext.getBean("testKey")).andReturn(this); expect(appContext.getBean("fakeKey")).andReturn(null); replay(appContext); List<GeoWebCacheExtensionsTest> extensions = GeoWebCacheExtensions.extensions(GeoWebCacheExtensionsTest.class); assertNotNull(extensions); assertEquals(2, extensions.size()); assertTrue(extensions.contains(this)); assertTrue(extensions.contains(null)); assertEquals(1, GeoWebCacheExtensions.extensionsCache.size()); assertTrue( GeoWebCacheExtensions.extensionsCache.containsKey(GeoWebCacheExtensionsTest.class)); assertNotNull(GeoWebCacheExtensions.extensionsCache.get(GeoWebCacheExtensionsTest.class)); assertEquals( 2, GeoWebCacheExtensions.extensionsCache.get(GeoWebCacheExtensionsTest.class).length); verify(appContext); } |
### Question:
GeoWebCacheExtensions implements ApplicationContextAware, ApplicationListener { public static String getProperty(String propertyName) { return getProperty(propertyName, context); } @SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD") void setApplicationContext(ApplicationContext context); @SuppressWarnings("unchecked") static final List<T> extensions(
Class<T> extensionPoint, ApplicationContext context); static String[] getBeansNamesOrderedByPriority(Class<T> extensionType); static final List<T> extensions(Class<T> extensionPoint); static List<T> configurations(
Class<T> extensionPoint, ApplicationContext context); static List<T> configurations(Class<T> extensionPoint); static void reinitialize(ApplicationContext context); static final Object bean(String name); static final Object bean(String name, ApplicationContext context); static final T bean(Class<T> type); static final T bean(Class<T> type, ApplicationContext context); void onApplicationEvent(ApplicationEvent event); static String getProperty(String propertyName); static String getProperty(String propertyName, ApplicationContext context); static String getProperty(String propertyName, ServletContext context); }### Answer:
@Test public void testSystemProperty() { testProperty.setValue("ABC"); assertEquals( "ABC", GeoWebCacheExtensions.getProperty("TEST_PROPERTY", (ApplicationContext) null)); assertEquals( "ABC", GeoWebCacheExtensions.getProperty("TEST_PROPERTY", (ServletContext) null)); }
@Test public void testWebProperty() { testProperty.setValue("ABC"); ServletContext servletContext = createMock(ServletContext.class); expect(servletContext.getInitParameter("TEST_PROPERTY")).andReturn("DEF").anyTimes(); expect(servletContext.getInitParameter("WEB_PROPERTY")).andReturn("WWW").anyTimes(); replay(servletContext); assertEquals("ABC", GeoWebCacheExtensions.getProperty("TEST_PROPERTY", servletContext)); assertEquals("WWW", GeoWebCacheExtensions.getProperty("WEB_PROPERTY", servletContext)); } |
### Question:
GridSetBroker implements ConfigurationAggregator<GridSetConfiguration>,
ApplicationContextAware,
InitializingBean { public @Nullable GridSet get(String gridSetId) { return getGridSet(gridSetId).orElse(null); } GridSetBroker(); GridSetBroker(List<GridSetConfiguration> configurations); void afterPropertiesSet(); @Nullable GridSet get(String gridSetId); Set<String> getEmbeddedNames(); Set<String> getNames(); Set<String> getGridSetNames(); Collection<GridSet> getGridSets(); synchronized void put(GridSet gridSet); void addGridSet(GridSet gridSet); synchronized GridSet remove(final String gridSetName); synchronized void removeGridSet(final String gridSetName); DefaultGridsets getDefaults(); GridSet getWorldEpsg4326(); GridSet getWorldEpsg3857(); @SuppressWarnings("unchecked") List<? extends GSC> getConfigurations(
Class<GSC> type); @Override void setApplicationContext(ApplicationContext applicationContext); }### Answer:
@Test public void testGetDefaultGridsetOld() throws IOException { GridSet existingGridSet = gridSetBroker.get(GWCConfigIntegrationTestData.GRIDSET_EPSG4326); assertThat( existingGridSet, hasProperty("name", equalTo(GWCConfigIntegrationTestData.GRIDSET_EPSG4326))); }
@Test public void testGetGridsetOld() throws IOException { GridSet existingGridSet = gridSetBroker.get(GWCConfigIntegrationTestData.GRIDSET_EPSG2163); assertThat( existingGridSet, hasProperty("name", equalTo(GWCConfigIntegrationTestData.GRIDSET_EPSG2163))); }
@Test public void testGetNotPresentGridsetOld() throws IOException { GridSet existingGridSet = gridSetBroker.get("DOESNOTEXIST"); assertThat(existingGridSet, nullValue()); } |
### Question:
GridSetBroker implements ConfigurationAggregator<GridSetConfiguration>,
ApplicationContextAware,
InitializingBean { protected Optional<GridSet> getGridSet(String name) { for (GridSetConfiguration c : getConfigurations()) { Optional<GridSet> gridSet = c.getGridSet(name); if (gridSet.isPresent()) { GridSet set = gridSet.get(); return Optional.of(set); } } return Optional.empty(); } GridSetBroker(); GridSetBroker(List<GridSetConfiguration> configurations); void afterPropertiesSet(); @Nullable GridSet get(String gridSetId); Set<String> getEmbeddedNames(); Set<String> getNames(); Set<String> getGridSetNames(); Collection<GridSet> getGridSets(); synchronized void put(GridSet gridSet); void addGridSet(GridSet gridSet); synchronized GridSet remove(final String gridSetName); synchronized void removeGridSet(final String gridSetName); DefaultGridsets getDefaults(); GridSet getWorldEpsg4326(); GridSet getWorldEpsg3857(); @SuppressWarnings("unchecked") List<? extends GSC> getConfigurations(
Class<GSC> type); @Override void setApplicationContext(ApplicationContext applicationContext); }### Answer:
@Test public void testGetDefaultGridSet() throws IOException { Optional<GridSet> existingGridSet = gridSetBroker.getGridSet(GWCConfigIntegrationTestData.GRIDSET_EPSG4326); assertThat( existingGridSet, isPresent( hasProperty( "name", equalTo(GWCConfigIntegrationTestData.GRIDSET_EPSG4326)))); }
@Test public void testGetGridSet() throws IOException { Optional<GridSet> existingGridSet = gridSetBroker.getGridSet(GWCConfigIntegrationTestData.GRIDSET_EPSG2163); assertThat( existingGridSet, isPresent( hasProperty( "name", equalTo(GWCConfigIntegrationTestData.GRIDSET_EPSG2163)))); }
@Test public void testGetNotPresentGridSet() throws IOException { Optional<GridSet> existingGridSet = gridSetBroker.getGridSet("DOESNOTEXIST"); assertThat(existingGridSet, notPresent()); } |
### Question:
GridSetBroker implements ConfigurationAggregator<GridSetConfiguration>,
ApplicationContextAware,
InitializingBean { public void addGridSet(GridSet gridSet) { log.debug("Adding " + gridSet.getName()); getConfigurations() .stream() .filter(c -> c.canSave(gridSet)) .findFirst() .orElseThrow( () -> new UnsupportedOperationException( "No Configuration is able to save gridset " + gridSet.getName())) .addGridSet(gridSet); } GridSetBroker(); GridSetBroker(List<GridSetConfiguration> configurations); void afterPropertiesSet(); @Nullable GridSet get(String gridSetId); Set<String> getEmbeddedNames(); Set<String> getNames(); Set<String> getGridSetNames(); Collection<GridSet> getGridSets(); synchronized void put(GridSet gridSet); void addGridSet(GridSet gridSet); synchronized GridSet remove(final String gridSetName); synchronized void removeGridSet(final String gridSetName); DefaultGridsets getDefaults(); GridSet getWorldEpsg4326(); GridSet getWorldEpsg3857(); @SuppressWarnings("unchecked") List<? extends GSC> getConfigurations(
Class<GSC> type); @Override void setApplicationContext(ApplicationContext applicationContext); }### Answer:
@Test public void testAddGridset() throws GeoWebCacheException, IOException { String gridsetName = "EPSG:3005"; GridSet epsg3005 = GridSetFactory.createGridSet( gridsetName, SRS.getSRS(gridsetName), new BoundingBox(35043.6538, 440006.8768, 1885895.3117, 1735643.8497), false, null, new double[] {25000000, 1250000, 500000, 250000}, null, GridSetFactory.DEFAULT_PIXEL_SIZE_METER, null, 256, 256, false); gridSetBroker.addGridSet(epsg3005); assertTrue(gridSetBroker.getNames().contains(gridsetName)); assertEquals(gridSetBroker.get(gridsetName), epsg3005); } |
### Question:
GridSetBroker implements ConfigurationAggregator<GridSetConfiguration>,
ApplicationContextAware,
InitializingBean { public synchronized void removeGridSet(final String gridSetName) { getConfigurations() .stream() .filter(c -> c.getGridSet(gridSetName).isPresent()) .forEach( c -> { c.removeGridSet(gridSetName); }); } GridSetBroker(); GridSetBroker(List<GridSetConfiguration> configurations); void afterPropertiesSet(); @Nullable GridSet get(String gridSetId); Set<String> getEmbeddedNames(); Set<String> getNames(); Set<String> getGridSetNames(); Collection<GridSet> getGridSets(); synchronized void put(GridSet gridSet); void addGridSet(GridSet gridSet); synchronized GridSet remove(final String gridSetName); synchronized void removeGridSet(final String gridSetName); DefaultGridsets getDefaults(); GridSet getWorldEpsg4326(); GridSet getWorldEpsg3857(); @SuppressWarnings("unchecked") List<? extends GSC> getConfigurations(
Class<GSC> type); @Override void setApplicationContext(ApplicationContext applicationContext); }### Answer:
@Test public void testRemoveGridset() throws IOException { String gridsetToRemove = GWCConfigIntegrationTestData.GRIDSET_EPSG2163; gridSetBroker.removeGridSet(gridsetToRemove); assertThat(gridSetBroker.getGridSetNames(), not(hasItem(gridsetToRemove))); assertThat(gridSetBroker.getGridSet(gridsetToRemove), notPresent()); } |
### Question:
GridSubset { public long[][] getCoverageIntersections(BoundingBox reqBounds) { final int zoomStart = getZoomStart(); final int zoomStop = getZoomStop(); long[][] ret = new long[1 + zoomStop - zoomStart][5]; for (int level = zoomStart; level <= zoomStop; level++) { ret[level - zoomStart] = getCoverageIntersection(level, reqBounds); } return ret; } protected GridSubset(
GridSet gridSet,
Map<Integer, GridCoverage> coverages,
BoundingBox originalExtent,
boolean fullCoverage); GridSubset(
GridSet gridSet,
Map<Integer, GridCoverage> coverages,
BoundingBox originalExtent,
boolean fullCoverage,
Integer minCachedZoom,
Integer maxCachedZoom); GridSubset(GridSubset subSet); BoundingBox boundsFromIndex(long[] tileIndex); BoundingBox boundsFromRectangle(long[] rectangleExtent); long[] closestIndex(BoundingBox tileBounds); long[] closestRectangle(BoundingBox rectangleBounds); boolean covers(long[] index); void checkCoverage(long[] index); void checkTileDimensions(int width, int height); long[][] expandToMetaFactors(final long[][] coverages, final int[] metaFactors); long[] getCoverage(int level); long[][] getCoverages(); double getDotsPerInch(); BoundingBox getCoverageBounds(int level); long[] getCoverageBestFit(); BoundingBox getCoverageBestFitBounds(); long[] getCoverageIntersection(long[] reqRectangle); long[][] getCoverageIntersections(BoundingBox reqBounds); long[] getCoverageIntersection(int level, BoundingBox reqBounds); long getGridIndex(String gridId); String[] getGridNames(); GridSet getGridSet(); BoundingBox getGridSetBounds(); long getNumTilesWide(int zoomLevel); long getNumTilesHigh(int zoomLevel); String getName(); BoundingBox getOriginalExtent(); double[] getResolutions(); long[][] getSubGrid(long[] gridLoc); boolean getScaleWarning(); SRS getSRS(); int getTileHeight(); int getTileWidth(); long[][] getWMTSCoverages(); int getZoomStart(); int getZoomStop(); Integer getMinCachedZoom(); Integer getMaxCachedZoom(); boolean fullGridSetCoverage(); boolean shouldCacheAtZoom(long zoom); @Override String toString(); }### Answer:
@Test public void testCreateTileRange() throws IOException, GeoWebCacheException { WMSLayer tl = createWMSLayer(); String gridSet = tl.getGridSubsets().iterator().next(); GridSubset gridSubSet = tl.getGridSubset(gridSet); BoundingBox bounds = new BoundingBox(0d, 0d, 1d, 1d); long[][] result = gridSubSet.getCoverageIntersections(bounds); assertNotNull(result); } |
### Question:
GridSet implements Info { public BoundingBox boundsFromIndex(long[] tileIndex) { final int tileZ = (int) tileIndex[2]; Grid grid = getGrid(tileZ); final long tileX = tileIndex[0]; final long tileY; if (yBaseToggle) { tileY = tileIndex[1] - grid.getNumTilesHigh(); } else { tileY = tileIndex[1]; } double width = grid.getResolution() * getTileWidth(); double height = grid.getResolution() * getTileHeight(); final double[] tileOrigin = tileOrigin(); BoundingBox tileBounds = new BoundingBox( tileOrigin[0] + width * tileX, tileOrigin[1] + height * (tileY), tileOrigin[0] + width * (tileX + 1), tileOrigin[1] + height * (tileY + 1)); return tileBounds; } protected GridSet(); GridSet(GridSet g); BoundingBox getOriginalExtent(); boolean isResolutionsPreserved(); BoundingBox boundsFromIndex(long[] tileIndex); long[] closestRectangle(BoundingBox rectangleBounds); @Override boolean equals(Object obj); @Override int hashCode(); BoundingBox getBounds(); double[] getOrderedTopLeftCorner(int gridIndex); String guessMapUnits(); boolean isTopLeftAligned(); int getNumLevels(); Grid getGrid(final int zLevel); void setGrid(final int zLevel, final Grid grid); double[] tileOrigin(); boolean isyCoordinateFirst(); boolean isScaleWarning(); double getMetersPerUnit(); double getPixelSize(); String getName(); String getDescription(); void setDescription(String description); SRS getSrs(); int getTileWidth(); int getTileHeight(); boolean shouldTruncateIfChanged(final GridSet another); @Override String toString(); }### Answer:
@Test public void testBoundsFromIndex() throws Exception { long[] index = {0, 0, 1}; BoundingBox bboxTL = gridSetTL.boundsFromIndex(index); BoundingBox bboxBL = gridSetBL.boundsFromIndex(index); BoundingBox bboxTLswap = gridSetTLswap.boundsFromIndex(index); BoundingBox bboxBLswap = gridSetBLswap.boundsFromIndex(index); BoundingBox solution = new BoundingBox(-180.0, -90.0, -90.0, 0); assertThat(bboxTL, closeTo(solution, 0.00000001)); assertThat(bboxBL, closeTo(solution, 0.00000001)); assertThat(bboxTLswap, closeTo(solution, 0.00000001)); assertThat(bboxBLswap, closeTo(solution, 0.00000001)); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.