io.dropwizard.server.DefaultServerFactory Java Examples

The following examples show how to use io.dropwizard.server.DefaultServerFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ServiceUtil.java    From helios with Apache License 2.0 6 votes vote down vote up
public static DefaultServerFactory createServerFactory(final InetSocketAddress httpEndpoint,
                                                       final InetSocketAddress adminEndpoint,
                                                       final boolean noHttp) {
  final DefaultServerFactory serverFactory = new DefaultServerFactory();
  if (noHttp) {
    serverFactory.setApplicationConnectors(Collections.<ConnectorFactory>emptyList());
    serverFactory.setAdminConnectors(Collections.<ConnectorFactory>emptyList());
  } else {
    final HttpConnectorFactory serviceConnector = new HttpConnectorFactory();
    serviceConnector.setPort(httpEndpoint.getPort());
    serviceConnector.setBindHost(httpEndpoint.getHostString());
    serverFactory.setApplicationConnectors(ImmutableList.<ConnectorFactory>of(serviceConnector));

    final HttpConnectorFactory adminConnector = new HttpConnectorFactory();
    adminConnector.setPort(adminEndpoint.getPort());
    adminConnector.setBindHost(adminEndpoint.getHostString());
    serverFactory.setAdminConnectors(ImmutableList.<ConnectorFactory>of(adminConnector));
  }
  return serverFactory;
}
 
Example #2
Source File: ServerUtils.java    From foxtrot with Apache License 2.0 6 votes vote down vote up
public static int port(ServerFactory serverFactory) {
    if(serverFactory instanceof SimpleServerFactory) {
        SimpleServerFactory simpleServerFactory = (SimpleServerFactory)serverFactory;
        return getPortFromConnector(simpleServerFactory.getConnector());

    }
    if(serverFactory instanceof DefaultServerFactory) {
        DefaultServerFactory defaultServerFactory = (DefaultServerFactory)serverFactory;
        for(ConnectorFactory connectorFactory : defaultServerFactory.getApplicationConnectors()) {
            if(connectorFactory instanceof HttpConnectorFactory) {
                return getPortFromConnector(connectorFactory);
            }
        }

    }
    throw new PortExtractionException("Cannot extract port from connector");
}
 
Example #3
Source File: DoctorKafkaMain.java    From doctorkafka with Apache License 2.0 5 votes vote down vote up
private void configureServerRuntime(DoctorKafkaAppConfig configuration, DoctorKafkaConfig config) {
  DefaultServerFactory defaultServerFactory = 
      (DefaultServerFactory) configuration.getServerFactory();

  // Disable gzip compression for HTTP, this is required in-order to make
  // Server-Sent-Events work, else due to GZIP the browser waits for entire chunks
  // to arrive thereby the UI receiving no events
  // We are programmatically disabling it here so it makes it easy to launch
  // Firefly
  GzipHandlerFactory gzipHandlerFactory = new GzipHandlerFactory();
  gzipHandlerFactory.setEnabled(false);
  defaultServerFactory.setGzipFilterFactory(gzipHandlerFactory);
  // Note that if someone explicitly enables gzip in the Dropwizard config YAML
  // then
  // this setting will be over-ruled causing the UI to stop working

  // Disable HTTP request logging
  LogbackAccessRequestLogFactory accessRequestLogFactory = new LogbackAccessRequestLogFactory();
  accessRequestLogFactory.setAppenders(ImmutableList.of());
  defaultServerFactory.setRequestLogFactory(accessRequestLogFactory);

  // Disable admin connector
  defaultServerFactory.setAdminConnectors(ImmutableList.of());

  // Configure bind host and port number
  HttpConnectorFactory application = (HttpConnectorFactory) HttpConnectorFactory.application();
  application.setPort(config.getWebserverPort());
  application.setBindHost(config.getWebserverBindHost());
  defaultServerFactory.setApplicationConnectors(Collections.singletonList(application));
}
 
