Java Code Examples for org.springframework.util.SocketUtils

The following examples show how to use org.springframework.util.SocketUtils. These examples are extracted from open source projects. 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
@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 ReactorNettyTcpStompClient("127.0.0.1", port);
	this.client.setMessageConverter(new StringMessageConverter());
	this.client.setTaskScheduler(taskScheduler);
}
 
Example 2
Source Project: spring-cloud-consul   Source File: ConsulBinderTests.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Launch a producer that publishes a test message.
 * @return {@link AppId} for producer
 */
private AppId launchProducer() {
	int producerPort = SocketUtils.findAvailableTcpPort();
	Map<String, String> appProperties = new HashMap<>();
	appProperties.put("server.port", String.valueOf(producerPort));
	List<String> args = new ArrayList<>();
	args.add(String.format("--server.port=%d", producerPort));
	args.add("--management.context-path=/");
	args.add("--management.security.enabled=false");
	args.add("--endpoints.shutdown.enabled=true");
	args.add(String.format("--partitioned=%b", false));
	args.add("--debug");

	return new AppId(launchApplication(TestProducer.class, appProperties, args),
			producerPort);
}
 
Example 3
Source Project: spring-cloud-aws   Source File: TestMemcacheServer.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 4
Source Project: tessera   Source File: Util.java    License: Apache License 2.0 6 votes vote down vote up
public static JerseyTest create(Enclave enclave) {

        SLF4JBridgeHandler.removeHandlersForRootLogger();
        SLF4JBridgeHandler.install();

        return new JerseyTest() {
            @Override
            protected Application configure() {
                
                enable(TestProperties.LOG_TRAFFIC);
                enable(TestProperties.DUMP_ENTITY);
                set(TestProperties.CONTAINER_PORT, SocketUtils.findAvailableTcpPort());
                EnclaveApplication application = new EnclaveApplication(new EnclaveResource(enclave));

                ResourceConfig config = ResourceConfig.forApplication(application);
                config.packages("com.quorum.tessera.enclave.rest");
                return config;
            }

        };
    }
 
Example 5
public static void startConfigServer(Properties properties) throws IOException, URISyntaxException {
    int configPort = SocketUtils.findAvailableTcpPort();
    File cfgFile = temporaryFolder.newFile("grpc-demo.properties");
    try(OutputStream os = new FileOutputStream(cfgFile)) {
        properties.store(os,null);
    }


    server = SpringApplication.run(org.springframework.cloud.config.server.ConfigServerApplication.class,
            "--server.port=" + configPort,
            "--spring.autoconfigure.exclude="+Stream.of(GRpcAutoConfiguration.class)
                    .map(Class::getName).collect(Collectors.joining(",")),
            "--spring.cloud.consul.discovery.enabled=false",
            "--spring.cloud.service-registry.enabled=false",
            "--spring.cloud.service-registry.auto-registration.enabled=false",
            "--spring.cloud.config.server.health.enabled=false",
            "--spring.cloud.config.server.bootstrap=false",
            "--spring.profiles.active=native",
            "--grpc.enabled=false",
            "--spring.cloud.config.server.native.search-locations[0]=file:"+temporaryFolder.getRoot().getAbsolutePath()
    );
    System.setProperty("config.port", "" + configPort);

}
 
Example 6
@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.exposure.include=*",
					"--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();
}
 
Example 7
Source Project: cxf   Source File: JAXRSClientMetricsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void usingClientStopIsCalledWhenConnectionIsRefused() throws Exception {
    final int port = SocketUtils.findAvailableTcpPort();
    
    final Client client = ClientBuilder
        .newClient()
        .register(new MetricsFeature(provider))
        .register(JacksonJsonProvider.class);

    try {
        expectedException.expect(ProcessingException.class);
        client
            .target("http://localhost:" + port + "/books/10")
            .request(MediaType.APPLICATION_JSON)
            .get()
            .readEntity(Book.class);
    } finally {
        Mockito.verify(resourceContext, times(1)).start(any(Exchange.class));
        Mockito.verify(resourceContext, times(1)).stop(anyLong(), anyLong(), anyLong(), any(Exchange.class));
        Mockito.verify(endpointContext, times(1)).start(any(Exchange.class));
        Mockito.verify(endpointContext, times(1)).stop(anyLong(), anyLong(), anyLong(), any(Exchange.class));
        Mockito.verifyNoInteractions(operationContext);
    }
}
 
Example 8
@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();
}
 
Example 9
Source Project: spring-analysis-note   Source File: CauchoRemotingTests.java    License: MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
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);
	}
}
 
