Example usage for java.net ServerSocket close

List of usage examples for java.net ServerSocket close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this socket.

Usage

From source file:org.apache.stratos.python.cartridge.agent.test.PythonCartridgeAgentTest.java

/**
 * TearDown method for test method testPythonCartridgeAgent
 *///ww w . ja v  a  2s  .  c o  m
@After
public void tearDown() {
    for (Map.Entry<String, Executor> entry : executorList.entrySet()) {
        try {
            String commandText = entry.getKey();
            Executor executor = entry.getValue();
            ExecuteWatchdog watchdog = executor.getWatchdog();
            if (watchdog != null) {
                log.info("Terminating process: " + commandText);
                watchdog.destroyProcess();
            }
            File workingDirectory = executor.getWorkingDirectory();
            if (workingDirectory != null) {
                log.info("Cleaning working directory: " + workingDirectory.getAbsolutePath());
                FileUtils.deleteDirectory(workingDirectory);
            }
        } catch (Exception ignore) {
        }
    }
    for (ServerSocket serverSocket : serverSocketList) {
        try {
            log.info("Stopping socket server: " + serverSocket.getLocalSocketAddress());
            serverSocket.close();
        } catch (IOException ignore) {
        }
    }

    try {
        log.info("Deleting source checkout folder...");
        FileUtils.deleteDirectory(new File(SOURCE_PATH));
    } catch (Exception ignore) {

    }

    this.instanceStatusEventReceiver.terminate();
    this.topologyEventReceiver.terminate();

    this.instanceActivated = false;
    this.instanceStarted = false;
}

From source file:org.apache.stratos.python.cartridge.agent.test.PythonAgentTestManager.java

/**
 * TearDown method for test method testPythonCartridgeAgent
 *//*from   w  w w.  j a  va 2  s .co  m*/
protected void tearDown(String sourcePath) {
    for (Map.Entry<String, Executor> entry : executorList.entrySet()) {
        try {
            String commandText = entry.getKey();
            Executor executor = entry.getValue();
            log.info("Terminating process: " + commandText);
            executor.setExitValue(0);
            executor.getWatchdog().destroyProcess();
        } catch (Exception ignore) {
        }
    }
    // wait until everything cleans up to avoid connection errors
    sleep(1000);
    for (ServerSocket serverSocket : serverSocketMap.values()) {
        try {
            log.info("Stopping socket server: " + serverSocket.getLocalSocketAddress());
            serverSocket.close();
        } catch (IOException ignore) {
        }
    }
    try {
        if (thriftTestServer != null) {
            thriftTestServer.stop();
        }
    } catch (Exception e) {
        log.error("Could not stop Thrift test server", e);
    }

    try {
        log.info("Deleting source checkout folder...");
        FileUtils.deleteDirectory(new File(sourcePath));
    } catch (Exception ignore) {
    }
    this.instanceStatusEventReceiver.terminate();
    this.topologyEventReceiver.terminate();

    this.instanceActivated = false;
    this.instanceStarted = false;
    try {
        broker.stop();
    } catch (Exception e) {
        log.error("Error while stopping the broker service", e);
    }
}

From source file:com.reversemind.hypergate.server.HyperGateServer.java

/**
 * Detect free setPort on System// w  w  w  .ja  va2  s  . c o m
 *
 * @return
 */
private int detectFreePort() {
    try {
        ServerSocket serverSocket = new ServerSocket(0);
        if (serverSocket.getLocalPort() == -1) {
            System.exit(-100);
            throw new RuntimeException(
                    "\n\nCould not start HyperGateServer there are no any free port in the system available");
        }

        int detectedPortNumber = serverSocket.getLocalPort();

        serverSocket.close();
        int count = 0;
        while (!serverSocket.isClosed()) {
            if (count++ > 10) {
                throw new RuntimeException("Could not start HyperGateServer");
            }
            try {
                Thread.sleep(100);
                LOG.info("Waiting for closing auto discovered socket try number#" + count);
            } catch (InterruptedException e) {
                System.exit(-100);
                throw new RuntimeException("Could not start HyperGateServer");
            }
        }
        serverSocket = null;

        return detectedPortNumber;
    } catch (IOException e) {
        e.printStackTrace();
    }
    throw new RuntimeException("Could not start HyperGateServer 'cause no any available free port in system");
}

