类org.apache.http.util.CharArrayBuffer源码实例Demo

下面列出了怎么用org.apache.http.util.CharArrayBuffer的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: docker-java-api   文件: ReadLogString.java
/**
 * Docker logs contains header
 * [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}
 * STREAM_TYPE
 * 0: stdin (is written on stdout)
 * 1: stdout
 * 2: stderr
 *
 * SIZE1, SIZE2, SIZE3, SIZE4 are the four bytes of the uint32 size
 * encoded as big endian.
 *
 * 1) Read 8 bytes from reader.
 * 2) Choose not stdin(0) depending on the first byte.
 * 3) Extract the frame size from the last four bytes.
 * 4) Read the extracted size from reader and save it in buffer in circle.
 * 5) Goto 1.
 *
 * @param buffer Buffer for save message.
 * @param reader Reader for read message.
 * @throws IOException if the entity cannot be read
 */
private void read(final CharArrayBuffer buffer,
                  final Reader reader) throws IOException {
    char[] controlChars = new char[8];
    int len;
    while (reader.read(controlChars) != -1) {
        if (controlChars[0] != 0) {
            long byteInLine = this.getUInt(controlChars);
            char[] stdout;
            if (byteInLine > 1024) {
                stdout = new char[1024];
            } else {
                stdout = new char[(int) byteInLine];
            }
            while (byteInLine > 0) {
                len = reader.read(stdout);
                byteInLine -= len;
                if (len != -1) {
                    buffer.append(stdout, 0, len);
                }
            }
        }
    }
}
 
源代码2 项目: ats-framework   文件: GGSSchemeBase.java
@Override
protected void parseChallenge(
                               final CharArrayBuffer buffer,
                               int beginIndex,
                               int endIndex ) throws MalformedChallengeException {

    String challenge = buffer.substringTrimmed(beginIndex, endIndex);
    if (log.isDebugEnabled()) {
        log.debug("Received challenge '" + challenge + "' from the auth server");
    }
    if (state == State.UNINITIATED) {
        token = base64codec.decode(challenge.getBytes());
        state = State.CHALLENGE_RECEIVED;
    } else {
        log.debug("Authentication already attempted");
        state = State.FAILED;
    }
}
 
@Override
protected void parseChallenge(
    final CharArrayBuffer buffer,
    final int beginIndex,
    final int endIndex) {
    this.challenge = buffer.substringTrimmed(beginIndex, endIndex);

    if(this.challenge.isEmpty()) {
        if(clientCred != null) {
            dispose(); // run cleanup first before throwing an exception otherwise can leak OS resources
            if(continueNeeded) {
                throw new RuntimeException("Unexpected token");
            }
        }
    }
}
 
源代码4 项目: BigApp_Discuz_Android   文件: URLEncodedUtils.java
/**
 * Returns a list of {@link org.apache.http.NameValuePair NameValuePairs} as parsed.
 *
 * @param s text to parse.
 * @since 4.2
 */
public static List<NameValuePair> parse(final String s) {
    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(nvp.getName(), nvp.getValue()));
        }
    }
    return list;
}
 
源代码5 项目: hawkular-agent   文件: JolokiaClientFactory.java
@Override
public Header authenticate(Credentials credentials, HttpRequest request, HttpContext context)
        throws AuthenticationException {
    Args.notNull(credentials, "Credentials");
    Args.notNull(request, "HTTP request");

    // the bearer token is stored in the password field, not credentials.getUserPrincipal().getName()
    String bearerToken = credentials.getPassword();

    CharArrayBuffer buffer = new CharArrayBuffer(64);
    if (isProxy()) {
        buffer.append("Proxy-Authorization");
    } else {
        buffer.append("Authorization");
    }
    buffer.append(": Bearer ");
    buffer.append(bearerToken);

    return new BufferedHeader(buffer);
}
 
源代码6 项目: gecco   文件: HttpClientDownloader.java
public String getContent(InputStream instream, long contentLength, String charset) throws IOException {
try {
	if (instream == null) {
           return null;
       }
       int i = (int)contentLength;
       if (i < 0) {
           i = 4096;
       }
       Reader reader = new InputStreamReader(instream, charset);
       CharArrayBuffer buffer = new CharArrayBuffer(i);
       char[] tmp = new char[1024];
       int l;
       while((l = reader.read(tmp)) != -1) {
           buffer.append(tmp, 0, l);
       }
       return buffer.toString();
} finally {
	Objects.requireNonNull(instream).reset();
}
      
  }
 
