src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
NettyRequestExecutor { @SuppressWarnings("unchecked") public CompletableFuture<Void> execute() { Promise<Channel> channelFuture = context.eventLoopGroup().next().newPromise(); executeFuture = createExecutionFuture(channelFuture); context.channelPool().acquire(channelFuture); channelFuture.addListener((GenericFutureList...
@Test public void cancelExecuteFuture_channelNotAcquired_failsAcquirePromise() { ArgumentCaptor<Promise> acquireCaptor = ArgumentCaptor.forClass(Promise.class); when(mockChannelPool.acquire(acquireCaptor.capture())).thenAnswer((Answer<Promise>) invocationOnMock -> { return invocationOnMock.getArgumentAt(0, Promise.clas...
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<Chann...
@Test public void release_openChannel_handlerShouldBeRemovedFromChannelPool() { assertHandlersNotRemoved(); handlerRemovingChannelPool.release(mockChannel); assertHandlersRemoved(); } @Test public void release_deregisteredOpenChannel_handlerShouldBeRemovedFromChannelPool() { mockChannel.deregister().awaitUninterruptibl...
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...
@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...
HealthCheckedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } HealthCheckedChannelPool(EventLoopGroup eventLoopGroup, NettyConfiguration configuration, SdkCha...
@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()).isE...
OneTimeReadTimeoutHandler extends ReadTimeoutHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ctx.pipeline().remove(this); super.channelRead(ctx, msg); } OneTimeReadTimeoutHandler(Duration timeout); @Override void channelRead(ChannelHandlerContext ctx, Object msg); ...
@Test public void channelRead_removesSelf() throws Exception { when(context.pipeline()).thenReturn(channelPipeline); handler.channelRead(context, object); verify(channelPipeline, times(1)).remove(eq(handler)); verify(context, times(1)).fireChannelRead(object); }
SharedSdkEventLoopGroup { @SdkTestInternalApi static synchronized int referenceCount() { return referenceCount; } private SharedSdkEventLoopGroup(); @SdkInternalApi static synchronized SdkEventLoopGroup get(); }
@Test public void referenceCountIsInitiallyZero() { assertThat(SharedSdkEventLoopGroup.referenceCount()).isEqualTo(0); }
SharedSdkEventLoopGroup { @SdkInternalApi public static synchronized SdkEventLoopGroup get() { if (sharedSdkEventLoopGroup == null) { sharedSdkEventLoopGroup = SdkEventLoopGroup.builder().build(); } referenceCount++; return SdkEventLoopGroup.create(new ReferenceCountingEventLoopGroup(sharedSdkEventLoopGroup.eventLoopGr...
@Test public void sharedEventLoopGroupIsDeallocatedWhenCountReachesZero() { DelegatingEventLoopGroup group1 = (DelegatingEventLoopGroup) SharedSdkEventLoopGroup.get().eventLoopGroup(); DelegatingEventLoopGroup group2 = (DelegatingEventLoopGroup) SharedSdkEventLoopGroup.get().eventLoopGroup(); assertThat(group1.getDeleg...
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).addLi...
@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.handlerAdd...
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()); retur...
@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(); } @...
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);...
@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); ...
BetterFixedChannelPool implements SdkChannelPool { public CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics) { CompletableFuture<Void> delegateMetricResult = delegateChannelPool.collectChannelPoolMetrics(metrics); CompletableFuture<Void> result = new CompletableFuture<>(); doInEventLoop(executor...
@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")); waitForC...
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...
@Test public void testGetOrCreateAttributeKey_calledTwiceWithSameName_returnsSameInstance() { String attr = "NettyUtilsTest.Foo"; AttributeKey<String> fooAttr = NettyUtils.getOrCreateAttributeKey(attr); assertThat(NettyUtils.getOrCreateAttributeKey(attr)).isSameAs(fooAttr); }
ChannelUtils { public static <T> Optional<T> getAttribute(Channel channel, AttributeKey<T> key) { return Optional.ofNullable(channel.attr(key)) .map(Attribute::get); } private ChannelUtils(); @SafeVarargs static void removeIfExists(ChannelPipeline pipeline, Class<? extends ChannelHandler>... handlers); static Optional...
@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_MULTIPLEXE...
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) { } } } } priv...
@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....
SocketChannelResolver { @SuppressWarnings("unchecked") public static ChannelFactory<? extends Channel> resolveSocketChannelFactory(EventLoopGroup eventLoopGroup) { if (eventLoopGroup instanceof DelegatingEventLoopGroup) { return resolveSocketChannelFactory(((DelegatingEventLoopGroup) eventLoopGroup).getDelegate()); } i...
@Test public void canDetectFactoryForStandardNioEventLoopGroup() { assertThat(resolveSocketChannelFactory(new NioEventLoopGroup()).newChannel()).isInstanceOf(NioSocketChannel.class); } @Test public void canDetectEpollEventLoopGroupFactory() { assumeTrue(Epoll.isAvailable()); assertThat(resolveSocketChannelFactory(new E...
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); sta...
@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(errorNotifie...
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 ExceptionH...
@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...
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(...
@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 goAwayWithChann...
Http2MultiplexedChannelPool implements SdkChannelPool { @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } Http2MultiplexedChannelPool(ChannelPool connectionPool, EventLoopGroup eventLoopGroup, Duration idleC...
@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 Http2MultiplexedCha...
Http2PingHandler extends SimpleChannelInboundHandler<Http2PingFrame> { @Override public void channelInactive(ChannelHandlerContext ctx) { stop(); ctx.fireChannelInactive(); } Http2PingHandler(int pingTimeoutMillis); @Override void handlerAdded(ChannelHandlerContext ctx); @Override void handlerRemoved(ChannelHandlerCont...
@Test public void channelInactive_shouldCancelTaskAndForwardToOtherHandlers() { EmbeddedChannel channel = createHttp2Channel(fastChecker); ChannelHandlerContext context = Mockito.mock(ChannelHandlerContext.class); fastChecker.channelInactive(context); Mockito.verify(context).fireChannelInactive(); channel.writeInbound(...
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).s...
@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(protocolCompl...
Http2SettingsFrameHandler extends SimpleChannelInboundHandler<Http2SettingsFrame> { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { channelError(cause, channel, ctx); } Http2SettingsFrameHandler(Channel channel, long clientMaxStreams, AtomicReference<ChannelPool> channelPoolRef); @Ov...
@Test public void exceptionCaught_shouldHandleErrorCloseChannel() throws Exception { Throwable cause = new Throwable(new RuntimeException("BOOM")); handler.exceptionCaught(context, cause); verifyChannelError(cause.getClass()); }
Http2SettingsFrameHandler extends SimpleChannelInboundHandler<Http2SettingsFrame> { @Override public void channelUnregistered(ChannelHandlerContext ctx) { if (!channel.attr(PROTOCOL_FUTURE).get().isDone()) { channelError(new IOException("The channel was closed before the protocol could be determined."), channel, ctx); ...
@Test public void channelUnregistered_ProtocolFutureNotDone_ShouldRaiseError() throws InterruptedException { handler.channelUnregistered(context); verifyChannelError(IOException.class); }
HttpToHttp2OutboundAdapter extends ChannelOutboundHandlerAdapter { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (!(msg instanceof HttpMessage || msg instanceof HttpContent)) { ctx.write(msg, promise); return; } boolean release = true; SimpleChannelPromiseAggregator pro...
@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(...
MultiplexedChannelRecord { boolean acquireStream(Promise<Channel> promise) { if (claimStream()) { releaseClaimOnFailure(promise); acquireClaimedStream(promise); return true; } return false; } MultiplexedChannelRecord(Channel connection, long maxConcurrencyPerConnection, Duration allowedIdleConnectionTime); Channel getC...
@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)...
HttpOrHttp2ChannelPool implements SdkChannelPool { @Override public void close() { doInEventLoop(eventLoop, this::close0); } HttpOrHttp2ChannelPool(ChannelPool delegatePool, EventLoopGroup group, int maxConcurrency, Ne...
@Test public void protocolConfigNotStarted_closeSucceeds() { httpOrHttp2ChannelPool.close(); } @Test public void protocolConfigNotStarted_closeClosesDelegatePool() throws InterruptedException { httpOrHttp2ChannelPool.close(); Thread.sleep(500); verify(mockDelegatePool).close(); }
Http2StreamExceptionHandler extends ChannelInboundHandlerAdapter { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (isIoError(cause) && ctx.channel().parent() != null) { Channel parent = ctx.channel().parent(); log.debug(() -> "An I/O error occurred on an Http2 stream, notifying t...
@Test public void timeoutException_shouldFireExceptionAndPropagateException() { when(streamChannel.parent()).thenReturn(embeddedParentChannel); handler.exceptionCaught(context, ReadTimeoutException.INSTANCE); assertThat(verifyExceptionHandler.exceptionCaught).isExactlyInstanceOf(Http2ConnectionTerminatingException.clas...
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.fireChannelR...
@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_shouldNotS...
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> ...
@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.runAllPending...
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.get...
@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 Atomi...
StaticKeyManagerFactorySpi extends KeyManagerFactorySpi { @Override protected KeyManager[] engineGetKeyManagers() { return keyManagers; } StaticKeyManagerFactorySpi(KeyManager[] keyManagers); }
@Test public void constructorCreatesArrayCopy() { KeyManager[] keyManagers = IntStream.range(0,8) .mapToObj(i -> mock(KeyManager.class)) .toArray(KeyManager[]::new); KeyManager[] arg = Arrays.copyOf(keyManagers, keyManagers.length); StaticKeyManagerFactorySpi spi = new StaticKeyManagerFactorySpi(arg); for (int i = 0; i...
StaticKeyManagerFactorySpi extends KeyManagerFactorySpi { @Override protected void engineInit(KeyStore ks, char[] password) { throw new UnsupportedOperationException("engineInit not supported by this KeyManagerFactory"); } StaticKeyManagerFactorySpi(KeyManager[] keyManagers); }
@Test(expected = UnsupportedOperationException.class) public void engineInit_storeAndPasswords_throws() { StaticKeyManagerFactorySpi staticKeyManagerFactorySpi = new StaticKeyManagerFactorySpi(new KeyManager[0]); staticKeyManagerFactorySpi.engineInit(null, null); } @Test(expected = UnsupportedOperationException.class) ...
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 ...
@Test public void testOtherHttpObjectRead_removesSelfFromPipeline() { HttpObject contentObject = mock(HttpContent.class); lastHttpContentSwallower.channelRead0(mockCtx, contentObject); verify(mockPipeline).remove(eq(lastHttpContentSwallower)); } @Test public void testLastHttpContentRead_removesSelfFromPipeline() { Last...
RequestAdapter { public HttpRequest adapt(SdkHttpRequest sdkRequest) { HttpMethod method = toNettyHttpMethod(sdkRequest.method()); HttpHeaders headers = new DefaultHttpHeaders(); String uri = encodedPathAndQueryParams(sdkRequest); DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, method, uri, he...
@Test public void adapt_h1Request_requestIsCorrect() { SdkHttpRequest request = SdkHttpRequest.builder() .uri(URI.create("http: .putRawQueryParameter("foo", "bar") .putRawQueryParameter("bar", "baz") .putHeader("header1", "header1val") .putHeader("header2", "header2val") .method(SdkHttpMethod.GET) .build(); HttpRequest...
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...
@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"), s3BucketR...
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(InetS...
@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); InetSocketAddr...
StaticKeyManagerFactory extends KeyManagerFactory { public static StaticKeyManagerFactory create(KeyManager[] keyManagers) { return new StaticKeyManagerFactory(keyManagers); } private StaticKeyManagerFactory(KeyManager[] keyManagers); static StaticKeyManagerFactory create(KeyManager[] keyManagers); }
@Test public void createReturnFactoryWithCorrectKeyManagers() { KeyManager[] keyManagers = IntStream.range(0,8) .mapToObj(i -> mock(KeyManager.class)) .toArray(KeyManager[]::new); StaticKeyManagerFactory staticKeyManagerFactory = StaticKeyManagerFactory.create(keyManagers); assertThat(staticKeyManagerFactory.getKeyMana...
SdkChannelOptions { public Map<ChannelOption, Object> channelOptions() { return Collections.unmodifiableMap(options); } SdkChannelOptions(); SdkChannelOptions putOption(ChannelOption<T> channelOption, T channelOptionValue); Map<ChannelOption, Object> channelOptions(); }
@Test public void defaultSdkSocketOptionPresent() { SdkChannelOptions channelOptions = new SdkChannelOptions(); Map<ChannelOption, Object> expectedOptions = new HashMap<>(); expectedOptions.put(ChannelOption.TCP_NODELAY, Boolean.TRUE); assertEquals(expectedOptions, channelOptions.channelOptions()); }
SdkEventLoopGroup { public static SdkEventLoopGroup create(EventLoopGroup eventLoopGroup, ChannelFactory<? extends Channel> channelFactory) { return new SdkEventLoopGroup(eventLoopGroup, channelFactory); } SdkEventLoopGroup(EventLoopGroup eventLoopGroup, ChannelFactory<? extends Channel> channelFactory); private SdkEv...
@Test(expected = IllegalArgumentException.class) public void notProvidingChannelFactory_unknownEventLoopGroup() { SdkEventLoopGroup.create(new DefaultEventLoopGroup()); }
ProxyConfiguration implements ToCopyableBuilder<ProxyConfiguration.Builder, ProxyConfiguration> { @Override public Builder toBuilder() { return new BuilderImpl(this); } private ProxyConfiguration(BuilderImpl builder); String scheme(); String host(); int port(); String username(); String password(); @Override boolean e...
@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 = allPropertiesSetCo...
CrtRequestExecutor { public CompletableFuture<Void> execute(CrtRequestContext executionContext) { CompletableFuture<Void> requestFuture = createExecutionFuture(executionContext.sdkRequest()); CompletableFuture<HttpClientConnection> httpClientConnectionCompletableFuture = executionContext.crtConnPool().acquireConnection...
@Test public void acquireConnectionThrowException_shouldInvokeOnError() { RuntimeException exception = new RuntimeException("error"); CrtRequestContext context = CrtRequestContext.builder() .crtConnPool(connectionManager) .request(AsyncExecuteRequest.builder() .responseHandler(responseHandler) .build()) .build(); Compl...
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> re...
@Test(expected = NullPointerException.class) public void buildWithMissingBucketName() { S3BucketResource.builder().build(); }
ApacheHttpClient implements SdkHttpClient { public static Builder builder() { return new DefaultBuilder(); } @SdkTestInternalApi ApacheHttpClient(ConnectionManagerAwareHttpClient httpClient, ApacheHttpRequestConfig requestConfig, AttributeMap resolvedOptions); private ApacheH...
@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(Illeg...
IdleConnectionReaper { public synchronized boolean registerConnectionManager(HttpClientConnectionManager manager, long maxIdleTime) { boolean notPreviouslyRegistered = connectionManagers.put(manager, maxIdleTime) == null; setupExecutorIfNecessary(); return notPreviouslyRegistered; } private IdleConnectionReaper(); @Sd...
@Test public void setsUpExecutorIfManagerNotPreviouslyRegistered() { idleConnectionReaper.registerConnectionManager(connectionManager, 1L); verify(executorService).execute(any(Runnable.class)); }
SdkTlsSocketFactory extends SSLConnectionSocketFactory { @Override protected final void prepareSocket(final SSLSocket socket) { String[] supported = socket.getSupportedProtocols(); String[] enabled = socket.getEnabledProtocols(); log.debug(() -> String.format("socket.getSupportedProtocols(): %s, socket.getEnabledProtoc...
@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[] getEn...
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, ConnPoo...
@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); ClientConn...
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> p...
@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(), co...
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(...
@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); ...
ProfileUseArnRegionProvider implements UseArnRegionProvider { public static ProfileUseArnRegionProvider create() { return new ProfileUseArnRegionProvider(ProfileFile::defaultProfileFile, ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow()); } private ProfileUseArnRegionProvider(Supplier<ProfileFile> profileFi...
@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 Strin...
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>"); }...
@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...
FileManager { List<File> getFiles(String layerName) { String[] pathBuilderCopy = getPathBuilderCopy(); if (replaceLayerName.first) pathBuilderCopy[replaceLayerName.second] = layerName; return getFiles(pathBuilderCopy); } FileManager( File rootDirectory, String pathTemplate, long rowRangeCount, long columnRa...
@Test public void testGetFilesByTileRange() throws Exception { String pathTemplate = Utils.buildPath("tiles", "{z}", "tiles-{x}-{y}.sqlite"); FileManager fileManager = new FileManager(getRootDirectory(), pathTemplate, 10, 10); File file1 = createFileInRootDir(Utils.buildPath("tiles", "5", "tiles-0-0.sqlite")); File fil...
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.getParamete...
@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[]...
SqliteBlobStore implements BlobStore { void replace(File newFile, String destination) { File destinationFile = new File(configuration.getRootDirectoryFile(), destination); connectionManager.replace(destinationFile, newFile); } protected SqliteBlobStore(SqliteInfo configuration, SqliteConnectionManager connectionManage...
@Test public void testFileReplaceOperation() throws Exception { File rootDirectoryA = Files.createTempDirectory("gwc-").toFile(); File rootDirectoryB = Files.createTempDirectory("gwc-").toFile(); addFilesToDelete(rootDirectoryA, rootDirectoryB); MbtilesInfo configurationA = getDefaultConfiguration(); configurationA.set...
MbtilesBlobStore extends SqliteBlobStore { @Override public boolean delete(TileObject tile) throws StorageException { File file = fileManager.getFile(tile); if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("Tile '%s' mapped to file '%s'.", tile, file)); } if (!file.exists()) { if (LOGGER.isDebugEnabled()) { LO...
@Test public void testDeleteLayerOperation() throws Exception { MbtilesInfo configuration = getDefaultConfiguration(); MbtilesBlobStore store = new MbtilesBlobStore(configuration); addStoresToClean(store); File asia1 = createFileInRootDir( Utils.buildPath("grid1", "asia", "image_png", "10", "tiles-0-500.sqlite")); File...
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(Mbtiles...
@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.sqli...
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 til...
@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....
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.normalize...
@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 ...
MbtilesBlobStore extends SqliteBlobStore { @Override public void put(TileObject tile) throws StorageException { File file = fileManager.getFile(tile); if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("Tile '%s' mapped to file '%s'.", tile, file)); } initDatabaseFileIfNeeded(file, tile.getLayerName(), tile.getB...
@Test public void testOpeningDatabaseFileWithMbtilesMetadata() throws Exception { File mbtilesMetadataDirectory = buildRootFile("mbtiles-metadata"); File mbtilesMetadataFile = new File(mbtilesMetadataDirectory, "europe_asia.properties"); String mbtilesMetadata = "attribution=some attribution" + System.lineSeparator() +...
WMSService extends Service { public void setSecurityDispatcher(SecurityDispatcher securityDispatcher) { this.securityDispatcher = securityDispatcher; } protected WMSService(); WMSService(StorageBroker sb, TileLayerDispatcher tld, RuntimeStats stats); WMSService( StorageBroker sb, TileLayerDis...
@Test public void testProxyRequestWhitelistWhenNoSecurityFilters() throws Exception { whitelistProperty.setValue("troz"); SecurityDispatcher secDisp = mock(SecurityDispatcher.class); when(secDisp.isSecurityEnabled()).thenReturn(false); GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServlet...
SwiftTile { public Payload getPayload() { Payload payload = new ByteArrayPayload(data); payload.setContentMetadata(getMetadata()); return payload; } SwiftTile(final TileObject tile); Payload getPayload(); void setExisted(long oldSize); void notifyListeners(BlobStoreListenerList listeners); String toString(); }
@Test public void testGetPayloadMetadataOutputLength() { Long testOutputLengthValue = 5L; ReflectionTestUtils.setField(swiftTile, "outputLength", testOutputLengthValue); Payload testPayload = swiftTile.getPayload(); assertEquals(testOutputLengthValue, testPayload.getContentMetadata().getContentLength()); } @Test public...
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( layerNam...
@Test public void testNotifyListenersWhenEmptyAndExisted() { ReflectionTestUtils.setField(swiftTile, "existed", true); swiftTile.notifyListeners(testListeners); checkListenersNotifications(0, 0); } @Test public void testNotifyListenersWhenEmptyAndNotExisted() { ReflectionTestUtils.setField(swiftTile, "existed", false);...
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 v...
@Test public void destroy() { this.swiftBlobStore.destroy(); try { verify(swiftApi, times(1)).close(); verify(blobStoreContext, times(1)).close(); } catch (IOException e) { fail(e.getMessage()); } }
SwiftBlobStore implements BlobStore { @Override public void addListener(BlobStoreListener listener) { listeners.addListener(listener); } SwiftBlobStore(SwiftBlobStoreInfo config, TileLayerDispatcher layers); @Override void destroy(); @Override void addListener(BlobStoreListener listener); @Override boolean removeListen...
@Test public void addListener() { assertTrue(testListeners.isEmpty()); BlobStoreListener swiftListener = mock(BlobStoreListener.class); this.swiftBlobStore.addListener(swiftListener); ArrayList<BlobStoreListener> blobStoreListenersResult = (ArrayList) testListeners.getListeners(); assertTrue(blobStoreListenersResult.co...
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 bool...
@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.remov...
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 l...
@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 (N...
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(...
@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 = mo...
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.dele...
@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 outco...
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; } SwiftBlob...
@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_L...
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 remo...
@Test public void clear() { try { this.swiftBlobStore.clear(); fail("This method should not work, it should throw a Unsupported Operation Exception"); } catch (UnsupportedOperationException e) { assertThat(e.getMessage(), is("clear() should not be called")); } }
SwiftBlobStore implements BlobStore { @Nullable @Override public String getLayerMetadata(String layerName, String key) { SwiftObject layer = this.objectApi.get(layerName); if (layer == null) { return null; } if (layer.getMetadata() == null) { return null; } else { return layer.getMetadata().get(key); } } SwiftBlobStore...
@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(swift...
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<>(); }...
@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)).t...
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 remove...
@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.layerExist...
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, S...
@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); Object...
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.delet...
@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.deleteByParame...
S3BlobStoreConfigProvider implements XMLConfigurationProvider { @Override public XStream getConfiguredXStream(XStream xs) { xs.alias("S3BlobStore", S3BlobStoreInfo.class); xs.registerLocalConverter( S3BlobStoreInfo.class, "maxConnections", EnvironmentNullableIntConverter); xs.registerLocalConverter( S3BlobStoreInfo.cla...
@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 S3BlobStoreI...
WMTSService extends Service { @Override public Conveyor getConveyor(HttpServletRequest request, HttpServletResponse response) throws GeoWebCacheException, OWSException { for (WMTSExtension extension : extensions) { Conveyor conveyor = extension.getConveyor(request, response, sb); if (conveyor != null) { return conveyor...
@Test public void testGetCap() throws Exception { GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); service = new WMTSService(sb, tld, null, mock(RuntimeStats.class)); @SuppressWarnings("unchecked") Map<String, String[]> kvp = new CaseInsensitiveMap(); kvp.p...
WMSTileFuser { protected void writeResponse(HttpServletResponse response, RuntimeStats stats) throws IOException, OutsideCoverageException, GeoWebCacheException, Exception { determineSourceResolution(); determineCanvasLayout(); createCanvas(); renderCanvas(); scaleRaster(); @SuppressWarnings("PMD.CloseResource") Accoun...
@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 =...
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.getRenameLayerSta...
@Test public void testRenameLayer() throws InterruptedException { assertEquals(16, countTileSetsByLayerName("topp:states")); store.renameLayer("topp:states", "states_renamed"); assertEquals(0, countTileSetsByLayerName("topp:states")); assertEquals(16, countTileSetsByLayerName("states_renamed")); }
JDBCQuotaStore implements QuotaStore { @Override public void deleteParameters(final String layerName, final String parametersId) { tt.execute( new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { Quota quota = getUsedQuotaByParametersId(parametersId)...
@Test public void testDeleteParameters() throws InterruptedException { String layerName = "topp:states"; TileSet tset1 = new TileSet(layerName, "EPSG:4326", "image/jpeg", paramIds[0]); addToQuotaStore(tset1); TileSet tset2 = new TileSet(layerName, "EPSG:4326", "image/jpeg", paramIds[1]); addToQuotaStore(tset2); Quota t...
JDBCQuotaStore implements QuotaStore { public void deleteLayer(final String layerName) { tt.execute( new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { deleteLayerInternal(layerName); } }); } JDBCQuotaStore(DefaultStorageFinder finder, TilePageCalc...
@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....
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(DefaultS...
@Test public void testGetTileSetById() throws Exception { TileSet tileSet = store.getTileSetById(testTileSet.getId()); assertNotNull(tileSet); assertEquals(testTileSet, tileSet); try { store.getTileSetById("NonExistentTileSetId"); fail("Expected IAE"); } catch (IllegalArgumentException e) { assertTrue(true); } }
JDBCQuotaStore implements QuotaStore { public Quota getUsedQuotaByLayerName(String layerName) { String sql = dialect.getUsedQuotaByLayerName(schema, "layerName"); return nonNullQuota( jt.queryForOptionalObject( sql, new DiskQuotaMapper(), Collections.singletonMap("layerName", layerName))); } JDBCQuotaStore(DefaultStora...
@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 = ne...
JDBCQuotaStore implements QuotaStore { public Quota getUsedQuotaByTileSetId(String tileSetId) { return nonNullQuota(getUsedQuotaByTileSetIdInternal(tileSetId)); } JDBCQuotaStore(DefaultStorageFinder finder, TilePageCalculator tilePageCalculator); SQLDialect getDialect(); void setDialect(SQLDialect dialect); String getS...
@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 ...
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 x...
@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 AzureB...
JDBCQuotaStore implements QuotaStore { public Quota getGloballyUsedQuota() throws InterruptedException { return nonNullQuota(getUsedQuotaByTileSetIdInternal(GLOBAL_QUOTA_NAME)); } JDBCQuotaStore(DefaultStorageFinder finder, TilePageCalculator tilePageCalculator); SQLDialect getDialect(); void setDialect(SQLDialect dial...
@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.getTileSets...
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); } PageStat...
@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.addToQuo...
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 dialec...
@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.g...
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...
@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 = tes...
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, TilePageCalculat...
@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 TilePa...
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...
@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(sourc...
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.internalNa...
@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...
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...
@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...
WMSGetCapabilities { String generateGetCapabilities(Charset encoding) { StringBuilder str = new StringBuilder(); XMLBuilder xml = new XMLBuilder(str); try { xml.header("1.0", encoding); xml.appendUnescaped( "<!DOCTYPE WMT_MS_Capabilities SYSTEM \"http: if (includeVendorSpecific) { xml.appendUnescaped("[\n"); xml.append...
@Test public void testEscapeXMLChars() throws Exception { TileLayerDispatcher tld = createMock(TileLayerDispatcher.class); HttpServletRequest servReq = createMock(HttpServletRequest.class); HttpServletResponse response = createMock(HttpServletResponse.class); String baseUrl = "http: String contextPath = "service/"; URL...
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,...
@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")); } @Tes...
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, S...
@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")))); } @T...
WMSService extends Service { @Override public ConveyorTile getConveyor(HttpServletRequest request, HttpServletResponse response) throws GeoWebCacheException { final String encoding = request.getCharacterEncoding(); final Map requestParameterMap = request.getParameterMap(); String[] keys = {"layers", "request", "tiled",...
@Test public void testGetCap() throws Exception { GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); service = new WMSService(sb, tld, mock(RuntimeStats.class), new NullURLMangler(), gwcd); @SuppressWarnings("unchecked") Map<String, String[]> kvp = new CaseIn...
TruncateBboxRequest implements MassTruncateRequest { @Override public boolean doTruncate(StorageBroker sb, TileBreeder breeder) throws StorageException, GeoWebCacheException { final Set<Map<String, String>> allParams = sb.getCachedParameters(layerName); final TileLayer tileLayer = breeder.findTileLayer(layerName); fina...
@Test public void testDoTruncate() throws Exception { String layerName = "testLayer"; BoundingBox bbox = new BoundingBox(0.0, 1.0, 10.0, 11.0); String gridSetName = "testGridset"; TruncateBboxRequest request = new TruncateBboxRequest(layerName, bbox, gridSetName); StorageBroker broker = EasyMock.createMock("broker", St...
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); Leg...
@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(); asser...
LegendInfoBuilder { public LegendInfoBuilder withCompleteUrl(String completeUrl) { this.completeUrl = completeUrl; return this; } LegendInfoBuilder withLayerName(String layerName); LegendInfoBuilder withLayerUrl(String layerUrl); LegendInfoBuilder withDefaultWidth(Integer defaultWidth); LegendInfoBuilder withDefaultHe...
@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:...
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); } }) .filt...
@Test public void testEmpty() throws Exception { ListenerCollection<Runnable> collection = new ListenerCollection<>(); collection.safeForEach( (x) -> { fail("should not be called"); }); }