From source file:de.uniluebeck.itm.spyglass.gui.wizard.WisebedPacketReaderConfigurationWizard.java

private boolean checkIfServerSocketCanBeOpened(String host, int port) {
    try {/*from ww w.  j  a va  2 s.co  m*/
        ServerSocket socket = new ServerSocket();
        socket.bind(new InetSocketAddress(host, port));
        socket.close();
        return true;
    } catch (IOException e) {
        return false;
    }
}

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

public void setupSSHD(String dataDir, boolean absolutePath) throws Exception {
    cd(dataDir, absolutePath);/*from ww  w.j ava  2 s  . c om*/
    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();
}

From source file:org.apache.stratos.cartridge.agent.test.JavaCartridgeAgentTest.java

@After
public void tearDown() {
    for (Map.Entry<String, Executor> entry : executorList.entrySet()) {
        try {//from w ww.j ava  2  s  .  c o  m
            String commandText = entry.getKey();
            Executor executor = entry.getValue();
            ExecuteWatchdog watchdog = executor.getWatchdog();
            if (watchdog != null) {
                log.info("Terminating process: " + commandText);
                watchdog.destroyProcess();
            }
            //                File workingDirectory = executor.getWorkingDirectory();
            //                if (workingDirectory != null) {
            //                    log.info("Cleaning working directory: " + workingDirectory.getAbsolutePath());
            //                    FileUtils.deleteDirectory(workingDirectory);
            //                }
        } catch (Exception ignore) {
        }
    }
    for (ServerSocket serverSocket : serverSocketList) {
        try {
            log.info("Stopping socket server: " + serverSocket.getLocalSocketAddress());
            serverSocket.close();
        } catch (IOException e) {
            log.info("Couldn't stop socket server " + serverSocket.getLocalSocketAddress() + ", "
                    + e.getMessage());
        }
    }

    try {
        log.info("Deleting source checkout folder...");
        FileUtils.deleteDirectory(new File("/tmp/test-jca-source"));
    } catch (Exception ignore) {
    }

    //this.instanceStatusEventReceiver.terminate();
    //  this.topologyEventReceiver.terminate();

    this.instanceActivated = false;
    this.instanceStarted = false;
}

From source file:org.apache.stratos.python.cartridge.agent.integration.tests.PythonAgentIntegrationTest.java

protected String startActiveMQInstance(int amqpPort, int mqttPort, boolean secured) throws Exception {

    try {/*from   w  w w. ja  va 2s . c  o m*/
        ServerSocket serverSocket = new ServerSocket(amqpPort);
        serverSocket.close();
    } catch (IOException e) {
        throw new RuntimeException("AMQP port " + amqpPort + " is already in use.", e);
    }

    try {
        ServerSocket serverSocket = new ServerSocket(mqttPort);
        serverSocket.close();
    } catch (IOException e) {
        throw new RuntimeException("MQTT port " + mqttPort + " is already in use.", e);
    }

    System.setProperty("mb.username", "system");
    System.setProperty("mb.password", "manager");

    String brokerName = "testBroker-" + amqpPort + "-" + mqttPort;

    log.info("Starting an ActiveMQ instance");
    BrokerService broker = new BrokerService();
    broker.addConnector("tcp://localhost:" + (amqpPort));
    broker.addConnector("mqtt://localhost:" + (mqttPort));

    if (secured) {
        AuthenticationUser authenticationUser = new AuthenticationUser("system", "manager", "users,admins");
        List<AuthenticationUser> authUserList = new ArrayList<>();
        authUserList.add(authenticationUser);
        broker.setPlugins(new BrokerPlugin[] { new SimpleAuthenticationPlugin(authUserList) });
    }

    broker.setBrokerName(brokerName);
    broker.setDataDirectory(PythonAgentIntegrationTest.class.getResource(PATH_SEP).getPath() + PATH_SEP + ".."
            + PATH_SEP + PYTHON_AGENT_DIR_NAME + PATH_SEP + "activemq-data-" + brokerName);
    broker.start();
    this.messageBrokers.put(brokerName, broker);
    log.info(
            "ActiveMQ Broker service [" + brokerName + "] started! [AMQP] " + amqpPort + " [MQTT] " + mqttPort);

    return brokerName;
}

