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.flink.runtime.taskmanager.TestManagerStartupTest.java

/**
 * Tests that the TaskManager fails synchronously when the actor system port
 * is in use.//  w w w  . j  a  v  a 2 s.c  o m
 */
@Test
public void testStartupWhenTaskmanagerActorPortIsUsed() {
    ServerSocket blocker = null;
    try {
        final String localHostName = "localhost";
        final InetAddress localAddress = InetAddress.getByName(localHostName);

        // block some port
        blocker = new ServerSocket(0, 50, localAddress);
        final int port = blocker.getLocalPort();

        try {
            TaskManager.runTaskManager(localHostName, port, new Configuration(), StreamingMode.BATCH_ONLY,
                    TaskManager.class);
            fail("This should fail with an IOException");
        } catch (IOException e) {
            // expected. validate the error message
            assertNotNull(e.getMessage());
            assertTrue(e.getMessage().contains("Address already in use"));
        }

    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    } finally {
        if (blocker != null) {
            try {
                blocker.close();
            } catch (IOException e) {
                // no need to log here
            }
        }
    }
}

From source file:ca.uhn.hl7v2.testpanel.controller.Controller.java

/**
 * Provide a random, currently unused port
 *//*w ww.ja  v a  2s.  c  om*/
private int provideRandomPort() {
    ServerSocket server;
    try {
        server = new ServerSocket(0);
        int port = server.getLocalPort();
        server.close();
        return port;
    } catch (IOException e) {
        throw new Error(e);
    }
}

From source file:com.mirth.connect.server.Mirth.java

/**
 * Test a port to see if it is already in use.
 * /*w w  w .j a va 2  s . c  o m*/
 * @param port
 *            The port to test.
 * @param name
 *            A friendly name to display in case of an error.
 * @return
 */
private boolean testPort(String host, String port, String name) {
    ServerSocket socket = null;

    try {
        if (StringUtils.equals(host, "0.0.0.0") || StringUtils.equals(host, "::")) {
            socket = new ServerSocket(Integer.parseInt(port));
        } else {
            socket = new ServerSocket(Integer.parseInt(port), 0, InetAddress.getByName(host));
        }
    } catch (NumberFormatException ex) {
        logger.error(name + " port is invalid: " + port);
        return false;
    } catch (IOException ex) {
        logger.error(name + " port is already in use: " + port);
        return false;
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                logger.error("Could not close test socket for " + name + ": " + port);
                return false;
            }
        }
    }

    return true;
}

From source file:com.addthis.hydra.task.output.tree.TreeMapper.java

