Start a server.

@return the http server
@throws Exception the exception
2215
public synchronized HttpServer<Buffer, Buffer> start() throws Exception {
		if (server == null) {
			server = createProtocolListener();
		}
		return server;
	}
1040271
@Override
    protected void doStart() throws Exception
    {
        log.info("starting...");
        super.doStart();
        _client = newClient(_serverString);
        if (_client == null)
        {
            throw new IllegalStateException("newClient(" + _serverString + ") returns null.");
        }
        log.info("use " + _client.getClass().getSimpleName() + " as client factory.");
        _client.establish();
        log.info("started.");
    }
1043031
public Javalin start() {
        Util.logJavalinBanner(this.config.showJavalinBanner);
        JettyUtil.disableJettyLogger();
        long startupTimer = System.currentTimeMillis();
        if (server.getStarted()) {
            throw new IllegalStateException("Cannot call start() again on a started server.");
        }
        server.setStarted(true);
        Util.printHelpfulMessageIfLoggerIsMissing();
        eventManager.fireEvent(JavalinEvent.SERVER_STARTING);
        try {
            log.info("Starting Javalin ...");
            server.start(servlet, wsServlet);
            log.info("Javalin started in " + (System.currentTimeMillis() - startupTimer) + "ms \\o/");
            eventManager.fireEvent(JavalinEvent.SERVER_STARTED);
        } catch (Exception e) {
            log.error("Failed to start Javalin");
            eventManager.fireEvent(JavalinEvent.SERVER_START_FAILED);
            if (Boolean.TRUE.equals(server.server().getAttribute("is-default-server"))) {
                stop();// stop if server is default server; otherwise, the caller is responsible to stop
            }
            if (e.getMessage() != null && e.getMessage().contains("Failed to bind to")) {
                throw new RuntimeException("Port already in use. Make sure no other process is using port " + server.getServerPort() + " and try again.", e);
            } else if (e.getMessage() != null && e.getMessage().contains("Permission denied")) {
                throw new RuntimeException("Port 1-1023 require elevated privileges (process must be started by admin).", e);
            }
            throw new RuntimeException(e);
        }
        return this;
    }
