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, int backlog) throws IOException 

Source Link

Document

Creates a server socket and binds it to the specified local port number, with the specified backlog.

Usage

From source file:org.fourthline.cling.android.alternate.AndroidUpnpServiceConfiguration.java

@Override
public StreamServer createStreamServer(NetworkAddressFactory networkAddressFactory) {

    return new StreamServerImpl(new StreamServerConfigurationImpl(networkAddressFactory.getStreamListenPort()) {
        @Override//ww  w  .j a  va2 s.  co m
        public boolean isStaleConnectionCheck() {
            return true;
        }

        @Override
        public boolean isTcpNoDelay() {
            return false;
        }
    }) {

        @Override
        synchronized public void init(InetAddress bindAddress, Router router) throws InitializationException {

            try {

                this.router = router;

                // don't bind to passed bindAddress to avoid reverse DNS lookup
                this.serverSocket = new ServerSocket(configuration.getListenPort(),
                        configuration.getTcpConnectionBacklog());

                log.info("Created socket (for receiving TCP streams) on: "
                        + serverSocket.getLocalSocketAddress());

                this.globalParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
                        configuration.getDataWaitTimeoutSeconds() * 1000);
                this.globalParams.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE,
                        configuration.getBufferSizeKilobytes() * 1024);
                this.globalParams.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK,
                        configuration.isStaleConnectionCheck());
                this.globalParams.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY,
                        configuration.isTcpNoDelay());
                ;

            } catch (Exception ex) {
                throw new InitializationException(
                        "Could not initialize " + getClass().getSimpleName() + ": " + ex.toString(), ex);
            }

        }

    };
}

From source file:org.apache.flink.runtime.blob.BlobServer.java

private BlobServer(Configuration config, BlobStore blobStore) throws IOException {
    checkNotNull(config);//from   ww w . j  a v  a  2 s  .  c om
    this.blobStore = checkNotNull(blobStore);

    this.blobServiceConfiguration = config;

    // configure and create the storage directory
    String storageDirectory = config.getString(ConfigConstants.BLOB_STORAGE_DIRECTORY_KEY, null);
    this.storageDir = BlobUtils.initStorageDirectory(storageDirectory);
    LOG.info("Created BLOB server storage directory {}", storageDir);

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

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

    this.shutdownHook = BlobUtils.addShutdownHook(this, LOG);

    if (config.getBoolean(ConfigConstants.BLOB_SERVICE_SSL_ENABLED,
            ConfigConstants.DEFAULT_BLOB_SERVICE_SSL_ENABLED)) {
        try {
            serverSSLContext = SSLUtils.createSSLServerContext(config);
        } catch (Exception e) {
            throw new IOException("Failed to initialize SSLContext for the blob server", e);
        }
    }

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

    String serverPortRange = config.getString(ConfigConstants.BLOB_SERVER_PORT,
            ConfigConstants.DEFAULT_BLOB_SERVER_PORT);

    Iterator<Integer> ports = NetUtils.getPortRangeFromString(serverPortRange);

    final int finalBacklog = backlog;
    ServerSocket socketAttempt = NetUtils.createSocketFromPorts(ports, new NetUtils.SocketFactory() {
        @Override
        public ServerSocket createSocket(int port) throws IOException {
            if (serverSSLContext == null) {
                return new ServerSocket(port, finalBacklog);
            } else {
                LOG.info("Enabling ssl for the blob server");
                return serverSSLContext.getServerSocketFactory().createServerSocket(port, finalBacklog);
            }
        }
    });

    if (socketAttempt == null) {
        throw new IOException(
                "Unable to allocate socket for blob server in specified port range: " + serverPortRange);
    } else {
        this.serverSocket = socketAttempt;
    }

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

    if (LOG.isInfoEnabled()) {
        LOG.info("Started BLOB server at {}:{} - max concurrent requests: {} - max backlog: {}",
                serverSocket.getInetAddress().getHostAddress(), getPort(), maxConnections, backlog);
    }
}

From source file:com.mirth.connect.connectors.mllp.MllpMessageReceiver.java