private void _init(TaskRunConfig runConfig) throws Exception {
    config = runConfig;//from   w w w .j  a  va2  s.  com
    mapstats = new TreeMapperStats(log);

    resolve();

    if (nodeCache != null)
        TreeCommonParameters.setDefaultCleanQueueSize(nodeCache);
    if (trashInterval != null)
        TreeCommonParameters.setDefaultTrashInterval(trashInterval);
    if (trashTimeLimit != null)
        TreeCommonParameters.setDefaultTrashTimeLimit(trashTimeLimit);
    if (storage != null) {
        if (storage.maxCacheSize != null)
            TreeCommonParameters.setDefaultMaxCacheSize(storage.maxCacheSize);
        if (storage.maxCacheMem != null)
            TreeCommonParameters.setDefaultMaxCacheMem(storage.maxCacheMem);
        if (storage.maxPageSize != null)
            TreeCommonParameters.setDefaultMaxPageSize(storage.maxCacheSize);
        if (storage.maxPageMem != null)
            TreeCommonParameters.setDefaultMaxPageMem(storage.maxPageMem);
        if (storage.memSample != null)
            TreeCommonParameters.setDefaultMemSample(storage.memSample);
    }

    if (Strings.isEmpty(localhost)) {
        localhost = InetAddress.getLocalHost().getHostAddress();
    }
    log.info("[init] java=" + System.getProperty("java.vm.version") + " query=" + enableQuery + " http="
            + enableHttp + " jmx=" + enableJmx + " live=" + live);
    log.info("[init] host=" + localhost + " port=" + port + " target=" + root + " job=" + config.jobId);

    Path treePath = Paths.get(runConfig.dir, "data");
    tree = new ConcurrentTree(Files.initDirectory(treePath.toFile()));
    bench = new Bench(EnumSet.allOf(BENCH.class), 1000);

    if (enableHttp) {
        jetty = new Server(port > 0 ? port++ : 0);
        jetty.start();
        int httpPort = jetty.getConnectors()[0].getLocalPort();
        log.info("[init.http] http://" + localhost + ":" + httpPort + "/");
        Files.write(new File("job.port"), Bytes.toBytes(Integer.toString(httpPort)), false);
    }

    if (enableJmx) {
        int queryPort = 0;
        jmxname = new ObjectName("com.addthis.hydra:type=Hydra,node=" + queryPort);
        ManagementFactory.getPlatformMBeanServer().registerMBean(mapstats, jmxname);
        ServerSocket ss = new ServerSocket();
        ss.setReuseAddress(true);
        ss.bind(port > 0 ? new InetSocketAddress(port++) : null);
        int jmxport = ss.getLocalPort();
        ss.close();
        if (jmxport == -1) {
            log.warn("[init.jmx] failed to get a port");
        } else {
            try {
                jmxremote = new MBeanRemotingSupport(jmxport);
                jmxremote.start();
                log.info("[init.jmx] port=" + jmxport);
            } catch (Exception e) {
                log.warn("[init.jmx] err=" + e);
            }
        }
    }

    if (config.jobId != null && live && livePort > -1) {
        QueryEngine liveQueryEngine = new QueryEngine(tree);
        connectToMesh(treePath.toFile(), runConfig.jobId, liveQueryEngine);
    }

    startTime = System.currentTimeMillis();

    if (pre != null) {
        log.warn("pre-chain: " + pre);
        processBundle(new KVBundle(), pre);
    }
}

From source file:eu.stratosphere.nephele.taskmanager.TaskManager.java

private int getAvailablePort() {
    ServerSocket serverSocket = null;
    int port = 0;
    for (int i = 0; i < 50; i++) {
        try {//from   w w w  .j av a 2  s. c o m
            serverSocket = new ServerSocket(0);
            port = serverSocket.getLocalPort();
            if (port != 0) {
                serverSocket.close();
                break;
            }
        } catch (IOException e) {
            LOG.debug("Unable to allocate port " + e.getMessage(), e);
        }
    }
    if (!serverSocket.isClosed()) {
        try {
            serverSocket.close();
        } catch (IOException e) {
            LOG.debug("error closing port", e);
        }
    }
    return port;
}

From source file:org.lilyproject.hadooptestfw.fork.HBaseTestingUtility.java

public static int randomFreePort() {
    int port = 0;
    do {//from  w  w w  .  j a  v  a  2s. c  o  m
        port = randomPort();
        try {
            ServerSocket sock = new ServerSocket(port);
            sock.close();
        } catch (IOException ex) {
            port = 0;
        }
    } while (port == 0);
    return port;
}

From source file:com.entertailion.java.fling.FlingFrame.java

