/** @tests java.net.ServerSocket#getLocalSocketAddress() */
  public void test_getLocalSocketAddress() throws Exception {
    // set up server connect and then validate that we get the right
    // response for the local address
    ServerSocket theSocket = new ServerSocket(0, 5, InetAddress.getLocalHost());
    int portNumber = theSocket.getLocalPort();
    assertTrue(
        "Returned incorrect InetSocketAddress(1):"
            + theSocket.getLocalSocketAddress().toString()
            + "Expected: "
            + (new InetSocketAddress(InetAddress.getLocalHost(), portNumber)).toString(),
        theSocket
            .getLocalSocketAddress()
            .equals(new InetSocketAddress(InetAddress.getLocalHost(), portNumber)));
    theSocket.close();

    // now create a socket that is not bound and validate we get the
    // right answer
    theSocket = new ServerSocket();
    assertNull(
        "Returned incorrect InetSocketAddress -unbound socket- Expected null",
        theSocket.getLocalSocketAddress());

    // now bind the socket and make sure we get the right answer
    theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
    int localPort = theSocket.getLocalPort();
    assertEquals(
        "Returned incorrect InetSocketAddress(2):",
        theSocket.getLocalSocketAddress(),
        new InetSocketAddress(InetAddress.getLocalHost(), localPort));
    theSocket.close();
  }
Esempio n. 2
0
 /** List file names */
 public Enumeration nlst(String s) throws IOException {
   InetAddress inetAddress = InetAddress.getLocalHost();
   byte ab[] = inetAddress.getAddress();
   serverSocket_ = new ServerSocket(0, 1);
   StringBuffer sb = new StringBuffer(32);
   sb.append("PORT ");
   for (int i = 0; i < ab.length; i++) {
     sb.append(String.valueOf(ab[i] & 255));
     sb.append(",");
   }
   sb.append(String.valueOf(serverSocket_.getLocalPort() >>> 8 & 255));
   sb.append(",");
   sb.append(String.valueOf(serverSocket_.getLocalPort() & 255));
   if (issueCommand(sb.toString()) != FTP_SUCCESS) {
     serverSocket_.close();
     throw new IOException(getResponseString());
   } else if (issueCommand("NLST " + ((s == null) ? "" : s)) != FTP_SUCCESS) {
     serverSocket_.close();
     throw new IOException(getResponseString());
   }
   dataSocket_ = serverSocket_.accept();
   serverSocket_.close();
   serverSocket_ = null;
   Vector v = readServerResponse_(dataSocket_.getInputStream());
   dataSocket_.close();
   dataSocket_ = null;
   return (v == null) ? null : v.elements();
 }
Esempio n. 3
0
  public TCPConnectionMap(
      String service_name,
      ThreadFactory f,
      SocketFactory socket_factory,
      Receiver r,
      InetAddress bind_addr,
      InetAddress external_addr,
      int srv_port,
      int max_port,
      long reaper_interval,
      long conn_expire_time)
      throws Exception {
    this.mapper = new Mapper(f, reaper_interval);
    this.receiver = r;
    this.bind_addr = bind_addr;
    this.conn_expire_time = conn_expire_time;
    if (socket_factory != null) this.socket_factory = socket_factory;
    this.srv_sock =
        Util.createServerSocket(this.socket_factory, service_name, bind_addr, srv_port, max_port);

    if (external_addr != null) local_addr = new IpAddress(external_addr, srv_sock.getLocalPort());
    else if (bind_addr != null) local_addr = new IpAddress(bind_addr, srv_sock.getLocalPort());
    else local_addr = new IpAddress(srv_sock.getLocalPort());

    acceptor = f.newThread(thread_group, new ConnectionAcceptor(), "ConnectionMap.Acceptor");
  }
  /** @tests java.net.ServerSocket#ServerSocket(int, int) */
  public void test_ConstructorII() throws IOException {
    try {
      s = new ServerSocket(0, 10);
      s.setSoTimeout(2000);
      startClient(s.getLocalPort());
      sconn = s.accept();
    } catch (InterruptedIOException e) {
      return;
    }

    ServerSocket s1 = new ServerSocket(0);
    try {
      try {
        ServerSocket s2 = new ServerSocket(s1.getLocalPort());
        s2.close();
        fail("Was able to create two serversockets on same port");
      } catch (BindException e) {
        // Expected
      }
    } finally {
      s1.close();
    }

    s1 = new ServerSocket(0);
    int allocatedPort = s1.getLocalPort();
    s1.close();
    s1 = new ServerSocket(allocatedPort);
    s1.close();
  }
