Example usage for org.apache.http.util CharArrayBuffer append

List of usage examples for org.apache.http.util CharArrayBuffer append

Introduction

In this page you can find the example usage for org.apache.http.util CharArrayBuffer append.

Prototype

public void append(Object obj) 

Source Link

Usage

From source file:com.soundcloud.playerapi.OAuth2Scheme.java

@Override
public void processChallenge(Header header) throws MalformedChallengeException {
    if (header == null) {
        throw new IllegalArgumentException("Header may not be null");
    }// www  . j a v a2s .c o  m
    String authHeader = header.getName();
    if (!authHeader.equalsIgnoreCase(AUTH.WWW_AUTH)) {
        throw new MalformedChallengeException("Unexpected header name: " + authHeader);
    }

    CharArrayBuffer buffer;
    int pos;
    if (header instanceof FormattedHeader) {
        buffer = ((FormattedHeader) header).getBuffer();
        pos = ((FormattedHeader) header).getValuePos();
    } else {
        String s = header.getValue();
        if (s == null) {
            throw new MalformedChallengeException("Header value is null");
        }
        buffer = new CharArrayBuffer(s.length());
        buffer.append(s);
        pos = 0;
    }
    while (pos < buffer.length() && HTTP.isWhitespace(buffer.charAt(pos))) {
        pos++;
    }
    int beginIndex = pos;
    while (pos < buffer.length() && !HTTP.isWhitespace(buffer.charAt(pos))) {
        pos++;
    }
    int endIndex = pos;
    String s = buffer.substring(beginIndex, endIndex);
    if (!s.equalsIgnoreCase(getSchemeName())) {
        throw new MalformedChallengeException("Invalid scheme identifier: " + s);
    }
    HeaderValueParser parser = BasicHeaderValueParser.DEFAULT;
    ParserCursor cursor = new ParserCursor(pos, buffer.length());
    HeaderElement[] elements = parser.parseElements(buffer, cursor);
    if (elements.length == 0) {
        throw new MalformedChallengeException("Authentication challenge is empty");
    }
    for (HeaderElement element : elements) {
        this.mParams.put(element.getName(), element.getValue());
    }
}

From source file:org.odk.collect.android.utilities.EnhancedDigestScheme.java

/**
 * Creates digest-response header as defined in RFC2617.
 * //from   w  ww .ja v a2 s  .  c  o m
 * @param credentials
 *            User credentials
 * 
 * @return The digest-response as String.
 */
