获取请求参数
@param request
@param inputStream
@return
@throws IOException
973204
public static Map<String, Object> getParametersMap(ContainerRequestContext requestContext,HttpServletRequest request)
			throws IOException {
		
		if(isMultipartContent(request)){
			return buildQueryParamsMap(request);
		}
		
		Map<String, Object> parameters = buildQueryParamsMap(request);
		
		if (RestConst.GET_METHOD.equals(request.getMethod())) {
			return parameters;
		}else if (RestConst.POST_METHOD.equals(request.getMethod())) {
			
			byte[] byteArray = IOUtils.toByteArray(requestContext.getEntityStream());
			//reset InputStream
			requestContext.setEntityStream(new ByteArrayInputStream(byteArray));
			
			if(byteArray == null || byteArray.length == 0)return parameters;
			String content = new String(byteArray);
			//JSON 
//			try {
//				return JsonUtils.toObject(content, Map.class);
//			} catch (Exception e) {}
			if(content.contains("{")){
				content = StringUtils.left(content, 2048).trim();
				if(!content.endsWith("}"))content = content + "...\n}";
				parameters.put("data", content);
				return parameters;
			}
			
			String[] split = content.split("\\&");
			for (String s : split) {
				String[] split2 = s.split("=");
				if (split2.length == 2 && StringUtils.isNotBlank(split2[1])) {
					parameters.put(split2[0], split2[1]);
				}
			}
			return parameters;
		
		}
		return null;
	}
1111536
public static byte[] streamBytes(InputStream stream) throws IOException {

		ByteArrayOutputStream bytes = new ByteArrayOutputStream();

		copyStream(stream, bytes);

		return bytes.toByteArray();
	}
65939
protected Optional<MutableHttpResponse<?>> handleRequest(HttpRequest request) {
        HttpHeaders headers = request.getHeaders();
        Optional<String> originHeader = headers.getOrigin();
        if (originHeader.isPresent()) {

            String requestOrigin = originHeader.get();
            boolean preflight = CorsUtil.isPreflightRequest(request);

            Optional<CorsOriginConfiguration> optionalConfig = getConfiguration(requestOrigin);

            if (optionalConfig.isPresent()) {
                CorsOriginConfiguration config = optionalConfig.get();

                HttpMethod requestMethod = request.getMethod();

                List<HttpMethod> allowedMethods = config.getAllowedMethods();

                if (!isAnyMethod(allowedMethods)) {
                    HttpMethod methodToMatch = preflight ? headers.getFirst(ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.class).orElse(requestMethod) : requestMethod;
                    if (allowedMethods.stream().noneMatch(method -> method.equals(methodToMatch))) {
                        return Optional.of(HttpResponse.status(HttpStatus.FORBIDDEN));
                    }
                }

                if (preflight) {
                    Optional<List> accessControlHeaders = headers.get(ACCESS_CONTROL_REQUEST_HEADERS, Argument.of(List.class, String.class));

                    List<String> allowedHeaders = config.getAllowedHeaders();

                    if (!isAny(allowedHeaders) && accessControlHeaders.isPresent()) {
                        if (!accessControlHeaders.get().stream()
                            .allMatch(header -> allowedHeaders.stream()
                                .anyMatch(allowedHeader -> allowedHeader.equals(header.toString().trim())))) {
                            return Optional.of(HttpResponse.status(HttpStatus.FORBIDDEN));
                        }
                    }

                    MutableHttpResponse<Object> ok = HttpResponse.ok();
                    handleResponse(request, ok);
                    return Optional.of(ok);
                }
            }
        }

        return Optional.empty();
    }
754160
@Override
    public InputStream getInputStream() throws IOException {
        ServletRESTRequestImpl ret = castRequest();
        if (ret != null)
            return ret.getInputStream();
        return null;
    }
