Java Code Examples for javax.net.ServerSocketFactory#getDefault()

The following examples show how to use javax.net.ServerSocketFactory#getDefault() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BaseMainService.java    From android-http-server with GNU General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
    isServiceStarted = true;

    if (activity == null) {
        throw new NullPointerException("Activity must be set at this point.");
    }
    ServerConfigFactory serverConfigFactory = getServerConfigFactory(activity);

    doFirstRunChecks(serverConfigFactory);

    controller = new ControllerImpl(serverConfigFactory, ServerSocketFactory.getDefault(), this);
    controller.start();

    return START_STICKY;
}
 
Example 2
Source File: NetworkServerControlImpl.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Create the right kind of server socket
 */

private ServerSocket createServerSocket()
	throws IOException
{
	if (hostAddress == null)
		hostAddress = InetAddress.getByName(hostArg);
	// Make a list of valid
	// InetAddresses for NetworkServerControl
	// admin commands.
	buildLocalAddressList(hostAddress);
										
	// Create the right kind of socket
	switch (getSSLMode()) {
	case SSL_OFF:
	default:
		ServerSocketFactory sf =
			ServerSocketFactory.getDefault();
		return sf.createServerSocket(portNumber
									 ,0,
									 hostAddress);
	case SSL_BASIC:
		SSLServerSocketFactory ssf =
			(SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
		return (SSLServerSocket)ssf.createServerSocket(portNumber,
													   0,
													   hostAddress);
	case SSL_PEER_AUTHENTICATION:
		SSLServerSocketFactory ssf2 =
			(SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
		SSLServerSocket sss2= 
			(SSLServerSocket)ssf2.createServerSocket(portNumber,
													 0,
													 hostAddress);
		sss2.setNeedClientAuth(true);
		return sss2;
	}
}
 
Example 3
Source File: MonitoringServer.java    From gsn with GNU General Public License v3.0 5 votes vote down vote up
/**
    * Return statistics about the GSN server, faking an HTTP server for retro-compatibility
    * 
    * the protocol is similar to the carbon protocol used by Graphite, except the timestamp
    * http://matt.aimonetti.net/posts/2013/06/26/practical-guide-to-graphite-monitoring/
    */
public MonitoringServer(int port) {
	super("Monitoring Server");

	try {
		ServerSocketFactory serverSocketFactory = ServerSocketFactory.getDefault();
           socket = serverSocketFactory.createServerSocket(port);
           socket.setSoTimeout(1000);
	}catch(Exception e){
		logger.error("unable to open socket for monitoring",e);
	}
}
 
Example 4
Source File: DefaultCliServerGui.java    From android-http-server with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Initializes the server.
 */
public void init() {
    System.setProperty("java.util.logging.SimpleFormatter.format",
            "%1$tF %1$tT  - %4$s  -  %2$s  -  %5$s%6$s%n");

    Logger rootLog = Logger.getLogger("");
    rootLog.setLevel(Level.FINE);
    rootLog.getHandlers()[0].setLevel(Level.FINE);

    ServerGui gui = new DefaultCliServerGui();
    System.out.println("   __ __ ______ ______ ___    ____                         \n"
            + "  / // //_  __//_  __// _ \\  / __/___  ____ _  __ ___  ____\n"
            + " / _  /  / /    / /  / ___/ _\\ \\ / -_)/ __/| |/ // -_)/ __/\n"
            + "/_//_/  /_/    /_/  /_/    /___/ \\__//_/   |___/ \\__//_/   \n");
    System.out.println("https://github.com/piotrpolak/android-http-server");
    System.out.println("");
    final ControllerImpl controllerImpl = new ControllerImpl(getServerConfigFactory(),
            ServerSocketFactory.getDefault(),
            gui);
    controllerImpl.start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            controllerImpl.stop();
        }
    });
}
 
Example 5
Source File: NetworkServerControlImpl.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Create the right kind of server socket
 */