private Header createDigestHeader(final Credentials credentials) throws AuthenticationException {
    String uri = getParameter("uri");
    String realm = getParameter("realm");
    String nonce = getParameter("nonce");
    String opaque = getParameter("opaque");
    String method = getParameter("methodname");
    String algorithm = getParameter("algorithm");
    if (uri == null) {
        throw new IllegalStateException("URI may not be null");
    }
    if (realm == null) {
        throw new IllegalStateException("Realm may not be null");
    }
    if (nonce == null) {
        throw new IllegalStateException("Nonce may not be null");
    }

    // TODO: add support for QOP_INT
    int qop = QOP_UNKNOWN;
    String qoplist = getParameter("qop");
    if (qoplist != null) {
        StringTokenizer tok = new StringTokenizer(qoplist, ",");
        while (tok.hasMoreTokens()) {
            String variant = tok.nextToken().trim();
            if (variant.equals("auth")) {
                qop = QOP_AUTH;
                break;
            }
        }
    } else {
        qop = QOP_MISSING;
    }

    if (qop == QOP_UNKNOWN) {
        throw new AuthenticationException("None of the qop methods is supported: " + qoplist);
    }

    // If an algorithm is not specified, default to MD5.
    if (algorithm == null) {
        algorithm = "MD5";
    }
    // If an charset is not specified, default to ISO-8859-1.
    String charset = getParameter("charset");
    if (charset == null) {
        charset = "ISO-8859-1";
    }

    String digAlg = algorithm;
    if (digAlg.equalsIgnoreCase("MD5-sess")) {
        digAlg = "MD5";
    }

    MessageDigest digester;
    try {
        digester = createMessageDigest(digAlg);
    } catch (UnsupportedDigestAlgorithmException ex) {
        throw new AuthenticationException("Unsuppported digest algorithm: " + digAlg);
    }

    String uname = credentials.getUserPrincipal().getName();
    String pwd = credentials.getPassword();

    if (nonce.equals(this.lastNonce)) {
        nounceCount++;
    } else {
        nounceCount = 1;
        cnonce = null;
        lastNonce = nonce;
    }
    StringBuilder sb = new StringBuilder(256);
    Formatter formatter = new Formatter(sb, Locale.US);
    formatter.format("%08x", nounceCount);
    String nc = sb.toString();

    if (cnonce == null) {
        cnonce = createCnonce();
    }

    a1 = null;
    a2 = null;
    // 3.2.2.2: Calculating digest
    if (algorithm.equalsIgnoreCase("MD5-sess")) {
        // H( unq(username-value) ":" unq(realm-value) ":" passwd )
        // ":" unq(nonce-value)
        // ":" unq(cnonce-value)

        // calculated one per session
        sb.setLength(0);
        sb.append(uname).append(':').append(realm).append(':').append(pwd);
        String checksum = encode(digester.digest(EncodingUtils.getBytes(sb.toString(), charset)));
        sb.setLength(0);
        sb.append(checksum).append(':').append(nonce).append(':').append(cnonce);
        a1 = sb.toString();
    } else {
        // unq(username-value) ":" unq(realm-value) ":" passwd
        sb.setLength(0);
        sb.append(uname).append(':').append(realm).append(':').append(pwd);
        a1 = sb.toString();
    }

    String hasha1 = encode(digester.digest(EncodingUtils.getBytes(a1, charset)));

    if (qop == QOP_AUTH) {
        // Method ":" digest-uri-value
        a2 = method + ':' + uri;
    } else if (qop == QOP_AUTH_INT) {
        // Method ":" digest-uri-value ":" H(entity-body)
        // TODO: calculate entity hash if entity is repeatable
        throw new AuthenticationException("qop-int method is not suppported");
    } else {
        a2 = method + ':' + uri;
    }

    String hasha2 = encode(digester.digest(EncodingUtils.getBytes(a2, charset)));

    // 3.2.2.1

    String digestValue;
    if (qop == QOP_MISSING) {
        sb.setLength(0);
        sb.append(hasha1).append(':').append(nonce).append(':').append(hasha2);
        digestValue = sb.toString();
    } else {
        sb.setLength(0);
        sb.append(hasha1).append(':').append(nonce).append(':').append(nc).append(':').append(cnonce)
                .append(':').append(qop == QOP_AUTH_INT ? "auth-int" : "auth").append(':').append(hasha2);
        digestValue = sb.toString();
    }

    String digest = encode(digester.digest(EncodingUtils.getAsciiBytes(digestValue)));

    CharArrayBuffer buffer = new CharArrayBuffer(128);
    if (isProxy()) {
        buffer.append(AUTH.PROXY_AUTH_RESP);
    } else {
        buffer.append(AUTH.WWW_AUTH_RESP);
    }
    buffer.append(": Digest ");

    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(20);
    params.add(new BasicNameValuePair("username", uname));
    params.add(new BasicNameValuePair("realm", realm));
    params.add(new BasicNameValuePair("nonce", nonce));
    params.add(new BasicNameValuePair("uri", uri));
    params.add(new BasicNameValuePair("response", digest));

    if (qop != QOP_MISSING) {
        params.add(new BasicNameValuePair("qop", qop == QOP_AUTH_INT ? "auth-int" : "auth"));
        params.add(new BasicNameValuePair("nc", nc));
        params.add(new BasicNameValuePair("cnonce", cnonce));
    }
    if (algorithm != null) {
        params.add(new BasicNameValuePair("algorithm", algorithm));
    }
    if (opaque != null) {
        params.add(new BasicNameValuePair("opaque", opaque));
    }

    for (int i = 0; i < params.size(); i++) {
        BasicNameValuePair param = params.get(i);
        if (i > 0) {
            buffer.append(", ");
        }
        boolean noQuotes = "nc".equals(param.getName()) || "qop".equals(param.getName());
        BasicHeaderValueFormatter.DEFAULT.formatNameValuePair(buffer, param, !noQuotes);
    }
    return new BufferedHeader(buffer);
}

