/* -----------------------------------------------------------------
323720
public void write(Writer out)
         throws IOException
    {
        out.write('<'+tag+attributes()+'>');
        super.write(out);
        out.write("</"+tag+"\n>");
    }
319643
public static void main(String[] pArgs) throws IOException {
        // params:
        int timeout = 0;
        boolean followRedirects = true;
        boolean debugHeaders = false;
        String requestPropertiesFile = null;
        String requestHeaders = null;
        String postData = null;
        File putData = null;
        int argIdx = 0;
        boolean errArgs = false;
        boolean writeToFile = false;
        boolean writeToStdOut = false;
        String outFileName = null;

        while ((argIdx < pArgs.length) && (pArgs[argIdx].charAt(0) == '-') && (pArgs[argIdx].length() >= 2)) {
            if ((pArgs[argIdx].charAt(1) == 't') || pArgs[argIdx].equals("--timeout")) {
                argIdx++;
                try {
                    timeout = Integer.parseInt(pArgs[argIdx++]);
                }
                catch (NumberFormatException nfe) {
                    errArgs = true;
                    break;
                }
            }
            else if ((pArgs[argIdx].charAt(1) == 'd') || pArgs[argIdx].equals("--debugheaders")) {
                debugHeaders = true;
                argIdx++;
            }
            else if ((pArgs[argIdx].charAt(1) == 'n') || pArgs[argIdx].equals("--nofollowredirects")) {
                followRedirects = false;
                argIdx++;
            }
            else if ((pArgs[argIdx].charAt(1) == 'r') || pArgs[argIdx].equals("--requestproperties")) {
                argIdx++;
                requestPropertiesFile = pArgs[argIdx++];
            }
            else if ((pArgs[argIdx].charAt(1) == 'p') || pArgs[argIdx].equals("--postdata")) {
                argIdx++;
                postData = pArgs[argIdx++];
            }
            else if ((pArgs[argIdx].charAt(1) == 'u') || pArgs[argIdx].equals("--putdata")) {
                argIdx++;
                putData = new File(pArgs[argIdx++]);
                if (!putData.exists()) {
                    errArgs = true;
                    break;
                }
            }
            else if ((pArgs[argIdx].charAt(1) == 'h') || pArgs[argIdx].equals("--header")) {
                argIdx++;
                requestHeaders = pArgs[argIdx++];
            }
            else if ((pArgs[argIdx].charAt(1) == 'f') || pArgs[argIdx].equals("--file")) {
                argIdx++;
                writeToFile = true;

                // Get optional file name
                if (!((argIdx >= (pArgs.length - 1)) || (pArgs[argIdx].charAt(0) == '-'))) {
                    outFileName = pArgs[argIdx++];
                }
            }
            else if ((pArgs[argIdx].charAt(1) == 'o') || pArgs[argIdx].equals("--output")) {
                argIdx++;
                writeToStdOut = true;
            }
            else {
                System.err.println("Unknown option \"" + pArgs[argIdx++] + "\"");
            }
        }
        if (errArgs || (pArgs.length < (argIdx + 1))) {
            System.err.println("Usage: java  NetUtil [-f|--file [<file name>]] [-d|--debugheaders] [-h|--header <header data>] [-p|--postdata <URL-encoded postdata>] [-u|--putdata <file name>] [-r|--requestProperties <properties file>] [-t|--timeout <miliseconds>] [-n|--nofollowredirects] fromUrl");
            System.exit(5);
        }
        String url = pArgs[argIdx/*++*/];

        // DONE ARGS
        // Get request properties
        Properties requestProperties = new Properties();

        if (requestPropertiesFile != null) {

            // Just read, no exception handling...
            requestProperties.load(new FileInputStream(new File(requestPropertiesFile)));
        }
        if (requestHeaders != null) {

            // Get request headers
            String[] headerPairs = StringUtil.toStringArray(requestHeaders, ",");

            for (String headerPair : headerPairs) {
                String[] pair = StringUtil.toStringArray(headerPair, ":");
                String key = (pair.length > 0)
                        ? pair[0].trim()
                        : null;
                String value = (pair.length > 1)
                        ? pair[1].trim()
                        : "";

                if (key != null) {
                    requestProperties.setProperty(key, value);
                }
            }
        }
        HttpURLConnection conn;

        // Create connection
        URL reqURL = getURLAndSetAuthorization(url, requestProperties);

        conn = createHttpURLConnection(reqURL, requestProperties, followRedirects, timeout);

        // POST
        if (postData != null) {
            // HTTP POST method
            conn.setRequestMethod(HTTP_POST);

            // Set entity headers
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", String.valueOf(postData.length()));
            conn.setRequestProperty("Content-Encoding", "ISO-8859-1");

            // Get outputstream (this is where the connect actually happens)
            OutputStream os = conn.getOutputStream();

            System.err.println("OutputStream: " + os.getClass().getName() + "@" + System.identityHashCode(os));
            OutputStreamWriter writer = new OutputStreamWriter(os, "ISO-8859-1");

            // Write post data to the stream
            writer.write(postData);
            writer.write("\r\n");

            //writer.flush();
            writer.close();  // Does this close the underlying stream?
        }
        // PUT
        else if (putData != null) {
            // HTTP PUT method
            conn.setRequestMethod(HTTP_PUT);

            // Set entity headers
            //conn.setRequestProperty("Content-Type", "???");
            // TODO: Set Content-Type to correct type?
            // TODO: Set content-encoding? Or can binary data be sent directly?
            conn.setRequestProperty("Content-Length", String.valueOf(putData.length()));

            // Get outputstream (this is where the connect actually happens)
            OutputStream os = conn.getOutputStream();

            System.err.println("OutputStream: " + os.getClass().getName() + "@" + System.identityHashCode(os));

            // Write put data to the stream
            FileUtil.copy(new FileInputStream(putData), os);

            os.close();
        }

        //
        InputStream is;

        if (conn.getResponseCode() == 200) {

            // Connect and get stream
            is = conn.getInputStream();
        }
        else {
            is = conn.getErrorStream();
        }

        //
        if (debugHeaders) {
            System.err.println("Request (debug):");
            System.err.println(conn.getClass());
            System.err.println("Response (debug):");

            // Headerfield 0 is response code
            System.err.println(conn.getHeaderField(0));

            // Loop from 1, as headerFieldKey(0) == null...
            for (int i = 1; ; i++) {
                String key = conn.getHeaderFieldKey(i);

                // Seems to be the way to loop through them all...
                if (key == null) {
                    break;
                }
                System.err.println(key + ": " + conn.getHeaderField(key));
            }
        }

        // Create output file if specified
        OutputStream os;

        if (writeToFile) {
            if (outFileName == null) {
                outFileName = reqURL.getFile();
                if (StringUtil.isEmpty(outFileName)) {
                    outFileName = conn.getHeaderField("Location");
                    if (StringUtil.isEmpty(outFileName)) {
                        outFileName = "index";

                        // Find a suitable extension
                        // TODO: Replace with MIME-type util with MIME/file ext mapping
                        String ext = conn.getContentType();

                        if (!StringUtil.isEmpty(ext)) {
                            int idx = ext.lastIndexOf('/');

                            if (idx >= 0) {
                                ext = ext.substring(idx + 1);
                            }
                            idx = ext.indexOf(';');
                            if (idx >= 0) {
                                ext = ext.substring(0, idx);
                            }
                            outFileName += "." + ext;
                        }
                    }
                }
                int idx = outFileName.lastIndexOf('/');

                if (idx >= 0) {
                    outFileName = outFileName.substring(idx + 1);
                }
                idx = outFileName.indexOf('?');
                if (idx >= 0) {
                    outFileName = outFileName.substring(0, idx);
                }
            }
            File outFile = new File(outFileName);

            if (!outFile.createNewFile()) {
                if (outFile.exists()) {
                    System.err.println("Cannot write to file " + outFile.getAbsolutePath() + ", file allready exists.");
                }
                else {
                    System.err.println("Cannot write to file " + outFile.getAbsolutePath() + ", check write permissions.");
                }
                System.exit(5);
            }
            os = new FileOutputStream(outFile);
        }
        else if (writeToStdOut) {
            os = System.out;
        }
        else {
            os = null;
        }

        // Get data.
        if ((writeToFile || writeToStdOut) && is != null) {
            FileUtil.copy(is, os);
        }

        /*
                    Hashtable postData = new Hashtable();
                    postData.put("SearchText", "condition");

                    try {
                        InputStream in = getInputStreamHttpPost(pArgs[argIdx], postData,
                                                             props, true, 0);
                        out = new FileOutputStream(file);
                        FileUtil.copy(in, out);
                    }
                    catch (Exception e) {
                        System.err.println("Error: " + e);
                        e.printStackTrace(System.err);
                        continue;
                    }
         */
    }