Example #4
Source File: ScanUploadTest.java    From emodb with Apache License 2.0 5 votes vote down vote up
private static void updatePortsToAvoidCollision(ServerFactory serverFactory) {
    if (serverFactory instanceof DefaultServerFactory) {
        DefaultServerFactory defaultServerFactory = (DefaultServerFactory)serverFactory;
        updatePortsToAvoidCollision(defaultServerFactory.getApplicationConnectors());
        updatePortsToAvoidCollision(defaultServerFactory.getAdminConnectors());
    } else if (serverFactory instanceof SimpleServerFactory) {
        SimpleServerFactory simpleServerFactory = (SimpleServerFactory)serverFactory;
        updatePortsToAvoidCollision(Collections.singleton(simpleServerFactory.getConnector()));
    } else {
        throw new IllegalStateException("Encountered an unexpected ServerFactory type");
    }
}
 
Example #5
Source File: BaseRoleConnectHelper.java    From emodb with Apache License 2.0 5 votes vote down vote up
protected String getAdminBaseURI () {
    int httpPort = 0;
    for(ConnectorFactory connector: ((DefaultServerFactory)_config.getServerFactory()).getAdminConnectors()) {
        if (connector.getClass().isAssignableFrom(HttpConnectorFactory.class)) {
            httpPort = ((HttpConnectorFactory) connector).getPort();
            break;
        }
    }

    return format("http://localhost:%d", httpPort);
}
 
Example #6
Source File: BaseRoleConnectHelper.java    From emodb with Apache License 2.0 5 votes vote down vote up
protected String getServiceBaseURI () {
    int port = 0;
    for(ConnectorFactory connector: ((DefaultServerFactory)_config.getServerFactory()).getApplicationConnectors()) {
        if (connector.getClass().isAssignableFrom(HttpConnectorFactory.class)) {
            port = ((HttpConnectorFactory) connector).getPort();
            break;
        }
    }

    return format("http://localhost:%d", port);
}
 
Example #7
Source File: BaseRoleConnectHelper.java    From emodb with Apache License 2.0 5 votes vote down vote up
protected int getServiceBasePort () {
    int port = 0;
    for(ConnectorFactory connector: ((DefaultServerFactory)_config.getServerFactory()).getApplicationConnectors()) {
        if (connector.getClass().isAssignableFrom(HttpConnectorFactory.class)) {
            port = ((HttpConnectorFactory) connector).getPort();
            break;
        }
    }

    return port;
}
 
Example #8
Source File: SelfHostAndPortModule.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Provides @Singleton @SelfHostAndPort
public HostAndPort provideSelfHostAndPort(ServerFactory serverFactory) {
    // Our method for obtaining connector factories from the server factory varies depending on the latter's type
    List<ConnectorFactory> appConnectorFactories;
    if (serverFactory instanceof DefaultServerFactory) {
        appConnectorFactories = ((DefaultServerFactory) serverFactory).getApplicationConnectors();
    } else if (serverFactory instanceof SimpleServerFactory) {
        appConnectorFactories = Collections.singletonList(((SimpleServerFactory) serverFactory).getConnector());
    } else {
        throw new IllegalStateException("Encountered an unexpected ServerFactory type");
    }

    return getHostAndPortFromConnectorFactories(appConnectorFactories);
}
 
Example #9
Source File: SelfHostAndPortModule.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Provides @Singleton @SelfAdminHostAndPort
public HostAndPort provideSelfAdminHostAndPort(ServerFactory serverFactory) {
    // Our method for obtaining connector factories from the server factory varies depending on the latter's type
    List<ConnectorFactory> adminConnectorFactories;
    if (serverFactory instanceof DefaultServerFactory) {
        adminConnectorFactories = ((DefaultServerFactory) serverFactory).getAdminConnectors();
    } else if (serverFactory instanceof SimpleServerFactory) {
        adminConnectorFactories = Collections.singletonList(((SimpleServerFactory) serverFactory).getConnector());
    } else {
        throw new IllegalStateException("Encountered an unexpected ServerFactory type");
    }

    return getHostAndPortFromConnectorFactories(adminConnectorFactories);
}
 
