下面列出了怎么用org.springframework.util.SocketUtils的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
/**
* 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);
}
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;
}
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;
}
};
}
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);
}
@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();
}
@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);
}
}
@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
@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);
}
}
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);
}
@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);
}
@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();
}
@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();
}
@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;
}
@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();
}
@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();
}
@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"));
}
@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();
}
@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);
}
@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);
}
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);
}
/**
* 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;
}
@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);
}
@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()));
}
}
@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}");
}
@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);
}
@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");
}
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;
}
/**
* Construct an EmbeddedZooKeeper with a random port.
*/
public EmbeddedZooKeeper() {
clientPort = SocketUtils.findAvailableTcpPort();
}
@Bean
public Integer randomPort() {
return SocketUtils.findAvailableTcpPort();
}