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:TestSecurity.java

/**
 * put your documentation comment here/*from  w w w . j  a v  a2s  . co m*/
 * @param req
 * @param res
 * @exception ServletException, IOException
 */
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    out.println("<HTML>");
    out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");
    out.println("<BODY>");
    out.println("<BIG>Test Security</BIG>");
    try {
        out.println(h2o + "Information..." + h2c);
        out.println("  Security Manager: " + getSecurityManager().getClass().getName() + p);
        out.println("  ClassLoader: " + this.getClass().getClassLoader() + p);
        //            weblogic.utils.classloaders.GenericClassLoader gcl = (weblogic.utils.classloaders.GenericClassLoader)this.getClass().getClassLoader();
        //            gcl.setDebug( true );
        out.println("  CodeSource: " + this.getClass().getProtectionDomain().getCodeSource().getLocation() + p);
        out.println(" -- allowed -- " + p);
    } catch (Exception e) {
        out.println(" -- rejected -- " + e.getMessage() + p);
    }
    /*
     try
     {
     out.println( h2o + "Trying some dangerous J2EE calls..." + h2c );
     String hack = request.getParameter( "hack" );
     Cookie[] cookies = request.getCookies();
     out.println( " -- allowed -- " + p );
     int x = 1 + 2 + 3;
     out.println( hack );  // use it
     int y = 1 + 2 + 3;
     out.println( cookies );  // use it
     String m = "COOKIE: " + cookies[0]; // use it again
     cookies = new Cookie[10]; // reset it
     String n = "COOKIE: " + cookies[5]; // use it again
     }
     catch( Exception e ) { out.println( " -- rejected -- " + e.getMessage() + p ); }
     */
    try {
        out.println(h2o + "Attempting file write to d:/Java..." + h2c);
        File f = new File("d:/Java/blah.txt");
        FileWriter fw = new FileWriter(f);
        fw.write("test\n");
        fw.close();
        out.println(" -- allowed -- " + p);
    } catch (Exception e) {
        out.println(" -- rejected -- " + e.getMessage() + p);
    }
    try {
        out.println(h2o + "Attempting file write to d:/Java/TestServlet..." + h2c);
        File f = new File("d:/Java/TestServlet/blah.txt");
        FileWriter fw = new FileWriter(f);
        fw.write("test\n");
        fw.close();
        out.println(" -- allowed -- " + p);
    } catch (Exception e) {
        out.println(" -- rejected -- " + e.getMessage() + p);
    }
    try {
        out.println(h2o + "Attempting file read to c:/Ntdetect..." + h2c);
        File f = new File("c:/Ntdetect.com");
        FileReader fr = new FileReader(f);
        int c = fr.read();
        out.println(" -- allowed -- " + p);
    } catch (Exception e) {
        out.println(" -- rejected -- " + e.getMessage() + p);
    }
    try {
        out.println(h2o + "Attempting file read to c:/weblogic/weblogic.properties..." + h2c);
        File f = new File("c:/weblogic/weblogic.properties");
        FileReader fr = new FileReader(f);
        int c = fr.read();
        out.println(" -- allowed -- " + p);
    } catch (Exception e) {
        out.println(" -- rejected -- " + e.getMessage() + p);
    }
    try {
        out.println(h2o + "Attempting to connect to yahoo.com..." + h2c);
        Socket s = new Socket("yahoo.com", 8080);
        out.println(" -- allowed -- " + p);
    } catch (Exception e) {
        out.println(" -- rejected -- " + e.getMessage() + p);
    }
    try {
        out.println(h2o + "Attempting to connect to hacker.com..." + h2c);
        Socket s = new Socket("hacker.com", 8080);
        out.println(" -- allowed -- " + p);
    } catch (Exception e) {
        out.println(" -- rejected -- " + e.getMessage() + p);
    }
    try {
        out.println(h2o + "Attempting to listen on port 37337..." + h2c);
        ServerSocket s = new ServerSocket(37337);
        Socket c = s.accept();
        out.println(" -- allowed -- " + p);
    } catch (Exception e) {
        out.println(" -- rejected -- " + e.getMessage() + p);
    }
    try {
        out.println(h2o + "Attempting to listen on port 7001..." + h2c);
        ServerSocket s = new ServerSocket(7001);
        Socket c = s.accept();
        out.println(" -- allowed -- " + p);
    } catch (Exception e) {
        out.println(" -- rejected -- " + e.getMessage() + p);
    }
    /*
     try
     {
     out.println( h2o + "Attempting native call..." + h2c );
     native0( 1 );
     out.println( " -- allowed -- " + p );
     }           
     catch( Exception e ) { out.println( " -- rejected -- " + e.getMessage() + p ); }
     */
    try {
        out.println(h2o + "Attempting exec..." + h2c);
        Runtime.getRuntime().exec("dir");
        out.println(" -- allowed -- " + p);
    } catch (Exception e) {
        out.println(" -- rejected -- " + e.getMessage() + p);
    }
    try {
        out.println(h2o + "Attempting system exit..." + h2c);
        out.println(" -- allowed -- " + p);
    } catch (Exception e) {
        out.println(" -- rejected -- " + e.getMessage() + p);
    }
    out.println("</BODY></HTML>");
}