protected ServerSocket createServerSocket(URI uri) throws IOException {
    String host = uri.getHost();//from  w  w w  . j  a v a  2s  .co m
    int backlog = connector.getBacklog();
    if (host == null || host.length() == 0) {
        host = "localhost";
    }
    InetAddress inetAddress = InetAddress.getByName(host);
    if (inetAddress.equals(InetAddress.getLocalHost()) || inetAddress.isLoopbackAddress()
            || host.trim().equals("localhost")) {
        return new ServerSocket(uri.getPort(), backlog);
    } else {
        return new ServerSocket(uri.getPort(), backlog, inetAddress);
    }
}

From source file:net.jradius.server.TCPListener.java

public void setConfiguration(ListenerConfigurationItem cfg, boolean noKeepAlive)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException,
        KeyManagementException, IOException {
    keepAlive = !noKeepAlive;/*from  www  .java2 s  . com*/
    config = cfg;

    Map props = config.getProperties();

    String s = (String) props.get("port");
    if (s != null)
        port = new Integer(s).intValue();

    s = (String) props.get("backlog");
    if (s != null)
        backlog = new Integer(s).intValue();

    if (keepAlive) {
        s = (String) props.get("keepAlive");
        if (s != null)
            keepAlive = new Boolean(s).booleanValue();
    }

    String useSSL = (String) props.get("useSSL");
    String trustAll = (String) props.get("trustAll");

    if (requiresSSL || "true".equalsIgnoreCase(useSSL)) {
        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;

        String keyManager = (String) props.get("keyManager");

        if (keyManager != null && keyManager.length() > 0) {
            try {
                KeyManager manager = (KeyManager) Configuration.getBean(keyManager);
                keyManagers = new KeyManager[] { manager };
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            String keystore = (String) props.get("keyStore");
            String keystoreType = (String) props.get("keyStoreType");
            String keystorePassword = (String) props.get("keyStorePassword");
            String keyPassword = (String) props.get("keyPassword");

            if (keystore != null) {
                if (keystoreType == null)
                    keystoreType = "pkcs12";

                KeyStore ks = KeyStore.getInstance(keystoreType);
                ks.load(new FileInputStream(keystore),
                        keystorePassword == null ? null : keystorePassword.toCharArray());

                KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
                kmf.init(ks, keyPassword == null ? null : keyPassword.toCharArray());
                keyManagers = kmf.getKeyManagers();
            }
        }

        String trustManager = (String) props.get("trustManager");

        if (trustManager != null && trustManager.length() > 0) {
            try {
                TrustManager manager = (TrustManager) Configuration.getBean(trustManager);
                trustManagers = new TrustManager[] { manager };
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("true".equalsIgnoreCase(trustAll)) {
            trustManagers = new TrustManager[] { new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType) {

                }

                public void checkServerTrusted(X509Certificate[] chain, String authType) {

                }

                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            } };
        } else {
            String keystore = (String) props.get("caStore");
            String keystoreType = (String) props.get("caStoreType");
            String keystorePassword = (String) props.get("caStorePassword");

            if (keystore != null) {
                if (keystoreType == null)
                    keystoreType = "pkcs12";

                KeyStore caKeys = KeyStore.getInstance(keystoreType);
                caKeys.load(new FileInputStream(keystore),
                        keystorePassword == null ? null : keystorePassword.toCharArray());
                TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
                tmf.init(caKeys);
                trustManagers = tmf.getTrustManagers();
            }
        }

        SSLContext sslContext = SSLContext.getInstance("SSLv3");
        sslContext.init(keyManagers, trustManagers, null);

        ServerSocketFactory socketFactory = sslContext.getServerSocketFactory();
        SSLServerSocket sslServerSocket = (SSLServerSocket) socketFactory.createServerSocket(port, backlog);
        serverSocket = sslServerSocket;

        if (sslWantClientAuth)
            sslServerSocket.setWantClientAuth(true);

        if (sslNeedClientAuth)
            sslServerSocket.setNeedClientAuth(true);

        if (sslEnabledProtocols != null)
            sslServerSocket.setEnabledProtocols(sslEnabledProtocols);

        if (sslEnabledCiphers != null)
            sslServerSocket.setEnabledCipherSuites(sslEnabledCiphers);

        usingSSL = true;
    } else {
        serverSocket = new ServerSocket(port, backlog);
    }

    serverSocket.setReuseAddress(true);
    setActive(true);
}

From source file:org.adblockplus.android.ProxyService.java

@SuppressLint("NewApi")
@Override//from ww  w .  j a va  2 s  .  c o  m
public void onCreate() {
    super.onCreate();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
        // Proxy is running in separate thread, it's just some resolution request during initialization.
        // Not worth spawning a separate thread for this.
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
        StrictMode.setThreadPolicy(policy);
    }

    // Get port for local proxy
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    Resources resources = getResources();

    // Try to read user proxy settings
    String proxyHost = null;
    String proxyPort = null;
    String proxyExcl = null;
    String proxyUser = null;
    String proxyPass = null;

    if (NATIVE_PROXY_SUPPORTED) {
        // Read system settings
        proxyHost = System.getProperty("http.proxyHost");
        proxyPort = System.getProperty("http.proxyPort");
        proxyExcl = System.getProperty("http.nonProxyHosts");

        Log.d(TAG, "PRX: " + proxyHost + ":" + proxyPort + "(" + proxyExcl + ")");
        // not used but left for future reference
        String[] px = ProxySettings.getUserProxy(getApplicationContext());
        if (px != null)
            Log.d(TAG, "PRX: " + px[0] + ":" + px[1] + "(" + px[2] + ")");
    } else {
        // Read application settings
        proxyHost = prefs.getString(getString(R.string.pref_proxyhost), null);
        proxyPort = prefs.getString(getString(R.string.pref_proxyport), null);
        proxyUser = prefs.getString(getString(R.string.pref_proxyuser), null);
        proxyPass = prefs.getString(getString(R.string.pref_proxypass), null);
    }

    // Check for root privileges and try to install transparent proxy
    if (RootTools.isAccessGiven()) {
        try {
            initIptables();

            StringBuffer cmd = new StringBuffer();
            int uid = getPackageManager().getPackageInfo(getPackageName(), 0).applicationInfo.uid;
            cmd.append(iptables);
            cmd.append(IPTABLES_RETURN.replace("{{UID}}", String.valueOf(uid)));
            String rules = cmd.toString();
            RootTools.sendShell(rules, DEFAULT_TIMEOUT);
            transparent = true;
        } catch (FileNotFoundException e) {
            // ignore - this is "normal" case
        } catch (NameNotFoundException e) {
            Log.e(TAG, "Failed to initialize iptables", e);
        } catch (IOException e) {
            Log.e(TAG, "Failed to initialize iptables", e);
        } catch (RootToolsException e) {
            Log.e(TAG, "Failed to initialize iptables", e);
        } catch (TimeoutException e) {
            Log.e(TAG, "Failed to initialize iptables", e);
        }
    }

    if (!transparent) {
        // Try to set native proxy
        nativeProxyAutoConfigured = ProxySettings.setConnectionProxy(getApplicationContext(), LOCALHOST, port,
                "");

        if (NATIVE_PROXY_SUPPORTED) {
            registerReceiver(connectionReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
            registerReceiver(connectionReceiver, new IntentFilter(Proxy.PROXY_CHANGE_ACTION));
        }
    }

    // Save current native proxy situation. The service is always started on the first run so
    // we will always have a correct value from the box
    SharedPreferences.Editor editor = prefs.edit();
    editor.putBoolean(getString(R.string.pref_proxyautoconfigured), transparent || nativeProxyAutoConfigured);
    editor.commit();

    registerReceiver(proxyReceiver, new IntentFilter(ProxyService.BROADCAST_PROXY_FAILED));
    registerReceiver(filterReceiver, new IntentFilter(AdblockPlus.BROADCAST_FILTERING_CHANGE));
    registerReceiver(filterReceiver, new IntentFilter(AdblockPlus.BROADCAST_FILTER_MATCHES));

    // Start proxy
    if (proxy == null) {
        // Select available port and bind to it, use previously selected port by default
        portVariants[0] = prefs.getInt(getString(R.string.pref_lastport), -1);
        ServerSocket listen = null;
        String msg = null;
        for (int p : portVariants) {
            if (p < 0)
                continue;
            try {
                listen = new ServerSocket(p, 1024);
                port = p;
                break;
            } catch (IOException e) {
                Log.e(TAG, null, e);
                msg = e.getMessage();
            }
        }
        if (listen == null) {
            sendBroadcast(new Intent(BROADCAST_PROXY_FAILED).putExtra("msg", msg));
            return;
        }

        // Save selected port
        editor.putInt(getString(R.string.pref_lastport), port);
        editor.commit();

        // Initialize proxy
        proxyConfiguration.put("handler", "main");
        proxyConfiguration.put("main.prefix", "");
        proxyConfiguration.put("main.class", "sunlabs.brazil.server.ChainHandler");
        if (transparent) {
            proxyConfiguration.put("main.handlers", "urlmodifier adblock");
            proxyConfiguration.put("urlmodifier.class", "org.adblockplus.brazil.TransparentProxyHandler");
        } else {
            proxyConfiguration.put("main.handlers", "https adblock");
            proxyConfiguration.put("https.class", "org.adblockplus.brazil.SSLConnectionHandler");
        }
        proxyConfiguration.put("adblock.class", "org.adblockplus.brazil.RequestHandler");
        if (logRequests)
            proxyConfiguration.put("adblock.proxylog", "yes");

        configureUserProxy(proxyConfiguration, proxyHost, proxyPort, proxyExcl, proxyUser, proxyPass);

        proxy = new ProxyServer();
        proxy.logLevel = Server.LOG_DIAGNOSTIC;
        proxy.setup(listen, proxyConfiguration.getProperty("handler"), proxyConfiguration);
        proxy.start();
    }

    if (transparent) {
        // Redirect traffic via iptables
        try {
            StringBuffer cmd = new StringBuffer();
            cmd.append(iptables);
            cmd.append(IPTABLES_ADD_HTTP.replace("{{PORT}}", String.valueOf(port)));
            String rules = cmd.toString();
            RootTools.sendShell(rules, DEFAULT_TIMEOUT);
        } catch (FileNotFoundException e) {
            // ignore - this is "normal" case
        } catch (IOException e) {
            Log.e(TAG, "Failed to initialize iptables", e);
        } catch (RootToolsException e) {
            Log.e(TAG, "Failed to initialize iptables", e);
        } catch (TimeoutException e) {
            Log.e(TAG, "Failed to initialize iptables", e);
        }
    }

    prefs.registerOnSharedPreferenceChangeListener(this);

    // Lock service
    hideIcon = prefs.getBoolean(getString(R.string.pref_hideicon), resources.getBoolean(R.bool.def_hideicon));
    startForeground(ONGOING_NOTIFICATION_ID, getNotification());

    // If automatic setting of proxy was blocked, check if user has set it manually
    boolean manual = isManual();
    if (manual && NATIVE_PROXY_SUPPORTED) {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
                Context.CONNECTIVITY_SERVICE);
        updateNoTrafficCheck(connectivityManager);
    }

    sendStateChangedBroadcast();
    Log.i(TAG, "Service started");
}

