/**
   * Estimates the length of a formatted name-value pair.
   *
   * @param nvp the name-value pair to format, or <code>null</code>
   * @return a length estimate, in number of characters
   */
  protected int estimateNameValuePairLen(final NameValuePair nvp) {
    if (nvp == null) return 0;

    int result = nvp.getName().length(); // name
    final String value = nvp.getValue();
    if (value != null) {
      // assume quotes, but no escaped characters
      result += 3 + value.length(); // ="value"
    }
    return result;
  }
  // non-javadoc, see interface HeaderValueFormatter
  public CharArrayBuffer formatNameValuePair(
      CharArrayBuffer buffer, final NameValuePair nvp, final boolean quote) {
    if (nvp == null) {
      throw new IllegalArgumentException("NameValuePair must not be null.");
    }

    int len = estimateNameValuePairLen(nvp);
    if (buffer == null) {
      buffer = new CharArrayBuffer(len);
    } else {
      buffer.ensureCapacity(len);
    }

    buffer.append(nvp.getName());
    final String value = nvp.getValue();
    if (value != null) {
      buffer.append('=');
      doFormatValue(buffer, value, quote);
    }

    return buffer;
  }
Example #3
0
  private List<Cookie> createCookies(final HeaderElement[] elems, final CookieOrigin origin)
      throws MalformedCookieException {
    List<Cookie> cookies = new ArrayList<Cookie>(elems.length);
    for (HeaderElement headerelement : elems) {
      String name = headerelement.getName();
      String value = headerelement.getValue();
      if (name == null || name.length() == 0) {
        throw new MalformedCookieException("Cookie name may not be empty");
      }

      BasicClientCookie2 cookie = new BasicClientCookie2(name, value);
      cookie.setPath(getDefaultPath(origin));
      cookie.setDomain(getDefaultDomain(origin));
      cookie.setPorts(new int[] {origin.getPort()});
      // cycle through the parameters
      NameValuePair[] attribs = headerelement.getParameters();

      // Eliminate duplicate attributes. The first occurrence takes precedence
      // See RFC2965: 3.2  Origin Server Role
      Map<String, NameValuePair> attribmap = new HashMap<String, NameValuePair>(attribs.length);
      for (int j = attribs.length - 1; j >= 0; j--) {
        NameValuePair param = attribs[j];
        attribmap.put(param.getName().toLowerCase(Locale.ENGLISH), param);
      }
      for (Map.Entry<String, NameValuePair> entry : attribmap.entrySet()) {
        NameValuePair attrib = entry.getValue();
        String s = attrib.getName().toLowerCase(Locale.ENGLISH);

        cookie.setAttribute(s, attrib.getValue());

        CookieAttributeHandler handler = findAttribHandler(s);
        if (handler != null) {
          handler.parse(cookie, attrib.getValue());
        }
      }
      cookies.add(cookie);
    }
    return cookies;
  }