Example usage for org.springframework.util SocketUtils findAvailableTcpPort

List of usage examples for org.springframework.util SocketUtils findAvailableTcpPort

Introduction

In this page you can find the example usage for org.springframework.util SocketUtils findAvailableTcpPort.

Prototype

public static int findAvailableTcpPort() 

Source Link

Document

Find an available TCP port randomly selected from the range [ #PORT_RANGE_MIN , #PORT_RANGE_MAX ].

Usage

From source file:com.wk.lodge.composite.web.tomcat.IntegrationCompositeTests.java

@BeforeClass
public static void setup() throws Exception {

    System.setProperty("spring.profiles.active", "test.tomcat");

    port = SocketUtils.findAvailableTcpPort();

    server = new TomcatWebSocketTestServer(port);
    server.deployConfig(TestDispatcherServletInitializer.class);
    server.start();//from   ww  w .  ja va  2 s .c  om

    webSocketUri = "ws://localhost:" + port + "/composite/websocket";

    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);

}

From source file:org.appverse.web.framework.backend.frontfacade.websocket.IntegrationWebsocketTest.java

@BeforeClass
public static void setup() throws Exception {

    // Since test classpath includes both embedded Tomcat and Jetty we need to
    // set a Spring profile explicitly to bypass WebSocket engine detection.
    // See {@link org.springframework.samples.portfolio.config.WebSocketConfig}

    // This test is not supported with Jetty because it doesn't seem to support
    // deployment withspecific ServletContainerInitializer's at for testing

    System.setProperty("spring.profiles.active", "test.tomcat");

    port = SocketUtils.findAvailableTcpPort();

    server = new TomcatWebSocketTestServer(port);
    server.deployConfig(TestDispatcherServletInitializer.class, WebSecurityInitializer.class);
    server.start();//w  w  w.java 2  s. c  om

    loginAndSaveJsessionIdCookie("fabrice", "fab123", 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);
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.google.GoogleProviderUtils.java

static private Proxy openSshTunnel(String ip, int port, String keyFile) throws InterruptedException {
    JobExecutor jobExecutor = DaemonTaskHandler.getJobExecutor();
    List<String> command = new ArrayList<>();

    // Make sure we don't have an entry for this host already (GCP recycles IPs).
    command.add("ssh-keygen");
    command.add("-R");
    command.add(ip);/*from  w  w  w  .  ja v a  2  s .c o m*/
    JobRequest request = new JobRequest().setTokenizedCommand(command);
    JobStatus status = jobExecutor.backoffWait(jobExecutor.startJob(request));

    if (status.getResult() != JobStatus.Result.SUCCESS) {
        if (status.getStdErr().contains("No such file")) {
            log.info("No ssh known_hosts file exists yet");
        } else {
            throw new HalException(FATAL, "Unable to remove old host entry " + status.getStdErr());
        }
    }

    int localPort = SocketUtils.findAvailableTcpPort();

    command.clear();
    command.add("ssh");
    command.add("ubuntu@" + ip);
    command.add("-o");
    command.add("StrictHostKeyChecking=no");
    command.add("-i");
    command.add(keyFile);
    command.add("-N");
    command.add("-L");
    command.add(String.format("%d:localhost:%d", localPort, port));
    request = new JobRequest().setTokenizedCommand(command);

    String jobId = jobExecutor.startJob(request);

    status = jobExecutor.updateJob(jobId);

    while (status == null) {
        DaemonTaskHandler.safeSleep(TimeUnit.SECONDS.toMillis(1));
        status = jobExecutor.updateJob(jobId);
    }

    return new Proxy().setJobId(jobId).setPort(localPort);
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.kubernetes.v1.KubernetesV1DistributedService.java

@Override
default <S> S connectToInstance(AccountDeploymentDetails<KubernetesAccount> details,
        SpinnakerRuntimeSettings runtimeSettings, SpinnakerService<S> sidecar, String instanceId) {
    ServiceSettings settings = runtimeSettings.getServiceSettings(sidecar);
    String namespace = getNamespace(settings);
    int localPort = SocketUtils.findAvailableTcpPort();
    int targetPort = settings.getPort();
    List<String> command = KubernetesV1ProviderUtils.kubectlPortForwardCommand(details, namespace, instanceId,
            targetPort, localPort);/*ww w .j  av  a  2s  . c  o  m*/
    JobRequest request = new JobRequest().setTokenizedCommand(command);
    String jobId = getJobExecutor().startJob(request);

    // Wait for the proxy to spin up.
    DaemonTaskHandler.safeSleep(TimeUnit.SECONDS.toMillis(5));

    JobStatus status = getJobExecutor().updateJob(jobId);

    // This should be a long-running job.
    if (status.getState() == JobStatus.State.COMPLETED) {
        throw new HalException(Problem.Severity.FATAL, "Unable to establish a proxy against " + getServiceName()
                + ":\n" + status.getStdOut() + "\n" + status.getStdErr());
    }

    return getServiceInterfaceFactory().createService(settings.getScheme() + "://localhost:" + localPort,
            sidecar);
}

From source file:org.apache.camel.spring.boot.fatjarroutertests.StandaloneFatJarRouterTest.java

@Test
public void shouldStartCamelRoute() throws InterruptedException, IOException {
    // Given/*from w  ww.ja va  2s. co m*/
    final int port = SocketUtils.findAvailableTcpPort();
    final URL httpEndpoint = new URL("http://localhost:" + port);
    new Thread() {
        @Override
        public void run() {
            TestFatJarRouter.main(
                    "--spring.main.sources=org.apache.camel.spring.boot.fatjarroutertests.TestFatJarRouter",
                    "--http.port=" + port);
        }
    }.start();
    await().atMost(1, MINUTES).until(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            try {
                httpEndpoint.openStream();
            } catch (ConnectException ex) {
                return false;
            }
            return true;
        }
    });

    // When
    String response = IOUtils.toString(httpEndpoint);

    // Then
    assertEquals("stringBean", response);
}