455772
@Override
    String sourceContentFor(String aSource, Boolean nullOnMissing) {
        if (this.sourcesContent == null) {
            return null;
        }

        if (this.sourceRoot != null) {
            aSource = Util.relative(this.sourceRoot, aSource);
        }

        if (this._sources.has(aSource)) {
            return this.sourcesContent.get(this._sources.indexOf(aSource));
        }

        ParsedUrl url;
        if (this.sourceRoot != null && ((url = Util.urlParse(this.sourceRoot)) != null)) {
            // XXX: file:// URIs and absolute paths lead to unexpected behavior for
            // many users. We can help them out when they expect file:// URIs to
            // behave like it would if they were running a local HTTP server. See
            // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
            String fileUriAbsPath = aSource.replaceAll("^file://", "");
            if (url.scheme.equals("file") && this._sources.has(fileUriAbsPath)) {
                return this.sourcesContent.get(this._sources.indexOf(fileUriAbsPath));
            }

            if ((url.path == null || url.path.equals("/")) && this._sources.has("/" + aSource)) {
                return this.sourcesContent.get(this._sources.indexOf("/" + aSource));
            }
        }

        // This function is used recursively from
        // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
        // don't want to throw if we can't find the source - we just want to
        // return null, so we provide a flag to exit gracefully.
        if (nullOnMissing != null && nullOnMissing) {
            return null;
        } else {
            throw new RuntimeException("\"" + aSource + "\" is not in the SourceMap.");
        }
    }