Example 10
Source Project: camel-spring-boot   Source File: ZookeeperServer.java    License: Apache License 2.0 5 votes vote down vote up
public ZookeeperServer(File root) throws IOException, InterruptedException {
    zkServer = new ZooKeeperServer();

    File dataDir = new File(root, "log");
    File snapDir = new File(root, "data");
    FileTxnSnapLog ftxn = new FileTxnSnapLog(dataDir, snapDir);

    zkServer.setTxnLogFactory(ftxn);
    zkServer.setTickTime(1000);

    connectionFactory = new NIOServerCnxnFactory();
    connectionFactory.configure(new InetSocketAddress("localhost", SocketUtils.findAvailableTcpPort()), 0);
    connectionFactory.startup(zkServer);
}
 
Example 11
Source Project: pinpoint   Source File: ReconnectTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void scheduledConnectDelayAndClosed() throws IOException, InterruptedException {
    int availableTcpPort = SocketUtils.findAvailableTcpPort(47000);
    PinpointClient client = clientFactory.scheduledConnect("localhost", availableTcpPort);

    Thread.sleep(2000);
    logger.debug("close pinpoint client");
    PinpointRPCTestUtils.close(client);
}
 
Example 12
@Before
public void setup() throws Exception {
	int port = SocketUtils.findAvailableTcpPort();
	this.testingServer = new TestingServer(port);
	String connectString = "localhost:" + port;
	this.curator = CuratorFrameworkFactory.builder()
			.retryPolicy(new RetryOneTime(500)).connectString(connectString).build();
	this.curator.start();

	List<String> children = this.curator.getChildren().forPath("/");
	for (String child : children) {
		if (child.startsWith(PREFIX) && child.length() > PREFIX.length()) {
			delete("/" + child);
		}
	}

	StringBuilder create = new StringBuilder(1024);
	create.append(this.curator.create().creatingParentsIfNeeded()
			.forPath(KEY_BASIC_PATH, VAL_BASIC.getBytes())).append('\n');
	create.append(this.curator.create().creatingParentsIfNeeded()
			.forPath(KEY_WITH_DOT_PATH, VAL_WITH_DOT.getBytes())).append('\n');
	create.append(this.curator.create().creatingParentsIfNeeded()
			.forPath(KEY_NESTED_PATH, VAL_NESTED.getBytes())).append('\n');
	create.append(this.curator.create().creatingParentsIfNeeded()
			.forPath(KEY_WITHOUT_VALUE_PATH, null)).append('\n');
	this.curator.close();
	System.out.println(create);

	this.context = new SpringApplicationBuilder(Config.class)
			.web(WebApplicationType.NONE)
			.run("--spring.cloud.zookeeper.connectString=" + connectString,
					"--spring.application.name=testZkPropertySource",
					"--logging.level.org.springframework.cloud.zookeeper=DEBUG",
					"--spring.cloud.zookeeper.config.root=" + ROOT);

	this.curator = this.context.getBean(CuratorFramework.class);
	this.properties = this.context.getBean(ZookeeperConfigProperties.class);
	this.environment = this.context.getEnvironment();
}
 
Example 13
@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();
}
 
Example 14
@Bean
public ArtemisConfigData getArtemisConfig()
{
    ArtemisConfigData artemisConfigData = new ArtemisConfigData();
    artemisConfigData
        .setMode( ArtemisMode.valueOf( (dhisConfig.getProperty( ConfigurationKey.ARTEMIS_MODE )).toUpperCase() ) );
    artemisConfigData.setHost( dhisConfig.getProperty( ConfigurationKey.ARTEMIS_HOST ) );

    artemisConfigData.setPort( Integer.parseInt( dhisConfig.getProperty( ConfigurationKey.ARTEMIS_PORT ) ) );

    if ( isTestRun( this.environment.getActiveProfiles() ) )
    {
        artemisConfigData.setPort( SocketUtils.findAvailableTcpPort( 3000 ) );
    }

    artemisConfigData.setUsername( dhisConfig.getProperty( ConfigurationKey.ARTEMIS_USERNAME ) );
    artemisConfigData.setPassword( dhisConfig.getProperty( ConfigurationKey.ARTEMIS_PASSWORD ) );

    ArtemisEmbeddedConfig artemisEmbeddedConfig = new ArtemisEmbeddedConfig();
    artemisEmbeddedConfig.setSecurity(
        Boolean.parseBoolean( dhisConfig.getProperty( ConfigurationKey.ARTEMIS_EMBEDDED_SECURITY ) ) );
    artemisEmbeddedConfig.setPersistence(
        Boolean.parseBoolean( dhisConfig.getProperty( ConfigurationKey.ARTEMIS_EMBEDDED_PERSISTENCE ) ) );

    artemisConfigData.setEmbedded( artemisEmbeddedConfig );

    return artemisConfigData;
}
 