Example #10
Source File: RandomPortsListener.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
@Override
public void onRun(final Configuration configuration,
                  final Environment environment,
                  final DropwizardTestSupport<Configuration> rule) throws Exception {
    final ServerFactory server = configuration.getServerFactory();
    if (server instanceof SimpleServerFactory) {
        ((HttpConnectorFactory) ((SimpleServerFactory) server).getConnector()).setPort(0);
    } else {
        final DefaultServerFactory dserv = (DefaultServerFactory) server;
        ((HttpConnectorFactory) dserv.getApplicationConnectors().get(0)).setPort(0);
        ((HttpConnectorFactory) dserv.getAdminConnectors().get(0)).setPort(0);
    }
}
 
Example #11
Source File: SingularityMainModule.java    From Singularity with Apache License 2.0 5 votes vote down vote up
@Provides
@Named(SingularityServiceUIModule.SINGULARITY_URI_BASE)
String getSingularityUriBase(final SingularityConfiguration configuration) {
  final String singularityUiPrefix;
  if (configuration.getServerFactory() instanceof SimpleServerFactory) {
    singularityUiPrefix =
      configuration
        .getUiConfiguration()
        .getBaseUrl()
        .orElse(
          (
            (SimpleServerFactory) configuration.getServerFactory()
          ).getApplicationContextPath()
        );
  } else {
    singularityUiPrefix =
      configuration
        .getUiConfiguration()
        .getBaseUrl()
        .orElse(
          (
            (DefaultServerFactory) configuration.getServerFactory()
          ).getApplicationContextPath()
        );
  }
  return (singularityUiPrefix.endsWith("/"))
    ? singularityUiPrefix.substring(0, singularityUiPrefix.length() - 1)
    : singularityUiPrefix;
}
 
Example #12
Source File: MetadataResourceApp.java    From eagle with Apache License 2.0 4 votes vote down vote up
@Override
public void run(Configuration configuration, Environment environment) throws Exception {
    ((HttpConnectorFactory) ((DefaultServerFactory) configuration.getServerFactory()).getApplicationConnectors().get(0)).setPort(0);
    ((HttpConnectorFactory) ((DefaultServerFactory) configuration.getServerFactory()).getAdminConnectors().get(0)).setPort(0);
    environment.jersey().register(MetadataResource.class);
}
 
Example #13
Source File: EagleMetricResourceApp.java    From eagle with Apache License 2.0 4 votes vote down vote up
@Override
public void run(Configuration configuration, Environment environment) throws Exception {
    ((HttpConnectorFactory) ((DefaultServerFactory) configuration.getServerFactory()).getApplicationConnectors().get(0)).setPort(0);
    ((HttpConnectorFactory) ((DefaultServerFactory) configuration.getServerFactory()).getAdminConnectors().get(0)).setPort(0);
    environment.jersey().register(EagleMetricResource.class);
}
 