317581
public JwwfServer startAndJoin() {
		try {
			server.start();
			server.join();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return this;
	}
668374
public final void start() throws Exception {
		synchronized (lock) {
			Preconditions.checkState(state == State.CREATED, "The RestServerEndpoint cannot be restarted.");

			log.info("Starting rest endpoint.");

			final Router router = new Router();
			final CompletableFuture<String> restAddressFuture = new CompletableFuture<>();

			handlers = initializeHandlers(restAddressFuture);

			/* sort the handlers such that they are ordered the following:
			 * /jobs
			 * /jobs/overview
			 * /jobs/:jobid
			 * /jobs/:jobid/config
			 * /:*
			 */
			Collections.sort(
				handlers,
				RestHandlerUrlComparator.INSTANCE);

			handlers.forEach(handler -> {
				registerHandler(router, handler, log);
			});

			ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {

				@Override
				protected void initChannel(SocketChannel ch) {
					RouterHandler handler = new RouterHandler(router, responseHeaders);

					// SSL should be the first handler in the pipeline
					if (isHttpsEnabled()) {
						ch.pipeline().addLast("ssl",
							new RedirectingSslHandler(restAddress, restAddressFuture, sslHandlerFactory));
					}

					ch.pipeline()
						.addLast(new HttpServerCodec())
						.addLast(new FileUploadHandler(uploadDir))
						.addLast(new FlinkHttpObjectAggregator(maxContentLength, responseHeaders))
						.addLast(new ChunkedWriteHandler())
						.addLast(handler.getName(), handler)
						.addLast(new PipelineErrorHandler(log, responseHeaders));
				}
			};

			NioEventLoopGroup bossGroup = new NioEventLoopGroup(1, new ExecutorThreadFactory("flink-rest-server-netty-boss"));
			NioEventLoopGroup workerGroup = new NioEventLoopGroup(0, new ExecutorThreadFactory("flink-rest-server-netty-worker"));

			bootstrap = new ServerBootstrap();
			bootstrap
				.group(bossGroup, workerGroup)
				.channel(NioServerSocketChannel.class)
				.childHandler(initializer);

			Iterator<Integer> portsIterator;
			try {
				portsIterator = NetUtils.getPortRangeFromString(restBindPortRange);
			} catch (IllegalConfigurationException e) {
				throw e;
			} catch (Exception e) {
				throw new IllegalArgumentException("Invalid port range definition: " + restBindPortRange);
			}

			int chosenPort = 0;
			while (portsIterator.hasNext()) {
				try {
					chosenPort = portsIterator.next();
					final ChannelFuture channel;
					if (restBindAddress == null) {
						channel = bootstrap.bind(chosenPort);
					} else {
						channel = bootstrap.bind(restBindAddress, chosenPort);
					}
					serverChannel = channel.syncUninterruptibly().channel();
					break;
				} catch (final Exception e) {
					// continue if the exception is due to the port being in use, fail early otherwise
					if (!(e instanceof org.jboss.netty.channel.ChannelException || e instanceof java.net.BindException)) {
						throw e;
					}
				}
			}

			if (serverChannel == null) {
				throw new BindException("Could not start rest endpoint on any port in port range " + restBindPortRange);
			}

			log.debug("Binding rest endpoint to {}:{}.", restBindAddress, chosenPort);

			final InetSocketAddress bindAddress = (InetSocketAddress) serverChannel.localAddress();
			final String advertisedAddress;
			if (bindAddress.getAddress().isAnyLocalAddress()) {
				advertisedAddress = this.restAddress;
			} else {
				advertisedAddress = bindAddress.getAddress().getHostAddress();
			}
			final int port = bindAddress.getPort();

			log.info("Rest endpoint listening at {}:{}", advertisedAddress, port);

			restBaseUrl = new URL(determineProtocol(), advertisedAddress, port, "").toString();

			restAddressFuture.complete(restBaseUrl);

			state = State.RUNNING;

			startInternal();
		}
	}
80360
public boolean start()
    throws Exception
  {
    // ServerNetwork clusterServer = getServerNetwork(_selfServer);
    
    if (_selfServer.port() >= 0) {
      // _hmuxProtocol = HmuxProtocol.create();
      _httpProtocol = new ProtocolHttp();
      _httpProtocolBartender = new ProtocolHttp();

      _httpProtocol.extensionProtocol(_protocolBartenderPublic);
      _httpProtocolBartender.extensionProtocol(_protocolBartender);
      
      ProtocolHttp protocolPublic = _httpProtocol;
      
      /*
      if (_serverConfig.getPortBartender() < 0) {
        protocolPublic = _httpProtocolBartender;
      }
      */
      
      Config config = _config;
      
      PortTcpBuilder portBuilder = new PortTcpBuilder(config);
      portBuilder.portName("server");
      //portBuilder.serverSocket(_serverConfig.getServerSocket());
      portBuilder.protocol(protocolPublic);
      portBuilder.ampManager(AmpSystem.currentManager());
      
      // XXX: config timing issues, see network/0330, 
      // NetworkServerConfig.getClusterIdleTime()
      
      _portPublic = new TcpPortBartender(portBuilder, _selfServer);
      portBuilder.portDefault(8080);
        
      if (config.get("bartender.port", int.class, 0) >= 0) {
        portBuilder = new PortTcpBuilder(config);
        portBuilder.portName("bartender");
        //portBuilder.serverSocket(_serverConfig.getSocketBartender());
        portBuilder.protocol(_httpProtocolBartender);
        //portBuilder.portDefault(_serverConfig.getPortBartender());
        portBuilder.ampManager(AmpSystem.currentManager());
          
        _portBartender = new TcpPortBartender(portBuilder, _selfServer);
      }
      
      /*
      _bartenderPortConfig.configure(_portPublic);
      _serverConfig.configurePort(_portPublic);
      
      if (_portBartender != null) {
        _bartenderPortConfig.configure(_portBartender);
        
        _serverConfig.configurePort(_portBartender);
      }
      */
    }
    
    startClusterPort();
    
    // validateHub(_selfServer.getPod());
    
    return true;
  }
1232532
@Override
  public ServerImpl start() throws IOException {
    synchronized (lock) {
      checkState(!started, "Already started");
      checkState(!shutdown, "Shutting down");
      // Start and wait for any ports to actually be bound.

      ServerListenerImpl listener = new ServerListenerImpl();
      for (InternalServer ts : transportServers) {
        ts.start(listener);
        activeTransportServers++;
      }
      executor = Preconditions.checkNotNull(executorPool.getObject(), "executor");
      started = true;
      return this;
    }
  }
529543
public function create() {
		$ssoServer = new \Flowpack\SingleSignOn\Server\Domain\Model\SsoServer();
		if ((string)$this->serverServiceBaseUri === '') {
			throw new Exception('Missing Flowpack.SingleSignOn.Server.server.serviceBaseUri setting', 1354805519);
		}
		$ssoServer->setServiceBaseUri($this->serverServiceBaseUri);
		if ((string)$this->serverKeyPairFingerprint === '') {
			throw new Exception('Missing Flowpack.SingleSignOn.Server.server.keyPairFingerprint setting', 1351699834);
		}
		$ssoServer->setKeyPairFingerprint($this->serverKeyPairFingerprint);
		return $ssoServer;
	}
202648
def start_server(self, addr='', port=8000):
        
        if self._multiprocess_on:
            raise SanicPrometheusError(
                "start_server can not be used when multiprocessing " +
                "is turned on")
        start_http_server(addr=addr, port=port)
473761
public void start() throws ConfigurationException {
		if (connectionFactory == null) {
			throw new ConfigurationException("can not start without client socket factory");
		}
		try {
			server = new ServerSocket(port);
		} catch (IOException e) {
			System.out.println(new LogEntry(e.getMessage(), e));
			throw new ConfigurationException("Cannot start server at port " + port, e);
		}
		System.out.println(new LogEntry("starting socket server at port " + port));
		serverThread = new Thread(this);
		serverThread.start();
	}
451073
public void startServer() {

    server = new Server(httpPort);
    server.setHandler(wrapHandlers());

    if (isWebSocketInClassPath()) {
      setupForWebSocket();
    }
    try {
      server.start();
      log().info("server started");

      Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownRunnable()));
      
      if (useStdInShutdown) {
        // generally for use in IDE via JettyRun, Use CTRL-D in IDE console to shutdown
        BufferedReader systemIn = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
        while((systemIn.readLine()) != null) {
          // ignore anything except CTRL-D by itself
        }
        System.out.println("Shutdown via CTRL-D");
        System.exit(0);
      }

    } catch (Exception e) {
      e.printStackTrace();
      System.exit(100);
    }
  }
