Search in sources :

Example 46 with CharArrayBuffer

use of org.apache.hc.core5.util.CharArrayBuffer in project httpcomponents-core by apache.

the class SessionInputBufferImpl method readLine.

@Override
public boolean readLine(final CharArrayBuffer lineBuffer, final boolean endOfStream) throws IOException {
    setOutputMode();
    // See if there is LF char present in the buffer
    int pos = -1;
    for (int i = buffer().position(); i < buffer().limit(); i++) {
        final int b = buffer().get(i);
        if (b == Chars.LF) {
            pos = i + 1;
            break;
        }
    }
    if (this.maxLineLen > 0) {
        final int currentLen = (pos > 0 ? pos : buffer().limit()) - buffer().position();
        if (currentLen >= this.maxLineLen) {
            throw new MessageConstraintException("Maximum line length limit exceeded");
        }
    }
    if (pos == -1) {
        if (endOfStream && buffer().hasRemaining()) {
            // No more data. Get the rest
            pos = buffer().limit();
        } else {
            // or no more data is expected
            return false;
        }
    }
    final int origLimit = buffer().limit();
    buffer().limit(pos);
    final int requiredCapacity = buffer().limit() - buffer().position();
    // Ensure capacity of len assuming ASCII as the most likely charset
    lineBuffer.ensureCapacity(requiredCapacity);
    if (this.charDecoder == null) {
        if (buffer().hasArray()) {
            final byte[] b = buffer().array();
            final int off = buffer().position();
            final int len = buffer().remaining();
            lineBuffer.append(b, buffer().arrayOffset() + off, len);
            buffer().position(off + len);
        } else {
            while (buffer().hasRemaining()) {
                lineBuffer.append((char) (buffer().get() & 0xff));
            }
        }
    } else {
        if (this.charbuffer == null) {
            this.charbuffer = CharBuffer.allocate(this.lineBuffersize);
        }
        this.charDecoder.reset();
        for (; ; ) {
            final CoderResult result = this.charDecoder.decode(buffer(), this.charbuffer, true);
            if (result.isError()) {
                result.throwException();
            }
            if (result.isOverflow()) {
                this.charbuffer.flip();
                lineBuffer.append(this.charbuffer.array(), this.charbuffer.arrayOffset() + this.charbuffer.position(), this.charbuffer.remaining());
                this.charbuffer.clear();
            }
            if (result.isUnderflow()) {
                break;
            }
        }
        // flush the decoder
        this.charDecoder.flush(this.charbuffer);
        this.charbuffer.flip();
        // append the decoded content to the line buffer
        if (this.charbuffer.hasRemaining()) {
            lineBuffer.append(this.charbuffer.array(), this.charbuffer.arrayOffset() + this.charbuffer.position(), this.charbuffer.remaining());
        }
    }
    buffer().limit(origLimit);
    // discard LF if found
    int l = lineBuffer.length();
    if (l > 0) {
        if (lineBuffer.charAt(l - 1) == Chars.LF) {
            l--;
            lineBuffer.setLength(l);
        }
        // discard CR if found
        if (l > 0 && lineBuffer.charAt(l - 1) == Chars.CR) {
            l--;
            lineBuffer.setLength(l);
        }
    }
    return true;
}
Also used : MessageConstraintException(org.apache.hc.core5.http.MessageConstraintException) CoderResult(java.nio.charset.CoderResult)

Example 47 with CharArrayBuffer

use of org.apache.hc.core5.util.CharArrayBuffer in project httpcomponents-core by apache.

the class BasicLineParser method parseStatusLine.

@Override
public StatusLine parseStatusLine(final CharArrayBuffer buffer) throws ParseException {
    Args.notNull(buffer, "Char array buffer");
    final ParserCursor cursor = new ParserCursor(0, buffer.length());
    this.tokenizer.skipWhiteSpace(buffer, cursor);
    final ProtocolVersion ver = parseProtocolVersion(buffer, cursor);
    this.tokenizer.skipWhiteSpace(buffer, cursor);
    final String s = this.tokenizer.parseToken(buffer, cursor, BLANKS);
    for (int i = 0; i < s.length(); i++) {
        if (!Character.isDigit(s.charAt(i))) {
            throw new ParseException("Status line contains invalid status code", buffer, cursor.getLowerBound(), cursor.getUpperBound(), cursor.getPos());
        }
    }
    final int statusCode;
    try {
        statusCode = Integer.parseInt(s);
    } catch (final NumberFormatException e) {
        throw new ParseException("Status line contains invalid status code", buffer, cursor.getLowerBound(), cursor.getUpperBound(), cursor.getPos());
    }
    final String text = buffer.substringTrimmed(cursor.getPos(), cursor.getUpperBound());
    return new StatusLine(ver, statusCode, text);
}
Also used : ParseException(org.apache.hc.core5.http.ParseException) ProtocolVersion(org.apache.hc.core5.http.ProtocolVersion)

Example 48 with CharArrayBuffer

use of org.apache.hc.core5.util.CharArrayBuffer in project httpcomponents-core by apache.

the class BasicLineParser method parseProtocolVersion.

