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

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

Introduction

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

Prototype

public CharArrayBuffer(int i) 

Source Link

Usage

From source file:com.androidquery.test.NTLMScheme.java

public Header authenticate(final Credentials credentials, final HttpRequest request)
        throws AuthenticationException {
    NTCredentials ntcredentials = null;//from  www  .  j  av a  2  s . co  m
    try {
        ntcredentials = (NTCredentials) credentials;
    } catch (ClassCastException e) {
        throw new InvalidCredentialsException(
                "Credentials cannot be used for NTLM authentication: " + credentials.getClass().getName());
    }
    String response = null;
    if (this.state == State.CHALLENGE_RECEIVED || this.state == State.FAILED) {
        response = this.engine.generateType1Msg(ntcredentials.getDomain(), ntcredentials.getWorkstation());
        this.state = State.MSG_TYPE1_GENERATED;
    } else if (this.state == State.MSG_TYPE2_RECEVIED) {
        response = this.engine.generateType3Msg(ntcredentials.getUserName(), ntcredentials.getPassword(),
                ntcredentials.getDomain(), ntcredentials.getWorkstation(), this.challenge);
        this.state = State.MSG_TYPE3_GENERATED;
    } else {
        throw new AuthenticationException("Unexpected state: " + this.state);
    }
    CharArrayBuffer buffer = new CharArrayBuffer(32);
    if (isProxy()) {
        buffer.append(AUTH.PROXY_AUTH_RESP);
    } else {
        buffer.append(AUTH.WWW_AUTH_RESP);
    }
    buffer.append(": NTLM ");
    buffer.append(response);
    return new BufferedHeader(buffer);
}

From source file:com.google.resting.component.impl.ServiceResponse.java

@Override
public String toString() {
    int length = 150;
    length = contentData.getContentLength() + length;
    for (Header header : responseHeaders) {
        length += header.getName().length() + header.getValue().length() + 3;
    }/*  ww w  . j a  va 2 s.  c  om*/
    CharArrayBuffer buffer = new CharArrayBuffer(length);
    buffer.append("\nServiceResponse\n---------------\nHTTP Status: ");
    buffer.append(statusCode);
    buffer.append("\nHeaders: \n");
    for (Header header : responseHeaders) {
        buffer.append(header.getName());
        buffer.append(" : ");
        buffer.append(header.getValue());
        buffer.append("\n");
    }

    buffer.append("Response body: \n");
    buffer.append(contentData);
    buffer.append("\n----------------\n");

    return buffer.toString();
}

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");
    }/*from   ww w.j av a  2  s.c  om*/
    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:cn.aage.robot.http.entity.ContentType.java

/**
 * Generates textual representation of this content type which can be used as the value
 * of a <code>Content-Type</code> header.
 *///w ww. j a  v  a 2s .c  om
@Override
public String toString() {
    final CharArrayBuffer buf = new CharArrayBuffer(64);
    buf.append(this.mimeType);
    if (this.params != null) {
        buf.append("; ");
        BasicHeaderValueFormatter.DEFAULT.formatParameters(buf, this.params, false);
    } else if (this.charset != null) {
        buf.append("; charset=");
        buf.append(this.charset.name());
    }
    return buf.toString();
}

From source file:org.vietspider.net.apache.DefaultResponseParser.java

