/* ------------------------------------------------------------
352275
public void setBufferSize(int size)
    {
        HttpOutputStream out = (HttpOutputStream)_httpResponse.getOutputStream();
        if (out.isWritten()  || _writer!=null && _writer.isWritten())
            throw new IllegalStateException("Output written");
        out.setBufferSize(size);
    }
362130
public function process()
    {
        parent::process();

        $data = &$this->getForm()->getFormData();

        if (!isset($data[$this->id])) {
            return;
        }

        $this->value = $data[$this->id];
        $length = $this->getValueLength();

        if ($length === 0) {
            $this->value = null;
        }

        if ($this->required && $length === 0) {
            $message = $this->getValidationMessage('required');
            $this->addMessage($message);
        } elseif ($this->maxlength !== null && $length > $this->maxlength) {
            $message = $this->getValidationMessage('too-long');
            $message->primary_content = sprintf(
                $message->primary_content,
                $this->maxlength
            );

            $this->addMessage($message);
        }
    }
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;
    }
1293545
@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String pathInfo = req.getPathInfo();
        if ( pathInfo == null ) {
            String dbg = req.getRequestURI();
            resp.sendRedirect(dbg +"/");
            return;
        }
        Resource resource = null;
        if ( "".equals(pathInfo) || "/".equals(pathInfo) ) {
            resource = dynamicResourceManager.getResource(pathInfo + "index.html");
        } else {
            resource = dynamicResourceManager.getResource(pathInfo);
        }
        if ( resource != null) {
            Long contentLength = resource.getContentLength();
            if ( contentLength != null ) {
                resp.setContentLength((int)contentLength.longValue());
            }
            byte bytes[] = null;
            if ( resource instanceof DynamicResourceManager.MyResource) {
                bytes = ((DynamicResourceManager.MyResource) resource).getBytes();
            } else if ( resource.getFile() != null ) {
                bytes = FileUtil.readFully(resource.getFile());
            }
            // FIXME: mimetype, lastModified / 304
            if ( bytes != null ) {
                ServletOutputStream out = resp.getOutputStream();
                out.write(bytes);
                out.flush();
                out.close();
                return;
            }
        }
        Log.Error(this,"Unhandled resource");
        unhandledGet(req,resp);
    }
516212
@Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Context context =
                ReadOnlyContext.getContext(Constants.HTTP_REQUEST.REST.uri,
                                           request);
        try {
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload();

            // Parse the request, looking for "file"
            InputStream in = null;
            FileItemIterator iter = upload.getItemIterator(request);
            while (in == null && iter.hasNext()) {
                FileItemStream item = iter.next();
                logger.info("Got next item: isFormField={} fieldName={}", item.isFormField(), item.getFieldName());
                if (!item.isFormField() && item.getFieldName().equals("file")) {
                    in = item.openStream();
                }
            }
            if (in == null) {
                sendResponse(HttpServletResponse.SC_BAD_REQUEST,
                             "No data sent.",
                             response);
            } else {
                sendResponse(HttpServletResponse.SC_CREATED,
                             m_management.putTempStream(context, in),
                             response);
            }
        } catch (AuthzException ae) {
            throw RootException.getServletException(ae,
                                                    request,
                                                    "Upload",
                                                    EMPTY_STRING_ARRAY);
        } catch (Exception e) {
            e.printStackTrace();
            sendResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e
                    .getClass().getName()
                    + ": " + e.getMessage(), response);
        }
    }
1264890
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException
	{
		servletRequest.setCharacterEncoding("UTF-8");
		httpRequest.set(servletRequest);
		httpResponse.set(servletResponse);

		Request appRequest = null;
		try
		{
//			String sessionToken = ServletSupport.getSessionTokenFromCookie(servletRequest);
			String sessionToken = ServletSupport.getCookieValue(servletRequest, SESSION_TOKEN_KEY);
			String userId = ServletSupport.getCookieValue(servletRequest, USER_ID_KEY);
			if("".equals(sessionToken))
			{
				sessionToken = null;
			}
			if("".equals(userId))
			{
				userId = null;
			}
 			if(accessManager != null) {
				appRequest = accessManager.bindRequest(this);
//				System.out.println("request bound!! " + appRequest);
				Session session = appRequest.resolveSession(sessionToken, userId);
			}

			if (this.syncUserPrefs &&  appRequest.getTimesEntered() == 0)
			{
				//pass user preferences here
				ServletSupport.importCookieValues(servletRequest,  appRequest.getUserSettings());
				ServletSupport.exportCookieValues(servletResponse,  appRequest.getUserSettings(), "/", userPrefsMaxAge, Arrays.asList(new String[]{SESSION_TOKEN_KEY}));
			}

			//if a user logged in, the user id must be stored
			if(userId == null)
			{
				User user = appRequest.getUser();
				if(user != null)
				{
					storeSessionDataInCookie(USER_ID_KEY, user.getId(), servletResponse);
				}
			}

			//role based access control
	//		checkAccess(servletRequest,  appRequest);

			//delegate request
			chain.doFilter(servletRequest, servletResponse);
		}
		catch (Throwable t)//make sure user gets a controlled response
		{
			//is this the actual entry point or is this entry point wrapped?
			if ( appRequest != null &&  appRequest.getTimesEntered() > 1)
			{
				//it's wrapped, so the exception must be thrown at the top entry point
				ServletSupport.rethrow(t);
			}
			handleException(servletRequest, servletResponse, t);
		}
		finally
		{
/*			if(loggingEnabled)
			{
				application.log(new PageVisitLogEntry((HttpServletRequest) servletRequest));
			}
			application.releaseRequest();  */
			if(accessManager != null) {
				accessManager.releaseRequest();
			}
		}
	}
