@Bean(destroyMethod = "stop") public Server databaseServer() throws SQLException, IOException { DriverManager.registerDriver(new org.hsqldb.jdbcDriver()); int hsqldbPort = SocketUtils.findAvailableTcpPort(10000); System.setProperty("db.server.port", Integer.toString(hsqldbPort)); logger.info("Database is using port: " + Integer.toString(hsqldbPort)); HsqlProperties configProps = new HsqlProperties(); configProps.setProperty("server.port", hsqldbPort); configProps.setProperty("server.database.0", "file:target/db/test"); configProps.setProperty("server.dbname.0", "test"); Server server = new org.hsqldb.Server(); server.setLogWriter(null); server.setErrWriter(null); server.setRestartOnShutdown(false); server.setNoSystemExit(true); server.setProperties(configProps); server.start(); return server; }
private void configureHttp(final TomcatEmbeddedServletContainerFactory tomcat) { final CasServerProperties.Http http = casProperties.getServer().getHttp(); if (http.isEnabled()) { LOGGER.debug("Creating HTTP configuration for the embedded tomcat container..."); final Connector connector = new Connector(http.getProtocol()); int port = http.getPort(); if (port <= 0) { LOGGER.warn("No explicit port configuration is provided to CAS. Scanning for available ports..."); port = SocketUtils.findAvailableTcpPort(); } LOGGER.info("Activated embedded tomcat container HTTP port to [{}]", port); connector.setPort(port); LOGGER.debug("Configuring embedded tomcat container for HTTP2 protocol support"); connector.addUpgradeProtocol(new Http2Protocol()); http.getAttributes().forEach(connector::setAttribute); tomcat.addAdditionalTomcatConnectors(connector); } }
public App(String appName, Map<String, String> env) { ProcessBuilder processBuilder = new ProcessBuilder("java", "-jar", appName + "-trace-example-0.0.1-SNAPSHOT.jar"); Map<String, String> environment = processBuilder.environment(); int port = SocketUtils.findAvailableTcpPort(); environment.put("SERVER_PORT", Integer.toString(port)); environment.putAll(env); processBuilder.directory(new File("../applications/" + appName + "/build/libs/")); File logFile = new File("tmp/" + appName + ".log"); processBuilder.redirectOutput(logFile); this.port = port; try { this.process = processBuilder.start(); } catch (IOException e) { throw new RuntimeException("app " + appName + " failed to start", e); } this.logFile = logFile; }
@Before public void setUp() throws Exception { logger.debug("Setting up before '" + this.testName.getMethodName() + "'"); int port = SocketUtils.findAvailableTcpPort(61613); this.activeMQBroker = new BrokerService(); this.activeMQBroker.addConnector("stomp://127.0.0.1:" + port); this.activeMQBroker.setStartAsync(false); this.activeMQBroker.setPersistent(false); this.activeMQBroker.setUseJmx(false); this.activeMQBroker.getSystemUsage().getMemoryUsage().setLimit(1024 * 1024 * 5); this.activeMQBroker.getSystemUsage().getTempUsage().setLimit(1024 * 1024 * 5); this.activeMQBroker.start(); ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.afterPropertiesSet(); this.client = new Reactor2TcpStompClient("127.0.0.1", port); this.client.setMessageConverter(new StringMessageConverter()); this.client.setTaskScheduler(taskScheduler); }
@Override public void setup() { this.port = SocketUtils.findAvailableTcpPort(); Connector connector = new Connector(Http11NioProtocol.class.getName()); connector.setPort(this.port); File baseDir = createTempDir("tomcat"); String baseDirPath = baseDir.getAbsolutePath(); this.tomcatServer = new Tomcat(); this.tomcatServer.setBaseDir(baseDirPath); this.tomcatServer.setPort(this.port); this.tomcatServer.getService().addConnector(connector); this.tomcatServer.setConnector(connector); }
@Test public void portClashOfSecondaryConnectorResultsInPortInUseException() throws IOException { doWithBlockedPort(new BlockedPortAction() { @Override public void run(int port) { try { AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.setPort(SocketUtils.findAvailableTcpPort(40000)); addConnector(port, factory); AbstractEmbeddedServletContainerFactoryTests.this.container = factory .getEmbeddedServletContainer(); AbstractEmbeddedServletContainerFactoryTests.this.container.start(); fail(); } catch (PortInUseException ex) { assertThat(ex.getPort()).isEqualTo(port); } } }); }
protected final void doWithBlockedPort(BlockedPortAction action) throws IOException { int port = SocketUtils.findAvailableTcpPort(40000); ServerSocket serverSocket = new ServerSocket(); for (int i = 0; i < 10; i++) { try { serverSocket.bind(new InetSocketAddress(port)); break; } catch (Exception ex) { } } try { action.run(port); } finally { serverSocket.close(); } }
@Test public void tomcatEngineNames() throws Exception { TomcatEmbeddedServletContainerFactory factory = getFactory(); this.container = factory.getEmbeddedServletContainer(); factory.setPort(SocketUtils.findAvailableTcpPort(40000)); TomcatEmbeddedServletContainer container2 = (TomcatEmbeddedServletContainer) factory .getEmbeddedServletContainer(); // Make sure that the names are different String firstContainerName = ((TomcatEmbeddedServletContainer) this.container) .getTomcat().getEngine().getName(); String secondContainerName = container2.getTomcat().getEngine().getName(); assertThat(firstContainerName).as("Tomcat engines must have different names") .isNotEqualTo(secondContainerName); container2.stop(); }
private void assertVersionConfiguration(String configuredVersion, String expectedVersion) { this.context = new AnnotationConfigApplicationContext(); int mongoPort = SocketUtils.findAvailableTcpPort(); EnvironmentTestUtils.addEnvironment(this.context, "spring.data.mongodb.port=" + mongoPort); if (configuredVersion != null) { EnvironmentTestUtils.addEnvironment(this.context, "spring.mongodb.embedded.version=" + configuredVersion); } this.context.register(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, EmbeddedMongoAutoConfiguration.class); this.context.refresh(); MongoTemplate mongo = this.context.getBean(MongoTemplate.class); CommandResult buildInfo = mongo.executeCommand("{ buildInfo: 1 }"); assertThat(buildInfo.getString("version")).isEqualTo(expectedVersion); }
@Test public void tomcatEngineNames() throws Exception { TomcatEmbeddedServletContainerFactory factory = getFactory(); this.container = factory.getEmbeddedServletContainer(); factory.setPort(SocketUtils.findAvailableTcpPort(40000)); TomcatEmbeddedServletContainer container2 = (TomcatEmbeddedServletContainer) factory .getEmbeddedServletContainer(); // Make sure that the names are different String firstContainerName = ((TomcatEmbeddedServletContainer) this.container) .getTomcat().getEngine().getName(); String secondContainerName = container2.getTomcat().getEngine().getName(); assertFalse("Tomcat engines must have different names", firstContainerName.equals(secondContainerName)); container2.stop(); }
@Test public void primaryConnectorPortClashThrowsIllegalStateException() throws InterruptedException, IOException { final int port = SocketUtils.findAvailableTcpPort(40000); doWithBlockedPort(port, new Runnable() { @Override public void run() { TomcatEmbeddedServletContainerFactory factory = getFactory(); factory.setPort(port); try { TomcatEmbeddedServletContainerFactoryTests.this.container = factory .getEmbeddedServletContainer(); TomcatEmbeddedServletContainerFactoryTests.this.container.start(); fail(); } catch (EmbeddedServletContainerException ex) { // Ignore } } }); }
private void assertVersionConfiguration(String configuredVersion, String expectedVersion) { this.context = new AnnotationConfigApplicationContext(); int mongoPort = SocketUtils.findAvailableTcpPort(); EnvironmentTestUtils.addEnvironment(this.context, "spring.data.mongodb.port=" + mongoPort); if (configuredVersion != null) { EnvironmentTestUtils.addEnvironment(this.context, "spring.mongodb.embedded.version=" + configuredVersion); } this.context.register(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, EmbeddedMongoAutoConfiguration.class); this.context.refresh(); MongoTemplate mongo = this.context.getBean(MongoTemplate.class); CommandResult buildInfo = mongo.executeCommand("{ buildInfo: 1 }"); assertThat(buildInfo.getString("version"), equalTo(expectedVersion)); }
@Test public void contextLoads() throws Exception { int zkPort = SocketUtils.findAvailableTcpPort(); TestingServer server = new TestingServer(zkPort); int port = SocketUtils.findAvailableTcpPort(zkPort+1); ConfigurableApplicationContext context = new SpringApplicationBuilder(SampleZookeeperApplication.class).run( "--server.port="+port, "--management.endpoints.web.expose=*", "--spring.cloud.zookeeper.connect-string=localhost:" + zkPort); ResponseEntity<String> response = new TestRestTemplate().getForEntity("http://localhost:"+port+"/hi", String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); context.close(); server.close(); }
@Before public void beforeClass() throws Exception { zookeeper = new TestingServer(SocketUtils.findAvailableTcpPort()); curatorFramework = CuratorFrameworkFactory.newClient(zookeeper.getConnectString(), new RetryOneTime(1000)); curatorFramework.start(); curatorFramework.create().forPath(CONFIG_BASE_PATH); Map<String, Object> defaults = new HashMap<>(); defaults.put(DEF_KEY1, DEF_VAL1); defaults.put(DEF_KEY2, DEF_VAL2); defaultConfiguration = new MapConfiguration(defaults); node = UUID.randomUUID().toString(); config = new ConcurrentCompositeConfiguration(); }
@Override public TeeworldsServer createAndBorrowServer(final TeeworldsConfig configuration) { if (this.borrowedServers.size() >= MAX_SERVER_AVAILABLE) { throw new TeeFunRuntimeException("Maximum server size reached."); } final String serverId = this.generateUUID(); try { final Integer port = SocketUtils.findAvailableUdpPort(TEEWORLDS_MIN_PORT, TEEWORLDS_MAX_PORT); configuration.setVariable("sv_port", port); } catch (final IllegalStateException exception) { LOGGER.error("Could not find any port.", exception); throw new TeeFunRuntimeException("Could not find any port.", exception); } configuration.setVariable("logfile", String.format(LOG_FILENAME_PATTERN, serverId)); configuration.generatePassword(); final TeeworldsServer server = new TeeworldsServer(configuration, serverId, System.currentTimeMillis(), this.SERVER_TTL); this.borrowedServers.add(server); LOGGER.debug("Created server : " + server.getServerId() + ". " + this.getNbFreeServers() + "/" + MAX_SERVER_AVAILABLE + " ."); return server; }
@Before public void before() throws Exception { serverSocket = new ServerSocket(SocketUtils.findAvailableTcpPort(), 1); sut = new SynchronizingClusterConnectionProvider<>(new AbstractClusterNodeConnectionFactory<String, String>( redisClient.getResources()) { @Override public ConnectionFuture<StatefulRedisConnection<String, String>> apply(ConnectionKey connectionKey) { RedisURI redisURI = RedisURI.create(TestSettings.host(), serverSocket.getLocalPort()); redisURI.setTimeout(5); redisURI.setUnit(TimeUnit.SECONDS); ConnectionFuture<StatefulRedisConnection<String, String>> future = redisClient.connectToNodeAsync( StringCodec.UTF8, "", null, () -> new InetSocketAddress(connectionKey.host, serverSocket.getLocalPort())); connectInitiated.countDown(); return future; } }); }
private DataReceiverGroupConfiguration createMockConfig(boolean tcpEnable, boolean udpEnable) { DataReceiverGroupConfiguration config = mock(DataReceiverGroupConfiguration.class); when(config.isTcpEnable()).thenReturn(tcpEnable); when(config.getTcpBindIp()).thenReturn("0.0.0.0"); when(config.getTcpBindPort()).thenReturn(SocketUtils.findAvailableTcpPort(19099)); when(config.isUdpEnable()).thenReturn(udpEnable); when(config.getUdpBindIp()).thenReturn("0.0.0.0"); when(config.getUdpBindPort()).thenReturn(SocketUtils.findAvailableTcpPort(29099)); when(config.getUdpReceiveBufferSize()).thenReturn(65535); when(config.getWorkerThreadSize()).thenReturn(2); when(config.getWorkerQueueSize()).thenReturn(10); when(config.isWorkerMonitorEnable()).thenReturn(false); return config; }
public static int startServer() { if (daemon == null) { System.setProperty("net.spy.log.LoggerImpl", SLF4JLogger.class.getName()); // Get next free port for the test server portForInstance = SocketUtils.findAvailableTcpPort(); //noinspection NonThreadSafeLazyInitialization daemon = new MemCacheDaemon<>(); CacheStorage<Key, LocalCacheElement> storage = ConcurrentLinkedHashMap.create(ConcurrentLinkedHashMap.EvictionPolicy.FIFO, 1024 * 1024, 1024 * 1024 * 1024); daemon.setCache(new CacheImpl(storage)); daemon.setAddr(new InetSocketAddress(portForInstance)); daemon.setVerbose(true); daemon.start(); } return portForInstance; }
@BeforeClass public static void setup() throws Exception { log.info("Setting up Quotes Web Socket Integration test...."); port = SocketUtils.findAvailableTcpPort(); server = new TomcatWebSocketTestServer(port); server.deployConfig(FrontendWebApplicationInitializer.class); server.start(); loginAndSaveXAuthToken("harrymitchell", "HarryMitchell5!", headers); List<Transport> transports = new ArrayList<>(); transports.add(new WebSocketTransport(new StandardWebSocketClient())); RestTemplateXhrTransport xhrTransport = new RestTemplateXhrTransport(new RestTemplate()); xhrTransport.setRequestHeaders(headers); transports.add(xhrTransport); sockJsClient = new SockJsClient(transports); sockJsClient.setHttpHeaderNames("X-Auth-Token"); log.info("Setup complete!"); }
/** * Launch one or more consumers based on the number of consumer groups. * Blocks execution until the consumers are bound. * * @param groups consumer groups; may be {@code null} * @return a set of {@link AppId}s for the consumers * @throws InterruptedException */ private Set<AppId> launchConsumers(String[] groups) throws InterruptedException { Set<AppId> consumers = new HashSet<>(); Map<String, String> appProperties = new HashMap<>(); int consumerCount = groups == null ? 1 : groups.length; for (int i = 0; i < consumerCount; i++) { int consumerPort = SocketUtils.findAvailableTcpPort(); appProperties.put("server.port", String.valueOf(consumerPort)); List<String> args = new ArrayList<>(); args.add(String.format("--server.port=%d", consumerPort)); args.add("--management.context-path=/"); args.add("--management.security.enabled=false"); args.add("--endpoints.shutdown.enabled=true"); args.add("--debug"); if (groups != null) { args.add(String.format("--group=%s", groups[i])); } consumers.add(new AppId(launchApplication(TestConsumer.class, appProperties, args), consumerPort)); } for (AppId app : consumers) { waitForConsumer(app.port); } return consumers; }
public static void main(String[] args) throws FileNotFoundException { final int oauth2ServerPort = SocketUtils.findAvailableTcpPort(); new SpringApplicationBuilder(OAuth2TestServer.class) .properties("oauth2.port:" + oauth2ServerPort).build() .run("--spring.config.location=classpath:" + "org/springframework/cloud/skipper/server/local/security/support/oauth2TestServerConfig.yml"); }
@Bean @Primary public HttpServerOptions httpServerOptions() { return new HttpServerOptions() .setPort(SocketUtils.findAvailableTcpPort()); }
@BeforeClass public static void startUp() throws InterruptedException, IOException { if (applicationContext == null) { if (System.getProperty(SHUTDOWN_AFTER_RUN) != null) { shutdownAfterRun = Boolean.getBoolean(SHUTDOWN_AFTER_RUN); } SpringApplication application = new SpringApplicationBuilder(TestConfig.class).build(); int randomPort = SocketUtils.findAvailableTcpPort(); String dataFlowUri = String.format("--dataflow.uri=http://localhost:%s", serverPort); String dataSourceUrl = String.format("jdbc:h2:tcp://localhost:%s/mem:dataflow", randomPort); applicationContext = application.run( String.format("--server.port=%s", serverPort), dataFlowUri, "--spring.jmx.default-domain=" + System.currentTimeMillis(), "--spring.jmx.enabled=false", "--security.basic.enabled=false", "--spring.main.show_banner=false", "--spring.cloud.config.enabled=false", "--spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.session.SessionAutoConfiguration", "--spring.datasource.url=" + dataSourceUrl); JLineShellComponent shell = applicationContext.getBean(JLineShellComponent.class); if (!shell.isRunning()) { shell.start(); } dataFlowShell = new DataFlowShell(shell); } }
@Override protected void before() throws Throwable { originalLdapPort = System.getProperty(LDAP_PORT_PROPERTY); temporaryFolder.create(); apacheDSContainer = new ApacheDSContainerWithSecurity("dc=springframework,dc=org", "classpath:org/springframework/cloud/deployer/admin/server/local/security/testUsers.ldif"); int ldapPort = SocketUtils.findAvailableTcpPort(); if (enabledSsl) { apacheDSContainer.setEnabledLdapOverSsl(true); final File temporaryKeyStoreFile = new File(temporaryFolder.getRoot(), "dataflow.keystore"); final File temporaryTrustStoreFile = new File(temporaryFolder.getRoot(), "dataflow.truststore"); FileCopyUtils.copy(keyStoreResource.getInputStream(), new FileOutputStream(temporaryKeyStoreFile)); FileCopyUtils.copy(trustStoreResource.getInputStream(), new FileOutputStream(temporaryTrustStoreFile)); Assert.isTrue(temporaryKeyStoreFile.isFile()); Assert.isTrue(temporaryTrustStoreFile.isFile()); apacheDSContainer.setKeyStoreFile(temporaryKeyStoreFile); apacheDSContainer.setKeyStorePassword(KEY_STORE_PASSWORD); System.setProperty("javax.net.ssl.trustStorePassword", TRUST_STORE_PASSWORD); System.setProperty("javax.net.ssl.trustStore", temporaryTrustStoreFile.getAbsolutePath()); System.setProperty("javax.net.ssl.trustStoreType", "jks"); } apacheDSContainer.setPort(ldapPort); apacheDSContainer.afterPropertiesSet(); workingDir = new File(temporaryFolder.getRoot(), UUID.randomUUID().toString()); apacheDSContainer.setWorkingDirectory(workingDir); apacheDSContainer.start(); System.setProperty(LDAP_PORT_PROPERTY, Integer.toString(ldapPort)); }
@Test public void testConfig() { SpringApplication app = new SpringApplication(LocalTestDataFlowServer.class); int randomPort = SocketUtils.findAvailableTcpPort(); String dataSourceUrl = String.format("jdbc:h2:tcp://localhost:%s/mem:dataflow", randomPort); context = app.run(new String[] { "--server.port=0", "--spring.datasource.url=" + dataSourceUrl}); assertThat(context.containsBean(APP_DEPLOYER_BEAN_NAME), is(true)); assertThat(context.getBean(APP_DEPLOYER_BEAN_NAME), instanceOf(LocalAppDeployer.class)); assertNotNull(context.getBean(AppRegistry.class)); }
/** * @return The server's HTTP port. */ public synchronized int getHttpPort() { if (httpPort == 0) { httpPort = SocketUtils.findAvailableTcpPort(); } return httpPort; }
@Test public void testHealthCommand() { int smtpPort = SocketUtils.findAvailableTcpPort(); ServerSetup setup = new ServerSetup(smtpPort, null, ServerSetup.PROTOCOL_SMTP); setup.setServerStartupTimeout(5000); GreenMail mailServer = new GreenMail(setup); mailServer.start(); ((JavaMailSenderImpl) mailSender).setPort(smtpPort); sshCallShell((is, os) -> { write(os, "health"); verifyResponse(is, "{\r\n \"status\" : \"UP\""); mailServer.stop(); }); }
@Test public void testStatusCommand() { int smtpPort = SocketUtils.findAvailableTcpPort(); ServerSetup setup = new ServerSetup(smtpPort, null, ServerSetup.PROTOCOL_SMTP); setup.setServerStartupTimeout(5000); GreenMail mailServer = new GreenMail(setup); mailServer.start(); ((JavaMailSenderImpl) mailSender).setPort(smtpPort); sshCallShell((is, os) -> { write(os, "status"); verifyResponse(is, "{\r\n \"status\" : \"UP\"\r\n}"); mailServer.stop(); }); }
@BeforeClass public static void setUpClass() { port = SocketUtils.findAvailableTcpPort(); server = RemoteCacheUtils.startCacheServerConfigurationSpec("org/littlewings/spring/session/infinispan/remote/config/annotation/web/http/infinispan-custom-hotrod.xml", port); }
@BeforeClass public static void setUpClass() { port = SocketUtils.findAvailableTcpPort(); server = RemoteCacheUtils .startCacheServerDefaultConfiguration(SESSION_CACHE_NAME, port, cb -> cb.expiration().wakeUpInterval(1L, TimeUnit.SECONDS)); }
@Before public void setUp() throws Exception { logger.debug("Setting up before '" + this.testName.getMethodName() + "'"); this.port = SocketUtils.findAvailableTcpPort(61613); this.responseChannel = new ExecutorSubscribableChannel(); this.responseHandler = new TestMessageHandler(); this.responseChannel.subscribe(this.responseHandler); this.eventPublisher = new TestEventPublisher(); startActiveMqBroker(); createAndStartRelay(); }
@Test public void simpleHessianServiceExporter() throws IOException { final int port = SocketUtils.findAvailableTcpPort(); TestBean tb = new TestBean("tb"); SimpleHessianServiceExporter exporter = new SimpleHessianServiceExporter(); exporter.setService(tb); exporter.setServiceInterface(ITestBean.class); exporter.setDebug(true); exporter.prepare(); HttpServer server = HttpServer.create(new InetSocketAddress(port), -1); server.createContext("/hessian", exporter); server.start(); try { HessianClientInterceptor client = new HessianClientInterceptor(); client.setServiceUrl("http://localhost:" + port + "/hessian"); client.setServiceInterface(ITestBean.class); //client.setHessian2(true); client.prepare(); ITestBean proxy = ProxyFactory.getProxy(ITestBean.class, client); assertEquals("tb", proxy.getName()); proxy.setName("test"); assertEquals("test", proxy.getName()); } finally { server.stop(Integer.MAX_VALUE); } }
/** * Create internal Elasticsearch node. * @return HTTP port of node */ private int createInternalNode() throws NodeValidationException { if (logger.isInfoEnabled()) { logger.info("Create test ES node"); } int port = SocketUtils.findAvailableTcpPort(); String clusterName = INTERNAL_TEST_CLUSTER_NAME + UUID.randomUUID(); Settings.Builder settingsBuilder = Settings.builder() .put("cluster.name", clusterName) .put("transport.type", "local") .put("http.type", "netty4") .put("http.port", String.valueOf(port)); if (this.esNodeproperties != null) { settingsBuilder.put(this.esNodeproperties.getProperties()); } Collection<Class<? extends Plugin>> plugins = scanPlugins(); plugins.add(Netty4Plugin.class); this.node = new InternalNode(settingsBuilder.build(), plugins).start(); return Integer.parseInt(settingsBuilder.get("http.port")); }
@Test public void customFeatures() { this.context = new AnnotationConfigApplicationContext(); int mongoPort = SocketUtils.findAvailableTcpPort(); EnvironmentTestUtils.addEnvironment(this.context, "spring.data.mongodb.port=" + mongoPort, "spring.mongodb.embedded.features=TEXT_SEARCH, SYNC_DELAY"); this.context.register(EmbeddedMongoAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(EmbeddedMongoProperties.class).getFeatures()) .contains(Feature.TEXT_SEARCH, Feature.SYNC_DELAY); }