private ServerSocket createServerSocket()
	throws IOException
{
	if (hostAddress == null)
		hostAddress = InetAddress.getByName(hostArg);
	// Make a list of valid
	// InetAddresses for NetworkServerControl
	// admin commands.
	buildLocalAddressList(hostAddress);
										
	// Create the right kind of socket
	switch (getSSLMode()) {
	case SSL_OFF:
	default:
		ServerSocketFactory sf =
			ServerSocketFactory.getDefault();
		return sf.createServerSocket(portNumber
									 ,0,
									 hostAddress);
	case SSL_BASIC:
		SSLServerSocketFactory ssf =
			(SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
		return (SSLServerSocket)ssf.createServerSocket(portNumber,
													   0,
													   hostAddress);
	case SSL_PEER_AUTHENTICATION:
		SSLServerSocketFactory ssf2 =
			(SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
		SSLServerSocket sss2= 
			(SSLServerSocket)ssf2.createServerSocket(portNumber,
													 0,
													 hostAddress);
		sss2.setNeedClientAuth(true);
		return sss2;
	}
}
 
Example 6
Source File: ServerSap.java    From iec61850bean with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a server socket waiting on the configured port for incoming association requests.
 *
 * @param serverEventListener the listener that is notified of incoming writes and when the server
 *     stopped listening for new connections.
 * @throws IOException if an error occurs binding to the port.
 */
public void startListening(ServerEventListener serverEventListener) throws IOException {
  timer = new Timer();
  if (serverSocketFactory == null) {
    serverSocketFactory = ServerSocketFactory.getDefault();
  }
  acseSap =
      new ServerAcseSap(port, backlog, bindAddr, new AcseListener(this), serverSocketFactory);
  acseSap.serverTSap.setMaxConnections(maxAssociations);
  this.serverEventListener = serverEventListener;
  listening = true;
  acseSap.startListening();
}
 
Example 7
Source File: InputSocket.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void start() throws Exception {
  logger.info("Starting socket server (port: {}, protocol: {}, secure: {})", port, protocol, secure);
  ServerSocketFactory socketFactory = secure ? SSLServerSocketFactory.getDefault() : ServerSocketFactory.getDefault();
  InputSocketMarker inputSocketMarker = new InputSocketMarker(this, port, protocol, secure, log4j);
  LogsearchConversion loggerConverter = new LogsearchConversion();

  try {
    serverSocket = socketFactory.createServerSocket(port);
    while (!isDrain()) {
      Socket socket = serverSocket.accept();
      if (log4j) {
        try (ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()))) {
          LoggingEvent loggingEvent = (LoggingEvent) ois.readObject();
          String jsonStr = loggerConverter.createOutput(loggingEvent);
          logger.trace("Incoming socket logging event: " + jsonStr);
          outputLine(jsonStr, inputSocketMarker);
        }
      } else {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));) {
          String line = in.readLine();
          logger.trace("Incoming socket message: " + line);
          outputLine(line, inputSocketMarker);
        }
      }
    }
  } catch (SocketException socketEx) {
    logger.warn("{}", socketEx.getMessage());
  } finally {
    serverSocket.close();
  }
}
 
Example 8
Source File: RandomPortSupplier.java    From embedded-rabbitmq with Apache License 2.0 4 votes vote down vote up
public RandomPortSupplier() {
  this(ServerSocketFactory.getDefault());
}
 
Example 9
Source File: BlobServer.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
/**
 * Instantiates a new BLOB server and binds it to a free network port.
 *
 * @param config Configuration to be used to instantiate the BlobServer
 * @param blobStore BlobStore to store blobs persistently
 *
 * @throws IOException
 * 		thrown if the BLOB server cannot bind to a free network port or if the
 * 		(local or distributed) file storage cannot be created or is not usable
 */