Esempio n. 5
0
  @Test
  public void testBind() throws Exception {
    Configuration conf = new Configuration();
    ServerSocket socket = new ServerSocket();
    InetSocketAddress address = new InetSocketAddress("0.0.0.0", 0);
    socket.bind(address);
    try {
      int min = socket.getLocalPort();
      int max = min + 100;
      conf.set("TestRange", min + "-" + max);

      ServerSocket socket2 = new ServerSocket();
      InetSocketAddress address2 = new InetSocketAddress("0.0.0.0", 0);
      Server.bind(socket2, address2, 10, conf, "TestRange");
      try {
        assertTrue(socket2.isBound());
        assertTrue(socket2.getLocalPort() > min);
        assertTrue(socket2.getLocalPort() <= max);
      } finally {
        socket2.close();
      }
    } finally {
      socket.close();
    }
  }
Esempio n. 6
0
  /** Setup the sockets needed for the given transfer mode (either passive or active). */
  private void setupTransferMode() {
    String resp = "";

    if (passive) {
      debug("Switching to passive mode");
      System.out.println("=> PASV");
      out.println(commands[PASV]);
      resp = getResponse();
      System.out.println(resp);

      /* If we've successfully entered passive mode, setup the socket */
      if (resp.startsWith("227")) {
        String[] foo = resp.split(",");
        int pasvPort =
            new Integer(foo[4]) * 256 + new Integer(foo[5].replaceAll("[a-zA-Z).]+", ""));

        debug("Opening passive socket on " + serverAddr + ":" + pasvPort);

        try {
          pasvSock = new Socket(serverAddr, pasvPort, null, sock.getLocalPort() + 1);
          pasvIn = new BufferedReader(new InputStreamReader(pasvSock.getInputStream()));
        } catch (IOException e) {
          System.err.println(e.getMessage());
        }
      } else {
        debug("Got invalid response from PASV command");
      }
    } else {
      /* Active mode */
      debug("Switching to active mode");

      try {
        activeSock = new ServerSocket(0);
      } catch (IOException e) {
        System.err.println("Error creating active socket: " + e.getMessage());
      }

      byte[] addr = sock.getLocalAddress().getAddress();
      debug("Listening on local port " + activeSock.getLocalPort());

      String portCmd =
          "PORT "
              + ((int) addr[0] & 0xFF)
              + ","
              + ((int) addr[1] & 0xFF)
              + ","
              + ((int) addr[2] & 0xFF)
              + ","
              + ((int) addr[3] & 0xFF)
              + ","
              + activeSock.getLocalPort() / 256
              + ","
              + activeSock.getLocalPort() % 256;

      System.out.println("=> " + portCmd);
      out.println(portCmd);
      System.out.println(getResponse());
    }
  }