源代码7 项目: cs-actions   文件: HeadersBuilder.java
public List<Header> buildHeaders() {
    ArrayList<Header> headersArr = new ArrayList<>();
    if (!StringUtils.isEmpty(headers)) {
        BufferedReader in = new BufferedReader(new StringReader(headers));

        String str;
        try {
            while ((str = in.readLine()) != null) {
                CharArrayBuffer charArrayBuffer = new CharArrayBuffer(str.length());
                charArrayBuffer.append(str);
                headersArr.add(new BufferedHeader(charArrayBuffer));
            }
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
    }

    if (entityContentType != null) {
        headersArr.add(entityContentType);
    } else if (contentType != null && !contentType.toString().isEmpty()) {
        headersArr.add(new BasicHeader("Content-Type", contentType.toString()));
    }
    return headersArr;
}
 
/**
 * Returns a list of {@link org.apache.http.NameValuePair NameValuePairs} as parsed.
 *
 * @param s text to parse.
 * @since 4.2
 */
public static List<NameValuePair> parse(final String s) {
    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(nvp.getName(), nvp.getValue()));
        }
    }
    return list;
}
 
源代码9 项目: RoboZombie   文件: URLEncodedUtils.java
/**
 * Returns a list of {@link NameValuePair NameValuePairs} as deserialized from the given string
 * using the given character encoding.
 *
 * @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 deserializer = 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 = deserializer.parseNameValuePair(buffer, cursor, DELIM);
        if (nvp.getName().length() > 0) {
            list.add(new BasicNameValuePair(
                    decodeFormFields(nvp.getName(), charset),
                    decodeFormFields(nvp.getValue(), charset)));
        }
    }
    return list;
}
 
源代码10 项目: htmlunit   文件: HtmlUnitBrowserCompatCookieSpec.java
@Override
public List<Header> formatCookies(final List<Cookie> cookies) {
    Collections.sort(cookies, COOKIE_COMPARATOR);

    final CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size());
    buffer.append(SM.COOKIE);
    buffer.append(": ");
    for (int i = 0; i < cookies.size(); i++) {
        final Cookie cookie = cookies.get(i);
        if (i > 0) {
            buffer.append("; ");
        }
        final String cookieName = cookie.getName();
        final String cookieValue = cookie.getValue();
        if (cookie.getVersion() > 0 && !isQuoteEnclosed(cookieValue)) {
            HtmlUnitBrowserCompatCookieHeaderValueFormatter.INSTANCE.formatHeaderElement(
                    buffer,
                    new BasicHeaderElement(cookieName, cookieValue),
                    false);
        }
        else {
            // Netscape style cookies do not support quoted values
            buffer.append(cookieName);
            buffer.append("=");
            if (cookieValue != null) {
                buffer.append(cookieValue);
            }
        }
    }
    final List<Header> headers = new ArrayList<>(1);
    headers.add(new BufferedHeader(buffer));
    return headers;
}
 
源代码11 项目: Elasticsearch   文件: LocalRestChannel.java
@Override
public void doSendResponse(RestResponse response) {
    status = response.status().getStatus();

    byte[] bytes = response.content().toBytes();
    long length = bytes.length;
    Args.check(length <= Integer.MAX_VALUE, "HTTP entity too large to be buffered in memory");
    if(length < 0) {
        length = 4096;
    }

    InputStream instream =  new ByteArrayInputStream(bytes);
    InputStreamReader reader = new InputStreamReader(instream, Consts.UTF_8);
    CharArrayBuffer buffer = new CharArrayBuffer((int)length);
    char[] tmp = new char[1024];

    int l;
    try {
        while ((l = reader.read(tmp)) != -1) {
            buffer.append(tmp, 0, l);
        }
        content = buffer.toString();
    } catch (IOException e) {
        status = RestStatus.INTERNAL_SERVER_ERROR.getStatus();
        content = "IOException: " + e.getMessage();
    } finally {
        try {
            reader.close();
            instream.close();
        } catch (IOException e1) {
            content = "IOException: " + e1.getMessage();
        } finally {
            count.countDown();
        }
    }
}
 
源代码12 项目: BUbiNG   文件: ByteArraySessionOutputBuffer.java
@Override
public void writeLine(final CharArrayBuffer buffer) throws IOException {
	if (buffer == null) return;
	for (int i = 0; i < buffer.length(); i++) {
		write(buffer.charAt(i));
	}
	write(CRLF);
}
 
源代码13 项目: BUbiNG   文件: InputStreamTestMocks.java
public static String[] readCRLFSeparatedBlock(SessionInputBuffer input) throws IOException {
	CharArrayBuffer line = new CharArrayBuffer(128);
	List<String> ret = new ArrayList<>();
	for (;;) {
		if (input.readLine(line) == -1) break;
		if (line.length() == 0) break;
		ret.add(line.toString());
		line.clear();
	}
	return ret.toArray(new String[ret.size()]);
}
 
源代码14 项目: lavaplayer   文件: ExtendedHttpClientBuilder.java
@Override
protected boolean reject(CharArrayBuffer line, int count) {
  if (line.length() > 4 && "ICY ".equals(line.substring(0, 4))) {
    throw new FriendlyException("ICY protocol is not supported.", COMMON, null);
  } else if (count > 10) {
    throw new FriendlyException("The server is giving us garbage.", SUSPICIOUS, null);
  }

  return false;
}
 
源代码15 项目: lavaplayer   文件: ExtendedHttpClientBuilder.java
@Override
public ProtocolVersion parseProtocolVersion(CharArrayBuffer buffer, ParserCursor cursor) {
  int index = cursor.getPos();
  int bound = cursor.getUpperBound();

  if (bound >= index + 4 && "ICY ".equals(buffer.substring(index, index + 4))) {
    cursor.updatePos(index + 4);
    return ICY_PROTOCOL;
  }

  return super.parseProtocolVersion(buffer, cursor);
}
 
源代码16 项目: lavaplayer   文件: ExtendedHttpClientBuilder.java
@Override
public boolean hasProtocolVersion(CharArrayBuffer buffer, ParserCursor cursor) {
  int index = cursor.getPos();
  int bound = cursor.getUpperBound();

  if (bound >= index + 4 && "ICY ".equals(buffer.substring(index, index + 4))) {
    return true;
  }

  return super.hasProtocolVersion(buffer, cursor);
}
 
源代码17 项目: MediaPlayerProxy   文件: HttpUtils.java
@Override
public boolean hasProtocolVersion(CharArrayBuffer buffer, ParserCursor cursor) {
	boolean superFound = super.hasProtocolVersion(buffer, cursor);
	if (superFound) {
		return true;
	}
	int index = cursor.getPos();

	final int protolength = ICY_PROTOCOL_NAME.length();

	if (buffer.length() < protolength)
		return false; // not long enough for "HTTP/1.1"

	if (index < 0) {
		// end of line, no tolerance for trailing whitespace
		// this works only for single-digit major and minor version
		index = buffer.length() - protolength;
	} else if (index == 0) {
		// beginning of line, tolerate leading whitespace
		while ((index < buffer.length()) && HTTP.isWhitespace(buffer.charAt(index))) {
			index++;
		}
	} // else within line, don't tolerate whitespace

	return index + protolength <= buffer.length()
			&& buffer.substring(index, index + protolength).equals(ICY_PROTOCOL_NAME);

}
 
源代码18 项目: MediaPlayerProxy   文件: HttpUtils.java
@Override
public ProtocolVersion parseProtocolVersion(CharArrayBuffer buffer, 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");
	}

	final int protolength = ICY_PROTOCOL_NAME.length();

	int indexFrom = cursor.getPos();
	int indexTo = cursor.getUpperBound();

	skipWhitespace(buffer, cursor);

	int i = cursor.getPos();

	// long enough for "HTTP/1.1"?
	if (i + protolength + 4 > indexTo) {
		throw new ParseException("Not a valid protocol version: " + buffer.substring(indexFrom, indexTo));
	}

	// check the protocol name and slash
	if (!buffer.substring(i, i + protolength).equals(ICY_PROTOCOL_NAME)) {
		return super.parseProtocolVersion(buffer, cursor);
	}

	cursor.updatePos(i + protolength);

	return createProtocolVersion(1, 0);
}
 
@Override
public Header parseHeader(final CharArrayBuffer buffer) throws ParseException {
  try {
    return super.parseHeader(buffer);
  } catch (ParseException ex) {
    // Suppress ParseException exception
    return new BasicHeader("invalid", buffer.toString());
  }
}
 
源代码20 项目: docker-java-api   文件: ReadLogString.java
/**
 * Docker logs contains header
 * [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}
 * STREAM_TYPE
 * 0: stdin (is written on stdout)
 * 1: stdout
 * 2: stderr
 *
 * SIZE1, SIZE2, SIZE3, SIZE4 are the four bytes of the uint32 size
 * encoded as big endian.
 *
 * This method do:
 *
 * 1) Read 8 bytes.
 * 2) Choose stdout or stderr depending on the first byte.
 * 3) Extract the frame size from the last four bytes.
 * 4) Read the extracted size and output it on the correct output.
 * 5) Goto 1.
 *
 * @param entity HttpEntity for read message.
 * @return Logs from container in String.
 * @throws IOException if the entity cannot be read
 */