public BlobServer(Configuration config, BlobStore blobStore) throws IOException {
	this.blobServiceConfiguration = checkNotNull(config);
	this.blobStore = checkNotNull(blobStore);
	this.readWriteLock = new ReentrantReadWriteLock();

	// configure and create the storage directory
	this.storageDir = BlobUtils.initLocalStorageDirectory(config);
	LOG.info("Created BLOB server storage directory {}", storageDir);

	// configure the maximum number of concurrent connections
	final int maxConnections = config.getInteger(BlobServerOptions.FETCH_CONCURRENT);
	if (maxConnections >= 1) {
		this.maxConnections = maxConnections;
	}
	else {
		LOG.warn("Invalid value for maximum connections in BLOB server: {}. Using default value of {}",
				maxConnections, BlobServerOptions.FETCH_CONCURRENT.defaultValue());
		this.maxConnections = BlobServerOptions.FETCH_CONCURRENT.defaultValue();
	}

	// configure the backlog of connections
	int backlog = config.getInteger(BlobServerOptions.FETCH_BACKLOG);
	if (backlog < 1) {
		LOG.warn("Invalid value for BLOB connection backlog: {}. Using default value of {}",
				backlog, BlobServerOptions.FETCH_BACKLOG.defaultValue());
		backlog = BlobServerOptions.FETCH_BACKLOG.defaultValue();
	}

	// Initializing the clean up task
	this.cleanupTimer = new Timer(true);

	this.cleanupInterval = config.getLong(BlobServerOptions.CLEANUP_INTERVAL) * 1000;
	this.cleanupTimer
		.schedule(new TransientBlobCleanupTask(blobExpiryTimes, readWriteLock.writeLock(),
			storageDir, LOG), cleanupInterval, cleanupInterval);

	this.shutdownHook = ShutdownHookUtil.addShutdownHook(this, getClass().getSimpleName(), LOG);

	//  ----------------------- start the server -------------------

	final String serverPortRange = config.getString(BlobServerOptions.PORT);
	final Iterator<Integer> ports = NetUtils.getPortRangeFromString(serverPortRange);

	final ServerSocketFactory socketFactory;
	if (SSLUtils.isInternalSSLEnabled(config) && config.getBoolean(BlobServerOptions.SSL_ENABLED)) {
		try {
			socketFactory = SSLUtils.createSSLServerSocketFactory(config);
		}
		catch (Exception e) {
			throw new IOException("Failed to initialize SSL for the blob server", e);
		}
	}
	else {
		socketFactory = ServerSocketFactory.getDefault();
	}

	final int finalBacklog = backlog;
	this.serverSocket = NetUtils.createSocketFromPorts(ports,
			(port) -> socketFactory.createServerSocket(port, finalBacklog));

	if (serverSocket == null) {
		throw new IOException("Unable to open BLOB Server in specified port range: " + serverPortRange);
	}

	// start the server thread
	setName("BLOB Server listener at " + getPort());
	setDaemon(true);

	if (LOG.isInfoEnabled()) {
		LOG.info("Started BLOB server at {}:{} - max concurrent requests: {} - max backlog: {}",
				serverSocket.getInetAddress().getHostAddress(), getPort(), maxConnections, backlog);
	}
}
 
Example 10
Source File: TCPNetSyslogServer.java    From syslog4j with GNU Lesser General Public License v2.1 4 votes vote down vote up
protected ServerSocketFactory getServerSocketFactory() throws IOException {
	ServerSocketFactory serverSocketFactory = ServerSocketFactory.getDefault();
	
	return serverSocketFactory;
}
 
Example 11
Source File: AbstractServer.java    From davmail with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Bind server socket on defined port.
 *
 * @throws DavMailException unable to create server socket
 */
