Example usage for java.net ServerSocket ServerSocket

List of usage examples for java.net ServerSocket ServerSocket

Introduction

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

Prototype

public ServerSocket(int port) throws IOException 

Source Link

Document

Creates a server socket, bound to the specified port.

Usage

From source file:com.metamx.tranquility.kafka.KafkaConsumerTest.java

private static KafkaConfig getKafkaTestConfig() throws Exception {
    int port;/*w ww. j a  va  2 s . c  om*/
    try (ServerSocket server = new ServerSocket(0)) {
        port = server.getLocalPort();
    }

    Properties props = new Properties();
    props.put("broker.id", "0");
    props.put("host.name", "localhost");
    props.put("port", port);
    props.put("log.dir", tempDir.getPath());
    props.put("zookeeper.connect", zk.getConnectString());
    props.put("replica.socket.timeout.ms", "1500");
    return new KafkaConfig(props);
}

From source file:disko.flow.analyzers.socket.SocketReceiver.java

@SuppressWarnings("unchecked")
public void process(C ctx, Ports ports) throws InterruptedException {
    log.debug("Listening to port " + port);
    ServerSocket serverSocket = null;

    try {//from   w  w  w .j a va  2s. c  o  m
        serverSocket = new ServerSocket(port);
        serverSocket.setSoTimeout(5000);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    log.debug("Server socket created.");
    Set<OutputPort> closedPorts = new HashSet<OutputPort>();
    try {
        while (closedPorts.size() < ports.getOutputCount()) {
            Message message = readMessage(serverSocket);
            if (message == null)
                break;
            OutputPort output = ports.getOutput(message.getChannelId());
            if (output == null) {
                log.error("OutputPort to channel " + message.getChannelId() + " not found!");
            } else if (message.getData() == null) {
                log.debug("Received EOS of " + message.getChannelId());
                if (!ignoreEOF) {
                    output.close();
                    closedPorts.add(output);
                }
            } else if (output.put(message.getData())) {
                log.debug("Accepted " + message);
            } else {
                closedPorts.add(output);
                log.debug("Ignoring " + message);
            }
        }
    } catch (Throwable t) {
        log.error("Exception at SocketReceiver.", t);
    }
    log.debug("All SocketREceiver outputs closed, exiting normally.");
    try {
        serverSocket.close();
    } catch (Exception ioe) {
        log.error(ioe);
    }
}

From source file:com.android.unit_tests.TestHttpServer.java

public TestHttpServer() throws IOException {
    super();/*from   w w w.j av a 2s  .c  om*/
    this.params = new BasicHttpParams();
    this.params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 20000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "TEST-SERVER/1.1");
    this.httpproc = new BasicHttpProcessor();
    this.httpproc.addInterceptor(new ResponseDate());
    this.httpproc.addInterceptor(new ResponseServer());
    this.httpproc.addInterceptor(new ResponseContent());
    this.httpproc.addInterceptor(new ResponseConnControl());
    this.connStrategy = new DefaultConnectionReuseStrategy();
    this.responseFactory = new DefaultHttpResponseFactory();
    this.reqistry = new HttpRequestHandlerRegistry();
    this.serversocket = new ServerSocket(0);
}

From source file:com.bskyb.cg.environments.server.LogServer.java

private void openServerSocket() {
    try {/*from w  w w  .  j  a  v a2  s  . c om*/
        logger.info("Starting server on port : " + port);
        this.serverSocket = new ServerSocket(port);
    } catch (IOException e) {
        throw new RuntimeException("Cannot open port " + this.port, e);
    }
}

From source file:gridool.communication.transport.tcp.GridMasterSlaveWorkerServer.java

private AcceptorThread acceptConnections(final int port, final BlockingQueue<Socket> taskQueue,
        final PooledRequestHandler handler) throws GridException {
    final ServerSocket ss;
    try {// w  w w . j av a  2 s  .  co m
        ss = new ServerSocket(port);
        ss.setReuseAddress(true);
    } catch (IOException e) {
        String errmsg = "Could not create ServerSocket on port: " + port;
        LogFactory.getLog(getClass()).error(errmsg, e);
        throw new GridException(errmsg);
    }

    if (LOG.isInfoEnabled()) {
        LOG.info("GridMultiWorkersServer is started at port: " + port);
    }

    final int growThreshold = config.getReadThreadsGrowThreshold();
    final AcceptorThread acceptor = new AcceptorThread(ss, taskQueue, readerPool, growThreshold, handler);
    acceptor.start();
    return acceptor;
}

From source file:com.image32.demo.simpleapi.SimpleApiDemo.java

public static boolean checkPortAvailablity(int port) {

    ServerSocket ss = null;/* ww w. j a v  a  2 s .c  o m*/
    DatagramSocket ds = null;
    try {
        ss = new ServerSocket(port);
        ss.setReuseAddress(true);
        ds = new DatagramSocket(port);
        ds.setReuseAddress(true);
        return true;
    } catch (IOException e) {
    } finally {
        if (ds != null) {
            ds.close();
        }
        if (ss != null) {
            try {
                ss.close();
            } catch (IOException e) {
                return false;
            }
        }
    }
    return false;
}

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 .  j a v  a 2  s. co  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:com.streamsets.pipeline.stage.origin.remote.TestRemoteDownloadSource.java

public void setupSSHD(String dataDir, boolean absolutePath) throws Exception {
    cd(dataDir, absolutePath);/*from  w  w  w  .  ja  va  2s. 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.servicemix.jbi.cluster.engine.AbstractClusterEndpointTest.java

protected int findFreePort() {
    int port = 61616;
    try {//w  w  w  .j  a v  a2 s .  c o  m
        ServerSocket ss = new ServerSocket(0);
        port = ss.getLocalPort();
        ss.close();
    } catch (Exception e) {
    }
    return port;
}

From source file:com.chinamobile.bcbsp.pipes.Application.java

/**
 * This method is the constructor./*from w  ww .j  ava  2s . com*/
 * @param job
 *        contains BSPJob configuration
 */
public Application(BSPJob job) throws IOException, InterruptedException {
    serverSocket = new ServerSocket(0);
    Map<String, String> env = new HashMap<String, String>();
    env.put("TMPDIR", System.getProperty("java.io.tmpdir"));
    env.put("bcbsp.pipes.command.port", Integer.toString(serverSocket.getLocalPort()));
    List<String> cmd = new ArrayList<String>();
    String executable = job.getJobExe();
    FileUtil.chmod(executable, "a+x");
    cmd.add(executable);

    process = runClient(cmd, env);
    clientSocket = serverSocket.accept();
    this.handler = new TaskHandler();
    this.downlink = new BinaryProtocol(clientSocket, handler);
    this.downlink.start();
}