Example usage for org.apache.http.util ByteArrayBuffer length

List of usage examples for org.apache.http.util ByteArrayBuffer length

Introduction

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

Prototype

public int length() 

Source Link

Usage

From source file:android.wulongdao.thirdparty.mime.HttpMultipart.java

private static void writeBytes(final ByteArrayBuffer b, final OutputStream out) throws IOException {
    out.write(b.buffer(), 0, b.length());
}

From source file:cn.isif.util_plus.http.client.multipart.HttpMultipart.java

private static void writeBytes(final ByteArrayBuffer b, final OutputStream out) throws IOException {
    out.write(b.buffer(), 0, b.length());
    out.flush();/*from   w ww. j  a  v  a  2s .c o  m*/
}

From source file:topoos.APIAccess.mime.HttpMultipart.java

/**
 * Write bytes.//  w  ww  . j a  va2s . c o m
 *
 * @param b the b
 * @param out the out
 * @throws IOException Signals that an I/O exception has occurred.
 */
private static void writeBytes(final ByteArrayBuffer b, final OutputStream out) throws IOException {
    out.write(b.buffer(), 0, b.length());
}

From source file:de.rub.syssec.saaf.misc.ByteUtils.java

/**
 * Read a line from an inputstream into a byte buffer. A line might end with a LF or an CRLF. CR's are accepted inside a line and
 * are not understood as a beginning new line. This should work therefore on Mac OS X, Unix, Linux and Windows.
 * /*from   w w w  . j a v a 2  s. c o m*/
 * See http://en.wikipedia.org/wiki/Newline for more.
 *  
 * @param in the inputstream
 * @param maxSize the maximum amount of bytes to read until a CRLF or LF is reached, a value of zero or smaller disables a limit (use w/ care!)
 * @return the buffer where read bytes are appended, this buffer will not contain any CR's or or CRLF's at the end of the array. Null is
 * returned if EOF is reached.
 * @throws IOException if something is wrong w/ the stream or the maxSize is reached
 */
public static byte[] parseLine(BufferedInputStream in, int maxSize) throws IOException {
    ByteArrayBuffer bab = new ByteArrayBuffer(512);
    int b;
    while (true) {
        if (!(maxSize <= 0 || bab.length() <= maxSize)) {
            throw new IOException("Maximal bytearraybuffer size of " + maxSize + " exceeded!");
        }
        b = in.read();
        if (b == -1) {
            if (bab.isEmpty()) {
                // we have nothing read yet and could nothing read, we will therefore return 'null' as this
                // indicates EOF.
                return null;
            } else {
                // return what we got so far
                return bab.toByteArray();
            }
        }
        // CRLF case
        if (b == '\r') { // check if we find a \n
            int next = in.read();
            if (b == -1) {
                // EOF; return what we got
                return bab.toByteArray();
            } else if (next == '\n') { // we did
                in.mark(-1); // rest mark
                return bab.toByteArray(); // return the line without CRLF
            } else {
                // found no CRLF but only a CR and some other byte, so we need to add both to the buffer and proceed
                bab.append('\r');
                bab.append(b);
            }
        }
        // LF case
        else if (b == '\n') { // we found a LF and therefore the end of a line
            return bab.toByteArray();
        } else { // we just found a byte which is happily appended
            bab.append(b);
        }
    }
}

From source file:crow.weibo.util.WeiboUtil.java

public static String multipartPost(HttpURLConnection conn, List<PostParameter> params) throws IOException {
    OutputStream os;//from www. jav  a2s . c o m
    List<PostParameter> dataparams = new ArrayList<PostParameter>();
    for (PostParameter key : params) {
        if (key.isFile()) {
            dataparams.add(key);
        }
    }

    String BOUNDARY = Util.md5(String.valueOf(System.currentTimeMillis()));

    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Charsert", "UTF-8");

    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);

    ByteArrayBuffer buff = new ByteArrayBuffer(1000);

    for (PostParameter p : params) {
        byte[] arr = p.toMultipartByte(BOUNDARY, "UTF-8");
        buff.append(arr, 0, arr.length);
    }
    String end = "--" + BOUNDARY + "--" + "\r\n";
    byte[] endArr = end.getBytes();
    buff.append(endArr, 0, endArr.length);

    conn.setRequestProperty("Content-Length", buff.length() + "");
    conn.connect();
    os = new BufferedOutputStream(conn.getOutputStream());
    os.write(buff.toByteArray());
    buff.clear();
    os.flush();
    String response = "";
    response = Util.inputStreamToString(conn.getInputStream());
    return response;
}

