Example usage for java.net ServerSocket getLocalPort

List of usage examples for java.net ServerSocket getLocalPort

Introduction

In this page you can find the example usage for java.net ServerSocket getLocalPort.

Prototype

public int getLocalPort() 

Source Link

Document

Returns the port number on which this socket is listening.

Usage

From source file:org.wso2.carbon.identity.common.testng.CarbonBasedTestListener.java

/**
 * Initializes the micro-service server.
 * Detects an available port from the system and use that for the microservice server.
 *///www .  j  a  v  a 2  s  . c o  m
private MicroserviceServer initMicroserviceServer(Object realInstance) throws TestCreationException {

    try {

        ServerSocket s = new ServerSocket(0);
        int port = s.getLocalPort();
        s.close();

        MicroserviceServer microserviceServer = new MicroserviceServer(port);
        microserviceServer.init();
        microserviceServerMap.put(realInstance, microserviceServer);
        return microserviceServer;

    } catch (IOException e) {
        throw new TestCreationException("Could not get an aviailable port for micro-service", e);
    }
}

From source file:org.robovm.eclipse.internal.AbstractLaunchConfigurationDelegate.java

public int findFreePort() {
    ServerSocket socket = null;
    try {/*w  ww  .j a va2 s. co  m*/
        socket = new ServerSocket(0);
        return socket.getLocalPort();
    } catch (IOException localIOException2) {
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException localIOException4) {
            }
        }
    }
    return -1;
}

From source file:org.springframework.security.config.ldap.LdapServerBeanDefinitionParser.java