84854
@Override
    protected void doPost(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException {
        LOG.debug("Entering");
        final AtomHandler handler = createAtomRequestHandler(req, res);
        final String userName = handler.getAuthenticatedUsername();
        if (userName != null) {
            final AtomRequest areq = new AtomRequestImpl(req);
            try {
                if (handler.isCollectionURI(areq)) {

                    if (req.getContentType().startsWith("application/atom+xml")) {

                        // parse incoming entry
                        final Entry entry = Atom10Parser.parseEntry(new BufferedReader(new InputStreamReader(req.getInputStream(), "UTF-8")), null, Locale.US);

                        // call handler to post it
                        final Entry newEntry = handler.postEntry(areq, entry);

                        // set Location and Content-Location headers
                        for (final Object element : newEntry.getOtherLinks()) {
                            final Link link = (Link) element;
                            if ("edit".equals(link.getRel())) {
                                res.addHeader("Location", link.getHrefResolved());
                                break;
                            }
                        }
                        for (final Object element : newEntry.getAlternateLinks()) {
                            final Link link = (Link) element;
                            if ("alternate".equals(link.getRel())) {
                                res.addHeader("Content-Location", link.getHrefResolved());
                                break;
                            }
                        }

                        // write entry back out to response
                        res.setStatus(HttpServletResponse.SC_CREATED);
                        res.setContentType("application/atom+xml; type=entry; charset=utf-8");

                        final Writer writer = res.getWriter();
                        Atom10Generator.serializeEntry(newEntry, writer);
                        writer.close();

                    } else if (req.getContentType() != null) {

                        // get incoming title and slug from HTTP header
                        final String title = areq.getHeader("Title");

                        // create new entry for resource, set title and type
                        final Entry resource = new Entry();
                        resource.setTitle(title);
                        final Content content = new Content();
                        content.setType(areq.getContentType());
                        resource.setContents(Collections.singletonList(content));

                        // hand input stream off to hander to post file
                        final Entry newEntry = handler.postMedia(areq, resource);

                        // set Location and Content-Location headers
                        for (final Object element : newEntry.getOtherLinks()) {
                            final Link link = (Link) element;
                            if ("edit".equals(link.getRel())) {
                                res.addHeader("Location", link.getHrefResolved());
                                break;
                            }
                        }
                        for (final Object element : newEntry.getAlternateLinks()) {
                            final Link link = (Link) element;
                            if ("alternate".equals(link.getRel())) {
                                res.addHeader("Content-Location", link.getHrefResolved());
                                break;
                            }
                        }

                        res.setStatus(HttpServletResponse.SC_CREATED);
                        res.setContentType("application/atom+xml; type=entry; charset=utf-8");

                        final Writer writer = res.getWriter();
                        Atom10Generator.serializeEntry(newEntry, writer);
                        writer.close();

                    } else {
                        res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "No content-type specified in request");
                    }

                } else {
                    res.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid collection specified in request");
                }
            } catch (final AtomException ae) {
                res.sendError(ae.getStatus(), ae.getMessage());
                LOG.debug("An error occured while processing POST", ae);
            } catch (final Exception e) {
                res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
                LOG.debug("An error occured while processing POST", e);
            }
        } else {
            res.setHeader("WWW-Authenticate", "BASIC realm=\"AtomPub\"");
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
        LOG.debug("Exiting");
    }
90742
@Override
  public void setHeader(String key, String value)
  {
    int tail;

    if (_headerSize > 0) {
      tail = (_headerValues[_headerSize - 1].offset()
              + _headerValues[_headerSize - 1].length());
    }
    else {
      tail = 0;
    }

    int keyLength = key.length();
    int valueLength = value.length();
    char []headerBuffer = _headerBuffer;
    
    for (int i = keyLength - 1; i >= 0; i--) {
      headerBuffer[tail + i] = key.charAt(i);
    }

    _headerKeys[_headerSize].init(headerBuffer, tail, keyLength);

    tail += keyLength;

    for (int i = valueLength - 1; i >= 0; i--) {
      headerBuffer[tail + i] = value.charAt(i);
    }

    _headerValues[_headerSize].init(headerBuffer, tail, valueLength);
    _headerSize++;
    // XXX: size
  }
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();
    }
