Configure Jetty to serve http requests. Example of a client connection URL:
http://localhost:10000/servlets/thrifths2/ A gateway may cause actual target URL to differ,
e.g. http://gateway:port/hive2/servlets/thrifths2/
430232
@Override
  public void run() {
    try {
      // Server thread pool
      // Start with minWorkerThreads, expand till maxWorkerThreads and reject subsequent requests
      String threadPoolName = "HiveServer2-HttpHandler-Pool";
      ThreadPoolExecutor executorService = new ThreadPoolExecutor(minWorkerThreads, maxWorkerThreads,
          workerKeepAliveTime, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),
          new ThreadFactoryWithGarbageCleanup(threadPoolName));
      ExecutorThreadPool threadPool = new ExecutorThreadPool(executorService);

      // HTTP Server
      httpServer = new org.eclipse.jetty.server.Server(threadPool);

      // Connector configs

      ConnectionFactory[] connectionFactories;
      boolean useSsl = hiveConf.getBoolVar(ConfVars.HIVE_SERVER2_USE_SSL);
      String schemeName = useSsl ? "https" : "http";
      // Change connector if SSL is used
      if (useSsl) {
        String keyStorePath = hiveConf.getVar(ConfVars.HIVE_SERVER2_SSL_KEYSTORE_PATH).trim();
        String keyStorePassword = ShimLoader.getHadoopShims().getPassword(hiveConf,
            HiveConf.ConfVars.HIVE_SERVER2_SSL_KEYSTORE_PASSWORD.varname);
        if (keyStorePath.isEmpty()) {
          throw new IllegalArgumentException(ConfVars.HIVE_SERVER2_SSL_KEYSTORE_PATH.varname
              + " Not configured for SSL connection");
        }
        SslContextFactory sslContextFactory = new SslContextFactory();
        String[] excludedProtocols = hiveConf.getVar(ConfVars.HIVE_SSL_PROTOCOL_BLACKLIST).split(",");
        LOG.info("HTTP Server SSL: adding excluded protocols: " + Arrays.toString(excludedProtocols));
        sslContextFactory.addExcludeProtocols(excludedProtocols);
        LOG.info("HTTP Server SSL: SslContextFactory.getExcludeProtocols = " +
          Arrays.toString(sslContextFactory.getExcludeProtocols()));
        sslContextFactory.setKeyStorePath(keyStorePath);
        sslContextFactory.setKeyStorePassword(keyStorePassword);
        connectionFactories = AbstractConnectionFactory.getFactories(
            sslContextFactory, new HttpConnectionFactory());
      } else {
        connectionFactories = new ConnectionFactory[] { new HttpConnectionFactory() };
      }
      ServerConnector connector = new ServerConnector(
          httpServer,
          null,
          // Call this full constructor to set this, which forces daemon threads:
          new ScheduledExecutorScheduler("HiveServer2-HttpHandler-JettyScheduler", true),
          null,
          -1,
          -1,
          connectionFactories);

      connector.setPort(portNum);
      // Linux:yes, Windows:no
      connector.setReuseAddress(!Shell.WINDOWS);
      int maxIdleTime = (int) hiveConf.getTimeVar(ConfVars.HIVE_SERVER2_THRIFT_HTTP_MAX_IDLE_TIME,
          TimeUnit.MILLISECONDS);
      connector.setIdleTimeout(maxIdleTime);

      httpServer.addConnector(connector);

      // Thrift configs
      hiveAuthFactory = new HiveAuthFactory(hiveConf);
      TProcessor processor = new TCLIService.Processor<Iface>(this);
      TProtocolFactory protocolFactory = new TBinaryProtocol.Factory();
      // Set during the init phase of HiveServer2 if auth mode is kerberos
      // UGI for the hive/_HOST (kerberos) principal
      UserGroupInformation serviceUGI = cliService.getServiceUGI();
      // UGI for the http/_HOST (SPNego) principal
      UserGroupInformation httpUGI = cliService.getHttpUGI();
      String authType = hiveConf.getVar(ConfVars.HIVE_SERVER2_AUTHENTICATION);
      TServlet thriftHttpServlet = new ThriftHttpServlet(processor, protocolFactory, authType,
          serviceUGI, httpUGI);

      // Context handler
      final ServletContextHandler context = new ServletContextHandler(
          ServletContextHandler.SESSIONS);
      context.setContextPath("/");
      String httpPath = getHttpPath(hiveConf
          .getVar(HiveConf.ConfVars.HIVE_SERVER2_THRIFT_HTTP_PATH));
      httpServer.setHandler(context);
      context.addServlet(new ServletHolder(thriftHttpServlet), httpPath);

      // TODO: check defaults: maxTimeout, keepalive, maxBodySize, bodyRecieveDuration, etc.
      // Finally, start the server
      httpServer.start();
      String msg = "Started " + ThriftHttpCLIService.class.getSimpleName() + " in " + schemeName
          + " mode on port " + connector.getLocalPort()+ " path=" + httpPath + " with " + minWorkerThreads + "..."
          + maxWorkerThreads + " worker threads";
      LOG.info(msg);
      httpServer.join();
    } catch (Throwable t) {
      LOG.fatal(
          "Error starting HiveServer2: could not start "
              + ThriftHttpCLIService.class.getSimpleName(), t);
      System.exit(-1);
    }
  }