Esempio n. 7
0
  private void onBind(ProxyMessage msg) throws IOException {
    ProxyMessage response = null;

    if (proxy == null) ss = new ServerSocket(0);
    else ss = new SocksServerSocket(proxy, msg.ip, msg.port);

    ss.setSoTimeout(acceptTimeout);

    log("Trying accept on " + ss.getInetAddress() + ":" + ss.getLocalPort());

    if (msg.version == 5)
      response = new Socks5Message(CProxy.SOCKS_SUCCESS, ss.getInetAddress(), ss.getLocalPort());
    else
      response = new Socks4Message(Socks4Message.REPLY_OK, ss.getInetAddress(), ss.getLocalPort());
    response.write(out);

    mode = ACCEPT_MODE;

    pipe_thread1 = Thread.currentThread();
    pipe_thread2 = new Thread(this);
    pipe_thread2.start();

    // Make timeout infinit.
    sock.setSoTimeout(0);
    int eof = 0;

    try {
      while ((eof = in.read()) >= 0) {
        if (mode != ACCEPT_MODE) {
          if (mode != PIPE_MODE) return; // Accept failed

          remote_out.write(eof);
          break;
        }
      }
    } catch (EOFException eofe) {
      // System.out.println("EOF exception");
      return; // Connection closed while we were trying to accept.
    } catch (InterruptedIOException iioe) {
      // Accept thread interrupted us.
      // System.out.println("Interrupted");
      if (mode != PIPE_MODE) return; // If accept thread was not successfull return.
    } finally {
      // System.out.println("Finnaly!");
    }

    if (eof < 0) // Connection closed while we were trying to accept;
    return;

    // Do not restore timeout, instead timeout is set on the
    // remote socket. It does not make any difference.

    pipe(in, remote_out);
  }
  public SetIfModifiedSince() throws Exception {

    serverSock = new ServerSocket(0);
    int port = serverSock.getLocalPort();

    Thread thr = new Thread(this);
    thr.start();

    Date date = new Date(new Date().getTime() - 1440000); // this time yesterday
    URL url;
    HttpURLConnection con;

    // url = new URL(args[0]);
    url = new URL("http://localhost:" + String.valueOf(port) + "/anything");
    con = (HttpURLConnection) url.openConnection();

    con.setIfModifiedSince(date.getTime());
    con.connect();
    int ret = con.getResponseCode();

    if (ret == 304) {
      System.out.println("Success!");
    } else {
      throw new RuntimeException(
          "Test failed! Http return code using setIfModified method is:"
              + ret
              + "\nNOTE:some web servers are not implemented according to RFC, thus a failed test does not necessarily indicate a bug in setIfModifiedSince method");
    }
  }
Esempio n. 9
0
  /**
   * Launches a thread to connect the Emacs standard I/O buffer for the current process to the
   * standard I/O of the process.
   *
   * <p>This method creates a socket for the standard I/O connection. The thread waits for Emacs to
   * connect to the standard I/O socket.
   *
   * @return Address of standard I/O socket.
   * @exception JDEException if an error occurs
   */
  public int initSIOConnect() throws JDEException {

    ServerSocket ss = null;
    try {
      ss = new ServerSocket(0);
    } catch (IOException ex) {
      throw new JDEException("Unable to create a server socket");
    }

    final ServerSocket sstmp = ss;
    final int port = ss.getLocalPort();

    standardIOConnectThread =
        new Thread("Standard I/O Thread for App #" + appID) {
          public void run() {
            try {
              signal(
                  MESSAGE, "Debugger waiting for Emacs to connect to app SIO port " + port + ".");
              sioSocket = sstmp.accept();
              sstmp.close();
            } catch (IOException ex) {
              signal(
                  ERROR,
                  "IOException occurred while connecting to app SIO port "
                      + port
                      + ". Shutting down...");
              shutdown();
            }
          }
        };

    standardIOConnectThread.start();
    return port;
  }