1221267
private void initReader(Object obj) {
		if (obj instanceof WorkingDirectoryLocationAware) {
			((WorkingDirectoryLocationAware) obj).setWorkingDirectory(workingDirectory);
		}
		if (obj instanceof ServletContextAware) {
			((ServletContextAware) obj).setServletContext(servletContext);
		}

		if (obj instanceof ResourceBrowser) {
			resourceInfoProviders.add(0, (ResourceBrowser) obj);
		}
	}
640449
private void initReader(Object obj) {
		if (obj instanceof WorkingDirectoryLocationAware) {
			((WorkingDirectoryLocationAware) obj).setWorkingDirectory(workingDirectory);
		}
		if (obj instanceof ServletContextAware) {
			((ServletContextAware) obj).setServletContext(servletContext);
		}

		if (obj instanceof ResourceBrowser) {
			if (obj instanceof ResourceGenerator) {
				resourceGeneratorInfoProviders.add(0, (ResourceBrowser) obj);
			} else {
				servletCtxResourceBrowser = (ResourceBrowser) obj;
			}
		}
	}
1174745
public function onBeforeWrite()
    {
        if (!$this->isInDB()) {
            $this->CreatorID = Member::currentUserID();
        }

        if (!$this->VersionNumber) {
            $versions = DataObject::get(
                'FileVersion', sprintf('"FileID" = %d', $this->FileID)
            );

            if ($versions) {
                $this->VersionNumber = $versions->Count() + 1;
            } else {
                $this->VersionNumber = 1;
            }
        }

        if (!$this->Filename) {
            $this->Filename = $this->saveCurrentVersion();
        }

        parent::onBeforeWrite();
    }