From source file:org.zywx.wbpalmstar.engine.eservice.EServiceTest.java

private static byte[] toByteArray(HttpEntity entity) throws Exception {
    if (entity == null) {
        throw new Exception("HTTP entity may not be null");
    }/*from  w w w .  j a  va 2  s . c  o m*/
    InputStream instream = entity.getContent();
    if (instream == null) {
        return new byte[] {};
    }
    long len = entity.getContentLength();
    if (len > Integer.MAX_VALUE) {
        throw new Exception("HTTP entity too large to be buffered in memory");
    }
    Header contentEncoding = entity.getContentEncoding();
    boolean gzip = false;
    if (null != contentEncoding) {
        if ("gzip".equalsIgnoreCase(contentEncoding.getValue())) {
            instream = new GZIPInputStream(instream, 2048);
            gzip = true;
        }
    }
    ByteArrayBuffer buffer = new ByteArrayBuffer(1024 * 8);
    // \&:38, \n:10, \r:13, \':39, \":34, \\:92
    try {
        if (gzip) {
            int lenth = 0;
            while (lenth != -1) {
                byte[] buf = new byte[2048];
                try {
                    lenth = instream.read(buf, 0, buf.length);
                    if (lenth != -1) {
                        buffer.append(buf, 0, lenth);
                    }
                } catch (EOFException e) {
                    int tl = buf.length;
                    int surpl;
                    for (int k = 0; k < tl; ++k) {
                        surpl = buf[k];
                        if (surpl != 0) {
                            buffer.append(surpl);
                        }
                    }
                    lenth = -1;
                }
            }
            int bl = buffer.length();
            ByteArrayBuffer temBuffer = new ByteArrayBuffer((int) (bl * 1.4));
            for (int j = 0; j < bl; ++j) {
                int cc = buffer.byteAt(j);
                //               if (cc == 34 || cc == 39 || cc == 92 || cc == 10
                //                     || cc == 13 || cc == 38) {
                //                  temBuffer.append('\\');
                //               }
                temBuffer.append(cc);
            }
            buffer = temBuffer;
        } else {
            int c;
            while ((c = instream.read()) != -1) {
                //               if (c == 34 || c == 39 || c == 92 || c == 10 || c == 13
                //                     || c == 38) {
                //                  buffer.append('\\');
                //               }
                buffer.append(c);
            }
        }
    } catch (Exception e) {
        instream.close();
    } finally {
        instream.close();
    }
    return buffer.toByteArray();
}

From source file:org.simalliance.openmobileapi.service.security.AccessControlDB.java

public byte[] readAPCertificate() throws AccessControlException, CardException {

    ByteArrayBuffer bytes = new ByteArrayBuffer(1024);
    ByteArrayBuffer buffer = new ByteArrayBuffer(256);
    int offset = 0;
    int length = 0;
    while (!mApplet.readAPCertificate(buffer, offset, length)) {
        if (buffer.length() == 0) {
            break;
        }//from  ww  w .  ja v a 2  s .  com
        offset += buffer.length();
        bytes.append(buffer.toByteArray(), 0, buffer.length());
    }
    return bytes.toByteArray();
}

From source file:com.sonyericsson.android.drm.drmlicenseservice.DLSHttpClient.java