Example 15
Source Project: raptor   Source File: ClientIntegrationBenchmark.java    License: Apache License 2.0 5 votes vote down vote up
@Setup
public void setup() {
    System.setProperty("server.port", String.valueOf(SocketUtils.findAvailableTcpPort()));
    context = SpringApplication.run(ClientIntegrationApplication.class);
    ClientIntegrationApplication demo = context.getBean(ClientIntegrationApplication.class);
    simple = demo.getSimple();
}
 
Example 16
Source Project: raptor   Source File: ClientMockBenchmark.java    License: Apache License 2.0 5 votes vote down vote up
@Setup
public void setup() {
    System.setProperty("server.port", String.valueOf(SocketUtils.findAvailableTcpPort()));
    context = SpringApplication.run(ClientMockApplication.class);
    ClientMockApplication demo = context.getBean(ClientMockApplication.class);
    simple = demo.getSimple();
}
 
Example 17
Source Project: pinpoint   Source File: ClusterTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
    acceptorPort = SocketUtils.findAvailableTcpPort(28000);
    acceptorAddress = DEFAULT_IP + ":" + acceptorPort;

    zookeeperPort = SocketUtils.findAvailableTcpPort(acceptorPort + 1);
    zookeeperAddress = DEFAULT_IP + ":" + zookeeperPort;

    ts = createZookeeperServer(zookeeperPort);

    CLUSTER_NODE_PATH = "/pinpoint-cluster/web/" + acceptorAddress;
    LOGGER.debug("CLUSTER_NODE_PATH:{}", CLUSTER_NODE_PATH);

    WebConfig config = mock(WebConfig.class);

    when(config.isClusterEnable()).thenReturn(true);
    when(config.getClusterTcpPort()).thenReturn(acceptorPort);
    when(config.getClusterZookeeperAddress()).thenReturn(zookeeperAddress);
    when(config.getClusterZookeeperRetryInterval()).thenReturn(60000);
    when(config.getClusterZookeeperSessionTimeout()).thenReturn(3000);

    clusterConnectionManager = new ClusterConnectionManager(config);
    clusterConnectionManager.start();

    clusterDataManager = new ZookeeperClusterDataManager(config);
    clusterDataManager.start();

    List<String> localV4IpList = NetUtils.getLocalV4IpList();
    clusterDataManager.registerWebCluster(acceptorAddress, convertIpListToBytes(localV4IpList, "\r\n"));
}
 
Example 18
Source Project: raptor   Source File: MockSpringMvcBenchmark.java    License: Apache License 2.0 5 votes vote down vote up
@Setup
public void setup() {
    port = SocketUtils.findAvailableTcpPort();
    System.setProperty("server.port", String.valueOf(port));
    context = SpringApplication.run(MockSpringMvcApplication.class);
    mvc = MockMvcBuilders.webAppContextSetup((WebApplicationContext) context).build();
}
 
Example 19
@BeforeAll
public static void init() throws Exception {
	headers.clear();
	String port = "" + SocketUtils.findAvailableTcpPort();
	System.setProperty("server.port", port);
	System.setProperty("my.port", port);
	context = SpringApplication.run(RestPojoConfiguration.class,
			"--spring.main.web-application-type=reactive");
	app = context.getBean(RestPojoConfiguration.class);
	// Sometimes the server doesn't start quick enough
	Thread.sleep(500L);
}
 
Example 20
Source Project: pinpoint   Source File: CuratorZookeeperClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUpClass() throws Exception {
    int availablePort = SocketUtils.findAvailableTcpPort();
    ts = new TestingServer(availablePort);

    eventHoldingZookeeperEventWatcher = new EventHoldingZookeeperEventWatcher();
    curatorZookeeperClient = createCuratorZookeeperClient(ts.getConnectString(), eventHoldingZookeeperEventWatcher);
    curatorZookeeperClient.createPath(PARENT_PATH);
}
 
Example 21
private void registerPropertySourceForDynamicEntries(
		ConfigurableEnvironment environment, String portProperty, int minPort,
		int maxPort, String dynamicPortProperty) {
	MutablePropertySources propertySources = environment.getPropertySources();
	addPropertySource(propertySources);
	Map<String, Object> source = ((MapPropertySource) propertySources.get("wiremock"))
			.getSource();
	source.put(portProperty, SocketUtils.findAvailableTcpPort(minPort, maxPort));
	source.put(dynamicPortProperty, true);
}
 
Example 22
Source Project: spring-cloud-consul   Source File: ConsulBinderTests.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 when waiting for message was interrupted
 */
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;
}
 
Example 23
@Nullable
private static Port obtainManagementServerPort(Integer port) {
    int actualPort = requireNonNull(port, "port");
    if (actualPort < 0) {
        return null;
    }
    if (actualPort == 0) {
        actualPort = SocketUtils.findAvailableTcpPort();
    }
    return new Port().setPort(actualPort).setProtocol(SessionProtocol.HTTP);
}
 