Example #14
Source File: StreamlineApplication.java    From streamline with Apache License 2.0 4 votes vote down vote up
private void registerResources(StreamlineConfiguration configuration, Environment environment, Subject subject) throws ConfigException,
        ClassNotFoundException, IllegalAccessException, InstantiationException {
    StorageManager storageManager = getDao(configuration);
    TransactionManager transactionManager;
    if (storageManager instanceof TransactionManager) {
        transactionManager = (TransactionManager) storageManager;
    } else {
        transactionManager = new NOOPTransactionManager();
    }
    environment.jersey().register(new TransactionEventListener(transactionManager, true));
    Collection<Class<? extends Storable>> streamlineEntities = getStorableEntities();
    storageManager.registerStorables(streamlineEntities);
    LOG.info("Registered streamline entities {}", streamlineEntities);
    FileStorage fileStorage = this.getJarStorage(configuration, storageManager);
    int appPort = ((HttpConnectorFactory) ((DefaultServerFactory) configuration.getServerFactory()).getApplicationConnectors().get(0)).getPort();
    String catalogRootUrl = configuration.getCatalogRootUrl().replaceFirst("8080", appPort + "");
    List<ModuleConfiguration> modules = configuration.getModules();
    List<Object> resourcesToRegister = new ArrayList<>();

    // add StreamlineConfigResource
    resourcesToRegister.add(new StreamlineConfigurationResource(configuration));

    // authorizer
    StreamlineAuthorizer authorizer;
    AuthorizerConfiguration authorizerConf = configuration.getAuthorizerConfiguration();
    SecurityCatalogService securityCatalogService = new SecurityCatalogService(storageManager);
    if (authorizerConf != null) {
        authorizer = ((Class<StreamlineAuthorizer>) Class.forName(authorizerConf.getClassName())).newInstance();
        Map<String, Object> authorizerConfig = new HashMap<>();
        authorizerConfig.put(DefaultStreamlineAuthorizer.CONF_CATALOG_SERVICE, securityCatalogService);
        authorizerConfig.put(DefaultStreamlineAuthorizer.CONF_ADMIN_PRINCIPALS, authorizerConf.getAdminPrincipals());
        authorizer.init(authorizerConfig);
        String filterClazzName = authorizerConf.getContainerRequestFilter();
        ContainerRequestFilter filter;
        if (StringUtils.isEmpty(filterClazzName)) {
            filter = new StreamlineKerberosRequestFilter(); // default
        } else {
            filter = ((Class<ContainerRequestFilter>) Class.forName(filterClazzName)).newInstance();
        }
        LOG.info("Registering ContainerRequestFilter: {}", filter.getClass().getCanonicalName());
        environment.jersey().register(filter);
    } else {
        LOG.info("Authorizer config not set, setting noop authorizer");
        String noopAuthorizerClassName = "com.hortonworks.streamline.streams.security.impl.NoopAuthorizer";
        authorizer = ((Class<StreamlineAuthorizer>) Class.forName(noopAuthorizerClassName)).newInstance();
    }

    for (ModuleConfiguration moduleConfiguration: modules) {
        String moduleName = moduleConfiguration.getName();
        String moduleClassName = moduleConfiguration.getClassName();
        LOG.info("Registering module [{}] with class [{}]", moduleName, moduleClassName);
        ModuleRegistration moduleRegistration = (ModuleRegistration) Class.forName(moduleClassName).newInstance();
        if (moduleConfiguration.getConfig() == null) {
            moduleConfiguration.setConfig(new HashMap<String, Object>());
        }
        if (moduleName.equals(Constants.CONFIG_STREAMS_MODULE)) {
            moduleConfiguration.getConfig().put(Constants.CONFIG_CATALOG_ROOT_URL, catalogRootUrl);
        }
        Map<String, Object> initConfig = new HashMap<>(moduleConfiguration.getConfig());
        initConfig.put(Constants.CONFIG_AUTHORIZER, authorizer);
        initConfig.put(Constants.CONFIG_SECURITY_CATALOG_SERVICE, securityCatalogService);
        initConfig.put(Constants.CONFIG_SUBJECT, subject);
        if ((initConfig.get("proxyUrl") != null) && (configuration.getHttpProxyUrl() == null || configuration.getHttpProxyUrl().isEmpty())) {
            LOG.warn("Please move proxyUrl, proxyUsername and proxyPassword configuration properties under streams module to httpProxyUrl, " +
                    "httpProxyUsername and httpProxyPassword respectively at top level in your streamline.yaml");
            configuration.setHttpProxyUrl((String) initConfig.get("proxyUrl"));
            configuration.setHttpProxyUsername((String) initConfig.get("proxyUsername"));
            configuration.setHttpProxyPassword((String) initConfig.get("proxyPassword"));
        }
        // pass http proxy information from top level config to each module. Up to them how they want to use it. Currently used in StreamsModule
        initConfig.put(Constants.CONFIG_HTTP_PROXY_URL, configuration.getHttpProxyUrl());
        initConfig.put(Constants.CONFIG_HTTP_PROXY_USERNAME, configuration.getHttpProxyUsername());
        initConfig.put(Constants.CONFIG_HTTP_PROXY_PASSWORD, configuration.getHttpProxyPassword());
        moduleRegistration.init(initConfig, fileStorage);
        if (moduleRegistration instanceof StorageManagerAware) {
            LOG.info("Module [{}] is StorageManagerAware and setting StorageManager.", moduleName);
            StorageManagerAware storageManagerAware = (StorageManagerAware) moduleRegistration;
            storageManagerAware.setStorageManager(storageManager);
        }
        if (moduleRegistration instanceof TransactionManagerAware) {
            LOG.info("Module [{}] is TransactionManagerAware and setting TransactionManager.", moduleName);
            TransactionManagerAware transactionManagerAware = (TransactionManagerAware) moduleRegistration;
            transactionManagerAware.setTransactionManager(transactionManager);
        }
        resourcesToRegister.addAll(moduleRegistration.getResources());

    }

    LOG.info("Registering resources to Jersey environment: [{}]", resourcesToRegister);
    for(Object resource : resourcesToRegister) {
        environment.jersey().register(resource);
    }
    environment.jersey().register(MultiPartFeature.class);

    final ErrorPageErrorHandler errorPageErrorHandler = new ErrorPageErrorHandler();
    errorPageErrorHandler.addErrorPage(Response.Status.UNAUTHORIZED.getStatusCode(), "/401.html");
    environment.getApplicationContext().setErrorHandler(errorPageErrorHandler);
}
 