private static void writeDataToFile(String suffix, ByteArrayBuffer data) {
    if (Constants.DEBUG) {
        File dir = new File(Environment.getExternalStorageDirectory() + "/dls");
        if (!dir.exists() && !dir.mkdirs()) {
            return;
        }/*www. ja  va 2  s  . c om*/
        String datestr = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss.SSS-", Locale.US).format(new Date());
        File f = new File(Environment.getExternalStorageDirectory() + "/dls/" + datestr + suffix + ".xml");
        if (data != null) {
            try {
                FileOutputStream fos = new FileOutputStream(f);
                try {
                    fos.write(data.buffer(), 0, data.length());
                } finally {
                    fos.close();
                }
            } catch (FileNotFoundException e) {
                DrmLog.logException(e);
            } catch (IOException e) {
                DrmLog.logException(e);
            }
        } else {
            try {
                f.createNewFile();
            } catch (IOException e) {
                DrmLog.logException(e);
            }
        }
    }
}

From source file:com.digitalpebble.stormcrawler.protocol.okhttp.HttpProtocol.java

private final byte[] toByteArray(final ResponseBody responseBody, MutableBoolean trimmed) throws IOException {

    if (responseBody == null)
        return new byte[] {};

    final InputStream instream = responseBody.byteStream();
    if (instream == null) {
        return null;
    }//from w ww  .j  ava2s.  c  om
    if (responseBody.contentLength() > Integer.MAX_VALUE) {
        throw new IOException("Cannot buffer entire body for content length: " + responseBody.contentLength());
    }
    int reportedLength = (int) responseBody.contentLength();
    // set default size for buffer: 100 KB
    int bufferInitSize = 102400;
    if (reportedLength != -1) {
        bufferInitSize = reportedLength;
    }
    // avoid init of too large a buffer when we will trim anyway
    if (maxContent != -1 && bufferInitSize > maxContent) {
        bufferInitSize = maxContent;
    }
    long endDueFor = -1;
    if (completionTimeout != -1) {
        endDueFor = System.currentTimeMillis() + (completionTimeout * 1000);
    }
    final ByteArrayBuffer buffer = new ByteArrayBuffer(bufferInitSize);
    final byte[] tmp = new byte[4096];
    int lengthRead;
    while ((lengthRead = instream.read(tmp)) != -1) {
        // check whether we need to trim
        if (maxContent != -1 && buffer.length() + lengthRead > maxContent) {
            buffer.append(tmp, 0, maxContent - buffer.length());
            trimmed.setValue(true);
            break;
        }
        buffer.append(tmp, 0, lengthRead);
        // check whether we hit the completion timeout
        if (endDueFor != -1 && endDueFor <= System.currentTimeMillis()) {
            trimmed.setValue(true);
            break;
        }
    }
    return buffer.toByteArray();
}

From source file:de.luhmer.owncloudnewsreader.async_tasks.GetImageThreaded.java

@Override
public void run() {
    try {//from  ww  w .  j a v  a2s  .co m
        File cacheFile = ImageHandler.getFullPathOfCacheFile(WEB_URL_TO_FILE.toString(), rootPath);

        DatabaseConnectionOrm dbConn = new DatabaseConnectionOrm(cont);
        Feed feed = dbConn.getFeedById(ThreadId);
        if (!cacheFile.isFile() || feed.getAvgColour() == null) {
            File dir = new File(rootPath);
            dir.mkdirs();
            cacheFile = ImageHandler.getFullPathOfCacheFile(WEB_URL_TO_FILE.toString(), rootPath);
            //cacheFile.createNewFile();

            /* Open a connection to that URL. */
            URLConnection urlConn = WEB_URL_TO_FILE.openConnection();

            urlConn.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

            /*
             * Define InputStreams to read from the URLConnection.
             */
            InputStream is = urlConn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);

            /*
             * Read bytes to the Buffer until there is nothing more to read(-1).
             */
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }

            //If the file is not empty
            if (baf.length() > 0) {
                bmp = BitmapFactory.decodeByteArray(baf.toByteArray(), 0, baf.length());

                FileOutputStream fos = new FileOutputStream(cacheFile);
                fos.write(baf.toByteArray());
                fos.close();
            }
        }
        //return cacheFile.getPath();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    //return bmp;

    if (imageDownloadFinished != null)
        imageDownloadFinished.DownloadFinished(ThreadId, bmp);

    super.run();
}