private String toString(final HttpEntity entity) throws IOException {
    final InputStream instream = entity.getContent();
    final CharArrayBuffer buffer = new CharArrayBuffer(
            this.getCapacity(entity)
    );
    if (instream != null) {
        try {
            final Reader reader = new InputStreamReader(
                    instream,
                    this.getCharset(ContentType.get(entity))
            );
            this.read(buffer, reader);
        } finally {
            instream.close();
        }
    }
    return buffer.toString();
}
 
源代码21 项目: TVRemoteIME   文件: HTTPGet.java
public static String readString(String uri){
    HTTPSTrustManager.allowAllSSL();
    try {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "text/html, application/xhtml+xml, image/jxr, */*");
        conn.setRequestProperty("Accept-Encoding", "identity");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
        int code = conn.getResponseCode();
        if (code == 200) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            try {
                int length = conn.getContentLength();
                if (length < 0) {
                    length = 4096;
                }
                CharArrayBuffer buffer = new CharArrayBuffer(length);
                char[] tmp = new char[1024];

                int l;
                while ((l = reader.read(tmp)) != -1) {
                    buffer.append(tmp, 0, l);
                }
                return buffer.toString();
            }finally {

                reader.close();
            }
        } else {
            return null;
        }
    } catch (Exception e) {
        Log.e("HTTPGet", "readString", e);
    }
    finally {

    }
    return null;
}
 
