private void startService() { try { mailService = new MailService(new FuncTestLoggerImpl()); mailService.configureAndStartGreenMail(JIRAServerSetup.SMTP_POP3); mailService.addUser(DEFAULT_EMAIL_ADDRESS, DEFAULT_USERNAME, DEFAULT_PASSWORD); syncUI(); System.out.println("Mail Service Started."); } catch (BindException ex) { JOptionPane.showMessageDialog(null, ex.getMessage()); } }
/** Sets the local IP address into the variable <i>localIpAddress</i> */ public static void setLocalIpAddress() { localIpAddress = "127.0.0.1"; try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { if (inetAddress.getHostAddress().toString().contains(":")) continue; if (!PreferenceManager.getDefaultSharedPreferences(getUIContext()) .getBoolean(Settings.PREF_STUN, Settings.DEFAULT_STUN)) { localIpAddress = inetAddress.getHostAddress().toString(); } else { try { String StunServer = PreferenceManager.getDefaultSharedPreferences(getUIContext()) .getString(Settings.PREF_STUN_SERVER, Settings.DEFAULT_STUN_SERVER); int StunServerPort = Integer.valueOf( PreferenceManager.getDefaultSharedPreferences(getUIContext()) .getString( Settings.PREF_STUN_SERVER_PORT, Settings.DEFAULT_STUN_SERVER_PORT)); DiscoveryTest StunDiscover = new DiscoveryTest(inetAddress, StunServer, StunServerPort); // call out to stun server StunDiscover.test(); // System.out.println("Public ip is:" + // StunDiscover.di.getPublicIP().getHostAddress()); localIpAddress = StunDiscover.di.getPublicIP().getHostAddress(); } catch (BindException be) { if (!Sipdroid.release) System.out.println(inetAddress.toString() + ": " + be.getMessage()); } catch (Exception e) { if (!Sipdroid.release) { System.out.println(e.getMessage()); e.printStackTrace(); } } } } } } } catch (Exception ex) { // do nothing } }
private ServerSocket getServerSocket() throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(port); } catch (BindException e) { if (e.getMessage().contains("Address already in use")) { port = port + 1; serverSocket = getServerSocket(); } else { throw e; } } return serverSocket; }
private static ServerSocket createServerSocketTry(int port, boolean ssl) { try { InetAddress bindAddress = getBindAddress(); if (ssl) { return CipherFactory.createServerSocket(port, bindAddress); } if (bindAddress == null) { return new ServerSocket(port); } return new ServerSocket(port, 0, bindAddress); } catch (BindException be) { throw DbException.get(ErrorCode.EXCEPTION_OPENING_PORT_2, be, "" + port, be.toString()); } catch (IOException e) { throw DbException.convertIOException(e, "port: " + port + " ssl: " + ssl); } }
/** Creates the SSL ServerSocket. */ public static QServerSocket create( InetAddress host, int port, int listenBacklog, boolean isEnableJni) throws IOException { if (isEnableJni) { try { // JNI doesn't listen immediately QServerSocket ss = createJNI(host, port); if (ss != null) return ss; } catch (IOException e) { log.log(Level.FINE, e.toString(), e); } catch (Throwable e) { log.log(Level.FINE, e.toString(), e); } } for (int i = 0; i < 10; i++) { try { ServerSocket ss = new ServerSocket(port, listenBacklog, host); return new QServerSocketWrapper(ss); } catch (BindException e) { } try { Thread.currentThread().sleep(1); } catch (Throwable e) { } } try { ServerSocket ss = new ServerSocket(port, listenBacklog, host); return new QServerSocketWrapper(ss); } catch (BindException e) { if (host != null) throw new BindException( L.l( "{0}\nCan't bind to {1}:{2}.\nCheck for another server listening to that port.", e.getMessage(), host, String.valueOf(port))); else throw new BindException( L.l( "{0}\nCan't bind to *:{1}.\nCheck for another server listening to that port.", e.getMessage(), String.valueOf(port))); } }
/** Starts the server, and waits for clients. */ public Server() { instance = this; System.out.println( "== SERVER v" + Constants.NETCODE_VERSION + " == started at IP address: " + getLocalIP()); clients = new LinkedList<ClientMachine>(); try { beginListening(Constants.DEFAULT_PORT); } catch (BindException e) { Main.fatalError( "Couldn't bind to port " + Constants.DEFAULT_PORT + ". Perhaps a server is already running?\n\n" + e.getLocalizedMessage()); } catch (SocketException ex) { ex.printStackTrace(); } }
/** * A convenience method to bind to a given address and report better exceptions if the address is * not a valid host. * * @param socket the socket to bind * @param address the address to bind to * @param backlog the number of connections allowed in the queue * @throws BindException if the address can't be bound * @throws UnknownHostException if the address isn't a valid host name * @throws IOException other random errors from bind */ public static void bind(ServerSocket socket, InetSocketAddress address, int backlog) throws IOException { try { socket.bind(address, backlog); } catch (BindException e) { BindException bindException = new BindException("Problem binding to " + address + " : " + e.getMessage()); bindException.initCause(e); throw bindException; } catch (SocketException e) { // If they try to bind to a different host's address, give a better // error message. if ("Unresolved address".equals(e.getMessage())) { throw new UnknownHostException("Invalid hostname for server: " + address.getHostName()); } else { throw e; } } }
private Lantern() { Guice.createInjector(new LanternGuiceModule(this)).getInstance(SpongeImpl.class); this.game = SpongeImpl.getGame(); try { RegistryHelper.setFinalStatic(Sponge.class, "game", this.game); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } preInit(); init(); try { SpongeImpl.getGame().setServer(new LanternServer()); } catch (BindException e) { SpongeImpl.getLogger().error("The server could not bind to the requested address."); if (e.getMessage().startsWith("Cannot assign requested address")) { SpongeImpl.getLogger().error("The 'server.ip' in your configuration may not be valid."); SpongeImpl.getLogger().error("Unless you are sure you need it, try removing it."); SpongeImpl.getLogger().error(e.toString()); } else if (e.getMessage().startsWith("Address already in use")) { SpongeImpl.getLogger().error("The address was already in use. Check that no server is"); SpongeImpl.getLogger().error("already running on that port. If needed, try killing all"); SpongeImpl.getLogger().error("Java processes using Task Manager or similar."); SpongeImpl.getLogger().error(e.toString()); } else { SpongeImpl.getLogger().error("An unknown bind error has occurred.", e); } System.exit(1); } catch (Throwable t) { // general server startup crash SpongeImpl.getLogger().error("Error during server startup.", t); System.exit(1); } }
public void initEndpoint() throws IOException, InstantiationException { try { if (factory == null) factory = ServerSocketFactory.getDefault(); if (serverSocket == null) { try { if (inet == null) { serverSocket = factory.createSocket(port, backlog); } else { serverSocket = factory.createSocket(port, backlog, inet); } } catch (BindException be) { throw new BindException(be.getMessage() + ":" + port); } } if (serverTimeout >= 0) serverSocket.setSoTimeout(serverTimeout); } catch (IOException ex) { // log("couldn't start endpoint", ex, Logger.DEBUG); throw ex; } catch (InstantiationException ex1) { // log("couldn't start endpoint", ex1, Logger.DEBUG); throw ex1; } initialized = true; }
public static void initialize(String MBeanArray[], String MBeanTypeArray[]) { try { setupTls(); logger.info(""); logger.info("############# MBean Server ##################"); logger.info("Create the MBean server..."); mbeanServer = MBeanServerFactory.createMBeanServer(); logger.info("Created !"); for (int i = 0; i < MBeanArray.length; i++) { ObjectName mbeanName = new ObjectName("MBeans:type=" + MBeanTypeArray[i]); logger.info(MBeanArray[i] + " MBean is created ..."); mbeanServer.createMBean( JMXServer.class.getPackage().getName() + ".beans." + MBeanArray[i], mbeanName, null, null); } logger.info(ResourceMapper.SECTION_DIVISON_KARE); logger.info(""); logger.info("######### JMXMP-TLS Connector Server ############"); logger.info(""); // Create a JMXMP-TLS connector server // logger.info("Create a JMXMP-TLS connector server... > "); // hardcoded ip : localhost port : 5555 int port = TlosSpaceWide.getSpaceWideRegistry() .getTlosSWConfigInfo() .getJmxParams() .getJmxTlsPort() .getPortNumber(); if (port <= 0) { port = 5555; } logger.info("Using port number : " + port); String ipAddress = TlosSpaceWide.getSpaceWideRegistry().getServerConfig().getServerParams().getIpAddress(); if (ipAddress == null || ipAddress.equals("")) { ipAddress = null; } logger.info("Using ip address : " + ipAddress); JMXServiceURL url = new JMXServiceURL("jmxmp", ipAddress, port); jConnectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbeanServer); logger.info("Created !"); // Start the JMXMP-TLS connector server // logger.info("Start the JMXMP-TLS connector server... > "); jConnectorServer.start(); logger.info("Started !"); logger.info("Waiting for incoming connections..."); logger.info("#############################################"); logger.info(""); String jmxUserName = "" + new Random(new Long(Calendar.getInstance().getTimeInMillis())).nextLong(); Thread.sleep(10); String jmxPassWord = "" + new Random(new Long(Calendar.getInstance().getTimeInMillis())).nextLong(); JmxUser jmxUser = new JmxUser(); jmxUser.setJmxClientAuthanticationId(jmxUserName); jmxUser.setJmxClientAuthanticationKey(jmxPassWord); TlosSpaceWide.getSpaceWideRegistry().setJmxUser(jmxUser); } catch (MalformedURLException mue) { logger.error("### MalformedURLException ###"); mue.printStackTrace(); try { jConnectorServer.stop(); } catch (IOException e) { e.printStackTrace(); } } catch (SecurityException e) { // System.out.println(" ### SecurityException ### "); logger.error("### SecurityException ###"); e.printStackTrace(); System.exit(-1); } catch (BindException e) { // System.out.println(" ### BindException ### "); logger.error("### BindException ###"); e.printStackTrace(); System.exit(-1); } catch (Exception e) { // System.out.println(" ### Unclassified Error ### "); logger.error("### Unclassified Error ###"); e.printStackTrace(); System.exit(-1); } }
protected void startServer() { if (server == null) { // stop excessive logging Log.setLog(null); System.setProperty("DEBUG", "false"); System.setProperty("VERBOSE", "false"); server = new Server(); } Connector connector = null; if (useSSL) { SslContextFactory contextFactory = new SslContextFactory(); contextFactory.setKeyStore(sslKeystore); contextFactory.setKeyStorePassword(sslPassword); contextFactory.setKeyManagerPassword(sslKeyPassword); contextFactory.setNeedClientAuth(needClientAuth); connector = new SslSelectChannelConnector(contextFactory); // Setup JSSE keystore and set parameters here correctly // connector = new SslSocketConnector(); // ((SslSocketConnector)connector).setKeystore(sslKeystore); // ((SslSocketConnector)connector).setPassword(sslPassword); // ((SslSocketConnector)connector).setKeyPassword(sslKeyPassword); // ((SslSocketConnector)connector).setNeedClientAuth(needClientAuth); // uses an entry in the keystore called "jetty" } else { // connector = new SocketConnector(); connector = new SelectChannelConnector(); } connector.setPort(port); server.addConnector(connector); // set the Server's HandlerCollection. Other handlers will be added to the HandlerCollection handlerCollection = new ContextHandlerCollection(); server.setHandler(handlerCollection); // create servlet context servletContext = new ServletContextHandler( handlerCollection, servletContextString, ServletContextHandler.SESSIONS); // servletContext = new ServletContextHandler(handlerCollection, servletContextString, // ServletContextHandler.SESSIONS); // create web app context // webAppContext = new Context(handlerCollection, webAppContextString, Context.SESSIONS); try { // add ResourceHandlers addResourceHandlers(); // add servlets to the servlet context // servletContext.addHandler(new SecurityHandler()); addServletsToContext(servletContext); // addWebApps(); // add default handler to the server handlerCollection.addHandler(new DefaultHandler()); // start a Jetty server.start(); } catch (BindException ex) { logger.log( Level.INFO, "Could not start web server on port " + port + ": " + ex.getMessage(), ex); lifeCycleControlConduit.vote(meemContext.getWedgeIdentifier(), false); return; } catch (InstantiationException ex) { logger.log(Level.INFO, "Could not add servlet: ", ex); lifeCycleControlConduit.vote(meemContext.getWedgeIdentifier(), false); return; } catch (IllegalAccessException ex) { logger.log(Level.INFO, "Could not add servlet: ", ex); lifeCycleControlConduit.vote(meemContext.getWedgeIdentifier(), false); return; } catch (ClassNotFoundException ex) { logger.log(Level.INFO, "Could not add servlet: ", ex); lifeCycleControlConduit.vote(meemContext.getWedgeIdentifier(), false); return; } catch (MultiException ex) { logger.log(Level.INFO, "Problem while starting the web server: ", ex); lifeCycleControlConduit.vote(meemContext.getWedgeIdentifier(), false); return; } catch (Exception ex) { logger.log(Level.INFO, "Problem while starting the web server: ", ex); lifeCycleControlConduit.vote(meemContext.getWedgeIdentifier(), false); return; } lifeCycleControlConduit.vote(meemContext.getWedgeIdentifier(), true); }
/** @return true = the server is started successfully. */ public synchronized int startServer(String ip, int port, boolean isDynamicPort) { if (isProxyRunning) { stopServer(); } isProxyRunning = false; // ZAP: Set the name of the thread. thread = new Thread(this, "ZAP-ProxyServer"); thread.setDaemon(true); // the priority below should be higher than normal to allow fast accept on the server socket thread.setPriority(Thread.NORM_PRIORITY + 1); proxySocket = null; for (int i = 0; i < 20 && proxySocket == null; i++) { try { proxySocket = createServerSocket(ip, port); proxySocket.setSoTimeout(PORT_TIME_OUT); isProxyRunning = true; } catch (UnknownHostException e) { // ZAP: Warn the user if the host is unknown if (View.isInitialised()) { View.getSingleton() .showWarningDialog(Constant.messages.getString("proxy.error.host.unknow") + " " + ip); } else { System.out.println(Constant.messages.getString("proxy.error.host.unknow") + " " + ip); } return -1; } catch (BindException e) { if ("Cannot assign requested address".equals(e.getMessage())) { showErrorMessage(Constant.messages.getString("proxy.error.address") + " " + ip); return -1; } else if ("Permission denied".equals(e.getMessage()) || "Address already in use".equals(e.getMessage())) { if (!isDynamicPort) { showErrorMessage( Constant.messages.getString("proxy.error.port") + " " + ip + ":" + port); return -1; } else if (port < 65535) { port++; } } else { handleUnknownException(e); return -1; } } catch (IOException e) { handleUnknownException(e); return -1; } } if (proxySocket == null) { return -1; } thread.start(); return proxySocket.getLocalPort(); }
@JRubyMethod( name = "initialize", required = 1, optional = 1, visibility = Visibility.PRIVATE, backtrace = true) public IRubyObject initialize(ThreadContext context, IRubyObject[] args) { IRubyObject hostname = args[0]; IRubyObject port = args.length > 1 ? args[1] : context.getRuntime().getNil(); if (hostname.isNil() || ((hostname instanceof RubyString) && ((RubyString) hostname).isEmpty())) { hostname = context.getRuntime().newString("0.0.0.0"); } else if (hostname instanceof RubyFixnum) { // numeric host, use it for port port = hostname; hostname = context.getRuntime().newString("0.0.0.0"); } String shost = hostname.convertToString().toString(); try { InetAddress addr = InetAddress.getByName(shost); ssc = ServerSocketChannel.open(); int portInt; if (port instanceof RubyInteger) { portInt = RubyNumeric.fix2int(port); } else { IRubyObject portString = port.convertToString(); IRubyObject portInteger = portString.convertToInteger("to_i"); portInt = RubyNumeric.fix2int(portInteger); if (portInt <= 0) { portInt = RubyNumeric.fix2int( RubySocket.getservbyname( context, context.getRuntime().getObject(), new IRubyObject[] {portString})); } } socket_address = new InetSocketAddress(addr, portInt); ssc.socket().bind(socket_address); initSocket(context.getRuntime(), new ChannelDescriptor(ssc, new ModeFlags(ModeFlags.RDWR))); } catch (InvalidValueException ex) { throw context.getRuntime().newErrnoEINVALError(); } catch (UnknownHostException e) { throw sockerr(context.getRuntime(), "initialize: name or service not known"); } catch (BindException e) { // e.printStackTrace(); String msg = e.getMessage(); if (msg == null) { msg = "bind"; } else { msg = "bind - " + msg; } // This is ugly, but what can we do, Java provides the same BindingException // for both EADDRNOTAVAIL and EADDRINUSE, so we differentiate the errors // based on BindException's message. if (ADDR_NOT_AVAIL_PATTERN.matcher(msg).find()) { throw context.getRuntime().newErrnoEADDRNOTAVAILError(msg); } else { throw context.getRuntime().newErrnoEADDRINUSEError(msg); } } catch (SocketException e) { String msg = e.getMessage(); if (msg.indexOf("Permission denied") != -1) { throw context.getRuntime().newErrnoEACCESError("bind(2)"); } else { throw sockerr(context.getRuntime(), "initialize: name or service not known"); } } catch (IOException e) { throw sockerr(context.getRuntime(), "initialize: name or service not known"); } catch (IllegalArgumentException iae) { throw sockerr(context.getRuntime(), iae.getMessage()); } return this; }