public void bind() throws DavMailException {
    String bindAddress = Settings.getProperty("davmail.bindAddress");
    String keystoreFile = Settings.getProperty("davmail.ssl.keystoreFile");

    ServerSocketFactory serverSocketFactory;
    if (keystoreFile == null || keystoreFile.length() == 0 || nosslFlag) {
        serverSocketFactory = ServerSocketFactory.getDefault();
    } else {
        try {

            // SSLContext is environment for implementing JSSE...
            // create ServerSocketFactory
            SSLContext sslContext = SSLContext.getInstance("TLS");

            // initialize sslContext to work with key managers
            sslContext.init(getKeyManagers(), getTrustManagers(), null);

            // create ServerSocketFactory from sslContext
            serverSocketFactory = sslContext.getServerSocketFactory();
        } catch (IOException | GeneralSecurityException ex) {
            throw new DavMailException("LOG_EXCEPTION_CREATING_SSL_SERVER_SOCKET", getProtocolName(), port, ex.getMessage() == null ? ex.toString() : ex.getMessage());
        }
    }
    try {
        // create the server socket
        if (bindAddress == null || bindAddress.length() == 0) {
            serverSocket = serverSocketFactory.createServerSocket(port);
        } else {
            serverSocket = serverSocketFactory.createServerSocket(port, 0, Inet4Address.getByName(bindAddress));
        }
        if (serverSocket instanceof SSLServerSocket) {
            // CVE-2014-3566 disable SSLv3
            HashSet<String> protocols = new HashSet<>();
            for (String protocol : ((SSLServerSocket) serverSocket).getEnabledProtocols()) {
                if (!protocol.startsWith("SSL")) {
                    protocols.add(protocol);
                }
            }
            ((SSLServerSocket) serverSocket).setEnabledProtocols(protocols.toArray(new String[0]));
            ((SSLServerSocket) serverSocket).setNeedClientAuth(Settings.getBooleanProperty("davmail.ssl.needClientAuth", false));
        }

    } catch (IOException e) {
        throw new DavMailException("LOG_SOCKET_BIND_FAILED", getProtocolName(), port);
    }
}
 
Example 12
Source File: TcpTransportFactory.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
protected ServerSocketFactory createServerSocketFactory() throws IOException {
   return ServerSocketFactory.getDefault();
}
 
Example 13
Source File: ServerSocketFactoryTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public final void test_createServerSocket() throws Exception {
    ServerSocketFactory sf = ServerSocketFactory.getDefault();
    ServerSocket ss = sf.createServerSocket();
    assertNotNull(ss);
    ss.close();
}
 
Example 14
Source File: BlobServer.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * Instantiates a new BLOB server and binds it to a free network port.
 *
 * @param config Configuration to be used to instantiate the BlobServer
 * @param blobStore BlobStore to store blobs persistently
 *
 * @throws IOException
 * 		thrown if the BLOB server cannot bind to a free network port or if the
 * 		(local or distributed) file storage cannot be created or is not usable
 */
public BlobServer(Configuration config, BlobStore blobStore) throws IOException {
	this.blobServiceConfiguration = checkNotNull(config);
	this.blobStore = checkNotNull(blobStore);
	this.readWriteLock = new ReentrantReadWriteLock();

	// configure and create the storage directory
	this.storageDir = BlobUtils.initLocalStorageDirectory(config);
	LOG.info("Created BLOB server storage directory {}", storageDir);

	// configure the maximum number of concurrent connections
	final int maxConnections = config.getInteger(BlobServerOptions.FETCH_CONCURRENT);
	if (maxConnections >= 1) {
		this.maxConnections = maxConnections;
	}
	else {
		LOG.warn("Invalid value for maximum connections in BLOB server: {}. Using default value of {}",
				maxConnections, BlobServerOptions.FETCH_CONCURRENT.defaultValue());
		this.maxConnections = BlobServerOptions.FETCH_CONCURRENT.defaultValue();
	}

	// configure the backlog of connections
	int backlog = config.getInteger(BlobServerOptions.FETCH_BACKLOG);
	if (backlog < 1) {
		LOG.warn("Invalid value for BLOB connection backlog: {}. Using default value of {}",
				backlog, BlobServerOptions.FETCH_BACKLOG.defaultValue());
		backlog = BlobServerOptions.FETCH_BACKLOG.defaultValue();
	}

	// Initializing the clean up task
	this.cleanupTimer = new Timer(true);

	this.cleanupInterval = config.getLong(BlobServerOptions.CLEANUP_INTERVAL) * 1000;
	this.cleanupTimer
		.schedule(new TransientBlobCleanupTask(blobExpiryTimes, readWriteLock.writeLock(),
			storageDir, LOG), cleanupInterval, cleanupInterval);

	this.shutdownHook = ShutdownHookUtil.addShutdownHook(this, getClass().getSimpleName(), LOG);

	//  ----------------------- start the server -------------------

	final String serverPortRange = config.getString(BlobServerOptions.PORT);
	final Iterator<Integer> ports = NetUtils.getPortRangeFromString(serverPortRange);

	final ServerSocketFactory socketFactory;
	if (SSLUtils.isInternalSSLEnabled(config) && config.getBoolean(BlobServerOptions.SSL_ENABLED)) {
		try {
			socketFactory = SSLUtils.createSSLServerSocketFactory(config);
		}
		catch (Exception e) {
			throw new IOException("Failed to initialize SSL for the blob server", e);
		}
	}
	else {
		socketFactory = ServerSocketFactory.getDefault();
	}

	final int finalBacklog = backlog;
	this.serverSocket = NetUtils.createSocketFromPorts(ports,
			(port) -> socketFactory.createServerSocket(port, finalBacklog));

	if (serverSocket == null) {
		throw new IOException("Unable to open BLOB Server in specified port range: " + serverPortRange);
	}

	// start the server thread
	setName("BLOB Server listener at " + getPort());
	setDaemon(true);

	if (LOG.isInfoEnabled()) {
		LOG.info("Started BLOB server at {}:{} - max concurrent requests: {} - max backlog: {}",
				serverSocket.getInetAddress().getHostAddress(), getPort(), maxConnections, backlog);
	}
}
 