private String getDefaultPort() {
    ServerSocket serverSocket = null;
    try {/*from w  w w  .ja  va 2 s.  c om*/
        try {
            serverSocket = new ServerSocket(DEFAULT_PORT);
        } catch (IOException e) {
            try {
                serverSocket = new ServerSocket(0);
            } catch (IOException e2) {
                return String.valueOf(DEFAULT_PORT);
            }
        }
        return String.valueOf(serverSocket.getLocalPort());
    } finally {
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:net.sourceforge.cobertura.test.util.WebappServer.java

public WebappServer(File webappServerDir, boolean tomcat) {
    this.tomcat = tomcat;
    ServerSocket s;
    try {/*from www  . java 2s .c  o m*/
        s = new ServerSocket(0);
        webappPort = s.getLocalPort();
        s.close();

        s = new ServerSocket(0);
        stopPort = s.getLocalPort();
        s.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.springframework.security.kerberos.test.MiniKdc.java

/**
 * Creates a MiniKdc.// w  ww . ja  v a2 s. c o  m
 *
 * @param conf MiniKdc configuration.
 * @param workDir working directory, it should be the build directory. Under
 *                this directory an ApacheDS working directory will be created,
 *                this directory will be deleted when the MiniKdc stops.
 * @throws Exception  thrown if the MiniKdc could not be created.
 */
public MiniKdc(Properties conf, File workDir) throws Exception {
    if (!conf.keySet().containsAll(PROPERTIES)) {
        Set<String> missingProperties = new HashSet<String>(PROPERTIES);
        missingProperties.removeAll(conf.keySet());
        throw new IllegalArgumentException("Missing configuration properties: " + missingProperties);
    }
    this.workDir = new File(workDir, Long.toString(System.currentTimeMillis()));
    if (!workDir.exists() && !workDir.mkdirs()) {
        throw new RuntimeException("Cannot create directory " + workDir);
    }
    LOG.info("Configuration:");
    LOG.info("---------------------------------------------------------------");
    for (Map.Entry<?, ?> entry : conf.entrySet()) {
        LOG.info("  {}: {}", entry.getKey(), entry.getValue());
    }
    LOG.info("  localhost hostname: {}", InetAddress.getLocalHost().getHostName());
    LOG.info("  localhost canonical hostname: {}", InetAddress.getLocalHost().getCanonicalHostName());
    LOG.info("---------------------------------------------------------------");
    this.conf = conf;
    port = Integer.parseInt(conf.getProperty(KDC_PORT));
    if (port == 0) {
        ServerSocket ss = new ServerSocket(0, 1, InetAddress.getByName(conf.getProperty(KDC_BIND_ADDRESS)));
        port = ss.getLocalPort();
        ss.close();
    }
    String orgName = conf.getProperty(ORG_NAME);
    String orgDomain = conf.getProperty(ORG_DOMAIN);
    realm = orgName.toUpperCase() + "." + orgDomain.toUpperCase();
}

From source file:org.coltram.nsd.bonjour.LocalExposedBonjourService.java

public LocalExposedBonjourService(TopManager topManager, ServerSocket serverSocket, ServiceInfo serviceInfo,
        String serviceId, JSONObject service) {
    this.serviceInfo = serviceInfo;
    this.serviceId = serviceId;
    this.topManager = topManager;
    this.serverSocket = serverSocket;
    services.add(this);
    log.finer("created coltram bonjour service on port " + serverSocket.getLocalPort() + " id:" + serviceId);
    JSONArray events = service.optJSONArray("eventList");
    if (events != null) {
        try {/* w w w  .ja v a  2  s .  c  om*/
            eventVariables = new ArrayList<EventVariable>();
            for (int i = 0; i < events.length(); i++) {
                // create event variable
                eventVariables.add(new EventVariable(events.getString(i)));
            }
        } catch (JSONException e) {
        }
    }
}

From source file:hudson.remoting.Launcher.java

/**
 * Listens on an ephemeral port, record that port number in a port file,
 * then accepts one TCP connection.//  w  w w . j  a va2  s .c  o m
 */
private void runAsTcpServer() throws IOException, InterruptedException {
    // if no one connects for too long, assume something went wrong
    // and avoid hanging foreever
    ServerSocket ss = new ServerSocket(0, 1);
    ss.setSoTimeout(30 * 1000);

    // write a port file to report the port number
    FileWriter w = new FileWriter(tcpPortFile);
    w.write(String.valueOf(ss.getLocalPort()));
    w.close();

    // accept just one connection and that's it.
    // when we are done, remove the port file to avoid stale port file
    Socket s;
    try {
        s = ss.accept();
        ss.close();
    } finally {
        tcpPortFile.delete();
    }

    runOnSocket(s);
}

From source file:org.y20k.transistor.helpers.MetadataHelper.java

private void createShoutcastProxyConnection() {
    closeShoutcastProxyConnection();//from  w  ww. ja v  a2 s.c  om
    mProxyRunning = true;
    final StringBuffer shoutcastProxyUri = new StringBuffer();

    try {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Socket proxy = null;
                URLConnection connection = null;

                try {
                    final ServerSocket proxyServer = new ServerSocket(0, 1, InetAddress.getLocalHost());
                    shoutcastProxyUri.append("http://localhost:")
                            .append(String.valueOf(proxyServer.getLocalPort())).append("/");
                    LogHelper.v(LOG_TAG, "createProxyConnection: " + shoutcastProxyUri.toString());

                    proxy = proxyServer.accept();
                    mProxyConnection = proxy;
                    proxyServer.close();

                    connection = new URL(mStreamUri).openConnection();

                    shoutcastProxyReaderLoop(proxy, connection);

                } catch (Exception e) {
                    LogHelper.e(LOG_TAG, "Error: Unable to create proxy server. (" + e + ")");
                }

                mProxyRunning = false;

                try {
                    if (connection != null) {
                        ((HttpURLConnection) connection).disconnect();
                    }
                } catch (Exception ee) {
                    LogHelper.e(LOG_TAG, "Error: Unable to disconnect HttpURLConnection. (" + ee + ")");
                }

                try {
                    if (proxy != null && !proxy.isClosed()) {
                        proxy.close();
                    }
                } catch (Exception eee) {
                    LogHelper.e(LOG_TAG, "Error: Unable to close proxy. (" + eee + ")");
                }
            }
        }).start();

        while (shoutcastProxyUri.length() == 0) {
            try {
                Thread.sleep(10);
            } catch (Exception e) {
                LogHelper.e(LOG_TAG, "Error: Unable to Thread.sleep. (" + e + ")");
            }
        }
        mShoutcastProxy = shoutcastProxyUri.toString();

    } catch (Exception e) {
        LogHelper.e(LOG_TAG,
                "createProxyConnection: Cannot create new listening socket on localhost: " + e.toString());
        mProxyRunning = false;
        mShoutcastProxy = "";
    }
}

From source file:org.vaadin.testbenchsauce.BaseTestBenchTestCase.java

private static int findFreePort() {
    ServerSocket socket = null;
    try {// www  . ja  va 2 s.c  o  m
        socket = new ServerSocket(0);
        socket.setReuseAddress(true);
        int port = socket.getLocalPort();
        try {
            socket.close();
        } catch (IOException e) {
            // Ignore IOException on close()
        }
        return port;
    } catch (IOException ignored) {
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException ignored) {
            }
        }
    }
    throw new IllegalStateException("Could not find a free TCP/IP port to start embedded Jetty HTTP Server on");
}

From source file:com.streamsets.pipeline.stage.origin.remote.TestRemoteDownloadSource.java

public void setupSSHD(String dataDir, boolean absolutePath) throws Exception {
    cd(dataDir, absolutePath);//from  w w w .j a  va  2s . c  o  m
    ServerSocket s = new ServerSocket(0);
    port = s.getLocalPort();
    s.close();
    sshd = SshServer.setUpDefaultServer();
    sshd.setPort(port);
    sshd.setSubsystemFactories(Arrays.<NamedFactory<Command>>asList(new SftpSubsystemFactory()));
    sshd.setPasswordAuthenticator(new PasswdAuth());
    sshd.setPublickeyAuthenticator(new TestPublicKeyAuth());
    sshd.setKeyPairProvider(new HostKeyProvider());
    sshd.start();
}