From source file:net.lightbody.bmp.proxy.jetty.util.ThreadedServer.java

/**
 * New server socket. Creates a new servers socket. May be overriden by derived class to create
 * specialist serversockets (eg SSL)./*from  ww  w.j a  v  a 2s . c om*/
 * 
 * @param address Address and port
 * @param acceptQueueSize Accept queue size
 * @return The new ServerSocket
 * @exception java.io.IOException
 */
protected ServerSocket newServerSocket(InetAddrPort address, int acceptQueueSize) throws java.io.IOException {
    if (address == null)
        return new ServerSocket(0, acceptQueueSize);

    return new ServerSocket(address.getPort(), acceptQueueSize, address.getInetAddress());
}

From source file:hudson.remoting.Launcher.java

/**
 * Listens on an ephemeral port, record that port number in a port file,
 * then accepts one TCP connection./*from  w w w  . jav  a  2  s .  c  om*/
 */
private void runAsTcpServer() throws IOException, InterruptedException {
    // if no one connects for too long, assume something went wrong
    // and avoid hanging foreever
    ServerSocket ss = new ServerSocket(0, 1);
    ss.setSoTimeout(30 * 1000);

    // write a port file to report the port number
    FileWriter w = new FileWriter(tcpPortFile);
    w.write(String.valueOf(ss.getLocalPort()));
    w.close();

    // accept just one connection and that's it.
    // when we are done, remove the port file to avoid stale port file
    Socket s;
    try {
        s = ss.accept();
        ss.close();
    } finally {
        tcpPortFile.delete();
    }

    runOnSocket(s);
}