136155
public void start() throws Exception {
		server = new Server();
		ServerConnector connector = new ServerConnector(server);
		if (serverAddress != null) {
			connector.setHost(serverAddress.getHostAddress());
		}
		connector.setPort(serverPort);
		server.addConnector(connector);
		server.setHandler(new JmxWebHandler());
		server.start();
	}
136130
public void start() throws IOException {
        myServerSocket = new ServerSocket();
        myServerSocket.bind((hostname != null) ? new InetSocketAddress(
                hostname, myPort) : new InetSocketAddress(myPort));

        myThread = new Thread(new Runnable() {
            @Override
            public void run() {
                do {
                    try {
                        final Socket finalAccept = myServerSocket.accept();
                        registerConnection(finalAccept);
                        finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
                        final InputStream inputStream = finalAccept
                                .getInputStream();
                        asyncRunner.exec(new Runnable() {
                            @Override
                            public void run() {
                                OutputStream outputStream = null;
                                try {
                                    outputStream = finalAccept
                                            .getOutputStream();
                                    TempFileManager tempFileManager = tempFileManagerFactory
                                            .create();
                                    HTTPSession session = new HTTPSession(
                                            tempFileManager, inputStream,
                                            outputStream, finalAccept
                                                    .getInetAddress());
                                    while (!finalAccept.isClosed()) {
                                        session.execute();
                                    }
                                } catch (Exception e) {
                                    // When the socket is closed by the client,
                                    // we throw our own SocketException
                                    // to break the "keep alive" loop above.
                                    if (!(e instanceof SocketException && "NanoHttpd Shutdown"
                                            .equals(e.getMessage()))) {
                                        e.printStackTrace();
                                    }
                                } finally {
                                    safeClose(outputStream);
                                    safeClose(inputStream);
                                    safeClose(finalAccept);
                                    unRegisterConnection(finalAccept);
                                }
                            }
                        });
                    } catch (IOException e) {
                    }
                } while (!myServerSocket.isClosed());
            }
        });
        myThread.setDaemon(true);
        myThread.setName("NanoHttpd Main Listener");
        myThread.start();
    }