345526
public function execute($action = NULL)
	{
		$action = ($action == NULL)
			? strtolower($this->request->getMethod())
			: $action;

		$this->before();
		$this->{$action}();
		$this->after();
	}
53301
protected final static void init(HttpServletRequest req) {
		// -- 字符集的过滤
		String charset = HuluSetting.charset;
		try {
			req.setCharacterEncoding(charset);
		} catch (Exception e) {
			log.warn("Charset [{}] not support!", charset);
		}
		servletRequestLocal.set(req);
		
		if(isMultipart()){
			try {
				multipartFormDataLocal.set(parseMultipart());
			} catch (IOException e) {
				throw new ActionRuntimeException(e);
			}
		}
	}
1018090
@Override
  public void header(String key, String value)
  {
    _is.header(key, value);
  }
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));
      }
    }
  }
106579
@Override
  protected void initRequest()
  {
    super.initRequest();
    
    _state = _state.toActive();
    
    // HttpBufferStore httpBuffer = getHttpBufferStore();
    HttpBufferStore bufferStore = getHttpBufferStore();

    _method.clear();
    _methodString = null;
    _protocol.clear();

    _uriLength = 0;
    if (bufferStore == null) {
      // server/05h8
      _uri = getSmallUriBuffer(); // httpBuffer.getUriBuffer();
      
      _headerBuffer = getSmallHeaderBuffer(); // httpBuffer.getHeaderBuffer();
      _headerKeys = getSmallHeaderKeys();     // httpBuffer.getHeaderKeys();
      _headerValues = getSmallHeaderValues(); // httpBuffer.getHeaderValues();
    }

    _uriHost.clear();
    _host = null;
    _keepalive = KeepaliveState.INIT;

    _headerSize = 0;
    _headerLength = 0;
    
    _inOffset = 0;
    _isChunkedIn = false;
    _isFirst = true;
  }
938915
public void initImpl()
  {
    if (_level == null) {
      return;
    }
    
    if (_names.size() == 0) {
      _names.add("");
    }
    
    for (String name : _names) {
      _logger = Logger.getLogger(name);
    
      if (_level != null) {
        _logger.setLevel(_level);
      }

      if (_useParentHandlers != null) {
        _logger.setUseParentHandlers(_useParentHandlers.booleanValue());
      }
    
      for (Handler handler : _handlerList) {
        _logger.addHandler(handler);
      }
    
      if (_filter != null) {
        _logger.setFilter(_filter);
      }
    }
  }
1052544
@Override
    protected void initInputSource(WstxInputSource newInput, boolean isExt, String entityId)
        throws XMLStreamException
    {
        if (mFlattenWriter != null) {
            // Anything to flush from previous buffer contents?
            mFlattenWriter.flush(mInputBuffer, mInputPtr);
            mFlattenWriter.disableOutput();
            try {
                /* Then let's let base class do the 'real' input source setup;
                 * this includes skipping of optional XML declaration that we
                 * do NOT want to output
                 */
                super.initInputSource(newInput, isExt, entityId);
            } finally {
                // This will effectively skip declaration
                mFlattenWriter.enableOutput(mInputPtr);
            }
        } else {
            super.initInputSource(newInput, isExt, entityId);
        }
    }
1205071
public function write() {
        $this->getAbstractClass()->write();
        $child = $this->buildChild();
        if(!file_exists($child->getFileName())) {
            $child->write();
        }
        $this->buildTestTable()->write();
        $this->getValidationClass()->write();
        if(!file_exists($this->getValidationChildClass()->getFileName())) {
            $this->getValidationChildClass()->write();
        }
    }