Esempio n. 10
0
  void test() throws Exception {
    InetSocketAddress proxyAddress = new InetSocketAddress(proxyHost, proxyPort);
    Proxy httpProxy = new Proxy(Proxy.Type.HTTP, proxyAddress);

    try (ServerSocket ss = new ServerSocket(0);
        Socket sock = new Socket(httpProxy)) {
      sock.setSoTimeout(SO_TIMEOUT);
      sock.setTcpNoDelay(false);

      InetSocketAddress externalAddress =
          new InetSocketAddress(InetAddress.getLocalHost(), ss.getLocalPort());

      out.println("Trying to connect to server socket on " + externalAddress);
      sock.connect(externalAddress);
      try (Socket externalSock = ss.accept()) {
        // perform some simple checks
        check(sock.isBound(), "Socket is not bound");
        check(sock.isConnected(), "Socket is not connected");
        check(!sock.isClosed(), "Socket should not be closed");
        check(sock.getSoTimeout() == SO_TIMEOUT, "Socket should have a previously set timeout");
        check(sock.getTcpNoDelay() == false, "NODELAY should be false");

        simpleDataExchange(sock, externalSock);
      }
    }
  }
Esempio n. 11
0
  /**
   * Create a server with the specified port, listen backlog, and local IP address to bind to. The
   * localIP argument can be used on a multi-homed host for a ServerSocket that will only accept
   * connect requests to one of its addresses. If localIP is null, it will default accepting
   * connections on any/all local addresses. The port must be between 0 and 65535, inclusive. <br>
   * This methods blocks.
   */
  public void start(final int port, final int backlog, final InetAddress localIP) {

    executor = Executors.newFixedThreadPool(poolSize);

    try {
      ss = new ServerSocket(port, backlog, localIP);
      final String address = ss.getInetAddress().getHostAddress();
      final int localPort = ss.getLocalPort();
      log.info("Starting SOCKS Proxy on: {}:{}", address, localPort);
      setProxyStatus(ProxyStatus.STARTED);

      while (true) {
        final Socket s = ss.accept();
        final String hostName = s.getInetAddress().getHostName();
        final int port2 = s.getPort();
        log.info("Accepted from:{}:{}", hostName, port2);

        final DnsProxyServer ps = new DnsProxyServer(auth, s, dnsResolver);
        executor.submit(ps);
      }
    } catch (final IOException ioe) {
      log.error("Can't start proxy", ioe);
      setProxyStatus(ProxyStatus.ERROR);
    } finally {
    }
  }
Esempio n. 12
0
  public static void main(String[] args) {

    try {
      System.out.println("Initializing Plain Server");

      ServerSocket myServerSocket = new ServerSocket(DEFAULT_SERVER_PORT);

      System.out.println(
          "Server is waiting for an incoming connection on host="
              + InetAddress.getLocalHost().getCanonicalHostName()
              + " port="
              + myServerSocket.getLocalPort());
      Socket socket = myServerSocket.accept();

      BufferedReader myInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      PrintStream myOutput = new PrintStream(socket.getOutputStream());

      String buf = myInput.readLine();

      if (buf != null) {
        String message = "Server read: [" + buf + "]";
        System.out.println(message);
        myOutput.print(message);
      }

      socket.close();
      System.out.println("Server completed task.");

    } catch (IOException ex) {
      ex.printStackTrace();
      System.err.println("FATAL: Server died on the task.");
    }
  }
  /**
   * Tries to start a server on the specified port.
   *
   * @param host - host name (IP) to use
   * @param port - port to use for opened socket
   */
  private void init(String host, int port) {
    if (host != null) {
      this.host = host;
    } else {
      try {
        this.host = InetAddress.getLocalHost().getHostAddress();
      } catch (UnknownHostException xcp) {
        xcp.printStackTrace();
        this.host = null;
      }
    }

    try {
      serverSocket = new ServerSocket(port);
    } catch (IOException xcp) {
      handleFailureToCreateServerSocket(port, xcp);
      return;
    }

    // Get port being used for server socket
    this.port = serverSocket.getLocalPort();

    // Create a server thread and start it listening
    Runnable serverConnectionDaemon = new ServerConnectionDaemon();
    ThreadTools.startAsDaemon(serverConnectionDaemon, "Data Object Server Conn Daemon");

    printIfDebug(
        ".init: comm server started listening on:\n"
            + "\thost = "
            + this.host
            + "\n\tport = "
            + this.port);
  }
