Same as in BaseServer but as a thread.
        In addition, exception handling is done here.
437580
def process_request_thread(self, request, client_address):
        
        from ..blockstackd import get_gc_thread

        try:
            self.finish_request(request, client_address)
        except Exception:
            self.handle_error(request, client_address)
        finally:
            self.shutdown_request(request)

        shutdown_thread = False
        with self._thread_guard:
            if threading.current_thread().ident in self._threads:
                del self._threads[threading.current_thread().ident]
                shutdown_thread = True

                if BLOCKSTACK_TEST:
                    log.debug('{} active threads (removed {})'.format(len(self._threads), threading.current_thread().ident))

        if shutdown_thread:
            gc_thread = get_gc_thread()
            if gc_thread:
                # count this towards our preemptive garbage collection
                gc_thread.gc_event()
416368
def process_exception(self, request, exception):
        
        if isinstance(exception, HttpRedirectRequest):
            return HttpResponseRedirect(exception.url, status=exception.status)
        else:
            return None
164319
private void processUncaughtException(Thread thread, Throwable throwable) {
        if (exceptionPurger != null) {
            throwable = exceptionPurger.purge(throwable);
        }
        logException(thread, throwable);
        notifyUserAboutException(thread, throwable);
    }
1069181
def handleException(exception):
    
    serverException = exception
    if not isinstance(exception, exceptions.BaseServerException):
        with app.test_request_context():
            app.log_exception(exception)
        serverException = exceptions.getServerError(exception)
    error = serverException.toProtocolElement()
    # If the exception is being viewed by a web browser, we can render a nicer
    # view.
    if flask.request and 'Accept' in flask.request.headers and \
            flask.request.headers['Accept'].find('text/html') != -1:
        message = "<h1>Error {}</h1><pre>{}</pre>".format(
                    serverException.httpStatus,
                    protocol.toJson(error))
        if serverException.httpStatus == 401 \
                or serverException.httpStatus == 403:
            message += "Please try <a href=\"/login\">logging in</a>."
        return message
    else:
        responseStr = protocol.toJson(error)
        return getFlaskResponse(responseStr, serverException.httpStatus)
792307
@Override
    public void checkIn(ServiceHandle<S> handle) throws Exception {
        checkNotNull(handle);

        S service = handle.getService();
        ServiceEndPoint endPoint = handle.getEndPoint();

        // Figure out if we should check this revision in.  If it was created before the last known invalid revision
        // for this particular end point, or the cache is closed, then we shouldn't check it in.
        Long invalidRevision = _invalidRevisions.get(endPoint);
        Long serviceRevision = _checkedOutRevisions.remove(handle);

        if (_isClosed || (invalidRevision != null && serviceRevision < invalidRevision)) {
            _pool.invalidateObject(endPoint, service);
        } else {
            _pool.returnObject(endPoint, service);
        }
    }
25735
public void postDeploy() throws Throwable
   {
      if (server != null &&
          !server.isRunning() &&
          handlers != null && handlers.getHandlers() != null && handlers.getHandlers().length > 0)
      {
         try
         {
            ContextHandlerCollection chc = new ContextHandlerCollection();
            chc.setHandlers(handlers.getHandlers());

            server.setHandler(chc);
      
            server.start();
         }
         catch (Exception e)
         {
            log.error("Could not start Jetty webserver", e);
         }
      }
   }
635989
def process_request_thread(self, mainthread):
        """"""
        life_time   = time.time()
        nb_requests = 0

        while not mainthread.killed():
            if self.max_life_time > 0:
                if (time.time() - life_time) >= self.max_life_time:
                    mainthread.add_worker(1)
                    return
                try:
                    SocketServer.ThreadingTCPServer.process_request_thread(self, *self.requests.get(True, 0.5))
                except Queue.Empty:
                    continue
            else:
                SocketServer.ThreadingTCPServer.process_request_thread(self, *self.requests.get())

            LOG.debug("nb_requests: %d, max_requests: %d", nb_requests, self.max_requests)
            nb_requests += 1

            if self.max_requests > 0 and nb_requests >= self.max_requests:
                mainthread.add_worker(1)
                return
833115
@Override
    public void run() {
        try {
            handle();
        } catch (Exception e) {
            Throwables.throwIfUnchecked(e);
            throw new RuntimeException(e);
        }
    }