From source file:io.vertx.ext.consul.dc.ConsulAgent.java

private static int getFreePort() {
    int port = -1;
    try {/*from  w  w w  .  j  av a 2 s. c  om*/
        ServerSocket socket = new ServerSocket(0);
        port = socket.getLocalPort();
        socket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return port;
}

From source file:in.raster.oviyam.servlet.ListenerServlet.java

private boolean getListenerStatus() {
    boolean success = true;

    ListenerHandler lh = new ListenerHandler();
    Listener listener = lh.getListener();

    try {//  w w w.  ja  v  a  2 s  .com
        (new ServerSocket(Integer.parseInt(listener.getPort()))).close();
    } catch (UnknownHostException e) {
        success = false;
    } catch (IOException e) {
        success = false;
    }

    return success;
}

From source file:com.mirth.connect.manager.ManagerController.java

/**
 * Test a port to see if it is already in use.
 * //from  w w w. j a  v  a2 s.  c o m
 * @param port
 *            The port to test.
 * @param name
 *            A friendly name to display in case of an error.
 * @return An error message, or null if the port is not in use and there was no error.
 */
private String testPort(String port, String name) {
    ServerSocket socket = null;
    try {
        socket = new ServerSocket(Integer.parseInt(port));
    } catch (NumberFormatException ex) {
        return name + " port is invalid: " + port;
    } catch (IOException ex) {
        return name + " port is already in use: " + port;
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                return "Could not close test socket for " + name + ": " + port;
            }
        }
    }
    return null;
}

From source file:com.meyling.telnet.startup.TelnetD.java

/**
 * Method to prepare the PortListener.<br>
 *
 * Creates and prepares and runs a PortListener, with settings from the
 * passed in Properties. Yet the Listener will not accept any incoming
 * connections before startServing() has been called. this has the advantage
 * that whenever a TelnetD Singleton has been factorized, it WILL 99% not
 * fail any longer (e.g. serve its purpose).
 *
 * @param   name            Name of listner.
 * @param     settings        Properties object that holds main settings.
 * @throws     BootException    Preparation failed.
 *///w w  w.j  a v  a2s .  c o m
private void prepareListener(final String name, final Properties settings) throws BootException {

    int port = 0;
    try {
        port = Integer.parseInt(settings.getProperty(name + ".port"));
        ServerSocket socket = new ServerSocket(port);
        socket.close();
    } catch (NumberFormatException e) {
        trace.fatal(e, e);
        throw new BootException(
                "Failure while parsing port number for \"" + name + ".port\": " + e.getMessage());
    } catch (IOException e) {
        trace.fatal(e, e);
        throw new BootException(
                "Failure while starting listener for port number " + port + ": " + e.getMessage());
    }
    // factorize PortListener
    final PortListener listener = PortListener.createPortListener(name, settings);
    // start the Thread derived PortListener
    try {
        listeners.add(listener);
    } catch (Exception e) {
        trace.fatal(e, e);
        throw new BootException("Failure while starting PortListener thread: " + e.getMessage());
    }

}

From source file:org.apache.cxf.dosgi.singlebundle.AggregatedActivatorTest.java

public void testHttpServicePortInUse() throws Exception {
    BundleContext bc = EasyMock.createNiceMock(BundleContext.class);
    EasyMock.replay(bc);//from   ww w.j a v  a 2 s. c  o m

    ServerSocket s = null;
    try {
        try {
            // now lets block the default port
            s = new ServerSocket(Integer.parseInt(AggregatedActivator.DEFAULT_HTTP_PORT));
        } catch (Exception e) {
            // if someone else already has it, thats fine too
        }

        assertNull("Precondition failed", System.getProperty(AggregatedActivator.HTTP_PORT_PROPERTY));
        new AggregatedActivator().setHttpServicePort(bc);
        assertTrue("The " + AggregatedActivator.HTTP_PORT_PROPERTY + " property should have been set",
                System.getProperty(AggregatedActivator.HTTP_PORT_PROPERTY).length() > 0);
    } finally {
        if (s != null) {
            s.close();
        }
    }
}