293465
private static void launchServer(final String url,
                                     final CloseableHttpClient client) {
        try {
            final JDialog dialog = new JDialog();
            dialog.setSize(new java.awt.Dimension(400, 75));
            dialog.setModalityType(ModalityType.MODELESS);
            dialog.setTitle("DuraCloud Sync");
            dialog.setLocationRelativeTo(null);

            JPanel panel = new JPanel();
            final JLabel label = new JLabel("Loading...");
            final JProgressBar progress = new JProgressBar();
            progress.setStringPainted(true);

            panel.add(label);
            panel.add(progress);
            dialog.add(panel);
            dialog.setVisible(true);

            port = SyncUIConfig.getPort();
            contextPath = SyncUIConfig.getContextPath();
            Server srv = new Server(port);

            // Setup JMX
            MBeanContainer mbContainer = new MBeanContainer(
                    ManagementFactory.getPlatformMBeanServer() );
            srv.addBean( mbContainer );

            ProtectionDomain protectionDomain =
                org.duracloud.syncui.SyncUIDriver.class.getProtectionDomain();
            String warFile =
                protectionDomain.getCodeSource().getLocation().toExternalForm();

            log.debug("warfile: {}", warFile);
            WebAppContext context = new WebAppContext();
            context.setContextPath(contextPath);
            context.setWar(warFile);
            context.setExtractWAR(Boolean.TRUE);

            Configuration.ClassList classlist = Configuration.ClassList
                    .setServerDefault( srv );
            classlist.addBefore(
                    "org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
                    "org.eclipse.jetty.annotations.AnnotationConfiguration" );

            context.setAttribute(
                    "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
                    ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$" );

            srv.setHandler(context);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    createSysTray(url, srv);

                    while (true) {
                        if (progress.getValue() < 100) {
                            progress.setValue(progress.getValue() + 3);
                        }

                        sleep(2000);
                        if (isAppRunning(url, client)) {
                            break;
                        }
                    }

                    progress.setValue(100);

                    label.setText("Launching browser...");
                    launchBrowser(url);
                    dialog.setVisible(false);
                }
            }).start();

            srv.start();

            srv.join();
        } catch (Exception e) {
            log.error("Error launching server: " + e.getMessage(), e);
        }
    }
