This method redirects the System.* stream to the repository.
It will print header if a implementation of logHeader is provided
346116
public static void redirectStreams() {
        try {
            AccessController.doPrivileged(new PrivilegedAction<Object>() {
                public Object run() {
                    HpelSystemStream newErr = new HpelSystemStream("SystemErr");
                    System.setErr(newErr);
                    HpelSystemStream newOut = new HpelSystemStream("SystemOut");
                    System.setOut(newOut);
                    return null;
                }
            });
        } catch (Throwable t) {
            throw new RuntimeException("Unable to replace System streams", t);
        }

        reset() ;
    }
1204797
function Request_redirect(url, isTemp) {
        logger.info('Request.redirect:', {
            url: url,
            isTemp: isTemp
        });
        this.addHeader('Location', url);
        this.stopPromiseChain();
        this.isRendered = true;
        if (Type.isBoolean(isTemp) && !!isTemp) {
            this.response.writeHead(302, this.headers);
        } else {
            this.response.writeHead(301, this.headers);
        }
        this.response.end('Redirect to:' + url);
    }
1197906
private void redirectToJavaLoggerProxy() {
        DefaultLoggerProxy lp = DefaultLoggerProxy.class.cast(this.loggerProxy);
        JavaLoggerProxy jlp = new JavaLoggerProxy(lp.name, lp.level);
        // the order of assignments is important
        this.javaLoggerProxy = jlp;   // isLoggable checks javaLoggerProxy if set
        this.loggerProxy = jlp;
    }
298530
def transfer_header(self, fw=sys.stdout):
        
        print("\n".join(self.header), file=fw)
405298
private void processRedirectResponse(Response response) throws RuntimeException, JSONException, MalformedURLException {
        // a valid redirect response must contain the Location header.
        ResponseImpl responseImpl = (ResponseImpl)response;
        List<String> locationHeaders = responseImpl.getHeader(LOCATION_HEADER_NAME);

        String location = (locationHeaders != null && locationHeaders.size() > 0) ? locationHeaders.get(0) : null;

        if (location == null) {
            throw new RuntimeException("Redirect response does not contain 'Location' header.");
        }

        // the redirect location url should contain "wl_result" value in query parameters.
        URL url = new URL(location);
        String query = url.getQuery();

        if (query.contains(WL_RESULT)) {
            String result = Utils.getParameterValueFromQuery(query, WL_RESULT);
            JSONObject jsonResult = new JSONObject(result);

            // process failures if any
            JSONObject jsonFailures = jsonResult.optJSONObject(AUTH_FAILURE_VALUE_NAME);

            if (jsonFailures != null) {
                processFailures(jsonFailures);
                listener.onFailure(response, null, null);
                return;
            }

            // process successes if any
            JSONObject jsonSuccesses = jsonResult.optJSONObject(AUTH_SUCCESS_VALUE_NAME);

            if (jsonSuccesses != null) {
                processSuccesses(jsonSuccesses);
            }
        }

        // the rest is handles by the caller
        listener.onSuccess(response);
    }
51293
private PrintStream newStream(String name) throws IOException {
    if(LOG.isDebuggingFiner()) {
      LOG.debugFiner("Requested stream: " + name);
    }
    // Ensure the directory exists:
    if(!basename.exists()) {
      basename.mkdirs();
    }
    String fn = basename.getAbsolutePath() + File.separator + name + EXTENSION;
    fn = usegzip ? fn + GZIP_EXTENSION : fn;
    OutputStream os = new FileOutputStream(fn);
    if(usegzip) {
      // wrap into gzip stream.
      os = new GZIPOutputStream(os);
    }
    PrintStream res = new PrintStream(os);
    if(LOG.isDebuggingFiner()) {
      LOG.debugFiner("Opened new output stream:" + fn);
    }
    // cache.
    return res;
  }
367363
protected OutputStream outputStream(String contentType, Map headers, int status) {
        try {
            RequestContext.setControllerResponse(new NopResponse(contentType, status));

            if (headers != null) {
                for (Object key : headers.keySet()) {
                    if (headers.get(key) != null)
                        RequestContext.getHttpResponse().addHeader(key.toString(), headers.get(key).toString());
                }
            }

            return RequestContext.getHttpResponse().getOutputStream();
        }catch(Exception e){
            throw new ControllerException(e);
        }
    }