From source file:UniqueInstance.java

/**
 * Essaye de dmarrer le gestionnaire d'instance unique. Si l'initialisation a russi, c'est que l'instance est
 * unique. Sinon, c'est qu'une autre instance de l'application est dj lance. L'appel de cette mthode prvient
 * l'application dj lance qu'une autre vient d'essayer de se connecter.
 *
 * @return {@code true} si l'instance de l'application est unique.
 */// ww w  .  ja va 2  s .  c  om
public boolean launch() {
    /* Indique si l'instance du programme est unique. */
    boolean unique;

    try {
        /* On cre une socket sur le port dfini. */
        final ServerSocket server = new ServerSocket(port);

        /* Si la cration de la socket russit, c'est que l'instance du programme est unique, aucune autre n'existe. */
        unique = true;

        /* Si il y a des actions  faire lorsqu'une autre instance essaye de dmarrer... */
        if (runOnReceive != null) {

            /* On lance un Thread d'coute sur ce port. */
            Thread portListenerThread = new Thread() {

                @Override
                public void run() {
                    /* Tant que l'application est lance... */
                    while (true) {
                        try {
                            /* On attend qu'une socket se connecte sur le serveur. */
                            final Socket socket = server.accept();

                            /* Si une socket est connecte, on coute le message envoy dans un nouveau Thread. */
                            new Thread() {

                                @Override
                                public void run() {
                                    receive(socket);
                                }
                            }.start();
                        } catch (IOException e) {
                            Logger.getLogger("UniqueInstance")
                                    .warning("Attente de connexion de socket choue.");
                        }
                    }
                }
            };

            /* Le Thread d'coute de port est dmon. */
            portListenerThread.setDaemon(true);

            /* On dmarre le Thread. */
            portListenerThread.start();
        }
    } catch (IOException e) {
        /* Si la cration de la socket choue, c'est que l'instance de n'est pas unique, une autre n'existe. */
        unique = false;

        /* Si des actions sont prvues par l'instance dj lance... */
        if (runOnReceive != null) {
            /*
             * Dans ce cas, on envoie un message  l'autre instance de l'application pour lui demander d'avoir le
             * focus (par exemple).
             */
            send();
        }
    }
    return unique;
}

From source file:org.apache.asterix.external.input.stream.factory.SocketServerInputStreamFactory.java

@Override
public synchronized AsterixInputStream createInputStream(IHyracksTaskContext ctx, int partition)
        throws HyracksDataException {
    try {/*from w  w w . j a v a  2 s . com*/
        Pair<String, Integer> socket = sockets.get(partition);
        ServerSocket server;
        server = new ServerSocket(socket.second);
        return new SocketServerInputStream(server);
    } catch (IOException e) {
        throw new HyracksDataException(e);
    }
}

From source file:org.auraframework.archetype.AuraArchetypeSimpleTestMANUAL.java

