Search in sources :

Example 11 with ParserCursor

use of org.apache.hc.core5.http.message.ParserCursor 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 12 with ParserCursor

use of org.apache.hc.core5.http.message.ParserCursor 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 13 with ParserCursor

use of org.apache.hc.core5.http.message.ParserCursor 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)

Example 14 with ParserCursor

use of org.apache.hc.core5.http.message.ParserCursor in project californium by eclipse.

the class CrossProtocolTranslator method getCoapOptions.

/**
 * Gets the coap options starting from an array of http headers.
 *
 * The content-type is not handled by this method. The method iterates over
 * an array of headers and for each of them tries to find a mapping in the
 * properties file, if the mapping does not exists it skips the header
 * ignoring it. The method handles separately certain headers which are
 * translated to options (such as accept or cache-control) whose content
 * should be semantically checked or requires ad-hoc translation. Otherwise,
 * the headers content is translated with the appropriate format required by
 * the mapped option.
 *
 * @param headers array of http headers
 * @param etagTranslator translator for etag
 * @return list of CoAP options.
 * @throws NullPointerException if headers is {@code null}
 */
public List<Option> getCoapOptions(Header[] headers, EtagTranslator etagTranslator) {
    if (headers == null) {
        throw new NullPointerException("http header must not be null!");
    }
    Option accept = null;
    float acceptQualifier = 0.0F;
    List<Option> optionList = new LinkedList<Option>();
    // iterate over the headers
    for (Header header : headers) {
        try {
            String headerName = header.getName().toLowerCase();
            // get the mapping from the property file
            Integer coapOption = translationMapping.getCoapOption(headerName);
            // ignore the header if not found in the properties file
            if (coapOption == null) {
                continue;
            }
            int optionNumber = coapOption;
            // payload
            if (optionNumber == OptionNumberRegistry.CONTENT_FORMAT) {
                continue;
            }
            // get the value of the current header
            String headerValue = header.getValue().trim();
            // values
            if (optionNumber == OptionNumberRegistry.ACCEPT) {
                final ParserCursor cursor = new ParserCursor(0, headerValue.length());
                HeaderElement[] headerElements = parser.parseElements(headerValue, cursor);
                for (HeaderElement element : headerElements) {
                    float qualifier = 1.0F;
                    String mimeType = element.getName();
                    NameValuePair q = element.getParameterByName("q");
                    if (q != null) {
                        try {
                            qualifier = Float.parseFloat(q.getValue());
                        } catch (NumberFormatException ex) {
                        }
                    }
                    if (accept == null || acceptQualifier < qualifier) {
                        int coapContentType = MediaTypeRegistry.UNDEFINED;
                        String headerFragment = mimeType.trim();
                        if (headerFragment.contains("*")) {
                            int[] coapContentTypes = MediaTypeRegistry.parseWildcard(headerFragment);
                            if (coapContentTypes.length > 0) {
                                coapContentType = coapContentTypes[0];
                            }
                        } else {
                            coapContentType = getCoapMediaType(headerFragment, MediaTypeRegistry.UNDEFINED);
                        }
                        if (coapContentType != MediaTypeRegistry.UNDEFINED) {
                            accept = new Option(optionNumber, coapContentType);
                            acceptQualifier = qualifier;
                        }
                    }
                }
            } else if (optionNumber == OptionNumberRegistry.MAX_AGE) {
                int maxAge = -1;
                final ParserCursor cursor = new ParserCursor(0, headerValue.length());
                HeaderElement[] headerElements = parser.parseElements(headerValue, cursor);
                for (HeaderElement element : headerElements) {
                    if (element.getName().equalsIgnoreCase("no-cache")) {
                        maxAge = 0;
                        break;
                    } else if (element.getName().equalsIgnoreCase("max-age")) {
                        String value = element.getValue();
                        try {
                            maxAge = Integer.parseInt(value);
                            break;
                        } catch (NumberFormatException e) {
                            LOGGER.debug("Cannot convert cache control '{}' in max-age option", value, e);
                        }
                    }
                }
                if (maxAge >= 0) {
                    // create the option
                    Option option = new Option(optionNumber, maxAge);
                    optionList.add(option);
                }
            } else if (optionNumber == OptionNumberRegistry.ETAG) {
                byte[] etag = etagTranslator.getCoapEtag(headerValue);
                Option option = new Option(optionNumber, etag);
                optionList.add(option);
            } else if (optionNumber == OptionNumberRegistry.IF_MATCH) {
                byte[] etag = etagTranslator.getCoapEtag(headerValue);
                Option option = new Option(optionNumber, etag);
                optionList.add(option);
            } else if (optionNumber == OptionNumberRegistry.IF_NONE_MATCH) {
                if (headerValue.equals("*")) {
                    Option option = new Option(optionNumber, Bytes.EMPTY);
                    optionList.add(option);
                } else {
                    LOGGER.debug("'if-none-match' with etag '{}' is not supported!", headerValue);
                }
            } else if (optionNumber == OptionNumberRegistry.LOCATION_PATH) {
                try {
                    URI uri = new URI(headerValue);
                    OptionSet set = new OptionSet();
                    String value = uri.getPath();
                    if (value != null) {
                        set.setLocationPath(value);
                    }
                    value = uri.getQuery();
                    if (value != null) {
                        set.setLocationQuery(value);
                    }
                    optionList.addAll(set.asSortedList());
                } catch (URISyntaxException e) {
                    LOGGER.debug("'content-location' with '{}' is not supported!", headerValue, e);
                } catch (IllegalArgumentException e) {
                    LOGGER.debug("'content-location' with '{}' is not supported!", headerValue, e);
                }
            } else {
                // create the option
                Option option = new Option(optionNumber);
                switch(OptionNumberRegistry.getFormatByNr(optionNumber)) {
                    case INTEGER:
                        option.setIntegerValue(Integer.parseInt(headerValue));
                        break;
                    case OPAQUE:
                        option.setValue(headerValue.getBytes(ISO_8859_1));
                        break;
                    case EMPTY:
                        option.setValue(Bytes.EMPTY);
                        break;
                    case STRING:
                    default:
                        option.setStringValue(headerValue);
                        break;
                }
                optionList.add(option);
            }
        } catch (RuntimeException e) {
            LOGGER.debug("Could not parse header line {}: {}", header, e.getMessage());
        }
    }
    if (accept != null) {
        optionList.add(accept);
    }
    return optionList;
}
Also used : ParserCursor(org.apache.hc.core5.http.message.ParserCursor) NameValuePair(org.apache.hc.core5.http.NameValuePair) HeaderElement(org.apache.hc.core5.http.HeaderElement) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) LinkedList(java.util.LinkedList) BasicHeader(org.apache.hc.core5.http.message.BasicHeader) Header(org.apache.hc.core5.http.Header) Option(org.eclipse.californium.core.coap.Option) OptionSet(org.eclipse.californium.core.coap.OptionSet)