From source file:com.mcxiaoke.next.http.entity.BasicHeaderValueFormatter.java

/**
 * Actually formats the value of a name-value pair.
 * This does not include a leading = character.
 * Called from {@link #formatNameValuePair formatNameValuePair}.
 *
 * @param buffer the buffer to append to, never <code>null</code>
 * @param value  the value to append, never <code>null</code>
 * @param quote  <code>true</code> to always formEncode with quotes,
 *               <code>false</code> to use quotes only when necessary
 *///from  ww  w. j  av  a 2  s  .  com
protected void doFormatValue(final CharArrayBuffer buffer, final String value, final boolean quote) {

    boolean quoteFlag = quote;
    if (!quoteFlag) {
        for (int i = 0; (i < value.length()) && !quoteFlag; i++) {
            quoteFlag = isSeparator(value.charAt(i));
        }
    }

    if (quoteFlag) {
        buffer.append('"');
    }
    for (int i = 0; i < value.length(); i++) {
        final char ch = value.charAt(i);
        if (isUnsafe(ch)) {
            buffer.append('\\');
        }
        buffer.append(ch);
    }
    if (quoteFlag) {
        buffer.append('"');
    }
}

From source file:com.gargoylesoftware.htmlunit.httpclient.HtmlUnitBrowserCompatCookieSpec.java

/**
 * {@inheritDoc}/*from  w  ww .j  a v a 2s  .  com*/
 */