71183
public void run () throws Exception
  {
    if (System.getSecurityManager () != null)
      throw new IllegalStateException ("Security Manager is set but not supported - aborting!");

    final String sTempDir = SystemProperties.getTmpDir ();

    // Create main server
    final Server aServer = new Server (m_aThreadPool);
    {
      // Create connector on Port
      final ServerConnector aConnector = new ServerConnector (aServer);
      aConnector.setPort (m_nPort);
      aConnector.setIdleTimeout (30_000);
      customizeServerConnector (aConnector);
      aServer.setConnectors (new Connector [] { aConnector });
      aServer.setAttribute ("org.eclipse.jetty.server.Request.maxFormContentSize",
                            Integer.valueOf (2 * CGlobal.BYTES_PER_MEGABYTE));
      aServer.setAttribute ("org.eclipse.jetty.server.Request.maxFormKeys", Integer.valueOf (20000));
    }

    customizeServer (aServer);

    final WebAppContext aWebAppCtx = new WebAppContext ();
    {
      aWebAppCtx.setBaseResource (m_aResourceBase);
      aWebAppCtx.setDescriptor (m_sWebXmlResource != null ? m_sWebXmlResource
                                                          : m_aResourceBase.addPath ("/WEB-INF/web.xml").getName ());
      aWebAppCtx.setContextPath (m_sContextPath);
      aWebAppCtx.setTempDirectory (new File (sTempDir + '/' + m_sDirBaseName + ".webapp"));
      aWebAppCtx.setParentLoaderPriority (true);
      aWebAppCtx.setThrowUnavailableOnStartupException (true);
      if (m_sContainerIncludeJarPattern != null)
      {
        // http://www.eclipse.org/jetty/documentation/9.4.x/configuring-webapps.html#container-include-jar-pattern
        // https://github.com/eclipse/jetty.project/issues/680
        aWebAppCtx.setAttribute (WebInfConfiguration.CONTAINER_JAR_PATTERN, m_sContainerIncludeJarPattern);
      }
      if (m_sWebInfIncludeJarPattern != null)
      {
        aWebAppCtx.setAttribute (WebInfConfiguration.WEBINF_JAR_PATTERN, m_sWebInfIncludeJarPattern);
      }

      if (m_bAllowAnnotationBasedConfig)
      {
        // Important to add the AnnotationConfiguration!
        aWebAppCtx.setConfigurations (new Configuration [] { new WebInfConfiguration (),
                                                             new WebXmlConfiguration (),
                                                             new MetaInfConfiguration (),
                                                             new FragmentConfiguration (),
                                                             new AnnotationConfiguration (),
                                                             new JettyWebXmlConfiguration () });
      }
      // else leave default
    }

    // Set session store directory to passivate/activate sessions
    if (m_bSpecialSessionMgr)
    {
      final SessionHandler aHdl = new SessionHandler ();
      final FileSessionDataStore aDataStore = new FileSessionDataStore ();
      aDataStore.setStoreDir (new File (sTempDir + '/' + m_sDirBaseName + ".sessions"));
      aDataStore.setDeleteUnrestorableFiles (true);
      final DefaultSessionCache aCache = new DefaultSessionCache (aHdl);
      aCache.setSessionDataStore (aDataStore);
      aCache.setRemoveUnloadableSessions (true);
      aHdl.setSessionCache (aCache);
      aWebAppCtx.setSessionHandler (aHdl);
    }

    if (StringHelper.hasText (m_sSessionCookieName))
      aWebAppCtx.getSessionHandler ().setSessionCookie (m_sSessionCookieName);

    customizeWebAppCtx (aWebAppCtx);

    aServer.setHandler (aWebAppCtx);
    final ServletContextHandler aCtx = aWebAppCtx;

    // Setting final properties
    // Stops the server when ctrl+c is pressed (registers to
    // Runtime.addShutdownHook)
    aServer.setStopAtShutdown (true);

    if (false)
    {
      // Debug output
      aServer.setDumpBeforeStop (true);
    }

    try
    {
      // Starting shutdown listener thread
      // May fail if port is in use
      if (m_bRunStopMonitor)
        new InternalJettyStopMonitorThread (m_nStopPort, m_sStopKey, () -> aServer.stop ()).start ();

      // Starting the engines:
      aServer.start ();
      LOGGER.info ("Started Jetty" + ":" + m_nPort + ":" + m_nStopPort + " " + m_sAppName);

      // Callback
      onServerStarted (aServer);

      Runtime.getRuntime ().addShutdownHook (new Thread ( () -> {
        try
        {
          aServer.stop ();
          aServer.join ();
        }
        catch (final Exception ex)
        {
          LOGGER.error ("Exception in ShutdownHook of JettyStarter!", ex);
        }
      }));
    }
    catch (final Throwable t)
    {
      // Do not throw something here, in case some exception occurs in finally
      // code
      LOGGER.error ("Failed to start Jetty " + m_sAppName + "!", t);

      // Callback
      onServerStartFailure (aServer, t);
    }
    finally
    {
      if (aCtx.isFailed ())
      {
        LOGGER.error ("Failed to start Jetty " + m_sAppName + " - stopping server!");
        try
        {
          // Throws an Exception e.g. in log4j2 2.5
          aServer.stop ();
          LOGGER.error ("Failed to start Jetty " + m_sAppName + " - stopped server!");
        }
        catch (final Throwable t)
        {
          LOGGER.error ("Error stopping Jetty " + m_sAppName + " after startup errors!", t);
        }
      }
      else
        if (!aServer.isFailed ())
        {
          // Running the server!
          aServer.join ();
        }
    }
  }