Esempio n. 14
0
  /**
   * Parses a script of AI programs with which to play, launching and connecting to each of them as
   * a new Player.
   *
   * @param launchFilename The formatted script containing the commands to run to be Players. Each
   *     line must be a separate command. Each line must wrap the intended identifier with curly
   *     braces and placehold the server port number with two percent signs ("%%").
   * @throws FileNotFoundException
   * @throws IOException
   * @throws InterruptedException
   * @throws ProtocolViolation
   */
  private void parseLaunchScript(String launchFilename)
      throws FileNotFoundException, IOException, InterruptedException, ProtocolViolation {
    int portNumber = accept.getLocalPort();
    Pattern getIdentifier = Pattern.compile("\\{([^}]+)\\}");
    Runtime r = Runtime.getRuntime();
    String portString = String.valueOf(portNumber);

    try (BufferedReader br = new BufferedReader(new FileReader(launchFilename))) {
      String line;
      while ((line = br.readLine()) != null) {
        Matcher matcher = getIdentifier.matcher(line);
        if (!matcher.find()) {
          throw new IllegalStateException("The identifier must be wrapped with curly braces.");
        }
        String identifier = matcher.group(1);
        line = matcher.replaceAll(identifier);
        line = line.replaceAll("%%", portString);

        System.out.format("Starting \"%s\": %s\n", identifier, line);

        Process process = r.exec(line);
        Socket socket = accept.accept();
        players.add(new Player(identifier, socket, process));
      }
    }
  }
Esempio n. 15
0
 public String decodeUrl(final String path) throws Exception {
   ServerSocket serverSocket = new ServerSocket(0);
   final int port = serverSocket.getLocalPort();
   serverSocket.close();
   Server server = new Server(port);
   server.setStopAtShutdown(true);
   ServletContextHandler ctx = new ServletContextHandler(server, "/", true, false);
   ctx.addServlet(new ServletHolder(new DecodeServlet()), "/*");
   server.start();
   ThreadUtils.sleep(500);
   new Thread() {
     @Override
     public void run() {
       try {
         ThreadUtils.sleep(500);
         InputStream is = new URL("http://localhost:" + port + path).openStream();
       } catch (IOException e) {
         throw new RuntimeException(e);
       }
     }
   }.start();
   synchronized (this) {
     wait();
   }
   return this.decodedPath;
 }
Esempio n. 16
0
  protected synchronized void stopHTTPServer() throws HTTPServerException {
    logger.log(2, "HTTP_SERVER/STOP_HTTP_SERVER");

    try {
      thread = null;

      try {
        Socket outputSocket = new Socket();
        outputSocket.connect(
            new InetSocketAddress(
                APJP.APJP_LOCAL_HTTP_SERVER_ADDRESS, serverSocket.getLocalPort()));
        outputSocket.close();
      } catch (Exception e) {

      }

      try {
        serverSocket.close();
      } catch (Exception e) {

      }
    } catch (Exception e) {
      logger.log(2, "HTTP_SERVER/STOP_HTTP_SERVER: EXCEPTION", e);

      throw new HTTPServerException("HTTP_SERVER/STOP_HTTP_SERVER", e);
    }
  }
  /**
   * Initializes the serversocket and the multiplexer.
   *
   * @param selectorCreator The selector creator that will be used for creating a selector for the
   *     multiplexer.
   */
  private void init(SelectorCreator selectorCreator) {
    try {
      ServerSocketChannel channel = ServerSocketChannel.open();
      ServerSocket serverSocket = channel.socket();

      // Set the preference to bandwidth > short connection time && latency (only large messages
      // will be send / received here).
      serverSocket.setPerformancePreferences(0, 0, 2);

      serverSocket.bind(null);
      Config.setUsingPort(serverSocket.getLocalPort());

      channel.configureBlocking(false);
      selector = selectorCreator.getSelector();
      channel.register(selector, SelectionKey.OP_ACCEPT);

      ToolDataHandlerFactory toolDataHandlerFactory =
          new ToolDataHandlerFactory(InterToolDataHandler.class);
      multiplexer =
          new MultiThreadedMultiplexer(
              selectorCreator, Multiplexer.SERVERMODE, toolDataHandlerFactory);
      multiplexer.setDaemon(true);
      multiplexer.start();
    } catch (IOException ioex) {
      Logger.getInstance()
          .log(
              "An IOException occured while initializing the MultiplexingClientServer.",
              Logger.ERROR,
              ioex);
    }
  }