1096336
public void configure() throws Exception {

        final String hostname = host.startsWith("http") ? host : "http://" + host;

        /**
         * A generic error handler (specific to this RouteBuilder)
         */
        onException(Exception.class)
            .maximumRedeliveries("{{error.maxRedeliveries}}")
            .log("Index Routing Error: ${routeId}");

        /**
         * Expose a RESTful endpoint for re-indexing
         */
        from("jetty:" + hostname + ":" + port + "{{rest.prefix}}?matchOnUriPrefix=true&httpMethodRestrict=GET,POST")
            .routeId("FcrepoReindexingRest")
            .routeDescription("Expose the reindexing endpoint over HTTP")
            .setHeader(FCREPO_URI).simple("{{fcrepo.baseUrl}}${headers.CamelHttpPath}")
            .choice()
                .when(header(HTTP_METHOD).isEqualTo("GET")).to("direct:usage")
                .otherwise().to("direct:reindex");

        from("direct:usage").routeId("FcrepoReindexingUsage")
            .setHeader(REINDEXING_PREFIX).simple("{{rest.prefix}}")
            .setHeader(REINDEXING_PORT).simple(port)
            .setHeader(FCREPO_BASE_URL).simple("{{fcrepo.baseUrl}}")
            .process(exchange -> {
                exchange.getIn().setHeader(REINDEXING_HOST, getLocalHost().getHostName());
            })
            .to("mustache:org/fcrepo/camel/reindexing/usage.mustache");

        /**
         * A Re-indexing endpoint, setting where in the fcrepo hierarchy
         * a re-indexing operation should begin.
         */
        from("direct:reindex").routeId("FcrepoReindexingReindex")
            .process(new RestProcessor())
            .removeHeaders("CamelHttp*")
            .removeHeader("JMSCorrelationID")
            .setBody(constant(null))
            .choice()
                .when(header(HTTP_RESPONSE_CODE).isGreaterThanOrEqualTo(BAD_REQUEST))
                    .endChoice()
                .when(header(REINDEXING_RECIPIENTS).isEqualTo(""))
                    .transform().simple("No endpoints configured for indexing")
                    .endChoice()
                .otherwise()
                    .log(INFO, LOGGER, "Initial indexing path: ${headers[CamelFcrepoUri]}")
                    .inOnly("{{reindexing.stream}}?disableTimeToLive=true")
                    .setHeader(CONTENT_TYPE).constant("text/plain")
                    .transform().simple("Indexing started at ${headers[CamelFcrepoUri]}");

        /**
         *  A route that traverses through a fedora heirarchy
         *  indexing nodes, as appropriate.
         */
        from("{{reindexing.stream}}?asyncConsumer=true").routeId("FcrepoReindexingTraverse")
            .inOnly("direct:recipients")
            .removeHeaders("CamelHttp*")
            .setHeader(HTTP_METHOD).constant(GET)
            .to("fcrepo:{{fcrepo.baseUrl}}?preferInclude=PreferContainment" +
                    "&preferOmit=ServerManaged&accept=application/n-triples")
            // split the n-triples stream on line breaks so that each triple is split into a separate message
            .split(body().tokenize("\\n")).streaming()
                .removeHeader(FCREPO_URI)
                .removeHeader("JMSCorrelationID")
                .process(exchange -> {
                    // This is a simple n-triples parser, spliting nodes on whitespace according to
                    // https://www.w3.org/TR/n-triples/#n-triples-grammar
                    // If the body is not null and the predicate is ldp:contains and the object is a URI,
                    // then set the CamelFcrepoUri header (if that header is not set, the processing stops
                    // at the filter() line below.
                    final String body = exchange.getIn().getBody(String.class);
                    if (body != null) {
                        final String parts[] = body.split("\\s+");
                        if (parts.length > 2 && parts[1].equals(LDP_CONTAINS) && parts[2].startsWith("<")) {
                            exchange.getIn().setHeader(FCREPO_URI, parts[2].substring(1, parts[2].length() - 1));
                        }
                        exchange.getIn().setBody(null);
                    }
                })
                .filter(header(FCREPO_URI).isNotNull())
                    .inOnly("{{reindexing.stream}}?disableTimeToLive=true");

        /**
         *  Send the message to all of the pre-determined endpoints
         */
        from("direct:recipients").routeId("FcrepoReindexingRecipients")
            .recipientList(header(REINDEXING_RECIPIENTS))
            .ignoreInvalidEndpoints();
    }