1220463
public static void consumeStream(InputStream is) {
        if (is != null) {
            try {
                // Copy the stream to a null destination
                long copied = IOUtils.copyLarge(is, NullOutputStream.NULL_OUTPUT_STREAM);
                if (copied > 0) {
                    logger.log(Level.WARNING, "Consumed unused HTTP response error stream.");
                }
            } catch (IOException ioe) {
                // The stream was probably already closed, there's nothing further we can do anyway
                logger.log(Level.FINEST, "Unable to consume stream.", ioe);
            }
        }
    }
640590
@POST
    public Response runBackup(final InputStream bodyStream) throws IOException {

        File backupDirectory;
        if (null != bodyStream) {
            final String body = IOUtils.toString(bodyStream).trim();

            backupDirectory = new File(body.trim());
            if (body.isEmpty()) {
                // Backup to a temp directory
                backupDirectory = createTempDir();

            } else if (!backupDirectory.exists() || !backupDirectory.canWrite()) {
                throw new WebApplicationException(
                        serverError().entity(
                                "Backup directory does not exist or is not writable: " +
                                        backupDirectory.getAbsolutePath())
                                .build());
            }

        } else {
            // Backup to a temp directory
            backupDirectory = createTempDir();
        }

        LOGGER.debug("Backing up to: {}", backupDirectory.getAbsolutePath());
        final Collection<Throwable> problems = repositoryService.backupRepository(session.getFedoraSession(),
                backupDirectory);

        if (!problems.isEmpty()) {
            LOGGER.error("Problems backing up the repository:");

            // Report the problems (we'll just print them out) ...
            final String output = problems.stream().map(Throwable::getMessage).peek(LOGGER::error)
                    .collect(joining("\n"));

            throw new WebApplicationException(serverError().entity(output).build());

        }
        return ok()
            .header("Warning", "This endpoint will be moving to an extension module in a future release of Fedora")
            .entity(backupDirectory.getCanonicalPath()).build();
    }
1155303
def resolve_redirects(self, resp, req, stream=False, timeout=None,
                          verify=True, cert=None, proxies=None):
        """"""

        i = 0
        hist = [] # keep track of history

        while resp.is_redirect:
            prepared_request = req.copy()

            if i > 0:
                # Update history and keep track of redirects.
                hist.append(resp)
                new_hist = list(hist)
                resp.history = new_hist

            try:
                resp.content  # Consume socket so it can be released
            except (ChunkedEncodingError, ContentDecodingError, RuntimeError):
                resp.raw.read(decode_content=False)

            if i >= self.max_redirects:
                raise TooManyRedirects('Exceeded %s redirects.' % self.max_redirects)

            # Release the connection back into the pool.
            resp.close()

            url = resp.headers['location']
            method = req.method

            # Handle redirection without scheme (see: RFC 1808 Section 4)
            if url.startswith('//'):
                parsed_rurl = urlparse(resp.url)
                url = '%s:%s' % (parsed_rurl.scheme, url)

            # The scheme should be lower case...
            parsed = urlparse(url)
            url = parsed.geturl()

            # Facilitate relative 'location' headers, as allowed by RFC 7231.
            # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
            # Compliant with RFC3986, we percent encode the url.
            if not parsed.netloc:
                url = urljoin(resp.url, requote_uri(url))
            else:
                url = requote_uri(url)

            prepared_request.url = to_native_string(url)
            # Cache the url, unless it redirects to itself.
            if resp.is_permanent_redirect and req.url != prepared_request.url:
                self.redirect_cache[req.url] = prepared_request.url

            # http://tools.ietf.org/html/rfc7231#section-6.4.4
            if (resp.status_code == codes.see_other and
                    method != 'HEAD'):
                method = 'GET'

            # Do what the browsers do, despite standards...
            # First, turn 302s into GETs.
            if resp.status_code == codes.found and method != 'HEAD':
                method = 'GET'

            # Second, if a POST is responded to with a 301, turn it into a GET.
            # This bizarre behaviour is explained in Issue 1704.
            if resp.status_code == codes.moved and method == 'POST':
                method = 'GET'

            prepared_request.method = method

            # https://github.com/kennethreitz/requests/issues/1084
            if resp.status_code not in (codes.temporary_redirect, codes.permanent_redirect):
                if 'Content-Length' in prepared_request.headers:
                    del prepared_request.headers['Content-Length']

                prepared_request.body = None

            headers = prepared_request.headers
            try:
                del headers['Cookie']
            except KeyError:
                pass

            # Extract any cookies sent on the response to the cookiejar
            # in the new request. Because we've mutated our copied prepared
            # request, use the old one that we haven't yet touched.
            extract_cookies_to_jar(prepared_request._cookies, req, resp.raw)
            prepared_request._cookies.update(self.cookies)
            prepared_request.prepare_cookies(prepared_request._cookies)

            # Rebuild auth and proxy information.
            proxies = self.rebuild_proxies(prepared_request, proxies)
            self.rebuild_auth(prepared_request, resp)

            # Override the original request.
            req = prepared_request

            resp = self.send(
                req,
                stream=stream,
                timeout=timeout,
                verify=verify,
                cert=cert,
                proxies=proxies,
                allow_redirects=False,
            )

            extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)

            i += 1
            yield resp