Example 15 with ParserCursor

use of org.apache.hc.core5.http.message.ParserCursor in project light-4j by networknt.

the class DistinguishedNameParser method parse.

List<NameValuePair> parse(final String s) {
    if (s == null) {
        return null;
    }
    final CharArrayBuffer buffer = new CharArrayBuffer(s.length());
    buffer.append(s);
    final ParserCursor cursor = new ParserCursor(0, s.length());
    return parse(buffer, cursor);
}
Also used : ParserCursor(org.apache.hc.core5.http.message.copied.ParserCursor) CharArrayBuffer(org.apache.hc.core5.util.copied.CharArrayBuffer)

Aggregations

CharArrayBuffer (org.apache.hc.core5.util.CharArrayBuffer)12 Test (org.junit.jupiter.api.Test)11 HeaderElement (org.apache.hc.core5.http.HeaderElement)8 NameValuePair (org.apache.hc.core5.http.NameValuePair)7 ArrayList (java.util.ArrayList)5 ParserCursor (org.apache.hc.core5.http.message.ParserCursor)4 ParseException (org.apache.hc.core5.http.ParseException)3 FormattedHeader (org.apache.hc.core5.http.FormattedHeader)2 Header (org.apache.hc.core5.http.Header)2 ProtocolVersion (org.apache.hc.core5.http.ProtocolVersion)2 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 LinkedList (java.util.LinkedList)1 HttpVersion (org.apache.hc.core5.http.HttpVersion)1 NameValuePair (org.apache.hc.core5.http.copied.NameValuePair)1 BasicHeader (org.apache.hc.core5.http.message.BasicHeader)1 BasicNameValuePair (org.apache.hc.core5.http.message.BasicNameValuePair)1 BasicNameValuePair (org.apache.hc.core5.http.message.copied.BasicNameValuePair)1 ParserCursor (org.apache.hc.core5.http.message.copied.ParserCursor)1 Tokenizer (org.apache.hc.core5.util.Tokenizer)1