667498
def _build_url(cls, request, path=None, **changes):
        
        changes = {k: v for k, v in changes.items() if v is not None}
        queries = {**request.url.query, **changes}
        queries = {k: v for k, v in queries.items() if v is not False}
        query_strings = []

        def add_query(key):
            query_strings.append('{}={}'.format(key, queries[key])
                                 if queries[key] != '' else key)

        def del_query(key):
            queries.pop(key, None)

        if 'head' in queries:
            add_query('head')
            del_query('head')

        if 'start' in changes:
            add_query('start')
        elif 'start' in queries:
            add_query('start')

        del_query('start')

        if 'limit' in queries:
            add_query('limit')
            del_query('limit')

        for key in sorted(queries):
            add_query(key)

        scheme = cls._get_forwarded(request, 'proto') or request.url.scheme
        host = cls._get_forwarded(request, 'host') or request.host
        forwarded_path = cls._get_forwarded(request, 'path')
        path = path if path is not None else request.path
        query = '?' + '&'.join(query_strings) if query_strings else ''

        url = '{}://{}{}{}{}'.format(scheme, host, forwarded_path, path, query)
        return url
604040
public static void main(String[] args) throws Exception {
    CustomHeaderClient client = new CustomHeaderClient("localhost", 50051);
    try {
      /* Access a service running on the local machine on port 50051 */
      String user = "world";
      if (args.length > 0) {
        user = args[0]; /* Use the arg as the name to greet if provided */
      }
      client.greet(user);
    } finally {
      client.shutdown();
    }
  }
181795
private static HttpURLConnection setup(HttpsFileUploaderConfig config) throws MalformedURLException, IOException {
        HttpURLConnection httpUrlConnection;
        boolean isHttps = false;
        URL url = config.getURL();
        if (url.getProtocol().equalsIgnoreCase("https")) {
            isHttps = true;
        }

        if (config.usesProxy()) {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(config.getProxyAddress(), config.getProxyPort()));
            httpUrlConnection = (HttpURLConnection) url.openConnection(proxy);
        } else {
            httpUrlConnection = (HttpURLConnection) url.openConnection();
        }
        
        
        if (!config.isValidateCertificates() && isHttps) {
            SSLUtils.setNoValidate(((HttpsURLConnection) httpUrlConnection), config.getAcceptedIssuers());
        }
        
        
        httpUrlConnection.setUseCaches(false);  // do not use connection caches
        httpUrlConnection.setDoOutput(true);

        // Set timeouts
        httpUrlConnection.setConnectTimeout(config.getConnectTimeoutMs());
        httpUrlConnection.setReadTimeout(config.getReadTimeoutMs());

        httpUrlConnection.setRequestMethod("POST");
        httpUrlConnection.setRequestProperty("Connection", "Keep-Alive");
        httpUrlConnection.setRequestProperty("Cache-Control", "no-cache");
        httpUrlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + MULTIPART_BOUNDARY);
        
        // Sets additional headers
        if (config.getAdditionalHeaders() != null) {
            for(Entry<String,String> e : config.getAdditionalHeaders().entrySet()) {
                // We use the 'set' method here and not the 'add' method because
                // it should be allowed for example for the user to override Java's default
                // User-Agent value. 
                httpUrlConnection.setRequestProperty(e.getKey(), e.getValue());
            }
        }
        
        
        if (config.endpointRequiresAuthentication()) {
            String authString = config.getEndpointUsername() + ":" + config.getEndpointPassword();

            // The only public Base64 encoder that exist in Java 7 and before is from the
            // JAXB package so we will (mis)use that here for Base64 encoding.        
            // Note: Java 8 will finally have a Base64 class in the Util package.
            String authStringEnc = javax.xml.bind.DatatypeConverter.printBase64Binary(authString.getBytes());
            httpUrlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        }
        
        return httpUrlConnection;
    }
