//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: @Override public void doFilter(final ServletRequest req, final ServletResponse resp, FilterChain chain) throws java.io.IOException, ServletException //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: public override void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final boolean isContentTypeJson = CONTENT_TYPE_JSON_PATTERN.matcher(req.getContentType() == null ? "" : req.getContentType()).find(); bool isContentTypeJson = CONTENT_TYPE_JSON_PATTERN.matcher(req.ContentType == null ? "" : req.ContentType).find(); if (isContentTypeJson) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.io.PushbackInputStream requestBody = new java.io.PushbackInputStream(req.getInputStream()); PushbackInputStream requestBody = new PushbackInputStream(req.InputStream); int firstByte = requestBody.read(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final boolean isBodyEmpty = firstByte == -1; bool isBodyEmpty = firstByte == -1; requestBody.unread(firstByte); HttpServletRequestWrapper wrappedRequest = new HttpServletRequestWrapperAnonymousInnerClass(this, (HttpServletRequest) req, requestBody, isBodyEmpty); chain.doFilter(wrappedRequest, resp); } else { chain.doFilter(req, resp); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: BomReader(java.io.InputStream inputStream) throws java.io.IOException internal BomReader(Stream inputStream) : base(inputStream) { Charset encoding; sbyte[] bom = new sbyte[MAX_BOM_SIZE]; // read first 3 bytes such that they can be pushed back later PushbackInputStream pushbackStream = new PushbackInputStream(inputStream, MAX_BOM_SIZE); int bytesRead = ByteStreams.read(pushbackStream, bom, 0, 3); // look for BOM and adapt, defauling to UTF-8 if (bytesRead >= 3 && bom[0] == X_EF && bom[1] == X_BB && bom[2] == X_BF) { encoding = StandardCharsets.UTF_8; pushbackStream.unread(bom, 3, (bytesRead - 3)); } else if (bytesRead >= 2 && bom[0] == X_FE && bom[1] == X_FF) { encoding = StandardCharsets.UTF_16BE; pushbackStream.unread(bom, 2, (bytesRead - 2)); } else if (bytesRead >= 2 && bom[0] == X_FF && bom[1] == X_FE) { encoding = StandardCharsets.UTF_16LE; pushbackStream.unread(bom, 2, (bytesRead - 2)); } else { encoding = StandardCharsets.UTF_8; pushbackStream.unread(bom, 0, bytesRead); } // use Java standard code now we know the encoding this.underlying = new StreamReader(pushbackStream, encoding); }
public void Unread_Many() { var text = "abcd"; var encoding = Encoding.UTF8; var bytes = encoding.GetBytes(text); using (var stream = new MemoryStream(bytes)) using (var input = new PushbackInputStream(stream)) using (var textSource = new StreamTextSource(input, encoding)) { // Arbitrarily chosen array size, but bigger than the input length char[] buffer = new char[32]; int len = textSource.Read(buffer, 0, 3); Assert.Equal(3, len); Assert.Equal('a', buffer[0]); Assert.Equal('b', buffer[1]); Assert.Equal('c', buffer[2]); Assert.Equal(default(char), buffer[3]); Assert.Equal(3, input.Position); textSource.Unread(buffer, 0, 3); Assert.Equal(0, input.Position); len = textSource.Read(buffer, 0, 4); Assert.Equal(4, len); Assert.Equal('a', buffer[0]); Assert.Equal('b', buffer[1]); Assert.Equal('c', buffer[2]); Assert.Equal('d', buffer[3]); Assert.Equal(4, input.Position); } }
/// <summary> /// Reads synchronously until headers are complete, then /// provides the remaining data in a stream /// </summary> public HttpResponse(Stream rawResponse, TimeSpan timeout) { _rawResponse = rawResponse ?? throw new ArgumentNullException(nameof(rawResponse)); RawHeaders = new MemoryStream(); Headers = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); ReadStatusLine(NextLine(_rawResponse)); foreach (var headerLine in NonBlankLines(_rawResponse)) { AddHeader(headerLine); } HeadersComplete = true; _rawResponse.ReadByte(); // eat one spare byte if (_rawResponse is SocketStream stream) { stream.ResetCounts(); } RawBodyStream = _rawResponse; // I am scared of this code: var buffered = new PushbackInputStream(_rawResponse); var dechunked = IsChunked() ? (Stream) new HttpChunkedStreamWrapper(buffered, timeout) : buffered; var decompressed = RestOfStreamDecompressed(dechunked); BodyReader = new HttpResponseStream(decompressed, ReportedBodyLength()) { Timeout = timeout }; }
public void setup() { _rawSample = new PushbackInputStream(HttpSample.ChunkedResponse()); var buf = new byte[74]; _rawSample.Read(buf, 0, 74); // skip HTTP headers _subject = new HttpChunkedStreamWrapper(_rawSample, TimeSpan.FromSeconds(1)); }
public void pushback_input_disposal() { var under = Substitute.For <Stream>(); var subject = new PushbackInputStream(under); subject.Dispose(); under.Received().Close(); }
public void CanWrite_WhenNotCanSeek_ReturnsFalse() { using (var stub = new FakeStream { OnCanReadGet = () => true, OnCanSeekGet = () => true }) using (var pushbackStream = new PushbackInputStream(stub)) { Assert.False(pushbackStream.CanWrite); } }
public void Position_WhenNotCanSeek_ThrowsNotSupportedException() { var stub = new FakeStream { OnCanReadGet = () => true, OnCanSeekGet = () => false }; using (var pushbackStream = new PushbackInputStream(stub)) { Assert.Throws<NotSupportedException>(() => pushbackStream.Position); } }
public void setup() { _underlying = Substitute.For <Stream>(); _underlying.Read(Arg.Any <byte[]>(), 0, 100).Returns(99); _underlying.CanSeek.Returns(true); _underlying.Seek(-100, SeekOrigin.Current).Returns(1); _underlying.Seek(10, SeekOrigin.Begin).Returns(9); _subject = new PushbackInputStream(_underlying); }
public void CanWrite_WhenCanSeek_ReturnsTrue() { var stub = new FakeStream { OnCanReadGet = () => true, OnCanSeekGet = () => false }; var sut = new PushbackInputStream(stub); using (stub) using (sut) { Assert.True(sut.CanWrite); } }
public void Position_WhenNotCanSeek_ThrowsNotSupportedException() { var stub = new FakeStream { OnCanReadGet = () => true, OnCanSeekGet = () => false }; using (var pushbackStream = new PushbackInputStream(stub)) { Assert.Throws <NotSupportedException>(() => pushbackStream.Position); } }
public void Position_WhenCanSeek_ReturnsPositionOfUnderlyingStream() { var stub = new FakeStream { OnCanReadGet = () => true, OnCanSeekGet = () => true, OnPositionGet = () => 128 }; using (var pushbackStream = new PushbackInputStream(stub)) { var position = pushbackStream.Position; Assert.Equal(128, position); } }
public VBAMacroReader(InputStream rstream) { PushbackInputStream stream = new PushbackInputStream(rstream, 8); byte[] header8 = IOUtils.PeekFirst8Bytes(stream); if (NPOIFSFileSystem.HasPOIFSHeader(header8)) { fs = new NPOIFSFileSystem(stream); } else { OpenOOXML(stream); } }
/// <exception cref="System.IO.IOException"></exception> public DeflateInputStream(InputStream wrapped) { byte[] peeked = new byte[6]; PushbackInputStream pushback = new PushbackInputStream(wrapped, peeked.Length); int headerLength = pushback.Read(peeked); if (headerLength == -1) { throw new IOException("Unable to read the response"); } byte[] dummy = new byte[1]; Inflater inf = new Inflater(); try { int n; while ((n = inf.Inflate(dummy)) == 0) { if (inf.IsFinished) { throw new IOException("Unable to read the response"); } if (inf.NeedsDictionary()) { break; } if (inf.IsNeedingInput) { inf.SetInput(peeked); } } if (n == -1) { throw new IOException("Unable to read the response"); } pushback.Unread(peeked, 0, headerLength); sourceStream = new DeflateInputStream.DeflateStream(pushback, new Inflater()); } catch (SharpZipBaseException) { pushback.Unread(peeked, 0, headerLength); sourceStream = new DeflateInputStream.DeflateStream(pushback, new Inflater(true)); } finally { inf.Finish(); } }
public void Write_WhenCanSeek_ThrowsIOException() { var stub = new FakeStream { OnCanReadGet = () => true, OnCanSeekGet = () => true, OnPositionGet = () => 128 }; var pushbackBytes = new byte[8]; using (var pushbackStream = new PushbackInputStream(stub)) { Assert.Throws <IOException>(() => pushbackStream.Write(pushbackBytes, 0, pushbackBytes.Length)); } }
public void testFileCorruptionOPOIFS() { // create test InputStream byte[] testData = { (byte)1, (byte)2, (byte)3 }; InputStream testInput = new ByteArrayInputStream(testData); // detect header InputStream in1 = new PushbackInputStream(testInput, 10); Assert.IsFalse(OPOIFSFileSystem.HasPOIFSHeader(in1)); // check if InputStream is still intact byte[] test = new byte[3]; in1.Read(test); Assert.IsTrue(Arrays.Equals(testData, test)); Assert.AreEqual(-1, in1.Read()); }
Stream RestOfStreamDecompressed(Stream unchunked) { if (!Headers.ContainsKey("Content-Encoding")) { return(unchunked); // plain body } var pushbackStream = new PushbackInputStream(unchunked); switch (Headers["Content-Encoding"]) { case "gzip": return(GzipUnwrap(pushbackStream)); case "deflate": return(DeflateUnwrap(unchunked)); // no good way to determine this default: throw new Exception("Unknown compression scheme: " + Headers["Content-Encoding"]); } }
public async Task ReceiveAsync(CancellationToken cancellationToken, OnResponseHeadersComplete callback = null) { if (disposed) { throw new ObjectDisposedException(GetType().FullName); } using (var pushbackInputStream = new PushbackInputStream(inputStream)) using (var textSource = new StreamTextSource(pushbackInputStream, Encoding.UTF8)) using (ITextScanner scanner = new TextScanner(textSource)) { var result = httpMessageLexer.Read(scanner); if (result == null) { throw new InvalidOperationException(); } throw new NotImplementedException(); } }
public void TestFileCorruption() { // create test InputStream byte[] testData = { (byte)1, (byte)2, (byte)3 }; ByteArrayInputStream testInput = new ByteArrayInputStream(testData); // detect header InputStream in1 = new PushbackInputStream(testInput, 10); Assert.IsFalse(DocumentFactoryHelper.HasOOXMLHeader(in1)); //noinspection deprecation Assert.IsFalse(POIXMLDocument.HasOOXMLHeader(in1)); // check if InputStream is still intact byte[] test = new byte[3]; Assert.AreEqual(3, in1.Read(test)); Assert.IsTrue(Arrays.Equals(testData, test)); Assert.AreEqual(-1, in1.Read()); }
public void Write_DoesNotWriteToUnderlyingStream() { var callsToWrite = 0; var stub = new FakeStream { OnCanReadGet = () => true, OnCanWriteGet = () => true, OnCanSeekGet = () => false, OnWriteByteArrayInt32Int32 = (_, __, ___) => callsToWrite++ }; var sut = new PushbackInputStream(stub); using (sut) { var buffer = new byte[] { 0x8a, 0x8f, 0x1c, 0xdd, 0x7a, 0xa7, 0xd0, 0x99, 0xa3, 0x4b }; sut.Write(buffer, 0, 10); } Assert.Equal(0, callsToWrite); }
public async void ReadAsync_ReadsFromBufferFirst() { const int Position = 128; var callsToRead = 0; // MEMO: all calls to PushbackInputStream.ReadAsync(...) are routed to PushbackInputStream.Read(...) // if we mocked FakeStream.ReadAsync(...), it would never be called // that is why the synchronous method is mocked instead var mock = new FakeStream { OnCanReadGet = () => true, OnCanSeekGet = () => false, OnPositionGet = () => Position, OnReadByteArrayInt32Int32 = (_, __, ___) => { callsToRead++; return(0); } }; using (var pushbackStream = new PushbackInputStream(mock)) { var pushbackBytes = new byte[] { 1, 2, 4, 8 }; pushbackStream.Write(pushbackBytes, 0, pushbackBytes.Length); // Read as many bytes as we wrote to the pusback buffer // The stream wrapper should not touch the underlying stream var result = new byte[pushbackBytes.Length]; var bytesRead = await pushbackStream.ReadAsync(result, 0, result.Length); Assert.Equal(0, callsToRead); Assert.Equal(pushbackBytes.Length, bytesRead); Assert.Equal(pushbackBytes, result); // The pushback buffer should be empty at this point; // a subsequent read should hit the underlying stream await pushbackStream.ReadAsync(result, 0, result.Length, CancellationToken.None); Assert.Equal(1, callsToRead); } }
public void Unread_One() { var text = "abcd"; var encoding = Encoding.UTF8; var bytes = encoding.GetBytes(text); using (var stream = new MemoryStream(bytes)) using (var input = new PushbackInputStream(stream)) using (var textSource = new StreamTextSource(input, encoding)) { var a = (char)textSource.Read(); Assert.Equal('a', a); Assert.Equal(1, input.Position); textSource.Unread(a); Assert.Equal(0, input.Position); a = (char)textSource.Read(); Assert.Equal('a', a); Assert.Equal(1, input.Position); } }
public void Read_Many_BuffersLazily() { // Ensure that StreamTextSource.Read() does not buffer more bytes than it needs var text = "abcd"; var encoding = Encoding.UTF8; var bytes = encoding.GetBytes(text); using (var stream = new MemoryStream(bytes)) using (var input = new PushbackInputStream(stream)) using (var textSource = new StreamTextSource(input, encoding)) { // Arbitrarily chosen array size, but bigger than the input length char[] buffer = new char[32]; int len = textSource.Read(buffer, 0, 3); Assert.Equal(3, len); Assert.Equal('a', buffer[0]); Assert.Equal('b', buffer[1]); Assert.Equal('c', buffer[2]); Assert.Equal(default(char), buffer[3]); Assert.Equal(3, input.Position); } }
/// <summary> /// Wraps a <seealso cref="System.IO.Stream_Input"/> in a <seealso cref="CharReadable"/>. /// </summary> /// <param name="stream"> <seealso cref="Reader"/> to wrap. </param> /// <param name="sourceName"> name or description of the source of the stream. </param> /// <param name="charset"> <seealso cref="Charset"/> to use for reading. </param> /// <param name="length"> total number of bytes provided by the reader. </param> /// <returns> a <seealso cref="CharReadable"/> for the <seealso cref="Reader"/>. </returns> /// <exception cref="IOException"> on I/O error. </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: public static CharReadable wrap(final java.io.InputStream stream, final String sourceName, java.nio.charset.Charset charset, long length) throws java.io.IOException //JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected: public static CharReadable Wrap(Stream stream, string sourceName, Charset charset, long length) { sbyte[] bytes = new sbyte[Magic.Longest()]; PushbackInputStream pushbackStream = new PushbackInputStream(stream, bytes.Length); Charset usedCharset = charset; int read = stream.Read(bytes, 0, bytes.Length); if (read >= 0) { bytes = read < bytes.Length ? Arrays.copyOf(bytes, read) : bytes; Magic magic = Magic.Of(bytes); int excessiveBytes = read; if (magic.ImpliesEncoding()) { // Unread the diff between the BOM and the longest magic we gathered bytes for excessiveBytes -= magic.Length(); usedCharset = magic.Encoding(); } pushbackStream.unread(bytes, read - excessiveBytes, excessiveBytes); } return(wrap(new InputStreamReaderAnonymousInnerClass(pushbackStream, usedCharset, sourceName) , length)); }
public void Read_One_BuffersLazily() { // Ensure that StreamTextSource.Read() does not buffer more bytes than it needs var text = "abcd"; var encoding = Encoding.UTF8; var bytes = encoding.GetBytes(text); using (var stream = new MemoryStream(bytes)) using (var input = new PushbackInputStream(stream)) using (var textSource = new StreamTextSource(input, encoding)) { var a = (char)textSource.Read(); Assert.Equal('a', a); Assert.Equal(1, input.Position); var b = (char)textSource.Read(); Assert.Equal('b', b); Assert.Equal(2, input.Position); var c = (char)textSource.Read(); Assert.Equal('c', c); Assert.Equal(3, input.Position); } }
/** * Checks that the supplied InputStream (which MUST * support mark and reset, or be a PushbackInputStream) * has a POIFS (OLE2) header at the start of it. * If your InputStream does not support mark / reset, * then wrap it in a PushBackInputStream, then be * sure to always use that, and not the original! * @param inp An InputStream which supports either mark/reset, or is a PushbackInputStream */ public static bool HasPOIFSHeader(Stream inp) { // We want to peek at the first 8 bytes //inp.Mark(8); byte[] header = new byte[8]; int bytesRead = IOUtils.ReadFully(inp, header); LongField signature = new LongField(HeaderBlockConstants._signature_offset, header); // Wind back those 8 bytes if (inp is PushbackInputStream) { PushbackInputStream pin = (PushbackInputStream)inp; pin.Unread(header, 0, bytesRead); } else { inp.Position = 0; } // Did it match the signature? return(signature.Value == HeaderBlockConstants._signature); }
public void Read_ReadsFromBufferFirst() { const int Position = 128; var callsToRead = 0; var mock = new FakeStream { OnCanReadGet = () => true, OnCanSeekGet = () => false, OnPositionGet = () => Position, OnReadByteArrayInt32Int32 = (_, __, ___) => { callsToRead++; return(0); } }; using (var pushbackStream = new PushbackInputStream(mock)) { var pushbackBytes = new byte[] { 1, 2, 4, 8 }; pushbackStream.Write(pushbackBytes, 0, pushbackBytes.Length); // Read as many bytes as we wrote to the pusback buffer // The stream wrapper should not touch the underlying stream var result = new byte[pushbackBytes.Length]; var bytesRead = pushbackStream.Read(result, 0, result.Length); Assert.Equal(0, callsToRead); Assert.Equal(pushbackBytes.Length, bytesRead); Assert.Equal(pushbackBytes, result); // The pushback buffer should be empty at this point; // a subsequent read should hit the underlying stream pushbackStream.Read(result, 0, result.Length); Assert.Equal(1, callsToRead); } }
public async void WriteAsync_DoesNotWriteToUnderlyingStream() { var callsToWrite = 0; // MEMO: all calls to PushbackInputStream.WriteAsync(...) are routed to PushbackInputStream.Write(...) // if we mocked FakeStream.WriteAsync(...), it would never be called // that is why the synchronous method is mocked instead var stub = new FakeStream { OnCanReadGet = () => true, OnCanWriteGet = () => true, OnCanSeekGet = () => false, OnWriteByteArrayInt32Int32 = (_, __, ___) => callsToWrite++ }; var sut = new PushbackInputStream(stub); using (sut) { var buffer = new byte[] { 0x8a, 0x8f, 0x1c, 0xdd, 0x7a, 0xa7, 0xd0, 0x99, 0xa3, 0x4b }; await sut.WriteAsync(buffer, 0, 10, CancellationToken.None); } Assert.Equal(0, callsToWrite); }
public void Write_WhenCanSeek_ThrowsIOException() { var stub = new FakeStream { OnCanReadGet = () => true, OnCanSeekGet = () => true, OnPositionGet = () => 128 }; var pushbackBytes = new byte[8]; using (var pushbackStream = new PushbackInputStream(stub)) { Assert.Throws<IOException>(() => pushbackStream.Write(pushbackBytes, 0, pushbackBytes.Length)); } }
static Stream GzipUnwrap(PushbackInputStream rawResponse) { return(new GZipStreamWrapper(rawResponse)); }
public async void ReadAsync_ReadsFromBufferFirst() { const int Position = 128; var callsToRead = 0; // MEMO: all calls to PushbackInputStream.ReadAsync(...) are routed to PushbackInputStream.Read(...) // if we mocked FakeStream.ReadAsync(...), it would never be called // that is why the synchronous method is mocked instead var mock = new FakeStream { OnCanReadGet = () => true, OnCanSeekGet = () => false, OnPositionGet = () => Position, OnReadByteArrayInt32Int32 = (_, __, ___) => { callsToRead++; return 0; } }; using (var pushbackStream = new PushbackInputStream(mock)) { var pushbackBytes = new byte[] { 1, 2, 4, 8 }; pushbackStream.Write(pushbackBytes, 0, pushbackBytes.Length); // Read as many bytes as we wrote to the pusback buffer // The stream wrapper should not touch the underlying stream var result = new byte[pushbackBytes.Length]; var bytesRead = await pushbackStream.ReadAsync(result, 0, result.Length); Assert.Equal(0, callsToRead); Assert.Equal(pushbackBytes.Length, bytesRead); Assert.Equal(pushbackBytes, result); // The pushback buffer should be empty at this point; // a subsequent read should hit the underlying stream await pushbackStream.ReadAsync(result, 0, result.Length, CancellationToken.None); Assert.Equal(1, callsToRead); } }
public void setup() { _underlying = new NonSeekable(_sample_data); _subject = new PushbackInputStream(_underlying); }
public void Read_ReadsFromBufferFirst() { const int Position = 128; var callsToRead = 0; var mock = new FakeStream { OnCanReadGet = () => true, OnCanSeekGet = () => false, OnPositionGet = () => Position, OnReadByteArrayInt32Int32 = (_, __, ___) => { callsToRead++; return 0; } }; using (var pushbackStream = new PushbackInputStream(mock)) { var pushbackBytes = new byte[] { 1, 2, 4, 8 }; pushbackStream.Write(pushbackBytes, 0, pushbackBytes.Length); // Read as many bytes as we wrote to the pusback buffer // The stream wrapper should not touch the underlying stream var result = new byte[pushbackBytes.Length]; var bytesRead = pushbackStream.Read(result, 0, result.Length); Assert.Equal(0, callsToRead); Assert.Equal(pushbackBytes.Length, bytesRead); Assert.Equal(pushbackBytes, result); // The pushback buffer should be empty at this point; // a subsequent read should hit the underlying stream pushbackStream.Read(result, 0, result.Length); Assert.Equal(1, callsToRead); } }
public InputStreamReaderAnonymousInnerClass(PushbackInputStream pushbackStream, Charset usedCharset, string sourceName) : base(pushbackStream, usedCharset) { this._sourceName = sourceName; }