@Override
public List<Cookie> parse(Header header, final CookieOrigin origin) throws MalformedCookieException {
    // first a hack to support empty headers
    final String text = header.getValue();
    int endPos = text.indexOf(';');
    if (endPos < 0) {
        endPos = text.indexOf('=');
    } else {
        final int pos = text.indexOf('=');
        if (pos > endPos) {
            endPos = -1;
        } else {
            endPos = pos;
        }
    }
    if (endPos < 0) {
        header = new BasicHeader(header.getName(), EMPTY_COOKIE_NAME + "=" + header.getValue());
    } else if (endPos == 0 || StringUtils.isBlank(text.substring(0, endPos))) {
        header = new BasicHeader(header.getName(), EMPTY_COOKIE_NAME + header.getValue());
    }

    final List<Cookie> cookies;

    final String headername = header.getName();
    if (!headername.equalsIgnoreCase(SM.SET_COOKIE)) {
        throw new MalformedCookieException("Unrecognized cookie header '" + header.toString() + "'");
    }
    final HeaderElement[] helems = header.getElements();
    boolean versioned = false;
    boolean netscape = false;
    for (final HeaderElement helem : helems) {
        if (helem.getParameterByName("version") != null) {
            versioned = true;
        }
        if (helem.getParameterByName("expires") != null) {
            netscape = true;
        }
    }
    if (netscape || !versioned) {
        // Need to parse the header again, because Netscape style cookies do not correctly
        // support multiple header elements (comma cannot be treated as an element separator)
        final NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.DEFAULT;
        final CharArrayBuffer buffer;
        final ParserCursor cursor;
        if (header instanceof FormattedHeader) {
            buffer = ((FormattedHeader) header).getBuffer();
            cursor = new ParserCursor(((FormattedHeader) header).getValuePos(), buffer.length());
        } else {
            final String s = header.getValue();
            if (s == null) {
                throw new MalformedCookieException("Header value is null");
            }
            buffer = new CharArrayBuffer(s.length());
            buffer.append(s);
            cursor = new ParserCursor(0, buffer.length());
        }
        final HeaderElement elem = parser.parseHeader(buffer, cursor);
        final String name = elem.getName();
        final String value = elem.getValue();
        if (name == null || name.isEmpty()) {
            throw new MalformedCookieException("Cookie name may not be empty");
        }
        final BasicClientCookie cookie = new BasicClientCookie(name, value);
        cookie.setPath(getDefaultPath(origin));
        cookie.setDomain(getDefaultDomain(origin));

        // cycle through the parameters
        final NameValuePair[] attribs = elem.getParameters();
        for (int j = attribs.length - 1; j >= 0; j--) {
            final NameValuePair attrib = attribs[j];
            final String s = attrib.getName().toLowerCase(Locale.ROOT);
            cookie.setAttribute(s, attrib.getValue());
            final CookieAttributeHandler handler = findAttribHandler(s);
            if (handler != null) {
                handler.parse(cookie, attrib.getValue());
            }
        }
        // Override version for Netscape style cookies
        if (netscape) {
            cookie.setVersion(0);
        }
        cookies = Collections.<Cookie>singletonList(cookie);
    } else {
        cookies = parse(helems, origin);
    }

    for (final Cookie c : cookies) {
        // re-add quotes around value if parsing as incorrectly trimmed them
        if (header.getValue().contains(c.getName() + "=\"" + c.getValue())) {
            ((BasicClientCookie) c).setValue('"' + c.getValue() + '"');
        }
    }
    return cookies;
}

From source file:com.nominanuda.web.http.HttpCoreHelper.java

private CharArrayBuffer readLine(InputStream is) throws IOException {
    CharArrayBuffer cab = new CharArrayBuffer(128);
    int status = 0;//0 reading, 1 CR seen
    while (true) {
        char c = (char) is.read();
        switch (c) {
        case (char) -1:
            throw new IOException("premature end of stream");
        case CR://  w  w  w.  j a v a 2  s  . c  om
            if (status == 1) {
                cab.append(c);
            }
            status = 1;
            break;
        case LF:
            if (status == 1) {
                return cab;
            } else {
                cab.append(LF);
            }
            break;
        default:
            cab.append(c);
            break;
        }
    }
}

From source file:com.subgraph.vega.ui.httpeditor.parser.ParserBase.java

/**
 * Get the next header line of characters from a CharArrayBuffer into another CharArrayBuffer. Treats LF and CRLF as
 * valid line delimiters. Treats the entire buffer as a line if no line delimiters are found. Supports folded header
 * field values as per the HTTP/1.1 specification.
 *    //from w  w  w . j a  v  a  2s  .  co m
 * @param src Source buffer to read line from.
 * @param srcCursor Parser cursor for src. Adjusted to discard line delimiters.
 * @param dst Destination buffer for characters from line. 
 * @return Number of characters in line minus line delimiters, or < 0 if none found.
 */
