public static String getFileNameFromHttpResponse(final HttpResponse response) { if (response == null) return null; String result = null; Header header = response.getFirstHeader("Content-Disposition"); if (header != null) { for (HeaderElement element : header.getElements()) { NameValuePair fileNamePair = element.getParameterByName("filename"); if (fileNamePair != null) { result = fileNamePair.getValue(); // try to get correct encoding str result = CharsetUtils.toCharset(result, HTTP.UTF_8, result.length()); break; } } } return result; }
public static String getCharsetFromHttpResponse(final HttpResponse response) { if (response == null) return null; String result = null; Header header = response.getEntity().getContentType(); if (header != null) { for (HeaderElement element : header.getElements()) { NameValuePair charsetPair = element.getParameterByName("charset"); if (charsetPair != null) { result = charsetPair.getValue(); break; } } } boolean isSupportedCharset = false; if (!TextUtils.isEmpty(result)) { try { isSupportedCharset = Charset.isSupported(result); } catch (Throwable e) { } } return isSupportedCharset ? result : null; }
public HeaderElement parseHeader( final CharArrayBuffer buffer, final ParserCursor cursor) throws ParseException { if (buffer == null) { throw new IllegalArgumentException("Char array buffer may not be null"); } if (cursor == null) { throw new IllegalArgumentException("Parser cursor may not be null"); } NameValuePair nvp = parseNameValuePair(buffer, cursor); List<NameValuePair> params = new ArrayList<NameValuePair>(); while (!cursor.atEnd()) { NameValuePair param = parseNameValuePair(buffer, cursor); params.add(param); } return new BasicHeaderElement( nvp.getName(), nvp.getValue(), params.toArray(new NameValuePair[params.size()])); }
public long getKeepAliveDuration(HttpResponse response, HttpContext context) { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); } HeaderElementIterator it = new BasicHeaderElementIterator( response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { try { return Long.parseLong(value) * 1000; } catch(NumberFormatException ignore) { } } } return -1; }
/** * Obtains character set of the entity, if known. * * @param entity must not be null * @return the character set, or null if not found * @throws ParseException if header elements cannot be parsed * @throws IllegalArgumentException if entity is null * * @deprecated (4.1.3) use {@link ContentType#getOrDefault(HttpEntity)} */ @Deprecated public static String getContentCharSet(final HttpEntity entity) throws ParseException { if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); } String charset = null; if (entity.getContentType() != null) { HeaderElement values[] = entity.getContentType().getElements(); if (values.length > 0) { NameValuePair param = values[0].getParameterByName("charset"); if (param != null) { charset = param.getValue(); } } } return charset; }
public Set<String> getAllowedMethods(final HttpResponse response) { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); } HeaderIterator it = response.headerIterator("Allow"); Set<String> methods = new HashSet<String>(); while (it.hasNext()) { Header header = it.nextHeader(); HeaderElement[] elements = header.getElements(); for (HeaderElement element : elements) { methods.add(element.getName()); } } return methods; }
@Override public List<Cookie> parse( final Header header, CookieOrigin origin) throws MalformedCookieException { if (header == null) { throw new IllegalArgumentException("Header may not be null"); } if (origin == null) { throw new IllegalArgumentException("Cookie origin may not be null"); } if (!header.getName().equalsIgnoreCase(SM.SET_COOKIE2)) { throw new MalformedCookieException("Unrecognized cookie header '" + header.toString() + "'"); } origin = adjustEffectiveHost(origin); HeaderElement[] elems = header.getElements(); return createCookies(elems, origin); }
private static ContentType create(final HeaderElement helem) { String mimeType = helem.getName(); String charset = null; NameValuePair param = helem.getParameterByName("charset"); if (param != null) { charset = param.getValue(); } return create(mimeType, charset); }
/** * Estimates the length of a formatted header element. * * @param elem the header element to format, or <code>null</code> * * @return a length estimate, in number of characters */ protected int estimateHeaderElementLen(final HeaderElement elem) { if (elem == null) return 0; int result = elem.getName().length(); // name final String value = elem.getValue(); if (value != null) { // assume quotes, but no escaped characters result += 3 + value.length(); // ="value" } final int parcnt = elem.getParameterCount(); if (parcnt > 0) { for (int i=0; i<parcnt; i++) { result += 2 + // ; <param> estimateNameValuePairLen(elem.getParameter(i)); } } return result; }
/** * Parses elements with the given parser. * * @param value the header value to parse * @param parser the parser to use, or <code>null</code> for default * * @return array holding the header elements, never <code>null</code> */ public final static HeaderElement[] parseElements(final String value, HeaderValueParser parser) throws ParseException { if (value == null) { throw new IllegalArgumentException ("Value to parse may not be null"); } if (parser == null) parser = BasicHeaderValueParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); ParserCursor cursor = new ParserCursor(0, value.length()); return parser.parseElements(buffer, cursor); }
public HeaderElement[] parseElements(final CharArrayBuffer buffer, final ParserCursor cursor) { if (buffer == null) { throw new IllegalArgumentException("Char array buffer may not be null"); } if (cursor == null) { throw new IllegalArgumentException("Parser cursor may not be null"); } List<HeaderElement> elements = new ArrayList<HeaderElement>(); while (!cursor.atEnd()) { HeaderElement element = parseHeaderElement(buffer, cursor); if (!(element.getName().length() == 0 && element.getValue() == null)) { elements.add(element); } } return elements.toArray(new HeaderElement[elements.size()]); }
/** * Parses an element with the given parser. * * @param value the header element to parse * @param parser the parser to use, or <code>null</code> for default * * @return the parsed header element */ public final static HeaderElement parseHeaderElement(final String value, HeaderValueParser parser) throws ParseException { if (value == null) { throw new IllegalArgumentException ("Value to parse may not be null"); } if (parser == null) parser = BasicHeaderValueParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); ParserCursor cursor = new ParserCursor(0, value.length()); return parser.parseHeaderElement(buffer, cursor); }
public HeaderElement parseHeaderElement(final CharArrayBuffer buffer, final ParserCursor cursor) { if (buffer == null) { throw new IllegalArgumentException("Char array buffer may not be null"); } if (cursor == null) { throw new IllegalArgumentException("Parser cursor may not be null"); } NameValuePair nvp = parseNameValuePair(buffer, cursor); NameValuePair[] params = null; if (!cursor.atEnd()) { char ch = buffer.charAt(cursor.getPos() - 1); if (ch != ELEM_DELIMITER) { params = parseParameters(buffer, cursor); } } return createHeaderElement(nvp.getName(), nvp.getValue(), params); }
public String getContentTypeCharset(String defaultCharset) { List<String> values = getHeader(Http.Headers.CONTENT_TYPE); if (values!=null) { for (String value: values) { HeaderElement[] headerElements = BasicHeaderValueParser.parseElements(value, (HeaderValueParser) null); if (headerElements!=null && headerElements.length>0) { NameValuePair charsetPair = headerElements[0].getParameterByName("charset"); if (charsetPair!=null) { return charsetPair.getValue(); } } } } return defaultCharset; }
@Override public long getKeepAliveDuration(HttpResponse response, HttpContext context) { HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { long timeout = Long.parseLong(value) * 1000; if (timeout > 20 * 1000) { return 20 * 1000; } else { return timeout; } } } return 5 * 1000; }
public static Charset getCharsetFromHttpRequest(final HttpRequestBase request) { if (request == null) return null; String charsetName = null; Header header = request.getFirstHeader("Content-Type"); if (header != null) { for (HeaderElement element : header.getElements()) { NameValuePair charsetPair = element.getParameterByName("charset"); if (charsetPair != null) { charsetName = charsetPair.getValue(); break; } } } boolean isSupportedCharset = false; if (!TextUtils.isEmpty(charsetName)) { try { isSupportedCharset = Charset.isSupported(charsetName); } catch (Throwable e) { } } return isSupportedCharset ? Charset.forName(charsetName) : null; }
@Override public long getKeepAliveDuration(HttpResponse response, HttpContext context) { // Honor 'keep-alive' header HeaderElementIterator it = new BasicHeaderElementIterator( response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { try { return Long.parseLong(value) * 1000; } catch (NumberFormatException ignore) { // Do nothing } } } // otherwise keep alive for 30 seconds return 30 * 1000; }
@Test public void testExplictContractorParams() throws Exception { final HttpEntity entity = MultipartEntityBuilder.create() .setLaxMode() .setBoundary("whatever") .setCharset(MIME.UTF8_CHARSET) .build(); Assert.assertNull(entity.getContentEncoding()); Assert.assertNotNull(entity.getContentType()); final Header header = entity.getContentType(); final HeaderElement[] elems = header.getElements(); Assert.assertNotNull(elems); Assert.assertEquals(1, elems.length); final HeaderElement elem = elems[0]; Assert.assertEquals("multipart/form-data", elem.getName()); final NameValuePair p1 = elem.getParameterByName("boundary"); Assert.assertNotNull(p1); Assert.assertEquals("whatever", p1.getValue()); final NameValuePair p2 = elem.getParameterByName("charset"); Assert.assertNotNull(p2); Assert.assertEquals("UTF-8", p2.getValue()); }
@Test public void valid() { Header[] headers = {new Header() { public String getName() { return "session_id"; } public String getValue() { return "12345"; } public HeaderElement[] getElements() throws ParseException { return new HeaderElement[0]; } }}; ApiClientResponse response = new ApiClientResponse(headers, "{\"key\":\"value\"}"); assertEquals("12345", response.getHeader("session_id")); assertEquals("{\n \"key\" : \"value\"\n}", response.toJson()); assertEquals("value", response.getField("key")); }
/** * Estimates the length of a formatted header element. * * @param elem the header element to format, or <code>null</code> * * @return a length estimate, in number of characters */ protected int estimateHeaderElementLen(final HeaderElement elem) { if (elem == null) { return 0; } int result = elem.getName().length(); // name final String value = elem.getValue(); if (value != null) { // assume quotes, but no escaped characters result += 3 + value.length(); // ="value" } final int parcnt = elem.getParameterCount(); if (parcnt > 0) { for (int i=0; i<parcnt; i++) { result += 2 + // ; <param> estimateNameValuePairLen(elem.getParameter(i)); } } return result; }
/** * Obtains character set of the entity, if known. * * @param entity must not be null * @return the character set, or null if not found * @throws ParseException if header elements cannot be parsed * @throws IllegalArgumentException if entity is null * * @deprecated (4.1.3) use {@link ContentType#getOrDefault(HttpEntity)} */ @Deprecated public static String getContentCharSet(final HttpEntity entity) throws ParseException { Args.notNull(entity, "Entity"); String charset = null; if (entity.getContentType() != null) { final HeaderElement values[] = entity.getContentType().getElements(); if (values.length > 0) { final NameValuePair param = values[0].getParameterByName("charset"); if (param != null) { charset = param.getValue(); } } } return charset; }
public long getKeepAliveDuration(final HttpResponse response, final HttpContext context) { Args.notNull(response, "HTTP response"); final HeaderElementIterator it = new BasicHeaderElementIterator( response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { final HeaderElement he = it.nextElement(); final String param = he.getName(); final String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { try { return Long.parseLong(value) * 1000; } catch(final NumberFormatException ignore) { } } } return -1; }
private HttpResponse httpResponse(String sessionIdInResult, String version) throws IOException { final HttpResponse httpResponseMock = mock(HttpResponse.class); StatusLine statusLineMock = mock(StatusLine.class); when(httpResponseMock.getStatusLine()).thenReturn(statusLineMock); when(statusLineMock.getStatusCode()).thenReturn(200); addMockedHeader(httpResponseMock, Headers.SESSION_ID, sessionIdInResult, null); addMockedHeader(httpResponseMock, Headers.VERSION, version, null); HeaderElement[] headerElements = new HeaderElement[1]; headerElements[0] = mock(HeaderElement.class); final HttpEntity httpEntityMock = mock(HttpEntity.class); when(httpResponseMock.getEntity()).thenReturn(httpEntityMock); final InputStream inputs = new ByteArrayInputStream("fake response data".getBytes()); when(httpEntityMock.getContent()).thenReturn(inputs); return httpResponseMock; }
@Test public void createCookieForHeaderElementTest() { String cookiePath = "/client/api"; String paramName = "paramName1"; String paramValue = "paramVale1"; NameValuePair[] parameters = new NameValuePair[1]; parameters[0] = new BasicNameValuePair(paramName, paramValue); String headerName = "headerElementName"; String headerValue = "headerElementValue"; HeaderElement headerElement = new BasicHeaderElement(headerName, headerValue, parameters); Mockito.doNothing().when(apacheCloudStackClient).configureDomainForCookie(Mockito.any(BasicClientCookie.class)); BasicClientCookie cookieForHeaderElement = apacheCloudStackClient.createCookieForHeaderElement(headerElement); Assert.assertNotNull(cookieForHeaderElement); Assert.assertEquals(headerName, cookieForHeaderElement.getName()); Assert.assertEquals(headerValue, cookieForHeaderElement.getValue()); Assert.assertEquals(paramValue, cookieForHeaderElement.getAttribute(paramName)); Assert.assertEquals(cookiePath, cookieForHeaderElement.getPath()); Mockito.verify(apacheCloudStackClient).configureDomainForCookie(Mockito.eq(cookieForHeaderElement)); }
@NotNull public static Collection<String> getTokenScopes(@NotNull GithubConnection connection) throws IOException { Header[] headers = connection.headRequest("/user", ACCEPT_V3_JSON); Header scopesHeader = null; for (Header header : headers) { if (header.getName().equals("X-OAuth-Scopes")) { scopesHeader = header; break; } } if (scopesHeader == null) { throw new GithubConfusingException("No scopes header"); } Collection<String> scopes = new ArrayList<String>(); for (HeaderElement elem : scopesHeader.getElements()) { scopes.add(elem.getName()); } return scopes; }
@Override public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) { HeaderElementIterator headerElementIterator = new BasicHeaderElementIterator(httpResponse.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (headerElementIterator.hasNext()) { HeaderElement headerElement = headerElementIterator.nextElement(); String name = headerElement.getName(); String value = headerElement.getValue(); if (value != null && name.equalsIgnoreCase("timeout")) { return Long.parseLong(value) * 1000; } } // Set own keep alive duration if server does not have it return applicationConfiguration.getRptConnectionPoolCustomKeepAliveTimeout() * 1000; }
private boolean explicitFreshnessRequest(final HttpRequestWrapper request, final HttpCacheEntry entry, final Date now) { for(final Header h : request.getHeaders(HeaderConstants.CACHE_CONTROL)) { for(final HeaderElement elt : h.getElements()) { if (HeaderConstants.CACHE_CONTROL_MAX_STALE.equals(elt.getName())) { try { final int maxstale = Integer.parseInt(elt.getValue()); final long age = validityPolicy.getCurrentAgeSecs(entry, now); final long lifetime = validityPolicy.getFreshnessLifetimeSecs(entry); if (age - lifetime > maxstale) { return true; } } catch (final NumberFormatException nfe) { return true; } } else if (HeaderConstants.CACHE_CONTROL_MIN_FRESH.equals(elt.getName()) || HeaderConstants.CACHE_CONTROL_MAX_AGE.equals(elt.getName())) { return true; } } } return false; }
private boolean explicitFreshnessRequest( final HttpRequestWrapper request, final HttpCacheEntry entry, final Date now) { for(final Header h : request.getHeaders(HeaderConstants.CACHE_CONTROL)) { for(final HeaderElement elt : h.getElements()) { if (HeaderConstants.CACHE_CONTROL_MAX_STALE.equals(elt.getName())) { try { final int maxstale = Integer.parseInt(elt.getValue()); final long age = validityPolicy.getCurrentAgeSecs(entry, now); final long lifetime = validityPolicy.getFreshnessLifetimeSecs(entry); if (age - lifetime > maxstale) { return true; } } catch (final NumberFormatException nfe) { return true; } } else if (HeaderConstants.CACHE_CONTROL_MIN_FRESH.equals(elt.getName()) || HeaderConstants.CACHE_CONTROL_MAX_AGE.equals(elt.getName())) { return true; } } } return false; }
public boolean mayReturnStaleWhileRevalidating(final HttpCacheEntry entry, final Date now) { for (final Header h : entry.getHeaders(HeaderConstants.CACHE_CONTROL)) { for(final HeaderElement elt : h.getElements()) { if (HeaderConstants.STALE_WHILE_REVALIDATE.equalsIgnoreCase(elt.getName())) { try { final int allowedStalenessLifetime = Integer.parseInt(elt.getValue()); if (getStalenessSecs(entry, now) <= allowedStalenessLifetime) { return true; } } catch (final NumberFormatException nfe) { // skip malformed directive } } } } return false; }
private boolean mayReturnStaleIfError(final Header[] headers, final long stalenessSecs) { boolean result = false; for(final Header h : headers) { for(final HeaderElement elt : h.getElements()) { if (HeaderConstants.STALE_IF_ERROR.equals(elt.getName())) { try { final int staleIfErrorSecs = Integer.parseInt(elt.getValue()); if (stalenessSecs <= staleIfErrorSecs) { result = true; break; } } catch (final NumberFormatException nfe) { // skip malformed directive } } } } return result; }
protected long getMaxAge(final HttpCacheEntry entry) { long maxage = -1; for (final Header hdr : entry.getHeaders(HeaderConstants.CACHE_CONTROL)) { for (final HeaderElement elt : hdr.getElements()) { if (HeaderConstants.CACHE_CONTROL_MAX_AGE.equals(elt.getName()) || "s-maxage".equals(elt.getName())) { try { final long currMaxAge = Long.parseLong(elt.getValue()); if (maxage == -1 || currMaxAge < maxage) { maxage = currMaxAge; } } catch (final NumberFormatException nfe) { // be conservative if can't parse maxage = 0; } } } } return maxage; }
private void stripOtherFreshnessDirectivesWithNoCache(final HttpRequest request) { final List<HeaderElement> outElts = new ArrayList<HeaderElement>(); boolean shouldStrip = false; for(final Header h : request.getHeaders(HeaderConstants.CACHE_CONTROL)) { for(final HeaderElement elt : h.getElements()) { if (!disallowedWithNoCache.contains(elt.getName())) { outElts.add(elt); } if (HeaderConstants.CACHE_CONTROL_NO_CACHE.equals(elt.getName())) { shouldStrip = true; } } } if (!shouldStrip) { return; } request.removeHeaders(HeaderConstants.CACHE_CONTROL); request.setHeader(HeaderConstants.CACHE_CONTROL, buildHeaderFromElements(outElts)); }
@Test public void testImplictContractorParams() throws Exception { final HttpEntity entity = MultipartEntityBuilder.create().build(); Assert.assertNull(entity.getContentEncoding()); Assert.assertNotNull(entity.getContentType()); final Header header = entity.getContentType(); final HeaderElement[] elems = header.getElements(); Assert.assertNotNull(elems); Assert.assertEquals(1, elems.length); final HeaderElement elem = elems[0]; Assert.assertEquals("multipart/form-data", elem.getName()); final NameValuePair p1 = elem.getParameterByName("boundary"); Assert.assertNotNull(p1); final String boundary = p1.getValue(); Assert.assertNotNull(boundary); Assert.assertTrue(boundary.length() >= 30); Assert.assertTrue(boundary.length() <= 40); final NameValuePair p2 = elem.getParameterByName("charset"); Assert.assertNull(p2); }