Search in sources :

Example 11 with HeaderElement

use of org.apache.hc.core5.http.HeaderElement in project dialogue by palantir.

the class InactivityValidationAwareConnectionKeepAliveStrategy method getKeepAliveDuration.

@Override
public TimeValue getKeepAliveDuration(HttpResponse response, HttpContext context) {
    Iterator<HeaderElement> headerElementIterator = MessageSupport.iterate(response, HeaderElements.KEEP_ALIVE);
    while (headerElementIterator.hasNext()) {
        HeaderElement headerElement = headerElementIterator.next();
        String headerElementName = headerElement.getName();
        String headerElementValue = headerElement.getValue();
        if (headerElementValue != null && TIMEOUT_ELEMENT.equalsIgnoreCase(headerElementName)) {
            try {
                long keepAliveTimeoutSeconds = Long.parseLong(headerElementValue);
                if (keepAliveTimeoutSeconds > 0) {
                    TimeValue keepAliveValue = TimeValue.ofSeconds(keepAliveTimeoutSeconds);
                    updateInactivityValidationInterval(response.getCode(), keepAliveValue);
                    return keepAliveValue;
                }
            } catch (NumberFormatException nfe) {
                log.debug("invalid timeout value {}", SafeArg.of("timeoutValue", headerElementValue), nfe);
            }
        }
    }
    HttpClientContext clientContext = HttpClientContext.adapt(context);
    RequestConfig requestConfig = clientContext.getRequestConfig();
    updateInactivityValidationInterval(response.getCode(), defaultValidateAfterInactivity);
    return requestConfig.getConnectionKeepAlive();
}
Also used : RequestConfig(org.apache.hc.client5.http.config.RequestConfig) HeaderElement(org.apache.hc.core5.http.HeaderElement) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) TimeValue(org.apache.hc.core5.util.TimeValue)

Example 12 with HeaderElement

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

use of org.apache.hc.core5.http.HeaderElement in project httpcomponents-core by apache.

the class TestHeaderElement method testConstructor3.

@Test
public void testConstructor3() throws Exception {
    final HeaderElement element = new BasicHeaderElement("name", "value", new NameValuePair[] { new BasicNameValuePair("param1", "value1"), new BasicNameValuePair("param2", "value2") });
    Assertions.assertEquals("name", element.getName());
    Assertions.assertEquals("value", element.getValue());
    Assertions.assertEquals(2, element.getParameters().length);
    Assertions.assertEquals("value1", element.getParameterByName("param1").getValue());
    Assertions.assertEquals("value2", element.getParameterByName("param2").getValue());
}
Also used : HeaderElement(org.apache.hc.core5.http.HeaderElement) Test(org.junit.jupiter.api.Test)

Example 14 with HeaderElement

use of org.apache.hc.core5.http.HeaderElement in project httpcomponents-core by apache.

the class TestHeaderElement method testConstructor2.

@Test
public void testConstructor2() throws Exception {
    final HeaderElement element = new BasicHeaderElement("name", "value");
    Assertions.assertEquals("name", element.getName());
    Assertions.assertEquals("value", element.getValue());
    Assertions.assertEquals(0, element.getParameters().length);
}
Also used : HeaderElement(org.apache.hc.core5.http.HeaderElement) Test(org.junit.jupiter.api.Test)

Example 15 with HeaderElement

use of org.apache.hc.core5.http.HeaderElement in project httpcomponents-core by apache.

the class TestBasicHeaderElementIterator method testMultiHeaderSameLine.

@Test
public void testMultiHeaderSameLine() {
    final Header[] headers = new Header[] { new BasicHeader("name", "value0,value1"), new BasicHeader("nAme", "cookie1=1,cookie2=2") };
    final Iterator<HeaderElement> hei = new BasicHeaderElementIterator(new BasicHeaderIterator(headers, "Name"));
    HeaderElement elem = hei.next();
    Assertions.assertEquals("value0", elem.getName(), "The two header values must be equal");
    elem = hei.next();
    Assertions.assertEquals("value1", elem.getName(), "The two header values must be equal");
    elem = hei.next();
    Assertions.assertEquals("cookie1", elem.getName(), "The two header values must be equal");
    Assertions.assertEquals("1", elem.getValue(), "The two header values must be equal");
    elem = hei.next();
    Assertions.assertEquals("cookie2", elem.getName(), "The two header values must be equal");
    Assertions.assertEquals("2", elem.getValue(), "The two header values must be equal");
}
Also used : Header(org.apache.hc.core5.http.Header) HeaderElement(org.apache.hc.core5.http.HeaderElement) Test(org.junit.jupiter.api.Test)

Aggregations

HeaderElement (org.apache.hc.core5.http.HeaderElement)17 Test (org.junit.jupiter.api.Test)13 CharArrayBuffer (org.apache.hc.core5.util.CharArrayBuffer)9 NameValuePair (org.apache.hc.core5.http.NameValuePair)5 Header (org.apache.hc.core5.http.Header)3 ParserCursor (org.apache.hc.core5.http.message.ParserCursor)2 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 ArrayList (java.util.ArrayList)1 LinkedList (java.util.LinkedList)1 RequestConfig (org.apache.hc.client5.http.config.RequestConfig)1 HttpClientContext (org.apache.hc.client5.http.protocol.HttpClientContext)1 HttpRequest (org.apache.hc.core5.http.HttpRequest)1 ProtocolVersion (org.apache.hc.core5.http.ProtocolVersion)1 BasicHeader (org.apache.hc.core5.http.message.BasicHeader)1 TimeValue (org.apache.hc.core5.util.TimeValue)1 Option (org.eclipse.californium.core.coap.Option)1 OptionSet (org.eclipse.californium.core.coap.OptionSet)1