protected void vlcTranscode(final String file) {
    // Transcoding does not support jumps
    isTranscoding = true;/*from   www . ja va 2 s.  c o m*/

    // http://caprica.github.io/vlcj/javadoc/2.1.0/index.html
    try {
        // clean up previous session
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }
        if (mediaPlayerFactory != null) {
            mediaPlayerFactory.release();
        }
        mediaPlayerFactory = new MediaPlayerFactory();
        mediaPlayer = mediaPlayerFactory.newHeadlessMediaPlayer();
        // Add a component to be notified of player events
        mediaPlayer.addMediaPlayerEventListener(new MediaPlayerEventAdapter() {
            public void opening(MediaPlayer mediaPlayer) {
                Log.d(LOG_TAG, "VLC Transcoding: Opening");
            }

            public void buffering(MediaPlayer mediaPlayer, float newCache) {
                Log.d(LOG_TAG, "VLC Transcoding: Buffering");
            }

            public void playing(MediaPlayer mediaPlayer) {
                Log.d(LOG_TAG, "VLC Transcoding: Playing");

                setDuration((int) (mediaPlayer.getLength() / 1000.0f));
                Log.d(LOG_TAG, "duration=" + duration);
            }

            public void paused(MediaPlayer mediaPlayer) {
                Log.d(LOG_TAG, "VLC Transcoding: Paused");
            }

            public void stopped(MediaPlayer mediaPlayer) {
                Log.d(LOG_TAG, "VLC Transcoding: Stopped");
            }

            public void finished(MediaPlayer mediaPlayer) {
                Log.d(LOG_TAG, "VLC Transcoding: Finished");
            }

            public void error(MediaPlayer mediaPlayer) {
                Log.d(LOG_TAG, "VLC Transcoding: Error");
            }

            public void videoOutput(MediaPlayer mediaPlayer, int newCount) {
                Log.d(LOG_TAG, "VLC Transcoding: VideoOutput");
            }
        });

        // Find a port for VLC HTTP server
        boolean started = false;
        int vlcPort = port + 1;
        while (!started) {
            try {
                ServerSocket serverSocket = new ServerSocket(vlcPort);
                Log.d(LOG_TAG, "Available port for VLC: " + vlcPort);
                started = true;
                serverSocket.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
                vlcPort++;
            } catch (Exception ex) {
                break;
            }
        }

        if (!rampClient.isClosed()) {
            rampClient.stop();
        }
        Inet4Address address = getNetworAddress();
        if (address != null) {
            // Play a particular item, with options if necessary
            final String options[] = { ":sout=#transcode{" + transcodingParameterValues
                    + "}:http{mux=webm,dst=:" + vlcPort + "/cast.webm}", ":sout-keep" };
            // http://192.168.0.8:8087/cast.webm
            final String url = "http://" + address.getHostAddress() + ":" + vlcPort + "/cast.webm";
            Log.d(LOG_TAG, "url=" + url);
            if (true || isChromeCast()) {
                rampClient.launchApp(appId == null ? APP_ID : appId, selectedDialServer);
                // wait for socket to be ready...
                new Thread(new Runnable() {
                    public void run() {
                        while (!rampClient.isStarted() && !rampClient.isClosed()) {
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                            }
                        }
                        if (!rampClient.isClosed()) {
                            mediaPlayer.playMedia(file, options);
                            rampClient.load(url);
                        }
                    }
                }).start();
            } else {
                rampClient.load(url);
            }
        } else {
            Log.d(LOG_TAG, "could not find a network interface");
        }
    } catch (Throwable e) {
        Log.e(LOG_TAG, "vlcTranscode: " + file, e);
    }
}

From source file:com.cloud.utils.crypt.EncryptionSecretKeyChecker.java