ProtocolVersion parseProtocolVersion(final CharArrayBuffer buffer, final ParserCursor cursor) throws ParseException {
    final String protoname = this.protocol.getProtocol();
    final int protolength = protoname.length();
    this.tokenizer.skipWhiteSpace(buffer, cursor);
    final int pos = cursor.getPos();
    // long enough for "HTTP/1.1"?
    if (pos + protolength + 4 > cursor.getUpperBound()) {
        throw new ParseException("Invalid protocol version", buffer, cursor.getLowerBound(), cursor.getUpperBound(), cursor.getPos());
    }
    // check the protocol name and slash
    boolean ok = true;
    for (int i = 0; ok && (i < protolength); i++) {
        ok = buffer.charAt(pos + i) == protoname.charAt(i);
    }
    if (ok) {
        ok = buffer.charAt(pos + protolength) == '/';
    }
    if (!ok) {
        throw new ParseException("Invalid protocol version", buffer, cursor.getLowerBound(), cursor.getUpperBound(), cursor.getPos());
    }
    cursor.updatePos(pos + protolength + 1);
    final String token1 = this.tokenizer.parseToken(buffer, cursor, FULL_STOP);
    final int major;
    try {
        major = Integer.parseInt(token1);
    } catch (final NumberFormatException e) {
        throw new ParseException("Invalid protocol major version number", buffer, cursor.getLowerBound(), cursor.getUpperBound(), cursor.getPos());
    }
    if (cursor.atEnd()) {
        throw new ParseException("Invalid protocol version", buffer, cursor.getLowerBound(), cursor.getUpperBound(), cursor.getPos());
    }
    cursor.updatePos(cursor.getPos() + 1);
    final String token2 = this.tokenizer.parseToken(buffer, cursor, BLANKS);
    final int minor;
    try {
        minor = Integer.parseInt(token2);
    } catch (final NumberFormatException e) {
        throw new ParseException("Invalid protocol minor version number", buffer, cursor.getLowerBound(), cursor.getUpperBound(), cursor.getPos());
    }
    return HttpVersion.get(major, minor);
}
Also used : ParseException(org.apache.hc.core5.http.ParseException)

Example 49 with CharArrayBuffer

use of org.apache.hc.core5.util.CharArrayBuffer in project httpcomponents-core by apache.

the class MessageSupport method format.

public static Header format(final String name, final Set<String> tokens) {
    Args.notBlank(name, "Header name");
    if (tokens == null || tokens.isEmpty()) {
        return null;
    }
    final CharArrayBuffer buffer = new CharArrayBuffer(256);
    buffer.append(name);
    buffer.append(": ");
    formatTokens(buffer, tokens);
    return BufferedHeader.create(buffer);
}
Also used : CharArrayBuffer(org.apache.hc.core5.util.CharArrayBuffer)

Example 50 with CharArrayBuffer

use of org.apache.hc.core5.util.CharArrayBuffer in project httpcomponents-core by apache.

the class MessageSupport method parseTokens.

public static Set<String> parseTokens(final Header header) {
    Args.notNull(header, "Header");
    if (header instanceof FormattedHeader) {
        final CharArrayBuffer buf = ((FormattedHeader) header).getBuffer();
        final ParserCursor cursor = new ParserCursor(0, buf.length());
        cursor.updatePos(((FormattedHeader) header).getValuePos());
        return parseTokens(buf, cursor);
    }
    final String value = header.getValue();
    final ParserCursor cursor = new ParserCursor(0, value.length());
    return parseTokens(value, cursor);
}
Also used : CharArrayBuffer(org.apache.hc.core5.util.CharArrayBuffer) FormattedHeader(org.apache.hc.core5.http.FormattedHeader)

Aggregations

CharArrayBuffer (org.apache.hc.core5.util.CharArrayBuffer)91 Test (org.junit.jupiter.api.Test)74 SessionOutputBuffer (org.apache.hc.core5.http.nio.SessionOutputBuffer)18 ByteArrayOutputStream (java.io.ByteArrayOutputStream)16 ByteArrayInputStream (java.io.ByteArrayInputStream)14 SessionInputBuffer (org.apache.hc.core5.http.io.SessionInputBuffer)13 BasicHttpTransportMetrics (org.apache.hc.core5.http.impl.BasicHttpTransportMetrics)11 ReadableByteChannel (java.nio.channels.ReadableByteChannel)10 Header (org.apache.hc.core5.http.Header)10 WritableByteChannelMock (org.apache.hc.core5.http.WritableByteChannelMock)10 SessionInputBuffer (org.apache.hc.core5.http.nio.SessionInputBuffer)10 HeaderElement (org.apache.hc.core5.http.HeaderElement)9 SessionOutputBuffer (org.apache.hc.core5.http.io.SessionOutputBuffer)9 NameValuePair (org.apache.hc.core5.http.NameValuePair)8 MessageConstraintException (org.apache.hc.core5.http.MessageConstraintException)7 WritableByteChannel (java.nio.channels.WritableByteChannel)6 CharsetDecoder (java.nio.charset.CharsetDecoder)6 CharsetEncoder (java.nio.charset.CharsetEncoder)6 ProtocolVersion (org.apache.hc.core5.http.ProtocolVersion)6 FormattedHeader (org.apache.hc.core5.http.FormattedHeader)5