public void testProjectCreation() throws Throwable {
    Process jettyProcess = null;//from   www .  j  a  va  2s  . c om
    workspace = new File(
            System.getProperty("java.io.tmpdir") + File.separator + getName() + System.currentTimeMillis());
    try {
        // create a workspace to place the project files in
        workspace.mkdirs();

        // generate a project from the archetype
        Process genProcess = startProcess(workspace,
                ImmutableList.of("mvn", "archetype:generate", "-DarchetypeRepository=" + archRepo,
                        "-DarchetypeCatalog=" + archCatalog, "-DarchetypeGroupId=" + archetype.groupId,
                        "-DarchetypeArtifactId=" + archetype.artifactId,
                        "-DarchetypeVersion=" + archetype.version, "-DgroupId=" + project.groupId,
                        "-DartifactId=" + project.artifactId, "-Dversion=" + project.version,
                        "-Dpackage=" + projectPackage, "-DinteractiveMode=false"));
        goldMavenOutput(genProcess, "-creation.txt", "Failed to generate artifact!");

        File projectDir = new File(workspace, project.artifactId);
        assertDirectory(projectDir);
        verifyGeneratedResources(projectDir);

        // build the new project
        Process buildProcess = startProcess(projectDir, ImmutableList.of("mvn", "install"));
        goldMavenOutput(buildProcess, "-install.txt", "Failed to build new project!");

        // get a free port for jetty
        ServerSocket socket = new ServerSocket(0);
        int jettyPort = socket.getLocalPort();
        socket.close();

        // start up jetty
        jettyProcess = startProcess(projectDir,
                ImmutableList.of("mvn", "jetty:run", "-Djetty.port=" + jettyPort));

        int status = 0;
        for (int i = 0; i < 30; i++) {
            try {
                HttpGet get = obtainGetMethod("/");
                HttpResponse response = perform(get);
                status = getStatusCode(response);
                get.releaseConnection();
                break;
            } catch (ConnectException ce) {
                // expected, before server is listening
                Thread.sleep(1000);
            }
        }
        assertEquals("Failed to connect to server", HttpStatus.SC_OK, status);

        verifyDefaultDocument();
        verifySampleComponents();
    } catch (Throwable t) {
        // if any errors in Jetty requests, let's print out the Jetty
        // console output for diag before killing the
        // test
        if (jettyProcess != null) {
            InputStream is = jettyProcess.getInputStream();
            int len = is.available();
            byte[] buf = new byte[len];
            is.read(buf);
            System.err.println(new String(buf));
        }
        throw t;
    } finally {
        // kill Jetty
        if (jettyProcess != null) {
            try {
                jettyProcess.exitValue();
            } catch (IllegalThreadStateException e) {
                jettyProcess.destroy();
            }
        }
        // cleanup generated workspace
        IOUtil.delete(workspace);
    }
}

From source file:org.auraframework.integration.test.archetype.AuraArchetypeSimpleTestMANUAL.java

@Test
public void testProjectCreation() throws Throwable {
    Process jettyProcess = null;/*from  w  ww. j  a v  a2  s .  co  m*/
    workspace = new File(IOUtil.newTempDir("archetype"));
    try {
        // create a workspace to place the project files in
        workspace.mkdirs();

        // generate a project from the archetype
        Process genProcess = startProcess(workspace,
                ImmutableList.of("mvn", "archetype:generate", "-DarchetypeRepository=" + archRepo,
                        "-DarchetypeCatalog=" + archCatalog, "-DarchetypeGroupId=" + archetype.groupId,
                        "-DarchetypeArtifactId=" + archetype.artifactId,
                        "-DarchetypeVersion=" + archetype.version, "-DgroupId=" + project.groupId,
                        "-DartifactId=" + project.artifactId, "-Dversion=" + project.version,
                        "-Dpackage=" + projectPackage, "-DinteractiveMode=false"));
        goldMavenOutput(genProcess, "-creation.txt", "Failed to generate artifact!");

        File projectDir = new File(workspace, project.artifactId);
        assertDirectory(projectDir);
        verifyGeneratedResources(projectDir);

        // build the new project
        Process buildProcess = startProcess(projectDir, ImmutableList.of("mvn", "install"));
        goldMavenOutput(buildProcess, "-install.txt", "Failed to build new project!");

        // get a free port for jetty
        ServerSocket socket = new ServerSocket(0);
        int jettyPort = socket.getLocalPort();
        socket.close();

        // start up jetty
        jettyProcess = startProcess(projectDir,
                ImmutableList.of("mvn", "jetty:run", "-Djetty.port=" + jettyPort));

        int status = 0;
        for (int i = 0; i < 30; i++) {
            try {
                HttpGet get = obtainGetMethod("/");
                HttpResponse response = perform(get);
                status = getStatusCode(response);
                get.releaseConnection();
                break;
            } catch (ConnectException ce) {
                // expected, before server is listening
                Thread.sleep(1000);
            }
        }
        assertEquals("Failed to connect to server", HttpStatus.SC_OK, status);

        verifyDefaultDocument();
        verifySampleComponents();
    } catch (Throwable t) {
        // if any errors in Jetty requests, let's print out the Jetty
        // console output for diag before killing the
        // test
        if (jettyProcess != null) {
            InputStream is = jettyProcess.getInputStream();
            int len = is.available();
            byte[] buf = new byte[len];
            is.read(buf);
            System.err.println(new String(buf));
        }
        throw t;
    } finally {
        // kill Jetty
        if (jettyProcess != null) {
            try {
                jettyProcess.exitValue();
            } catch (IllegalThreadStateException e) {
                jettyProcess.destroy();
            }
        }
        // cleanup generated workspace
        IOUtil.delete(workspace);
    }
}