236676
def serve(self, config, path, route_name=None, permission=None, **view_options):
        
        route_name = route_name or path.replace('/', '.').strip('.')
        path = path.strip('/') + '*traverse'

        self.route_name = route_name
        self.base_permission = permission

        # configure the route and the path
        config.add_route(route_name, path, factory=self.factory)
        config.add_view(
            self.handle_standard_error,
            route_name=route_name,
            renderer='json2',
            context=StandardError
        ),
        config.add_view(
            self.handle_http_error,
            route_name=route_name,
            renderer='json2',
            context=HTTPException
        )
        config.add_view(
            self.process,
            route_name=route_name,
            renderer='json2',
            **view_options
        )
1351169
def serve(name: str = "", port: int = 5000) -> None:
    
    logging.info(" * Listening on port %s", port)
    httpd = HTTPServer((name, port), RequestHandler)
    httpd.serve_forever()
542007
@Override
  public void onHttpRequest(
      final ParsedHttpRequest parsedHttpRequest,
      final HttpServletResponse response) throws IOException, ServletException {

    LOG.log(Level.INFO, "HttpServerReefEventHandler in webserver onHttpRequest is called: {0}",
        parsedHttpRequest.getRequestUri());

    final String version = parsedHttpRequest.getVersion().toLowerCase();
    final String target = parsedHttpRequest.getTargetEntity().toLowerCase();

    switch (target) {
    case "evaluators": {
      final String queryStr = parsedHttpRequest.getQueryString();
      if (queryStr == null || queryStr.isEmpty()) {
        if (version.equals(VER)) {
          writeEvaluatorsJsonOutput(response);
        } else {
          writeEvaluatorsWebOutput(response);
        }
      } else {
        handleQueries(response, parsedHttpRequest.getQueryMap(), version);
      }
      break;
    }
    case "driver":
      if (version.equals(VER)) {
        writeDriverJsonInformation(response);
      } else {
        writeDriverWebInformation(response);
      }
      break;
    case "close":
      for (final EventHandler<Void> e : clientCloseHandlers) {
        e.onNext(null);
      }
      response.getWriter().println("Enforced closing");
      break;
    case "kill":
      reefStateManager.onClientKill();
      response.getWriter().println("Killing");
      break;
    case "duration":
      final ArrayList<String> lines =
          LogParser.getFilteredLinesFromFile(driverStderrFile, LoggingScopeImpl.DURATION, LoggingScopeImpl.TOKEN, null);
      writeLines(response, lines, "Performance...");
      break;
    case "stages":
      final ArrayList<String> starts =
          LogParser.getFilteredLinesFromFile(driverStderrFile, LoggingScopeImpl.START_PREFIX, logLevelPrefix, null);
      final ArrayList<String> exits =
          LogParser.getFilteredLinesFromFile(driverStderrFile, LoggingScopeImpl.EXIT_PREFIX, logLevelPrefix,
              LoggingScopeImpl.DURATION);
      final ArrayList<String> startsStages = LogParser.findStages(starts, LogParser.START_INDICATORS);
      final ArrayList<String> endStages = LogParser.findStages(exits, LogParser.END_INDICATORS);
      final ArrayList<String> result = LogParser.mergeStages(startsStages, endStages);
      writeLines(response, result, "Current Stages...");
      break;
    case "logfile":
      final List<String> names = parsedHttpRequest.getQueryMap().get("filename");
      final PrintWriter writer = response.getWriter();
      if (names == null || names.size() == 0) {
        writer.println("File name is not provided");
      } else {
        final String fileName = names.get(0);
        if (!fileName.equals(driverStdoutFile) && !fileName.equals(driverStderrFile)) {
          writer.println(String.format("Unsupported file names: [%s] ", fileName));
        } else {
          try {
            final byte[] outputBody = readFile(fileName).getBytes(StandardCharsets.UTF_8);
            writer.print(Arrays.toString(outputBody));
          } catch (final IOException e) {
            writer.println(String.format("Cannot find the log file: [%s].", fileName));
          }
        }
      }
      break;
    case "progress":
      response.getWriter().println(progressProvider.get().getProgress());
      break;
    default:
      response.getWriter().println(String.format("Unsupported query for entity: [%s].", target));
    }
  }
