/* ------------------------------------------------------------
556215
private static String value(String nameEqualsValue) {
        int idx = nameEqualsValue.indexOf('=');
        String value = nameEqualsValue.substring(idx + 1).trim();
        return QuotedStringTokenizer.unquoteOnly(value);
    }
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;
                    }
         */
    }
1374179
public function process()
    {
        parent::process();

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

        $float_value = $this->getNumericValue($this->value);

        if ($float_value === null) {
            $this->addMessage($this->getValidationMessage('float'));
        } else {
            $this->value = $float_value;
        }
    }
329333
private synchronized void initOut() throws IOException
   {
      if (out == null)
      {
         OutputStream os = new IndexOutputStream(dir.createOutput(REDO_LOG));
         out = new BufferedWriter(new OutputStreamWriter(os));
      }
   }
1070896
private void requestInitialized(ServletRequest request)
    {
        ServletRequestEvent event = new ServletRequestEvent(_servletContext,request);
        for (int i=0;i<LazyList.size(_requestListeners);i++)
            ((ServletRequestListener)LazyList.get(_requestListeners,i))
                        .requestInitialized(event);
    }
282467
@Override
	protected StringBuffer doPostProcessBundle(BundleProcessingStatus status, StringBuffer bundleData)
			throws IOException {

		Matcher matcher = CHARSET_DECLARATION.matcher(bundleData.toString());
		StringBuffer sb = new StringBuffer();
		String currentCharset = null;
		boolean charsetDefinedAtBegining = false;
		while (matcher.find()) {
			if (matcher.start() == 0) {
				currentCharset = matcher.group(1);
				charsetDefinedAtBegining = true;
			} else {
				if (currentCharset != null) {
					if (!currentCharset.equalsIgnoreCase(matcher.group(1))) {
						LOGGER.warn("The bundle '" + status.getCurrentBundle().getId()
								+ "' contains CSS with different charset declaration.");
					}
				} else {
					currentCharset = matcher.group(1);
					LOGGER.warn("For the bundle '" + status.getCurrentBundle().getId()
							+ "', the charset declaration is not defined at the top. The charset which will be set is '"
							+ currentCharset + "'.");
				}

				matcher.appendReplacement(sb, "");
			}
		}
		matcher.appendTail(sb);

		// Put the declaration on top
		if (currentCharset != null && !charsetDefinedAtBegining) {
			sb = new StringBuffer(
					CHARSET_DECLARATION_PREFIX + currentCharset + CHARSET_DECLARATION_SUFFIX + "\n" + sb.toString());
		}
		return sb;
	}
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;
			}
		}
	}
1033482
public function process()
    {
        parent::process();

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

        try {
            $integer_value = $this->getNumericValue($this->value);

            if ($integer_value === null) {
                $this->addMessage($this->getValidationMessage('integer'));
            } else {
                $this->value = $integer_value;
            }
        } catch (SwatIntegerOverflowException $e) {
            if ($e->getSign() > 0) {
                $this->addMessage(
                    $this->getValidationMessage('integer-maximum')
                );
            } else {
                $this->addMessage(
                    $this->getValidationMessage('integer-minimum')
                );
            }

            $integer_value = null;
        }
    }
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);
    }
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);
    }
  }
1349210
@Override
    public void clear() {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
            Tr.event(tc, "Clearing this request: " + this);
        }
        super.clear();
        this.myMethod = MethodValues.UNDEF;
        this.myScheme = null;
        this.myURIBytes = SLASH;
        this.myURIString = null;
        this.myQueryBytes = null;
        this.queryParams = null;
        this.sUrlHost = null;
        this.sHdrHost = null;
        this.iUrlPort = HeaderStorage.NOTSET;
        this.iHdrPort = NOT_TESTED;
    }
722431
@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		//-- 处理请求，如果处理失败（无对应的Action），继续后续步骤
		if(false == ActionContext.handle(req, res)) {
			chain.doFilter(req, res);
		}
	}
1310192
public void start() {
    if (outputThread != null) {
      outputThread.start();
    }
    if (errorThread != null) {
      errorThread.start();
    }
    if (inputThread != null) {
      inputThread.start();
    }
  }
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));
      }
    }
  }
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);
        }
    }
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);
		}
	}
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");
    }