public void check(Properties dbProps) throws IOException {
    String encryptionType = dbProps.getProperty("db.cloud.encryption.type");

    s_logger.debug("Encryption Type: " + encryptionType);

    if (encryptionType == null || encryptionType.equals("none")) {
        return;/*from w  w  w  .java  2  s . c o  m*/
    }

    if (s_useEncryption) {
        s_logger.warn("Encryption already enabled, is check() called twice?");
        return;
    }

    s_encryptor.setAlgorithm("PBEWithMD5AndDES");
    String secretKey = null;

    SimpleStringPBEConfig stringConfig = new SimpleStringPBEConfig();

    if (encryptionType.equals("file")) {
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(s_keyFile);
        if (is == null) {
            is = this.getClass().getClassLoader().getResourceAsStream(s_altKeyFile);
        }
        if (is == null) { //This is means we are not able to load key file from the classpath.
            throw new CloudRuntimeException(
                    s_keyFile + " File containing secret key not found in the classpath: ");
        }
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(is));
            secretKey = in.readLine();
            //Check for null or empty secret key
        } catch (IOException e) {
            throw new CloudRuntimeException("Error while reading secret key from: " + s_keyFile, e);
        } finally {
            IOUtils.closeQuietly(in);
        }

        if (secretKey == null || secretKey.isEmpty()) {
            throw new CloudRuntimeException("Secret key is null or empty in file " + s_keyFile);
        }

    } else if (encryptionType.equals("env")) {
        secretKey = System.getenv(s_envKey);
        if (secretKey == null || secretKey.isEmpty()) {
            throw new CloudRuntimeException("Environment variable " + s_envKey + " is not set or empty");
        }
    } else if (encryptionType.equals("web")) {
        ServerSocket serverSocket = null;
        int port = 8097;
        try {
            serverSocket = new ServerSocket(port);
        } catch (IOException ioex) {
            throw new CloudRuntimeException("Error initializing secret key reciever", ioex);
        }
        s_logger.info("Waiting for admin to send secret key on port " + port);
        Socket clientSocket = null;
        try {
            clientSocket = serverSocket.accept();
        } catch (IOException e) {
            throw new CloudRuntimeException("Accept failed on " + port);
        }
        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String inputLine;
        if ((inputLine = in.readLine()) != null) {
            secretKey = inputLine;
        }
        out.close();
        in.close();
        clientSocket.close();
        serverSocket.close();
    } else {
        throw new CloudRuntimeException("Invalid encryption type: " + encryptionType);
    }

    stringConfig.setPassword(secretKey);
    s_encryptor.setConfig(stringConfig);
    s_useEncryption = true;
}

From source file:org.apache.flink.streaming.api.functions.sink.SocketClientSinkTest.java

@Test
public void testSocketSink() throws Exception {
    final ServerSocket server = new ServerSocket(0);
    final int port = server.getLocalPort();

    final AtomicReference<Throwable> error = new AtomicReference<Throwable>();

    Thread sinkRunner = new Thread("Test sink runner") {
        @Override/*from ww w .  ja va 2  s  .  co  m*/
        public void run() {
            try {
                SocketClientSink<String> simpleSink = new SocketClientSink<>(host, port, simpleSchema, 0);
                simpleSink.open(new Configuration());
                simpleSink.invoke(TEST_MESSAGE + '\n');
                simpleSink.close();
            } catch (Throwable t) {
                error.set(t);
            }
        }
    };

    sinkRunner.start();

    Socket sk = server.accept();
    BufferedReader rdr = new BufferedReader(new InputStreamReader(sk.getInputStream()));

    String value = rdr.readLine();

    sinkRunner.join();
    server.close();

    if (error.get() != null) {
        Throwable t = error.get();
        t.printStackTrace();
        fail("Error in spawned thread: " + t.getMessage());
    }

    assertEquals(TEST_MESSAGE, value);
}

From source file:org.apache.flink.streaming.api.functions.sink.SocketClientSinkTest.java

@Test
public void testSinkAutoFlush() throws Exception {
    final ServerSocket server = new ServerSocket(0);
    final int port = server.getLocalPort();

    final SocketClientSink<String> simpleSink = new SocketClientSink<>(host, port, simpleSchema, 0, true);
    simpleSink.open(new Configuration());

    final AtomicReference<Throwable> error = new AtomicReference<Throwable>();

    Thread sinkRunner = new Thread("Test sink runner") {
        @Override// w  w  w  .jav  a2 s  .c om
        public void run() {
            try {
                // need two messages here: send a fin to cancel the client state:FIN_WAIT_2 while the server is CLOSE_WAIT
                simpleSink.invoke(TEST_MESSAGE + '\n');
            } catch (Throwable t) {
                error.set(t);
            }
        }
    };

    sinkRunner.start();

    Socket sk = server.accept();
    BufferedReader rdr = new BufferedReader(new InputStreamReader(sk.getInputStream()));
    String value = rdr.readLine();

    sinkRunner.join();
    simpleSink.close();
    server.close();

    if (error.get() != null) {
        Throwable t = error.get();
        t.printStackTrace();
        fail("Error in spawned thread: " + t.getMessage());
    }

    assertEquals(TEST_MESSAGE, value);
}