Reads a {@link ApiRequest} from information found in the inbound
portion of the http request.
@param request the undertow http server request
@return a valid {@link ApiRequest}
@throws IOException
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;
    }
1226977
public static HttpRequest parseMessage(InputStream in) throws IOException {
        HttpRequest m = new HttpRequest();
        m.parse(in);
        return m;
    }
1065973
protected void readHeaders(ApiRequest srequest, HttpServletRequest request) {
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String hname = headerNames.nextElement();
            Enumeration<String> headerValues = request.getHeaders(hname);

            while (headerValues.hasMoreElements()) {
                String hval = headerValues.nextElement();

                if (hname != null && hname.equalsIgnoreCase("accept") && hval != null && hval.startsWith("application/apiman.")) { //$NON-NLS-1$ //$NON-NLS-2$
                    if (hval.contains("+json")) { //$NON-NLS-1$
                        hval = "application/json"; //$NON-NLS-1$
                    } else if (hval.contains("+xml")) { //$NON-NLS-1$
                        hval = "text/xml"; //$NON-NLS-1$
                    }
                }
                if (hname != null && hname.equalsIgnoreCase("X-API-Version")) { //$NON-NLS-1$
                    continue;
                }
                srequest.getHeaders().add(hname, hval);
            }
        }
    }
1228728
private URI getHasMemberFromRequest(final HttpServletRequest request) throws IOException {
        final String baseUri = request.getRequestURL().toString();
        final RDFReader reader;
        final String contentType = request.getContentType();
        final Lang format = contentTypeToLang(contentType);
        final Model inputModel;
        try {
            inputModel = createDefaultModel();
            reader = inputModel.getReader(format.getName().toUpperCase());
            reader.read(inputModel, request.getInputStream(), baseUri);
            final Statement st = inputModel.getProperty(null, MEMBERSHIP_RESOURCE);
            return (st != null ? URI.create(st.getObject().toString()) : null);
        } catch (final RiotException e) {
            throw new BadRequestException("RDF was not parsable: " + e.getMessage(), e);
        } catch (final RuntimeIOException e) {
            if (e.getCause() instanceof JsonParseException) {
                throw new MalformedRdfException(e.getCause());
            }
            throw new RepositoryRuntimeException(e);
        }
    }
898917
protected BufferedImage fetchImage(
            @Nonnull final ClientHttpRequest request, @Nonnull final MapfishMapContext transformer)
            throws IOException {
        final String baseMetricName = getClass().getName() + ".read." +
                StatsUtils.quotePart(request.getURI().getHost());
        final Timer.Context timerDownload = this.registry.timer(baseMetricName).time();
        try (ClientHttpResponse httpResponse = request.execute()) {
            if (httpResponse.getStatusCode() != HttpStatus.OK) {
                final String message = String.format(
                        "Invalid status code for %s (%d!=%d). The response was: '%s'",
                        request.getURI(), httpResponse.getStatusCode().value(),
                        HttpStatus.OK.value(), httpResponse.getStatusText());
                this.registry.counter(baseMetricName + ".error").inc();
                if (getFailOnError()) {
                    throw new RuntimeException(message);
                } else {
                    LOGGER.info(message);
                    return createErrorImage(transformer.getPaintArea());
                }
            }

            final List<String> contentType = httpResponse.getHeaders().get("Content-Type");
            if (contentType == null || contentType.size() != 1) {
                LOGGER.debug("The image {} didn't return a valid content type header.",
                             request.getURI());
            } else if (!contentType.get(0).startsWith("image/")) {
                final byte[] data;
                try (InputStream body = httpResponse.getBody()) {
                    data = IOUtils.toByteArray(body);
                }
                LOGGER.debug("We get a wrong image for {}, content type: {}\nresult:\n{}",
                             request.getURI(), contentType.get(0),
                             new String(data, StandardCharsets.UTF_8));
                this.registry.counter(baseMetricName + ".error").inc();
                return createErrorImage(transformer.getPaintArea());
            }

            final BufferedImage image = ImageIO.read(httpResponse.getBody());
            if (image == null) {
                LOGGER.warn("Cannot read image from %a", request.getURI());
                this.registry.counter(baseMetricName + ".error").inc();
                if (getFailOnError()) {
                    throw new RuntimeException("Cannot read image from " + request.getURI());
                } else {
                    return createErrorImage(transformer.getPaintArea());
                }
            }
            timerDownload.stop();
            return image;
        } catch (Throwable e) {
            this.registry.counter(baseMetricName + ".error").inc();
            throw e;
        }
    }
