/* ------------------------------------------------------------
327784
private void setTzFormatString(final  TimeZone tz )
    {
        int zIndex = _formatString.indexOf( "ZZZ" );
        if( zIndex >= 0 )
        {
            String ss1 = _formatString.substring( 0, zIndex );
            String ss2 = _formatString.substring( zIndex+3 );
            int tzOffset = tz.getRawOffset();
            
            StringBuffer sb = new StringBuffer(_formatString.length()+10);
            sb.append(ss1);
            sb.append("'");
            if( tzOffset >= 0 )
                sb.append( '+' );
            else
            {
                tzOffset = -tzOffset;
                sb.append( '-' );
            }
            
            int raw = tzOffset / (1000*60);		// Convert to seconds
            int hr = raw / 60;
            int min = raw % 60;
            
            if( hr < 10 )
                sb.append( '0' );
            sb.append( hr );
            if( min < 10 )
                sb.append( '0' );
            sb.append( min );
            sb.append( '\'' );
            
            sb.append(ss2);
            _tzFormatString=sb.toString();            
        }
        else
            _tzFormatString=_formatString;
        setMinFormatString();
    }
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);
		}
	}
282242
@Override public void beforeBlock() {
    if (count > 0) {
      try {
        flush();
      } catch (IOException e) {
        logger.log(Level.SEVERE, "Flush from soy failed", e);
      }
    }
  }
166366
protected void initFilterMapping(XmlParser.Node node)
    {
        String filterName=node.getString("filter-name",false,true);
        String pathSpec=node.getString("url-pattern",false,true);
        String servletName=node.getString("servlet-name",false,true);
        int dispatcher=Dispatcher.__DEFAULT;
        Iterator iter=node.iterator("dispatcher");
        while(iter.hasNext())
        {
            String d=((XmlParser.Node)iter.next()).toString(false,true);
            dispatcher|=Dispatcher.type(d);
        }
            
        FilterHolder holder=(servletName!=null)
                ?getWebApplicationHandler().addFilterServletMapping(servletName, filterName, dispatcher)
                :getWebApplicationHandler().addFilterPathMapping(pathSpec, filterName, dispatcher);
    }
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) {}
        }
    }
466510
private boolean init() throws IOException, CompoundNotFoundException {

		BufferedReader br = new BufferedReader(new FileReader(file));
		br.skip(sequenceStartIndex);
		String sequence = sequenceParser.getSequence(br, sequenceLength);
		setContents(sequence);
		br.close(); // close file to prevent too many being open

		return true;
	}
573405
private static synchronized void init() {
        LOGGER.trace("Reads static resources definition from [static-resources.xml]");

        final File staticResources = Latkes.getWebFile("/WEB-INF/static-resources.xml");
        if (null == staticResources || !staticResources.exists()) {
            throw new IllegalStateException("Not found static resources definition from [static-resources.xml]");
        }

        final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

        try {
            final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            final Document document = documentBuilder.parse(staticResources);
            final Element root = document.getDocumentElement();

            root.normalize();

            final StringBuilder logBuilder = new StringBuilder("Reading static files: [").append(Strings.LINE_SEPARATOR);
            final NodeList includes = root.getElementsByTagName("include");
            for (int i = 0; i < includes.getLength(); i++) {
                final Element include = (Element) includes.item(i);
                String path = include.getAttribute("path");
                final URI uri = new URI("http", "b3log.org", path, null);
                final String s = uri.toASCIIString();
                path = StringUtils.substringAfter(s, "b3log.org");

                STATIC_RESOURCE_PATHS.add(path);

                logBuilder.append("    ").append("path pattern [").append(path).append("]");
                if (i < includes.getLength() - 1) {
                    logBuilder.append(",");
                }
                logBuilder.append(Strings.LINE_SEPARATOR);
            }

            logBuilder.append("]");

            if (LOGGER.isTraceEnabled()) {
                LOGGER.debug(logBuilder.toString());
            }
        } catch (final Exception e) {
            LOGGER.log(Level.ERROR, "Reads [" + staticResources.getName() + "] failed", e);
            throw new RuntimeException(e);
        }

        final StringBuilder logBuilder = new StringBuilder("Static files: [").append(Strings.LINE_SEPARATOR);
        final Iterator<String> iterator = STATIC_RESOURCE_PATHS.iterator();
        while (iterator.hasNext()) {
            final String pattern = iterator.next();

            logBuilder.append("    ").append(pattern);
            if (iterator.hasNext()) {
                logBuilder.append(',');
            }
            logBuilder.append(Strings.LINE_SEPARATOR);
        }
        logBuilder.append("], ").append('[').append(STATIC_RESOURCE_PATHS.size()).append("] path patterns");

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace(logBuilder.toString());
        }

        inited = 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));
        }
    }
587529
public void doGet(HttpServletRequest req, HttpServletResponse res) 
		throws ServletException, IOException
	{
		this.doProcess(req, res);
	}
884038
public void doPost(HttpServletRequest request,
                        HttpServletResponse response) 
        throws ServletException, IOException
    {
        String target=null;

        Log l = LogFactory.getLog(Debug.class);
        
        if (!(l instanceof LogImpl))
            return;
        LogImpl log = (LogImpl) l;
        String action=request.getParameter("Action");
        
        if ("Set Options".equals(action))
        {
            log.setDebug("on".equals(request.getParameter("D")));
            log.setSuppressWarnings("on".equals(request.getParameter("W")));
            String v=request.getParameter("V");
            if (v!=null && v.length()>0)
                log.setVerbose(Integer.parseInt(v));
            else
                log.setVerbose(0);
            log.setDebugPatterns(request.getParameter("P"));


            LogSink[] sinks = log.getLogSinks();
            for (int s=0;sinks!=null && s<sinks.length;s++)
            {
                if (sinks[s]==null)
                    continue;
                
                if ("on".equals(request.getParameter("LSS"+s)))
                {
                    if(!sinks[s].isStarted())
                        try{sinks[s].start();}catch(Exception e){log.warn(e);}
                }
                else
                {
                    if(sinks[s].isStarted())
                        try{sinks[s].stop();}catch(InterruptedException e){}
                }

                String options=request.getParameter("LO"+s);
                if (options==null)
                    options="";
                
                if (sinks[s] instanceof OutputStreamLogSink)
                {
                    OutputStreamLogSink sink=(OutputStreamLogSink)sinks[s];
                    
                    sink.setLogTags("on".equals(request.getParameter("LT"+s)));
                    sink.setLogLabels ("on".equals(request.getParameter("LL"+s)));
                    sink.setLogStackSize("on".equals(request.getParameter("Ls"+s)));
                    sink.setLogStackTrace("on".equals(request.getParameter("LS"+s)));
                    sink.setSuppressStack("on".equals(request.getParameter("SS"+s)));
                    sink.setLogOneLine("on".equals(request.getParameter("SL"+s)));

                    sink.setFilename(request.getParameter("LF"+s));
                }
                
            }
        }
        else if ("Add LogSink".equals(action))
        {
            System.err.println("add log sink "+request.getParameter("LSC"));
            try
            {
                log.add(request.getParameter("LSC"));
            }
            catch(Exception e)
            {
                log.warn(e);
            }
        }
        else if ("Delete Stopped Sinks".equals(action))
        {
            log.deleteStoppedLogSinks();
        }
        
        response.sendRedirect(request.getContextPath()+
                              request.getServletPath()+"/"+
                              Long.toString(System.currentTimeMillis(),36)+
                              (target!=null?("#"+target):""));
    }
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();
    }
485647
private void _ws() throws
      IOException
  {
    builder.type = Type.S;
    // no need to preserve exact whitespace
    // but append an S char to keep the token
    // contract of always having a value
    builder.append(' ');
    reader.forward(NOT_WHITESPACE);

    if (debug)
    {
      int nxt = reader.peek();
      checkArgument(WHITESPACE.matches((char) reader.curChar));
      if (nxt > -1)
      {
        checkArgument(NOT_WHITESPACE.matches((char) nxt));
      }
    }
  }
639565
@Override
	protected StringBuffer doPostProcessBundle(BundleProcessingStatus status, StringBuffer bundleString)
			throws IOException {
		Charset charset = status.getJawrConfig().getResourceCharset();

		// The original JSMin doesn't handle Dos (CRLF) line endings
		// So here we replace the CRLF with LF only
		String bundleContent = bundleString.toString().replaceAll(CR_LF, LF);

		byte[] bundleBytes = bundleContent.getBytes(charset.name());
		ByteArrayInputStream bIs = new ByteArrayInputStream(bundleBytes);
		ByteArrayOutputStream bOs = new ByteArrayOutputStream();

		// Compress data and recover it as a byte array.
		JSMin minifier = new JSMin(bIs, bOs);
		try {
			minifier.jsmin();
		} catch (JSMinException e) {
			formatAndThrowJSLintError(status, bundleBytes, e);
		}
		byte[] minified = bOs.toByteArray();
		return byteArrayToString(charset, minified);
	}
345526
public function execute($action = NULL)
	{
		$action = ($action == NULL)
			? strtolower($this->request->getMethod())
			: $action;

		$this->before();
		$this->{$action}();
		$this->after();
	}
1108393
private void encodeThis() throws IOException {
        DerOutputStream out = new DerOutputStream();
        out.putInteger(skipCerts);
        this.extensionValue = out.toByteArray();
    }
1196252
@Override
	public void run() {
		try {
			byte[] bytes = new byte[8192];

			int pos = 0;

			// Read the first part of the header
			while (true) {
				int read = input.read();
				if (read == -1) {
					break;
				}
				bytes[pos] = (byte) read;
				if (pos >= 4) {
					// Find \r\n\r\n
					if (bytes[pos - 3] == '\r' && bytes[pos - 2] == '\n' && bytes[pos - 1] == '\r' && bytes[pos] == '\n') {
						break;
					}
				}
				pos++;
			}

			// Read from the header data
			BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes, 0, pos)));

			// Read the first line, defined as the status line
			String l = reader.readLine();

			// Sanity check, after not returning data the client MIGHT attempt
			// to send something back and it will end up being something we
			// cannot read.
			if (l == null) {
				sendError(HttpStatus.BAD_REQUEST, HttpStatus.BAD_REQUEST.toString());
				return;
			}

			// Otherwise continue on
			int idx = l.indexOf(' ');

			// Split out the method and path
			String methodString = l.substring(0, idx);
			HttpMethod method = null;

			for (HttpMethod m : HttpMethod.values()) {
				if (m.name().equals(methodString)) {
					method = m;
				}
			}

			// If it's an unknown method it won't be defined in the enum
			if (method == null) {
				sendError(HttpStatus.METHOD_NOT_ALLOWED, "This server currently does not support this method.");
				return;
			}

			// The URI
			String path = l.substring(idx + 1, l.lastIndexOf(' '));

			// Parse the headers
			Map<String, String> headers = new HashMap<String, String>();
			while ((l = reader.readLine()) != null) {
				// End header.
				if (l.equals(""))
					break;

				// Headers are usually Key: Value
				String key = l.substring(0, l.indexOf(':'));
				String value = l.substring(l.indexOf(':') + 1).trim();

				// Put the header in the map, correcting the header key if
				// needed.
				headers.put(HttpUtil.capitalizeHeader(key), value);
			}

			// Close the reader used for the header
			reader.close();

			HttpRequest request = new HttpRequest(this, method, path, headers);

			int questionIdx = path.indexOf('?');
			if (questionIdx != -1) {
				String queryString = path.substring(questionIdx + 1);
				request.setQueryString(queryString);
				request.setGetData(HttpUtil.parseData(queryString));

				path = path.substring(0, questionIdx);
				request.setUri(path);
			}

			// Parse cookies, only if the server has the capability enabled (to save time, processing power, and memory if it isn't used)
			if (headers.containsKey(HttpHeader.COOKIE) && server.hasCapability(HttpCapability.COOKIES)) {
				List<HttpCookie> cookies = new LinkedList<HttpCookie>();
				StringTokenizer tok = new StringTokenizer(headers.get(HttpHeader.COOKIE), ";");
				while (tok.hasMoreTokens()) {
					String token = tok.nextToken();
					int eqIdx = token.indexOf('=');
					if (eqIdx == -1) {
						// Invalid cookie
						continue;
					}
					String key = token.substring(0, eqIdx);
					String value = token.substring(eqIdx + 1);

					cookies.add(new HttpCookie(key, value));
				}
				request.setCookies(cookies);
			}

			// Read the request data
			if (method == HttpMethod.POST) {
				boolean acceptsStandard = server.hasCapability(HttpCapability.STANDARD_POST), acceptsMultipart = server.hasCapability(HttpCapability.MULTIPART_POST);
				// Make sure the server will accept POST or Multipart POST
				// before we start checking the content
				if (acceptsStandard || acceptsMultipart) {
					// Validate that there's a length header
					if (!headers.containsKey(HttpHeader.CONTENT_LENGTH)) {
						// If there isn't, send the correct response
						sendError(HttpStatus.LENGTH_REQUIRED, HttpStatus.LENGTH_REQUIRED.toString());
					} else {
						// Otherwise, continue on
						int contentLength = Integer.parseInt(headers.get(HttpHeader.CONTENT_LENGTH));

						String contentTypeHeader = headers.get(HttpHeader.CONTENT_TYPE);

						// Copy it to trim to what we need, keeping the original
						// to parse the boundary
						String contentType = contentTypeHeader;

						if (contentTypeHeader.indexOf(';') != -1) {
							contentType = contentTypeHeader.substring(0, contentTypeHeader.indexOf(';'));
						}
						// Check the content type
						if (contentType.equalsIgnoreCase("multipart/form-data")) {
							if (acceptsMultipart) {
								// The server will accept post requests with
								// multipart data
								String boundary = contentTypeHeader.substring(contentTypeHeader.indexOf(';')).trim();
								boundary = boundary.substring(boundary.indexOf('=') + 1);
								// Parse file uploads etc.
								request.setPostData(readMultipartData(boundary));
							} else {
								// The server has the multipart post
								// capabilities disabled
								sendError(HttpStatus.BAD_REQUEST, "This server does not support multipart/form-data requests.");
							}
						} else {
							if (acceptsStandard) {
								// Read the reported content length, TODO some
								// kind of check/timeout to make sure it won't
								// hang the thread?
								byte[] b = new byte[contentLength];
								int read, totalRead = 0;
								while (contentLength - totalRead > 0 && (read = input.read(b, totalRead, contentLength - totalRead)) > -1) {
									totalRead += read;
								}
								// We either read all of the data, or the
								// connection closed.
								if (totalRead < contentLength) {
									sendError(HttpStatus.BAD_REQUEST, "Unable to read correct amount of data!");
								} else {
									String data = new String(b);
									if (contentType.equalsIgnoreCase("application/x-www-form-urlencoded")) {
										// It is FOR SURE regular data.
										request.setPostData(HttpUtil.parseData(data));
									} else {
										// Could be JSON or XML etc
										request.setData(data);
									}
								}
							} else {
								// The server has the Standard post capabilities
								// disabled
								sendError(HttpStatus.BAD_REQUEST, "This server does not support POST requests.");
							}
						}
					}
				} else {
					// The server has the Standard and Multipart capabilities
					// disabled
					sendError(HttpStatus.METHOD_NOT_ALLOWED, "This server does not support POST requests.");
				}
			}

			this.request = request;

			server.dispatchRequest(request);
		} catch (SocketException e) {
			//Socket was closed probably
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
1155837
public function init(): void
    {
        if ($this->sourcePath !== null) {
            $this->sourcePath = $this->findPath($this->sourcePath);
        }
        if ($this->basePath !== null) {
            $this->basePath = $this->findPath($this->basePath);
        }
        if ($this->baseUrl !== null) {
            $this->baseUrl = rtrim(Yii::getAlias($this->baseUrl), '/');
        }
    }