/* ------------------------------------------------------------
504718
private void fillPacket() throws IOException
    {
        if (_closed)
            return;

        if (_gotFirst||_in.available()==0)
            _getBodyChunk.write(_out);
        _gotFirst=true;

        // read packet
        if (!_packet.read(_in))
            throw new IOException("EOF");

        if (_packet.unconsumedData()<=0)
            _closed=true;
        else if (_packet.getInt()>_packet.getBufferSize())
            throw new IOException("AJP Protocol error");
    }
991664
@Override
    public void execute() {
        try {
            String str = editor.readLine("Find:");
            editor.findNext(str);
            FindContext.setLastSearch(str);
        } catch (IOException e) {
            //noop
        }
    }
1242475
@Override
  protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
      throws ServletException, IOException {
    final Map<String, Object> ret = new HashMap<>();

    if (hasParam(req, ACTION_PARAM)) {
      final String action = getParam(req, ACTION_PARAM);
      if (action.equals(STATS_SET_REPORTINGINTERVAL)) {
        handleChangeMetricInterval(req, ret);
      } else if (action.equals(STATS_SET_CLEANINGINTERVAL)) {
        handleChangeCleaningInterval(req, ret);
      } else if (action.equals(STATS_SET_MAXREPORTERPOINTS)) {
        handleChangeEmitterPoints(req, ret);
      } else if (action.equals(STATS_GET_ALLMETRICSNAME)) {
        handleGetAllMMetricsName(req, ret);
      } else if (action.equals(STATS_GET_METRICHISTORY)) {
        handleGetMetricHistory(req, ret);
      } else if (action.equals(STATS_SET_ENABLEMETRICS)) {
        handleChangeManagerStatusRequest(req, ret, true);
      } else if (action.equals(STATS_SET_DISABLEMETRICS)) {
        handleChangeManagerStatusRequest(req, ret, false);
      } else {
        ret.put(RESPONSE_ERROR, "Invalid action");
      }
    }

    JSONUtils.toJSON(ret, resp.getOutputStream(), true);
  }
1296870
@Override
    public void init() throws ServletException {

        if (LOG.isInfoEnabled()) {
            LOG.info(Messages.get().getBundle().key(Messages.LOG_INIT_WEBDAV_SERVLET_0));
        }

        String value = null;

        // init parameter: listings
        try {
            value = getServletConfig().getInitParameter(INIT_PARAM_LIST);
            if (value != null) {
                m_listings = Boolean.valueOf(value).booleanValue();
            }
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error(
                    Messages.get().getBundle().key(Messages.LOG_READ_INIT_PARAM_ERROR_2, INIT_PARAM_LIST, value),
                    e);
            }
        }

        if (LOG.isInfoEnabled()) {
            LOG.info(
                Messages.get().getBundle().key(
                    Messages.LOG_READ_INIT_PARAM_2,
                    INIT_PARAM_LIST,
                    Boolean.valueOf(m_listings)));
        }

        // init parameter: read only
        try {
            value = getServletConfig().getInitParameter(INIT_PARAM_READONLY);
            if (value != null) {
                m_readOnly = Boolean.valueOf(value).booleanValue();
            }
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error(
                    Messages.get().getBundle().key(Messages.LOG_READ_INIT_PARAM_ERROR_2, INIT_PARAM_READONLY, value),
                    e);
            }
        }

        if (LOG.isInfoEnabled()) {
            LOG.info(
                Messages.get().getBundle().key(
                    Messages.LOG_READ_INIT_PARAM_2,
                    INIT_PARAM_READONLY,
                    Boolean.valueOf(m_readOnly)));
        }

        // Load the MD5 helper used to calculate signatures.
        try {
            m_md5Helper = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {

            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.ERR_MD5_NOT_AVAILABLE_0), e);
            }

            throw new UnavailableException(Messages.get().getBundle().key(Messages.ERR_MD5_NOT_AVAILABLE_0));
        }

        // Instantiate repository from init-param
        String repositoryName = getInitParameter(INIT_PARAM_REPOSITORY);
        if (repositoryName == null) {

            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.ERR_INIT_PARAM_MISSING_1, INIT_PARAM_REPOSITORY));
            }

            throw new ServletException(
                Messages.get().getBundle().key(Messages.ERR_INIT_PARAM_MISSING_1, INIT_PARAM_REPOSITORY));
        }

        m_repository = OpenCms.getRepositoryManager().getRepository(repositoryName, A_CmsRepository.class);
        if (m_repository == null) {

            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.ERR_REPOSITORY_NOT_FOUND_1, repositoryName));
            }

            throw new ServletException(
                Messages.get().getBundle().key(Messages.ERR_REPOSITORY_NOT_FOUND_1, repositoryName));
        }

        if (LOG.isInfoEnabled()) {
            LOG.info(Messages.get().getBundle().key(Messages.LOG_USE_REPOSITORY_1, repositoryName));
        }
    }
199046
public void init(HttpServletRequest request) {
		resetTimers();
		
		if (request != null) {
			String p = request.getPathInfo();
			final int pathLength = (p == null ? 0 : p.length());
			
			final StringBuffer urlSb = request.getRequestURL();
			String simpleUrl = urlSb.toString(); // without qs
			
			String qs = request.getQueryString();
			if (qs != null) urlSb.append("?").append(qs);
			final String fullUrl = urlSb.toString();
			contextUrl.set(fullUrl);
		
			requestCookies.remove();
			responseCookies.remove();
			
			StringBuilder cookiesDump = new StringBuilder();
			Map<String, Cookie> cookiez = requestCookies.get();
			for (javax.servlet.http.Cookie c : Check.ifNull(request.getCookies(), new javax.servlet.http.Cookie[0])) {
				cookiez.put(c.getName(), new BasicClientCookie(c.getName(), c.getValue()));
				cookiesDump.append(c.toString()).append(";");
			}
	
			String xForwardedFor = request.getHeader(HEADER_X_FORWARDED_FOR);
			clientIp.set(xForwardedFor != null ? xForwardedFor : request.getRemoteAddr());
			
			String xForwardedUrl = request.getHeader(HEADER_X_FORWARDED_URL);
			if (xForwardedUrl != null) {
				int i = xForwardedUrl.lastIndexOf("?");
				simpleUrl = (i == -1 ? xForwardedUrl : xForwardedUrl.substring(0, i));
			}
			
			try {
				simpleUrl = URLDecoder.decode(simpleUrl, "UTF-8"); // convert "%xx" stuff before working with lengths
			} catch (UnsupportedEncodingException e) {
				log.error(e.toString());
			}
			contextPath.set(simpleUrl.substring(0, simpleUrl.length() - pathLength));

			if (verbose) log.info(">>> Time 0 [" + fullUrl + "]. cookies from client: " + cookiesDump.toString());
		}
		
		initialized.set(true);
	}
1018090
@Override
  public void header(String key, String value)
  {
    _is.header(key, value);
  }
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();
            }
        }
    }
182907
public void doInitialKey()
    {
        FileListener nextListener = (FileListener)this.getNextEnabledListener();
        if (nextListener != null)
        {
            boolean bOldState = nextListener.setEnabledListener(false);  // Don't allow it to be called again
            nextListener.doInitialKey();
            nextListener.setEnabledListener(bOldState);
        }
        else if (this.getOwner() != null)
            this.getOwner().doInitialKey();
    }
583638
@SuppressWarnings("unchecked")
    public void init() throws ServletException {
	// Method re-written for PQ47469
	String servlets = getRequiredInitParameter(PARAM_SERVLET_PATHS);
	StringTokenizer sTokenizer = new StringTokenizer(servlets);
	Vector servletChainPath = new Vector();

	while (sTokenizer.hasMoreTokens() == true) {
		String path = sTokenizer.nextToken().trim();
			
		if (path.length() > 0) {
			servletChainPath.addElement(path);
		}
	}

	int chainLength = servletChainPath.size();

	if (chainLength > 0) {
		this.chainPath = new String[chainLength];
			
		for (int index = 0; index < chainLength; ++index) {
			this.chainPath[index] = (String)servletChainPath.elementAt(index);
		}
	}

    }
877972
public void init()
    {
        this.leading = 0;
        while (this.leading < this.value.length() && this.value.charAt(this.leading) == ' ')
        {
            this.leading++;
        }

        if (this.leading == this.value.length())
        {
            this.setEmpty();
        }
        else
        {
            this.isEmpty = false;
            this.trailing = 0;
            while (this.value.charAt(this.value.length() - this.trailing - 1) == ' ')
            {
                this.trailing++;
            }
        }
    }
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);
                }
            }
        }
    }
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.");
        }
    }
495561
@Override
    public void write(final String s) {
        usageFlag = true;
        if (trouble || s == null) {
            return;
        }

        try {
            getOut().write(s);
        }
        catch (IOException e) {
            handleIOException(e);
        }
    }
84608
private void encodeThis() throws IOException {
        if (names == null || names.isEmpty()) {
            this.extensionValue = null;
            return;
        }
        DerOutputStream os = new DerOutputStream();
        names.encode(os);
        this.extensionValue = os.toByteArray();
    }
274300
@Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        StringBuilder cacheControl = new StringBuilder(cacheability.getValue()).append(", max-age=").append(expiration);
        if (mustRevalidate) {
            cacheControl.append(", must-revalidate");
        }

        // Set cache directives
        httpServletResponse.setHeader(HTTPCacheHeader.CACHE_CONTROL.getName(), cacheControl.toString());
        httpServletResponse.setDateHeader(HTTPCacheHeader.EXPIRES.getName(), System.currentTimeMillis() + expiration
                * 1000L);

        // Set Vary field
        if (vary != null && !vary.isEmpty()) {
            httpServletResponse.setHeader(HTTPCacheHeader.VARY.getName(), vary);
        }

        /*
         * By default, some servers (e.g. Tomcat) will set headers on any SSL content to deny caching. Omitting the
         * Pragma header takes care of user-agents implementing HTTP/1.0.
         */
        filterChain.doFilter(servletRequest, new HttpServletResponseWrapper(httpServletResponse) {
            @Override
            public void addHeader(String name, String value) {
                if (!HTTPCacheHeader.PRAGMA.getName().equalsIgnoreCase(name)) {
                    super.addHeader(name, value);
                }
            }

            @Override
            public void setHeader(String name, String value) {
                if (!HTTPCacheHeader.PRAGMA.getName().equalsIgnoreCase(name)) {
                    super.setHeader(name, value);
                }
            }
        });
    }
