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

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

Introduction

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

Prototype

public ByteArrayBuffer(int i) 

Source Link

Usage

From source file:com.android.yijiang.kzx.http.DataAsyncHttpResponseHandler.java

/**
 * Returns byte array of response HttpEntity contents
 *
 * @param entity can be null/*from w  ww.j a  v  a  2  s.c  om*/
 * @return response entity body or null
 * @throws java.io.IOException if reading entity or creating byte array failed
 */
@Override
byte[] getResponseData(HttpEntity entity) throws IOException {

    byte[] responseBody = null;
    if (entity != null) {
        InputStream instream = entity.getContent();
        if (instream != null) {
            long contentLength = entity.getContentLength();
            if (contentLength > Integer.MAX_VALUE) {
                throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
            }
            if (contentLength < 0) {
                contentLength = BUFFER_SIZE;
            }
            try {
                ByteArrayBuffer buffer = new ByteArrayBuffer((int) contentLength);
                try {
                    byte[] tmp = new byte[BUFFER_SIZE];
                    int l;
                    // do not send messages if request has been cancelled
                    while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                        buffer.append(tmp, 0, l);
                        sendProgressDataMessage(copyOfRange(tmp, 0, l));
                    }
                } finally {
                    AsyncHttpClient.silentCloseInputStream(instream);
                }
                responseBody = buffer.toByteArray();
            } catch (OutOfMemoryError e) {
                System.gc();
                throw new IOException("File too large to fit into available memory");
            }
        }
    }
    return responseBody;
}

From source file:com.example.pierre.applicompanies.library_http.DataAsyncHttpResponseHandler.java

/**
 * Returns byte array of response HttpEntity contents
 *
 * @param entity can be null//w w  w  .  ja va  2s .c om
 * @return response entity body or null
 * @throws java.io.IOException if reading entity or creating byte array failed
 */
@Override
byte[] getResponseData(HttpEntity entity) throws IOException {

    byte[] responseBody = null;
    if (entity != null) {
        InputStream instream = entity.getContent();
        if (instream != null) {
            long contentLength = entity.getContentLength();
            if (contentLength > Integer.MAX_VALUE) {
                throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
            }
            if (contentLength < 0) {
                contentLength = BUFFER_SIZE;
            }
            try {
                ByteArrayBuffer buffer = new ByteArrayBuffer((int) contentLength);
                try {
                    byte[] tmp = new byte[BUFFER_SIZE];
                    int l, count = 0;
                    // do not send messages if request has been cancelled
                    while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                        buffer.append(tmp, 0, l);
                        sendProgressDataMessage(copyOfRange(tmp, 0, l));
                        sendProgressMessage(count, (int) contentLength);
                    }
                } finally {
                    AsyncHttpClient.silentCloseInputStream(instream);
                }
                responseBody = buffer.toByteArray();
            } catch (OutOfMemoryError e) {
                System.gc();
                throw new IOException("File too large to fit into available memory");
            }
        }
    }
    return responseBody;
}

From source file:cn.com.loopj.android.http.DataAsyncHttpResponseHandler.java

/**
 * Returns byte array of response HttpEntity contents
 *
 * @param entity can be null/*  w  w  w. j a  va  2 s .  co  m*/
 * @return response entity body or null
 * @throws IOException if reading entity or creating byte array failed
 */
@Override
byte[] getResponseData(HttpEntity entity) throws IOException {

    byte[] responseBody = null;
    if (entity != null) {
        InputStream instream = entity.getContent();
        if (instream != null) {
            long contentLength = entity.getContentLength();
            if (contentLength > Integer.MAX_VALUE) {
                throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
            }
            if (contentLength < 0) {
                contentLength = BUFFER_SIZE;
            }
            try {
                ByteArrayBuffer buffer = new ByteArrayBuffer((int) contentLength);
                try {
                    byte[] tmp = new byte[BUFFER_SIZE];
                    int l, count = 0;
                    // do not send messages if request has been cancelled
                    while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                        buffer.append(tmp, 0, l);
                        sendProgressDataMessage(copyOfRange(tmp, 0, l));
                        sendProgressMessage(count, contentLength);
                    }
                } finally {
                    AsyncHttpClient.silentCloseInputStream(instream);
                }
                responseBody = buffer.toByteArray();
            } catch (OutOfMemoryError e) {
                System.gc();
                throw new IOException("File too large to fit into available memory");
            }
        }
    }
    return responseBody;
}

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