Esempio n. 18
0
  /** Test the http protocol handler with one WWW-Authenticate header with the value "NTLM". */
  static void testNTLM() throws Exception {
    // server reply
    String reply = authReplyFor("NTLM");

    System.out.println("====================================");
    System.out.println("Expect client to fail with 401 Unauthorized");
    System.out.println(reply);

    try (ServerSocket ss = new ServerSocket(0)) {
      Client client = new Client(ss.getLocalPort());
      Thread thr = new Thread(client);
      thr.start();

      // client ---- GET ---> server
      // client <--- 401 ---- client
      try (Socket s = ss.accept()) {
        new MessageHeader().parseHeader(s.getInputStream());
        s.getOutputStream().write(reply.getBytes("US-ASCII"));
      }

      // the client should fail with 401
      System.out.println("Waiting for client to terminate");
      thr.join();
      IOException ioe = client.ioException();
      if (ioe != null) System.out.println("Client failed: " + ioe);
      int respCode = client.respCode();
      if (respCode != 0 && respCode != -1)
        System.out.println("Client received HTTP response code: " + respCode);
      if (respCode != HttpURLConnection.HTTP_UNAUTHORIZED)
        throw new RuntimeException("Unexpected response code");
    }
  }
Esempio n. 19
0
  public InetSocketAddress getAddress() {
    if (serverSocket != null && serverSocket.isBound()) {
      return new InetSocketAddress(serverSocket.getInetAddress(), serverSocket.getLocalPort());
    }

    return address;
  }
Esempio n. 20
0
  void ServerSocketTests() throws Exception {
    ServerSocket s1 = new ServerSocket();

    test("ServerSocket.setReuseAddress(true)");
    s1.setReuseAddress(true);
    check(s1.getReuseAddress());

    test("Socket.setReuseAddress(false)");
    s1.setReuseAddress(false);
    check(!s1.getReuseAddress());

    /* bind to any port */
    s1.bind(new InetSocketAddress(0));

    test("Binding ServerSocket to port already in use should throw " + "a BindException");
    ServerSocket s2 = new ServerSocket();
    try {
      s2.bind(new InetSocketAddress(s1.getLocalPort()));
      failed();
    } catch (BindException e) {
      passed();
    }
    s2.close();

    s1.close();
  }
Esempio n. 21
0
  /**
   * serviceClient accepts a client connection and reads lines from the socket. Each line is handed
   * to executeCommand for parsing and execution.
   */
  public void serviceClient() throws java.io.IOException {
    System.out.println("Accepting clients now");
    Socket clientConnection = serverSocket.accept();

    // Arrange to read input from the Socket
    InputStream inputStream = clientConnection.getInputStream();
    bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

    // Arrange to write result across Socket back to client
    OutputStream outputStream = clientConnection.getOutputStream();
    PrintStream printStream = new PrintStream(outputStream);

    System.out.println(
        "Client acquired on port #" + serverSocket.getLocalPort() + ", reading from socket");

    try {
      String commandLine;
      while ((commandLine = bufferedReader.readLine()) != null) {
        try {
          Float result = executeCommand(commandLine);
          // Only BALANCE command returns non-null
          if (result != null) {
            printStream.println(result); // Write it back to the client
          }
        } catch (ATMException atmex) {
          System.out.println("ERROR: " + atmex);
        }
      }
    } catch (SocketException sException) {
      // client has stopped sending commands.  Exit gracefully.
      System.out.println("done");
    }
  }