714159
protected static String adjustMappedUrl(SlingHttpServletRequest request, String url) {
        // build a pattern with the (false) default port
        Pattern defaultPortPattern = Pattern.compile(
                URL_PATTERN_STRING.replaceFirst("\\(:\\\\d\\+\\)\\?", ":" + getDefaultPort(request)));
        Matcher matcher = defaultPortPattern.matcher(url);
        // remove the port if the URL matches (contains the port nnumber)
        if (matcher.matches()) {
            if (null == matcher.group(1)) url = "//" + matcher.group(2);
            else url = matcher.group(1) + "://" + matcher.group(2);
            String uri = matcher.group(3);
            if (StringUtils.isNotBlank(uri)) {
                url += uri;
            } else {
                url += "/";
            }
        }
        return url;
    }
1246298
public void configureWebApp () throws Exception
    {
        //cannot configure if the _context is already started
        if (_context.isStarted())
        {
            if (log.isDebugEnabled()){log.debug("Cannot configure webapp after it is started");};
            return;
        }
        
        if(log.isDebugEnabled())
            log.debug("Configuring web-jetty.xml");
        
        Resource webInf=getWebApplicationContext().getWebInf();
        // handle any WEB-INF descriptors
        if(webInf!=null&&webInf.isDirectory())
        {
            // do jetty.xml file
            Resource jetty=webInf.addPath("web-jetty.xml");
            if(!jetty.exists())
                jetty=webInf.addPath("jetty-web.xml");
            if(!getWebApplicationContext().isIgnoreWebJetty()&&jetty.exists())
            {
                
                // Give permission to see Jetty classes
                String[] old_server_classes = _context.getServerClasses();
                String[] server_classes = new String[1+(old_server_classes==null?0:old_server_classes.length)];
                server_classes[0]="-org.browsermob.proxy.jetty.";
                if (server_classes!=null)
                    System.arraycopy(old_server_classes, 0, server_classes, 1, old_server_classes.length);
                
                try
                {
                    _context.setServerClasses(server_classes);
                    if(log.isDebugEnabled())
                        log.debug("Configure: "+jetty);
                    
                    XmlConfiguration jetty_config=new XmlConfiguration(jetty.getURL());
                    jetty_config.configure(getWebApplicationContext());
                }
                finally
                {
                    if (_context.getServerClasses()==server_classes)
                        _context.setServerClasses(old_server_classes);
                }
            }
        }
        
    }
59378
def serve_websocket(request, port):
    """"""
    env = request.environ

    # Send HTTP response 101 Switch Protocol downstream
    uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', ''))

    # Map the websocket URL to the upstream localhost:4000x Notebook instance
    parts = urlparse(request.url)
    parts = parts._replace(scheme="ws", netloc="localhost:{}".format(port))
    url = urlunparse(parts)

    # Proxy initial connection headers
    headers = [(header, value) for header, value in request.headers.items() if header.lower() in CAPTURE_CONNECT_HEADERS]

    logger.info("Connecting to upstream websockets: %s, headers: %s", url, headers)

    ws = ProxyClient(url, headers=headers)
    ws.connect()

    # TODO: Will complain loudly about already send headers - how to abort?
    return httpexceptions.HTTPOk()
974705
def connect(self, url):
        

        headers = httputil.HTTPHeaders({'Content-Type': APPLICATION_JSON})
        request = httpclient.HTTPRequest(url=url,
                                         connect_timeout=self.connect_timeout,
                                         request_timeout=self.request_timeout,
                                         headers=headers)
        ws = websocket_connect(url)
        ws.add_done_callback(self._connect_callback)
1223557
@Override
    public boolean isH2Request(HttpInboundConnection hic, ServletRequest request) throws ServletException {
        
        //first check if H2 is enabled for this channel/port
        if (!((Http2InboundConnection)hic).isHTTP2UpgradeRequest(null, true) ){
            return false;
        }
        
        Map<String, String> headers = new HashMap<String, String>();
        HttpServletRequest hsrt = (HttpServletRequest) request;
        Enumeration<String> headerNames = hsrt.getHeaderNames();
        
        // create a map of the headers to pass to the transport code
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = hsrt.getHeader(key);
            headers.put(key, value);
        }
        //check if this request is asking to do H2
        return ((Http2InboundConnection)hic).isHTTP2UpgradeRequest(headers, false);
    }