10941
public static void redirect(String url, boolean copyParameters, ServletRequest req, ServletResponse res)
	{
		if(url == null)
		{
			throw new IllegalArgumentException("URL cannot be null");
		}
		String redirectUrl = url;
		char separator = '?';
		if (redirectUrl.indexOf('?') != -1)
		{
			separator = '&';
		}
		if(copyParameters)
		{
			Enumeration e = req.getParameterNames();
			while (e.hasMoreElements())
			{
				String name = (String) e.nextElement();
				String value = req.getParameter(name);
				redirectUrl += separator + name + '=' + value;
				separator = '&';
			}
			e = req.getAttributeNames();
	/*		while (e.hasMoreElements())
			{
				String name = (String) e.nextElement();
				String value = req.getParameter(name);
				redirectUrl += separator + name + '=' + value;
				separator = '&';
			}  */
		}
		System.out.println(new LogEntry("about to redirect to " + redirectUrl));
		try
		{
			((HttpServletResponse)res).sendRedirect(redirectUrl);
		}
		catch(IOException ioe)
		{
			throw new ResourceException("redirect to '" + redirectUrl + "' failed with message: " +
			ioe.getMessage(), ioe);
		}
	}
1053856
def redirect_stdout(self, enabled=True, log_level=logging.INFO):
        
        if enabled:
            if self.__stdout_wrapper:
                self.__stdout_wrapper.update_log_level(log_level=log_level)
            else:
                self.__stdout_wrapper = StdOutWrapper(logger=self, log_level=log_level)

            self.__stdout_stream = self.__stdout_wrapper
        else:
            self.__stdout_stream = _original_stdout

        # Assign the new stream to sys.stdout
        sys.stdout = self.__stdout_stream
1112158
public void run() {
        try {
            callback.open();
            this.request = getLogRequest(true);
            final HttpResponse response = client.execute(request);
            parseResponse(response);
        } catch (LogCallback.DoneException e) {
            // Signifies we're finished with the log stream.
        } catch (IOException e) {
            callback.error("IO Error while requesting logs: " + e + " " + Thread.currentThread().getName());
        } finally {
            callback.close();
        }
    }
879770
private synchronized PrintStream getPrintStream(long numNewChars) {
        switch (currentStatus) {
            case INIT:

                if (!newLogsOnStart) {

                    // Check if we can fill into an existing file (including a new log header).
                    File primaryFile = getPrimaryFile();
                    if (primaryFile.exists()) {

                        // If maxFileSize is set in bootstrap.properties, then maxFileSizeBytes will have been
                        // updated before this INIT check to that value; otherwise, if maxFileSize was not
                        // set (i.e. default) or it was set in server.xml, then config processing hasn't run
                        // yet, so maxFileSizeBytes will be 0 (there will be an `update` call later). In the
                        // latter case, this means that we might add the logging header (about 1KB) plus
                        // any other messages up until that size update, meaning that we could go
                        // over the configured maxFileSize by a little bit, but this is okay. In that case,
                        // maxFileSizeBytes will be 0, so we'll fill the existing file, and then later on,
                        // it'll roll over if needed.

                        if (maxFileSizeBytes <= 0 || primaryFile.length() + logHeader.length() + numNewChars <= maxFileSizeBytes) {
                            // There's space, so print the header and return the stream.

                            return getPrimaryStream(true);
                        }
                    }
                }

                return createStream(true);
            case ACTIVE:
                if (maxFileSizeBytes > 0) {
                    long bytesWritten = currentCountingStream.count();

                    // Replace the stream if the size is or will likely be
                    // exceeded.  We're estimating one byte per char, which is
                    // only accurate for single-byte character sets.  That's
                    // fine: if a multi-byte character set is being used and
                    // we underestimate the number of bytes that will be
                    // written, we'll roll the log next time.
                    if (bytesWritten + numNewChars > maxFileSizeBytes)
                        return createStream(true);
                }
                break;
            case CLOSED:
                if (checkTime == null) {
                    checkTime = Long.valueOf(Calendar.getInstance().getTimeInMillis());
                } else {
                    long currentTime = Calendar.getInstance().getTimeInMillis();
                    // try to create stream again for every 5 seconds
                    if (currentTime - checkTime.longValue() > 5000L) {
                        checkTime = Long.valueOf(currentTime);
                        // show error for every 10 minutes
                        boolean showError = (retryTime == null) || (currentTime - retryTime.longValue() > 600000L);
                        if (showError)
                            retryTime = Long.valueOf(currentTime);
                        PrintStream ps = createStream(showError);
                        if (this.currentStatus == StreamStatus.ACTIVE) {
                            // stream successfully created
                            Tr.audit(getTc(), "LOG_FILE_RESUMED", new Object[] { getPrimaryFile().getAbsolutePath() });
                            this.checkTime = null;
                            this.retryTime = null;
                        }
                        return ps;
                    }
                }
        }

        return currentPrintStream;
    }
