Example usage for java.net ServerSocket accept

List of usage examples for java.net ServerSocket accept

Introduction

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

Prototype

public Socket accept() throws IOException 

Source Link

Document

Listens for a connection to be made to this socket and accepts it.

Usage

From source file:org.apache.oozie.action.email.TestEmailActionExecutor.java

public void testServerTimeouts() throws Exception {
    final ServerSocket srvSocket = new ServerSocket(0);
    int srvPort = srvSocket.getLocalPort();
    Thread serverThread = new Thread() {
        @Override/*from  w ww.j  a  v  a 2s.c om*/
        public void run() {
            try {
                Socket clientSocket = srvSocket.accept();
                // Sleep 1s (timeout applied on client is 0.1s)
                Thread.sleep(1000);
                clientSocket.getOutputStream().write(0);
                clientSocket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    serverThread.setDaemon(true);
    try {
        serverThread.start();
        EmailActionExecutor email = new EmailActionExecutor();
        Context ctx = createNormalContext("email-action");
        Services.get().get(ConfigurationService.class).getConf().setInt("oozie.email.smtp.port", srvPort);
        // Apply a 0.1s timeout to induce a very quick "Read timed out" error
        Services.get().get(ConfigurationService.class).getConf().setInt("oozie.email.smtp.socket.timeout.ms",
                100);
        try {
            email.validateAndMail(ctx, prepareEmailElement(false, false));
            fail("Should have failed with a socket timeout error!");
        } catch (Exception e) {
            Throwable rootCause = e;
            while (rootCause.getCause() != null) {
                rootCause = rootCause.getCause();
            }
            assertTrue("Expected exception type to be a SocketTimeoutException, but received: " + rootCause,
                    rootCause instanceof SocketTimeoutException);
            assertTrue("Expected error to be that of a socket read timeout, but got: " + rootCause.getMessage(),
                    rootCause.getMessage().contains("Read timed out"));
        }
    } finally {
        serverThread.interrupt();
        srvSocket.close();
    }
}

From source file:org.pentaho.pac.server.JettyServer.java

public void stopHandler(JettyServer jServer, int stopPort) {
    ServerSocket server = null;
    try {//  ww  w .ja va  2  s  .co m
        server = new ServerSocket(stopPort);
    } catch (IOException ioe) {
        logger.error("IO Error:" + ioe.getLocalizedMessage()); //$NON-NLS-1$
    }
    try {
        Socket s = server.accept();
        Thread t = new Thread(new RequestHandler(jServer, s));
        t.start();
    } catch (Exception e) {
        logger.error("IO Error:" + e.getLocalizedMessage()); //$NON-NLS-1$
    }
}

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;//www.j  av  a2s.  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.glite.security.trustmanager.tomcat.TMSSLServerSocketFactory.java

public Socket acceptSocket(ServerSocket sSocket) throws IOException {
    LOGGER.debug("TMSSLServerSocketFactory.acceptSocket:");

    SSLSocket asock = null;/*from w ww .jav a2s  .  co  m*/

    try {
        asock = (SSLSocket) sSocket.accept();
        configureClientAuth(asock);
    } catch (SSLException e) {
        throw new SocketException("SSL handshake error" + e.toString());
    }

    return asock;
}

From source file:WebServer.java

/**
 * WebServer constructor.// w w  w. j a v  a  2 s  .  c om
 */
protected void start() {
    ServerSocket s;

    System.out.println("Webserver starting up on port 80");
    System.out.println("(press ctrl-c to exit)");
    try {
        // create the main server socket
        s = new ServerSocket(80);
    } catch (Exception e) {
        System.out.println("Error: " + e);
        return;
    }

    System.out.println("Waiting for connection");
    for (;;) {
        try {
            // wait for a connection
            Socket remote = s.accept();
            // remote is now the connected socket
            System.out.println("Connection, sending data.");
            BufferedReader in = new BufferedReader(new InputStreamReader(remote.getInputStream()));
            PrintWriter out = new PrintWriter(remote.getOutputStream());

            // read the data sent. We basically ignore it,
            // stop reading once a blank line is hit. This
            // blank line signals the end of the client HTTP
            // headers.
            String str = ".";
            while (!str.equals(""))
                str = in.readLine();

            // Send the response
            // Send the headers
            out.println("HTTP/1.0 200 OK");
            out.println("Content-Type: text/html");
            out.println("Server: Bot");
            // this blank line signals the end of the headers
            out.println("");
            // Send the HTML page
            out.println("<H1>Welcome to the Ultra Mini-WebServer</H2>");
            out.flush();
            remote.close();
        } catch (Exception e) {
            System.out.println("Error: " + e);
        }
    }
}

From source file:com.yahoo.pulsar.testclient.LoadSimulationClient.java

public void run() throws Exception {
    final ServerSocket serverSocket = new ServerSocket(port);

    while (true) {
        // Technically, two controllers can be connected simultaneously, but
        // non-sequential handling of commands
        // has not been tested or considered and is not recommended.
        log.info("Listening for controller command...");
        final Socket socket = serverSocket.accept();
        log.info("Connected to {}\n", socket.getInetAddress().getHostName());
        executor.submit(() -> {/* w w  w.  j a v  a  2  s.  c o m*/
            try {
                handle(socket);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        });
    }
}

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

@Test
public void testExitNoRetries() throws Exception {
    ServerSocket server = new ServerSocket(0);
    Socket channel = null;//from ww  w  .j a  v a 2 s.c o m

    try {
        SocketTextStreamFunction source = new SocketTextStreamFunction(LOCALHOST, server.getLocalPort(), "\n",
                0);

        SocketSourceThread runner = new SocketSourceThread(source);
        runner.start();

        channel = server.accept();
        channel.close();

        try {
            runner.waitUntilDone();
        } catch (Exception e) {
            assertTrue(e.getCause() instanceof EOFException);
        }
    } finally {
        if (channel != null) {
            IOUtils.closeQuietly(channel);
        }
        IOUtils.closeQuietly(server);
    }
}

From source file:org.skfiy.typhon.startup.Typhon.java

private void await() {
    ServerSocket serverSocket = null;
    try {// w w  w.  java 2 s.  co m
        serverSocket = new ServerSocket();
        serverSocket.bind(new InetSocketAddress(server.getHost(), server.getPort()), 1);
    } catch (IOException e) {
        throw new TyphonException(e);
    }

    for (;;) {
        Socket socket = null;
        try {
            socket = serverSocket.accept();
            InputStream in = socket.getInputStream();
            byte[] cur = server.getShutdown().getBytes(StandardCharsets.UTF_8);
            byte[] buf = new byte[cur.length];
            int l = in.read(buf);
            // 
            if (l == cur.length && Arrays.equals(cur, buf)) {
                break;
            }
        } catch (IOException e) {
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // nothing
                }
            }
        }
    }

    try {
        serverSocket.close();
    } catch (IOException e) {
        // nothing
    }

    // ??
    stop();
}

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

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

    try {//from  w  w w .  j  a  v  a  2  s . c o  m
        final AtomicReference<Throwable> error = new AtomicReference<Throwable>();

        Thread serverRunner = new Thread("Test server runner") {

            @Override
            public void run() {
                try {
                    Socket sk = server.accept();
                    sk.close();
                } catch (Throwable t) {
                    error.set(t);
                }
            }
        };
        serverRunner.start();

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

        // wait socket server to close
        serverRunner.join();
        if (error.get() != null) {
            Throwable t = error.get();
            t.printStackTrace();
            fail("Error in server thread: " + t.getMessage());
        }

        try {
            // socket should be closed, so this should trigger a re-try
            // need two messages here: send a fin to cancel the client state:FIN_WAIT_2 while the server is CLOSE_WAIT
            while (true) { // we have to do this more often as the server side closed is not guaranteed to be noticed immediately
                simpleSink.invoke(TEST_MESSAGE + '\n');
            }
        } catch (IOException e) {
            // check whether throw a exception that reconnect failed.
            assertTrue("Wrong exception", e.getMessage().contains(EXCEPTION_MESSGAE));
        } catch (Exception e) {
            fail("wrong exception: " + e.getClass().getName() + " - " + e.getMessage());
        }

        assertEquals(0, simpleSink.getCurrentNumberOfRetries());
    } finally {
        IOUtils.closeQuietly(server);
    }
}

From source file:org.apache.pulsar.testclient.LoadSimulationClient.java

/**
 * Start listening for controller commands to create producers and consumers.
 *//*  ww w .  j a  v  a2  s.c om*/
public void run() throws Exception {
    final ServerSocket serverSocket = new ServerSocket(port);

    while (true) {
        // Technically, two controllers can be connected simultaneously, but
        // non-sequential handling of commands
        // has not been tested or considered and is not recommended.
        log.info("Listening for controller command...");
        final Socket socket = serverSocket.accept();
        log.info("Connected to {}", socket.getInetAddress().getHostName());
        executor.submit(() -> {
            try {
                handle(socket);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        });
    }
}