public static Header[] parseHeaders(final SessionInputBuffer inbuffer, int maxHeaderCount, int maxLineLen,
        LineParser parser) throws HttpException, IOException {

    if (inbuffer == null) {
        throw new IllegalArgumentException("Session input buffer may not be null");
    }/*from   w  w  w.  j  a va  2  s .  c  o  m*/

    if (parser == null)
        parser = BasicLineParser.DEFAULT;

    ArrayList<CharArrayBuffer> headerLines = new ArrayList<CharArrayBuffer>();

    CharArrayBuffer current = null;
    CharArrayBuffer previous = null;
    for (;;) {
        if (current == null) {
            current = new CharArrayBuffer(64);
        } else {
            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
        if ((current.charAt(0) == ' ' || current.charAt(0) == '\t') && previous != null) {
            // we have continuation folded header
            // so append value
            int i = 0;
            while (i < current.length()) {
                char ch = current.charAt(i);
                if (ch != ' ' && ch != '\t') {
                    break;
                }
                i++;
            }
            if (maxLineLen > 0 && previous.length() + 1 + current.length() - i > maxLineLen) {
                throw new IOException("Maximum line length limit exceeded");
            }
            previous.append(' ');
            previous.append(current, i, current.length() - i);
        } else {
            headerLines.add(current);
            previous = current;
            current = null;
        }

        if (maxHeaderCount > 0 && headerLines.size() >= maxHeaderCount) {
            throw new IOException("Maximum header count exceeded");
        }
    }

    Header[] headers = new Header[headerLines.size()];
    for (int i = 0; i < headerLines.size(); i++) {
        CharArrayBuffer buffer = headerLines.get(i);
        try {
            headers[i] = parser.parseHeader(buffer);
        } catch (ParseException ex) {
            throw new ProtocolException(ex.getMessage());
        }
    }
    return headers;
}

From source file:me.xiaopan.android.gohttp.JsonHttpResponseHandler.java

private String toString(HttpRequest httpRequest, final HttpEntity entity, final String defaultCharset)
        throws IOException, ParseException {
    InputStream inputStream = entity.getContent();
    if (inputStream == null) {
        return "";
    }//from  www. ja  va  2s . co  m
    if (entity.getContentLength() > Integer.MAX_VALUE) {
        throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
    }
    int contentLength = (int) entity.getContentLength();
    if (contentLength < 0) {
        contentLength = 4096;
    }
    String charset = StringHttpResponseHandler.getContentCharSet(entity);
    if (charset == null) {
        charset = defaultCharset;
    }
    if (charset == null) {
        charset = HTTP.DEFAULT_CONTENT_CHARSET;
    }

    long averageLength = contentLength / httpRequest.getProgressCallbackNumber();
    int callbackNumber = 0;
    Reader reader = new InputStreamReader(inputStream, charset);
    CharArrayBuffer buffer = new CharArrayBuffer(contentLength);
    HttpRequest.ProgressListener progressListener = httpRequest.getProgressListener();
    try {
        char[] tmp = new char[1024];
        int readLength;
        long completedLength = 0;
        while (!httpRequest.isStopReadData() && (readLength = reader.read(tmp)) != -1) {
            buffer.append(tmp, 0, readLength);
            completedLength += readLength;
            if (progressListener != null && !httpRequest.isCanceled()
                    && (completedLength >= (callbackNumber + 1) * averageLength
                            || completedLength == contentLength)) {
                callbackNumber++;
                new HttpRequestHandler.UpdateProgressRunnable(httpRequest, contentLength, completedLength)
                        .execute();
            }
        }
    } finally {
        reader.close();
    }
    return buffer.toString();
}

From source file:cn.mimessage.and.sdk.net.request.DefaultValuePair.java

/**
 * Get a string representation of this pair.
 * /*www.  jav  a  2 s .c om*/
 * @return A string representation.
 */
@Override
public String toString() {
    // don't call complex default formatting for a simple toString

    int len = this.name.length();
    if (this.value != null)
        len += 1 + this.value.length();
    CharArrayBuffer buffer = new CharArrayBuffer(len);

    buffer.append(this.name);
    if (this.value != null) {
        buffer.append("=");
        buffer.append(this.value);
    }
    return buffer.toString();
}

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

/**
 * Parse HTTP headers and add them to a IHttpMessageBuilder until a non-header line is encountered.
 * //from w  w  w .java  2s . c o  m
 * @param parser HC line parser.
 * @param builder IHttpMessageBuilder to add parsed headers to.
 * @param buf Buffer containing header data.
 * @param bufCursor Parser cursor for buf. Adjusted to one character past the end of headers and optional CRLF line.
 */
protected void parseHeaders(final LineParser parser, final IHttpMessageBuilder builder,
        final CharArrayBuffer buf, final ParserCursor bufCursor) {
    final CharArrayBuffer lnBuf = new CharArrayBuffer(0);
    while (true) {
        lnBuf.clear();
        int idxPos = bufCursor.getPos();
        if (readLineHeader(buf, bufCursor, lnBuf) > 0) {
            try {
                // REVISIT don't want an extra step
                Header header = parser.parseHeader(lnBuf);
                builder.addHeader(header.getName(), header.getValue());
            } catch (ParseException e) {
                // for now we'll move the cursor back so the line gets treated as the start of the body
                bufCursor.updatePos(idxPos);
                return;
            }
        } else {
            break;
        }
    }
}

From source file:com.sina.cloudstorage.util.URLEncodedUtils.java

/**
 * Returns a list of {@link NameValuePair NameValuePairs} as parsed from the given string
 * using the given character encoding./*from   w w w .  j a  va  2  s  . co  m*/
 *
 * @param s
 *            text to parse.
 * @param charset
 *            Encoding to use when decoding the parameters.
 *
 * @since 4.2
 */
public static List<NameValuePair> parse(final String s, final Charset charset) {
    if (s == null) {
        return Collections.emptyList();
    }
    BasicHeaderValueParser parser = BasicHeaderValueParser.DEFAULT;
    CharArrayBuffer buffer = new CharArrayBuffer(s.length());
    buffer.append(s);
    ParserCursor cursor = new ParserCursor(0, buffer.length());
    List<NameValuePair> list = new ArrayList<NameValuePair>();
    while (!cursor.atEnd()) {
        NameValuePair nvp = parser.parseNameValuePair(buffer, cursor, DELIM);
        if (nvp.getName().length() > 0) {
            list.add(new BasicNameValuePair(decode(nvp.getName(), charset), decode(nvp.getValue(), charset)));
        }
    }
    return list;
}

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

public CharArrayBuffer formatElements(final CharArrayBuffer charBuffer, final HeaderElement[] elems,
        final boolean quote) {
    AssertUtils.notNull(elems, "Header element array");
    final int len = estimateElementsLen(elems);
    CharArrayBuffer buffer = charBuffer;
    if (buffer == null) {
        buffer = new CharArrayBuffer(len);
    } else {//  w  w w .j a va  2 s.  c o m
        buffer.ensureCapacity(len);
    }

    for (int i = 0; i < elems.length; i++) {
        if (i > 0) {
            buffer.append(", ");
        }
        formatHeaderElement(buffer, elems[i], quote);
    }

    return buffer;
}