335060
public void compileAndRun() throws Exception {
		synchronized (this.monitor) {
			try {
				stop();
				Class<?>[] compiledSources = compile();
				monitorForChanges();
				// Run in new thread to ensure that the context classloader is setup
				this.runThread = new RunThread(compiledSources);
				this.runThread.start();
				this.runThread.join();
			}
			catch (Exception ex) {
				if (this.fileWatchThread == null) {
					throw ex;
				}
				else {
					ex.printStackTrace();
				}
			}
		}
	}
1091230
public void process(InputStream is) throws Exception
   {
      readHeader(is);
      readVersion(is);
      readTableData(readTableHeaders(is), is);
   }
1189908
public void startServer() throws Exception {
        if (!externalDatabaseHost) {
            try {
                this.port = Utils.getSystemPort(Constants.SYS_DB_PORT);
                server = Server.createTcpServer("-tcpPort", String.valueOf(port), "-tcpAllowOthers").start();
            } catch (SQLException e) {
                if (e.toString().contains("java.net.UnknownHostException")) {
                    logger.error("Startup failure. Potential bug in OSX & Java7. Workaround: add name of local machine to '/etc/hosts.'");
                    logger.error("Example: 127.0.0.1 MacBook");
                    throw e;
                }
            }
        }
    }
254269
def set_exception(self, exception, traceback=None):
        
        if not isinstance(exception, BaseException):
            raise RuntimeError("Exception must be of BaseException type")
        self._exception = exception
        self._traceback = traceback
        self._event.set()
        self._invoke_callbacks()
628405
private static void initExceptionThreadPool() {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "initExceptionThreadPool");

        // Do a synchronous check to ensure once-only creation
        synchronized (exceptionTPCreateSync) {
            if (exceptionThreadPool == null) {
                // Get the maximum size for the thread pool, defaulting if
                // not specified or if the value cannot be parsed
                int maxThreads = Integer.parseInt(ApiJmsConstants.EXCEPTION_MAXTHREADS_DEFAULT_INT);
                String maxThreadsStr = RuntimeInfo.getProperty(ApiJmsConstants.EXCEPTION_MAXTHREADS_NAME_INT,
                                                               ApiJmsConstants.EXCEPTION_MAXTHREADS_DEFAULT_INT);
                try {
                    maxThreads = Integer.parseInt(maxThreadsStr);
                } catch (NumberFormatException e) {
                    // No FFDC code needed, but we will exception this
                    SibTr.exception(tc, e);
                }

                // Trace the value we will use
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    SibTr.debug(tc, ApiJmsConstants.EXCEPTION_MAXTHREADS_NAME_INT + ": " + Integer.toString(maxThreads));

                // Create the thread pool
                exceptionThreadPool = new ThreadPool(ApiJmsConstants.EXCEPTION_THREADPOOL_NAME_INT, 0, maxThreads);
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "initExceptionThreadPool");
    }