From source file:brooklyn.util.ssh.BashCommandsIntegrationTest.java

License:asdf

@Test(groups = "Integration", dependsOnMethods = "testSudo")
public void testWaitForPortFreeWhenAbortingOnTimeout() throws Exception {
    ServerSocket serverSocket = openServerSocket();
    try {//from w w w.ja  v a2  s  . c om
        int port = serverSocket.getLocalPort();
        String cmd = BashCommands.waitForPortFree(port, Duration.ONE_SECOND, true);

        int exitcode = loc.execCommands("test", ImmutableList.of(cmd));
        assertEquals(exitcode, 1);

        serverSocket.close();
        assertTrue(Networking.isPortAvailable(port));
        int exitcode2 = loc.execCommands("test", ImmutableList.of(cmd));
        assertEquals(exitcode2, 0);
    } finally {
        serverSocket.close();
    }
}

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

private String getDefaultPort() {
    ServerSocket serverSocket = null;
    try {//from   ww w  .j  a  va 2s  . 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:org.apache.servicemix.http.ProviderEndpointTest.java

public void testSendProblemWithServerDying() throws Exception {
    HttpComponent http = new HttpComponent();

    HttpSoapProviderEndpoint ep1 = new HttpSoapProviderEndpoint();
    ep1.setService(new QName("http://servicemix.apache.org/samples/wsdl-first", "PersonService"));
    ep1.setEndpoint("soap");
    ep1.setWsdl(new ClassPathResource("person.wsdl"));
    ep1.setValidateWsdl(false); // TODO: Soap 1.2 not handled yet
    ep1.setUseJbiWrapper(true);/*w  ww . j a va  2 s. com*/

    http.addEndpoint(ep1);
    container.activateComponent(http, "http");

    container.start();

    new Thread() {
        public void run() {
            ServerSocket ss = null;
            try {
                ss = new ServerSocket(8192);
                Socket s = ss.accept();
                Thread.sleep(50);
                s.close();
            } catch (Throwable t) {
                t.printStackTrace();
            } finally {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }.start();

    ServiceMixClient client = new DefaultServiceMixClient(container);
    InOut me = client.createInOutExchange();
    me.setService(new QName("http://servicemix.apache.org/samples/wsdl-first", "PersonService"));
    me.setOperation(new QName("http://servicemix.apache.org/samples/wsdl-first", "GetPerson"));
    me.getInMessage().setContent(
            new StringSource("<jbi:message xmlns:jbi=\"http://java.sun.com/xml/ns/jbi/wsdl-11-wrapper\""
                    + "             xmlns:msg=\"http://servicemix.apache.org/samples/wsdl-first/types\" "
                    + "             name=\"Hello\" " + "             type=\"msg:HelloRequest\" "
                    + "             version=\"1.0\">" + "  <jbi:part>"
                    + "    <msg:GetPerson><msg:personId>id</msg:personId></msg:GetPerson>" + "  </jbi:part>"
                    + "</jbi:message>"));
    client.sendSync(me);
    assertEquals(ExchangeStatus.ERROR, me.getStatus());
}