Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.yammer.dropwizard.config;
  
 
 import java.io.File;
 import java.net.URI;
 import java.util.Map;
 
 /*
  * A factory for creating instances of {@link org.eclipse.jetty.server.Server} and configuring Servlets
  * 
  * Registers {@link com.yammer.metrics.core.HealthCheck}s, both default and user defined
  * 
  * Creates instances of {@link org.eclipse.jetty.server.Connector},
  * configured by {@link com.yammer.dropwizard.config.HttpConfiguration} for external and admin port
  * 
  * Registers {@link org.eclipse.jetty.server.Handler}s for admin and service Servlets.
  * {@link TaskServlet} 
  * {@link AdminServlet}
  * {@link com.sun.jersey.spi.container.servlet.ServletContainer} with all resources in {@link DropwizardResourceConfig} 
  * 
  * */
 public class ServerFactory {
     private static final Logger LOGGER = LoggerFactory.getLogger(ServerFactory.class);
 
     private final HttpConfiguration config;
 
     public ServerFactory(HttpConfiguration configString name) {
         this. = config;
                                                                      name);
     }
 
     public Server buildServer(Environment envthrows ConfigurationException {
         HealthChecks.defaultRegistry().register(new DeadlockHealthCheck());
         for (HealthCheck healthCheck : env.getHealthChecks()) {
             HealthChecks.defaultRegistry().register(healthCheck);
         }
 
         if (env.getHealthChecks().isEmpty()) {
             .warn('\n' +
                              "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n" +
                              "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n" +
                              "!    THIS SERVICE HAS NO HEALTHCHECKS. THIS MEANS YOU WILL NEVER KNOW IF IT    !\n" +
                              "!    DIES IN PRODUCTION, WHICH MEANS YOU WILL NEVER KNOW IF YOU'RE LETTING     !\n" +
                              "!     YOUR USERS DOWN. YOU SHOULD ADD A HEALTHCHECK FOR EACH DEPENDENCY OF     !\n" +
                              "!     YOUR SERVICE WHICH FULLY (BUT LIGHTLY) TESTS YOUR SERVICE'S ABILITY TO   !\n" +
                              "!      USE THAT SERVICE. THINK OF IT AS A CONTINUOUS INTEGRATION TEST.         !\n" +
                              "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n" +
                              "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
             );
         }
 
         final Server server = createServer();
        server.setHandler(createHandler(env));
        server.addBean(env);
        return server;
    }
    private Server createServer() {
        final Server server = new Server();
        server.addConnector(createExternalConnector());
        // if we're dynamically allocating ports, no worries if they are the same (i.e. 0)
        if (.getAdminPort() == 0 || (.getAdminPort() != .getPort()) ) {
            server.addConnector(createInternalConnector());
        }
        server.addBean(new UnbrandedErrorHandler());
        server.setThreadPool(createThreadPool());
        server.setStopAtShutdown(true);
        return server;
    }
    private Connector createExternalConnector() {
        final AbstractConnector connector = createConnector(.getPort());
        connector.setHost(.getBindHost().orNull());
        connector.setAcceptors(.getAcceptorThreads());
        connector.setForwarded(.useForwardedHeaders());
        connector.setMaxIdleTime((int.getMaxIdleTime().toMilliseconds());
                                                         .toMilliseconds());
        connector.setAcceptQueueSize(.getAcceptQueueSize());
        connector.setMaxBuffers(.getMaxBufferCount());
        connector.setRequestBufferSize((int.getRequestBufferSize().toBytes());
        connector.setRequestHeaderSize((int.getRequestHeaderBufferSize().toBytes());
        connector.setResponseBufferSize((int.getResponseBufferSize().toBytes());
        connector.setReuseAddress(.isReuseAddressEnabled());
        
        final Optional<DurationlingerTime = .getSoLingerTime();
        if (lingerTime.isPresent()) {
            connector.setSoLingerTime((intlingerTime.get().toMilliseconds());
        }
        connector.setPort(.getPort());
        connector.setName("main");
        return connector;
    }
    private AbstractConnector createConnector(int port) {
        final AbstractConnector connector;
        switch (.getConnectorType()) {
            case :
                connector = new InstrumentedBlockingChannelConnector(port);
                break;
            case :
                connector = new InstrumentedSocketConnector(port);
                break;
            case :
                connector = new InstrumentedSslSocketConnector(port);
                break;
            case :
                connector = new InstrumentedSelectChannelConnector(port);
                break;
            case :
                connector = new InstrumentedSslSelectChannelConnector(port);
                break;
            default:
                throw new IllegalStateException("Invalid connector type: " + .getConnectorType());
        }
        if (connector instanceof SslConnector) {
            configureSslContext(((SslConnectorconnector).getSslContextFactory());
        }
        if (connector instanceof SelectChannelConnector) {
        }
        if (connector instanceof AbstractNIOConnector) {
            ((AbstractNIOConnectorconnector).setUseDirectBuffers(.useDirectBuffers());
        }
        return connector;
    }
    private void configureSslContext(SslContextFactory factory) {
        final SslConfiguration sslConfig = .getSslConfiguration();
        for (File keyStore : sslConfig.getKeyStore().asSet()) {
            factory.setKeyStorePath(keyStore.getAbsolutePath());
        }
        for (String password : sslConfig.getKeyStorePassword().asSet()) {
            factory.setKeyStorePassword(password);
        }
        for (String password : sslConfig.getKeyManagerPassword().asSet()) {
            factory.setKeyManagerPassword(password);
        }
        for (String certAlias : sslConfig.getCertAlias().asSet()) {
            factory.setCertAlias(certAlias);
        }
        final String keyStoreType = sslConfig.getKeyStoreType();
        if (keyStoreType.startsWith("Windows-")) {
            try {
                final KeyStore keyStore = KeyStore.getInstance(keyStoreType);
                keyStore.load(nullnull);
                factory.setKeyStore(keyStore);
            } catch (Exception e) {
                throw new IllegalStateException("Windows key store not supported"e);
            }
        } else {
            factory.setKeyStoreType(keyStoreType);
        }
        for (File trustStore : sslConfig.getTrustStore().asSet()) {
            factory.setTrustStore(trustStore.getAbsolutePath());
        }
        for (String password : sslConfig.getTrustStorePassword().asSet()) {
            factory.setTrustStorePassword(password);
        }
        final String trustStoreType = sslConfig.getTrustStoreType();
        if (trustStoreType.startsWith("Windows-")) {
            try {
                final KeyStore keyStore = KeyStore.getInstance(trustStoreType);
                keyStore.load(nullnull);
                factory.setTrustStore(keyStore);
            } catch (Exception e) {
                throw new IllegalStateException("Windows key store not supported"e);
            }
        } else {
            factory.setTrustStoreType(trustStoreType);
        }
        for (Boolean needClientAuth : sslConfig.getNeedClientAuth().asSet()) {
            factory.setNeedClientAuth(needClientAuth);
        }
        for (Boolean wantClientAuth : sslConfig.getWantClientAuth().asSet()) {
            factory.setWantClientAuth(wantClientAuth);
        }
        for (Boolean allowRenegotiate : sslConfig.getAllowRenegotiate().asSet()) {
            factory.setAllowRenegotiate(allowRenegotiate);
        }
        for (File crlPath : sslConfig.getCrlPath().asSet()) {
            factory.setCrlPath(crlPath.getAbsolutePath());
        }
        for (Boolean enable : sslConfig.getCrldpEnabled().asSet()) {
            factory.setEnableCRLDP(enable);
        }
        for (Boolean enable : sslConfig.getOcspEnabled().asSet()) {
            factory.setEnableOCSP(enable);
        }
        for (Integer length : sslConfig.getMaxCertPathLength().asSet()) {
            factory.setMaxCertPathLength(length);
        }
        for (URI uri : sslConfig.getOcspResponderUrl().asSet()) {
            factory.setOcspResponderURL(uri.toASCIIString());
        }
        for (String provider : sslConfig.getJceProvider().asSet()) {
            factory.setProvider(provider);
        }
        for (Boolean validate : sslConfig.getValidatePeers().asSet()) {
            factory.setValidatePeerCerts(validate);
        }
        factory.setIncludeProtocols(Iterables.toArray(sslConfig.getSupportedProtocols(),
                                                      String.class));
    }
    private Handler createHandler(Environment env) {
        final HandlerCollection collection = new HandlerCollection();
        collection.addHandler(createInternalServlet(env));
        collection.addHandler(createExternalServlet(env));
        if (.isEnabled()) {
            collection.addHandler(.build());
        }
        return collection;
    }
    private Handler createInternalServlet(Environment env) {
        final ServletContextHandler handler = new ServletContextHandler();
        handler.addServlet(new ServletHolder(new TaskServlet(env.getTasks())), "/tasks/*");
        handler.addServlet(new ServletHolder(new AdminServlet()), "/*");
        if (.getAdminPort() != 0 && .getAdminPort() == .getPort()) {
            handler.setContextPath("/admin");
            handler.setConnectorNames(new String[]{"main"});
        } else {
            handler.setConnectorNames(new String[]{"internal"});
        }
        }
        return handler;
    }
    private SecurityHandler basicAuthHandler(String usernameString password) {
        final HashLoginService loginService = new HashLoginService();
        loginService.putUser(username, Credential.getCredential(password), new String[] {"user"});
        loginService.setName("admin");
        final Constraint constraint = new Constraint();
        constraint.setName(.);
        constraint.setRoles(new String[]{"user"});
        constraint.setAuthenticate(true);
        final ConstraintMapping constraintMapping = new ConstraintMapping();
        constraintMapping.setConstraint(constraint);
        constraintMapping.setPathSpec("/*");
        final ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
        csh.setAuthenticator(new BasicAuthenticator());
        csh.setRealmName("admin");
        csh.addConstraintMapping(constraintMapping);
        csh.setLoginService(loginService);
        return csh;
    }
    private Handler createExternalServlet(Environment env) {
        final ServletContextHandler handler = new ServletContextHandler();
        handler.addFilter(ThreadNameFilter.class"/*", EnumSet.of(.));
        handler.setBaseResource(env.getBaseResource());
        if(!env.getProtectedTargets().isEmpty()) {
            handler.setProtectedTargets(env.getProtectedTargets().toArray(new String[env.getProtectedTargets().size()]));
        }
        for (ImmutableMap.Entry<StringServletHolderentry : env.getServlets().entrySet()) {
            handler.addServlet(entry.getValue(), entry.getKey());
        }
        final ServletContainer jerseyContainer = env.getJerseyServletContainer();
        if (jerseyContainer != null) {
            env.addProvider(new JacksonMessageBodyProvider(env.getObjectMapperFactory().build(),
                                                           env.getValidator()));
            final ServletHolder jerseyHolder = new ServletHolder(jerseyContainer);
            jerseyHolder.setInitOrder(.);
            handler.addServlet(jerseyHolder.getRootPath());
        }
        for (ImmutableMap.Entry<StringFilterHolderentry : env.getFilters().entries()) {
            handler.addFilter(entry.getValue(), entry.getKey(), EnumSet.of(.));
        }
        for (EventListener listener : env.getServletListeners()) {
            handler.addEventListener(listener);
        }
        for (Map.Entry<StringStringentry : .getContextParameters().entrySet()) {
            handler.setInitParameterentry.getKey(), entry.getValue() );
        }
        handler.setSessionHandler(env.getSessionHandler());
        handler.setConnectorNames(new String[]{"main"});
        return wrapHandler(handler);
    }
    private Handler wrapHandler(ServletContextHandler handler) {
        final InstrumentedHandler instrumented = new InstrumentedHandler(handler);
        final GzipConfiguration gzip = .getGzipConfiguration();
        if (gzip.isEnabled()) {
            final BiDiGzipHandler gzipHandler = new BiDiGzipHandler(instrumented);
            final Size minEntitySize = gzip.getMinimumEntitySize();
            gzipHandler.setMinGzipSize((intminEntitySize.toBytes());
            final Size bufferSize = gzip.getBufferSize();
            gzipHandler.setBufferSize((intbufferSize.toBytes());
            final ImmutableSet<StringuserAgents = gzip.getExcludedUserAgents();
            if (!userAgents.isEmpty()) {
                gzipHandler.setExcluded(userAgents);
            }
            final ImmutableSet<StringmimeTypes = gzip.getCompressedMimeTypes();
            if (!mimeTypes.isEmpty()) {
                gzipHandler.setMimeTypes(mimeTypes);
            }
            return gzipHandler;
        }
        return instrumented;
    }
    private ThreadPool createThreadPool() {
        final InstrumentedQueuedThreadPool pool = new InstrumentedQueuedThreadPool();
        pool.setMinThreads(.getMinThreads());
        pool.setMaxThreads(.getMaxThreads());
        return pool;
    }
    private Connector createInternalConnector() {
        final SocketConnector connector = new SocketConnector();
        connector.setHost(.getBindHost().orNull());
        connector.setPort(.getAdminPort());
        connector.setName("internal");
        connector.setThreadPool(new QueuedThreadPool(8));
        return connector;
    }
New to GrepCode? Check out our FAQ X