Example 24
Source Project: pinpoint   Source File: PinpointClientFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void connectFail() {
    try {
        int availableTcpPort = SocketUtils.findAvailableTcpPort(47000);
        clientFactory.connect("127.0.0.1", availableTcpPort);
        Assert.fail();
    } catch (PinpointSocketException e) {
        Assert.assertTrue(ConnectException.class.isInstance(e.getCause()));
    } 
}
 
Example 25
@Override
protected void before() {
	originalDataflowServerPort = System.getProperty(DATAFLOW_PORT_PROPERTY);

	this.dataflowServerPort = SocketUtils.findAvailableTcpPort();

	logger.info("Setting Dataflow Server port to " + this.dataflowServerPort);

	System.setProperty(DATAFLOW_PORT_PROPERTY, String.valueOf(this.dataflowServerPort));

	originalConfigLocation = System.getProperty("spring.config.additional-locationn");

	if (!StringUtils.isEmpty(configurationLocation)) {
		final Resource resource = new PathMatchingResourcePatternResolver().getResource(configurationLocation);
		if (!resource.exists()) {
		  throw new IllegalArgumentException(String.format("Resource 'configurationLocation' ('%s') does not exist.", configurationLocation));
		}
		System.setProperty("spring.config.additional-location", configurationLocation);
	}

	app = new SpringApplication(TestConfig.class);

	configurableApplicationContext = (WebApplicationContext) app.run(new String[] {
			"--spring.cloud.kubernetes.enabled=false",
			"--" + FeaturesProperties.FEATURES_PREFIX + "." + FeaturesProperties.STREAMS_ENABLED + "="
					+ this.streamsEnabled,
			"--" + FeaturesProperties.FEATURES_PREFIX + "." + FeaturesProperties.TASKS_ENABLED + "="
					+ this.tasksEnabled,
			"--" + FeaturesProperties.FEATURES_PREFIX + "." + FeaturesProperties.SCHEDULES_ENABLED + "="
					+ this.schedulesEnabled,
			"--spring.cloud.skipper.client.serverUri=http://localhost:" + this.skipperServerPort + "/api"
	});
	skipperClient = configurableApplicationContext.getBean(SkipperClient.class);
	LauncherRepository launcherRepository = configurableApplicationContext.getBean(LauncherRepository.class);
	launcherRepository.save(new Launcher("default", "local", new LocalTaskLauncher(new LocalDeployerProperties())));
	Collection<Filter> filters = configurableApplicationContext.getBeansOfType(Filter.class).values();
	mockMvc = MockMvcBuilders.webAppContextSetup(configurableApplicationContext)
			.addFilters(filters.toArray(new Filter[filters.size()])).build();
	dataflowPort = configurableApplicationContext.getEnvironment().resolvePlaceholders("${server.port}");
}
 
Example 26
@Bean
public ServletWebServerFactory servletContainer(
		@Value("${server.port:0}") int serverPort) {
	log.info("Starting container at port [" + serverPort + "]");
	return new TomcatServletWebServerFactory(
			serverPort == 0 ? SocketUtils.findAvailableTcpPort() : serverPort);
}
 
Example 27
Source Project: tutorials   Source File: ManualEmbeddedMongoDbIntegrationTest.java    License: MIT License 5 votes vote down vote up
@BeforeEach
void setup() throws Exception {
    String ip = "localhost";
    int randomPort = SocketUtils.findAvailableTcpPort();

    IMongodConfig mongodConfig = new MongodConfigBuilder().version(Version.Main.PRODUCTION)
        .net(new Net(ip, randomPort, Network.localhostIsIPv6()))
        .build();

    MongodStarter starter = MongodStarter.getDefaultInstance();
    mongodExecutable = starter.prepare(mongodConfig);
    mongodExecutable.start();
    mongoTemplate = new MongoTemplate(new MongoClient(ip, randomPort), "test");
}
 
Example 28
public Integer getRunningPort() {
    if (null == runningPort) {
        synchronized (this) {
            if (null == runningPort) {
                runningPort = Optional.ofNullable(port)
                        .map(p -> 0 == p ? SocketUtils.findAvailableTcpPort() : p)
                        .orElse(DEFAULT_GRPC_PORT);
            }
        }
    }
    return runningPort;

}
 
Example 29
Source Project: dubbo-samples   Source File: EmbeddedZooKeeper.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Construct an EmbeddedZooKeeper with a random port.
 */
public EmbeddedZooKeeper() {
    clientPort = SocketUtils.findAvailableTcpPort();
}
 
Example 30
@Bean
public Integer randomPort() {
    return SocketUtils.findAvailableTcpPort();
}