/** * Set the body of the request by providing an InputStream * * @param body the bytes of the body * @param contentLength how long the body is supposed to be */ public EventBuilder withBody(InputStream body, int contentLength) { Objects.requireNonNull(body, "body"); if (contentLength < 0) { throw new IllegalArgumentException("Invalid contentLength"); } // This is for safety. Because we concatenate events, an input stream shorter than content length will cause // the implementation to continue reading through to the next http request. We need to avoid a sort of // buffer overrun. // FIXME: Make InputStream handling simpler. SessionInputBufferImpl sib = new SessionInputBufferImpl(new HttpTransportMetricsImpl(), 65535); sib.bind(body); this.body = new ContentLengthInputStream(sib, contentLength); this.contentLength = contentLength; return this; }
/** * Creates new instance of BHttpConnectionBase. * * @param buffersize buffer size. Must be a positive number. * @param fragmentSizeHint fragment size hint. * @param chardecoder decoder to be used for decoding HTTP protocol elements. * If <code>null</code> simple type cast will be used for byte to char conversion. * @param charencoder encoder to be used for encoding HTTP protocol elements. * If <code>null</code> simple type cast will be used for char to byte conversion. * @param constraints Message constraints. If <code>null</code> * {@link MessageConstraints#DEFAULT} will be used. * @param incomingContentStrategy incoming content length strategy. If <code>null</code> * {@link LaxContentLengthStrategyHC4#INSTANCE} will be used. * @param outgoingContentStrategy outgoing content length strategy. If <code>null</code> * {@link StrictContentLengthStrategyHC4#INSTANCE} will be used. */ protected BHttpConnectionBase( final int buffersize, final int fragmentSizeHint, final CharsetDecoder chardecoder, final CharsetEncoder charencoder, final MessageConstraints constraints, final ContentLengthStrategy incomingContentStrategy, final ContentLengthStrategy outgoingContentStrategy) { super(); Args.positive(buffersize, "Buffer size"); final HttpTransportMetricsImpl inTransportMetrics = new HttpTransportMetricsImpl(); final HttpTransportMetricsImpl outTransportMetrics = new HttpTransportMetricsImpl(); this.inbuffer = new SessionInputBufferImpl(inTransportMetrics, buffersize, -1, constraints != null ? constraints : MessageConstraints.DEFAULT, chardecoder); this.outbuffer = new SessionOutputBufferImpl(outTransportMetrics, buffersize, fragmentSizeHint, charencoder); this.connMetrics = new HttpConnectionMetricsImpl(inTransportMetrics, outTransportMetrics); this.incomingContentStrategy = incomingContentStrategy != null ? incomingContentStrategy : LaxContentLengthStrategyHC4.INSTANCE; this.outgoingContentStrategy = outgoingContentStrategy != null ? outgoingContentStrategy : StrictContentLengthStrategyHC4.INSTANCE; }
/** * Converts chunked response data (returned by in the request body) <br> * into a single piece, regular byte array. * * @param content Chunked data byte array * @return Unchunked (regular) byte array */ public byte[] unchunkResponse(byte[] content) { SessionInputBufferImpl buffer = new SessionInputBufferImpl(new HttpTransportMetricsImpl(), 1024); buffer.bind(new ByteArrayInputStream(content)); try { if (content != null && content.length > 0) { return IOUtils.toByteArray(new ChunkedInputStream(buffer)); } } catch (IOException e) { LOG.error("Cannot write chunked input stream to byte array!", e); } return content; }
public FnHttpEventBuilder withBody(InputStream body, int contentLength) { Objects.requireNonNull(body, "body"); if (contentLength < 0) { throw new IllegalArgumentException("Invalid contentLength"); } // This is for safety. Because we concatenate events, an input stream shorter than content length will cause // the implementation to continue reading through to the next http request. We need to avoid a sort of // buffer overrun. // FIXME: Make InputStream handling simpler. SessionInputBufferImpl sib = new SessionInputBufferImpl(new HttpTransportMetricsImpl(), 65535); sib.bind(body); this.bodyStream = new ContentLengthInputStream(sib, contentLength); this.contentLength = contentLength; return this; }
/** * Creates a new {@link SessionInputBuffer} bounded to a given maximum length. * * @param buffer the buffer to wrap * @param length the maximum number of bytes to read (from the buffered stream). */ public BoundSessionInputBuffer(final SessionInputBuffer buffer, final long length) { super(new HttpTransportMetricsImpl(), BUFFER_SIZE, 0, null, null); this.bounded = new ContentLengthInputStream(buffer, length); this.input = new CountingInputStream(this.bounded); super.bind(this.input); this.length = length; }
public SessionInputBufferMock( final InputStream instream, final int buffersize, final MessageConstraints constrains, final CharsetDecoder decoder) { super(new HttpTransportMetricsImpl(), buffersize, -1, constrains, decoder); bind(instream); }
private ExpectedResult parseExpectedResponse(Element element, Evaluator evaluator, ResultRecorder resultRecorder) { String contents = getTextAndRemoveIndent(element); contents = replaceVariableReferences(evaluator, contents, resultRecorder); SessionInputBufferImpl buffer = new SessionInputBufferImpl(new HttpTransportMetricsImpl(), contents.length()); buffer.bind(new ByteArrayInputStream(contents.getBytes(StandardCharsets.UTF_8))); DefaultHttpResponseParser defaultHttpResponseParser = new DefaultHttpResponseParser(buffer); ExpectedResult.ExpectedResultBuilder builder = expectedResult(); String body = null; try { HttpResponse httpResponse = defaultHttpResponseParser.parse(); StatusLine statusLine = httpResponse.getStatusLine(); builder.withStatus(statusLine.getStatusCode()); for (Header header : httpResponse.getAllHeaders()) { builder.withHeader(header.getName(), header.getValue()); } if (buffer.hasBufferedData()) { body = ""; while (buffer.hasBufferedData()) { body += (char) buffer.read(); } } builder.withBody(body); } catch (IOException | HttpException e) { e.printStackTrace(); } return builder.build(); }
public static SessionInputBuffer warpSessionInputBuffer(final InputStream input) { final SessionInputBufferImpl bufferImpl = new SessionInputBufferImpl(new HttpTransportMetricsImpl(), 1024, 0, null, null); bufferImpl.bind(input); return bufferImpl; }
/** {@inheritDoc} */ public boolean run() { boolean success = false; String error = null; try { String bu = context.getSpecification().getBaseUrl(); if (bu.startsWith("https")) { return true; } URI uri = new URI(bu); String host = uri.getHost(); context.acquireRequestPermit(); Socket socket = new Socket(host, HTTP_PORT); OutputStream os = socket.getOutputStream(); String request = "GET " + rawUri + " HTTP/1.1\n" + "Host: " + host + "\n" + "Accept: application/rdap+json\n\n"; os.write(request.getBytes("UTF-8")); InputStream is = socket.getInputStream(); SessionInputBufferImpl sibl = new SessionInputBufferImpl( new HttpTransportMetricsImpl(), BUFFER_SIZE ); sibl.bind(is); DefaultHttpResponseParser dhrp = new DefaultHttpResponseParser(sibl); HttpResponse hr = dhrp.parse(); HttpEntity he = hr.getEntity(); /* It is assumed that this class is used to produce * invalid requests. The error codes aren't checked here; * it's just for confirming that the content (if present) * is JSON. With some servers, e.g. Jetty, it's not * possible to do things like setting the content type in * this sort of situation, so that is explicitly not * checked. */ if ((he == null) || (he.getContentLength() == 0)) { success = true; } else { InputStream isc = he.getContent(); InputStreamReader iscr = new InputStreamReader(isc, "UTF-8"); new Gson().fromJson(iscr, Map.class); success = true; } } catch (Exception e) { error = e.toString(); } Result nr = new Result(proto); nr.setPath(rawUri); nr.setCode("content"); if (success) { nr.setStatus(Status.Success); } else if (!nr.getStatusSet()) { nr.setStatus(Status.Failure); } String prefix = (expectedSuccess) ? "content" : "error content"; nr.setInfo(success ? prefix + " is empty or JSON" : prefix + " is not empty or JSON: " + error); context.addResult(nr); return success; }
private HttpRequest parseRequest(Element element, Evaluator evaluator, ResultRecorder resultRecorder) { String contents = getTextAndRemoveIndent(element); contents = replaceVariableReferences(evaluator, contents, resultRecorder); SessionInputBufferImpl buffer = new SessionInputBufferImpl(new HttpTransportMetricsImpl(), contents.length()); buffer.bind(new ByteArrayInputStream(contents.getBytes(StandardCharsets.UTF_8))); DefaultHttpRequestParser defaultHttpRequestParser = new DefaultHttpRequestParser(buffer); LinkedListMultimap<String, String> queryParameters = LinkedListMultimap.create(); String method = ""; String url = ""; LinkedListMultimap<String, String> headers = LinkedListMultimap.create(); String body = null; String server = null; try { org.apache.http.HttpRequest httpRequest = defaultHttpRequestParser.parse(); method = httpRequest.getRequestLine().getMethod(); url = httpRequest.getRequestLine().getUri(); if (url.startsWith("#")) { url = "" + evaluator.evaluate(url); } Matcher matcher = Pattern.compile("(https?://[^/]+)(/.*)").matcher(url); if (matcher.matches()) { server = matcher.group(1); url = matcher.group(2); } if (url.contains("?")) { String[] urlAndQueryParameters = url.split("\\?"); url = urlAndQueryParameters[0]; for (String queryParameter : urlAndQueryParameters[1].split("&")) { String[] parameter = queryParameter.split("="); queryParameters.put(parameter[0], parameter[1]); } } for (Header header : httpRequest.getAllHeaders()) { headers.put(header.getName(), header.getValue()); } if (buffer.hasBufferedData()) { body = ""; while (buffer.hasBufferedData()) { body += (char) buffer.read(); } } } catch (IOException | HttpException e) { e.printStackTrace(); } return new HttpRequest(method, url, headers, body, server, queryParameters); }