index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/karyon/karyon2-examples/src/main/java/netflix/karyon/examples/hellonoss
Create_ds/karyon/karyon2-examples/src/main/java/netflix/karyon/examples/hellonoss/common/LoggingInterceptor.java
package netflix.karyon.examples.hellonoss.common; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import netflix.karyon.transport.interceptor.DuplexInterceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; /** * @author Nitesh Kant */ public class LoggingInterceptor implements DuplexInterceptor<HttpServerRequest<ByteBuf>, HttpServerResponse<ByteBuf>> { private static final Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class); private static int count; private final int id; public LoggingInterceptor() { id = ++count; } @Override public Observable<Void> in(HttpServerRequest<ByteBuf> request, HttpServerResponse<ByteBuf> response) { logger.info("Logging interceptor with id {} invoked for direction IN.", id); return Observable.empty(); } @Override public Observable<Void> out(HttpServerResponse<ByteBuf> response) { logger.info("Logging interceptor with id {} invoked for direction OUT.", id); return Observable.empty(); } }
3,200
0
Create_ds/karyon/karyon2-examples/src/main/java/netflix/karyon/examples/hellonoss/common
Create_ds/karyon/karyon2-examples/src/main/java/netflix/karyon/examples/hellonoss/common/auth/AuthInterceptor.java
package netflix.karyon.examples.hellonoss.common.auth; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import netflix.karyon.transport.interceptor.InboundInterceptor; import rx.Observable; import rx.functions.Func1; import javax.inject.Inject; /** * @author Nitesh Kant */ public class AuthInterceptor implements InboundInterceptor<HttpServerRequest<ByteBuf>, HttpServerResponse<ByteBuf>> { private final AuthenticationService authService; @Inject public AuthInterceptor(AuthenticationService authService) { this.authService = authService; } @Override public Observable<Void> in(HttpServerRequest<ByteBuf> request, HttpServerResponse<ByteBuf> response) { return authService.authenticate(request).map(new Func1<Boolean, Void>() { @Override public Void call(Boolean aBoolean) { return null; } }); } }
3,201
0
Create_ds/karyon/karyon2-examples/src/main/java/netflix/karyon/examples/hellonoss/common
Create_ds/karyon/karyon2-examples/src/main/java/netflix/karyon/examples/hellonoss/common/auth/AuthenticationService.java
package netflix.karyon.examples.hellonoss.common.auth; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import rx.Observable; /** * @author Nitesh Kant */ public interface AuthenticationService { Observable<Boolean> authenticate(HttpServerRequest<ByteBuf> request); }
3,202
0
Create_ds/karyon/karyon2-examples/src/main/java/netflix/karyon/examples/hellonoss/common
Create_ds/karyon/karyon2-examples/src/main/java/netflix/karyon/examples/hellonoss/common/auth/AuthenticationServiceImpl.java
package netflix.karyon.examples.hellonoss.common.auth; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import rx.Observable; /** * @author Nitesh Kant */ public class AuthenticationServiceImpl implements AuthenticationService { public static final String AUTH_HEADER_NAME = "MY-USER-ID"; @Override public Observable<Boolean> authenticate(HttpServerRequest<ByteBuf> request) { if (request.getHeaders().contains(AUTH_HEADER_NAME)) { return Observable.just(Boolean.TRUE); } else { return Observable.error(new IllegalArgumentException("Should pass a header: " + AUTH_HEADER_NAME)); } } }
3,203
0
Create_ds/karyon/karyon2-examples/src/main/java/netflix/karyon/examples/hellonoss/common
Create_ds/karyon/karyon2-examples/src/main/java/netflix/karyon/examples/hellonoss/common/health/HealthCheck.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package netflix.karyon.examples.hellonoss.common.health; import com.google.inject.Singleton; import netflix.karyon.health.HealthCheckHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; /** * @author Nitesh Kant (nkant@netflix.com) */ @Singleton public class HealthCheck implements HealthCheckHandler { private static final Logger logger = LoggerFactory.getLogger(HealthCheck.class); @PostConstruct public void init() { logger.info("Health check initialized."); } @Override public int getStatus() { // TODO: Health check logic. logger.info("Health check invoked."); return 200; } }
3,204
0
Create_ds/karyon/karyon2-examples/src/main/java/netflix/karyon/examples
Create_ds/karyon/karyon2-examples/src/main/java/netflix/karyon/examples/websockets/WebSocketEchoServer.java
package netflix.karyon.examples.websockets; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketFrame; import io.reactivex.netty.RxNetty; import io.reactivex.netty.channel.ConnectionHandler; import io.reactivex.netty.channel.ObservableConnection; import io.reactivex.netty.server.RxServer; import netflix.adminresources.resources.KaryonWebAdminModule; import netflix.karyon.Karyon; import netflix.karyon.KaryonBootstrapModule; import netflix.karyon.ShutdownModule; import netflix.karyon.archaius.ArchaiusBootstrapModule; import netflix.karyon.servo.KaryonServoModule; import rx.Observable; import rx.functions.Func1; /** * Simple WebSockets echo server. * * @author Tomasz Bak */ public final class WebSocketEchoServer { public static void main(final String[] args) { RxServer<TextWebSocketFrame, TextWebSocketFrame> webSocketServer = RxNetty.newWebSocketServerBuilder( 8888, new ConnectionHandler<TextWebSocketFrame, TextWebSocketFrame>() { @Override public Observable<Void> handle(final ObservableConnection<TextWebSocketFrame, TextWebSocketFrame> connection) { return connection.getInput().flatMap(new Func1<WebSocketFrame, Observable<Void>>() { @Override public Observable<Void> call(WebSocketFrame wsFrame) { TextWebSocketFrame textFrame = (TextWebSocketFrame) wsFrame; System.out.println("Got message: " + textFrame.text()); return connection.writeAndFlush(new TextWebSocketFrame(textFrame.text().toUpperCase())); } }); } } ).build(); Karyon.forWebSocketServer( webSocketServer, new KaryonBootstrapModule(), new ArchaiusBootstrapModule("websocket-echo-server"), // KaryonEurekaModule.asBootstrapModule(), /* Uncomment if you need eureka */ Karyon.toBootstrapModule(KaryonWebAdminModule.class), ShutdownModule.asBootstrapModule(), KaryonServoModule.asBootstrapModule()) .startAndWaitTillShutdown(); } }
3,205
0
Create_ds/karyon/karyon2-examples/src/main/java/netflix/karyon/examples
Create_ds/karyon/karyon2-examples/src/main/java/netflix/karyon/examples/tcp/TcpPipelineApp.java
package netflix.karyon.examples.tcp; import com.google.inject.AbstractModule; import com.netflix.governator.annotations.Modules; import io.netty.buffer.ByteBuf; import netflix.adminresources.resources.KaryonWebAdminModule; import netflix.karyon.KaryonBootstrap; import netflix.karyon.ShutdownModule; import netflix.karyon.archaius.ArchaiusBootstrap; import netflix.karyon.examples.tcp.TcpPipelineApp.ApplicationModule; import netflix.karyon.examples.tcp.TcpPipelineApp.TcpBackendModule; import netflix.karyon.examples.tcp.TcpPipelineApp.TcpFrontendModule; import netflix.karyon.transport.tcp.KaryonTcpModule; /** * @author Tomasz Bak */ @ArchaiusBootstrap @KaryonBootstrap(name = "sample-rxnetty-tcp-noss") @Modules(include = { ShutdownModule.class, KaryonWebAdminModule.class, // KaryonEurekaModule.class, // Uncomment this to enable Eureka client. ApplicationModule.class, TcpFrontendModule.class, TcpBackendModule.class }) public interface TcpPipelineApp { class ApplicationModule extends AbstractModule { @Override protected void configure() { bind(TcpPipelineHandlers.QueueProvider.class).asEagerSingleton(); } } class TcpFrontendModule extends KaryonTcpModule<ByteBuf, ByteBuf> { public TcpFrontendModule() { super("tcpFrontServer", ByteBuf.class, ByteBuf.class); } @Override protected void configureServer() { bindConnectionHandler().to(TcpPipelineHandlers.FrontendConnectionHandler.class); server().port(7770); } } class TcpBackendModule extends KaryonTcpModule<ByteBuf, ByteBuf> { public TcpBackendModule() { super("tcpBackendServer", ByteBuf.class, ByteBuf.class); } @Override protected void configureServer() { bindConnectionHandler().to(TcpPipelineHandlers.BackendConnectionHandler.class); server().port(7771); } } }
3,206
0
Create_ds/karyon/karyon2-examples/src/main/java/netflix/karyon/examples
Create_ds/karyon/karyon2-examples/src/main/java/netflix/karyon/examples/tcp/TcpPipelineHandlers.java
package netflix.karyon.examples.tcp; import com.google.inject.Inject; import com.google.inject.Singleton; import io.netty.buffer.ByteBuf; import io.reactivex.netty.channel.ConnectionHandler; import io.reactivex.netty.channel.ObservableConnection; import rx.Observable; import rx.functions.Func1; import java.nio.charset.Charset; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; /** * @author Tomasz Bak */ public interface TcpPipelineHandlers { @Singleton class QueueProvider { private static final BlockingQueue<String> messageQueue = new LinkedBlockingQueue<>(); public boolean isEmpty() { return messageQueue.isEmpty(); } public String poll() { return messageQueue.poll(); } public void put(String message) { messageQueue.add(message); } } class FrontendConnectionHandler implements ConnectionHandler<ByteBuf, ByteBuf> { private final QueueProvider queueProvider; @Inject public FrontendConnectionHandler(QueueProvider queueProvider) { this.queueProvider = queueProvider; } @Override public Observable<Void> handle(final ObservableConnection<ByteBuf, ByteBuf> connection) { System.out.println("New frontend connection"); return connection.getInput().flatMap(new Func1<ByteBuf, Observable<Void>>() { @Override public Observable<Void> call(ByteBuf byteBuf) { String message = byteBuf.toString(Charset.defaultCharset()); System.out.println("Received: " + message); queueProvider.put(message); ByteBuf output = connection.getAllocator().buffer(); output.writeBytes("Want some more:\n".getBytes()); return connection.writeAndFlush(output); } }); } } class BackendConnectionHandler implements ConnectionHandler<ByteBuf, ByteBuf> { private final QueueProvider queueProvider; @Inject public BackendConnectionHandler(QueueProvider queueProvider) { this.queueProvider = queueProvider; } @Override public Observable<Void> handle(final ObservableConnection<ByteBuf, ByteBuf> connection) { System.out.println("New backend connection"); return Observable.interval(1, TimeUnit.SECONDS).flatMap(new Func1<Long, Observable<Void>>() { @Override public Observable<Void> call(Long tick) { while (!queueProvider.isEmpty()) { ByteBuf output = connection.getAllocator().buffer(); output.writeBytes(queueProvider.poll().getBytes()); connection.write(output); } return connection.flush(); } }); } } }
3,207
0
Create_ds/karyon/karyon2-eureka/src/main/java/netflix/karyon
Create_ds/karyon/karyon2-eureka/src/main/java/netflix/karyon/eureka/EurekaHealthCheckHandler.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package netflix.karyon.eureka; import com.netflix.appinfo.InstanceInfo; import netflix.karyon.health.HealthCheckHandler; import javax.inject.Inject; /** * @author Nitesh Kant */ public class EurekaHealthCheckHandler implements com.netflix.appinfo.HealthCheckHandler { private final HealthCheckHandler healthCheckHandler; private final EurekaKaryonStatusBridge eurekaKaryonStatusBridge; @Inject public EurekaHealthCheckHandler(HealthCheckHandler healthCheckHandler, EurekaKaryonStatusBridge eurekaKaryonStatusBridge) { this.healthCheckHandler = healthCheckHandler; this.eurekaKaryonStatusBridge = eurekaKaryonStatusBridge; } @Override public InstanceInfo.InstanceStatus getStatus(InstanceInfo.InstanceStatus currentStatus) { int healthStatus = healthCheckHandler.getStatus(); return eurekaKaryonStatusBridge.interpretKaryonStatus(healthStatus); } }
3,208
0
Create_ds/karyon/karyon2-eureka/src/main/java/netflix/karyon
Create_ds/karyon/karyon2-eureka/src/main/java/netflix/karyon/eureka/DefaultEurekaKaryonStatusBridge.java
package netflix.karyon.eureka; import com.netflix.appinfo.InstanceInfo; /** * @author Nitesh Kant */ public class DefaultEurekaKaryonStatusBridge implements EurekaKaryonStatusBridge { @Override public InstanceInfo.InstanceStatus interpretKaryonStatus(int karyonStatus) { if(karyonStatus == 204) { return InstanceInfo.InstanceStatus.STARTING; } else if (karyonStatus >= 200 && karyonStatus < 300) { return InstanceInfo.InstanceStatus.UP; } return InstanceInfo.InstanceStatus.DOWN; } }
3,209
0
Create_ds/karyon/karyon2-eureka/src/main/java/netflix/karyon
Create_ds/karyon/karyon2-eureka/src/main/java/netflix/karyon/eureka/EurekaKaryonStatusBridge.java
package netflix.karyon.eureka; import com.google.inject.ImplementedBy; import com.netflix.appinfo.InstanceInfo; /** * @author Nitesh Kant */ @ImplementedBy(DefaultEurekaKaryonStatusBridge.class) public interface EurekaKaryonStatusBridge { InstanceInfo.InstanceStatus interpretKaryonStatus(int karyonStatus); }
3,210
0
Create_ds/karyon/karyon2-eureka/src/main/java/netflix/karyon
Create_ds/karyon/karyon2-eureka/src/main/java/netflix/karyon/eureka/KaryonEurekaModule.java
package netflix.karyon.eureka; import com.google.inject.AbstractModule; import com.google.inject.binder.LinkedBindingBuilder; import com.netflix.appinfo.ApplicationInfoManager; import com.netflix.appinfo.EurekaInstanceConfig; import com.netflix.appinfo.providers.CloudInstanceConfigProvider; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.EurekaNamespace; import com.netflix.discovery.providers.DefaultEurekaClientConfigProvider; import com.netflix.governator.guice.BootstrapModule; import netflix.karyon.Karyon; /** * Initialize Eureka, by binding the &quot;eureka.&quot; namespace and adding providers for EurekaClientConfig * and EurekaInstanceConfig. * * @author Nitesh Kant */ public class KaryonEurekaModule extends AbstractModule { private final String eurekaNamespace; public KaryonEurekaModule() { this("eureka."); } public KaryonEurekaModule(String eurekaNamespace) { this.eurekaNamespace = eurekaNamespace; } @Override protected void configure() { bind(com.netflix.appinfo.HealthCheckHandler.class).to(EurekaHealthCheckHandler.class); bind(ApplicationInfoManager.class).asEagerSingleton(); bind(DiscoveryClient.class).asEagerSingleton(); configureEureka(); } protected void configureEureka() { bindEurekaNamespace().toInstance(eurekaNamespace); bindEurekaInstanceConfig().toProvider(CloudInstanceConfigProvider.class); bindEurekaClientConfig().toProvider(DefaultEurekaClientConfigProvider.class); } protected LinkedBindingBuilder<EurekaInstanceConfig> bindEurekaInstanceConfig() { return bind(EurekaInstanceConfig.class); } protected LinkedBindingBuilder<EurekaClientConfig > bindEurekaClientConfig() { return bind(EurekaClientConfig.class); } protected LinkedBindingBuilder<String> bindEurekaNamespace() { return bind(String.class).annotatedWith(EurekaNamespace.class); } public static BootstrapModule asBootstrapModule() { return Karyon.toBootstrapModule(KaryonEurekaModule.class); } }
3,211
0
Create_ds/karyon/karyon2-admin/src/test/java/netflix
Create_ds/karyon/karyon2-admin/src/test/java/netflix/adminresources/AuthFilter.java
package netflix.adminresources; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class AuthFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException {} @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { String url = ((HttpServletRequest)request).getRequestURI(); if (url.startsWith("/main") || url.startsWith("/auth")) { ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN); } chain.doFilter(request, response); } } @Override public void destroy() { } }
3,212
0
Create_ds/karyon/karyon2-admin/src/test/java/netflix
Create_ds/karyon/karyon2-admin/src/test/java/netflix/adminresources/AdminResourceTest.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package netflix.adminresources; import static org.junit.Assert.assertEquals; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.commons.configuration.AbstractConfiguration; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.google.inject.Guice; import com.google.inject.Injector; import com.netflix.config.ConfigurationManager; import netflix.admin.AdminConfigImpl; import netflix.admin.RedirectRules; public class AdminResourceTest { @Path("/ping") @Produces(MediaType.TEXT_HTML) public static class PingResource { @GET public Response ping() { return Response.ok().entity("pong").build(); } } static class AdminResourcesFixture implements AutoCloseable { @Inject private AdminResourcesContainer container; @Inject @Named(KaryonAdminModule.ADMIN_RESOURCES_SERVER_PORT) private int serverPort; public void close() { container.shutdown(); } } public AdminResourcesFixture adminTestFixture() throws Exception { final Injector appInjector = Guice.createInjector(new KaryonAdminModule() { @Override protected void configure() { bind(RedirectRules.class).toInstance(new RedirectRules() { @Override public Map<String, String> getMappings() { Map<String, String> routes = new HashMap<>(); routes.put("/", "/bad-route"); routes.put("/check-me", "/jr/ping"); routes.put("/auth/ping", "/jr/ping"); return routes; } @Override public String getRedirect(HttpServletRequest httpServletRequest) { final String requestURI = httpServletRequest.getRequestURI(); if (requestURI.startsWith("/proxy-ping")) { return "/jr/ping"; } return null; } }); } }); AdminResourcesContainer adminResourcesContainer = appInjector.getInstance(AdminResourcesContainer.class); adminResourcesContainer.init(); return appInjector.getInstance(AdminResourcesFixture.class); } @BeforeClass public static void init() { setConfig(AdminConfigImpl.CONTAINER_LISTEN_PORT, "0"); setConfig(AdminConfigImpl.NETFLIX_ADMIN_RESOURCE_CONTEXT, "/jr"); setConfig(AdminConfigImpl.NETFLIX_ADMIN_TEMPLATE_CONTEXT, "/main"); } @AfterClass public static void cleanup() { final AbstractConfiguration configInst = ConfigurationManager.getConfigInstance(); configInst.clearProperty(AdminConfigImpl.CONTAINER_LISTEN_PORT); } private static void setConfig(String name, String value) { ConfigurationManager.getConfigInstance().setProperty(name, value); } private static void enableAdminConsole() { ConfigurationManager.getConfigInstance().setProperty(AdminConfigImpl.SERVER_ENABLE_PROP_NAME, true); } private static void disableAdminConsole() { ConfigurationManager.getConfigInstance().setProperty(AdminConfigImpl.SERVER_ENABLE_PROP_NAME, false); } @Test public void checkPing() throws Exception { try (AdminResourcesFixture testFixture = adminTestFixture()) { HttpClient client = new DefaultHttpClient(); HttpGet healthGet = new HttpGet(String.format("http://localhost:%d/jr/ping", testFixture.serverPort)); HttpResponse response = client.execute(healthGet); assertEquals("admin resource ping resource failed.", 200, response.getStatusLine().getStatusCode()); } } @Test public void checkAuthFilter() throws Exception { setConfig(AdminConfigImpl.NETFLIX_ADMIN_CTX_FILTERS, "netflix.adminresources.AuthFilter"); try (AdminResourcesFixture testFixture = adminTestFixture()) { HttpClient client = new DefaultHttpClient(); HttpGet healthGet = new HttpGet(String.format("http://localhost:%d/jr/ping", testFixture.serverPort)); HttpResponse response = client.execute(healthGet); assertEquals("admin resource ping resource failed.", 200, response.getStatusLine().getStatusCode()); consumeResponse(response); healthGet = new HttpGet(String.format("http://localhost:%d/main/get-user-id", testFixture.serverPort)); response = client.execute(healthGet); assertEquals("admin resource ping resource failed.", 403, response.getStatusLine().getStatusCode()); consumeResponse(response); healthGet = new HttpGet(String.format("http://localhost:%d/auth/no-page", testFixture.serverPort)); response = client.execute(healthGet); assertEquals("admin resource ping resource failed.", 404, response.getStatusLine().getStatusCode()); consumeResponse(response); healthGet = new HttpGet(String.format("http://localhost:%d/foo/ping", testFixture.serverPort)); response = client.execute(healthGet); assertEquals("admin resource ping resource failed.", 404, response.getStatusLine().getStatusCode()); consumeResponse(response); // verify redirect filter gets applied healthGet = new HttpGet(String.format("http://localhost:%d/check-me", testFixture.serverPort)); response = client.execute(healthGet); assertEquals("admin resource did not pick a custom redirect routing", 200, response.getStatusLine().getStatusCode()); BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); assertEquals("ping resource did not return pong", br.readLine(), "pong"); // verify auth filter not applied to a potential redirect path healthGet = new HttpGet(String.format("http://localhost:%d/auth/ping", testFixture.serverPort)); response = client.execute(healthGet); assertEquals("admin resource did not pick a custom redirect routing", 200, response.getStatusLine().getStatusCode()); br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); assertEquals("ping resource did not return pong", br.readLine(), "pong"); } finally { final AbstractConfiguration configInst = ConfigurationManager.getConfigInstance(); configInst.clearProperty(AdminConfigImpl.NETFLIX_ADMIN_CTX_FILTERS); } } @Test public void checkDefaultRedirectRule() throws Exception { try (AdminResourcesFixture testFixture = adminTestFixture()) { HttpClient client = new DefaultHttpClient(); HttpGet rootGet = new HttpGet(String.format("http://localhost:%d/", testFixture.serverPort)); HttpResponse response = client.execute(rootGet); assertEquals("admin resource root resource does not redirect to template root context.", 404, response.getStatusLine().getStatusCode()); } } @Test public void testEphemeralAdminResourcePort() throws Exception { try (AdminResourcesFixture testFixture = adminTestFixture()) { Assert.assertEquals(0, ConfigurationManager.getConfigInstance().getInt(AdminConfigImpl.CONTAINER_LISTEN_PORT)); Assert.assertTrue(testFixture.serverPort > 0); Assert.assertEquals(testFixture.serverPort, testFixture.container.getServerPort()); } } @Test public void testServiceDisabledFlag() throws Exception { disableAdminConsole(); try (AdminResourcesFixture testFixture = adminTestFixture()) { assertEquals("admin resource did not get disabled with a config flag", 0, testFixture.serverPort); } enableAdminConsole(); } @Test public void checkCustomRedirectRule() throws Exception { try (AdminResourcesFixture testFixture = adminTestFixture()) { HttpClient client = new DefaultHttpClient(); HttpGet rootGet = new HttpGet(String.format("http://localhost:%d/", testFixture.serverPort)); HttpResponse response = client.execute(rootGet); assertEquals("admin resource did not execute custom redirect routing", 404, response.getStatusLine().getStatusCode()); consumeResponse(response); HttpGet healthGet = new HttpGet(String.format("http://localhost:%d/check-me", testFixture.serverPort)); response = client.execute(healthGet); assertEquals("admin resource did not pick a custom redirect routing", 200, response.getStatusLine().getStatusCode()); BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); assertEquals("ping resource did not return pong", br.readLine(), "pong"); healthGet = new HttpGet( String.format("http://localhost:%d/proxy-ping/or-not?when=some-day", testFixture.serverPort)); response = client.execute(healthGet); assertEquals("admin resource did not pick a custom redirect routing", 200, response.getStatusLine().getStatusCode()); br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); assertEquals("ping resource did not return pong", br.readLine(), "pong"); } } private void consumeResponse(HttpResponse response) throws IOException { if (response.getEntity() != null && response.getEntity().getContent() != null) { final BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); while (br.readLine() != null) ; } } }
3,213
0
Create_ds/karyon/karyon2-admin/src/test/java/netflix
Create_ds/karyon/karyon2-admin/src/test/java/netflix/admin/AdminUtilsTest.java
package netflix.admin; import com.netflix.explorers.PropertiesGlobalModelContext; import org.junit.Test; import java.util.Properties; import static junit.framework.Assert.assertTrue; public class AdminUtilsTest { @Test public void environmentPropertyLoaded() { final Properties properties = AdminUtils.loadAdminConsoleProps(); assertTrue(properties.getProperty(PropertiesGlobalModelContext.PROPERTY_ENVIRONMENT_NAME) != null); } @Test public void regionPropertyLoaded() { final Properties properties = AdminUtils.loadAdminConsoleProps(); assertTrue(properties.getProperty(PropertiesGlobalModelContext.PROPERTY_CURRENT_REGION) != null); } }
3,214
0
Create_ds/karyon/karyon2-admin/src/test/java/netflix
Create_ds/karyon/karyon2-admin/src/test/java/netflix/admin/AdminPageRegistryTest.java
package netflix.admin; import com.google.inject.Module; import com.netflix.config.ConfigurationManager; import netflix.adminresources.AbstractAdminPageInfo; import netflix.adminresources.AdminPage; import netflix.adminresources.AdminPageInfo; import netflix.adminresources.AdminPageRegistry; import org.junit.Before; import org.junit.Test; import java.lang.annotation.Annotation; import java.util.*; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.*; public class AdminPageRegistryTest { static final AdminPageRegistry adminPageRegistry = new AdminPageRegistry(); @java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME) public static @interface MockAnnotation1 { } @java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME) public static @interface MockAnnotation2 { } @AdminPage public static class MockPlugin1 extends AbstractAdminPageInfo { public MockPlugin1() { super("id-plugin1", "plugin-1"); } @Override public String getJerseyResourcePackageList() { return "pkg1;pkg2"; } } @AdminPage public static class MockPlugin2 extends AbstractAdminPageInfo { public MockPlugin2() { super("id-plugin2", "plugin-2"); } @Override public String getJerseyResourcePackageList() { return "pkg3;pkg4"; } } @AdminPage public static class DisabledMockPlugin3 extends AbstractAdminPageInfo { public DisabledMockPlugin3() { super("id-plugin3", "plugin-3"); } @Override public boolean isEnabled() { return false; } } @AdminPage public static class DisabledMockPlugin4 implements AdminPageInfo { private String id = "id-plugin4"; private String name = "plugin4"; @Override public String getPageId() { return id; } @Override public String getName() { return name; } @Override public String getPageTemplate() { return null; } @Override public Map<String, Object> getDataModel() { Map<String, Object> dataModel = new HashMap<>(1); dataModel.put("foo", "bar"); return dataModel; } @Override public String getJerseyResourcePackageList() { return null; } @Override public List<Module> getGuiceModules() { return new ArrayList<>(0); } @Override public boolean isEnabled() { return true; } @Override public boolean isVisible() { return false; } } @Before public void init() { adminPageRegistry.registerAdminPagesWithClasspathScan(); } @Test public void verifyAllPages() { final Collection<AdminPageInfo> allPages = adminPageRegistry.getAllPages(); // 4 modules - 1 disabled assertTrue(allPages.size() == 3); for (AdminPageInfo pageInfo : allPages) { assertTrue(pageInfo.getName().startsWith("plugin")); } } @Test public void addAndRemoveAdminPluginDynamically() { Collection<AdminPageInfo> allPlugins = adminPageRegistry.getAllPages(); assertThat("Admin plugins are not null by default", allPlugins, notNullValue()); assertThat("Admin plugins size is 3", allPlugins.size(), is(3)); final AbstractAdminPageInfo dynamicPlugin1 = new AbstractAdminPageInfo("dynamicPluginId1", "dynamicPluginName1") { }; adminPageRegistry.add(dynamicPlugin1); assertThat("Admin plugins added dynamically", adminPageRegistry.getAllPages().size(), is(4)); adminPageRegistry.remove(dynamicPlugin1); assertThat("Admin plugins removed dynamically", adminPageRegistry.getAllPages().size(), is(3)); } @Test public void verifyJerseyPkgPath() { final String jerseyResourcePath = adminPageRegistry.buildJerseyResourcePkgListForAdminPages(); assertEquals("pkg1;pkg2;pkg3;pkg4;", jerseyResourcePath); } @Test public void verifyVisible() { final AdminPageInfo plugin4 = adminPageRegistry.getPageInfo("id-plugin4"); assertThat("Plugin4 should not be null", plugin4, notNullValue()); assertThat("Plugin4 should not be visible", plugin4.isVisible(), is(false)); } @Test public void verifyDataModel() { final AdminPageInfo plugin4 = adminPageRegistry.getPageInfo("id-plugin4"); assertThat("Plugin4 should is null", plugin4, notNullValue()); final Map<String, Object> dataModel = plugin4.getDataModel(); assertThat("Data model is null", dataModel, notNullValue()); assertThat("Data model does not contain 1 entry", dataModel.size(), is(1)); assertThat("Data model does not contain foo", dataModel.containsKey("foo"), is(true)); } @Test public void defaultAdminPageAnnotations() { final List<Class<? extends Annotation>> adminPageAnnotations = adminPageRegistry.getAdminPageAnnotations(); assertThat("AdminPage Annotations are not null by default", adminPageAnnotations, notNullValue()); assertThat("AdminPage Annotations size is 1 by default", adminPageAnnotations.size(), is(1)); final String defaultAnnotationClassName = adminPageAnnotations.get(0).getName(); assertThat("DefaultAnnotationClassName is AdminPage", defaultAnnotationClassName, is("netflix.adminresources.AdminPage")); } @Test public void badAdminPageAnnotation() { ConfigurationManager.getConfigInstance().setProperty(AdminPageRegistry.PROP_ID_ADMIN_PAGE_ANNOTATION, "netflix.InvalidAnnotation1;netflix.InvalidAnnotation2"); final List<Class<? extends Annotation>> adminPageAnnotations = adminPageRegistry.getAdminPageAnnotations(); assertThat("AdminPage Annotations are not null", adminPageAnnotations, notNullValue()); assertThat("AdminPage Annotations size is 0", adminPageAnnotations.size(), is(0)); ConfigurationManager.getConfigInstance().setProperty(AdminPageRegistry.PROP_ID_ADMIN_PAGE_ANNOTATION, AdminPageRegistry.DEFAULT_ADMIN_PAGE_ANNOTATION); } @Test public void configureAdminPageAnnotation() { ConfigurationManager.getConfigInstance().setProperty(AdminPageRegistry.PROP_ID_ADMIN_PAGE_ANNOTATION, "netflix.admin.AdminPageRegistryTest$MockAnnotation1;netflix.admin.AdminPageRegistryTest$MockAnnotation2"); final List<Class<? extends Annotation>> adminPageAnnotations = adminPageRegistry.getAdminPageAnnotations(); assertThat("AdminPage Annotations are not empty", adminPageAnnotations, notNullValue()); assertThat("AdminPage Annotations size is 2", adminPageAnnotations.size(), is(2)); final String firstAnnotation = adminPageAnnotations.get(0).getName(); final String secondAnnotation = adminPageAnnotations.get(1).getName(); assertThat("AdminPage annotation is netflix.Annotation1", firstAnnotation, is("netflix.admin.AdminPageRegistryTest$MockAnnotation1")); assertThat("AdminPage annotation is netflix.Annotation2", secondAnnotation, is("netflix.admin.AdminPageRegistryTest$MockAnnotation2")); ConfigurationManager.getConfigInstance().setProperty(AdminPageRegistry.PROP_ID_ADMIN_PAGE_ANNOTATION, AdminPageRegistry.DEFAULT_ADMIN_PAGE_ANNOTATION); } }
3,215
0
Create_ds/karyon/karyon2-admin/src/main/java/netflix
Create_ds/karyon/karyon2-admin/src/main/java/netflix/adminresources/AdminPage.java
package netflix.adminresources; @java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME) public @interface AdminPage { }
3,216
0
Create_ds/karyon/karyon2-admin/src/main/java/netflix
Create_ds/karyon/karyon2-admin/src/main/java/netflix/adminresources/AdminResourcesContainer.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package netflix.adminresources; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.servlet.Filter; import org.mortbay.jetty.Connector; import org.mortbay.jetty.Handler; import org.mortbay.jetty.Server; import org.mortbay.jetty.handler.HandlerCollection; import org.mortbay.jetty.handler.ResourceHandler; import org.mortbay.jetty.security.SslSocketConnector; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.DefaultServlet; import org.mortbay.jetty.servlet.FilterHolder; import org.mortbay.jetty.servlet.ServletHolder; import org.mortbay.jetty.servlet.SessionHandler; import org.mortbay.resource.Resource; import org.mortbay.thread.QueuedThreadPool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Singleton; import com.google.inject.Stage; import com.netflix.governator.guice.LifecycleInjector; import com.netflix.governator.lifecycle.LifecycleManager; import com.sun.jersey.api.core.PackagesResourceConfig; import netflix.admin.AdminConfigImpl; import netflix.admin.AdminContainerConfig; /** * This class starts an embedded jetty server, listening at port specified by property * {@link netflix.admin.AdminContainerConfig#listenPort()} and defaulting to * {@link netflix.admin.AdminContainerConfig}. <br> * <p/> * The embedded server uses jersey so any jersey resources available in packages * specified via properties {@link netflix.admin.AdminContainerConfig#jerseyResourcePkgList()}will be scanned and initialized. <br> * <p/> * Karyon admin starts in an embedded container to have a "always available" endpoint for any application. This helps * in a homogeneous admin view for all applications. <br> * <p/> * <h3>Available resources</h3> * <p/> * The following resources are available by default: * <p/> * </ul> */ @Singleton public class AdminResourcesContainer { private static final Logger logger = LoggerFactory.getLogger(AdminResourcesContainer.class); /** * @deprecated here for backwards compatibility. Use {@link AdminConfigImpl#CONTAINER_LISTEN_PORT}. */ @Deprecated public static final String CONTAINER_LISTEN_PORT = AdminConfigImpl.CONTAINER_LISTEN_PORT; private Server server; @Inject(optional = true) private Injector appInjector; @Inject(optional = true) private AdminContainerConfig adminContainerConfig; @Inject(optional = true) private AdminPageRegistry adminPageRegistry; private AtomicBoolean alreadyInited = new AtomicBoolean(false); private int serverPort; // actual server listen port (apart from what's in Config) @Inject public AdminResourcesContainer() {} public AdminResourcesContainer(Injector appInjector, AdminContainerConfig adminContainerConfig, AdminPageRegistry adminPageRegistry) { this.appInjector = appInjector; this.adminContainerConfig = adminContainerConfig; this.adminPageRegistry = adminPageRegistry; } /** * Starts the container and hence the embedded jetty server. * * @throws Exception if there is an issue while starting the server */ @PostConstruct public void init() throws Exception { try { if (alreadyInited.compareAndSet(false, true)) { initAdminContainerConfigIfNeeded(); initAdminRegistryIfNeeded(); if (! adminContainerConfig.shouldEnable()) { return; } if (adminContainerConfig.shouldScanClassPathForPluginDiscovery()) { adminPageRegistry.registerAdminPagesWithClasspathScan(); } Injector adminResourceInjector; if (shouldShareResourcesWithParentInjector()) { adminResourceInjector = appInjector.createChildInjector(buildAdminPluginsGuiceModules()); } else { adminResourceInjector = LifecycleInjector .builder() .inStage(Stage.DEVELOPMENT) .usingBasePackages("com.netflix.explorers") .withModules(buildAdminPluginsGuiceModules()) .build() .createInjector(); adminResourceInjector.getInstance(LifecycleManager.class).start(); } server = new Server(adminContainerConfig.listenPort()); final List<Filter> additionaFilters = adminContainerConfig.additionalFilters(); // redirect filter based on configurable RedirectRules final Context rootHandler = new Context(); rootHandler.setContextPath("/"); rootHandler.addFilter(new FilterHolder(adminResourceInjector.getInstance(RedirectFilter.class)), "/*", Handler.DEFAULT); rootHandler.addServlet(new ServletHolder(new DefaultServlet()), "/*"); // admin page template resources AdminResourcesFilter arfTemplatesResources = adminResourceInjector.getInstance(AdminResourcesFilter.class); Map<String, Object> props = new HashMap<>(adminContainerConfig.getJerseyConfigProperties()); props.put(PackagesResourceConfig.PROPERTY_PACKAGES, adminContainerConfig.jerseyViewableResourcePkgList() + ";" + Objects.toString(props.get(PackagesResourceConfig.PROPERTY_PACKAGES))); arfTemplatesResources.setProperties(props); logger.info("Admin templates context : {}", adminContainerConfig.templateResourceContext()); final Context adminTemplatesResHandler = new Context(); adminTemplatesResHandler.setContextPath(adminContainerConfig.templateResourceContext()); adminTemplatesResHandler.setSessionHandler(new SessionHandler()); adminTemplatesResHandler.addFilter(LoggingFilter.class, "/*", Handler.DEFAULT); adminTemplatesResHandler.addFilter(new FilterHolder(adminResourceInjector.getInstance(RedirectFilter.class)), "/*", Handler.DEFAULT); applyAdditionalFilters(adminTemplatesResHandler, additionaFilters); adminTemplatesResHandler.addFilter(new FilterHolder(arfTemplatesResources), "/*", Handler.DEFAULT); adminTemplatesResHandler.addServlet(new ServletHolder(new DefaultServlet()), "/*"); // admin page data resources AdminResourcesFilter arfDataResources = adminResourceInjector.getInstance(AdminResourcesFilter.class); props = new HashMap<>(adminContainerConfig.getJerseyConfigProperties()); props.put(PackagesResourceConfig.PROPERTY_PACKAGES, appendCoreJerseyPackages(adminPageRegistry.buildJerseyResourcePkgListForAdminPages()) + ";" + Objects.toString(props.get(PackagesResourceConfig.PROPERTY_PACKAGES))); arfDataResources.setProperties(props); logger.info("Admin resources context : {}", adminContainerConfig.ajaxDataResourceContext()); final Context adminDataResHandler = new Context(); adminDataResHandler.setContextPath(adminContainerConfig.ajaxDataResourceContext()); adminDataResHandler.addFilter(LoggingFilter.class, "/*", Handler.DEFAULT); adminDataResHandler.addFilter(new FilterHolder(adminResourceInjector.getInstance(RedirectFilter.class)), "/*", Handler.DEFAULT); applyAdditionalFilters(adminDataResHandler, additionaFilters); adminDataResHandler.addFilter(new FilterHolder(arfDataResources), "/*", Handler.DEFAULT); adminDataResHandler.addServlet(new ServletHolder(new DefaultServlet()), "/*"); QueuedThreadPool threadPool = new QueuedThreadPool(); threadPool.setDaemon(true); server.setThreadPool(threadPool); ResourceHandler resource_handler = new ResourceHandler() { @Override public Resource getResource(String path) throws MalformedURLException { Resource resource = Resource.newClassPathResource(path); if (resource == null || !resource.exists()) { resource = Resource.newClassPathResource("META-INF/resources" + path); } if (resource != null && resource.isDirectory()) { return null; } return resource; } }; resource_handler.setResourceBase("/"); HandlerCollection handlers = new HandlerCollection(); handlers.setHandlers(new Handler[]{resource_handler, adminTemplatesResHandler, adminDataResHandler, rootHandler}); server.setHandler(handlers); for (Connector connector : adminContainerConfig.additionalConnectors()) { server.addConnector(connector); } server.start(); final Connector connector = server.getConnectors()[0]; serverPort = connector.getLocalPort(); logger.info("jetty started on port {}", serverPort); } } catch (Exception e) { logger.error("Exception in building AdminResourcesContainer ", e); } } private void initAdminContainerConfigIfNeeded() { if (adminContainerConfig == null) { adminContainerConfig = new AdminConfigImpl(); } } private void initAdminRegistryIfNeeded() { if (adminPageRegistry == null) { adminPageRegistry = new AdminPageRegistry(); } } public int getServerPort() { return serverPort; } public AdminPageRegistry getAdminPageRegistry() { return adminPageRegistry; } private Module getAdditionalBindings() { return new AbstractModule() { @Override protected void configure() { bind(AdminResourcesFilter.class); if (! shouldShareResourcesWithParentInjector()) { bind(AdminPageRegistry.class).toInstance(adminPageRegistry); bind(AdminContainerConfig.class).toInstance(adminContainerConfig); } } }; } private String appendCoreJerseyPackages(String jerseyResourcePkgListForAdminPages) { String pkgPath = adminContainerConfig.jerseyResourcePkgList(); if (jerseyResourcePkgListForAdminPages != null && !jerseyResourcePkgListForAdminPages.isEmpty()) { pkgPath += ";" + jerseyResourcePkgListForAdminPages; } return pkgPath; } private List<Module> buildAdminPluginsGuiceModules() { List<Module> guiceModules = new ArrayList<>(); if (adminPageRegistry != null) { final Collection<AdminPageInfo> allPages = adminPageRegistry.getAllPages(); for (AdminPageInfo adminPlugin : allPages) { logger.info("Adding admin page {}: jersey={} modules{}", adminPlugin.getName(), adminPlugin.getJerseyResourcePackageList(), adminPlugin.getGuiceModules()); final List<Module> guiceModuleList = adminPlugin.getGuiceModules(); if (guiceModuleList != null && !guiceModuleList.isEmpty()) { guiceModules.addAll(adminPlugin.getGuiceModules()); } } } guiceModules.add(getAdditionalBindings()); return guiceModules; } private boolean shouldShareResourcesWithParentInjector() { return appInjector != null && ! adminContainerConfig.shouldIsolateResources(); } private void applyAdditionalFilters(final Context contextHandler, List<Filter> additionalFilters) { if (additionalFilters != null && !additionalFilters.isEmpty()) { for(Filter f : additionalFilters) { contextHandler.addFilter(new FilterHolder(f), "/*", Handler.DEFAULT); } } } @PreDestroy public void shutdown() { try { if (server != null) { server.stop(); } } catch (Throwable t) { logger.warn("Error while shutting down Admin resources server", t); } finally { alreadyInited.set(false); } } }
3,217
0
Create_ds/karyon/karyon2-admin/src/main/java/netflix
Create_ds/karyon/karyon2-admin/src/main/java/netflix/adminresources/AbstractAdminPageInfo.java
package netflix.adminresources; import com.google.inject.Module; import com.netflix.config.ConfigurationManager; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public abstract class AbstractAdminPageInfo implements AdminPageInfo { public static final String ADMIN_PAGE_DISABLE_PROP_PREFIX = "netflix.platform.admin.pages."; public static final String DISABLED = ".disabled"; private final String pageId; private final String name; public AbstractAdminPageInfo(String pageId, String name) { this.pageId = pageId; this.name = name; } public String getPageId() { return pageId; } @Override public String getName() { return name; } @Override public String getPageTemplate() { return "/webadmin/" + pageId + "/index.ftl"; } @Override public String getJerseyResourcePackageList() { return ""; } @Override public boolean isEnabled() { final String disablePagePropId = ADMIN_PAGE_DISABLE_PROP_PREFIX + pageId + DISABLED; boolean isDisabled = ConfigurationManager.getConfigInstance().getBoolean(disablePagePropId, false); return !isDisabled; } @Override public List<Module> getGuiceModules() { return new ArrayList<>(0); } @Override public Map<String, Object> getDataModel() { return new HashMap<>(); } @Override public boolean isVisible() { return true; } }
3,218
0
Create_ds/karyon/karyon2-admin/src/main/java/netflix
Create_ds/karyon/karyon2-admin/src/main/java/netflix/adminresources/AdminPageRegistry.java
package netflix.adminresources; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.inject.Injector; import com.google.inject.Singleton; import com.netflix.config.ConfigurationManager; import com.netflix.governator.lifecycle.ClasspathScanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.inject.Inject; @Singleton public class AdminPageRegistry { private static final Logger LOG = LoggerFactory.getLogger(AdminPageRegistry.class); public final static String PROP_ID_ADMIN_PAGES_SCAN = "netflix.platform.admin.pages.packages"; public static final String DEFAULT_SCAN_PKG = "netflix"; public final static String PROP_ID_ADMIN_PAGE_ANNOTATION = "netflix.platform.admin.pages.annotation"; public static final String DEFAULT_ADMIN_PAGE_ANNOTATION = "netflix.adminresources.AdminPage"; private Map<String, AdminPageInfo> baseServerPageInfoMap; private Injector injector; public AdminPageRegistry() { this.baseServerPageInfoMap = new ConcurrentHashMap<>(); this.injector = null; } @Inject public AdminPageRegistry(Injector injector) { this.baseServerPageInfoMap = new ConcurrentHashMap<>(); this.injector = injector; } public void add(AdminPageInfo baseServerPageInfo) { Preconditions.checkNotNull(baseServerPageInfo); baseServerPageInfoMap.put(baseServerPageInfo.getPageId(), baseServerPageInfo); } public void remove(AdminPageInfo baseServerPageInfo) { Preconditions.checkNotNull(baseServerPageInfo); baseServerPageInfoMap.remove(baseServerPageInfo.getPageId()); } public AdminPageInfo getPageInfo(String pageId) { return baseServerPageInfoMap.get(pageId); } public Collection<AdminPageInfo> getAllPages() { List<AdminPageInfo> pages = Lists.newArrayList(baseServerPageInfoMap.values()); List<AdminPageInfo> enabledPages = getEnabledPages(pages); // list needs to be sorted by page titles if available Collections.sort(enabledPages, new Comparator<AdminPageInfo>() { public int compare(AdminPageInfo left, AdminPageInfo right) { String leftVal = left.getName() != null ? left.getName() : left.getPageId(); String rightVal = right.getName() != null ? right.getName() : right.getPageId(); return leftVal.compareToIgnoreCase(rightVal); } }); return enabledPages; } public void registerAdminPagesWithClasspathScan() { List<Class<? extends Annotation>> annotationList = getAdminPageAnnotations(); ClasspathScanner cs = new ClasspathScanner(getAdminPagesPackagesToScan(), annotationList); for (Class<?> baseServerAdminPageClass : cs.getClasses()) { if (derivedFromAbstractBaseServePageInfo(baseServerAdminPageClass) || implementsAdminPageInfo(baseServerAdminPageClass)) { try { add((AdminPageInfo) (injector == null ? baseServerAdminPageClass.newInstance() : injector.getInstance(baseServerAdminPageClass))); } catch (Exception e) { LOG.warn(String.format("Exception registering %s admin page", baseServerAdminPageClass.getName()), e); } } } } public String buildJerseyResourcePkgListForAdminPages() { StringBuilder stringBuilder = new StringBuilder(); Collection<AdminPageInfo> adminPages = getAllPages(); int i = 0; for (AdminPageInfo adminPage : adminPages) { if (i > 0) { stringBuilder.append(";"); } String pkgList = adminPage.getJerseyResourcePackageList(); if (pkgList != null) { stringBuilder.append(pkgList); } i++; } return stringBuilder.toString(); } private List<String> getAdminPagesPackagesToScan() { final String adminPagesPkgPath = ConfigurationManager.getConfigInstance().getString(PROP_ID_ADMIN_PAGES_SCAN, DEFAULT_SCAN_PKG); String[] pkgPaths = adminPagesPkgPath.split(";"); return Lists.newArrayList(pkgPaths); } private boolean implementsAdminPageInfo(Class<?> baseServerAdminPageClass) { Class<?>[] interfacesImplemented = baseServerAdminPageClass.getInterfaces(); for (Class<?> interfaceObj : interfacesImplemented) { if (interfaceObj.equals(AdminPageInfo.class)) { return true; } } return false; } private boolean derivedFromAbstractBaseServePageInfo(Class<?> baseServerAdminPageClass) { Class<?> superClass = baseServerAdminPageClass.getSuperclass(); while (superClass != null) { if (superClass.equals(AbstractAdminPageInfo.class)) { return true; } superClass = superClass.getSuperclass(); } return false; } public List<Class<? extends Annotation>> getAdminPageAnnotations() { final String adminPageAnnotationClasses = ConfigurationManager.getConfigInstance().getString(PROP_ID_ADMIN_PAGE_ANNOTATION, DEFAULT_ADMIN_PAGE_ANNOTATION); String[] clsNameList = adminPageAnnotationClasses.split(";"); List<Class<? extends Annotation>> clsList = new ArrayList<>(clsNameList.length); for (String clsName : clsNameList) { try { final Class<?> aClass = Class.forName(clsName); if (aClass.isAnnotation()) { clsList.add(aClass.asSubclass(Annotation.class)); } } catch (ClassNotFoundException e) { LOG.warn("Invalid AdminPage Annotation class - " + clsName); } } return clsList; } private List<AdminPageInfo> getEnabledPages(List<AdminPageInfo> pages) { List<AdminPageInfo> enabledPages = Lists.newArrayList(); for (AdminPageInfo page : pages) { if (page.isEnabled()) { enabledPages.add(page); } } return enabledPages; } }
3,219
0
Create_ds/karyon/karyon2-admin/src/main/java/netflix
Create_ds/karyon/karyon2-admin/src/main/java/netflix/adminresources/RedirectFilter.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package netflix.adminresources; import com.google.inject.Inject; import com.google.inject.Singleton; import netflix.admin.RedirectRules; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Map; @Singleton public class RedirectFilter implements Filter { private RedirectRules redirectRules; @Inject public RedirectFilter(RedirectRules redirectRules) { this.redirectRules = redirectRules; } @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; final String requestURI = httpRequest.getRequestURI(); // redirect based on a simple table lookup final Map<String, String> mappings = redirectRules.getMappings(); for (Map.Entry<String, String> mapping : mappings.entrySet()) { if (requestURI.equals(mapping.getKey())) { ((HttpServletResponse) response).sendRedirect(mapping.getValue()); return; } } // redirect based on a custom logic for request final String redirectTo = redirectRules.getRedirect(httpRequest); if (redirectTo != null && !redirectTo.isEmpty() && !redirectTo.equals(requestURI)) { ((HttpServletResponse) response).sendRedirect(redirectTo); return; } chain.doFilter(httpRequest, response); } @Override public void init(FilterConfig config) throws ServletException { } }
3,220
0
Create_ds/karyon/karyon2-admin/src/main/java/netflix
Create_ds/karyon/karyon2-admin/src/main/java/netflix/adminresources/KaryonAdminModule.java
package netflix.adminresources; import javax.inject.Named; import com.google.inject.AbstractModule; import com.google.inject.Provides; public class KaryonAdminModule extends AbstractModule { public static final String ADMIN_RESOURCES_SERVER_PORT = "adminResourcesServerPort"; @Override protected void configure() { bind(AdminResourcesContainer.class).asEagerSingleton(); } @Provides @Named(ADMIN_RESOURCES_SERVER_PORT) public int adminListenPort(AdminResourcesContainer adminResourcesContainer) { return adminResourcesContainer.getServerPort(); } }
3,221
0
Create_ds/karyon/karyon2-admin/src/main/java/netflix
Create_ds/karyon/karyon2-admin/src/main/java/netflix/adminresources/LoggingFilter.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package netflix.adminresources; import com.google.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.regex.Pattern; /** * A {@link Filter} implementation to capture request details like remote host, HTTP method and request URI * * @author pkamath * @author Nitesh Kant */ @Singleton public class LoggingFilter implements Filter { private static final Logger logger = LoggerFactory.getLogger(LoggingFilter.class); // We will not log requests for these file extensions private static Pattern PATTERN_FOR_CSS_JS_ETC = Pattern.compile(".*js$|.*png$|.*gif$|.*css$|.*jpg$|.*jpeg$|.*ico$"); @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; if (!PATTERN_FOR_CSS_JS_ETC.matcher(httpRequest.getRequestURI()) .matches()) { StringBuilder sb = new StringBuilder("AdminResources request details: "); sb.append(httpRequest.getRemoteHost()).append(" ") .append(httpRequest.getRemoteAddr()).append(" ") .append(httpRequest.getMethod()).append(" ") .append(httpRequest.getRequestURI()); logger.info(sb.toString()); } chain.doFilter(httpRequest, response); } @Override public void init(FilterConfig config) throws ServletException { } }
3,222
0
Create_ds/karyon/karyon2-admin/src/main/java/netflix
Create_ds/karyon/karyon2-admin/src/main/java/netflix/adminresources/AdminPageInfo.java
package netflix.adminresources; import com.google.inject.Module; import java.util.List; import java.util.Map; public interface AdminPageInfo { // id of the new page String getPageId(); // title as shown in tab UI String getName(); // freemarker template path String getPageTemplate(); // exports additional bindings needed by the plugin Map<String, Object> getDataModel(); // additional jersey resource package list if needed String getJerseyResourcePackageList(); // Guice modules that need to be added to the injector List<Module> getGuiceModules(); // controls if the module should be visible/enabled in admin console boolean isEnabled(); // should it be visible (by rendering page template as defined above) boolean isVisible(); }
3,223
0
Create_ds/karyon/karyon2-admin/src/main/java/netflix
Create_ds/karyon/karyon2-admin/src/main/java/netflix/adminresources/AdminResourcesFilter.java
package netflix.adminresources; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.inject.Inject; import javax.servlet.ServletException; import com.google.inject.Injector; import com.netflix.explorers.providers.FreemarkerTemplateProvider; import com.netflix.explorers.providers.WebApplicationExceptionMapper; import com.sun.jersey.api.core.PackagesResourceConfig; import com.sun.jersey.api.core.ResourceConfig; import com.sun.jersey.guice.spi.container.servlet.GuiceContainer; import com.sun.jersey.spi.container.servlet.WebConfig; import netflix.admin.AdminFreemarkerTemplateProvider; /** * This class is a minimal simulation of GuiceFilter. Due to the number of * statics used in GuiceFilter, there cannot be more than one in an application. * The AdminResources app needs minimal features and this class provides those. */ class AdminResourcesFilter extends GuiceContainer { private Map<String, Object> props = Collections.emptyMap(); @Inject AdminResourcesFilter(Injector injector) { super(injector); } @Override protected ResourceConfig getDefaultResourceConfig(Map<String, Object> props, WebConfig webConfig) throws ServletException { HashMap<String, Object> mergedProps = new HashMap<>(props); mergedProps.putAll(this.props); return new PackagesResourceConfig(mergedProps) { @Override public Set<Class<?>> getProviderClasses() { Set<Class<?>> providers = super.getProviderClasses(); // remove conflicting provider if present providers.remove(FreemarkerTemplateProvider.class); providers.add(AdminFreemarkerTemplateProvider.class); providers.add(WebApplicationExceptionMapper.class); return providers; } }; } public void setProperties(Map<String, Object> props) { this.props = new HashMap<>(props); } }
3,224
0
Create_ds/karyon/karyon2-admin/src/main/java/netflix
Create_ds/karyon/karyon2-admin/src/main/java/netflix/admin/DefaultRedirectRules.java
package netflix.admin; import java.util.HashMap; import java.util.Map; import javax.inject.Singleton; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; @Singleton public class DefaultRedirectRules implements RedirectRules { private AdminContainerConfig adminContainerConfig; @Inject public DefaultRedirectRules(AdminContainerConfig adminContainerConfig) { this.adminContainerConfig = adminContainerConfig; } @Override public Map<String, String> getMappings() { Map<String, String> urlRedirects = new HashMap<>(); urlRedirects.put("/", adminContainerConfig.templateResourceContext()); return urlRedirects; } @Override public String getRedirect(HttpServletRequest httpServletRequest) { return httpServletRequest.getRequestURI(); } }
3,225
0
Create_ds/karyon/karyon2-admin/src/main/java/netflix
Create_ds/karyon/karyon2-admin/src/main/java/netflix/admin/AdminConfigImpl.java
package netflix.admin; import com.google.inject.Injector; import com.netflix.config.ConfigurationManager; import com.netflix.config.util.ConfigurationUtils; import org.mortbay.jetty.Connector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.Filter; import java.util.*; import java.util.Map.Entry; @Singleton public class AdminConfigImpl implements AdminContainerConfig { private static final Logger logger = LoggerFactory.getLogger(AdminConfigImpl.class); public static final String ADMIN_PREFIX = "netflix.admin."; public static final String NETFLIX_ADMIN_TEMPLATE_CONTEXT = ADMIN_PREFIX + "template.context"; public static final String TEMPLATE_CONTEXT_DEFAULT = "/admin"; public static final String NETFLIX_ADMIN_RESOURCE_CONTEXT = ADMIN_PREFIX + "resource.context"; public static final String RESOURCE_CONTEXT_DEFAULT = "/webadmin"; private static final String JERSEY_CORE_RESOURCES = "netflix.platform.admin.resources.core.packages"; public static final String JERSEY_CORE_RESOURCES_DEFAULT = "netflix.adminresources;com.netflix.explorers.resources;com.netflix.explorers.providers"; private static final String JERSEY_VIEWABLE_RESOURCES = "netflix.platform.admin.resources.viewable.packages"; public static final String JERSEY_VIEWABLE_RESOURCES_DEFAULT = "netflix.admin;netflix.adminresources.pages;com.netflix.explorers.resources"; public static final String CONTAINER_LISTEN_PORT = "netflix.platform.admin.resources.port"; public static final int LISTEN_PORT_DEFAULT = 8077; public static final String SERVER_ENABLE_PROP_NAME = "netflix.platform.admin.resources.enable"; public static final boolean SERVER_ENABLE_DEFAULT = true; public static final String NETFLIX_ADMIN_RESOURCES_ISOLATE = ADMIN_PREFIX + "resources.isolate"; public static final boolean ISOLATE_RESOURCES_DEFAULT = false; public static final String NETFLIX_ADMIN_CTX_FILTERS = ADMIN_PREFIX + "additional.filters"; public static final String DEFAULT_CONTEXT_FILTERS = ""; public static final String NETFLIX_ADMIN_CTX_CONNECTORS = ADMIN_PREFIX + "additional.connectors"; public static final String DEFAULT_CONTEXT_CONNECTORS = ""; private static final String JERSEY_PROPERTY_PREFIX = "com.sun.jersey.config"; private static final String ADMIN_JERSEY_PROPERTY_PREFIX = ADMIN_PREFIX + JERSEY_PROPERTY_PREFIX; private final Injector injector; public AdminConfigImpl() { this(null); } @Inject public AdminConfigImpl(Injector injector) { this.injector = injector; } @Override public boolean shouldIsolateResources() { return ConfigurationManager.getConfigInstance().getBoolean(NETFLIX_ADMIN_RESOURCES_ISOLATE, ISOLATE_RESOURCES_DEFAULT); } @Override public boolean shouldEnable() { return ConfigurationManager.getConfigInstance().getBoolean(SERVER_ENABLE_PROP_NAME, SERVER_ENABLE_DEFAULT); } @Override public String templateResourceContext() { return ConfigurationManager.getConfigInstance().getString(NETFLIX_ADMIN_TEMPLATE_CONTEXT, TEMPLATE_CONTEXT_DEFAULT); } @Override public String ajaxDataResourceContext() { return ConfigurationManager.getConfigInstance().getString(NETFLIX_ADMIN_RESOURCE_CONTEXT, RESOURCE_CONTEXT_DEFAULT); } @Override public String jerseyResourcePkgList() { return ConfigurationManager.getConfigInstance().getString(JERSEY_CORE_RESOURCES, JERSEY_CORE_RESOURCES_DEFAULT); } @Override public String jerseyViewableResourcePkgList() { return ConfigurationManager.getConfigInstance().getString(JERSEY_VIEWABLE_RESOURCES, JERSEY_VIEWABLE_RESOURCES_DEFAULT); } @Override public boolean shouldScanClassPathForPluginDiscovery() { return true; } @Override public int listenPort() { return ConfigurationManager.getConfigInstance().getInt(CONTAINER_LISTEN_PORT, LISTEN_PORT_DEFAULT); } @Override public Map<String, Object> getJerseyConfigProperties() { Map<String, Object> result = new HashMap<>(); Properties props = ConfigurationUtils.getProperties(ConfigurationManager.getConfigInstance().subset(ADMIN_JERSEY_PROPERTY_PREFIX)); for (Entry<Object, Object> prop : props.entrySet()) { result.put(JERSEY_PROPERTY_PREFIX + "." + prop.getKey().toString(), prop.getValue().toString()); } return result; } @Override public List<String> homeScriptResources() { return Collections.emptyList(); } @Override public List<Filter> additionalFilters() { return getInstancesFromClassList( ConfigurationManager.getConfigInstance().getString(NETFLIX_ADMIN_CTX_FILTERS, DEFAULT_CONTEXT_FILTERS), Filter.class); } @Override public List<Connector> additionalConnectors() { return getInstancesFromClassList( ConfigurationManager.getConfigInstance().getString(NETFLIX_ADMIN_CTX_CONNECTORS, DEFAULT_CONTEXT_CONNECTORS), Connector.class); } private <T> List<T> getInstancesFromClassList(String classList, Class<T> clazz) { if (classList.isEmpty()) { return Collections.emptyList(); } List<T> instances = new ArrayList<>(); final String[] classNames = classList.split(","); for (String className : classNames) { try { final Class<?> implClass = Class.forName(className, false, getClass().getClassLoader()); if (clazz.isAssignableFrom(implClass)) { instances.add(clazz.cast(injector == null ? implClass.newInstance() : injector.getInstance(implClass))); } } catch (InstantiationException | IllegalAccessException e) { logger.warn("Class can not be instantiated " + className); } catch (ClassNotFoundException e) { logger.warn("Class not found " + className); } } return instances; } }
3,226
0
Create_ds/karyon/karyon2-admin/src/main/java/netflix
Create_ds/karyon/karyon2-admin/src/main/java/netflix/admin/DefaultGlobalContextOverride.java
package netflix.admin; import java.util.Properties; public class DefaultGlobalContextOverride implements GlobalModelContextOverride { @Override public Properties overrideProperties(Properties properties) { return properties; } }
3,227
0
Create_ds/karyon/karyon2-admin/src/main/java/netflix
Create_ds/karyon/karyon2-admin/src/main/java/netflix/admin/AdminUtils.java
package netflix.admin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class AdminUtils { private static final Logger LOG = LoggerFactory.getLogger(AdminExplorerManager.class); public static Properties loadAdminConsoleProps() { final Properties properties = new Properties(); final InputStream propsResourceStream = AdminUtils.class.getClassLoader().getResourceAsStream("admin-explorers.properties"); if (propsResourceStream != null) { try { properties.load(propsResourceStream); } catch (IOException e) { LOG.error("Exception loading admin console properties file.", e); } } return properties; } }
3,228
0
Create_ds/karyon/karyon2-admin/src/main/java/netflix
Create_ds/karyon/karyon2-admin/src/main/java/netflix/admin/AdminFreemarkerTemplateProvider.java
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package netflix.admin; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.netflix.explorers.ExplorerManager; import com.netflix.explorers.context.GlobalModelContext; import com.netflix.explorers.context.RequestContext; import com.netflix.explorers.providers.ToJsonMethod; import com.sun.jersey.api.view.Viewable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.net.URL; import java.security.Principal; import java.util.HashMap; import java.util.Map; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.ext.MessageBodyWriter; import freemarker.cache.ClassTemplateLoader; import freemarker.cache.MultiTemplateLoader; import freemarker.cache.TemplateLoader; import freemarker.cache.URLTemplateLoader; import freemarker.template.Configuration; import freemarker.template.TemplateModelException; public class AdminFreemarkerTemplateProvider implements MessageBodyWriter<Viewable> { private static final Logger LOG = LoggerFactory.getLogger(AdminFreemarkerTemplateProvider.class); private static final String ADMIN_CONSOLE_LAYOUT = "bootstrap"; private Configuration fmConfig = new Configuration(); private ExplorerManager manager; @Context private ThreadLocal<HttpServletRequest> requestInvoker; class ViewableResourceTemplateLoader extends URLTemplateLoader { static final String KEY_NETFLIX_ADMIN_REQUEST_VIEWABLE = "netflix.admin.request.viewable"; @Override protected URL getURL(String name) { URL viewResource = null; Viewable viewable = (Viewable)requestInvoker.get().getAttribute(ViewableResourceTemplateLoader.KEY_NETFLIX_ADMIN_REQUEST_VIEWABLE); if (viewable != null && viewable.getResolvingClass() != null) { viewResource = viewable.getResolvingClass().getResource(name); } return viewResource; } } @Inject public AdminFreemarkerTemplateProvider(AdminExplorerManager adminExplorerManager) { manager = adminExplorerManager; } @PostConstruct public void commonConstruct() { // Just look for files in the class path fmConfig.setTemplateLoader(new MultiTemplateLoader(new TemplateLoader[]{ new ViewableResourceTemplateLoader(), new ClassTemplateLoader(getClass(), "/"), })); fmConfig.setNumberFormat("0"); fmConfig.setLocalizedLookup(false); fmConfig.setTemplateUpdateDelay(0); try { if (manager != null) { fmConfig.setSharedVariable("Global", manager.getGlobalModel()); fmConfig.setSharedVariable("Explorers", manager); } fmConfig.setSharedVariable("toJson", new ToJsonMethod()); } catch (TemplateModelException e) { throw new RuntimeException(e); } } @Override public long getSize(Viewable t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return !(!(mediaType.isCompatible(MediaType.TEXT_HTML_TYPE) || mediaType.isCompatible(MediaType.APPLICATION_XHTML_XML_TYPE)) || !Viewable.class.isAssignableFrom(type)); } /** * Write the HTML by invoking the FTL template * <p/> * Variables accessibile to the template * <p/> * it - The 'model' provided by the controller * Explorer - IExplorerModule reference * Explorers - Map of all explorer modules * Global - Global variables from the ExploreModule manager * Request - The HTTPRequestHandler * Instance - Information about the running instance * Headers - HTTP headers * Parameters - HTTP parameters */ @SuppressWarnings({"unchecked"}) @Override public void writeTo(Viewable viewable, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream out) throws IOException, WebApplicationException { String resolvedPath = viewable.getTemplateName(); Object model = viewable.getModel(); LOG.debug("Evaluating freemarker template (" + resolvedPath + ") with model of type " + (model == null ? "null" : model.getClass().getSimpleName())); // Build the model context that will be passed to the page final Map<String, Object> vars; if (model instanceof Map) { vars = new HashMap<>((Map<String, Object>) model); } else { vars = new HashMap<>(); vars.put("it", model); } RequestContext requestContext = new RequestContext(); HttpServletRequest httpServletRequest = requestInvoker != null ? requestInvoker.get() : null; requestContext.setHttpServletRequest(httpServletRequest ); vars.put("RequestContext", requestContext); vars.put("Request", httpServletRequest); if (httpServletRequest != null && viewable.getResolvingClass() != null) { httpServletRequest.setAttribute(ViewableResourceTemplateLoader.KEY_NETFLIX_ADMIN_REQUEST_VIEWABLE, viewable); } Principal ctx = null; if (httpServletRequest != null) { ctx = httpServletRequest.getUserPrincipal(); if (ctx == null && httpServletRequest.getSession(false) != null) { final String username = (String) httpServletRequest.getSession().getAttribute("SSO_UserName"); if (username != null) { ctx = new Principal() { @Override public String getName() { return username; } }; } } } vars.put("Principal", ctx); // The following are here for backward compatibility and should be deprecated as soon as possible Map<String, Object> global = Maps.newHashMap(); if (manager != null) { GlobalModelContext globalModel = manager.getGlobalModel(); global.put("sysenv", globalModel.getEnvironment()); // TODO: DEPRECATE vars.put("Explorer", manager.getExplorer(AdminExplorerManager.ADMIN_EXPLORER_NAME)); } vars.put("global", global); // TODO: DEPRECATE vars.put("pathToRoot", requestContext.getPathToRoot()); // TODO: DEPRECATE final StringWriter stringWriter = new StringWriter(); try { if (requestContext.getIsAjaxRequest()) { fmConfig.getTemplate(resolvedPath).process(vars, stringWriter); } else { vars.put("nestedpage", resolvedPath); fmConfig.getTemplate("/layout/" + ADMIN_CONSOLE_LAYOUT + "/main.ftl").process(vars, stringWriter); } final OutputStreamWriter writer = new OutputStreamWriter(out); writer.write(stringWriter.getBuffer().toString()); writer.flush(); } catch (Throwable t) { LOG.error("Error processing freemarker template @ " + resolvedPath + ": " + t.getMessage(), t); throw new WebApplicationException(t, Response.Status.INTERNAL_SERVER_ERROR); } } }
3,229
0
Create_ds/karyon/karyon2-admin/src/main/java/netflix
Create_ds/karyon/karyon2-admin/src/main/java/netflix/admin/GlobalModelContextOverride.java
package netflix.admin; import com.google.inject.ImplementedBy; import java.util.Properties; @ImplementedBy(DefaultGlobalContextOverride.class) public interface GlobalModelContextOverride { Properties overrideProperties(Properties properties); }
3,230
0
Create_ds/karyon/karyon2-admin/src/main/java/netflix
Create_ds/karyon/karyon2-admin/src/main/java/netflix/admin/AdminExplorerManager.java
package netflix.admin; import com.google.common.base.Supplier; import com.google.inject.Inject; import com.google.inject.Singleton; import com.netflix.explorers.AbstractExplorerModule; import com.netflix.explorers.Explorer; import com.netflix.explorers.ExplorerManager; import com.netflix.explorers.PropertiesGlobalModelContext; import com.netflix.explorers.context.GlobalModelContext; import org.apache.commons.configuration.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; import java.util.Collection; import java.util.Collections; import java.util.Properties; import java.util.Set; @Singleton public class AdminExplorerManager implements ExplorerManager { private static final Logger LOG = LoggerFactory.getLogger(AdminExplorerManager.class); public static final String ADMIN_EXPLORER_NAME = "baseserver"; public static class AdminResourceExplorer extends AbstractExplorerModule { public AdminResourceExplorer() { super(ADMIN_EXPLORER_NAME); } } private PropertiesGlobalModelContext propertiesGlobalModelContext; private AdminResourceExplorer adminExplorer; @Inject private GlobalModelContextOverride globalModelContextOverride; @PostConstruct @Override public void initialize() { Properties properties = AdminUtils.loadAdminConsoleProps(); if (globalModelContextOverride != null) { properties = globalModelContextOverride.overrideProperties(properties); } propertiesGlobalModelContext = new PropertiesGlobalModelContext(properties); adminExplorer = new AdminResourceExplorer(); adminExplorer.initialize(); } @Override public void shutdown() { } @Override public String getDefaultModule() { return null; } @Override public void registerExplorer(Explorer module) { } @Override public void unregisterExplorer(Explorer module) { } @Override public void registerExplorerFromClassName(String className) throws Exception { } @Override public Explorer getExplorer(String name) { if (name.equals(ADMIN_EXPLORER_NAME)) { return adminExplorer; } throw new IllegalArgumentException("AdminExplorerManager called with explorerName = " + name); } @Override public Collection<Explorer> getExplorers() { return Collections.emptyList(); } @Override public GlobalModelContext getGlobalModel() { return propertiesGlobalModelContext; } @Override public Configuration getConfiguration() { return null; } @Override public void registerExplorersFromClassNames(Set<String> classNames) { } @Override public <T> T getService(Class<T> className) { return null; } @Override public <T> void registerService(Class<T> serviceClass, T instance) { } @Override public <T> void registerService(Class<T> serviceClass, Supplier<T> supplier) { } @Override public <T> void registerService(Class<T> serviceClass, Class<? extends T> serviceImplClassName) { } @Override public boolean getHasAuthProvider() { return false; } }
3,231
0
Create_ds/karyon/karyon2-admin/src/main/java/netflix
Create_ds/karyon/karyon2-admin/src/main/java/netflix/admin/RedirectRules.java
package netflix.admin; import com.google.inject.ImplementedBy; import javax.servlet.http.HttpServletRequest; import java.util.Map; @ImplementedBy(DefaultRedirectRules.class) public interface RedirectRules { Map<String, String> getMappings(); String getRedirect(HttpServletRequest httpServletRequest); }
3,232
0
Create_ds/karyon/karyon2-admin/src/main/java/netflix
Create_ds/karyon/karyon2-admin/src/main/java/netflix/admin/AdminContainerConfig.java
package netflix.admin; import java.util.List; import java.util.Map; import javax.servlet.Filter; import com.google.inject.ImplementedBy; import org.mortbay.jetty.Connector; @ImplementedBy(AdminConfigImpl.class) public interface AdminContainerConfig { boolean shouldIsolateResources(); boolean shouldEnable(); String templateResourceContext(); String ajaxDataResourceContext(); String jerseyResourcePkgList(); String jerseyViewableResourcePkgList(); boolean shouldScanClassPathForPluginDiscovery(); int listenPort(); List<Filter> additionalFilters(); List<Connector> additionalConnectors(); Map<String, Object> getJerseyConfigProperties(); List<String> homeScriptResources(); }
3,233
0
Create_ds/karyon/karyon2-servo/src/main/java/netflix/karyon
Create_ds/karyon/karyon2-servo/src/main/java/netflix/karyon/servo/KaryonServoModule.java
package netflix.karyon.servo; import com.google.inject.AbstractModule; import com.netflix.governator.guice.BootstrapModule; import io.reactivex.netty.RxNetty; import io.reactivex.netty.servo.ServoEventsListenerFactory; import netflix.karyon.Karyon; /** * Register global RxNetty's Metric Listeners Factory to use Servo. * * @author Nitesh Kant */ public class KaryonServoModule extends AbstractModule { @Override protected void configure() { RxNetty.useMetricListenersFactory(new ServoEventsListenerFactory()); } public static BootstrapModule asBootstrapModule() { return Karyon.toBootstrapModule(KaryonServoModule.class); } }
3,234
0
Create_ds/karyon/karyon2-governator/src/test/java/netflix/karyon/transport
Create_ds/karyon/karyon2-governator/src/test/java/netflix/karyon/transport/tcp/KaryonTcpModuleTest.java
package netflix.karyon.transport.tcp; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; import com.netflix.governator.guice.LifecycleInjector; import com.netflix.governator.lifecycle.LifecycleManager; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.MessageToMessageCodec; import io.reactivex.netty.RxNetty; import io.reactivex.netty.channel.ConnectionHandler; import io.reactivex.netty.channel.ObservableConnection; import io.reactivex.netty.pipeline.PipelineConfigurator; import io.reactivex.netty.server.RxServer; import org.junit.After; import org.junit.Before; import org.junit.Test; import rx.Observable; import rx.functions.Func1; import java.nio.charset.Charset; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; /** * @author Tomasz Bak */ public class KaryonTcpModuleTest { private static final Key<Map<String, RxServer>> RX_SERVERS_KEY = Key.get(new TypeLiteral<Map<String, RxServer>>() { }); private static final String SERVER_MESSAGE = "Hello"; private Injector injector; private LifecycleManager lifecycleManager; private RxServer server; @Before public void setUp() throws Exception { injector = LifecycleInjector.bootstrap(TestableTcpModule.class); lifecycleManager = injector.getInstance(LifecycleManager.class); lifecycleManager.start(); server = injector.getInstance(RX_SERVERS_KEY).values().iterator().next(); } @After public void tearDown() throws Exception { if (lifecycleManager != null) { lifecycleManager.close(); } } @Test public void testGovernatedTcpServer() throws Exception { String message = RxNetty.createTcpClient("localhost", server.getServerPort()).connect() .flatMap(new Func1<ObservableConnection<ByteBuf, ByteBuf>, Observable<String>>() { @Override public Observable<String> call(ObservableConnection<ByteBuf, ByteBuf> connection) { return connection.getInput().map(new Func1<ByteBuf, String>() { @Override public String call(ByteBuf byteBuf) { return byteBuf.toString(Charset.defaultCharset()); } }); } }).single().toBlocking().toFuture().get(60, TimeUnit.SECONDS); assertEquals("Invalid message received from server", SERVER_MESSAGE, message); } public static class TestableTcpModule extends KaryonTcpModule<String, String> { public TestableTcpModule() { super("testTcpModule", String.class, String.class); } @Override protected void configureServer() { bindPipelineConfigurator().to(StringCodecPipelineConfigurator.class); bindConnectionHandler().to(TestableConnectionHandler.class); server().port(0); } } private static class TestableConnectionHandler implements ConnectionHandler<String, String> { @Override public Observable<Void> handle(ObservableConnection<String, String> connection) { return connection.writeAndFlush(SERVER_MESSAGE); } } public static class StringCodecPipelineConfigurator implements PipelineConfigurator<ByteBuf, String> { @Override public void configureNewPipeline(ChannelPipeline pipeline) { pipeline.addLast(new MessageToMessageCodec<ByteBuf, String>() { @Override protected void encode(ChannelHandlerContext ctx, String msg, List<Object> out) throws Exception { out.add(Unpooled.copiedBuffer(msg, Charset.defaultCharset())); } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception { out.add(msg.toString(Charset.defaultCharset())); } }); } } }
3,235
0
Create_ds/karyon/karyon2-governator/src/test/java/netflix/karyon/transport
Create_ds/karyon/karyon2-governator/src/test/java/netflix/karyon/transport/http/KaryonHttpModuleTest.java
package netflix.karyon.transport.http; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; import com.netflix.governator.guice.LifecycleInjector; import com.netflix.governator.lifecycle.LifecycleManager; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpResponseStatus; import io.reactivex.netty.RxNetty; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.server.RequestHandler; import io.reactivex.netty.server.RxServer; import netflix.karyon.transport.interceptor.DuplexInterceptor; import org.junit.After; import org.junit.Before; import org.junit.Test; import rx.Observable; import rx.functions.Func1; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertEquals; /** * @author Tomasz Bak */ public class KaryonHttpModuleTest { private static final Key<Map<String, RxServer>> RX_SERVERS_KEY = Key.get(new TypeLiteral<Map<String, RxServer>>() { }); private Injector injector; private LifecycleManager lifecycleManager; private RxServer server; @Before public void setUp() throws Exception { injector = LifecycleInjector.bootstrap(TestableHttpModule.class); lifecycleManager = injector.getInstance(LifecycleManager.class); lifecycleManager.start(); server = injector.getInstance(RX_SERVERS_KEY).values().iterator().next(); } @After public void tearDown() throws Exception { if (lifecycleManager != null) { lifecycleManager.close(); } } @Test public void testHttpRouterAndInterceptorSupport() throws Exception { int counterInitial = CountingInterceptor.counter.get(); HttpResponseStatus status = sendRequest("/sendOK", server); assertEquals("Expected HTTP 200", HttpResponseStatus.OK, status); status = sendRequest("/sendNotFound", server); assertEquals("Expected HTTP NOT_FOUND", HttpResponseStatus.NOT_FOUND, status); int counterFinal = CountingInterceptor.counter.get(); assertEquals("Invalid number of counting interceptor invocations", 4, counterFinal - counterInitial); } private HttpResponseStatus sendRequest(String path, RxServer server) throws Exception { return (HttpResponseStatus) RxNetty.createHttpGet("http://localhost:" + server.getServerPort() + path) .flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<?>>() { @Override public Observable<HttpResponseStatus> call(HttpClientResponse<ByteBuf> httpClientResponse) { return Observable.just(httpClientResponse.getStatus()); } }).single().toBlocking().toFuture().get(60, TimeUnit.SECONDS); } public static class TestableRequestRouter implements RequestHandler<ByteBuf, ByteBuf> { @Override public Observable<Void> handle(HttpServerRequest<ByteBuf> request, HttpServerResponse<ByteBuf> response) { if (request.getPath().contains("/sendOK")) { response.setStatus(HttpResponseStatus.OK); } else if (request.getPath().contains("/sendNotFound")) { response.setStatus(HttpResponseStatus.NOT_FOUND); } else { response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR); } return Observable.empty(); } } public static class TestableHttpModule extends KaryonHttpModule<ByteBuf, ByteBuf> { public TestableHttpModule() { super("testableHttpModule", ByteBuf.class, ByteBuf.class); } @Override protected void configureServer() { bindRouter().to(TestableRequestRouter.class); interceptorSupport().forHttpMethod(HttpMethod.GET).intercept(CountingInterceptor.class); server().port(0); } } public static class CountingInterceptor implements DuplexInterceptor<HttpServerRequest<ByteBuf>, HttpServerResponse<ByteBuf>> { static AtomicInteger counter = new AtomicInteger(); @Override public Observable<Void> in(HttpServerRequest<ByteBuf> request, HttpServerResponse<ByteBuf> response) { counter.incrementAndGet(); return Observable.empty(); } @Override public Observable<Void> out(HttpServerResponse<ByteBuf> response) { counter.incrementAndGet(); return Observable.empty(); } } }
3,236
0
Create_ds/karyon/karyon2-governator/src/test/java/netflix/karyon/transport/http
Create_ds/karyon/karyon2-governator/src/test/java/netflix/karyon/transport/http/websockets/KaryonWebSocketsModuleTest.java
package netflix.karyon.transport.http.websockets; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; import com.netflix.governator.guice.LifecycleInjector; import com.netflix.governator.lifecycle.LifecycleManager; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.reactivex.netty.RxNetty; import io.reactivex.netty.channel.ConnectionHandler; import io.reactivex.netty.channel.ObservableConnection; import io.reactivex.netty.server.RxServer; import org.junit.After; import org.junit.Before; import org.junit.Test; import rx.Observable; import rx.functions.Func1; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; /** * @author Tomasz Bak */ public class KaryonWebSocketsModuleTest { private static final Key<Map<String, RxServer>> RX_SERVERS_KEY = Key.get(new TypeLiteral<Map<String, RxServer>>() { }); private static final String SERVER_MESSAGE = "Hello"; private Injector injector; private LifecycleManager lifecycleManager; private RxServer server; @Before public void setUp() throws Exception { injector = LifecycleInjector.bootstrap(TestableWebSocketsModule.class); lifecycleManager = injector.getInstance(LifecycleManager.class); lifecycleManager.start(); server = injector.getInstance(RX_SERVERS_KEY).values().iterator().next(); } @After public void tearDown() throws Exception { if (lifecycleManager != null) { lifecycleManager.close(); } } @Test public void testGovernatedTcpServer() throws Exception { String message = RxNetty.<TextWebSocketFrame, TextWebSocketFrame>newWebSocketClientBuilder("localhost", server.getServerPort()) .build() .connect() .flatMap(new Func1<ObservableConnection<TextWebSocketFrame, TextWebSocketFrame>, Observable<String>>() { @Override public Observable<String> call(ObservableConnection<TextWebSocketFrame, TextWebSocketFrame> connection) { return connection.getInput().map(new Func1<TextWebSocketFrame, String>() { @Override public String call(TextWebSocketFrame frame) { return frame.text(); } }); } }).single().toBlocking().toFuture().get(60, TimeUnit.SECONDS); assertEquals("Invalid message received from server", SERVER_MESSAGE, message); } public static class TestableWebSocketsModule extends KaryonWebSocketsModule<TextWebSocketFrame, TextWebSocketFrame> { public TestableWebSocketsModule() { super("testWebSocketsModule", TextWebSocketFrame.class, TextWebSocketFrame.class); } @Override protected void configureServer() { bindConnectionHandler().to(TestableConnectionHandler.class); server().port(0); } } private static class TestableConnectionHandler implements ConnectionHandler<TextWebSocketFrame, TextWebSocketFrame> { @Override public Observable<Void> handle(ObservableConnection<TextWebSocketFrame, TextWebSocketFrame> newConnection) { return newConnection.writeAndFlush(new TextWebSocketFrame(SERVER_MESSAGE)); } } }
3,237
0
Create_ds/karyon/karyon2-governator/src/main/java/netflix
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/KaryonServerBackedServer.java
package netflix.karyon; import com.netflix.governator.guice.BootstrapModule; /** * An implementation of {@link KaryonServer} which wraps an existing {@link KaryonServer}. * * @author Nitesh Kant * @deprecated 2016-07-20 Karyon2 no longer supported. See https://github.com/Netflix/karyon/issues/347 for more info */ @Deprecated class KaryonServerBackedServer implements KaryonServer { private final AbstractKaryonServer delegate; private final BootstrapModule[] bootstrapModules; KaryonServerBackedServer(AbstractKaryonServer delegate, BootstrapModule... bootstrapModules) { this.delegate = delegate; this.bootstrapModules = bootstrapModules; } @Override public void start() { delegate.startWithAdditionalBootstrapModules(bootstrapModules); } @Override public void shutdown() { delegate.shutdown(); } @Override public void waitTillShutdown() { delegate.waitTillShutdown(); } @Override public void startAndWaitTillShutdown() { start(); waitTillShutdown(); } }
3,238
0
Create_ds/karyon/karyon2-governator/src/main/java/netflix
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/ShutdownModule.java
package netflix.karyon; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.binder.LinkedBindingBuilder; import com.google.inject.name.Named; import com.google.inject.name.Names; import com.netflix.governator.guice.BootstrapModule; import com.netflix.governator.lifecycle.LifecycleManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.functions.Action0; import javax.annotation.PostConstruct; /** * Provide shutdown listener as Governator managed service. Default shutdown action * destroys Governator container. A user can provide additional actions to be run * either before or after the container shutdown. * * @author Tomasz Bak * @deprecated 2016-07-20 Karyon2 no longer supported. See https://github.com/Netflix/karyon/issues/347 for more info */ @Deprecated public class ShutdownModule extends AbstractModule { public static final int DEFAULT_PORT = 7002; private final int port; @Inject public ShutdownModule() { port = DEFAULT_PORT; } protected ShutdownModule(int port) { this.port = port; } @Override protected void configure() { bind(Integer.class).annotatedWith(Names.named("shutdownPort")).toInstance(port); bind(ShutdownServer.class).asEagerSingleton(); } protected LinkedBindingBuilder<Action0> bindBeforeShutdownAction() { return bind(Action0.class).annotatedWith(Names.named("beforeShutdownAction")); } protected LinkedBindingBuilder<Action0> bindAfterShutdownAction() { return bind(Action0.class).annotatedWith(Names.named("afterShutdownAction")); } public static BootstrapModule asBootstrapModule() { return asBootstrapModule(7002); } public static BootstrapModule asBootstrapModule(final int port) { return Karyon.toBootstrapModule(new ShutdownModule(port)); } @Singleton public static class ShutdownServer { private static final Logger logger = LoggerFactory.getLogger(ShutdownServer.class); @Inject @Named("shutdownPort") private int port; @Inject(optional = true) @Named("beforeShutdownAction") private Action0 beforeAction; @Inject(optional = true) @Named("afterShutdownAction") private Action0 afterAction; @Inject private LifecycleManager lifeCycleManager; private ShutdownListener shutdownListener; @PostConstruct public void start() { shutdownListener = new ShutdownListener(port, new Action0() { @Override public void call() { logger.info("Shutdown request received on port {}; stopping all services...", port); try { runShutdownCommands(); } catch (Exception e) { logger.error("Errors during shutdown", e); } finally { try { shutdownListener.shutdown(); } catch (Exception e) { logger.error("Errors during stopping shutdown listener", e); } } } }); shutdownListener.start(); } private void runShutdownCommands() { try { if (beforeAction != null) { beforeAction.call(); } } finally { try { lifeCycleManager.close(); } finally { if (afterAction != null) { afterAction.call(); } } } } } }
3,239
0
Create_ds/karyon/karyon2-governator/src/main/java/netflix
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/KaryonRunner.java
package netflix.karyon; import com.netflix.governator.guice.BootstrapModule; import com.netflix.governator.guice.annotations.Bootstrap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * An application runner which consumes a main class annotated with governator's {@link Bootstrap} annotations. * * This is shorthand for: * <PRE> com.netflix.karyon.forApplication(MyApp.class).startAndWaitTillShutdown() </PRE> * * where the name of the Application class is passed as the argument to the main method. * * This is useful while creating standard packaging scripts where the main class for starting the JVM remains the same * and the actual application class differs from one application to another. * * If you are bootstrapping karyon programmatically, it is better to use {@code Karyon} directly. * * @author Nitesh Kant * @deprecated 2016-07-20 Karyon2 no longer supported. See https://github.com/Netflix/karyon/issues/347 for more info */ @Deprecated public class KaryonRunner { private static final Logger logger = LoggerFactory.getLogger(KaryonRunner.class); public static void main(String[] args) { if (args.length == 0) { System.out.println("Usage: " + KaryonRunner.class.getCanonicalName() + " <main classs name>"); System.exit(-1); } String mainClassName = args[0]; System.out.println("Using main class: " + mainClassName); try { Karyon.forApplication(Class.forName(mainClassName), (BootstrapModule[]) null) .startAndWaitTillShutdown(); } catch (@SuppressWarnings("UnusedCatchParameter") ClassNotFoundException e) { System.out.println("Main class: " + mainClassName + " not found."); System.exit(-1); } catch (Exception e) { logger.error("Error while starting karyon server.", e); System.exit(-1); } // In case we have non-daemon threads running System.exit(0); } }
3,240
0
Create_ds/karyon/karyon2-governator/src/main/java/netflix
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/KaryonBootstrap.java
package netflix.karyon; import com.netflix.governator.guice.annotations.Bootstrap; import netflix.karyon.health.AlwaysHealthyHealthCheck; import netflix.karyon.health.HealthCheckHandler; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author Nitesh Kant * @deprecated 2016-07-20 Karyon2 no longer supported. See https://github.com/Netflix/karyon/issues/347 for more info */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Bootstrap(bootstrap = KaryonBootstrapModule.class) @Deprecated public @interface KaryonBootstrap { String name(); Class<? extends HealthCheckHandler> healthcheck() default AlwaysHealthyHealthCheck.class; }
3,241
0
Create_ds/karyon/karyon2-governator/src/main/java/netflix
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/KaryonBootstrapModule.java
package netflix.karyon; import com.google.inject.AbstractModule; import com.google.inject.binder.AnnotatedBindingBuilder; import com.google.inject.binder.LinkedBindingBuilder; import com.netflix.governator.guice.*; import netflix.karyon.health.AlwaysHealthyHealthCheck; import netflix.karyon.health.HealthCheckHandler; import netflix.karyon.health.HealthCheckInvocationStrategy; import netflix.karyon.health.SyncHealthCheckInvocationStrategy; import javax.inject.Inject; /** * A guice module that defines all bindings required by karyon. Applications must use this to bootstrap karyon. * * @author Nitesh Kant * @deprecated 2016-07-20 Karyon2 no longer supported. See https://github.com/Netflix/karyon/issues/347 for more info */ @Deprecated public class KaryonBootstrapModule implements BootstrapModule { private final Class<? extends HealthCheckHandler> healthcheckHandlerClass; private final HealthCheckHandler healthcheckHandler; private final KaryonBootstrap karyonBootstrap; public KaryonBootstrapModule() { this((HealthCheckHandler)null); } public KaryonBootstrapModule(HealthCheckHandler healthcheckHandler) { this.healthcheckHandler = null == healthcheckHandler ? new AlwaysHealthyHealthCheck() : healthcheckHandler; this.healthcheckHandlerClass = null; this.karyonBootstrap = null; } public KaryonBootstrapModule(Class<? extends HealthCheckHandler> healthcheckHandlerClass) { this.healthcheckHandler = null; this.healthcheckHandlerClass = healthcheckHandlerClass; this.karyonBootstrap = null; } @Inject KaryonBootstrapModule(KaryonBootstrap karyonBootstrap) { this.karyonBootstrap = karyonBootstrap; this.healthcheckHandlerClass = karyonBootstrap.healthcheck(); this.healthcheckHandler = null; } @Override public void configure(BootstrapBinder bootstrapBinder) { bootstrapBinder.inMode(LifecycleInjectorMode.SIMULATED_CHILD_INJECTORS); bootstrapBinder.include(new AbstractModule() { @Override protected void configure() { bindHealthCheck(bind(HealthCheckHandler.class)); bindHealthCheckInvocationStrategy(bind(HealthCheckInvocationStrategy.class)); } }); } private static void bindHealthCheckInvocationStrategy(AnnotatedBindingBuilder<HealthCheckInvocationStrategy> bindingBuilder) { bindingBuilder.to(SyncHealthCheckInvocationStrategy.class); } protected void bindHealthCheck(LinkedBindingBuilder<HealthCheckHandler> bindingBuilder) { if (null != healthcheckHandlerClass) { bindingBuilder.to(healthcheckHandlerClass); } else { bindingBuilder.toInstance(healthcheckHandler); } } }
3,242
0
Create_ds/karyon/karyon2-governator/src/main/java/netflix
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/KaryonServer.java
package netflix.karyon; /** * A logical abstraction to manage the lifecycle of a karyon based application. * This does not define any contracts of handling and processing requests, those should all be defined by means of * modules. * @deprecated 2016-07-20 Karyon2 no longer supported. See https://github.com/Netflix/karyon/issues/347 for more info */ @Deprecated public interface KaryonServer { /** * Starts the server and hence the modules associated with this server. */ void start(); /** * Shutdown the server and hence the modules associated with this server. */ void shutdown(); /** * A utility method to block the caller thread till the server is shutdown (by external invocation). * <b>This method does not start or shutdown the server. It just waits for shutdown.</b> */ void waitTillShutdown(); /** * A shorthand for calling {@link #start()} and {@link #waitTillShutdown()} */ void startAndWaitTillShutdown(); }
3,243
0
Create_ds/karyon/karyon2-governator/src/main/java/netflix
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/Karyon.java
package netflix.karyon; import com.google.common.collect.Lists; import com.google.inject.Module; import com.netflix.governator.guice.BootstrapBinder; import com.netflix.governator.guice.BootstrapModule; import com.netflix.governator.guice.annotations.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.websocketx.WebSocketFrame; import io.reactivex.netty.RxNetty; import io.reactivex.netty.channel.ConnectionHandler; import io.reactivex.netty.protocol.http.server.HttpServer; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.server.RequestHandler; import io.reactivex.netty.protocol.udp.server.UdpServer; import io.reactivex.netty.server.RxServer; import netflix.karyon.transport.KaryonTransport; import netflix.karyon.transport.http.HttpRequestHandler; import rx.Observable; /** * An entry point into karyon to create various flavors of karyon servers. For applications using governator's * {@link Bootstrap} annotations it is easier to use {@link KaryonRunner} passing the main class containing all the * {@link Bootstrap} annotations. * * @author Nitesh Kant * @deprecated 2016-07-20 Karyon2 no longer supported. See https://github.com/Netflix/karyon/issues/347 for more info */ @Deprecated public final class Karyon { private Karyon() { } /** * Creates a new {@link KaryonServer} that has a single HTTP server instance which delegates all request * handling to {@link RequestHandler}. * The {@link HttpServer} is created using {@link KaryonTransport#newHttpServer(int, HttpRequestHandler)} * * @param port Port for the server. * @param handler Request Handler * @param modules Additional modules if any. * * @return {@link KaryonServer} which is to be used to start the created server. */ public static KaryonServer forRequestHandler(int port, final RequestHandler<ByteBuf, ByteBuf> handler, Module... modules) { return forRequestHandler(port, handler, toBootstrapModule(modules)); } /** * Creates a new {@link KaryonServer} that has a single HTTP server instance which delegates all request * handling to {@link RequestHandler}. * The {@link HttpServer} is created using {@link KaryonTransport#newHttpServer(int, HttpRequestHandler)} * * @param port Port for the server. * @param handler Request Handler * @param bootstrapModules Additional bootstrapModules if any. * * @return {@link KaryonServer} which is to be used to start the created server. */ public static KaryonServer forRequestHandler(int port, final RequestHandler<ByteBuf, ByteBuf> handler, BootstrapModule... bootstrapModules) { HttpServer<ByteBuf, ByteBuf> httpServer = KaryonTransport.newHttpServer(port, new RequestHandler<ByteBuf, ByteBuf>() { @Override public Observable<Void> handle(HttpServerRequest<ByteBuf> request, HttpServerResponse<ByteBuf> response) { return handler.handle(request, response); } }); return new RxNettyServerBackedServer(httpServer, bootstrapModules); } /** * Creates a new {@link KaryonServer} that has a single TCP server instance which delegates all connection * handling to {@link ConnectionHandler}. * The {@link RxServer} is created using {@link RxNetty#newTcpServerBuilder(int, ConnectionHandler)} * * @param port Port for the server. * @param handler Connection Handler * @param modules Additional modules if any. * * @return {@link KaryonServer} which is to be used to start the created server. */ public static KaryonServer forTcpConnectionHandler(int port, ConnectionHandler<ByteBuf, ByteBuf> handler, Module... modules) { return forTcpConnectionHandler(port, handler, toBootstrapModule(modules)); } /** * Creates a new {@link KaryonServer} that has a single TCP server instance which delegates all connection * handling to {@link ConnectionHandler}. * The {@link RxServer} is created using {@link RxNetty#newTcpServerBuilder(int, ConnectionHandler)} * * @param port Port for the server. * @param handler Connection Handler * @param bootstrapModules Additional bootstrapModules if any. * * @return {@link KaryonServer} which is to be used to start the created server. */ public static KaryonServer forTcpConnectionHandler(int port, ConnectionHandler<ByteBuf, ByteBuf> handler, BootstrapModule... bootstrapModules) { RxServer<ByteBuf, ByteBuf> server = RxNetty.newTcpServerBuilder(port, handler).build(); return new RxNettyServerBackedServer(server, bootstrapModules); } /** * Creates a new {@link KaryonServer} that has a single UDP server instance which delegates all connection * handling to {@link ConnectionHandler}. * The {@link RxServer} is created using {@link RxNetty#newUdpServerBuilder(int, ConnectionHandler)} * * @param port Port for the server. * @param handler Connection Handler * @param modules Additional modules if any. * * @return {@link KaryonServer} which is to be used to start the created server. */ public static KaryonServer forUdpConnectionHandler(int port, ConnectionHandler<ByteBuf, ByteBuf> handler, Module... modules) { return forUdpConnectionHandler(port, handler, toBootstrapModule(modules)); } /** * Creates a new {@link KaryonServer} that has a single UDP server instance which delegates all connection * handling to {@link ConnectionHandler}. * The {@link RxServer} is created using {@link RxNetty#newUdpServerBuilder(int, ConnectionHandler)} * * @param port Port for the server. * @param handler Connection Handler * @param bootstrapModules Additional bootstrapModules if any. * * @return {@link KaryonServer} which is to be used to start the created server. */ public static KaryonServer forUdpConnectionHandler(int port, ConnectionHandler<ByteBuf, ByteBuf> handler, BootstrapModule... bootstrapModules) { UdpServer<ByteBuf, ByteBuf> server = RxNetty.newUdpServerBuilder(port, handler).build(); return new RxNettyServerBackedServer(server, bootstrapModules); } /** * Creates a new {@link KaryonServer} which combines lifecycle of the passed {@link RxServer} with * it's own lifecycle. * * @param server TCP server * @param modules Additional modules if any. * * @return {@link KaryonServer} which is to be used to start the created server. */ public static KaryonServer forTcpServer(RxServer<?, ?> server, Module... modules) { return forTcpServer(server, toBootstrapModule(modules)); } /** * Creates a new {@link KaryonServer} which combines lifecycle of the passed {@link RxServer} with * it's own lifecycle. * * @param server TCP server * @param bootstrapModules Additional bootstrapModules if any. * * @return {@link KaryonServer} which is to be used to start the created server. */ public static KaryonServer forTcpServer(RxServer<?, ?> server, BootstrapModule... bootstrapModules) { return new RxNettyServerBackedServer(server, bootstrapModules); } /** * Creates a new {@link KaryonServer} which combines lifecycle of the passed {@link HttpServer} with * it's own lifecycle. * * @param server HTTP server * @param modules Additional bootstrapModules if any. * * @return {@link KaryonServer} which is to be used to start the created server. */ public static KaryonServer forHttpServer(HttpServer<?, ?> server, Module... modules) { return forHttpServer(server, toBootstrapModule(modules)); } /** * Creates a new {@link KaryonServer} which combines lifecycle of the passed {@link HttpServer} with * it's own lifecycle. * * @param server HTTP server * @param bootstrapModules Additional bootstrapModules if any. * * @return {@link KaryonServer} which is to be used to start the created server. */ public static KaryonServer forHttpServer(HttpServer<?, ?> server, BootstrapModule... bootstrapModules) { return new RxNettyServerBackedServer(server, bootstrapModules); } /** * Creates a new {@link KaryonServer} which combines lifecycle of the passed WebSockets {@link RxServer} with * it's own lifecycle. * * @param server WebSocket server * @param modules Additional bootstrapModules if any. * * @return {@link KaryonServer} which is to be used to start the created server. */ public static KaryonServer forWebSocketServer(RxServer<? extends WebSocketFrame, ? extends WebSocketFrame> server, Module... modules) { return forWebSocketServer(server, toBootstrapModule(modules)); } /** * Creates a new {@link KaryonServer} which combines lifecycle of the passed WebSockets {@link RxServer} with * it's own lifecycle. * * @param server WebSocket server * @param bootstrapModules Additional bootstrapModules if any. * * @return {@link KaryonServer} which is to be used to start the created server. */ public static KaryonServer forWebSocketServer(RxServer<? extends WebSocketFrame, ? extends WebSocketFrame> server, BootstrapModule... bootstrapModules) { return new RxNettyServerBackedServer(server, bootstrapModules); } /** * Creates a new {@link KaryonServer} which combines lifecycle of the passed {@link UdpServer} with * it's own lifecycle. * * @param server UDP server * @param modules Additional modules if any. * * @return {@link KaryonServer} which is to be used to start the created server. */ public static KaryonServer forUdpServer(UdpServer<?, ?> server, Module... modules) { return forUdpServer(server, toBootstrapModule(modules)); } /** * Creates a new {@link KaryonServer} which combines lifecycle of the passed {@link UdpServer} with * it's own lifecycle. * * @param server UDP server * @param bootstrapModules Additional bootstrapModules if any. * * @return {@link KaryonServer} which is to be used to start the created server. */ public static KaryonServer forUdpServer(UdpServer<?, ?> server, BootstrapModule... bootstrapModules) { return new RxNettyServerBackedServer(server, bootstrapModules); } /** * Creates a new {@link KaryonServer} which combines lifecycle of the passed {@link KaryonServer} with * it's own lifecycle. This is useful when a {@link KaryonServer} is already present and the passed * {@link Module}s are to be added to that server. * * @param server An existing karyon server * @param modules Additional modules. * * @return {@link KaryonServer} which is to be used to start the created server. */ public static KaryonServer forServer(KaryonServer server, Module... modules) { return forServer(server, toBootstrapModule(modules)); } /** * Creates a new {@link KaryonServer} which combines lifecycle of the passed {@link KaryonServer} with * it's own lifecycle. This is useful when a {@link KaryonServer} is already present and the passed * {@link BootstrapModule}s are to be added to that server. * * @param server An existing karyon server * @param bootstrapModules Additional bootstrapModules. * * @return {@link KaryonServer} which is to be used to start the created server. */ public static KaryonServer forServer(KaryonServer server, BootstrapModule... bootstrapModules) { return new KaryonServerBackedServer((AbstractKaryonServer)server, bootstrapModules); } /** * Creates a new {@link KaryonServer} which uses the passed class to detect any modules. * * @param mainClass Any class/interface containing governator's {@link Bootstrap} annotations. * @param modules Additional modules if any. * * @return {@link KaryonServer} which is to be used to start the created server. */ public static KaryonServer forApplication(Class<?> mainClass, Module... modules) { return forApplication(mainClass, toBootstrapModule(modules)); } /** * Creates a new {@link KaryonServer} which uses the passed class to detect any modules. * * @param mainClass Any class/interface containing governator's {@link Bootstrap} annotations. * @param bootstrapModules Additional bootstrapModules if any. * * @return {@link KaryonServer} which is to be used to start the created server. */ public static KaryonServer forApplication(Class<?> mainClass, BootstrapModule... bootstrapModules) { return new MainClassBasedServer(mainClass, bootstrapModules); } /** * Creates a new {@link KaryonServer} from the passed modules. * * @param modules Modules to use for the server. * * @return {@link KaryonServer} which is to be used to start the created server. */ public static KaryonServer forModules(Module... modules) { return forSuites(toBootstrapModule(modules)); } /** * Creates a new {@link KaryonServer} from the passed bootstrapModules. * * @param bootstrapModules Bootstrap modules to use for the server. * * @return {@link KaryonServer} which is to be used to start the created server. */ public static KaryonServer forSuites(BootstrapModule... bootstrapModules) { return new MainClassBasedServer(KaryonServer.class, bootstrapModules); } public static BootstrapModule toBootstrapModule(final Module... modules) { if (null == modules) { return null; } return new BootstrapModule() { @Override public void configure(BootstrapBinder binder) { binder.includeModules(modules); } }; } @SafeVarargs public static BootstrapModule toBootstrapModule(final Class<? extends Module>... moduleClasses) { if (null == moduleClasses) { return null; } return new BootstrapModule() { @Override public void configure(BootstrapBinder binder) { binder.include(Lists.newArrayList(moduleClasses)); } }; } public static BootstrapModule toBootstrapModule(final Class<? extends Module> moduleClass) { if (null == moduleClass) { return null; } return new BootstrapModule() { @Override public void configure(BootstrapBinder binder) { binder.include(moduleClass); } }; } }
3,244
0
Create_ds/karyon/karyon2-governator/src/main/java/netflix
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/MainClassBasedServer.java
package netflix.karyon; import com.google.inject.Injector; import com.netflix.governator.guice.BootstrapModule; import com.netflix.governator.guice.LifecycleInjector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.CountDownLatch; /** * @author Nitesh Kant * @deprecated 2016-07-20 Karyon2 no longer supported. See https://github.com/Netflix/karyon/issues/347 for more info */ @Deprecated class MainClassBasedServer extends AbstractKaryonServer { private static final Logger logger = LoggerFactory.getLogger(MainClassBasedServer.class); private final Class<?> mainClass; protected MainClassBasedServer(Class<?> mainClass, BootstrapModule... bootstrapModules) { super(bootstrapModules); this.mainClass = mainClass; } @Override public void waitTillShutdown() { final CountDownLatch shutdownFinished = new CountDownLatch(1); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { shutdown(); logger.info("Leaving main loop - shutdown finished."); } finally { shutdownFinished.countDown(); } } }); try { shutdownFinished.await(); } catch (InterruptedException e) { logger.error("Interrupted while waiting for shutdown.", e); Thread.interrupted(); throw new RuntimeException(e); } } @Override protected void _start() { // No Op. } @Override protected Injector newInjector(BootstrapModule... applicableBootstrapModules) { return LifecycleInjector.bootstrap(mainClass, applicableBootstrapModules); } }
3,245
0
Create_ds/karyon/karyon2-governator/src/main/java/netflix
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/RxNettyServerBackedServer.java
package netflix.karyon; import com.netflix.governator.guice.BootstrapModule; import io.reactivex.netty.server.AbstractServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * An implementation of {@link KaryonServer} which wraps an RxNetty's server. * * @author Nitesh Kant * @deprecated 2016-07-20 Karyon2 no longer supported. See https://github.com/Netflix/karyon/issues/347 for more info */ @Deprecated class RxNettyServerBackedServer extends MainClassBasedServer { private static final Logger logger = LoggerFactory.getLogger(RxNettyServerBackedServer.class); @SuppressWarnings("rawtypes") private final AbstractServer rxNettyServer; RxNettyServerBackedServer(AbstractServer rxNettyServer, BootstrapModule... bootstrapModules) { super(RxNettyServerBackedServer.class, bootstrapModules); this.rxNettyServer = rxNettyServer; } @Override protected void _start() { rxNettyServer.start(); } @Override public void shutdown() { super.shutdown(); try { rxNettyServer.shutdown(); } catch (InterruptedException e) { logger.error("Interrupted while shutdown.", e); Thread.interrupted(); throw new RuntimeException(e); } } @Override public void waitTillShutdown() { try { rxNettyServer.waitTillShutdown(); } catch (InterruptedException e) { logger.error("Interrupted while waiting for shutdown.", e); Thread.interrupted(); throw new RuntimeException(e); } } }
3,246
0
Create_ds/karyon/karyon2-governator/src/main/java/netflix
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/AbstractKaryonServer.java
package netflix.karyon; import com.google.inject.Injector; import com.netflix.governator.guice.BootstrapModule; import com.netflix.governator.lifecycle.LifecycleManager; import java.util.Arrays; /** * @author Nitesh Kant * @deprecated 2016-07-20 Karyon2 no longer supported. See https://github.com/Netflix/karyon/issues/347 for more info */ @Deprecated abstract class AbstractKaryonServer implements KaryonServer { protected final BootstrapModule[] bootstrapModules; protected LifecycleManager lifecycleManager; protected Injector injector; public AbstractKaryonServer(BootstrapModule... bootstrapModules) { this.bootstrapModules = bootstrapModules; } @Override public final void start() { startWithAdditionalBootstrapModules(); } public final void startWithAdditionalBootstrapModules(BootstrapModule... additionalBootstrapModules) { BootstrapModule[] applicableBootstrapModules = this.bootstrapModules; if (null != additionalBootstrapModules && additionalBootstrapModules.length != 0) { applicableBootstrapModules = Arrays.copyOf(bootstrapModules, bootstrapModules.length + additionalBootstrapModules.length); System.arraycopy(additionalBootstrapModules, 0, applicableBootstrapModules, bootstrapModules.length, additionalBootstrapModules.length); } injector = newInjector(applicableBootstrapModules); startLifecycleManager(); _start(); } protected abstract void _start(); @Override public void shutdown() { if (lifecycleManager != null) { lifecycleManager.close(); } } @Override public void startAndWaitTillShutdown() { start(); waitTillShutdown(); } protected abstract Injector newInjector(BootstrapModule... applicableBootstrapModules); protected void startLifecycleManager() { lifecycleManager = injector.getInstance(LifecycleManager.class); try { lifecycleManager.start(); } catch (Exception e) { throw new RuntimeException(e); // So that this does not pollute the API. } } }
3,247
0
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/transport/AbstractServerModule.java
package netflix.karyon.transport; import com.google.inject.AbstractModule; import com.google.inject.Key; import com.google.inject.binder.LinkedBindingBuilder; import com.google.inject.name.Named; import com.google.inject.name.Names; import io.reactivex.netty.pipeline.PipelineConfigurator; import netflix.karyon.transport.AbstractServerModule.ServerConfigBuilder; /** * @author Tomasz Bak */ @SuppressWarnings("rawtypes") public abstract class AbstractServerModule<I, O, B extends ServerConfigBuilder> extends AbstractModule { protected final Named nameAnnotation; protected final Class<I> iType; protected final Class<O> oType; protected final Key<PipelineConfigurator> pipelineConfiguratorKey; protected final Key<ServerConfig> serverConfigKey; protected final B serverConfigBuilder; protected AbstractServerModule(String moduleName, Class<I> iType, Class<O> oType) { nameAnnotation = Names.named(moduleName); this.iType = iType; this.oType = oType; pipelineConfiguratorKey = Key.get(PipelineConfigurator.class, nameAnnotation); serverConfigKey = Key.get(ServerConfig.class, nameAnnotation); serverConfigBuilder = newServerConfigBuilder(); } protected abstract void configureServer(); protected abstract B newServerConfigBuilder(); protected LinkedBindingBuilder<PipelineConfigurator> bindPipelineConfigurator() { return bind(pipelineConfiguratorKey); } protected B server() { return serverConfigBuilder; } public static class ServerConfig { private final int port; public ServerConfig(int port) { this.port = port; } public int getPort() { return port; } } @SuppressWarnings("unchecked") public static class ServerConfigBuilder<B extends ServerConfigBuilder, C extends ServerConfig> { protected int port = 8080; public B port(int port) { this.port = port; return (B) this; } public C build() { return (C) new ServerConfig(port); } } }
3,248
0
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/transport/util/HttpContentInputStream.java
package netflix.karyon.transport.util; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Observer; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * @author Nitesh Kant */ public class HttpContentInputStream extends InputStream { private static final Logger logger = LoggerFactory.getLogger(HttpContentInputStream.class); private final Lock lock = new ReentrantLock(); private volatile boolean isClosed = false; private volatile boolean isCompleted = false; private volatile Throwable completedWithError = null; private final Condition contentAvailabilityMonitor = lock.newCondition(); private final ByteBuf contentBuffer; public HttpContentInputStream(final ByteBufAllocator allocator, final Observable<ByteBuf> content) { contentBuffer = allocator.buffer(); content.subscribe(new Observer<ByteBuf>() { @Override public void onCompleted() { lock.lock(); try { isCompleted = true; logger.debug( "Processing complete" ); contentAvailabilityMonitor.signalAll(); } finally { lock.unlock(); } } @Override public void onError(Throwable e) { lock.lock(); try { completedWithError = e; isCompleted = true; logger.error("Observer, got error: " + e.getMessage()); contentAvailabilityMonitor.signalAll(); } finally { lock.unlock(); } } @Override public void onNext(ByteBuf byteBuf) { lock.lock(); try { //This is not only to stop writing 0 bytes as it might seems //In case of no payload request, like GET //We are getting onNext( 0 bytes ), onComplete during the stress conditions //AFTER we say subscriber.onCompleted() and tiered down and close //request stream, this doesn't contradict logic, in fact 0 bytes is just the same as nothing to write //but that save us annoying log record every time this happens if( byteBuf.readableBytes() > 0 ) { contentBuffer.writeBytes( byteBuf ); } contentAvailabilityMonitor.signalAll(); } catch( Exception e ) { logger.error("Error on server", e); } finally { lock.unlock(); } } }); } @Override public int available() throws IOException { return isCompleted ? contentBuffer.readableBytes() : 0; } @Override public void mark(int readlimit) { contentBuffer.markReaderIndex(); } @Override public boolean markSupported() { return true; } @Override public int read() throws IOException { lock.lock(); try { if( !await() ) { return -1; } return contentBuffer.readByte() & 0xff; } finally { lock.unlock(); } } @Override public int read(final byte[] b, final int off, final int len) throws IOException { if( b == null ) { throw new NullPointerException( "Null buffer" ); } if( len < 0 || off < 0 || len > b.length - off ) { throw new IndexOutOfBoundsException( "Invalid index" ); } if( len == 0 ) { return 0; } lock.lock(); try { if( !await() ) { return -1; } int size = Math.min( len, contentBuffer.readableBytes() ); contentBuffer.readBytes( b, off, size ); return size; } finally { lock.unlock(); } } @Override public void close() throws IOException { //we need a sync block here, as the double close sometimes is reality and we want to decrement ref. counter only once synchronized ( this ) { if ( isClosed ) { return; } isClosed = true; } contentBuffer.release(); } @Override public void reset() throws IOException { contentBuffer.resetReaderIndex(); } @Override public long skip(long n) throws IOException { //per InputStream contract, if n is negative, 0 bytes are skipped if( n <= 0 ) { return 0; } if (n > Integer.MAX_VALUE) { return skipBytes(Integer.MAX_VALUE); } else { return skipBytes((int) n); } } private int skipBytes(int n) throws IOException { int nBytes = Math.min(available(), n); contentBuffer.skipBytes(nBytes); return nBytes; } private boolean await() throws IOException { //await in here while( !isCompleted && !contentBuffer.isReadable() ) { try { contentAvailabilityMonitor.await(); } catch (InterruptedException e) { // Restore interrupt status and bailout Thread.currentThread().interrupt(); logger.error("Interrupted: " + e.getMessage()); throw new IOException( e ); } } if( completedWithError != null ) { throw new IOException( completedWithError ); } if( isCompleted && !contentBuffer.isReadable() ) { return false; } return true; } }
3,249
0
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/transport/tcp/KaryonTcpModule.java
package netflix.karyon.transport.tcp; import com.google.inject.Key; import com.google.inject.binder.LinkedBindingBuilder; import com.google.inject.multibindings.MapBinder; import io.reactivex.netty.channel.ConnectionHandler; import io.reactivex.netty.server.RxServer; import netflix.karyon.transport.AbstractServerModule; import netflix.karyon.transport.AbstractServerModule.ServerConfigBuilder; import static netflix.karyon.utils.TypeUtils.keyFor; /** * @author Tomasz Bak */ @SuppressWarnings("rawtypes") public abstract class KaryonTcpModule<I, O> extends AbstractServerModule<I, O, ServerConfigBuilder> { protected final Key<ConnectionHandler<I, O>> connectionHandlerKey; protected final Key<RxServer<I, O>> serverKey; protected KaryonTcpModule(String moduleName, Class<I> iType, Class<O> oType) { super(moduleName, iType, oType); connectionHandlerKey = keyFor(ConnectionHandler.class, iType, oType, nameAnnotation); serverKey = keyFor(RxServer.class, iType, oType, nameAnnotation); } @Override protected void configure() { configureServer(); bind(serverConfigKey).toInstance(serverConfigBuilder.build()); MapBinder.newMapBinder(binder(), String.class, RxServer.class).addBinding(nameAnnotation.value()).toProvider( new TcpRxServerProvider<I, O, RxServer<I, O>>(nameAnnotation.value(), iType, oType) ).asEagerSingleton(); } @Override protected ServerConfigBuilder newServerConfigBuilder() { return new ServerConfigBuilder(); } public LinkedBindingBuilder<ConnectionHandler<I, O>> bindConnectionHandler() { return bind(connectionHandlerKey); } }
3,250
0
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/transport/tcp/TcpRxServerProvider.java
package netflix.karyon.transport.tcp; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.name.Named; import com.google.inject.name.Names; import io.reactivex.netty.RxNetty; import io.reactivex.netty.channel.ConnectionHandler; import io.reactivex.netty.metrics.MetricEventsListenerFactory; import io.reactivex.netty.pipeline.PipelineConfigurator; import io.reactivex.netty.server.RxServer; import io.reactivex.netty.server.ServerBuilder; import netflix.karyon.transport.AbstractServerModule.ServerConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PreDestroy; import static netflix.karyon.utils.TypeUtils.keyFor; /** * @author Tomasz Bak */ @SuppressWarnings("unchecked") public class TcpRxServerProvider<I, O, S extends RxServer<I, O>> implements Provider<S> { private static final Logger logger = LoggerFactory.getLogger(TcpRxServerProvider.class); private final Named nameAnnotation; protected final Key<ConnectionHandler<I, O>> connectionHandlerKey; @SuppressWarnings("rawtypes") private final Key<PipelineConfigurator> pipelineConfiguratorKey; private final Key<MetricEventsListenerFactory> metricEventsListenerFactoryKey; private final Key<ServerConfig> serverConfigKey; private RxServer<I, O> server; public TcpRxServerProvider(String name, Class<I> iType, Class<O> oType) { nameAnnotation = Names.named(name); connectionHandlerKey = keyFor(ConnectionHandler.class, iType, oType, nameAnnotation); pipelineConfiguratorKey = Key.get(PipelineConfigurator.class, nameAnnotation); metricEventsListenerFactoryKey = Key.get(MetricEventsListenerFactory.class, nameAnnotation); serverConfigKey = Key.get(ServerConfig.class, nameAnnotation); } @Override public S get() { return (S) server; } @PreDestroy public void shutdown() throws InterruptedException { if (server != null) { server.shutdown(); } } @Inject public void setInjector(Injector injector) { ServerConfig config = injector.getInstance(serverConfigKey); ConnectionHandler<I, O> connectionHandler = injector.getInstance(connectionHandlerKey); ServerBuilder<I, O> builder = RxNetty.newTcpServerBuilder(config.getPort(), connectionHandler); if (injector.getExistingBinding(pipelineConfiguratorKey) != null) { builder.appendPipelineConfigurator(injector.getInstance(pipelineConfiguratorKey)); } if (injector.getExistingBinding(metricEventsListenerFactoryKey) != null) { builder.withMetricEventsListenerFactory(injector.getInstance(metricEventsListenerFactoryKey)); } server = builder.build().start(); logger.info("Starting server {} on port {}...", nameAnnotation.value(), server.getServerPort()); } }
3,251
0
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/transport/http/KaryonHttpModule.java
package netflix.karyon.transport.http; import com.google.inject.Key; import com.google.inject.binder.LinkedBindingBuilder; import com.google.inject.multibindings.MapBinder; import io.reactivex.netty.protocol.http.server.HttpServer; import io.reactivex.netty.protocol.http.server.RequestHandler; import io.reactivex.netty.server.RxServer; import netflix.karyon.transport.AbstractServerModule; import netflix.karyon.transport.http.KaryonHttpModule.HttpServerConfigBuilder; import static netflix.karyon.utils.TypeUtils.keyFor; /** * @author Tomasz Bak */ public abstract class KaryonHttpModule<I, O> extends AbstractServerModule<I, O, HttpServerConfigBuilder> { protected final Key<RequestHandler<I, O>> routerKey; protected final Key<HttpServer<I, O>> httpServerKey; protected final Key<GovernatorHttpInterceptorSupport<I, O>> interceptorSupportKey; private final GovernatorHttpInterceptorSupport<I, O> interceptorSupportInstance = new GovernatorHttpInterceptorSupport<I, O>(); protected KaryonHttpModule(String moduleName, Class<I> iType, Class<O> oType) { super(moduleName, iType, oType); routerKey = keyFor(RequestHandler.class, iType, oType, nameAnnotation); interceptorSupportKey = keyFor(GovernatorHttpInterceptorSupport.class, iType, oType, nameAnnotation); httpServerKey = keyFor(HttpServer.class, iType, oType, nameAnnotation); } @Override protected void configure() { configureServer(); bind(serverConfigKey).toInstance(serverConfigBuilder.build()); bind(interceptorSupportKey).toInstance(interceptorSupportInstance); MapBinder.newMapBinder(binder(), String.class, RxServer.class).addBinding(nameAnnotation.value()).toProvider( new HttpRxServerProvider<I, O, HttpServer<I, O>>(nameAnnotation.value(), iType, oType) ).asEagerSingleton(); } @Override protected HttpServerConfigBuilder newServerConfigBuilder() { return new HttpServerConfigBuilder(); } protected LinkedBindingBuilder<RequestHandler<I, O>> bindRouter() { return bind(routerKey); } protected GovernatorHttpInterceptorSupport<I, O> interceptorSupport() { return interceptorSupportInstance; } public static class HttpServerConfig extends AbstractServerModule.ServerConfig { private final int threadPoolSize; public HttpServerConfig(int port) { super(port); this.threadPoolSize = -1; } public HttpServerConfig(int port, int threadPoolSize) { super(port); this.threadPoolSize = threadPoolSize; } public int getThreadPoolSize() { return threadPoolSize; } public boolean requiresThreadPool() { return threadPoolSize > 0; } } public static class HttpServerConfigBuilder extends AbstractServerModule.ServerConfigBuilder<HttpServerConfigBuilder, HttpServerConfig> { protected int poolSize = -1; public HttpServerConfigBuilder threadPoolSize(int poolSize) { this.poolSize = poolSize; return this; } @Override public HttpServerConfig build() { return new HttpServerConfig(port, poolSize); } } }
3,252
0
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/transport/http/HttpRxServerProvider.java
package netflix.karyon.transport.http; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.name.Named; import com.google.inject.name.Names; import io.reactivex.netty.metrics.MetricEventsListenerFactory; import io.reactivex.netty.pipeline.PipelineConfigurator; import io.reactivex.netty.protocol.http.server.HttpServer; import io.reactivex.netty.protocol.http.server.HttpServerBuilder; import io.reactivex.netty.protocol.http.server.RequestHandler; import netflix.karyon.transport.AbstractServerModule.ServerConfig; import netflix.karyon.transport.KaryonTransport; import netflix.karyon.transport.http.KaryonHttpModule.HttpServerConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PreDestroy; import static netflix.karyon.utils.TypeUtils.keyFor; /** * @author Tomasz Bak */ @SuppressWarnings("unchecked") public class HttpRxServerProvider<I, O, S extends HttpServer<I, O>> implements Provider<S> { private static final Logger logger = LoggerFactory.getLogger(HttpRxServerProvider.class); private final Named nameAnnotation; private final Key<RequestHandler<I, O>> routerKey; private final Key<GovernatorHttpInterceptorSupport<I, O>> interceptorSupportKey; @SuppressWarnings("rawtypes") private final Key<PipelineConfigurator> pipelineConfiguratorKey; private final Key<MetricEventsListenerFactory> metricEventsListenerFactoryKey; private final Key<ServerConfig> serverConfigKey; private volatile HttpServer<I, O> httpServer; public HttpRxServerProvider(String name, Class<I> iType, Class<O> oType) { nameAnnotation = Names.named(name); routerKey = keyFor(RequestHandler.class, iType, oType, nameAnnotation); interceptorSupportKey = keyFor(GovernatorHttpInterceptorSupport.class, iType, oType, nameAnnotation); pipelineConfiguratorKey = Key.get(PipelineConfigurator.class, nameAnnotation); metricEventsListenerFactoryKey = Key.get(MetricEventsListenerFactory.class, nameAnnotation); serverConfigKey = Key.get(ServerConfig.class, nameAnnotation); } @Override public S get() { return (S) httpServer; } @PreDestroy public void shutdown() throws InterruptedException { if (httpServer != null) { httpServer.shutdown(); } } @SuppressWarnings("rawtypes") @Inject public void setInjector(Injector injector) { HttpServerConfig config = (HttpServerConfig) injector.getInstance(serverConfigKey); RequestHandler router = injector.getInstance(routerKey); GovernatorHttpInterceptorSupport<I, O> interceptorSupport = injector.getInstance(interceptorSupportKey); interceptorSupport.finish(injector); HttpRequestHandler<I, O> httpRequestHandler = new HttpRequestHandler<I, O>(router, interceptorSupport); HttpServerBuilder<I, O> builder = KaryonTransport.newHttpServerBuilder(config.getPort(), httpRequestHandler); if (config.requiresThreadPool()) { builder.withRequestProcessingThreads(config.getThreadPoolSize()); } if (injector.getExistingBinding(pipelineConfiguratorKey) != null) { builder.appendPipelineConfigurator(injector.getInstance(pipelineConfiguratorKey)); } if (injector.getExistingBinding(metricEventsListenerFactoryKey) != null) { builder.withMetricEventsListenerFactory(injector.getInstance(metricEventsListenerFactoryKey)); } httpServer = builder.build().start(); logger.info("Starting server {} on port {}...", nameAnnotation.value(), httpServer.getServerPort()); } }
3,253
0
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/transport/http/GovernatorHttpInterceptorSupport.java
package netflix.karyon.transport.http; import com.google.inject.Injector; import io.netty.handler.codec.http.HttpMethod; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import netflix.karyon.transport.interceptor.AbstractAttacher; import netflix.karyon.transport.interceptor.AbstractInterceptorSupport; import netflix.karyon.transport.interceptor.DuplexInterceptor; import netflix.karyon.transport.interceptor.InboundInterceptor; import netflix.karyon.transport.interceptor.InterceptorHolder; import netflix.karyon.transport.interceptor.InterceptorKey; import netflix.karyon.transport.interceptor.OutboundInterceptor; import rx.functions.Action1; import java.util.ArrayList; import java.util.List; /** * * @author Nitesh Kant */ public class GovernatorHttpInterceptorSupport<I, O> extends AbstractInterceptorSupport<HttpServerRequest<I>, HttpServerResponse<O>, HttpKeyEvaluationContext, GovernatorHttpInterceptorSupport.GovernatorHttpAttacher<I, O>, GovernatorHttpInterceptorSupport<I, O>> { protected final List<HttpInClassHolder<I, O>> inboundInterceptorClasses; protected final List<HttpOutClassHolder<I, O>> outboundInterceptorClasses; private Action1<GovernatorHttpInterceptorSupport<I, O>> finishListener; public GovernatorHttpInterceptorSupport() { inboundInterceptorClasses = new ArrayList<HttpInClassHolder<I, O>>(); outboundInterceptorClasses = new ArrayList<HttpOutClassHolder<I, O>>(); } @Override protected GovernatorHttpAttacher<I, O> newAttacher(InterceptorKey<HttpServerRequest<I>, HttpKeyEvaluationContext> key) { return new GovernatorHttpAttacher<I, O>(this, key); } public GovernatorHttpAttacher<I, O> forUri(String uri) { if (null == uri || uri.isEmpty()) { throw new IllegalArgumentException("Uri can not be null or empty."); } return getAttacherForKey(new ServletStyleUriConstraintKey<I>(uri, "")); } public GovernatorHttpAttacher<I, O> forUriRegex(String uriRegEx) { if (null == uriRegEx || uriRegEx.isEmpty()) { throw new IllegalArgumentException("Uri regular expression can not be null or empty."); } return getAttacherForKey(new RegexUriConstraintKey<I>(uriRegEx)); } public GovernatorHttpAttacher<I, O> forHttpMethod(HttpMethod method) { if (null == method) { throw new IllegalArgumentException("Uri can not be null or empty."); } return getAttacherForKey(new MethodConstraintKey<I>(method)); } public GovernatorHttpInterceptorSupport<I, O> finish(Injector injector) { if (!finished) { for (HttpInClassHolder<I, O> holder : inboundInterceptorClasses) { HttpInboundHolder<I, O> ins = new HttpInboundHolder<I, O>(holder.getKey()); for (Class<? extends InboundInterceptor<HttpServerRequest<I>, HttpServerResponse<O>>> interceptor : holder .getInterceptors()) { ins.addIn(injector.getInstance(interceptor)); } inboundInterceptors.add(ins.buildHolder()); } for (HttpOutClassHolder<I, O> holder : outboundInterceptorClasses) { HttpOutboundHolder<I, O> outs = new HttpOutboundHolder<I, O>(holder.getKey()); for (Class<? extends OutboundInterceptor<HttpServerResponse<O>>> interceptor : holder.getInterceptors()) { outs.addOut(injector.getInstance(interceptor)); } outboundInterceptors.add(outs.buildHolder()); } _finish(); finished = true; if (null != finishListener) { finishListener.call(this); } } return this; } public void setFinishListener(Action1<GovernatorHttpInterceptorSupport<I, O>> finishListener) { this.finishListener = finishListener; } public static class GovernatorHttpAttacher<I, O> extends AbstractAttacher<HttpServerRequest<I>, HttpServerResponse<O>, HttpKeyEvaluationContext, GovernatorHttpInterceptorSupport<I, O>> { public GovernatorHttpAttacher(GovernatorHttpInterceptorSupport<I, O> support, InterceptorKey<HttpServerRequest<I>, HttpKeyEvaluationContext> key) { super(support, key); } public GovernatorHttpInterceptorSupport<I, O> interceptIn(Class<? extends InboundInterceptor<HttpServerRequest<I>, HttpServerResponse<O>>> interceptor) { ArrayList<Class<? extends InboundInterceptor<HttpServerRequest<I>, HttpServerResponse<O>>>> interceptors = new ArrayList<Class<? extends InboundInterceptor<HttpServerRequest<I>, HttpServerResponse<O>>>>(); interceptors.add(interceptor); return interceptIn(interceptors); } public GovernatorHttpInterceptorSupport<I, O> interceptIn( List<Class<? extends InboundInterceptor<HttpServerRequest<I>, HttpServerResponse<O>>>> interceptors) { HttpInClassHolder<I, O> holder = new HttpInClassHolder<I, O>(key, interceptors); interceptorSupport.inboundInterceptorClasses.add(holder); return interceptorSupport; } public GovernatorHttpInterceptorSupport<I, O> interceptOut(Class<? extends OutboundInterceptor<HttpServerResponse<O>>> interceptor) { ArrayList<Class<? extends OutboundInterceptor<HttpServerResponse<O>>>> interceptors = new ArrayList<Class<? extends OutboundInterceptor<HttpServerResponse<O>>>>(); interceptors.add(interceptor); return interceptOut(interceptors); } public GovernatorHttpInterceptorSupport<I, O> interceptOut(List<Class<? extends OutboundInterceptor<HttpServerResponse<O>>>> interceptors) { HttpOutClassHolder<I, O> holder = new HttpOutClassHolder<I, O>(key, interceptors); interceptorSupport.outboundInterceptorClasses.add(holder); return interceptorSupport; } @SuppressWarnings("unchecked") public GovernatorHttpInterceptorSupport<I, O> intercept(Class<? extends DuplexInterceptor<HttpServerRequest<I>, HttpServerResponse<O>>> interceptor) { ArrayList<Class<? extends DuplexInterceptor<HttpServerRequest<I>, HttpServerResponse<O>>>> interceptors = new ArrayList<Class<? extends DuplexInterceptor<HttpServerRequest<I>, HttpServerResponse<O>>>>(); interceptors.add(interceptor); return intercept(interceptors); } public GovernatorHttpInterceptorSupport<I, O> intercept(List<Class<? extends DuplexInterceptor<HttpServerRequest<I>, HttpServerResponse<O>>>> interceptors) { ArrayList<Class<? extends InboundInterceptor<HttpServerRequest<I>, HttpServerResponse<O>>>> ins = new ArrayList<Class<? extends InboundInterceptor<HttpServerRequest<I>, HttpServerResponse<O>>>>(); ArrayList<Class<? extends OutboundInterceptor<HttpServerResponse<O>>>> outs = new ArrayList<Class<? extends OutboundInterceptor<HttpServerResponse<O>>>>(); for (Class<? extends DuplexInterceptor<HttpServerRequest<I>, HttpServerResponse<O>>> interceptor : interceptors) { ins.add(interceptor); outs.add(interceptor); } HttpInClassHolder<I, O> inHolder = new HttpInClassHolder<I, O>(key, ins); interceptorSupport.inboundInterceptorClasses.add(inHolder); HttpOutClassHolder<I, O> outHolder = new HttpOutClassHolder<I, O>(key, outs); interceptorSupport.outboundInterceptorClasses.add(outHolder); return interceptorSupport; } } private static class HttpInboundHolder<I, O> { private final InterceptorKey<HttpServerRequest<I>, HttpKeyEvaluationContext> key; private final List<InboundInterceptor<HttpServerRequest<I>, HttpServerResponse<O>>> interceptors; private HttpInboundHolder(InterceptorKey<HttpServerRequest<I>, HttpKeyEvaluationContext> key) { this.key = key; interceptors = new ArrayList<InboundInterceptor<HttpServerRequest<I>, HttpServerResponse<O>>>(); } private void addIn(InboundInterceptor<HttpServerRequest<I>, HttpServerResponse<O>> interceptor) { interceptors.add(interceptor); } private InterceptorHolder<HttpServerRequest<I>, HttpKeyEvaluationContext, InboundInterceptor<HttpServerRequest<I>, HttpServerResponse<O>>> buildHolder() { return new InterceptorHolder<HttpServerRequest<I>, HttpKeyEvaluationContext, InboundInterceptor<HttpServerRequest<I>, HttpServerResponse<O>>>(key, interceptors); } } private static class HttpOutboundHolder<I, O> { private final InterceptorKey<HttpServerRequest<I>, HttpKeyEvaluationContext> key; private final List<OutboundInterceptor<HttpServerResponse<O>>> interceptors; private HttpOutboundHolder(InterceptorKey<HttpServerRequest<I>, HttpKeyEvaluationContext> key) { this.key = key; interceptors = new ArrayList<OutboundInterceptor<HttpServerResponse<O>>>(); } private void addOut(OutboundInterceptor<HttpServerResponse<O>> interceptor) { interceptors.add(interceptor); } private InterceptorHolder<HttpServerRequest<I>, HttpKeyEvaluationContext, OutboundInterceptor<HttpServerResponse<O>>> buildHolder() { return new InterceptorHolder<HttpServerRequest<I>, HttpKeyEvaluationContext, OutboundInterceptor<HttpServerResponse<O>>>(key, interceptors); } } private static class HttpInClassHolder<I, O> extends InterceptorHolder<HttpServerRequest<I>, HttpKeyEvaluationContext, Class<? extends InboundInterceptor<HttpServerRequest<I>, HttpServerResponse<O>>>> { private HttpInClassHolder(InterceptorKey<HttpServerRequest<I>, HttpKeyEvaluationContext> key, List<Class<? extends InboundInterceptor<HttpServerRequest<I>, HttpServerResponse<O>>>> interceptors) { super(key, interceptors); } } private static class HttpOutClassHolder<I, O> extends InterceptorHolder<HttpServerRequest<I>, HttpKeyEvaluationContext, Class<? extends OutboundInterceptor<HttpServerResponse<O>>>> { private HttpOutClassHolder(InterceptorKey<HttpServerRequest<I>, HttpKeyEvaluationContext> key, List<Class<? extends OutboundInterceptor<HttpServerResponse<O>>>> interceptors) { super(key, interceptors); } } }
3,254
0
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/transport/http
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/transport/http/health/HealthCheckEndpoint.java
package netflix.karyon.transport.http.health; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpResponseStatus; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.server.RequestHandler; import netflix.karyon.health.HealthCheckHandler; import rx.Observable; import javax.inject.Inject; /** * An implementation of {@link RequestHandler} to provide health status over HTTP. * * This endpoint does <b>NOT</b> validate whether the passed request URI is actually of healthcheck or not. It assumes * that it is used by a higher level router that makes appropriate decisions of which handler to call based on the URI. * * @author Nitesh Kant */ public class HealthCheckEndpoint implements RequestHandler<ByteBuf, ByteBuf> { private final HealthCheckHandler healthCheckHandler; @Inject public HealthCheckEndpoint(HealthCheckHandler healthCheckHandler) { this.healthCheckHandler = healthCheckHandler; } @Override public Observable<Void> handle(HttpServerRequest<ByteBuf> request, HttpServerResponse<ByteBuf> response) { int httpStatus = healthCheckHandler.getStatus(); response.setStatus(HttpResponseStatus.valueOf(httpStatus)); return response.close(); } }
3,255
0
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/transport/http
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/transport/http/websockets/KaryonWebSocketsModule.java
package netflix.karyon.transport.http.websockets; import com.google.inject.Key; import com.google.inject.binder.LinkedBindingBuilder; import com.google.inject.multibindings.MapBinder; import io.netty.handler.codec.http.websocketx.WebSocketFrame; import io.reactivex.netty.channel.ConnectionHandler; import io.reactivex.netty.server.RxServer; import netflix.karyon.transport.AbstractServerModule; import netflix.karyon.transport.http.websockets.KaryonWebSocketsModule.WebSocketsServerConfigBuilder; import static netflix.karyon.utils.TypeUtils.keyFor; /** * @author Tomasz Bak */ public abstract class KaryonWebSocketsModule<I extends WebSocketFrame, O extends WebSocketFrame> extends AbstractServerModule<I, O, WebSocketsServerConfigBuilder> { protected final Key<ConnectionHandler<I, O>> connectionHandlerKey; protected final Key<RxServer<I, O>> serverKey; protected KaryonWebSocketsModule(String moduleName, Class<I> iType, Class<O> oType) { super(moduleName, iType, oType); connectionHandlerKey = keyFor(ConnectionHandler.class, iType, oType, nameAnnotation); serverKey = keyFor(RxServer.class, iType, oType, nameAnnotation); } @Override protected void configure() { configureServer(); bind(serverConfigKey).toInstance(serverConfigBuilder.build()); MapBinder.newMapBinder(binder(), String.class, RxServer.class).addBinding(nameAnnotation.value()).toProvider( new WebSocketsRxServerProvider<I, O, RxServer<I, O>>(nameAnnotation.value(), iType, oType) ).asEagerSingleton(); } @Override protected WebSocketsServerConfigBuilder newServerConfigBuilder() { return new WebSocketsServerConfigBuilder(); } public LinkedBindingBuilder<ConnectionHandler<I, O>> bindConnectionHandler() { return bind(connectionHandlerKey); } public static class WebSocketsServerConfig extends AbstractServerModule.ServerConfig { private final boolean messageAggregator; public WebSocketsServerConfig(int port, boolean messageAggregator) { super(port); this.messageAggregator = messageAggregator; } public boolean isMessageAggregator() { return messageAggregator; } } public static class WebSocketsServerConfigBuilder extends AbstractServerModule.ServerConfigBuilder<WebSocketsServerConfigBuilder, WebSocketsServerConfig> { protected boolean messageAggregator; public WebSocketsServerConfigBuilder withMessageAggregator(boolean messageAggregator) { this.messageAggregator = messageAggregator; return this; } @Override public WebSocketsServerConfig build() { return new WebSocketsServerConfig(port, messageAggregator); } } }
3,256
0
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/transport/http
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/transport/http/websockets/WebSocketsRxServerProvider.java
package netflix.karyon.transport.http.websockets; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.name.Named; import com.google.inject.name.Names; import io.netty.handler.codec.http.websocketx.WebSocketFrame; import io.reactivex.netty.RxNetty; import io.reactivex.netty.channel.ConnectionHandler; import io.reactivex.netty.metrics.MetricEventsListenerFactory; import io.reactivex.netty.pipeline.PipelineConfigurator; import io.reactivex.netty.protocol.http.websocket.WebSocketServerBuilder; import io.reactivex.netty.server.RxServer; import netflix.karyon.transport.AbstractServerModule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PreDestroy; import static netflix.karyon.utils.TypeUtils.keyFor; /** * @author Tomasz Bak */ public class WebSocketsRxServerProvider<I extends WebSocketFrame, O extends WebSocketFrame, S extends RxServer<I, O>> implements Provider<S> { private static final Logger logger = LoggerFactory.getLogger(WebSocketsRxServerProvider.class); private final Named nameAnnotation; protected final Key<ConnectionHandler<I, O>> connectionHandlerKey; @SuppressWarnings("rawtypes") private final Key<PipelineConfigurator> pipelineConfiguratorKey; private final Key<MetricEventsListenerFactory> metricEventsListenerFactoryKey; private final Key<AbstractServerModule.ServerConfig> serverConfigKey; private RxServer<I, O> server; public WebSocketsRxServerProvider(String name, Class<I> iType, Class<O> oType) { nameAnnotation = Names.named(name); connectionHandlerKey = keyFor(ConnectionHandler.class, iType, oType, nameAnnotation); pipelineConfiguratorKey = Key.get(PipelineConfigurator.class, nameAnnotation); metricEventsListenerFactoryKey = Key.get(MetricEventsListenerFactory.class, nameAnnotation); serverConfigKey = Key.get(AbstractServerModule.ServerConfig.class, nameAnnotation); } @SuppressWarnings("unchecked") @Override public S get() { return (S) server; } @PreDestroy public void shutdown() throws InterruptedException { if (server != null) { logger.info("Starting WebSockets server {} on port {}...", nameAnnotation.value(), server.getServerPort()); server.shutdown(); } } @Inject @SuppressWarnings("unchecked") public void setInjector(Injector injector) { KaryonWebSocketsModule.WebSocketsServerConfig config = (KaryonWebSocketsModule.WebSocketsServerConfig) injector.getInstance(serverConfigKey); ConnectionHandler<I, O> connectionHandler = injector.getInstance(connectionHandlerKey); WebSocketServerBuilder<I, O> builder = RxNetty.newWebSocketServerBuilder(config.getPort(), connectionHandler) .withMessageAggregator(config.isMessageAggregator()); if (injector.getExistingBinding(pipelineConfiguratorKey) != null) { builder.appendPipelineConfigurator(injector.getInstance(pipelineConfiguratorKey)); } if (injector.getExistingBinding(metricEventsListenerFactoryKey) != null) { builder.withMetricEventsListenerFactory(injector.getInstance(metricEventsListenerFactoryKey)); } server = builder.build().start(); logger.info("Starting WebSockets server {} on port {}...", nameAnnotation.value(), server.getServerPort()); } }
3,257
0
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/health/SyncHealthCheckInvocationStrategy.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package netflix.karyon.health; import javax.inject.Inject; import java.util.concurrent.TimeoutException; /** * An implementation of {@link netflix.karyon.health.HealthCheckInvocationStrategy} that synchronously calls the underlying * {@link netflix.karyon.health.HealthCheckHandler}. * * @author Nitesh Kant */ @SuppressWarnings("unused") public class SyncHealthCheckInvocationStrategy implements HealthCheckInvocationStrategy { private final HealthCheckHandler handler; @Inject public SyncHealthCheckInvocationStrategy(HealthCheckHandler handler) { this.handler = handler; } @Override public int invokeCheck() throws TimeoutException { return handler.getStatus(); } @Override public HealthCheckHandler getHandler() { return handler; } }
3,258
0
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon
Create_ds/karyon/karyon2-governator/src/main/java/netflix/karyon/utils/TypeUtils.java
package netflix.karyon.utils; import com.google.inject.Key; import com.google.inject.TypeLiteral; import com.google.inject.util.Types; import java.lang.annotation.Annotation; /** * Set of utility methods. * * @author Tomasz Bak */ public final class TypeUtils { private TypeUtils() { } @SuppressWarnings("unchecked") public static <T> Key<T> keyFor(Class<?> type, Class<?> typeArg1, Class<?> typeArg2, Annotation annotation) { TypeLiteral<T> typeLiteral = (TypeLiteral<T>) TypeLiteral.get(Types.newParameterizedType(type, typeArg1, typeArg2)); return Key.get(typeLiteral, annotation); } }
3,259
0
Create_ds/karyon/karyon2-archaius/src/main/java/netflix/karyon
Create_ds/karyon/karyon2-archaius/src/main/java/netflix/karyon/archaius/ArchaiusBootstrap.java
package netflix.karyon.archaius; import com.netflix.governator.guice.annotations.Bootstrap; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * @author Nitesh Kant */ @Documented @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Bootstrap(bootstrap = ArchaiusBootstrapModule.class) public @interface ArchaiusBootstrap { Class<? extends PropertiesLoader> loader() default DefaultPropertiesLoader.class; }
3,260
0
Create_ds/karyon/karyon2-archaius/src/main/java/netflix/karyon
Create_ds/karyon/karyon2-archaius/src/main/java/netflix/karyon/archaius/ArchaiusBootstrapModule.java
package netflix.karyon.archaius; import com.netflix.governator.configuration.ArchaiusConfigurationProvider; import com.netflix.governator.configuration.ConfigurationOwnershipPolicies; import com.netflix.governator.guice.BootstrapBinder; import com.netflix.governator.guice.BootstrapModule; import javax.inject.Inject; /** * A guice module that defines all bindings required by karyon. Applications must use this to bootstrap karyon. * * @author Nitesh Kant */ public class ArchaiusBootstrapModule implements BootstrapModule { private final Class<? extends PropertiesLoader> propertiesLoaderClass; private final PropertiesLoader propertiesLoader; public ArchaiusBootstrapModule(String appName) { this(new DefaultPropertiesLoader(appName)); } public ArchaiusBootstrapModule(PropertiesLoader propertiesLoader) { this.propertiesLoader = propertiesLoader; this.propertiesLoaderClass = null; } public ArchaiusBootstrapModule(Class<PropertiesLoader> propertiesLoader) { this.propertiesLoaderClass = propertiesLoader; this.propertiesLoader = null; } @Inject ArchaiusBootstrapModule(ArchaiusBootstrap archaiusBootstrap) { propertiesLoaderClass = archaiusBootstrap.loader(); propertiesLoader = null; } @Override public void configure(BootstrapBinder bootstrapBinder) { if (null != propertiesLoaderClass) { bootstrapBinder.bind(PropertiesLoader.class).to(propertiesLoaderClass).asEagerSingleton(); } else { bootstrapBinder.bind(PropertiesLoader.class).toInstance(propertiesLoader); } bootstrapBinder.bind(PropertiesInitializer.class).asEagerSingleton(); ArchaiusConfigurationProvider.Builder builder = ArchaiusConfigurationProvider.builder(); builder.withOwnershipPolicy(ConfigurationOwnershipPolicies.ownsAll()); bootstrapBinder.bindConfigurationProvider().toInstance(builder.build()); } /** * This is required as we want to invoke {@link PropertiesLoader#load()} automatically. * One way of achieving this is by using {@link @javax.annotation.PostConstruct} but archaius initialization is done * in the bootstrap phase and {@link @javax.annotation.PostConstruct} is not invoked in the bootstrap phase. */ private static class PropertiesInitializer { @Inject public PropertiesInitializer(PropertiesLoader loader) { loader.load(); } } }
3,261
0
Create_ds/karyon/karyon2-archaius/src/main/java/netflix/karyon
Create_ds/karyon/karyon2-archaius/src/main/java/netflix/karyon/archaius/DefaultPropertiesLoader.java
package netflix.karyon.archaius; import com.netflix.config.ConfigurationManager; import com.netflix.config.DeploymentContext; import netflix.karyon.KaryonBootstrap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import java.io.IOException; /** * Default property loading mechanism for archaius. It loads two property files: * * <ul> <li>Any file with name &lt;application_name&gt;.properties</li> <li>Any file with name &lt;application_name&gt;-&lt; archaius environment&gt;.properties: The environment name is as provided by {@link DeploymentContext#getDeploymentEnvironment()} where the deployment context is as configured for archaius and retrieved by {@link ConfigurationManager#getDeploymentContext()}</li> </ul> * * The application name is either provided to this loader or defaults to {@link DeploymentContext#getApplicationId()} * where {@link DeploymentContext} is as retrieved by {@link ConfigurationManager#getDeploymentContext()} * * @author Nitesh Kant */ public class DefaultPropertiesLoader implements PropertiesLoader { private static final Logger logger = LoggerFactory.getLogger(DefaultPropertiesLoader.class); private final String appName; public DefaultPropertiesLoader() { this.appName = null; } public DefaultPropertiesLoader(String appName) { this.appName = appName; } @Inject DefaultPropertiesLoader(KaryonBootstrap karyonBootstrap) { appName = karyonBootstrap.name(); } @Override public void load() { String appNameToUse = appName; if (null == appNameToUse) { appNameToUse = ConfigurationManager.getDeploymentContext().getApplicationId(); } try { logger.info(String.format("Loading application properties with app id: %s and environment: %s", appNameToUse, ConfigurationManager.getDeploymentContext().getDeploymentEnvironment())); /** * This loads a property file with the name "appName".properties and "appName"-"env".properties, if found. */ ConfigurationManager.loadCascadedPropertiesFromResources(appNameToUse); } catch (IOException e) { logger.error(String.format( "Failed to load properties for application id: %s and environment: %s. This is ok, if you do not have application level properties.", appNameToUse, ConfigurationManager.getDeploymentContext().getDeploymentEnvironment()), e); } } }
3,262
0
Create_ds/karyon/karyon2-archaius/src/main/java/netflix/karyon
Create_ds/karyon/karyon2-archaius/src/main/java/netflix/karyon/archaius/PropertiesLoader.java
package netflix.karyon.archaius; /** * @author Nitesh Kant */ public interface PropertiesLoader { void load(); }
3,263
0
Create_ds/karyon/karyon2-core/src/test/java/netflix/karyon
Create_ds/karyon/karyon2-core/src/test/java/netflix/karyon/server/MockChannelHandlerContext.java
package netflix.karyon.server; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelProgressivePromise; import io.netty.channel.ChannelPromise; import io.netty.channel.DefaultChannelProgressivePromise; import io.netty.channel.DefaultChannelPromise; import io.netty.channel.local.LocalChannel; import io.netty.util.Attribute; import io.netty.util.AttributeKey; import io.netty.util.AttributeMap; import io.netty.util.DefaultAttributeMap; import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.GlobalEventExecutor; import java.net.SocketAddress; /** * @author Nitesh Kant */ public class MockChannelHandlerContext implements ChannelHandlerContext { private final Channel channel; private final String name; private final ChannelDuplexHandler handler; private final UnpooledByteBufAllocator bufAllocator = new UnpooledByteBufAllocator(true); private final AttributeMap attributeMap = new DefaultAttributeMap(); public MockChannelHandlerContext(String name) { this(new LocalChannel(), name, null); } public MockChannelHandlerContext(Channel channel, String name, ChannelDuplexHandler handler) { this.channel = channel; this.name = name; this.handler = handler; } @Override public Channel channel() { return channel; } @Override public EventExecutor executor() { return GlobalEventExecutor.INSTANCE; } @Override public String name() { return name; } @Override public ChannelHandler handler() { return handler; } @Override public boolean isRemoved() { return false; } @Override public ChannelHandlerContext fireChannelRegistered() { try { if (null != handler) { handler.channelRegistered(this); } } catch (Exception e) { throw new RuntimeException(e); } return this; } @Override public ChannelHandlerContext fireChannelUnregistered() { try { if (null != handler) { handler.channelUnregistered(this); } } catch (Exception e) { throw new RuntimeException(e); } return this; } @Override public ChannelHandlerContext fireChannelActive() { try { if (null != handler) { handler.channelActive(this); } } catch (Exception e) { throw new RuntimeException(e); } return this; } @Override public ChannelHandlerContext fireChannelInactive() { try { if (null != handler) { handler.channelInactive(this); } } catch (Exception e) { throw new RuntimeException(e); } return this; } @Override public ChannelHandlerContext fireExceptionCaught(Throwable cause) { try { if (null != handler) { handler.exceptionCaught(this, cause); } } catch (Exception e) { throw new RuntimeException(e); } return this; } @Override public ChannelHandlerContext fireUserEventTriggered(Object event) { try { if (null != handler) { handler.userEventTriggered(this, event); } } catch (Exception e) { throw new RuntimeException(e); } return this; } @Override public ChannelHandlerContext fireChannelRead(Object msg) { try { if (null != handler) { handler.channelRead(this, msg); } } catch (Exception e) { throw new RuntimeException(e); } return this; } @Override public ChannelHandlerContext fireChannelReadComplete() { try { if (null != handler) { handler.channelReadComplete(this); } } catch (Exception e) { throw new RuntimeException(e); } return this; } @Override public ChannelHandlerContext fireChannelWritabilityChanged() { try { if (null != handler) { handler.channelWritabilityChanged(this); } } catch (Exception e) { throw new RuntimeException(e); } return this; } @Override public ChannelFuture bind(SocketAddress localAddress) { DefaultChannelPromise promise = new DefaultChannelPromise(channel); promise.setSuccess(); return promise; } @Override public ChannelFuture connect(SocketAddress remoteAddress) { DefaultChannelPromise promise = new DefaultChannelPromise(channel); promise.setSuccess(); return promise; } @Override public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) { DefaultChannelPromise promise = new DefaultChannelPromise(channel); promise.setSuccess(); return promise; } @Override public ChannelFuture disconnect() { DefaultChannelPromise promise = new DefaultChannelPromise(channel); promise.setSuccess(); return promise; } @Override public ChannelFuture close() { DefaultChannelPromise promise = new DefaultChannelPromise(channel); promise.setSuccess(); return promise; } @Override public ChannelFuture deregister() { DefaultChannelPromise promise = new DefaultChannelPromise(channel); promise.setSuccess(); return promise; } @Override public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) { promise.setSuccess(); return promise; } @Override public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) { promise.setSuccess(); return promise; } @Override public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { promise.setSuccess(); return promise; } @Override public ChannelFuture disconnect(ChannelPromise promise) { promise.setSuccess(); return promise; } @Override public ChannelFuture close(ChannelPromise promise) { promise.setSuccess(); return promise; } @Override public ChannelFuture deregister(ChannelPromise promise) { promise.setSuccess(); return promise; } @Override public ChannelHandlerContext read() { channel.read(); return this; } @Override public ChannelFuture write(Object msg) { DefaultChannelPromise promise = new DefaultChannelPromise(channel); promise.setSuccess(); return promise; } @Override public ChannelFuture write(Object msg, ChannelPromise promise) { promise.setSuccess(); return promise; } @Override public ChannelHandlerContext flush() { try { if (null != handler) { handler.flush(this); } } catch (Exception e) { throw new RuntimeException(e); } return this; } @Override public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) { try { if (null != handler) { handler.write(this, msg, promise); handler.flush(this); } } catch (Exception e) { promise.tryFailure(e); } return promise; } @Override public ChannelFuture writeAndFlush(Object msg) { DefaultChannelPromise promise = new DefaultChannelPromise(channel); try { if (null != handler) { handler.write(this, msg, promise); handler.flush(this); } } catch (Exception e) { promise.tryFailure(e); } return promise; } @Override public ChannelPipeline pipeline() { return null; } @Override public ByteBufAllocator alloc() { return bufAllocator; } @Override public ChannelPromise newPromise() { return new DefaultChannelPromise(channel); } @Override public ChannelProgressivePromise newProgressivePromise() { return new DefaultChannelProgressivePromise(channel); } @Override public ChannelFuture newSucceededFuture() { return new DefaultChannelPromise(channel).setSuccess(); } @Override public ChannelFuture newFailedFuture(Throwable cause) { return new DefaultChannelPromise(channel).setFailure(cause); } @Override public ChannelPromise voidPromise() { return new DefaultChannelPromise(channel); } @Override public <T> Attribute<T> attr(AttributeKey<T> key) { return attributeMap.attr(key); } }
3,264
0
Create_ds/karyon/karyon2-core/src/test/java/netflix/karyon/server
Create_ds/karyon/karyon2-core/src/test/java/netflix/karyon/server/http/ServletStyleConstraintTest.java
package netflix.karyon.server.http; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpVersion; import io.reactivex.netty.protocol.http.UnicastContentSubject; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import netflix.karyon.server.MockChannelHandlerContext; import netflix.karyon.transport.http.HttpKeyEvaluationContext; import netflix.karyon.transport.http.ServletStyleUriConstraintKey; import org.junit.Assert; import org.junit.Test; /** * @author Nitesh Kant */ public class ServletStyleConstraintTest extends InterceptorConstraintTestBase { @Test public void testServletPathExactMatch() throws Exception { ServletStyleUriConstraintKey<ByteBuf> key = new ServletStyleUriConstraintKey<>("d/a/b/c", "d"); HttpKeyEvaluationContext context = new HttpKeyEvaluationContext(new MockChannelHandlerContext("mock").channel()); HttpServerRequest<ByteBuf> request = newRequest("/d/a/b/c/"); boolean keyApplicable = key.apply(request, context); Assert.assertTrue("Exact match servlet style constraint failed.", keyApplicable); String servletPath = key.getServletPath(request, context); Assert.assertEquals("Unexpected servlet path.", "/a/b/c/", servletPath); } @Test public void testServletPathPrefixMatch() throws Exception { ServletStyleUriConstraintKey<ByteBuf> key = new ServletStyleUriConstraintKey<>("d/a/*", "d"); HttpKeyEvaluationContext context = new HttpKeyEvaluationContext(new MockChannelHandlerContext("mock").channel()); HttpServerRequest<ByteBuf> request = newRequest("/d/a/b/c/"); boolean keyApplicable = key.apply(request, context); Assert.assertTrue("Prefix match servlet style constraint failed.", keyApplicable); String servletPath = key.getServletPath(request, context); Assert.assertEquals("Unexpected servlet path.", "/a", servletPath); } @Test public void testServletPathExtensionMatch() throws Exception { ServletStyleUriConstraintKey<ByteBuf> key = new ServletStyleUriConstraintKey<>("*.boo", "d"); HttpKeyEvaluationContext context = new HttpKeyEvaluationContext(new MockChannelHandlerContext("mock").channel()); HttpServerRequest<ByteBuf> request = newRequest("/d/a/b/c.boo"); boolean keyApplicable = key.apply(request, context); Assert.assertTrue("Extension match servlet style constraint failed.", keyApplicable); String servletPath = key.getServletPath(request, context); Assert.assertEquals("Unexpected servlet path.", "", servletPath); } @Test public void testExactMatch() throws Exception { ServletStyleUriConstraintKey<ByteBuf> key = new ServletStyleUriConstraintKey<>("a/b/c", ""); boolean keyApplicable = doApplyForGET(key, "/a/b/c"); Assert.assertTrue("Exact match servlet style constraint failed.", keyApplicable); } @Test public void testExactMatchWithTrailingSlashInUri() throws Exception { ServletStyleUriConstraintKey<ByteBuf> key = new ServletStyleUriConstraintKey<>("a/b/c", ""); boolean keyApplicable = doApplyForGET(key, "/a/b/c/"); Assert.assertTrue("Exact match servlet style constraint failed.", keyApplicable); } @Test public void testExactMatchWithTrailingSlashInConstraint() throws Exception { ServletStyleUriConstraintKey<ByteBuf> key = new ServletStyleUriConstraintKey<>("a/b/c/", ""); boolean keyApplicable = doApplyForGET(key, "/a/b/c"); Assert.assertTrue("Exact match servlet style constraint failed.", keyApplicable); } @Test public void testPrefixMatch() throws Exception { ServletStyleUriConstraintKey<ByteBuf> key = new ServletStyleUriConstraintKey<>("a/b/c*", ""); boolean keyApplicable = doApplyForGET(key, "/a/b/c/def"); Assert.assertTrue("Prefix match servlet style constraint failed.", keyApplicable); } @Test public void testPrefixMatchWithSlashInConstraint() throws Exception { ServletStyleUriConstraintKey<ByteBuf> key = new ServletStyleUriConstraintKey<>("a/b/c/*", ""); boolean keyApplicable = doApplyForGET(key, "/a/b/c/def"); Assert.assertTrue("Prefix match servlet style constraint failed.", keyApplicable); } @Test public void testPrefixMatchWithExactUri() throws Exception { ServletStyleUriConstraintKey<ByteBuf> key = new ServletStyleUriConstraintKey<>("a/b/c/*", ""); boolean keyApplicable = doApplyForGET(key, "/a/b/c/"); Assert.assertTrue("Prefix match servlet style constraint failed.", keyApplicable); } @Test public void testPrefixMatchWithNoSlashInUri() throws Exception { ServletStyleUriConstraintKey<ByteBuf> key = new ServletStyleUriConstraintKey<>("a/b/c/*", ""); boolean keyApplicable = doApplyForGET(key, "/a/b/c"); Assert.assertTrue("Prefix match servlet style constraint failed.", keyApplicable); } @Test public void testExtensionMatch() throws Exception { ServletStyleUriConstraintKey<ByteBuf> key = new ServletStyleUriConstraintKey<>("*.boo", ""); boolean keyApplicable = doApplyForGET(key, "/a/b/c/d.boo"); Assert.assertTrue("Extension match servlet style constraint failed.", keyApplicable); } @Test public void testQueryDecoderCache() throws Exception { ServletStyleUriConstraintKey<ByteBuf> key = new ServletStyleUriConstraintKey<>("d/a/b/c", "d"); Channel mockChannel = new MockChannelHandlerContext("mock").channel(); HttpKeyEvaluationContext context = new HttpKeyEvaluationContext(mockChannel); HttpServerRequest<ByteBuf> request = newRequest("/d/a/b/c/"); boolean keyApplicable = key.apply(request, context); Assert.assertTrue("Exact match servlet style constraint failed.", keyApplicable); HttpKeyEvaluationContext context2 = new HttpKeyEvaluationContext(mockChannel); request = newRequest("/x/y/z"); keyApplicable = key.apply(request, context2); Assert.assertFalse("Query decoder cache not cleared..", keyApplicable); } protected HttpServerRequest<ByteBuf> newRequest(String uri) { return new HttpServerRequest<ByteBuf>(new DefaultHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, uri), UnicastContentSubject.<ByteBuf>createWithoutNoSubscriptionTimeout()); } }
3,265
0
Create_ds/karyon/karyon2-core/src/test/java/netflix/karyon/server
Create_ds/karyon/karyon2-core/src/test/java/netflix/karyon/server/http/InterceptorConstraintTestBase.java
package netflix.karyon.server.http; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpVersion; import io.reactivex.netty.protocol.http.UnicastContentSubject; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import netflix.karyon.server.MockChannelHandlerContext; import netflix.karyon.transport.http.HttpKeyEvaluationContext; import netflix.karyon.transport.interceptor.InterceptorKey; /** * @author Nitesh Kant */ public class InterceptorConstraintTestBase { protected static boolean doApplyForGET(InterceptorKey<HttpServerRequest<ByteBuf>, HttpKeyEvaluationContext> key, String uri) { return doApply(key, uri, HttpMethod.GET); } protected static boolean doApply(InterceptorKey<HttpServerRequest<ByteBuf>, HttpKeyEvaluationContext> key, String uri, HttpMethod httpMethod) { DefaultHttpRequest nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_0, httpMethod, uri); return key.apply(new HttpServerRequest<ByteBuf>(nettyRequest, UnicastContentSubject.<ByteBuf>createWithoutNoSubscriptionTimeout()), new HttpKeyEvaluationContext(new MockChannelHandlerContext("mock").channel())); } }
3,266
0
Create_ds/karyon/karyon2-core/src/test/java/netflix/karyon/server
Create_ds/karyon/karyon2-core/src/test/java/netflix/karyon/server/http/MethodConstraintTest.java
package netflix.karyon.server.http; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpMethod; import netflix.karyon.transport.http.MethodConstraintKey; import org.junit.Assert; import org.junit.Test; /** * @author Nitesh Kant */ public class MethodConstraintTest extends InterceptorConstraintTestBase { @Test public void testMethodConstraint() throws Exception { MethodConstraintKey<ByteBuf> key = new MethodConstraintKey<ByteBuf>(HttpMethod.HEAD); boolean keyApplicable = doApply(key, "a/b/c", HttpMethod.HEAD); Assert.assertTrue("Http Method style constraint failed.", keyApplicable); } @Test public void testMethodConstraintFail() throws Exception { MethodConstraintKey<ByteBuf> key = new MethodConstraintKey<ByteBuf>(HttpMethod.HEAD); boolean keyApplicable = doApply(key, "a/b/c", HttpMethod.GET); Assert.assertFalse("Http Method style constraint failed.", keyApplicable); } }
3,267
0
Create_ds/karyon/karyon2-core/src/test/java/netflix/karyon/server
Create_ds/karyon/karyon2-core/src/test/java/netflix/karyon/server/http/RegExConstraintTest.java
package netflix.karyon.server.http; import io.netty.buffer.ByteBuf; import netflix.karyon.transport.http.RegexUriConstraintKey; import org.junit.Assert; import org.junit.Test; /** * @author Nitesh Kant */ public class RegExConstraintTest extends InterceptorConstraintTestBase { @Test public void testRegExConstraint() throws Exception { RegexUriConstraintKey<ByteBuf> key = new RegexUriConstraintKey<ByteBuf>("a/.*"); boolean keyApplicable = doApplyForGET(key, "a/b/c"); Assert.assertTrue("Regex style constraint failed.", keyApplicable); } }
3,268
0
Create_ds/karyon/karyon2-core/src/test/java/netflix/karyon/server
Create_ds/karyon/karyon2-core/src/test/java/netflix/karyon/server/interceptor/TestableInboundInterceptor.java
package netflix.karyon.server.interceptor; import io.netty.buffer.ByteBuf; import netflix.karyon.server.MockChannelHandlerContext; import netflix.karyon.transport.interceptor.InboundInterceptor; import netflix.karyon.transport.interceptor.InterceptorKey; import netflix.karyon.transport.interceptor.KeyEvaluationContext; import rx.Observable; /** * @author Nitesh Kant */ class TestableInboundInterceptor implements InboundInterceptor<ByteBuf, ByteBuf> { private final InterceptorKey<ByteBuf, KeyEvaluationContext> filterKey; private volatile boolean wasLastCallValid; private volatile boolean receivedACall; public TestableInboundInterceptor(InterceptorKey<ByteBuf, KeyEvaluationContext> filterKey) { this.filterKey = filterKey; } public boolean wasLastCallValid() { return wasLastCallValid; } boolean isReceivedACall() { return receivedACall; } @Override public Observable<Void> in(ByteBuf request, ByteBuf response) { MockChannelHandlerContext context = new MockChannelHandlerContext("mock"); wasLastCallValid = filterKey.apply(request, new KeyEvaluationContext(context.channel())); receivedACall = true; return Observable.empty(); } }
3,269
0
Create_ds/karyon/karyon2-core/src/test/java/netflix/karyon/server
Create_ds/karyon/karyon2-core/src/test/java/netflix/karyon/server/interceptor/InterceptorExecutorTest.java
package netflix.karyon.server.interceptor; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import netflix.karyon.server.MockChannelHandlerContext; import netflix.karyon.transport.interceptor.InterceptorExecutor; import netflix.karyon.transport.interceptor.InterceptorKey; import netflix.karyon.transport.interceptor.InterceptorSupport; import netflix.karyon.transport.interceptor.KeyEvaluationContext; import org.junit.Assert; import org.junit.Test; import rx.functions.Action0; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * @author Nitesh Kant */ public class InterceptorExecutorTest { @Test public void testInbound() throws Exception { InterceptorKey<ByteBuf, KeyEvaluationContext> key = new MockKey(true); TestableInboundInterceptor interceptor1 = new TestableInboundInterceptor(key); TestableInboundInterceptor interceptor2 = new TestableInboundInterceptor(key); TestableInboundInterceptor interceptor3 = new TestableInboundInterceptor(key); InterceptorSupport<ByteBuf, ByteBuf, KeyEvaluationContext> support = new InterceptorSupport<ByteBuf, ByteBuf, KeyEvaluationContext>(); support.forKey(key).intercept(interceptor1); support.forKey(key).intercept(interceptor2); support.forKey(key).intercept(interceptor3); TestableRequestRouter<ByteBuf, ByteBuf> router = new TestableRequestRouter<ByteBuf, ByteBuf>(); InterceptorExecutor<ByteBuf, ByteBuf, KeyEvaluationContext> executor = new InterceptorExecutor<ByteBuf, ByteBuf, KeyEvaluationContext>(support, router); executeAndAwait(executor); Assert.assertTrue("1st interceptor did not get invoked.", interceptor1.isReceivedACall()); Assert.assertTrue("2rd interceptor did not get invoked.", interceptor2.isReceivedACall()); Assert.assertTrue("3rd interceptor did not get invoked.", interceptor3.isReceivedACall()); Assert.assertTrue("Tail interceptor did not get invoked.", router.isReceivedACall()); } @Test public void testOutbound() throws Exception { InterceptorKey<ByteBuf, KeyEvaluationContext> key = new MockKey(true); TestableOutboundInterceptor interceptor1 = new TestableOutboundInterceptor(key); TestableOutboundInterceptor interceptor2 = new TestableOutboundInterceptor(key); TestableOutboundInterceptor interceptor3 = new TestableOutboundInterceptor(key); InterceptorSupport<ByteBuf, ByteBuf, KeyEvaluationContext> support = new InterceptorSupport<ByteBuf, ByteBuf, KeyEvaluationContext>(); support.forKey(key).intercept(interceptor1); support.forKey(key).intercept(interceptor2); support.forKey(key).intercept(interceptor3); TestableRequestRouter<ByteBuf, ByteBuf> router = new TestableRequestRouter<ByteBuf, ByteBuf>(); InterceptorExecutor<ByteBuf, ByteBuf, KeyEvaluationContext> executor = new InterceptorExecutor<ByteBuf, ByteBuf, KeyEvaluationContext>(support, router); executeAndAwait(executor); Assert.assertTrue("1st interceptor did not get invoked.", interceptor1.isReceivedACall()); Assert.assertTrue("2rd interceptor did not get invoked.", interceptor2.isReceivedACall()); Assert.assertTrue("3rd interceptor did not get invoked.", interceptor3.isReceivedACall()); Assert.assertTrue("Tail interceptor did not get invoked.", router.isReceivedACall()); } @Test public void testUnsubscribe() throws Exception { TestableRequestRouter<ByteBuf, ByteBuf> router = new TestableRequestRouter<ByteBuf, ByteBuf>(); InterceptorSupport<ByteBuf, ByteBuf, KeyEvaluationContext> support = new InterceptorSupport<ByteBuf, ByteBuf, KeyEvaluationContext>(); InterceptorExecutor<ByteBuf, ByteBuf, KeyEvaluationContext> executor = new InterceptorExecutor<ByteBuf, ByteBuf, KeyEvaluationContext>(support, router); executeAndAwait(executor); Assert.assertTrue("Router did not get invoked.", router.isReceivedACall()); Assert.assertTrue("Router did not get unsubscribed.", router.isUnsubscribed()); } protected void executeAndAwait(InterceptorExecutor<ByteBuf, ByteBuf, KeyEvaluationContext> executor) throws InterruptedException { final CountDownLatch completionLatch = new CountDownLatch(1); executor.execute(Unpooled.buffer(), Unpooled.buffer(), new KeyEvaluationContext(new MockChannelHandlerContext("mock").channel())) .doOnCompleted(new Action0() { @Override public void call() { completionLatch.countDown(); } }) .subscribe(); completionLatch.await(1, TimeUnit.MINUTES); } }
3,270
0
Create_ds/karyon/karyon2-core/src/test/java/netflix/karyon/server
Create_ds/karyon/karyon2-core/src/test/java/netflix/karyon/server/interceptor/TestableDuplexInterceptor.java
package netflix.karyon.server.interceptor; import io.netty.buffer.ByteBuf; import netflix.karyon.server.MockChannelHandlerContext; import netflix.karyon.transport.interceptor.DuplexInterceptor; import netflix.karyon.transport.interceptor.InterceptorKey; import netflix.karyon.transport.interceptor.KeyEvaluationContext; import rx.Observable; /** * @author Nitesh Kant */ public class TestableDuplexInterceptor implements DuplexInterceptor<ByteBuf, ByteBuf> { private final InterceptorKey<ByteBuf, KeyEvaluationContext> filterKey; private volatile boolean inCalled; private volatile boolean outCalled; private volatile boolean wasLastInCallValid; private volatile boolean wasLastOutCallValid; @SuppressWarnings("unchecked") public TestableDuplexInterceptor(InterceptorKey<ByteBuf, KeyEvaluationContext> filterKey) { this.filterKey = filterKey; } public boolean isCalledForIn() { return inCalled; } public boolean isCalledForOut() { return outCalled; } public boolean wasLastInCallValid() { return wasLastInCallValid; } public boolean wasLastOutCallValid() { return wasLastOutCallValid; } @Override public Observable<Void> in(ByteBuf request, ByteBuf response) { inCalled = true; MockChannelHandlerContext mock = new MockChannelHandlerContext("mock"); wasLastInCallValid = filterKey.apply(request, new KeyEvaluationContext(mock.channel())); return Observable.empty(); } @Override public Observable<Void> out(ByteBuf response) { outCalled = true; wasLastOutCallValid = filterKey.apply(response, new KeyEvaluationContext(new MockChannelHandlerContext("").channel())); return Observable.empty(); } }
3,271
0
Create_ds/karyon/karyon2-core/src/test/java/netflix/karyon/server
Create_ds/karyon/karyon2-core/src/test/java/netflix/karyon/server/interceptor/TestableRequestRouter.java
package netflix.karyon.server.interceptor; import io.reactivex.netty.channel.Handler; import rx.Observable; import rx.functions.Action0; /** * @author Nitesh Kant */ class TestableRequestRouter<I, O> implements Handler<I, O> { private volatile boolean called; private volatile boolean unsubscribed; public boolean isReceivedACall() { return called; } public boolean isUnsubscribed() { return unsubscribed; } @Override public Observable<Void> handle(I input, O output) { called = true; return Observable.<Void>empty().doOnUnsubscribe(new Action0() { @Override public void call() { unsubscribed = true; } }); } }
3,272
0
Create_ds/karyon/karyon2-core/src/test/java/netflix/karyon/server
Create_ds/karyon/karyon2-core/src/test/java/netflix/karyon/server/interceptor/MockKey.java
package netflix.karyon.server.interceptor; import io.netty.buffer.ByteBuf; import netflix.karyon.transport.interceptor.InterceptorKey; import netflix.karyon.transport.interceptor.KeyEvaluationContext; /** * @author Nitesh Kant */ class MockKey implements InterceptorKey<ByteBuf, KeyEvaluationContext> { private final boolean result; public MockKey(boolean result) { this.result = result; } @Override public boolean apply(ByteBuf request, KeyEvaluationContext context) { return result; } }
3,273
0
Create_ds/karyon/karyon2-core/src/test/java/netflix/karyon/server
Create_ds/karyon/karyon2-core/src/test/java/netflix/karyon/server/interceptor/TestableOutboundInterceptor.java
package netflix.karyon.server.interceptor; import io.netty.buffer.ByteBuf; import netflix.karyon.transport.interceptor.InterceptorKey; import netflix.karyon.transport.interceptor.KeyEvaluationContext; /** * @author Nitesh Kant */ public class TestableOutboundInterceptor extends TestableDuplexInterceptor { public TestableOutboundInterceptor(InterceptorKey<ByteBuf, KeyEvaluationContext> filterKey) { super(filterKey); } public boolean isReceivedACall() { return isCalledForOut(); } }
3,274
0
Create_ds/karyon/karyon2-core/src/main/java/netflix
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/ShutdownListener.java
package netflix.karyon; import io.reactivex.netty.RxNetty; import io.reactivex.netty.channel.ConnectionHandler; import io.reactivex.netty.channel.ObservableConnection; import io.reactivex.netty.pipeline.PipelineConfigurators; import io.reactivex.netty.server.RxServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.functions.Action0; import rx.functions.Action1; import rx.functions.Func1; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * A shutdown listener for karyon which aids shutdown of a server using a remote command over a socket. * * @author Nitesh Kant */ public class ShutdownListener { private static final Logger logger = LoggerFactory.getLogger(ShutdownListener.class); private final RxServer<String, String> shutdownCmdServer; public ShutdownListener(int shutdownPort, final Func1<String, Observable<Void>> commandHandler) { shutdownCmdServer = RxNetty.createTcpServer(shutdownPort, PipelineConfigurators.stringMessageConfigurator(), new ShutdownConnectionHandler(commandHandler)); } public ShutdownListener(int shutdownPort, final Action0 shutdownAction) { this(shutdownPort, new DefaultCommandHandler(shutdownAction)); } public int getShutdownPort() { return shutdownCmdServer.getServerPort(); } public void start() { shutdownCmdServer.start(); } public void shutdown() throws InterruptedException { shutdownCmdServer.shutdown(); } private static class DefaultCommandHandler implements Func1<String, Observable<Void>> { private final ExecutorService shutdownExec; private final Action0 shutdownAction; public DefaultCommandHandler(Action0 shutdownAction) { this.shutdownAction = shutdownAction; shutdownExec = Executors.newFixedThreadPool(1); } @Override public Observable<Void> call(String cmd) { if ("shutdown".equalsIgnoreCase(cmd)) { return shutdownAsync(); } return Observable.error(new UnsupportedOperationException("Unknown command: " + cmd)); } private Observable<Void> shutdownAsync() { final Future<Void> submitFuture = shutdownExec.submit(new Callable<Void>() { @Override public Void call() throws Exception { shutdownAction.call(); return null; } }); return Observable.interval(10, TimeUnit.SECONDS) .take(1) .map(new Func1<Long, Void>() { @Override public Void call(Long aLong) { logger.info("Checking if shutdown is done.."); if (submitFuture.isDone()) { try { submitFuture.get(); logger.info("Shutdown is done.."); } catch (InterruptedException e) { logger.info("Shutdown returned error. ", e); } catch (ExecutionException e) { if (e.getCause() instanceof IllegalStateException) { logger.info("Server already shutdown. ", e); } else { logger.info("Shutdown returned error. ", e); } } } else { logger.debug("Shutdown not yet done."); } return null; } }); } } private class ShutdownConnectionHandler implements ConnectionHandler<String, String> { private final Func1<String, Observable<Void>> commandHandler; public ShutdownConnectionHandler(Func1<String, Observable<Void>> commandHandler) { this.commandHandler = commandHandler; } @Override public Observable<Void> handle(final ObservableConnection<String, String> conn) { return conn.getInput().take(1) /*Take only one command per connection*/ .doOnNext(new Action1<String>() { @Override public void call(String s) { logger.info("Received a command: " + s); } }) .flatMap(commandHandler) .doOnCompleted(new Action0() { @Override public void call() { try { shutdown(); } catch (InterruptedException e) { logger.error("Interrupted while shutting down the shutdown command listener."); } } }); } } }
3,275
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport/KaryonTransport.java
package netflix.karyon.transport; import io.reactivex.netty.contexts.RxContexts; import io.reactivex.netty.protocol.http.server.HttpServer; import io.reactivex.netty.protocol.http.server.HttpServerBuilder; import io.reactivex.netty.protocol.http.server.RequestHandler; import netflix.karyon.transport.http.HttpRequestHandler; /** * A factory class for creating karyon transport servers which are created using * <a href="https://github.com/Netflix/RxNetty">RxNetty</a> * * @author Nitesh Kant */ public final class KaryonTransport { public static final String DEFAULT_REQUEST_ID_CTX_KEY = "X-Karyon-REQUEST_ID"; static { RxContexts.useRequestIdContextKey(DEFAULT_REQUEST_ID_CTX_KEY); } private KaryonTransport() { } public static <I, O> HttpServerBuilder<I, O> newHttpServerBuilder(int port, RequestHandler<I, O> router) { return RxContexts.newHttpServerBuilder(port, new HttpRequestHandler<I, O>(router), RxContexts.DEFAULT_CORRELATOR); } public static <I, O> HttpServerBuilder<I, O> newHttpServerBuilder(int port, HttpRequestHandler<I, O> requestHandler) { return RxContexts.newHttpServerBuilder(port, requestHandler, RxContexts.DEFAULT_CORRELATOR); } public static <I, O> HttpServer<I, O> newHttpServer(int port, RequestHandler<I, O> router) { return newHttpServerBuilder(port, router).build(); } public static <I, O> HttpServer<I, O> newHttpServer(int port, HttpRequestHandler<I, O> requestHandler) { return newHttpServerBuilder(port, requestHandler).build(); } /** * Karyon * * @param name The name of the context key to be used as default. */ public static void useRequestIdContextKey(String name) { RxContexts.useRequestIdContextKey(name); } }
3,276
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport/RequestRouter.java
package netflix.karyon.transport; import rx.Observable; /** * @author Nitesh Kant * * @deprecated Use RxNetty's {@link io.reactivex.netty.channel.Handler} instead. */ @Deprecated public interface RequestRouter<I, O> { Observable<Void> route(I request, O response); }
3,277
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport/http/HttpKeyEvaluationContext.java
package netflix.karyon.transport.http; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.HttpRequest; import io.netty.util.Attribute; import io.netty.util.AttributeKey; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import netflix.karyon.transport.interceptor.KeyEvaluationContext; /** * @author Nitesh Kant */ public class HttpKeyEvaluationContext extends KeyEvaluationContext { /** * In order to optimize for request URI parsing, karyon stores the {@link QueryStringDecoder} instances, if created, * in the {@link io.netty.channel.ChannelHandlerContext} as an {@link io.netty.util.Attribute}. <br> * This attribute is not always available and hence the users must always check for availability. It is always a * good practice to store the decoder back in the context, once created so that other code can use it if required. */ public static final AttributeKey<QueryStringDecoder> queryDecoderKey = AttributeKey.valueOf("_queryStringDecoder"); private QueryStringDecoder queryStringDecoder; public HttpKeyEvaluationContext(Channel channel) { super(channel); channel.attr(queryDecoderKey).remove(); } /** * Parses (if not done previously) and returns the path component in the URI. * * @param httpRequest HTTP request for which the URI path is to be returned. * * @return The path component of the URI (as returned by {@link HttpRequest#getUri()} or {@code null} if the * URI is null. */ String getRequestUriPath(HttpServerRequest<?> httpRequest) { String uri = httpRequest.getUri(); if (null == uri) { return null; } if (null == queryStringDecoder) { if (null == channel) { queryStringDecoder = new QueryStringDecoder(uri); } else { queryStringDecoder = getOrCreateQueryStringDecoder(httpRequest); } } return queryStringDecoder.nettyDecoder().path(); } private QueryStringDecoder getOrCreateQueryStringDecoder(HttpServerRequest<?> request) { if (null == request) { throw new NullPointerException("Request can not be null."); } String uri = request.getUri(); if (null == uri) { return null; } Attribute<QueryStringDecoder> queryDecoderAttr = channel.attr(queryDecoderKey); QueryStringDecoder _queryStringDecoder = queryDecoderAttr.get(); if (null == _queryStringDecoder) { _queryStringDecoder = new QueryStringDecoder(uri); queryDecoderAttr.setIfAbsent(_queryStringDecoder); } return _queryStringDecoder; } public static QueryStringDecoder getOrCreateQueryStringDecoder(HttpServerRequest<?> request, ChannelHandlerContext channelHandlerContext) { if (null == request) { throw new NullPointerException("Request can not be null."); } String uri = request.getUri(); if (null == uri) { return null; } Attribute<QueryStringDecoder> queryDecoderAttr = channelHandlerContext.attr(queryDecoderKey); QueryStringDecoder _queryStringDecoder = queryDecoderAttr.get(); if (null == _queryStringDecoder) { _queryStringDecoder = new QueryStringDecoder(uri); queryDecoderAttr.setIfAbsent(_queryStringDecoder); } return _queryStringDecoder; } }
3,278
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport/http/SimpleUriRouter.java
package netflix.karyon.transport.http; import io.netty.handler.codec.http.HttpResponseStatus; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.server.RequestHandler; import netflix.karyon.transport.interceptor.InterceptorKey; import rx.Observable; import java.util.concurrent.CopyOnWriteArrayList; /** * A simple implementation for handling requests for different URIs. This router provides a facility to update the * routes at runtime. Thread-safety is maintained by using a "copy-on-write" data structure underneath, hence it comes * with an object allocation cost. * * The correct way to use this router would be to create all the routes at startup and then do not update the routes * at runtime unless it is required. * * @author Nitesh Kant */ public class SimpleUriRouter<I, O> implements RequestHandler<I, O> { private final CopyOnWriteArrayList<Route> routes; public SimpleUriRouter() { routes = new CopyOnWriteArrayList<Route>(); } @Override public Observable<Void> handle(HttpServerRequest<I> request, HttpServerResponse<O> response) { HttpKeyEvaluationContext context = new HttpKeyEvaluationContext(response.getChannel()); for (Route route : routes) { if (route.key.apply(request, context)) { return route.getHandler().handle(request, response); } } // None of the routes matched. response.setStatus(HttpResponseStatus.NOT_FOUND); return response.close(); } /** * Add a new URI -&lt; Handler route to this router. * @param uri URI to match. * @param handler Request handler. * @return The updated router. */ public SimpleUriRouter<I, O> addUri(String uri, RequestHandler<I, O> handler) { routes.add(new Route(new ServletStyleUriConstraintKey<I>(uri, ""), handler)); return this; } /** * Add a new URI regex -&lt; Handler route to this router. * @param uriRegEx URI regex to match * @param handler Request handler. * @return The updated router. */ public SimpleUriRouter<I, O> addUriRegex(String uriRegEx, RequestHandler<I, O> handler) { routes.add(new Route(new RegexUriConstraintKey<I>(uriRegEx), handler)); return this; } private class Route { private final InterceptorKey<HttpServerRequest<I>, HttpKeyEvaluationContext> key; private final RequestHandler<I, O> handler; public Route(InterceptorKey<HttpServerRequest<I>, HttpKeyEvaluationContext> key, RequestHandler<I, O> handler) { this.key = key; this.handler = handler; } public InterceptorKey<HttpServerRequest<I>, HttpKeyEvaluationContext> getKey() { return key; } public RequestHandler<I, O> getHandler() { return handler; } } }
3,279
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport/http/HttpRequestHandlerBuilder.java
package netflix.karyon.transport.http; import io.netty.handler.codec.http.HttpMethod; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.RequestHandler; import netflix.karyon.transport.interceptor.InterceptorKey; /** * A convenience builder to create {@link HttpRequestHandler} instances. * * @author Nitesh Kant */ public class HttpRequestHandlerBuilder<I, O> { private final HttpInterceptorSupport<I, O> interceptorSupport; private final RequestHandler<I, O> router; public HttpRequestHandlerBuilder(RequestHandler<I, O> router) { this(new HttpInterceptorSupport<I, O>(), router); } public HttpRequestHandlerBuilder(HttpInterceptorSupport<I, O> interceptorSupport, RequestHandler<I, O> router) { this.interceptorSupport = interceptorSupport; this.router = router; } public HttpInterceptorSupport.HttpAttacher<I, O> forKey(InterceptorKey<HttpServerRequest<I>, HttpKeyEvaluationContext> key) { return interceptorSupport.forKey(key); } public HttpInterceptorSupport.HttpAttacher<I, O> forUri(String uri) { return interceptorSupport.forUri(uri); } public HttpInterceptorSupport.HttpAttacher<I, O> forUriRegex(String uriRegEx) { return interceptorSupport.forUriRegex(uriRegEx); } public HttpInterceptorSupport.HttpAttacher<I, O> forHttpMethod(HttpMethod method) { return interceptorSupport.forHttpMethod(method); } public HttpInterceptorSupport<I, O> getInterceptorSupport() { return interceptorSupport; } public RequestHandler<I, O> getRouter() { return router; } public HttpRequestHandler<I, O> build() { interceptorSupport.finish(); return new HttpRequestHandler<I, O>(router, interceptorSupport); } }
3,280
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport/http/HttpInterceptorKey.java
package netflix.karyon.transport.http; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import netflix.karyon.transport.interceptor.InterceptorKey; /** * @author Nitesh Kant */ public interface HttpInterceptorKey<I> extends InterceptorKey<HttpServerRequest<I>, HttpKeyEvaluationContext> { }
3,281
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport/http/RegexUriConstraintKey.java
package netflix.karyon.transport.http; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Provides constraint implementation for {@link netflix.karyon.transport.interceptor.InterceptorKey} for matching URI paths as regular expressions as * supported by {@link java.util.regex.Pattern}. * The request URI path is as retrieved using: {@link HttpKeyEvaluationContext#getRequestUriPath(HttpServerRequest)} * * @author Nitesh Kant */ public class RegexUriConstraintKey<I> implements HttpInterceptorKey<I> { private static final Logger logger = LoggerFactory.getLogger(RegexUriConstraintKey.class); private final Pattern regEx; public RegexUriConstraintKey(String constraint) { if (null == constraint) { throw new NullPointerException("Constraint can not be null."); } regEx = Pattern.compile(constraint); } @Override public String toString() { return "RegexUriConstraintKey{" + "regEx=" + regEx + '}'; } @Override public boolean apply(HttpServerRequest<I> request, HttpKeyEvaluationContext context) { String requestUriPath = context.getRequestUriPath(request); boolean matches = false; if (null != requestUriPath) { Matcher matcher = regEx.matcher(requestUriPath); matches = matcher.matches(); } if (logger.isDebugEnabled()) { logger.debug("Result for regex based uri constraint for uri path {} and pattern {} : {}", requestUriPath, regEx, matches); } return matches; } }
3,282
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport/http/QueryStringDecoder.java
package netflix.karyon.transport.http; /** * A simple wrapper over {@link io.netty.handler.codec.http.QueryStringDecoder} to also provide access to the uri string. * * @author Nitesh Kant */ public class QueryStringDecoder { private final io.netty.handler.codec.http.QueryStringDecoder nettyDecoder; private final String uri; public QueryStringDecoder(String uri) { if (null == uri) { throw new NullPointerException("Uri can not be null."); } this.uri = uri; uri = io.netty.handler.codec.http.QueryStringDecoder.decodeComponent(uri); if (!uri.endsWith("/") && !uri.contains(".") && !uri.contains("?")) { // Normalize the URI for better matching of Servlet style URI constraints. uri += "/"; } nettyDecoder = new io.netty.handler.codec.http.QueryStringDecoder(uri); } public io.netty.handler.codec.http.QueryStringDecoder nettyDecoder() { return nettyDecoder; } public String uri() { return uri; } }
3,283
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport/http/ServletStyleUriConstraintKey.java
package netflix.karyon.transport.http; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provides constraint implementation for {@link netflix.karyon.transport.interceptor.InterceptorKey} similar to java servlet specifications. <p></p> * The following types of constraints are supported: * <ul> <li>Exact uri mapping: Give the exact string that should match the URI path of the incoming request. eg: "/myresource/foo" will match <em>ALL</em> the URIs: <ul> <li>"/myresource/foo"</li> <li>"/myresource/foo/"</li> </ul> <li> Prefix uri mapping: Give the prefix in the URI path you want to match, ending with a "*". eg: "/myresource/foo/*" will match <em>ALL</em> the URIs: <ul> <li>"/myresource/foo/bar"</li> <li>"/myresource/foo/"</li> <li>"/myresource/foo"</li> </ul> </li> </ul> * * In any of the pattersn above the leading slash in the constraint is optional, i.e., "/myresource/foo" is equivalent to * "myresource/foo". * * As compared to servlets/web applications there are no context paths of an application so the URI path has to be * absolute. <br> * * The request URI path is as retrieved using: {@link HttpKeyEvaluationContext#getRequestUriPath(HttpServerRequest)} * * @author Nitesh Kant */ public class ServletStyleUriConstraintKey<I> implements HttpInterceptorKey<I> { private static final Logger logger = LoggerFactory.getLogger(ServletStyleUriConstraintKey.class); private final Matcher matcher; private final String contextPath; public ServletStyleUriConstraintKey(final String constraint, final String contextPath) { if (null == constraint) { throw new NullPointerException("Constraint can not be null."); } this.contextPath = contextPath.startsWith("/") ? contextPath : '/' + contextPath; // uri & constraint always starts with a / String normalizedConstraint = constraint; if (!constraint.startsWith("/")) { // URI always comes with a leading '/' normalizedConstraint = '/' + constraint; } if (normalizedConstraint.startsWith("/*.")) { matcher = new ExtensionMatcher( constraint); // not normalizedConstraint as then we will have to ignore the first character. } else if (normalizedConstraint.endsWith("/*")) { matcher = new PrefixMatcher(normalizedConstraint.substring(0, normalizedConstraint.length() - 1), new Matcher(normalizedConstraint.substring(0, normalizedConstraint.length() - 2), null)); // Prefix match removing * or exact match removing /* } else if (normalizedConstraint.endsWith("*")) { matcher = new PrefixMatcher(normalizedConstraint.substring(0, normalizedConstraint.length() - 1), null); } else { matcher = new Matcher(normalizedConstraint, new Matcher(normalizedConstraint + '/', null)); } } /** * This must be called if and only if {@link #apply(HttpServerRequest, HttpKeyEvaluationContext)} * returned for the same request. * * @param request Request which satisfies this key. * @param context The key evaluation context. * * @return The servlet path. */ public String getServletPath(HttpServerRequest<I> request, HttpKeyEvaluationContext context) { String requestUriPath = context.getRequestUriPath(request); if (null != requestUriPath) { return matcher.getServletPath(requestUriPath); } return ""; } @Override public boolean apply(HttpServerRequest<I> request, HttpKeyEvaluationContext context) { String requestUriPath = context.getRequestUriPath(request); boolean matches = false; if (null != requestUriPath) { matches = matcher.match(requestUriPath); } return matches; } private class Matcher { protected final String constraint; protected final String constraintWithoutContextPath; private final Matcher nextMatcher; private Matcher(String constraint, Matcher nextMatcher) { this.constraint = constraint; constraintWithoutContextPath = constraint.isEmpty() ? constraint : constraint.substring(contextPath.length()); this.nextMatcher = nextMatcher; } protected boolean match(String requestUriPath) { return isMatching(requestUriPath, false) || null != nextMatcher && nextMatcher.match(requestUriPath); } protected boolean isMatching(String requestUriPath, boolean noLog) { boolean matches = requestUriPath.equals(constraint); if (!noLog && logger.isDebugEnabled()) { logger.debug("Exact match result for servlet style uri constraint for uri path {} and constraint {} : {}", requestUriPath, constraint, matches); } return matches; } public String getServletPath(String requestUriPath) { if (requestUriPath.equals(constraint)) { // exact match & hence not required to query the next matcher. return constraintWithoutContextPath; } return null != nextMatcher ? nextMatcher.getServletPath(requestUriPath) : ""; } @Override public String toString() { return "Matcher{" + "constraint='" + constraint + '\'' + ", nextMatcher=" + nextMatcher + '}'; } } private class PrefixMatcher extends Matcher { private PrefixMatcher(String prefix, Matcher nextMatcher) { super(prefix, nextMatcher); } @Override protected boolean isMatching(String requestUriPath, boolean noLog) { boolean matches = requestUriPath.startsWith(constraint); if (!noLog && logger.isDebugEnabled()) { logger.debug("Prefix match result for servlet style uri constraint for uri path {} and constraint {} : {}", requestUriPath, constraint, matches); } return matches; } @Override public String getServletPath(String requestUriPath) { if (isMatching(requestUriPath, true)) { return constraintWithoutContextPath.substring(0, constraintWithoutContextPath.length() - 1); // Leaving out the postfix of *, this is what we need. } return super.getServletPath(requestUriPath); } } private class ExtensionMatcher extends Matcher { private ExtensionMatcher(String constraint) { super(constraint.substring(1), null); // This matcher does a contains query removing the * prefix } @Override protected boolean isMatching(String requestUriPath, boolean noLog) { boolean matches = requestUriPath.contains(constraint);// The constructor removes the preciding * in the constraint. if (!noLog && logger.isDebugEnabled()) { logger.debug("Extension match result for servlet style uri constraint for uri path {} and constraint {} : {}", requestUriPath, constraint, matches); } return matches; } @Override public String getServletPath(String requestUriPath) { if (isMatching(requestUriPath, true)) { return ""; // Extension mapping does not have servlet path. } return super.getServletPath(requestUriPath); } } @Override public String toString() { return "ServletStyleUriConstraintKey{" + "matcher=" + matcher + '}'; } }
3,284
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport/http/HttpInterceptorSupport.java
package netflix.karyon.transport.http; import io.netty.handler.codec.http.HttpMethod; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import netflix.karyon.transport.interceptor.AbstractAttacher; import netflix.karyon.transport.interceptor.AbstractInterceptorSupport; import netflix.karyon.transport.interceptor.InterceptorKey; /** * An extension of {@link netflix.karyon.transport.interceptor.InterceptorSupport} to add HTTP specific methods for attaching interceptors. * * @author Nitesh Kant */ public class HttpInterceptorSupport<I, O> extends AbstractInterceptorSupport<HttpServerRequest<I>, HttpServerResponse<O>, HttpKeyEvaluationContext, HttpInterceptorSupport.HttpAttacher<I, O>, HttpInterceptorSupport<I, O>> { @Override protected HttpAttacher<I, O> newAttacher(InterceptorKey<HttpServerRequest<I>, HttpKeyEvaluationContext> key) { return new HttpAttacher<I, O>(this, key); } public HttpAttacher<I, O> forUri(String uri) { if (null == uri || uri.isEmpty()) { throw new IllegalArgumentException("Uri can not be null or empty."); } return getAttacherForKey(new ServletStyleUriConstraintKey<I>(uri, "")); } public HttpAttacher<I, O> forUriRegex(String uriRegEx) { if (null == uriRegEx || uriRegEx.isEmpty()) { throw new IllegalArgumentException("Uri regular expression can not be null or empty."); } return getAttacherForKey(new RegexUriConstraintKey<I>(uriRegEx)); } public HttpAttacher<I, O> forHttpMethod(HttpMethod method) { if (null == method) { throw new IllegalArgumentException("Uri can not be null or empty."); } return getAttacherForKey(new MethodConstraintKey<I>(method)); } public static class HttpAttacher<I, O> extends AbstractAttacher<HttpServerRequest<I>, HttpServerResponse<O>, HttpKeyEvaluationContext, HttpInterceptorSupport<I, O>> { public HttpAttacher(HttpInterceptorSupport<I, O> support, InterceptorKey<HttpServerRequest<I>, HttpKeyEvaluationContext> key) { super(support, key); } } }
3,285
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport/http/MethodConstraintKey.java
package netflix.karyon.transport.http; import io.netty.handler.codec.http.HttpMethod; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Nitesh Kant */ public class MethodConstraintKey<I> implements HttpInterceptorKey<I> { private static final Logger logger = LoggerFactory.getLogger(MethodConstraintKey.class); private final HttpMethod method; public MethodConstraintKey(HttpMethod method) { if (null == method) { throw new NullPointerException("HTTP method in the interceptor constraint can not be null."); } this.method = method; } @Override public String toString() { return "MethodConstraintKey{" + "method=" + method + '}'; } @Override public boolean apply(HttpServerRequest<I> request, HttpKeyEvaluationContext context) { boolean matches = request.getHttpMethod().equals(method); if (logger.isDebugEnabled()) { logger.debug("Result for HTTP method constraint for method {} and required method {} : {}", request.getHttpMethod(), method, matches); } return matches; } }
3,286
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport/http/HttpRequestHandler.java
package netflix.karyon.transport.http; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.server.RequestHandler; import netflix.karyon.transport.interceptor.AbstractInterceptorSupport; import netflix.karyon.transport.interceptor.InterceptorExecutor; import rx.Observable; /** * An implementation of {@link RequestHandler} for karyon. * * @author Nitesh Kant */ public class HttpRequestHandler<I, O> implements RequestHandler<I, O> { private final InterceptorExecutor<HttpServerRequest<I>, HttpServerResponse<O>, HttpKeyEvaluationContext> executor; public HttpRequestHandler(RequestHandler<I, O> router) { this(router, new HttpInterceptorSupport<I, O>()); } public HttpRequestHandler(RequestHandler<I, O> router, AbstractInterceptorSupport<HttpServerRequest<I>, HttpServerResponse<O>, HttpKeyEvaluationContext, ?, ?> interceptorSupport) { executor = new InterceptorExecutor<HttpServerRequest<I>, HttpServerResponse<O>, HttpKeyEvaluationContext>(interceptorSupport, router); } @Override public Observable<Void> handle(HttpServerRequest<I> request, HttpServerResponse<O> response) { return executor.execute(request, response, new HttpKeyEvaluationContext(response.getChannel())); } }
3,287
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport/interceptor/AbstractInterceptorSupport.java
package netflix.karyon.transport.interceptor; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * @author Nitesh Kant */ public abstract class AbstractInterceptorSupport<I, O, C extends KeyEvaluationContext, A extends AbstractAttacher<I, O, C, S>, S extends AbstractInterceptorSupport<I, O, C, A, S>> { protected final Map<InterceptorKey<I, C>, A> attachers; protected List<InterceptorHolder<I, C, InboundInterceptor<I, O>>> inboundInterceptors; protected List<InterceptorHolder<I, C, OutboundInterceptor<O>>> outboundInterceptors; protected boolean finished; public AbstractInterceptorSupport() { attachers = new HashMap<InterceptorKey<I, C>, A>(); inboundInterceptors = new LinkedList<InterceptorHolder<I, C, InboundInterceptor<I, O>>>(); outboundInterceptors = new LinkedList<InterceptorHolder<I, C, OutboundInterceptor<O>>>(); } protected List<InterceptorHolder<I, C, InboundInterceptor<I, O>>> getInboundInterceptors() { return inboundInterceptors; } protected List<InterceptorHolder<I, C, OutboundInterceptor<O>>> getOutboundInterceptors() { return outboundInterceptors; } public A forKey(InterceptorKey<I, C> key) { if (finished) { throw new IllegalArgumentException("Interceptor support can not be modified after finishing."); } return getAttacherForKey(key); } protected A getAttacherForKey(InterceptorKey<I, C> key) { A attacher = attachers.get(key); if (null == attacher) { attacher = newAttacher(key); attachers.put(key, attacher); } return attacher; } protected abstract A newAttacher(InterceptorKey<I, C> key); public boolean hasAtleastOneInterceptor() { return !inboundInterceptors.isEmpty() || !outboundInterceptors.isEmpty(); } public S finish() { if (!finished) { _finish(); finished = true; } return returnSupport(); } protected void _finish() { attachers.clear(); inboundInterceptors = Collections.unmodifiableList(inboundInterceptors); outboundInterceptors = Collections.unmodifiableList(outboundInterceptors); } @SuppressWarnings("unchecked") protected S returnSupport() { return (S) this; } }
3,288
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport/interceptor/OutboundInterceptor.java
package netflix.karyon.transport.interceptor; import rx.Observable; /** * @author Nitesh Kant */ public interface OutboundInterceptor<O> { Observable<Void> out(O response); }
3,289
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport/interceptor/KeyEvaluationContext.java
package netflix.karyon.transport.interceptor; import io.netty.channel.Channel; import java.util.HashMap; import java.util.Map; /** * A context to store results of costly operations during evaluation of filter keys, eg: request URI parsing. * <b>This context is not thread-safe.</b> */ public class KeyEvaluationContext { protected final Channel channel; public KeyEvaluationContext(Channel channel) { this.channel = channel; } enum KeyEvaluationResult { Apply, Skip, NotExecuted } private final Map<InterceptorKey<?, ?>, Boolean> keyEvaluationCache = new HashMap<InterceptorKey<?, ?>, Boolean>(); protected void updateKeyEvaluationResult(InterceptorKey<?, ?> key, boolean result) { keyEvaluationCache.put(key, result); } protected KeyEvaluationResult getEvaluationResult(InterceptorKey<?, ?> key) { Boolean result = keyEvaluationCache.get(key); return null == result ? KeyEvaluationResult.NotExecuted : result ? KeyEvaluationResult.Apply : KeyEvaluationResult.Skip; } }
3,290
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport/interceptor/AbstractAttacher.java
package netflix.karyon.transport.interceptor; import java.util.Arrays; import java.util.List; /** * @author Nitesh Kant */ public class AbstractAttacher<I, O, C extends KeyEvaluationContext, S extends AbstractInterceptorSupport> { protected final S interceptorSupport; protected final InterceptorKey<I, C> key; public AbstractAttacher(S interceptorSupport, InterceptorKey<I, C> key) { this.interceptorSupport = interceptorSupport; this.key = key; } @SuppressWarnings({"unchecked", "rawtypes"}) public S intercept(InboundInterceptor<I, O>... interceptors) { List list = interceptorSupport.getInboundInterceptors(); list.add(new InterceptorHolder<I, C, InboundInterceptor<I, O>>(key, Arrays.asList(interceptors))); return interceptorSupport; } @SuppressWarnings({"unchecked", "rawtypes"}) public S intercept(OutboundInterceptor<O>... interceptors) { List list = interceptorSupport.getOutboundInterceptors(); list.add(new InterceptorHolder<I, C, OutboundInterceptor<O>>(key, Arrays.asList(interceptors))); return interceptorSupport; } @SuppressWarnings({"unchecked", "rawtypes"}) public S intercept(DuplexInterceptor<I, O>... interceptors) { List ins = interceptorSupport.getInboundInterceptors(); ins.add(new InterceptorHolder(key, Arrays.asList(interceptors))); List outs = interceptorSupport.getOutboundInterceptors(); outs.add(new InterceptorHolder(key, Arrays.asList(interceptors))); return interceptorSupport; } public InterceptorKey<I, C> getKey() { return key; } }
3,291
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport/interceptor/InboundInterceptor.java
package netflix.karyon.transport.interceptor; import rx.Observable; /** * @author Nitesh Kant */ public interface InboundInterceptor<I, O> { Observable<Void> in(I request, O response); }
3,292
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport/interceptor/InterceptorSupport.java
package netflix.karyon.transport.interceptor; /** * A contract to support interceptors for requests i.e. how to attach filters to a request processing. * * @author Nitesh Kant */ public class InterceptorSupport<I, O, C extends KeyEvaluationContext> extends AbstractInterceptorSupport<I, O, C, InterceptorSupport.Attacher<I, O, C>, InterceptorSupport<I, O, C>> { @Override protected Attacher<I, O, C> newAttacher(InterceptorKey<I, C> key) { return new Attacher<I, O, C>(this, key); } public static class Attacher<I, O, C extends KeyEvaluationContext> extends AbstractAttacher<I, O, C, InterceptorSupport<I, O, C>> { public Attacher(InterceptorSupport<I, O, C> interceptorSupport, InterceptorKey<I, C> key) { super(interceptorSupport, key); } } }
3,293
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport/interceptor/InterceptorExecutor.java
package netflix.karyon.transport.interceptor; import io.reactivex.netty.channel.Handler; import netflix.karyon.transport.RequestRouter; import rx.Observable; import rx.Subscriber; import rx.subscriptions.SerialSubscription; import java.util.ArrayList; import java.util.List; /** * A utility class to execute a chain of interceptors defined by {@link InterceptorSupport} * * @author Nitesh Kant */ public class InterceptorExecutor<I, O, C extends KeyEvaluationContext> { private final List<InterceptorHolder<I, C, InboundInterceptor<I, O>>> allIn; private final List<InterceptorHolder<I, C, OutboundInterceptor<O>>> allOut; private final Handler<I, O> router; public InterceptorExecutor(AbstractInterceptorSupport<I, O, C, ?, ?> support, Handler<I, O> router) { this.router = router; allIn = support.getInboundInterceptors(); allOut = support.getOutboundInterceptors(); } /** * @deprecated Use {@link #InterceptorExecutor(AbstractInterceptorSupport, Handler)} instead. */ @Deprecated public InterceptorExecutor(AbstractInterceptorSupport<I, O, C, ?, ?> support, final RequestRouter<I, O> router) { this.router = new Handler<I, O>() { @Override public Observable<Void> handle(I input, O output) { return router.route(input, output); } }; allIn = support.getInboundInterceptors(); allOut = support.getOutboundInterceptors(); } /** * Executes the interceptor chain for the passed request and response. * * @param request Request to be executed. * @param response Response to be populated. * @param keyEvaluationContext The context for {@link InterceptorKey} evaluation. * * @return The final result of execution after executing all the inbound and outbound interceptors and the router. */ public Observable<Void> execute(final I request, final O response, C keyEvaluationContext) { final ExecutionContext context = new ExecutionContext(request, keyEvaluationContext); InboundInterceptor<I, O> nextIn = context.nextIn(request); Observable<Void> startingPoint; if (null != nextIn) { startingPoint = nextIn.in(request, response); } else if (context.invokeRouter()){ startingPoint = router.handle(request, response); } else { return Observable.error(new IllegalStateException("No router defined.")); // No router defined. } return startingPoint.lift(new Observable.Operator<Void, Void>() { @Override public Subscriber<? super Void> call(Subscriber<? super Void> child) { SerialSubscription subscription = new SerialSubscription(); ChainSubscriber chainSubscriber = new ChainSubscriber(subscription, context, request, response, child); subscription.set(chainSubscriber); child.add(subscription); return chainSubscriber; } }); } private enum NextExecutionState { NotStarted, NextInHolder, NextInInterceptor, Router, NextOutInterceptor, End} private class ExecutionContext { private final C keyEvaluationContext; private NextExecutionState nextExecutionState = NextExecutionState.NotStarted; /** * This list is eagerly created by evaluating keys of all out interceptors as we do not want to hold the * request (for key evaluation) till the outbound interceptor execution starts. */ private List<OutboundInterceptor<O>> applicableOutInterceptors; private int currentHolderIndex; private int currentInterceptorIndex; public ExecutionContext(I request, C keyEvaluationContext) { this.keyEvaluationContext = keyEvaluationContext; applicableOutInterceptors = new ArrayList<OutboundInterceptor<O>>(); // Execution is not multi-threaded. for (InterceptorHolder<I, C, OutboundInterceptor<O>> holder : allOut) { switch (keyEvaluationContext.getEvaluationResult(holder.getKey())) { // Result is cached. case Apply: applicableOutInterceptors.addAll(holder.getInterceptors()); break; case Skip: break; case NotExecuted: boolean apply = holder.getKey().apply(request, keyEvaluationContext); keyEvaluationContext.updateKeyEvaluationResult(holder.getKey(), apply); if (apply) { applicableOutInterceptors.addAll(holder.getInterceptors()); } break; } } } public InboundInterceptor<I, O> nextIn(I request) { switch (nextExecutionState) { case NotStarted: nextExecutionState = NextExecutionState.NextInInterceptor; // Index is 0, so we can skip the NextInHolder state. return nextIn(request); case NextInHolder: ++currentHolderIndex; currentInterceptorIndex = 0; nextExecutionState = NextExecutionState.NextInInterceptor; return nextIn(request); case NextInInterceptor: if (currentHolderIndex >= allIn.size()) { nextExecutionState = NextExecutionState.Router; return null; } else { InterceptorHolder<I, C, InboundInterceptor<I, O>> holder = allIn.get( currentHolderIndex); switch (keyEvaluationContext.getEvaluationResult(holder.getKey())) { // Result is cached. case Apply: return returnNextInterceptor(request, holder); case Skip: nextExecutionState = NextExecutionState.NextInHolder; return nextIn(request); case NotExecuted: boolean apply = holder.getKey().apply(request, keyEvaluationContext); keyEvaluationContext.updateKeyEvaluationResult(holder.getKey(), apply); return nextIn(request); } } } return null; } public OutboundInterceptor<O> nextOut() { switch (nextExecutionState) { case NextOutInterceptor: if (currentInterceptorIndex >= applicableOutInterceptors.size()) { nextExecutionState = NextExecutionState.End; return null; } else { return applicableOutInterceptors.get(currentInterceptorIndex++); } } return null; } private InboundInterceptor<I, O> returnNextInterceptor(I request, InterceptorHolder<I, C, InboundInterceptor<I, O>> holder) { List<InboundInterceptor<I, O>> interceptors = holder.getInterceptors(); if (currentInterceptorIndex >= interceptors.size()) { nextExecutionState = NextExecutionState.NextInHolder; return nextIn(request); } return interceptors.get(currentInterceptorIndex++); } public boolean invokeRouter() { if (NextExecutionState.Router == nextExecutionState) { currentHolderIndex = 0; nextExecutionState = NextExecutionState.NextOutInterceptor; return true; } else { return false; } } } private class ChainSubscriber extends Subscriber<Void> { private final SerialSubscription subscription; private final ExecutionContext context; private final I request; private final O response; private final Subscriber<? super Void> child; public ChainSubscriber(SerialSubscription subscription, ExecutionContext context, I request, O response, Subscriber<? super Void> child) { this.subscription = subscription; this.context = context; this.request = request; this.response = response; this.child = child; } @Override public void onCompleted() { InboundInterceptor<I, O> nextIn = context.nextIn(request); OutboundInterceptor<O> nextOut; if (null != nextIn) { Observable<Void> interceptorResult = nextIn.in(request, response); handleResult(interceptorResult); } else if (context.invokeRouter()) { handleResult(router.handle(request, response)); } else if (null != (nextOut = context.nextOut())) { handleResult(nextOut.out(response)); } else { child.onCompleted(); } } private void handleResult(Observable<Void> aResult) { ChainSubscriber nextSubscriber = new ChainSubscriber(subscription, context, request, response, child); subscription.set(nextSubscriber); aResult.unsafeSubscribe(nextSubscriber); } @Override public void onError(Throwable e) { child.onError(e); } @Override public void onNext(Void aVoid) { child.onNext(aVoid); } } }
3,294
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport/interceptor/InterceptorHolder.java
package netflix.karyon.transport.interceptor; import java.util.List; /** * @author Nitesh Kant */ public class InterceptorHolder<I, C extends KeyEvaluationContext, T> { private final InterceptorKey<I, C> key; private final List<T> interceptors; public InterceptorHolder(InterceptorKey<I, C> key, List<T> interceptors) { this.key = key; this.interceptors = interceptors; } public InterceptorKey<I, C> getKey() { return key; } public List<T> getInterceptors() { return interceptors; } }
3,295
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport/interceptor/DuplexInterceptor.java
package netflix.karyon.transport.interceptor; /** * * @author Nitesh Kant */ public interface DuplexInterceptor<I, O> extends InboundInterceptor<I, O>, OutboundInterceptor<O> { }
3,296
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/transport/interceptor/InterceptorKey.java
package netflix.karyon.transport.interceptor; /** * Key for a {@link InboundInterceptor} or {@link OutboundInterceptor} which determines whether a interceptor must * be applied for a particular request. <br> * Any implementation for the key must be aware that it will be invoked for every request so it should always optimize * for speed of evaluation. * * @author Nitesh Kant */ public interface InterceptorKey<I, C extends KeyEvaluationContext> { /** * This is invoked for a request to determine whether the interceptor attached to this key must be executed for this * request. * * @param request Request to determine whether the attached interceptor is to be applied or not. * @param context Context for the key evaluation, usually used to cache costly operations like parsing request * URI. * * @return {@code true} if the interceptor must be applied for this request. */ boolean apply(I request, C context); }
3,297
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/health/HealthCheckHandler.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package netflix.karyon.health; /** * This is an extension to the <a href="https://github.com/Netflix/eureka/blob/master/eureka-client/src/main/java/com/netflix/appinfo/HealthCheckCallback.java">callback handler </a> * in <a href="https://github.com/Netflix/eureka/">eureka</a> to provide a * more flexible health check response (an HTTP status code) as a healthcheck request. <br> * * This healthcheck handler is also used to have a fixed healthcheck endpoint created by karyon. <br> * * @author Nitesh Kant */ public interface HealthCheckHandler { /** * Checks the health of the application and returns a status code, which can be directly consumed as a HTTP status * code. <br> * <b>Kayon considers any status code &gt;= 200 and &lt; 300 as healthy.</b> * * @return The health status of the application. */ int getStatus(); }
3,298
0
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon
Create_ds/karyon/karyon2-core/src/main/java/netflix/karyon/health/HealthCheckInvocationStrategy.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package netflix.karyon.health; import java.util.concurrent.TimeoutException; /** * A strategy to make application specific healthchecks. Since, the application health checks can be poorly implemented * and hence take a long time to complete, in some cases, it is wise to have an SLA around the health check response * times. * There is a 1:1 mapping between a strategy instance and a {@link HealthCheckHandler} instance and hence it is assumed * that the strategy already knows about the handler instance. * * @author Nitesh Kant */ public interface HealthCheckInvocationStrategy { /** * Invokes the handler associated with this strategy and returns the response. This method may block waiting for results. <br> * If this strategy supports timeouts, this call must not wait more than the timeout value. * * @return The health check result. * * @throws TimeoutException If the healthcheck did not return after the stipulated time (governed entirely by this * strategy implementation) */ int invokeCheck() throws TimeoutException; /** * Returns the instance of {@link HealthCheckHandler} associated with this strategy. * * @return The instance of {@link HealthCheckHandler} associated with this strategy. */ HealthCheckHandler getHandler(); }
3,299