Example 15
Source File: ServerTSap.java    From iec61850bean with Apache License 2.0 2 votes vote down vote up
/**
 * Use this constructor to create a server TSAP that can listen on a port.
 *
 * @param port the TCP port that the ServerSocket will connect to. Should be between 1 and 65535.
 * @param conListener the ConnectionListener that will be notified when remote TSAPs are
 *     connecting or the server stopped listening.
 * @param backlog is passed to the java.net.ServerSocket
 * @param bindAddr the IP address to bind to. It is passed to java.net.ServerSocket
 */
public ServerTSap(int port, int backlog, InetAddress bindAddr, TConnectionListener conListener) {
  this(port, backlog, bindAddr, conListener, ServerSocketFactory.getDefault());
}
 
Example 16
Source File: ServerTSap.java    From iec61850bean with Apache License 2.0 2 votes vote down vote up
/**
 * Use this constructor to create a server TSAP that can listen on a port.
 *
 * @param port the TCP port that the ServerSocket will connect to. Should be between 1 and 65535.
 * @param conListener the ConnectionListener that will be notified when remote TSAPs are
 *     connecting or the server stopped listening.
 */
public ServerTSap(int port, TConnectionListener conListener) {
  this(port, 0, null, conListener, ServerSocketFactory.getDefault());
}
 
Example 17
Source File: JsonLogServer.java    From wildfly-core with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * Creates a new TCP listening log server.
 *
 * @param port the port to listen on
 *
 * @return the log server
 */
public static JsonLogServer createTcpServer(final int port) {
    return new TcpServer(ServerSocketFactory.getDefault(), port);
}
 
Example 18
Source File: SocketServerRpcConnectionFactory.java    From protobuf-socket-rpc with MIT License 2 votes vote down vote up
/**
 * @param port Port that this server socket will be started on.
 * @param backlog the maximum length of the queue. A value <=0 uses default
 *        backlog.
 * @param bindAddr the local InetAddress the server socket will bind to. A
 *        null value binds to any/all local IP addresses.
 * @param delimited Use delimited communication mode.
 */
public SocketServerRpcConnectionFactory(int port, int backlog,
    InetAddress bindAddr, boolean delimited) {
  this(port, backlog, bindAddr, delimited, ServerSocketFactory.getDefault());
}
 
Example 19
Source File: TelnetTerminalServer.java    From lanterna with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Creates a new TelnetTerminalServer on a specific port
 * @param port Port to listen for incoming telnet connections
 * @throws IOException If there was an underlying I/O exception
 */
public TelnetTerminalServer(int port) throws IOException {
    this(ServerSocketFactory.getDefault(), port);
}
 
Example 20
Source File: TelnetTerminalServer.java    From lanterna with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Creates a new TelnetTerminalServer on a specific port, using a certain character set
 * @param port Port to listen for incoming telnet connections
 * @param charset Character set to use
 * @throws IOException If there was an underlying I/O exception
 */
public TelnetTerminalServer(int port, Charset charset) throws IOException {
    this(ServerSocketFactory.getDefault(), port, charset);
}