747808
public function init(): void
    {
        parent::init();

        if ($this->default !== '' && $this->default !== null && !is_array($this->default)) {
            try {
                $default = Json::decode($this->default);

                if (is_array($default)) {
                    $this->default = $default;
                }
            } catch (InvalidArgumentException $exception) {}
        }
    }
319111
@Override
    public void onStartup(Set<Class<?>> arg0, ServletContext servletContext) throws ServletException {
        FilterRegistration.Dynamic dynamic =
                        servletContext.addFilter("com.ibm.ws.security.jaspi.servlet.filter", JaspiServletFilter.class);
        dynamic.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*");
        dynamic.setAsyncSupported(true);
    }
84079
public function init()
    {
        parent::init();

        if (($this->module === null) || ($this->match === false)) {
            return;
        }

        $this->module->on(
            Module::EVENT_BEFORE_ACTION,
            function (ActionEvent $event) {
                $this->beforeAction($event);
            }
        );

        $this->module->on(
            Module::EVENT_AFTER_ACTION,
            function (ActionEvent $event) {
                $this->afterAction($event);
            }
        );

        $this->module->on(
            Module::EVENT_PROCESS_FILE,
            function ($event) {
                $this->onProcessFile($event);
            }
        );
    }
329333
private synchronized void initOut() throws IOException
   {
      if (out == null)
      {
         OutputStream os = new IndexOutputStream(dir.createOutput(REDO_LOG));
         out = new BufferedWriter(new OutputStreamWriter(os));
      }
   }
136783
@PostConstruct
    public void process() {
        Collection<BeanDefinition<?>> filterDefinitions = beanContext.getBeanDefinitions(Qualifiers.byStereotype(Filter.class));
        for (BeanDefinition<?> beanDefinition : filterDefinitions) {
            if (HttpClientFilter.class.isAssignableFrom(beanDefinition.getBeanType())) {
                // ignore http client filters
                continue;
            }
            String[] patterns = beanDefinition.getValue(Filter.class, String[].class).orElse(null);
            if (ArrayUtils.isNotEmpty(patterns)) {
                HttpMethod[] methods = beanDefinition.getValue(Filter.class, "methods", HttpMethod[].class).orElse(null);
                String first = patterns[0];
                FilterRoute filterRoute = addFilter(first, () -> beanContext.getBean((Class<HttpFilter>) beanDefinition.getBeanType()));
                if (patterns.length > 1) {
                    for (int i = 1; i < patterns.length; i++) {
                        String pattern = patterns[i];
                        filterRoute.pattern(pattern);
                    }
                }
                if (ArrayUtils.isNotEmpty(methods)) {
                    filterRoute.methods(methods);
                }
            }
        }
    }
