org.apache.http.util.CharArrayBuffer Java Examples

The following examples show how to use org.apache.http.util.CharArrayBuffer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: URLEncodedUtils.java    From android-open-project-demo with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #2
Source File: ReadLogString.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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);
                }
            }
        }
    }
}
 
Example #3
Source File: HeadersBuilder.java    From cs-actions with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #4
Source File: GGSSchemeBase.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
@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;
    }
}
 
Example #5
Source File: BackportWindowsNegotiateScheme.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@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");
            }
        }
    }
}
 
Example #6
Source File: HttpClientDownloader.java    From gecco with MIT License 6 votes vote down vote up
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();
}
      
  }
 
Example #7
Source File: JolokiaClientFactory.java    From hawkular-agent with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #8
Source File: URLEncodedUtils.java    From BigApp_Discuz_Android with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #9
Source File: URLEncodedUtils.java    From RoboZombie with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #10
Source File: ExtendedHttpClientBuilder.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #11
Source File: CustomConnectionsHttpClientFactory.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@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());
  }
}
 
Example #12
Source File: HttpUtils.java    From MediaPlayerProxy with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #13
Source File: HttpUtils.java    From MediaPlayerProxy with Apache License 2.0 5 votes vote down vote up
@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);

}
 
Example #14
Source File: ExtendedHttpClientBuilder.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #15
Source File: ExtendedHttpClientBuilder.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #16
Source File: InputStreamTestMocks.java    From BUbiNG with Apache License 2.0 5 votes vote down vote up
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()]);
}
 
Example #17
Source File: ByteArraySessionOutputBuffer.java    From BUbiNG with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #18
Source File: LocalRestChannel.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@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();
        }
    }
}
 
Example #19
Source File: HtmlUnitBrowserCompatCookieSpec.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #20
Source File: Http4SignatureAuthScheme.java    From httpsig-java with The Unlicense 4 votes vote down vote up
@Override
protected void parseChallenge(CharArrayBuffer buffer, int pos, int len) throws MalformedChallengeException {
    super.parseChallenge(buffer, pos, len);
    this.rotate = true;
}
 
Example #21
Source File: EntityUtils.java    From RoboZombie with Apache License 2.0 4 votes vote down vote up
/**
 * 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();
    }
}
 
Example #22
Source File: HttpUtils.java    From MediaPlayerProxy with Apache License 2.0 4 votes vote down vote up
@Override
public StatusLine parseStatusLine(CharArrayBuffer buffer, ParserCursor cursor) throws ParseException {
	return super.parseStatusLine(buffer, cursor);
}
 
Example #23
Source File: HTTPGet.java    From TVRemoteIME with GNU General Public License v2.0 4 votes vote down vote up
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;
}
 
Example #24
Source File: ReadLogString.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * 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();
}