protected int readLineHeader(final CharArrayBuffer src, final ParserCursor srcCursor,
        final CharArrayBuffer dst) {
    if (srcCursor.atEnd()) {
        return -1;
    }

    int idxPos = srcCursor.getPos();
    int chCnt = 0;
    int idxLf, idxEnd;

    do {
        idxLf = src.indexOf(HTTP.LF, idxPos, srcCursor.getUpperBound());

        if (idxLf > 0) {
            if (src.charAt(idxLf - 1) == HTTP.CR) {
                idxEnd = idxLf - 1;
            } else {
                idxEnd = idxLf;
            }
        } else {
            idxEnd = srcCursor.getUpperBound();
            idxLf = idxEnd - 1;
        }

        if (chCnt != 0) {
            while (idxPos < idxEnd && (src.charAt(idxPos) == HTTP.HT || src.charAt(idxPos) == HTTP.SP)) {
                idxPos++;
            }
            if (idxPos != idxEnd) {
                dst.append(' ');
            }
        }

        dst.append(src, idxPos, idxEnd - idxPos);
        chCnt += idxEnd - idxPos;
        idxPos = idxLf + 1;
        srcCursor.updatePos(idxPos);
    } while (idxPos < srcCursor.getUpperBound()
            && (src.charAt(idxPos) == HTTP.HT || src.charAt(idxPos) == HTTP.SP));

    return chCnt;
}

From source file:org.mycard.net.network.AndroidHttpClientConnection.java

/***
 * Parses the response headers and adds them to the
 * given {@code headers} object, and returns the response StatusLine
 * @param headers store parsed header to headers.
 * @throws IOException/*from w w w . j a v  a  2 s  .com*/
 * @return StatusLine
 * @see HttpClientConnection#receiveResponseHeader()
  */
public StatusLine parseResponseHeader(Headers headers) throws IOException, ParseException {
    assertOpen();

    CharArrayBuffer current = new CharArrayBuffer(64);

    if (inbuffer.readLine(current) == -1) {
        throw new NoHttpResponseException("The target server failed to respond");
    }

    // Create the status line from the status string
    StatusLine statusline = BasicLineParser.DEFAULT.parseStatusLine(current,
            new ParserCursor(0, current.length()));

    //if (HttpLog.LOGV) HttpLog.v("read: " + statusline);
    int statusCode = statusline.getStatusCode();

    // Parse header body
    CharArrayBuffer previous = null;
    int headerNumber = 0;
    while (true) {
        if (current == null) {
            current = new CharArrayBuffer(64);
        } else {
            // This must be he buffer used to parse the status
            current.clear();
        }
        int l = inbuffer.readLine(current);
        if (l == -1 || current.length() < 1) {
            break;
        }
        // Parse the header name and value
        // Check for folded headers first
        // Detect LWS-char see HTTP/1.0 or HTTP/1.1 Section 2.2
        // discussion on folded headers
        char first = current.charAt(0);
        if ((first == ' ' || first == '\t') && previous != null) {
            // we have continuation folded header
            // so append value
            int start = 0;
            int length = current.length();
            while (start < length) {
                char ch = current.charAt(start);
                if (ch != ' ' && ch != '\t') {
                    break;
                }
                start++;
            }
            if (maxLineLength > 0 && previous.length() + 1 + current.length() - start > maxLineLength) {
                throw new IOException("Maximum line length limit exceeded");
            }
            previous.append(' ');
            previous.append(current, start, current.length() - start);
        } else {
            if (previous != null) {
                headers.parseHeader(previous);
            }
            headerNumber++;
            previous = current;
            current = null;
        }
        if (maxHeaderCount > 0 && headerNumber >= maxHeaderCount) {
            throw new IOException("Maximum header count exceeded");
        }
    }

    if (previous != null) {
        headers.parseHeader(previous);
    }

    if (statusCode >= 200) {
        this.metrics.incrementResponseCount();
    }
    return statusline;
}

From source file:com.gargoylesoftware.htmlunit.WebClient.java

/**
 * Parses the given cookie and adds this to our cookie store.
 * @param cookieString the string to parse
 * @param pageUrl the url of the page that likes to set the cookie
 * @param origin the requester//w w  w.  j  av  a  2s .  c o  m
 */