419222
private synchronized void lazyInit(HttpServletRequest request) throws IOException {
        List<File> files;
        URL url;
        long lastModified;
        long now;
        Resolver resolver;
        Node localhost;
        FileNode file;
        Object[] tmp;

        resolver = application.resolver;
        if (engine != null && resolver.isLife()) {
            for (Node node : reloadFiles) {
                lastModified = node.getLastModified();
                if (lastModified > loaded) {
                    now = System.currentTimeMillis();
                    if (lastModified > now) {
                        // fail to avoid repeated re-init
                        throw new IOException(node.getUri() + " has lastModifiedDate in the future: "
                                + new Date(lastModified) + "(now: " + new Date(now) + ")");
                    }
                    LOG.info("reloading jasmin for application '" + application.getContextPath() + "' - changed file: " + node);
                    engine = null;
                    resolver.reset();
                }
            }
        }
        if (engine == null) {
            url = new URL(request.getRequestURL().toString());
            try {
                localhost = resolver.getWorld().node(new URI(url.getProtocol(), null, url.getHost(), url.getPort(), "", null, null));
            } catch (URISyntaxException e) {
                throw new IllegalStateException(e);
            }
            tmp = application.createEngine(docroot, localhost);
            engine = (Engine) tmp[0];
            LOG.info("started engine, initial url=" + url);
            for (Module module : engine.repository.modules()) {
                files = module.files();
                if (files.size() > 2) {
                    LOG.warn("deprecated: module '" + module.getName() + "' contains more than 2 file: " + files);
                }
                for (File f : files) {
                    if (f.getNormal() instanceof HttpNode) {
                        LOG.warn("deprecated: module '" + module.getName() + "' uses base LOCALHOST: " + f.getNormal().getUri());
                    }
                }
            }
            if (resolver.isLife()) {
                reloadFiles = (List<Node>) tmp[1];
                file = resolver.getLiveXml();
                if (file != null) {
                    reloadFiles.add(file);
                }
                LOG.info("reload if one of these " + reloadFiles.size() + " files is modified: ");
                for (Node node : reloadFiles) {
                    LOG.info("  " + node.getUri());
                }
                loaded = System.currentTimeMillis();
            }
            if (engine == null) {
                throw new IllegalStateException();
            }
        }
    }
1310192
public void start() {
    if (outputThread != null) {
      outputThread.start();
    }
    if (errorThread != null) {
      errorThread.start();
    }
    if (inputThread != null) {
      inputThread.start();
    }
  }
1298327
@Override
	final protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setBufferSize(BUFFER_SIZE);
		getCount.incrementAndGet();
		try {
			reportingDoGet(req, resp);
		} catch (ThreadDeath t) {
			throw t;
		} catch (RuntimeException | ServletException | IOException e) {
			getLogger().log(Level.SEVERE, null, e);
			throw e;
		} catch (SQLException t) {
			getLogger().log(Level.SEVERE, null, t);
			throw new ServletException(t);
		}
	}
1041449
@Override
  public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
    final ClassLoaderLeakPreventorListener classLoaderLeakPreventorListener = new ClassLoaderLeakPreventorListener();
    try {
      classLoaderLeakPreventorListener.contextInitialized(servletContext); // Initialize immediately

      servletContext.addListener(new ServletContextListener() {
        @Override
        public void contextInitialized(ServletContextEvent servletContextEvent) {
          // Do nothing, already done above
        }

        @Override
        public void contextDestroyed(ServletContextEvent servletContextEvent) {
          classLoaderLeakPreventorListener.contextDestroyed(servletContextEvent);
        }
      });
    }
    catch (Throwable t) { // (Shouldn't really be needed)
      t.printStackTrace(System.err);
    }

    for(ServletContextListener otherListener : ClassLoaderLeakPreventorListener.getDefaultOtherListeners()) {
      servletContext.addListener(otherListener);
    }
  }
1374198
private void init() {
        cacheable = null;
        status = SC_OK;
        cachedResponse = cached.createCachedResponse();
        streamDelegate = new ServletResponseStreamDelegate(this) {
            protected OutputStream createOutputStream() throws IOException {
                // Test if this request is really cacheable, otherwise,
                // just write through to underlying response, and don't cache
                if (isCacheable()) {
                    return cachedResponse.getOutputStream();
                }
                else {
                    cachedResponse.setStatus(status);
                    cachedResponse.writeHeadersTo(CacheResponseWrapper.this.response);
                    return super.getOutputStream();
                }
            }
        };
    }
587529
public void doGet(HttpServletRequest req, HttpServletResponse res) 
		throws ServletException, IOException
	{
		this.doProcess(req, res);
	}