212169
public OutputStream decorateLogger(AbstractBuild build, OutputStream logger) throws IOException, InterruptedException {
        if (Util.isOverridden(ConsoleLogFilter.class, getClass(), "decorateLogger", Run.class, OutputStream.class)) {
            // old client calling newer implementation. forward the call.
            return decorateLogger((Run) build, logger);
        } else {
            // happens only if the subtype fails to override neither decorateLogger method
            throw new AssertionError("The plugin '" + this.getClass().getName() + "' still uses " +
                    "deprecated decorateLogger(AbstractBuild,OutputStream) method. " +
                    "Update the plugin to use setUp(Run,OutputStream) instead.");
        }
    }
180726
LogFileHeader logFileHeader() throws InternalLogException
    {
        if (tc.isEntryEnabled())
            Tr.entry(tc, "logFileHeader", this);

        // Check that the file is actually open
        if (_activeFile == null)
        {
            if (tc.isEntryEnabled())
                Tr.exit(tc, "logFileHeader", "InternalLogException");
            throw new InternalLogException(null);
        }

        final LogFileHeader logFileHeader = _activeFile.logFileHeader();

        if (tc.isEntryEnabled())
            Tr.exit(tc, "logFileHeader", logFileHeader);
        return logFileHeader;
    }
325491
public static void loggerInit(Level level, boolean isRedirectStdOutErr, String format)
      throws IOException {
    // Set the java util logging format
    setLoggingFormat(format);

    // Configure the root logger and its handlers so that all the
    // derived loggers will inherit the properties
    Logger rootLogger = Logger.getLogger("");
    for (Handler handler : rootLogger.getHandlers()) {
      handler.setLevel(level);
    }

    rootLogger.setLevel(level);

    if (rootLogger.getLevel().intValue() < Level.WARNING.intValue()) {
      // zookeeper logging scares me. if people want this, we can patch to config-drive this
      Logger.getLogger("org.apache.zookeeper").setLevel(Level.WARNING);
    }

    // setting logging for http client to be error level
    System.setProperty(
        "org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
    System.setProperty(
        "org.apache.commons.logging.simplelog.log.httpclient.wire", "ERROR");
    System.setProperty(
        "org.apache.commons.logging.simplelog.log.org.apache.http", "ERROR");
    System.setProperty(
        "org.apache.commons.logging.simplelog.log.org.apache.http.headers", "ERROR");

    if (isRedirectStdOutErr) {

      // Remove ConsoleHandler if present, to avoid StackOverflowError.
      // ConsoleHandler writes to System.err and since we are redirecting
      // System.err to Logger, it results in an infinite loop.
      for (Handler handler : rootLogger.getHandlers()) {
        if (handler instanceof ConsoleHandler) {
          rootLogger.removeHandler(handler);
        }
      }

      // now rebind stdout/stderr to logger
      Logger logger;
      LoggingOutputStream los;

      logger = Logger.getLogger("stdout");
      los = new LoggingOutputStream(logger, StdOutErrLevel.STDOUT);
      System.setOut(new PrintStream(los, true));

      logger = Logger.getLogger("stderr");
      los = new LoggingOutputStream(logger, StdOutErrLevel.STDERR);
      System.setErr(new PrintStream(los, true));
    }
  }