From source file:org.jbb.lib.db.H2ManagedTcpServerManager.java

private void resolveH2Port() {
    if (!dbProperties.propertyNames().contains(DbProperties.H2_MANAGED_SERVER_DB_PORT_KEY)
            || StringUtils.isBlank(dbProperties.getProperty(DbProperties.H2_MANAGED_SERVER_DB_PORT_KEY))) {
        Integer randomPort = SocketUtils.findAvailableTcpPort();
        dbProperties.setProperty(DbProperties.H2_MANAGED_SERVER_DB_PORT_KEY, randomPort.toString());
        log.info("Port {} has been chosen for H2 database managed server", randomPort);
    }/*from   w  w w.  j  a  v a 2  s . c  om*/
}

From source file:org.springframework.cloud.dataflow.server.local.metrics.FakeMetricsCollector.java

public static void main(String[] args) {
    int port = SocketUtils.findAvailableTcpPort();
    LOGGER.info("Setting Fake Metrics Collector port to " + port);
    new SpringApplicationBuilder(FakeMetricsCollector.class).properties("fakeMetricsCollector.port:" + port)
            .properties("logging.level.org.springframework.boot=debug").build()
            .run("--spring.config.location=classpath:/org/springframework/cloud/dataflow/server/local/metrics/fakeMetricsCollectorConfig.yml");
}

From source file:org.springframework.cloud.dataflow.server.local.metrics.FakeMetricsCollectorResource.java

@Override
protected void before() throws Throwable {

    originalServerPort = System.getProperty(FAKE_METRICS_COLLECTOR_PORT_PROPERTY);

    this.serverPort = SocketUtils.findAvailableTcpPort();

    LOGGER.info("Setting Fake Metrics Collector port to " + this.serverPort);

    System.setProperty(FAKE_METRICS_COLLECTOR_PORT_PROPERTY, String.valueOf(this.serverPort));

    this.application = new SpringApplicationBuilder(FakeMetricsCollector.class)
            .properties("logging.level.org.springframework.boot.autoconfigure.logging=debug").build()
            .run("--spring.config.location=classpath:/org/springframework/cloud/dataflow/server/local/metrics/fakeMetricsCollectorConfig.yml");

}

From source file:org.springframework.cloud.dataflow.server.local.security.OAuth2ServerResource.java

@Override
protected void before() throws Throwable {

    originalOAuth2Port = System.getProperty(OAUTH2_PORT_PROPERTY);

    this.oauth2ServerPort = SocketUtils.findAvailableTcpPort();

    LOGGER.info("Setting OAuth2 Server port to " + this.oauth2ServerPort);

    System.setProperty(OAUTH2_PORT_PROPERTY, String.valueOf(this.oauth2ServerPort));

    this.application = new SpringApplicationBuilder(OAuth2TestServer.class).build()
            .run("--spring.config.location=classpath:/org/springframework/cloud/dataflow/server/local/security"
                    + "/support/oauth2TestServerConfig.yml");
}