當前位置: 首頁>>代碼示例>>Java>>正文


Java SocketUtils.findAvailableTcpPort方法代碼示例

本文整理匯總了Java中org.springframework.util.SocketUtils.findAvailableTcpPort方法的典型用法代碼示例。如果您正苦於以下問題:Java SocketUtils.findAvailableTcpPort方法的具體用法?Java SocketUtils.findAvailableTcpPort怎麽用?Java SocketUtils.findAvailableTcpPort使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.springframework.util.SocketUtils的用法示例。


在下文中一共展示了SocketUtils.findAvailableTcpPort方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: testHealthCommand

import org.springframework.util.SocketUtils; //導入方法依賴的package包/類
@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();
    });
}
 
開發者ID:anand1st,項目名稱:sshd-shell-spring-boot,代碼行數:15,代碼來源:SshdShellAutoConfigurationTest.java

示例2: databaseServer

import org.springframework.util.SocketUtils; //導入方法依賴的package包/類
@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;
}
 
開發者ID:spring-cloud,項目名稱:spring-cloud-task-modules,代碼行數:20,代碼來源:SqoopToolDatabaseConfiguration.java

示例3: configureHttp

import org.springframework.util.SocketUtils; //導入方法依賴的package包/類
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);
    }
}
 
開發者ID:mrluo735,項目名稱:cas-5.1.0,代碼行數:21,代碼來源:CasEmbeddedContainerTomcatConfiguration.java

示例4: App

import org.springframework.util.SocketUtils; //導入方法依賴的package包/類
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;
}
 
開發者ID:pivotal-cf,項目名稱:pcf-metrics-trace-example-spring,代碼行數:21,代碼來源:App.java

示例5: testStatusCommand

import org.springframework.util.SocketUtils; //導入方法依賴的package包/類
@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();
    });
}
 
開發者ID:anand1st,項目名稱:sshd-shell-spring-boot,代碼行數:15,代碼來源:SshdShellAutoConfigurationTest.java

示例6: assertVersionConfiguration

import org.springframework.util.SocketUtils; //導入方法依賴的package包/類
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);
}
 
開發者ID:philwebb,項目名稱:spring-boot-concourse,代碼行數:19,代碼來源:EmbeddedMongoAutoConfigurationTests.java

示例7: setup

import org.springframework.util.SocketUtils; //導入方法依賴的package包/類
@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);
}
 
開發者ID:langtianya,項目名稱:spring4-understanding,代碼行數:17,代碼來源:TomcatWebSocketTestServer.java

示例8: setup

import org.springframework.util.SocketUtils; //導入方法依賴的package包/類
@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!");
}
 
開發者ID:bjornharvold,項目名稱:bearchoke,代碼行數:22,代碼來源:QuotesWebSocketIntegrationTest.java

示例9: beforeClass

import org.springframework.util.SocketUtils; //導入方法依賴的package包/類
@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();
}
 
開發者ID:Kixeye,項目名稱:chassis,代碼行數:18,代碼來源:DynamicZookeeperConfigurationSourceTest.java

示例10: before

import org.springframework.util.SocketUtils; //導入方法依賴的package包/類
@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;
        }
    });
}
 
開發者ID:lettuce-io,項目名稱:lettuce-core,代碼行數:25,代碼來源:SynchronizingClusterConnectionProviderTest.java

示例11: startServer

import org.springframework.util.SocketUtils; //導入方法依賴的package包/類
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;
}
 
開發者ID:spring-cloud,項目名稱:spring-cloud-aws,代碼行數:18,代碼來源:TestMemcacheServer.java

示例12: main

import org.springframework.util.SocketUtils; //導入方法依賴的package包/類
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");
}
 
開發者ID:spring-cloud,項目名稱:spring-cloud-skipper,代碼行數:8,代碼來源:OAuth2TestServer.java

示例13: startUp

import org.springframework.util.SocketUtils; //導入方法依賴的package包/類
@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);
	}
}
 
開發者ID:spring-cloud,項目名稱:spring-cloud-dashboard,代碼行數:31,代碼來源:AbstractShellIntegrationTest.java

示例14: before

import org.springframework.util.SocketUtils; //導入方法依賴的package包/類
@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));
}
 
開發者ID:spring-cloud,項目名稱:spring-cloud-dashboard,代碼行數:39,代碼來源:LdapServerResource.java

示例15: testConfig

import org.springframework.util.SocketUtils; //導入方法依賴的package包/類
@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));
}
 
開發者ID:spring-cloud,項目名稱:spring-cloud-dashboard,代碼行數:12,代碼來源:LocalConfigurationTests.java


注:本文中的org.springframework.util.SocketUtils.findAvailableTcpPort方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。