org.springframework.util.SocketUtils Java Examples

The following examples show how to use org.springframework.util.SocketUtils. 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: Util.java    From tessera with 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 #2
Source File: TestMemcacheServer.java    From spring-cloud-aws with 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 #3
Source File: JAXRSClientMetricsTest.java    From cxf with 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 #4
Source File: SampleApplicationTests.java    From spring-cloud-zookeeper with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: ConsulBinderTests.java    From spring-cloud-consul with 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 #6
Source File: ConfigServerEnvironmentBaseTest.java    From grpc-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: ReactorNettyTcpStompClientTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #8
Source File: ZookeeperPropertySourceLocatorTests.java    From spring-cloud-zookeeper with Apache License 2.0 5 votes vote down vote up
@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 #9
Source File: StompBrokerRelayMessageHandlerIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 #10
Source File: WireMockApplicationListener.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
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 #11
Source File: ArmeriaSpringActuatorAutoConfiguration.java    From armeria with Apache License 2.0 5 votes vote down vote up
@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 #12
Source File: ReconnectTest.java    From pinpoint with 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 #13
Source File: ZookeeperServer.java    From camel-spring-boot with 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 #14
Source File: CauchoRemotingTests.java    From spring-analysis-note with 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 #15
Source File: ArtemisConfig.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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 #16
Source File: StompBrokerRelayMessageHandlerIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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 #17
Source File: ClientMockBenchmark.java    From raptor with 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 #18
Source File: ClientIntegrationBenchmark.java    From raptor with 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 #19
Source File: ClusterTest.java    From pinpoint with 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 #20
Source File: MockSpringMvcBenchmark.java    From raptor with 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 #21
Source File: FunctionalExporterTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@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 #22
Source File: CuratorZookeeperClientTest.java    From pinpoint with 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 #23
Source File: GRpcServerProperties.java    From grpc-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
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 #24
Source File: ManualEmbeddedMongoDbIntegrationTest.java    From tutorials with 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 #25
Source File: ConsulBinderTests.java    From spring-cloud-consul with 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 #26
Source File: SleuthBenchmarkingSpringApp.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@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 File: LocalDataflowResource.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
@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 #28
Source File: PinpointClientFactoryTest.java    From pinpoint with 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 #29
Source File: LocalTaskLauncherIntegrationTests.java    From spring-cloud-deployer-local with Apache License 2.0 4 votes vote down vote up
private void basicLaunchAndValidation(AppDefinition definition, Map<String, String> deploymentProperties) {
	List<String> commandLineArgs = new ArrayList<>(1);
	// Test to ensure no issues parsing server.port command line arg.
	commandLineArgs.add(LocalTaskLauncher.SERVER_PORT_KEY_COMMAND_LINE_ARG + SocketUtils.findAvailableTcpPort(LocalTaskLauncher.DEFAULT_SERVER_PORT));

	AppDeploymentRequest request = new AppDeploymentRequest(definition, this.testApplication(), deploymentProperties, commandLineArgs);


	this.log.info("Launching {}...", request.getDefinition().getName());

	String launchId = this.taskLauncher().launch(request);
	assertThat(taskLauncher.getRunningTaskExecutionCount(), eventually(is(1)));
	Timeout timeout = this.deploymentTimeout();

	Assert.assertThat(launchId, EventuallyMatcher.eventually(this.hasStatusThat(Matchers.hasProperty("state", Matchers.is(LaunchState.complete))), timeout.maxAttempts, timeout.pause));

	this.taskLauncher().destroy(definition.getName());
	assertThat(taskLauncher.getRunningTaskExecutionCount(), eventually(is(0)));
}
 
Example #30
Source File: NioUdpDataSenderTest.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
@After
public void setDown()  {
    IOUtils.closeQuietly(receiver);
    // port conflict happens when testcases run continuously so port number is increased.
    PORT = SocketUtils.findAvailableUdpPort(61112);
}