895509
def serve(args):
    
    # Sever's parameters
    port = args.serve_port or PORT
    host = "0.0.0.0"

    # Current working directory
    dir_path = Path().absolute()
    web_dir = dir_path / "site"

    # Update routes
    utils.set_routes()

    # Offline mode
    if args.offline:
        os.environ["MKINX_OFFLINE"] = "true"
        _ = subprocess.check_output("mkdocs build > /dev/null", shell=True)
        utils.make_offline()

    class MkinxHTTPHandler(SimpleHTTPRequestHandler):
        """Class routing urls (paths) to projects (resources)
        """

        def translate_path(self, path):
            # default root -> cwd
            location = str(web_dir)
            route = location

            if len(path) != 0 and path != "/":
                for key, loc in utils.get_routes():
                    if path.startswith(key):
                        location = loc
                        path = path[len(key) :]
                        break

            if location[-1] == "/" or not path or path[0] == "/":
                route = location + path
            else:
                route = location + "/" + path

            return route.split("?")[0]

    # Serve as deamon thread
    success = False
    count = 0
    print("Waiting for server port...")
    try:
        while not success:
            try:
                httpd = socketserver.TCPServer((host, port), MkinxHTTPHandler)
                success = True
            except OSError:
                count += 1
            finally:
                if not success and count > 20:
                    s = "port {} seems occupied. Try with {} ? (y/n)"
                    if "y" in input(s.format(port, port + 1)):
                        port += 1
                        count = 0
                    else:
                        print("You can specify a custom port with mkinx serve -s")
                        return
                time.sleep(0.5)
    except KeyboardInterrupt:
        print("Aborting.")
        return

    httpd.allow_reuse_address = True
    print("\nServing at http://{}:{}\n".format(host, port))
    thread = threading.Thread(target=httpd.serve_forever)
    thread.daemon = True
    thread.start()

    # Watch for changes
    event_handler = utils.MkinxFileHandler(
        patterns=["*.rst", "*.md", "*.yml", "*.yaml"]
    )
    observer = Observer()
    observer.schedule(event_handler, path=str(dir_path), recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
        httpd.server_close()
    observer.join()
632357
protected URL buildURL(Map<String,String> headers, String instanceHostPort) throws MalformedURLException {
        String origUrl = headers.get(Listener.METAINFO_REQUEST_URL);
        if (origUrl == null || !origUrl.startsWith("http")) {
            // other protocol: forward to standard services url
            return new URL("http://" + instanceHostPort + "/" + getServicesRoot() + "/Services");
        }
        else {
            URL origHttpUrl = new URL(origUrl);
            String path = origHttpUrl.getPath();
            // Re-route from SOAP to REST since MDW only cares about message Payload, plus we no longer have the SOAP Envelope in the request
            if (path != null && (path.contains("/SOAP") || path.contains("/MDWWebService")))
                path = "/" + getServicesRoot() + "/Services";

            String destUrl = origHttpUrl.getProtocol() + "://" + instanceHostPort + path;
            if (!StringHelper.isEmpty(headers.get(Listener.METAINFO_REQUEST_QUERY_STRING)))
                destUrl += "?" + headers.get(Listener.METAINFO_REQUEST_QUERY_STRING);
            return new URL(destUrl);
        }
    }
327797
public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException
    {
        URI uri = request.getURI();

        // Is this a CONNECT request?
        if (HttpRequest.__CONNECT.equalsIgnoreCase(request.getMethod()))
        {
            response.setField(HttpFields.__Connection, "close"); // TODO Needed for IE????
            handleConnect(pathInContext, pathParams, request, response);
            return;
        }

        try
        {
            // Do we proxy this?
            URL url = isProxied(uri);
            if (url == null)
            {
                if (isForbidden(uri))
                    sendForbid(request, response, uri);
                return;
            }

            if (log.isDebugEnabled())
                log.debug("PROXY URL=" + url);

            URLConnection connection = url.openConnection();
            connection.setAllowUserInteraction(false);

            // Set method
            HttpURLConnection http = null;
            if (connection instanceof HttpURLConnection)
            {
                http = (HttpURLConnection) connection;
                http.setRequestMethod(request.getMethod());
                http.setInstanceFollowRedirects(false);
            }

            // check connection header
            String connectionHdr = request.getField(HttpFields.__Connection);
            if (connectionHdr != null && (connectionHdr.equalsIgnoreCase(HttpFields.__KeepAlive) || connectionHdr.equalsIgnoreCase(HttpFields.__Close)))
                connectionHdr = null;

            // copy headers
            boolean xForwardedFor = false;
            boolean hasContent = false;
            Enumeration enm = request.getFieldNames();
            while (enm.hasMoreElements())
            {
                // TODO could be better than this!
                String hdr = (String) enm.nextElement();

                if (_DontProxyHeaders.containsKey(hdr) || !_chained && _ProxyAuthHeaders.containsKey(hdr))
                    continue;
                if (connectionHdr != null && connectionHdr.indexOf(hdr) >= 0)
                    continue;

                if (HttpFields.__ContentType.equals(hdr))
                    hasContent = true;

                Enumeration vals = request.getFieldValues(hdr);
                while (vals.hasMoreElements())
                {
                    String val = (String) vals.nextElement();
                    if (val != null)
                    {
                        connection.addRequestProperty(hdr, val);
                        xForwardedFor |= HttpFields.__XForwardedFor.equalsIgnoreCase(hdr);
                    }
                }
            }

            // Proxy headers
            if (!_anonymous)
                connection.setRequestProperty("Via", "1.1 (jetty)");
            if (!xForwardedFor)
                connection.addRequestProperty(HttpFields.__XForwardedFor, request.getRemoteAddr());

            // a little bit of cache control
            String cache_control = request.getField(HttpFields.__CacheControl);
            if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0))
                connection.setUseCaches(false);

            // customize Connection
            customizeConnection(pathInContext, pathParams, request, connection);

            try
            {
                connection.setDoInput(true);

                // do input thang!
                InputStream in = request.getInputStream();
                if (hasContent)
                {
                    connection.setDoOutput(true);
                    IO.copy(in, connection.getOutputStream());
                }

                // Connect
                connection.connect();
            }
            catch (Exception e)
            {
                LogSupport.ignore(log, e);
            }

            InputStream proxy_in = null;

            // handler status codes etc.
            int code = HttpResponse.__500_Internal_Server_Error;
            if (http != null)
            {
                proxy_in = http.getErrorStream();

                code = http.getResponseCode();
                response.setStatus(code);
                response.setReason(http.getResponseMessage());
            }

            if (proxy_in == null)
            {
                try
                {
                    proxy_in = connection.getInputStream();
                }
                catch (Exception e)
                {
                    LogSupport.ignore(log, e);
                    proxy_in = http.getErrorStream();
                }
            }

            // clear response defaults.
            response.removeField(HttpFields.__Date);
            response.removeField(HttpFields.__Server);

            // set response headers
            int h = 0;
            String hdr = connection.getHeaderFieldKey(h);
            String val = connection.getHeaderField(h);
            while (hdr != null || val != null)
            {
                if (hdr != null && val != null && !_DontProxyHeaders.containsKey(hdr) && (_chained || !_ProxyAuthHeaders.containsKey(hdr)))
                    response.addField(hdr, val);
                h++;
                hdr = connection.getHeaderFieldKey(h);
                val = connection.getHeaderField(h);
            }
            if (!_anonymous)
                response.setField("Via", "1.1 (jetty)");

            // Handled
            request.setHandled(true);
            if (proxy_in != null)
                IO.copy(proxy_in, response.getOutputStream());

        }
        catch (Exception e)
        {
            log.warn(e.toString());
            LogSupport.ignore(log, e);
            if (!response.isCommitted())
                response.sendError(HttpResponse.__400_Bad_Request);
        }
    }