139882
private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content)
            throws IOException {
        // Validate the requested file ------------------------------------------------------------

        // Get requested file by path info.
        String requestedFile = request.getPathInfo();
        if (logger.isDebugEnabled()) {
            logger.debug("Requested path:" + requestedFile);
        }

        // Check if file is actually supplied to the request URL.
        if (requestedFile == null) {
            logger.debug("No file requested, return 404.");
            // Do your thing if the file is not supplied to the request URL.
            // Throw an exception, or send 404, or show default/warning page, or just ignore it.
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        Configuration rootConfiguration = (Configuration) request.getServletContext().getAttribute(Configuration.class.getName());
        Configuration runtimeConfiguration = rootConfiguration.subset("runtime-settings");

        String basePath = runtimeConfiguration.getString("cache-path");
        int bufferSize = runtimeConfiguration.getInteger("cache-buffer-size", DEFAULT_BUFFER_SIZE);
        long expireTime = runtimeConfiguration.getLong("cache-expire-time", DEFAULT_EXPIRE_TIME);

        // URL-decode the file name (might contain spaces and on) and prepare file object.
        String fDecodedPath = URLDecoder.decode(requestedFile, "UTF-8");
        File file = new File(basePath, fDecodedPath);

        // Check if file actually exists in filesystem.
        if (!file.exists()) {
            logger.debug("Requested file not found, return 404.");
            // Do your thing if the file appears to be non-existing.
            // Throw an exception, or send 404, or show default/warning page, or just ignore it.
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // Prepare some variables. The ETag is an unique identifier of the file.
        String fileName = file.getName();
        long length = file.length();
        long lastModified = file.lastModified();
        String eTag = fileName + "_" + length + "_" + lastModified;
        long expires = System.currentTimeMillis() + expireTime;

        // Validate request headers for caching ---------------------------------------------------
        // If-None-Match header should contain "*" or ETag. If so, then return 304.
        String ifNoneMatch = request.getHeader("If-None-Match");
        if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
            logger.debug("IfNoneMatch/Etag not matching, return 304.");
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            response.setHeader("ETag", eTag); // Required in 304.
            response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
            return;
        }

        // If-Modified-Since header should be greater than LastModified. If so, then return 304.
        // This header is ignored if any If-None-Match header is specified.
        long ifModifiedSince = request.getDateHeader("If-Modified-Since");
        if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
            logger.debug("IfModifiedSince not matching, return 304.");
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            response.setHeader("ETag", eTag); // Required in 304.
            response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
            return;
        }

        // Validate request headers for resume ----------------------------------------------------
        // If-Match header should contain "*" or ETag. If not, then return 412.
        String ifMatch = request.getHeader("If-Match");
        if (ifMatch != null && !matches(ifMatch, eTag)) {
            logger.debug("ifMatch not matching, return 412.");
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }

        // If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
        long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
        if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
            logger.debug("ifUnmodifiedSince not matching, return 412.");
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }

        // Prepare and initialize response --------------------------------------------------------
        // Get content type by file name and content disposition.
        String contentType = getServletContext().getMimeType(fileName);
        String disposition = "inline";

        // If content type is unknown, then set the default value.
        // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
        // To add new content types, add new mime-mapping entry in web.xml.
        if (contentType == null) {
            contentType = "application/octet-stream";
        }

        // If content type is text, expand content type with the one and right character encoding.
        if (contentType.startsWith("text")) {
            contentType += ";charset=UTF-8";
        } // Else, expect for images, determine content disposition. If content type is supported by
        // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
        else if (!contentType.startsWith("image")) {
            String accept = request.getHeader("Accept");
            disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
        }

        // Initialize response.
        response.reset();
        response.setBufferSize(bufferSize);
        response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("ETag", eTag);
        response.setDateHeader("Last-Modified", lastModified);
        response.setDateHeader("Expires", expires);

        // Send requested file (part(s)) to client ------------------------------------------------
        // Prepare streams.
        FileInputStream input = null;
        OutputStream output = null;

        if (content) {
            logger.debug("Content requested,streaming.");
            // Open streams.
            input = new FileInputStream(file);
            output = response.getOutputStream();
            long streamed = stream(input, output, bufferSize);
            if (logger.isDebugEnabled()) {
                logger.debug("Bytes streamed:" + streamed);
            }
        }

    }
130249
@Deprecated
    public static InputStream inputStreamForRequest(InputStream is,
            AmazonWebServiceRequest req) {
        return req == null
             ? is
             : inputStreamForRequest(is, req.getGeneralProgressListener());
    }
686713
private MultipartParsingResult parseRequest(HttpRequest request) throws MultipartException {
        String encoding = determineEncoding(request);
        FileUpload fileUpload = prepareFileUpload(encoding);
        try {
            RequestBody body = request.getBody();
            Assert.notNull(body, "The body cannot be null.");
            List<FileItem> fileItems = fileUpload.parseRequest(new BodyContext(body));
            return parseFileItems(fileItems, encoding);
        } catch (FileUploadBase.SizeLimitExceededException ex) {
            throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
        } catch (FileUploadBase.FileSizeLimitExceededException ex) {
            throw new MaxUploadSizeExceededException(fileUpload.getFileSizeMax(), ex);
        } catch (FileUploadException ex) {
            throw new MultipartException("Failed to parse multipart servlet request.", ex);
        }
    }
960947
protected void init(InputStream inputStream) throws IOException {
		stream = inputStream;
		st = new StreamTokenizer(new BufferedReader(new InputStreamReader(
				stream, ENCODING)));

		EOF_reached = false;
		skipStatements();

	}