From source file:com.sun.grizzly.http.jk.common.ChannelSocket.java

/**
 * jmx:managed-operation/* w w w . j  a va2  s .c om*/
 */
public void init() throws IOException {
    // Find a port.
    if (startPort == 0) {
        port = 0;

        LoggerUtils.getLogger().info("JK: ajp13 disabling channelSocket");
        running = true;
        return;
    }
    if (maxPort < startPort) {
        maxPort = startPort;
    }
    for (int i = startPort; i <= maxPort; i++) {
        try {
            if (inet == null) {
                sSocket = new ServerSocket(i, 0);
            } else {
                sSocket = new ServerSocket(i, 0, inet);
            }
            port = i;
            break;
        } catch (IOException ex) {

            LoggerUtils.getLogger().info("Port busy " + i + " " + ex.toString());
            continue;
        }
    }

    if (sSocket == null) {
        LoggerUtils.getLogger().log(Level.SEVERE, "Can't find free port " + startPort + " " + maxPort);
        return;
    }

    LoggerUtils.getLogger().info("JK: ajp13 listening on " + getAddress() + ":" + port);

    // If this is not the base port and we are the 'main' channleSocket and
    // SHM didn't already set the localId - we'll set the instance id
    if ("channelSocket".equals(name) && port != startPort && (wEnv.getLocalId() == 0)) {
        wEnv.setLocalId(port - startPort);
    }
    if (serverTimeout > 0) {
        sSocket.setSoTimeout(serverTimeout);
    }

    // XXX Reverse it -> this is a notification generator !!
    if (next == null && wEnv != null) {
        if (nextName != null) {
            setNext(wEnv.getHandler(nextName));
        }
        if (next == null) {
            next = wEnv.getHandler("dispatch");
        }
        if (next == null) {
            next = wEnv.getHandler("request");
        }
    }
    JMXRequestNote = wEnv.getNoteId(WorkerEnv.ENDPOINT_NOTE, "requestNote");
    running = true;

    // Run a thread that will accept connections.
    // XXX Try to find a thread first - not sure how...
    if (this.domain != null) {
        try {
            tpOName = new ObjectName(domain + ":type=ThreadPool,name=" + getChannelName());

            Registry.getRegistry(null, null).registerComponent(tp, tpOName, null);

            rgOName = new ObjectName(domain + ":type=GlobalRequestProcessor,name=" + getChannelName());
            Registry.getRegistry(null, null).registerComponent(global, rgOName, null);
        } catch (Exception e) {
            LoggerUtils.getLogger().log(Level.SEVERE, "Can't register threadpool");
        }
    }

    tp.start();
    SocketAcceptor acceptAjp = new SocketAcceptor(this);
    tp.runIt(acceptAjp);

}