883145
@Override
	public void invoke() throws Exception {

		if (LOG.isDebugEnabled()) {
			LOG.debug(formatLogString("Start task code."));
		}

		// whatever happens in this scope, make sure that the local strategies are cleaned up!
		// note that the initialization of the local strategies is in the try-finally block as well,
		// so that the thread that creates them catches its own errors that may happen in that process.
		// this is especially important, since there may be asynchronous closes (such as through canceling).
		try {
			// initialize the serializers (one per channel) of the record writers
			initOutputWriters(this.eventualOutputs);

			// initialize the remaining data structures on the input and trigger the local processing
			// the local processing includes building the dams / caches
			try {
				int numInputs = driver.getNumberOfInputs();
				int numBroadcastInputs = this.config.getNumBroadcastInputs();
				
				initInputsSerializersAndComparators(numInputs);
				initBroadcastInputsSerializers(numBroadcastInputs);
				
				// set the iterative status for inputs and broadcast inputs
				{
					List<Integer> iterativeInputs = new ArrayList<Integer>();
					
					for (int i = 0; i < numInputs; i++) {
						final int numberOfEventsUntilInterrupt = getTaskConfig().getNumberOfEventsUntilInterruptInIterativeGate(i);
			
						if (numberOfEventsUntilInterrupt < 0) {
							throw new IllegalArgumentException();
						}
						else if (numberOfEventsUntilInterrupt > 0) {
							this.inputReaders[i].setIterative(numberOfEventsUntilInterrupt);
							iterativeInputs.add(i);
				
							if (LOG.isDebugEnabled()) {
								LOG.debug(formatLogString("Input [" + i + "] reads in supersteps with [" +
										+ numberOfEventsUntilInterrupt + "] event(s) till next superstep."));
							}
						}
					}
					this.iterativeInputs = asArray(iterativeInputs);
				}
				
				{
					List<Integer> iterativeBcInputs = new ArrayList<Integer>();
					
					for (int i = 0; i < numBroadcastInputs; i++) {
						final int numberOfEventsUntilInterrupt = getTaskConfig().getNumberOfEventsUntilInterruptInIterativeBroadcastGate(i);
						
						if (numberOfEventsUntilInterrupt < 0) {
							throw new IllegalArgumentException();
						}
						else if (numberOfEventsUntilInterrupt > 0) {
							this.broadcastInputReaders[i].setIterative(numberOfEventsUntilInterrupt);
							iterativeBcInputs.add(i);
				
							if (LOG.isDebugEnabled()) {
								LOG.debug(formatLogString("Broadcast input [" + i + "] reads in supersteps with [" +
										+ numberOfEventsUntilInterrupt + "] event(s) till next superstep."));
							}
						}
					}
					this.iterativeBroadcastInputs = asArray(iterativeBcInputs);
				}
				
				initLocalStrategies(numInputs);
			} catch (Exception e) {
				throw new RuntimeException("Initializing the input processing failed" +
					e.getMessage() == null ? "." : ": " + e.getMessage(), e);
			}

			if (!this.running) {
				if (LOG.isDebugEnabled()) {
					LOG.debug(formatLogString("Task cancelled before task code was started."));
				}
				return;
			}

			// pre main-function initialization
			initialize();

			// read the broadcast variables
			for (int i = 0; i < this.config.getNumBroadcastInputs(); i++) {
				final String name = this.config.getBroadcastInputName(i);
				readAndSetBroadcastInput(i, name, this.runtimeUdfContext);
			}

			// the work goes here
			run();
		}
		finally {
			// clean up in any case!
			closeLocalStrategiesAndCaches();
		}

		if (this.running) {
			if (LOG.isDebugEnabled()) {
				LOG.debug(formatLogString("Finished task code."));
			}
		} else {
			if (LOG.isDebugEnabled()) {
				LOG.debug(formatLogString("Task code cancelled."));
			}
		}
	}
522052
void doMethod(HttpServletRequest request, HttpServletResponse response, HttpMethod httpMethod) {

        // Locate a request handler:
        String requestPath = mapRequestPath(request);
        Route route = api.get(requestPath);

        try {

            if (route != null && route.requestHandlers.containsKey(httpMethod)) {
                handleRequest(request, response, route, httpMethod);
            } else {
                handleNotFound(request, response);
            }

        } catch (Throwable t) {

            // Chances are the exception we've actually caught is the reflection
            // one from Method.invoke(...)
            Throwable caught = t;
            if (InvocationTargetException.class.isAssignableFrom(t.getClass())) {
                caught = t.getCause();
            }

            RequestHandler requestHandler = (route == null ? null : route.requestHandlers.get(httpMethod));
            handleError(request, response, requestHandler, caught);
        }

    }
364029
public static void safelyIgnoreException(Throwable t)
    {
        if (t instanceof ThreadDeath)
        {
            throw (ThreadDeath) t;
        }

        if (t instanceof OutOfMemoryError)
        {
            throw (OutOfMemoryError) t;
        }

    }
719639
@Override
    public void handleException(HttpServletRequest req, HttpServletResponse rsp, Throwable wse) throws ServletException, IOException, ClassCastException {
        WebReply reply = ((WebSecurityCollaboratorException) (wse)).getWebReply();
        int sc = reply.getStatusCode();

        // Throw an exception if an error
        if (sc == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) {
            String method = null;
            if (req != null) {
                method = req.getMethod();
            }
            String url = getRequestURL(req);

            final ServletException ex = new ServletException(TraceNLS.getFormattedMessage(
                                                                                          this.getClass(),
                                                                                          TraceConstants.MESSAGE_BUNDLE,
                                                                                          "SEC_WEB_INTERNAL_SERVER_ERROR",
                                                                                          new Object[] { method, url },
                                                                                          "CWWKS9115E: The server encountered an unexpected condition which prevented it from fulfilling the request of method {0} for URL {1}. Review the server logs for more information."), wse);
            throw ex;
        }
        reply.writeResponse(rsp);
    }