Esempio n. 22
0
  public void run() {
    while (true) {
      try {
        System.out.println("Server name: " + serverSocket.getInetAddress().getHostName());
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket server = serverSocket.accept();
        System.out.println("Just connected to " + server.getRemoteSocketAddress());

        ObjectInputStream objectIn = new ObjectInputStream(server.getInputStream());

        try {
          Recipe rec = (Recipe) objectIn.readObject();
          startHMI(rec, rec.getProductName());

          //				System.out.println("Object Received: width: "+rec.getWidth()+" height:
          // "+rec.getHeight());
        } catch (ClassNotFoundException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }

        DataOutputStream out = new DataOutputStream(server.getOutputStream());
        out.writeUTF(
            "Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye!");
        server.close();
      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }
Esempio n. 23
0
  @Before
  public void setup() throws Exception {
    try (ServerSocket serverSocket = new ServerSocket(0)) {
      googlePort = serverSocket.getLocalPort();
    }
    googleServer = new Server(googlePort);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    googleServer.setHandler(context);
    context.addServlet(new ServletHolder(userinfoServlet), "/oauth2/v2/userinfo");
    context.addServlet(new ServletHolder(tokenServlet), "/o/oauth2/token");
    googleServer.start();

    // Allow attributes to be set and got from a session.
    final Map<String, Object> attributes = Maps.newHashMap();
    Answer<Void> setAttributeAnswer =
        new Answer<Void>() {
          @Override
          public Void answer(InvocationOnMock invocation) throws Throwable {
            attributes.put((String) invocation.getArguments()[0], invocation.getArguments()[1]);
            return null;
          }
        };
    Answer<Object> getAttributeAnswer =
        new Answer<Object>() {
          @Override
          public Object answer(InvocationOnMock invocation) throws Throwable {
            return attributes.get((String) invocation.getArguments()[0]);
          }
        };
    when(session.getAttribute(anyString())).thenAnswer(getAttributeAnswer);
    when(session.getId()).thenReturn("sessionID");
    doAnswer(setAttributeAnswer).when(session).setAttribute(anyString(), anyObject());
  }
Esempio n. 24
0
  protected void bind() throws IOException {
    URI bind = getBindLocation();

    String host = bind.getHost();
    host = (host == null || host.length() == 0) ? "localhost" : host;
    InetAddress addr = InetAddress.getByName(host);

    try {
      if (host.trim().equals("localhost") || addr.equals(InetAddress.getLocalHost())) {
        this.serverSocket = serverSocketFactory.createServerSocket(bind.getPort(), backlog);
      } else {
        this.serverSocket = serverSocketFactory.createServerSocket(bind.getPort(), backlog, addr);
      }
      this.serverSocket.setSoTimeout(2000);
    } catch (IOException e) {
      throw IOExceptionSupport.create(
          "Failed to bind to server socket: " + bind + " due to: " + e, e);
    }
    try {
      setConnectURI(
          new URI(
              bind.getScheme(),
              bind.getUserInfo(),
              resolveHostName(bind.getHost()),
              serverSocket.getLocalPort(),
              bind.getPath(),
              bind.getQuery(),
              bind.getFragment()));
    } catch (URISyntaxException e) {
      throw IOExceptionSupport.create(e);
    }
  }
Esempio n. 25
0
    public void run() {

      try {
        isStarting = true;
        synchronized (this) {
          serverSocket = new ServerSocket(0);
          this.port = serverSocket.getLocalPort();
          setRunning(true);
          isStarting = false;
          this.notifyAll();
        }

        System.err.println("Child-process heartbeat server started on port: " + port);

        while (true) {
          Socket sock = serverSocket.accept();
          log("Got heartbeat connection from client; starting heartbeat.");
          synchronized (heartBeatThreads) {
            HeartbeatThread hbt = new HeartbeatThread(sock);
            heartBeatThreads.add(hbt);
            hbt.start();
          }
        }
      } catch (Exception e) {
        if (!running) log("Heartbeat server was shutdown.");
        else log("Got expcetion in heartbeat server: " + e.getMessage());
      } finally {
        setRunning(false);
        log("Heartbeat server terminated.");
      }
    }
Esempio n. 26
0
 private void writeHostAndPortToFile(File portFile) {
   String host = socket.getInetAddress().getHostName();
   int port = socket.getLocalPort();
   // The motivation for the Log.warn would be better satisfied by Bug 38.
   Log.warn("echo " + host + ":" + port + " > " + portFile);
   StringUtilities.writeFile(portFile, host + ":" + port + "\n");
 }
Esempio n. 27
0
 public synchronized void startREPLServer() {
   if (ackREPLServer == null) {
     try {
       // TODO use ClojureOSGi.withBundle instead
       Var startServer =
           BundleUtils.requireAndGetVar(
               getBundle().getSymbolicName(), "clojure.tools.nrepl.server/start-server");
       Object defaultHandler =
           BundleUtils.requireAndGetVar(
                   getBundle().getSymbolicName(), "clojure.tools.nrepl.server/default-handler")
               .invoke();
       Object handler =
           BundleUtils.requireAndGetVar(
                   getBundle().getSymbolicName(), "clojure.tools.nrepl.ack/handle-ack")
               .invoke(defaultHandler);
       ackREPLServer =
           (ServerSocket)
               ((Map) startServer.invoke(Keyword.intern("handler"), handler))
                   .get(Keyword.intern("server-socket"));
       CCWPlugin.log(
           "Started ccw nREPL server: nrepl://127.0.0.1:" + ackREPLServer.getLocalPort());
     } catch (Exception e) {
       CCWPlugin.logError("Could not start plugin-hosted REPL server", e);
       throw new RuntimeException("Could not start plugin-hosted REPL server", e);
     }
   }
 }
Esempio n. 28
0
  public void run() {
    Prefs prefs = Prefs.getPrefs();
    ServerSocket socket = null;
    String ipcKey = UUID.randomUUID().toString();
    try {
      socket = new ServerSocket(0, 0, LOCALHOST);
      int port = socket.getLocalPort();
      prefs.setPort(port);
      prefs.setIPCKey(ipcKey);
      prefs.flush();

      while (true) {
        Socket s = socket.accept();
        new SocketProcessor(s, ipcKey);
      }
    } catch (IOException e) {
      throw new IllegalStateException(e);
    } finally {
      if (socket != null) {
        try {
          socket.close();
        } catch (IOException e) {
          // ignore
        }
      }
    }
  }
Esempio n. 29
0
  /**
   * Returns port number {@link SelectorHandler} is listening on Similar to <code>getPort()</code>,
   * but getting port number directly from connection ({@link ServerSocket}, {@link
   * DatagramSocket}). So if default port number 0 was set during initialization, then <code>
   * getPort()</code> will return 0, but getPortLowLevel() will return port number assigned by OS.
   *
   * @return port number or -1 if {@link SelectorHandler} was not initialized for accepting
   *     connections.
   * @deprecated Use {@link getPort}
   */
  public int getPortLowLevel() {
    if (serverSocket != null) {
      return serverSocket.getLocalPort();
    }

    return -1;
  }
 /**
  * For finding the free port available.
  *
  * @return
  */
 private static int findFreePort() {
   ServerSocket socket = null;
   try {
     socket = new ServerSocket(0);
     socket.setReuseAddress(true);
     int port = socket.getLocalPort();
     try {
       socket.close();
     } catch (IOException e) {
       // Ignore IOException on close()
     }
     return port;
   } catch (Exception e) {
     // Ignore
   } finally {
     if (socket != null) {
       try {
         socket.close();
       } catch (IOException e) {
         throw new RuntimeException(e);
       }
     }
   }
   return 2181;
 }