Example #15
Source File: TimbuctooConfiguration.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
@Override
@JsonProperty("server")
@Value.Default
public ServerFactory getServerFactory() {
  return new DefaultServerFactory();
}
 
Example #16
Source File: CommaFeedApplication.java    From commafeed with Apache License 2.0 4 votes vote down vote up
@Override
public void run(CommaFeedConfiguration config, Environment environment) throws Exception {
	// guice init
	Injector injector = Guice.createInjector(new CommaFeedModule(hibernateBundle.getSessionFactory(), config, environment.metrics()));

	// session management
	environment.servlets().setSessionHandler(config.getSessionHandlerFactory().build());

	// support for "@SecurityCheck User user" injection
	environment.jersey().register(new SecurityCheckFactoryProvider.Binder(injector.getInstance(UserService.class)));
	// support for "@Context SessionHelper sessionHelper" injection
	environment.jersey().register(new SessionHelperFactoryProvider.Binder());

	// REST resources
	environment.jersey().setUrlPattern("/rest/*");
	((DefaultServerFactory) config.getServerFactory()).setJerseyRootPath("/rest/*");
	environment.jersey().register(injector.getInstance(AdminREST.class));
	environment.jersey().register(injector.getInstance(CategoryREST.class));
	environment.jersey().register(injector.getInstance(EntryREST.class));
	environment.jersey().register(injector.getInstance(FeedREST.class));
	environment.jersey().register(injector.getInstance(PubSubHubbubCallbackREST.class));
	environment.jersey().register(injector.getInstance(ServerREST.class));
	environment.jersey().register(injector.getInstance(UserREST.class));

	// Servlets
	environment.servlets().addServlet("next", injector.getInstance(NextUnreadServlet.class)).addMapping("/next");
	environment.servlets().addServlet("logout", injector.getInstance(LogoutServlet.class)).addMapping("/logout");
	environment.servlets().addServlet("customCss", injector.getInstance(CustomCssServlet.class)).addMapping("/custom_css.css");
	environment.servlets().addServlet("analytics.js", injector.getInstance(AnalyticsServlet.class)).addMapping("/analytics.js");

	// Scheduled tasks
	Set<ScheduledTask> tasks = injector.getInstance(Key.get(new TypeLiteral<Set<ScheduledTask>>() {
	}));
	ScheduledExecutorService executor = environment.lifecycle().scheduledExecutorService("task-scheduler", true).threads(tasks.size())
			.build();
	for (ScheduledTask task : tasks) {
		task.register(executor);
	}

	// database init/changelogs
	environment.lifecycle().manage(injector.getInstance(StartupService.class));

	// background feed fetching
	environment.lifecycle().manage(injector.getInstance(FeedRefreshTaskGiver.class));
	environment.lifecycle().manage(injector.getInstance(FeedRefreshWorker.class));
	environment.lifecycle().manage(injector.getInstance(FeedRefreshUpdater.class));

	// cache configuration
	// prevent caching on REST resources, except for favicons
	environment.servlets().addFilter("cache-filter", new CacheBustingFilter() {
		@Override
		public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
			String path = ((HttpServletRequest) request).getRequestURI();
			if (path.contains("/feed/favicon")) {
				chain.doFilter(request, response);
			} else {
				super.doFilter(request, response, chain);
			}
		}
	}).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/rest/*");

}