源代码22 项目: MediaPlayerProxy   文件: HttpUtils.java
@Override
public StatusLine parseStatusLine(CharArrayBuffer buffer, ParserCursor cursor) throws ParseException {
	return super.parseStatusLine(buffer, cursor);
}
 
源代码23 项目: RoboZombie   文件: EntityUtils.java
/**
 * Get the entity content as a String, using the provided default character set
 * if none is found in the entity.
 * If defaultCharset is null, the default "ISO-8859-1" is used.
 *
 * @param entity must not be null
 * @param defaultCharset character set to be applied if none found in the entity
 * @return the entity content as a String. May be null if
 *   {@link HttpEntity#getContent()} is null.
 * @throws ParseException if header elements cannot be deserialized
 * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE
 * @throws IOException if an error occurs reading the input stream
 */
public static String toString(
        final HttpEntity entity, final Charset defaultCharset) throws IOException, ParseException {
    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }
    InputStream instream = entity.getContent();
    if (instream == null) {
        return null;
    }
    try {
        if (entity.getContentLength() > Integer.MAX_VALUE) {
            throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
        }
        int i = (int)entity.getContentLength();
        if (i < 0) {
            i = 4096;
        }
        Charset charset = null;
        try {
            ContentType contentType = ContentType.getOrDefault(entity);
            charset = contentType.getCharset();
        } catch (UnsupportedCharsetException ex) {
            throw new UnsupportedEncodingException(ex.getMessage());
        }
        if (charset == null) {
            charset = defaultCharset;
        }
        if (charset == null) {
            charset = HTTP.DEF_CONTENT_CHARSET;
        }
        Reader reader = new InputStreamReader(instream, charset);
        CharArrayBuffer buffer = new CharArrayBuffer(i);
        char[] tmp = new char[1024];
        int l;
        while((l = reader.read(tmp)) != -1) {
            buffer.append(tmp, 0, l);
        }
        return buffer.toString();
    } finally {
        instream.close();
    }
}
 
源代码24 项目: httpsig-java   文件: Http4SignatureAuthScheme.java
@Override
protected void parseChallenge(CharArrayBuffer buffer, int pos, int len) throws MalformedChallengeException {
    super.parseChallenge(buffer, pos, len);
    this.rotate = true;
}
 
 类所在包
 同包方法