650783
private boolean parseRequest()
    throws IOException
  {
    try {
      ReadStream is = connTcp().readStream();
      
      if (! readRequest(is)) {
        clearRequest();

        return false;
      }
      
      _sequence = connHttp().nextSequenceRead();

      if (log.isLoggable(Level.FINE)) {
        log.fine(_method + " "
                 + new String(_uri, 0, _uriLength) + " " + _protocol
                 + " (" + dbgId() + ")");
        log.fine("Remote-IP: " + connTcp().addressRemote()
                 + ":" + connTcp().portRemote() + " (" + dbgId() + ")");
      }

      parseHeaders(is);

      return true;
    } catch (ClientDisconnectException e) {
      throw e;
    } catch (SocketTimeoutException e) {
      log.log(Level.FINER, e.toString(), e);
      
      return false;
    } catch (ArrayIndexOutOfBoundsException e) {
      log.log(Level.FINEST, e.toString(), e);
      
      throw new BadRequestException(L.l("Invalid request: URL or headers are too long"), e);
    } catch (Throwable e) {
      log.log(Level.FINEST, e.toString(), e);
      
      throw new BadRequestException(String.valueOf(e), e);
    }
  }
57328
public static String getPostData(HttpServletRequest request) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        //return URLDecoder.decode(sb.toString(), Constant.DEFAULT_CHATSET);
        return sb.toString();
    }
1040962
protected void load(final Request request) throws IOException {
		log("load(" + request + ')');
		final CallbackHandler handler = request.handler != null ? request.handler : this.handler;
		final boolean safe = request.safe != null ? request.safe : this.safe;
		Callback callback = request.callback != null ? request.callback.get() : null;

		// Don't load if URL is the favorites key
		if(request.url.equals(KEY_FAVORITES)) {
			log("Favorites URL detected, skipping load...");
			return;
		}

		// Notify callback
		handler.onPreload(safe, callback);

		// Create safe url for pagination/indexing purposes
		String safeUrl = request.downloader == null ? downloader.toSafeUrl(request) : request.downloader.toSafeUrl(request);

		// Put the page index into the request's HashMap
		pageTracker.put(safeUrl, request.page);

		// Get response from this request
		String response = request.downloader == null ? downloader.execute(request) : request.downloader.execute(request);

		// Parse articles from response and inset into global list
		List<Article> newArticles = request.parser == null ? parser.parse(response) : request.parser.parse(response);
		insert(safeUrl, newArticles);

		// Notify callback
		handler.onLoaded(safe, callback, newArticles);
	}
100891
def read(self, request):
        
        pipeline = view_pipeline_factory.read_pipeline(
            configuration=self.configuration)
        return pipeline(request=request)
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);
            }
        }

    }
573110
public byte[] getObjectContent(GetObjectRequest request) {
        BosObjectInputStream content = this.getObject(request).getObjectContent();
        try {
            return IOUtils.toByteArray(content);
        } catch (IOException e) {
            try {
                content.close();
            } catch (IOException e1) {
                // ignore, throw e not e1.
            }
            throw new BceClientException("Fail read object content", e);
        } finally {
            try {
                content.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
957291
public static String extractIPAddress(final HttpServletRequest request) {

        String ip = request.getHeader("x-forwarded-for");
        if (isIPAdressValid(ip)) {
            return ip;
        }
        ip = request.getHeader("Proxy-Client-IP");
        if (isIPAdressValid(ip)) {
            return ip;
        }
        ip = request.getHeader("WL-Proxy-Client-IP");
        if (isIPAdressValid(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }
414918
public Nfs3ReaddirResponse getReaddir(NfsReaddirRequest request) throws IOException {
        Nfs3ReaddirResponse response = new Nfs3ReaddirResponse();
        _rpcWrapper.callRpcNaked(request, response);
        return response;
    }
552731
private byte[] readRequestBody() {
        int bytesLeft = m_request.getContentLength();
        if (bytesLeft <= 0) {
            return new byte[0];
        }

        int totalBytesRead = 0;
        try {
            byte[] byteBuffer = new byte[bytesLeft];
            try (InputStream inputStream = m_request.getInputStream()) {
                int bytesRead = -1;
                int offset = 0;
                while ((bytesRead = inputStream.read(byteBuffer, offset, bytesLeft)) > 0) {
                    offset += bytesRead;
                    bytesLeft -= bytesRead;
                    totalBytesRead += bytesRead;
                }
            }
            return byteBuffer;
        } catch (IOException e) {
            String errMsg =
                String.format("Error reading from input request; expected %d bytes; only read %d bytes",
                              m_request.getContentLength(), totalBytesRead);
            throw new RuntimeException(errMsg, e);
        }
    }
265742
@GET
  @Path("me")
  @RolesAllowed({"ROLE_ADMIN", "ROLE_USER"})
  public Response readMe(@Context HttpServletRequest request) throws IOException {
    Long userId = (Long) request.getAttribute(OAuth2Filter.NAME_USER_ID);
    return read(userId);
  }
1058852
public static boolean isHttpGetRequest(HttpServletRequest request) {
        boolean isSane = isSaneRequest(request);
        boolean isGet = isSane && request.getMethod().equals(HttpMethod.GET.toString());
        return isSane && isGet;
    }
1025691
public void filter(ClientRequestContext request) throws IOException
    {
        if(!request.getHeaders().containsKey("X-Api-Key"))
            request.getHeaders().add("X-Api-Key", this.apikey);
    }