Java Code Examples for org.apache.http.util.CharArrayBuffer#append()

The following examples show how to use org.apache.http.util.CharArrayBuffer#append() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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();
    }
}