public void addCookie(final String cookieString, final URL pageUrl, final Object origin) {
    final CookieManager cookieManager = getCookieManager();
    if (cookieManager.isCookiesEnabled()) {
        final CharArrayBuffer buffer = new CharArrayBuffer(cookieString.length() + 22);
        buffer.append("Set-Cookie: ");
        buffer.append(cookieString);

        final BrowserVersion browserVersion = getBrowserVersion();
        final CookieSpec cookieSpec = new HtmlUnitBrowserCompatCookieSpec(browserVersion);

        try {
            final List<org.apache.http.cookie.Cookie> cookies = cookieSpec.parse(new BufferedHeader(buffer),
                    cookieManager.buildCookieOrigin(pageUrl));

            for (org.apache.http.cookie.Cookie cookie : cookies) {
                final Cookie htmlUnitCookie = new Cookie((ClientCookie) cookie);
                cookieManager.addCookie(htmlUnitCookie);

                if (LOG.isDebugEnabled()) {
                    LOG.debug("Added cookie: '" + cookieString + "'");
                }
            }
        } catch (final MalformedCookieException e) {
            getIncorrectnessListener().notify("set-cookie http-equiv meta tag: invalid cookie '" + cookieString
                    + "'; reason: '" + e.getMessage() + "'.", origin);
        }
    } else if (LOG.isDebugEnabled()) {
        LOG.debug("Skipped adding cookie: '" + cookieString + "'");
    }
}

From source file:org.apache.http.impl.auth.BasicScheme.java

/**
 * Produces basic authorization header for the given set of {@link Credentials}.
 *
 * @param credentials The set of credentials to be used for authentication
 * @param request The request being authenticated
 * @throws org.apache.http.auth.InvalidCredentialsException if authentication
 *   credentials are not valid or not applicable for this authentication scheme
 * @throws AuthenticationException if authorization string cannot
 *   be generated due to an authentication failure
 *
 * @return a basic authorization string/*from   ww w .  j ava2s .  c  om*/
 */
@Override
public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context)
        throws AuthenticationException {

    Args.notNull(credentials, "Credentials");
    Args.notNull(request, "HTTP request");
    final StringBuilder tmp = new StringBuilder();
    tmp.append(credentials.getUserPrincipal().getName());
    tmp.append(":");
    tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword());

    final byte[] base64password = base64codec
            .encode(EncodingUtils.getBytes(tmp.toString(), getCredentialsCharset(request)));

    final CharArrayBuffer buffer = new CharArrayBuffer(32);
    if (isProxy()) {
        buffer.append(AUTH.PROXY_AUTH_RESP);
    } else {
        buffer.append(AUTH.WWW_AUTH_RESP);
    }
    buffer.append(": Basic ");
    buffer.append(base64password, 0, base64password.length);

    return new BufferedHeader(buffer);
}

From source file:org.apache.http.impl.auth.BasicScheme.java

/**
 * Returns a basic <tt>Authorization</tt> header value for the given
 * {@link Credentials} and charset.//from   w w w  .  j a va 2  s .  c  om
 *
 * @param credentials The credentials to encode.
 * @param charset The charset to use for encoding the credentials
 *
 * @return a basic authorization header
 *
 * @deprecated (4.3) use {@link #authenticate(Credentials, HttpRequest, HttpContext)}.
 */
@Deprecated
public static Header authenticate(final Credentials credentials, final String charset, final boolean proxy) {
    Args.notNull(credentials, "Credentials");
    Args.notNull(charset, "charset");

    final StringBuilder tmp = new StringBuilder();
    tmp.append(credentials.getUserPrincipal().getName());
    tmp.append(":");
    tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword());

    final byte[] base64password = Base64.encodeBase64(EncodingUtils.getBytes(tmp.toString(), charset), false);

    final CharArrayBuffer buffer = new CharArrayBuffer(32);
    if (proxy) {
        buffer.append(AUTH.PROXY_AUTH_RESP);
    } else {
        buffer.append(AUTH.WWW_AUTH_RESP);
    }
    buffer.append(": Basic ");
    buffer.append(base64password, 0, base64password.length);

    return new BufferedHeader(buffer);
}