764986
public function start()
    {
        $this->_socket_http = socket_create(AF_INET, SOCK_STREAM, IPPROTO_IP);
        if (!$this->_socket_http) {
            throw new Exception("Unable to create socket\n");
        }

        if (!socket_bind($this->_socket_http, self::SERVER_IP, self::LISTENING_PORT)) {
            throw new Exception('Could not bind address and port');
        }

        // Start listening for connections
        if (!socket_listen($this->_socket_http)) {
            throw new Exception('Could not listen to main socket!');
        }

        while (true) {
            // Setup clients listen socket for reading
            $this->read = $this->checkSocket($this->_socket_http);

            // Set up a blocking call to socket_select()
            $this->ready = socket_select($this->read, $this->write, $this->expect, null);

            if ($this->ready === false) {
                $this->getError();
            }

            // if there a no clients we don't need to write
            if (!$this->checkClient() || empty($this->client)) {
                continue;
            }

            // init the Execute phase
            $this->execute();

        } // end while

        // Close the master sockets
        $this->close($this->_socket_http);
    }
1041342
@Override
    public void start(Map<String, String> options) throws Exception {
        // This must be done before starting "RebuildServer"
        // rather than after, so any application caches
        // (in particular the hash map held by PIDGenerator)
        // don't get out of sync with the database.
        blankExistingTables();
        try {
            m_server = Rebuild.getServer();
            // now get the connectionpool
            ConnectionPoolManager cpm =
                    (ConnectionPoolManager) m_server
                            .getModule("org.fcrepo.server.storage.ConnectionPoolManager");
            if (cpm == null) {
                throw new ModuleInitializationException("ConnectionPoolManager not loaded.",
                                                        "ConnectionPoolManager");
            }
            m_connectionPool = cpm.getPool();
            ensureFedoraTables();
            // set m_now, which is both when we are starting this job and the flag
            // that it was started
            m_now = System.currentTimeMillis();
            startStatus(m_now);
            m_context =
                    ReadOnlyContext.getContext("utility", "fedoraAdmin", "", /* null, */
                    ReadOnlyContext.DO_OP);

            ILowlevelStorage llstore =
                    (ILowlevelStorage) m_server
                            .getModule("org.fcrepo.server.storage.lowlevel.ILowlevelStorage");
            try {
                llstore.rebuildObject();
                llstore.rebuildDatastream();
            } catch (LowlevelStorageException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } catch (InitializationException ie) {
            logger.error("Error initializing", ie);
            throw ie;
        }
    }
957724
@Override
  public void start() throws Exception {
    SynchronousQueue<Runnable> synchronousQueue = new SynchronousQueue<>();
    mThreadPool =
        new ThreadPoolExecutor(mMinNumberOfThreads, mMaxNumberOfThreads,
            THREAD_KEEP_ALIVE_TIME_MS, TimeUnit.MILLISECONDS, synchronousQueue);
    mStopped = false;
    try {
      mServerSocket = new ServerSocket(mPort);
    } catch (IOException e) {
      throw new RuntimeException("Failed to bind to port {}.", e);
    }
    while (!mStopped) {
      Socket client;
      try {
        client = mServerSocket.accept();
      } catch (IOException e) {
        if (mServerSocket.isClosed()) {
          break;
        } else {
          continue;
        }
      }
      String clientAddress = client.getInetAddress().getHostAddress();
      LOG.info("Starting thread to read logs from {}", clientAddress);
      AlluxioLog4jSocketNode clientSocketNode = new AlluxioLog4jSocketNode(mBaseLogsDir, client);
      synchronized (mClientSockets) {
        mClientSockets.add(client);
      }
      try {
        CompletableFuture.runAsync(clientSocketNode, mThreadPool)
            .whenComplete((r, e) -> {
              synchronized (mClientSockets) {
                mClientSockets.remove(client);
              }
            });
      } catch (RejectedExecutionException e) {
        // Alluxio log clients (master, secondary master, proxy and workers) establish
        // long-living connections with the log server. Therefore, if the log server cannot
        // find a thread to service a log client, it is very likely due to low number of
        // worker threads. If retry fails, then it makes sense just to let system throw
        // an exception. The system admin should increase the thread pool size.
        String errorMessage = String.format(
            "Log server cannot find a worker thread to service log requests from %s. Increase"
                + " the number of worker threads in the thread pool by configuring"
                + " alluxio.logserver.threads.max in alluxio-site.properties. Current value"
                + " is %d.", clientAddress, mMaxNumberOfThreads);
        throw new RuntimeException(errorMessage, e);
      }
    }
  }