From source file:nl.nn.adapterframework.http.AuthSSLProtocolSocketFactoryBase.java

public ServerSocket createServerSocket(int port, int backlog) throws IOException {
    return new ServerSocket(port, backlog);
}

From source file:com.sshtools.appframework.ui.SshToolsApplication.java

public void init(String[] args) throws SshToolsApplicationException {
    instance = this;

    boolean listen = isReuseCapable();

    // Do parse 1 of the command line arguments - see if we need to start
    // the daemon
    Options options1 = new Options();
    SshToolsApplication.this.buildCLIOptions(options1);

    pluginManager = new PluginManager();
    try {/*from w  w w .j  a  v a 2  s .  c  o m*/
        initPluginManager(options1);
    } catch (PluginException e1) {
        log(PluginHostContext.LOG_ERROR, "Failed to initialise plugin manager.", e1);
    }

    CommandLineParser parser1 = new PosixParser();
    CommandLine commandLine1;

    try {
        // parse the command line arguments
        commandLine1 = parser1.parse(options1, args);
        if (commandLine1.hasOption("d")) {
            listen = false;
        }

        if (commandLine1.hasOption('r')) {
            reusePort = Integer.parseInt(commandLine1.getOptionValue('r'));
        }
    } catch (Exception e) {
        // Don't care at the moment
    }

    // Try and message the reuse daemon if possible - saves starting another
    // instance
    if (listen) {
        Socket s = null;
        try {
            String hostname = "localhost";
            if (reusePort == -1) {
                reusePort = getDefaultReusePort();
            }
            log.debug("Attempting connection to reuse server on " + hostname + ":" + reusePort);
            s = new Socket(hostname, reusePort);
            log.debug("Found reuse server on " + hostname + ":" + reusePort + ", sending arguments");
            s.setSoTimeout(5000);
            PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
            for (int i = 0; args != null && i < args.length; i++) {
                pw.println(args[i]);
            }
            pw.println();
            BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));
            log.debug("Waiting for reuse server reply");
            String error = r.readLine();
            log.debug("Reuse server replied with '" + error + "'");
            if (error != null && !error.equals("")) {
                throw new SshToolsApplicationException(error);
            }
            System.exit(0);
        } catch (SshToolsApplicationException t) {
            throw t;
        } catch (SocketException se) {
            log.debug("No reuse server found.");
        } catch (SocketTimeoutException se) {
            log.debug("Reuse server not responding.", se);
        } catch (Exception e) {
            throw new SshToolsApplicationException(e);
        } finally {
            if (s != null) {
                try {
                    s.close();
                } catch (IOException ioe) {
                }
            }
        }
    }

    additionalOptionsTabs = new ArrayList<OptionsTab>();
    log.info("Initialising application");
    File f = getApplicationPreferencesDirectory();
    if (f != null) {
        //
        FilePreferencesFactory.setPreferencesFile(new File(f, "javaprefs.properties"));
        PreferencesStore.init(new File(f, getApplicationName() + ".properties"));
    }
    setLookAndFeel(getDefaultLAF());

    log.debug("Plugin manager initialised, adding global preferences tabs");

    postInitialization();
    addAdditionalOptionsTab(new GlobalOptionsTab(this));

    Options options = new Options();
    buildCLIOptions(options);
    log.debug("Parsing command line");
    CommandLineParser parser = new PosixParser();
    try {
        // parse the command line arguments
        cli = parser.parse(options, args);
        if (cli.hasOption("?")) {
            printHelp(options);
            System.exit(0);
        }
    } catch (Exception e) {
        System.err.println("Invalid option: " + e.getMessage());
        printHelp(options);
        System.exit(1);
    }
    log.debug("Parsed command line");

    if (listen) {
        Thread t = new Thread("RemoteCommandLine") {
            @Override
            public void run() {
                Socket s = null;
                try {
                    reuseServerSocket = new ServerSocket(reusePort, 1);
                    while (true) {
                        s = reuseServerSocket.accept();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
                        String line = null;
                        List<String> args = new ArrayList<String>();
                        while ((line = reader.readLine()) != null && !line.equals("")) {
                            args.add(line);
                        }
                        final PrintWriter pw = new PrintWriter(s.getOutputStream());
                        String[] a = new String[args.size()];
                        args.toArray(a);
                        CommandLineParser parser = new PosixParser();
                        Options options = new Options();
                        buildCLIOptions(options);
                        // parse the command line arguments
                        final CommandLine remoteCLI = parser.parse(options, a);
                        pw.println("");
                        SwingUtilities.invokeAndWait(new Runnable() {
                            public void run() {
                                try {
                                    reuseRequest(remoteCLI);
                                } catch (Throwable t) {
                                    pw.println(t.getMessage());
                                }
                            }
                        });
                        s.close();
                        s = null;
                    }
                } catch (Exception e) {
                    /* DEBUG */e.printStackTrace();
                } finally {
                    if (s != null) {
                        try {
                            s.close();
                        } catch (IOException ioe) {

                        }
                    }
                }
            }
        };
        t.setDaemon(true);
        t.start();
    }
}