164145
protected ApiRequest readRequest(HttpServletRequest request) throws Exception {
        ApiRequestPathInfo pathInfo = getEngine().getApiRequestPathParser().parseEndpoint(request.getPathInfo(), wrapMultiMap(request));//parseApiRequestPath(request);
        if (pathInfo.orgId == null) {
            throw new Exception(Messages.i18n.format("GatewayServlet.InvalidApiEndpoint")); //$NON-NLS-1$
        }
        QueryMap queryParams = parseApiRequestQueryParams(request.getQueryString());

        String apiKey = getApiKey(request, queryParams);

        ApiRequest srequest = GatewayThreadContext.getApiRequest();
        srequest.setApiKey(apiKey);
        srequest.setApiOrgId(pathInfo.orgId);
        srequest.setApiId(pathInfo.apiId);
        srequest.setApiVersion(pathInfo.apiVersion);
        srequest.setUrl(request.getRequestURL().toString());
        srequest.setDestination(pathInfo.resource);
        srequest.setQueryParams(queryParams);
        readHeaders(srequest, request);
        srequest.setRawRequest(request);
        srequest.setRemoteAddr(request.getRemoteAddr());
        srequest.setTransportSecure(request.isSecure());
        return srequest;
    }
535434
public static WrappedRequest wrap(final HttpServletRequest request) throws IOException {
        if (request instanceof WrappedRequest) {
            return (WrappedRequest) request;
        }

        return new WrappedRequest(request);
    }
1297722
public static String getBody(ServletRequest request) {
		try {
			return IoUtil.read(request.getReader());
		} catch (IOException e) {
			throw new IORuntimeException(e);
		}
	}
554080
public void handleRequest(String request) {
        if (messageListener != null) {
            log.debug("Received Http request");
            messageListener.onInboundMessage(new RawMessage(request), null);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Received Http request:" + NEWLINE + request);
            }
        }
    }
446559
public Response get(String service, Request request) throws IOException {
        return call(Method.GET, service, request, null);
    }
1999
public static void readAndWriteStreams(InputStream inputStream,OutputStream outputStream) throws IOException
    {
        byte[] buffer=new byte[5000];
        int read=-1;
        try
        {
            do
            {
                //read next buffer
                read=inputStream.read(buffer);
                
                if(read!=-1)
                {
                    //write to in memory stream
                    outputStream.write(buffer,0,read);
                }
            }while(read!=-1);
        }
        finally
        {
            //close streams
            IOHelper.closeResource(inputStream);
            IOHelper.closeResource(outputStream);
        }
    }
918906
public void deleteStream(DeleteStreamRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");

        checkStringNotEmpty(request.getDomain(), "Domain should NOT be empty.");
        checkStringNotEmpty(request.getApp(), "App should NOT be empty.");
        checkStringNotEmpty(request.getStream(), "Stream should NOT be empty.");

        InternalRequest internalRequest = createRequest(HttpMethodName.DELETE, request,
                LIVE_DOMAIN, request.getDomain(), LIVE_APP, request.getApp(),
                LIVE_STREAM, request.getStream());
        invokeHttpClient(internalRequest, AbstractBceResponse.class);
    }
981026
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8"); 
        response.setCharacterEncoding("UTF-8"); 
        request.setCharacterEncoding("UTF-8");
        
        String questionStr = request.getParameter("q");
        String n = request.getParameter("n");
        int topN = -1;
        if(n != null && StringUtils.isNumeric(n)){
            topN = Integer.parseInt(n);
        }
        Question question = null;
        List<CandidateAnswer> candidateAnswers = null;
        if (questionStr != null && questionStr.trim().length() > 3) {
            question = SharedQuestionAnsweringSystem.getInstance().answerQuestion(questionStr);
            if (question != null) {
                candidateAnswers = question.getAllCandidateAnswer();
            }
        }
        LOG.info("问题："+questionStr); 
        try (PrintWriter out = response.getWriter()) {
            String json = JsonGenerator.generate(candidateAnswers, topN);
            out.println(json);
            LOG.info("答案："+json);
        }
    }
699823
@SuppressWarnings("resource")
    public InputStream getInputStream(String filename)
    {
        InputStream streamIn = null;
        if (filename.indexOf(':') == -1)
        {
            String filepath = ((BaseHttpTask)this.getTask()).getRealPath(this.getServletRequest(), filename);
            if (filepath != null)
            {
	            File file = new File(filepath);
	            try   {
	                streamIn = new FileInputStream(file);
	            } catch (FileNotFoundException ex)  {
	                streamIn = null;
	            }
            }
        }
        if (streamIn == null)
            streamIn = Utility.getInputStream(filename, this.getApplication());
        return streamIn;
    }