protected void init(final InputStream _instream, int buffersize, final HttpParams params) {
    if (_instream == null) {
        throw new IllegalArgumentException("Input stream may not be null");
    }/* www .jav a 2 s  .  c o m*/
    if (buffersize <= 0) {
        throw new IllegalArgumentException("Buffer size may not be negative or zero");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    this.instream = _instream;
    this.buffer = new byte[buffersize];
    this.bufferpos = 0;
    this.bufferlen = 0;
    this.linebuffer = new ByteArrayBuffer(buffersize);
    this.charset = HttpProtocolParams.getHttpElementCharset(params);
    //    this.timeoutSocket = params.getBooleanParameter("vietspider.socket.timeout", false);
    this.ascii = this.charset.equalsIgnoreCase(HTTP.US_ASCII) || this.charset.equalsIgnoreCase(HTTP.ASCII);
    this.maxLineLen = params.getIntParameter(CoreConnectionPNames.MAX_LINE_LENGTH, -1);
    this.metrics = new HttpTransportMetricsImpl();
}

From source file:com.mpower.mintel.android.application.MIntel.java

private static void copyAudioFiles(String[] assetName) {
    for (int i = 0; i < assetName.length; i++) {
        File file = new File(METADATA_PATH, assetName[i]);
        if (!file.exists()) {
            AssetManager mngr = getAppContext().getAssets();
            ByteArrayBuffer baf = new ByteArrayBuffer(2048);
            try {
                InputStream path = mngr.open(assetName[i]);
                BufferedInputStream bis = new BufferedInputStream(path, 1024);
                int current = 0;
                while ((current = bis.read()) != -1) {
                    baf.append((byte) current);
                }//from   ww w.  j a  va 2s  .  c om
                byte[] bitmapdata = baf.toByteArray();

                FileOutputStream fos;
                fos = new FileOutputStream(file);
                fos.write(bitmapdata);
                fos.flush();
                fos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

From source file:fr.gcastel.freeboxV6GeekIncDownloader.services.GeekIncLogoDownloadService.java

public void downloadAndResize(int requiredSize) throws Exception {
    // Si le logo existe depuis moins d'une semaine, on ne le retlcharge
    // pas//from w  w  w .  j  av a 2 s  .c  o  m
    if (outFile.exists()) {
        // Moins une semaine
        long uneSemainePlusTot = System.currentTimeMillis() - (7 * 24 * 60 * 60 * 1000);

        if (outFile.lastModified() > uneSemainePlusTot) {
            Log.i("GeekIncLogoDownloadService",
                    "Le logo a dj t tlcharg il y a moins d'une semaine.");
            return;
        }
    }

    URLConnection ucon = toDownload.openConnection();
    InputStream is = ucon.getInputStream();

    BufferedInputStream bis = new BufferedInputStream(is);
    ByteArrayBuffer baf = new ByteArrayBuffer(50);
    int current = 0;
    while ((current = bis.read()) != -1) {
        baf.append((byte) current);
    }

    bis.close();
    is.close();

    // Fichier temporaire pour redimensionnement
    File tmpFile = new File(outFile.getAbsolutePath() + "tmp");
    FileOutputStream fos = new FileOutputStream(tmpFile);
    fos.write(baf.toByteArray());
    fos.close();

    saveAndResizeFile(tmpFile, outFile, requiredSize);

    // Suppression du fichier temporaire
    tmpFile.delete();
}

From source file:es.prodevelop.gvsig.mini.tasks.namefinder.NameFinderFunc.java

@Override
public boolean execute() {

    NameFinder NFTask = new NameFinder();
    String query = new String(NFTask.URL + NFTask.parms).replaceAll(" ", "%20");

    try {/*from  ww w  . jav a  2 s  .  c o  m*/
        log.log(Level.FINE, query);
        InputStream is = Utils.openConnection(query);
        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 = 0;
        while ((current = bis.read()) != -1) {
            if (this.isCanceled()) {
                res = TaskHandler.CANCELED;
                return true;
            }
            baf.append((byte) current);

        }

        Vector result = NFTask.parse(baf.toByteArray());

        if (result != null) {
            // handler.sendEmptyMessage(map.POI_SUCCEEDED);
            Named[] searchRes = new Named[result.size()];
            desc = new String[result.size()];
            for (int i = 0; i < result.size(); i++) {
                Named n = (Named) result.elementAt(i);
                desc[i] = n.description;
                searchRes[i] = n;

                if (this.isCanceled()) {
                    res = TaskHandler.CANCELED;
                    return true;
                }
            }

            if (this.isCanceled()) {
                res = TaskHandler.CANCELED;
                return true;
            }
            nm = new NamedMultiPoint(searchRes);

            res = TaskHandler.FINISHED;
        } else {
            res = TaskHandler.CANCELED;
        }
    } catch (IOException e) {
        if (e instanceof UnknownHostException) {
            res = TaskHandler.NO_RESPONSE;
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, "Namefinder" + e.getMessage(), e);
    } finally {

    }
    return true;
}

From source file:de.tlabs.ssr.g1.client.XmlInputThread.java

@Override
public void run() {
    Log.d(TAG, "(" + this.getId() + ") HELLO");

    try {/*from   www  . jav  a2s .  c o  m*/
        // create sax parser
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();

        // get an xml reader 
        XMLReader xr = sp.getXMLReader();

        // set up xml input source
        XMLChunkInputStream xmlChunkInputStream;
        synchronized (GlobalData.socketChannel) {
            xmlChunkInputStream = new XMLChunkInputStream(new ByteArrayBuffer(32 * 1024),
                    GlobalData.socketChannel.socket().getInputStream());
        }
        InputSource inputSource = new InputSource(xmlChunkInputStream);

        // create handler for scene description and assign it
        SceneDescrXMLHandler sceneDescrXMLHandler = new SceneDescrXMLHandler(GlobalData.audioScene);
        xr.setContentHandler(sceneDescrXMLHandler);

        // parse scene description
        //Log.d(TAG, "(" + this.getId() + ") parsing description...");
        //xmlChunkInputStream.printToLog = true;
        while (xmlChunkInputStream.bufferNextChunk() && !sceneDescrXMLHandler.receivedSceneDescr()) {
            // parse and process xml input
            xr.parse(inputSource);
        }
        //xmlChunkInputStream.printToLog = false;

        // signal that scene description was parsed
        //Log.d(TAG, "(" + this.getId() + ") sending SCENEPARSED_OK_MSG");
        GlobalData.sourcesMoverMsgHandler
                .sendMessage(GlobalData.sourcesMoverMsgHandler.obtainMessage(SourcesMover.SCENEPARSED_OK_MSG));

        // create handler for scene updates and assign it
        SceneUpdateXMLHandler sceneUpdateXMLHandler = new SceneUpdateXMLHandler(GlobalData.audioScene);
        xr.setContentHandler(sceneUpdateXMLHandler);

        // parse scene updates
        Log.d(TAG, "(" + this.getId() + ") starting xml input loop...");
        while (xmlChunkInputStream.bufferNextChunk()) {
            // parse and process xml input
            xr.parse(inputSource);

            // check if we should abort
            synchronized (abortFlag) {
                if (abortFlag == true) {
                    break;
                }
            }
        }
    } catch (Exception e) {
        Log.d(TAG, "(" + this.getId() + ") Exception " + e.toString() + ": " + e.getMessage());

        // check if this thread was aborted and/or stopped by a call to interrupt()
        if (Thread.interrupted() || abortFlag) {
            Log.d(TAG, "(" + this.getId() + ") interrupted/aborted");
        } else {
            GlobalData.sourcesMoverMsgHandler.sendMessage(GlobalData.sourcesMoverMsgHandler
                    .obtainMessage(SourcesMover.XMLINPUT_ERR_MSG, e.getMessage()));
            Log.d(TAG, "(" + this.getId() + ") sending XMLINPUT_ERR_MSG");
        }
    }

    Log.d(TAG, "(" + this.getId() + ") GOOD BYE");
}

From source file:com.github.matthesrieke.jprox.JProxViaParameterServlet.java

private byte[] readInputStream(InputStream inputStream, int estimateLength) throws IOException {
    ByteArrayBuffer bb = new ByteArrayBuffer(estimateLength);
    int b;//from ww w.ja v  a 2s . co m
    while ((b = inputStream.read()) != -1) {
        bb.append(b);
    }
    inputStream.close();
    return bb.toByteArray();
}

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

@Override
public void run() {
    try {/*from   www .j a  v a  2  s  .c o 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();
}