844314
@Override
  public void execute() {
    super.execute();
    if (output == null) {
      System.err.println(
          "Please add an <output> for the <" + getTaskName() + "> at " + this.getLocation());
      return;
    }

    // Gather output in a buffer rather than generating a bad file with a valid timestamp.
    StringBuilder sb = new StringBuilder();

    // Output the source files that use the helper functions first, so we get the appropriate file
    // overviews and copyright headers.
    for (FileRef input : inputs) {
      try {
        boolean inGeneratedCode = false;
        for (String line : Files.readLines(input.file, Charsets.UTF_8)) {
          // Skip code between generated code markers so that this transformation is idempotent.
          // We can run an old output through this class, and get the latest version out.
          if (inGeneratedCode) {
            if (GENERATED_CODE_END_MARKER.equals(line.trim())) {
              inGeneratedCode = false;
            }
          } else if (GENERATED_CODE_START_MARKER.equals(line.trim())) {
            inGeneratedCode = true;
          } else {
            sb.append(line).append('\n');
          }
        }
      } catch (IOException ex) {
        System.err.println("Failed to read " + input.file);
        ex.printStackTrace();
        return;
      }
    }

    // Generate helper functions for escape directives.
    generateCode(availableIdentifiers, sb);

    // Output a file now that we know generation hasn't failed.
    try {
      Files.asCharSink(output.file, Charsets.UTF_8).write(sb);
    } catch (IOException ex) {
      // Make sure an abortive write does not leave a file w
      output.file.delete();
    }
  }
970680
public function init()
    {
        if ($this->countRows < 1) {
            $this->totalPages = 0;
            $this->currentPage = 0;

            return;
        }

        if ($this->limit < 10) {
            $this->limit = 10;
        }

        $this->totalPages = (int)($this->countRows / $this->limit);

        if ($this->countRows % $this->limit) {
            $this->totalPages++;
        }

        if ($this->totalPages === 0) {
            $this->totalPages = 1;
        }

        if ($this->currentPage < 0) {
            $this->currentPage = 0;
        }

        if ($this->currentPage > $this->totalPages) {
            $this->currentPage = $this->totalPages;
        }
    }