List of usage examples for java.io ByteArrayOutputStream size
public synchronized int size()
From source file:org.archive.util.LaxHttpParser.java
/** * Return byte array from an (unchunked) input stream. * Stop reading when <tt>"\n"</tt> terminator encountered * If the stream ends before the line terminator is found, * the last part of the string will still be returned. * If no input data available, <code>null</code> is returned. * * @param inputStream the stream to read from * * @throws IOException if an I/O problem occurs * @return a byte array from the stream/*from w w w . ja va 2s . c om*/ */ public static byte[] readRawLine(InputStream inputStream) throws IOException { LOG.trace("enter LaxHttpParser.readRawLine()"); ByteArrayOutputStream buf = new ByteArrayOutputStream(); int ch; while ((ch = inputStream.read()) >= 0) { buf.write(ch); if (ch == '\n') { // be tolerant (RFC-2616 Section 19.3) break; } } if (buf.size() == 0) { return null; } return buf.toByteArray(); }
From source file:com.ms.commons.utilities.HttpClientUtils.java
public static String getResponseBodyAsString(HttpMethod method, Integer tryTimes, String responseCharSet, Integer maximumResponseByteSize, Integer soTimeoutMill) { init();//from w w w. j ava 2 s. c om if (tryTimes == null) { tryTimes = 1; } if (StringUtils.isBlank(responseCharSet)) { responseCharSet = "utf-8"; } if (maximumResponseByteSize == null) { maximumResponseByteSize = 50 * 1024 * 1024; } if (soTimeoutMill == null) { soTimeoutMill = 20000; } method.getParams().setSoTimeout(soTimeoutMill); InputStream httpInputStream = null; for (int i = 0; i < tryTimes; i++) { try { int responseCode = client.executeMethod(method); if (responseCode == HttpStatus.SC_OK || responseCode == HttpStatus.SC_MOVED_PERMANENTLY || responseCode == HttpStatus.SC_MOVED_TEMPORARILY) { if (method instanceof HttpMethodBase) { responseCharSet = ((HttpMethodBase) method).getResponseCharSet(); } int read = 0; byte[] cbuf = new byte[4096]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); httpInputStream = method.getResponseBodyAsStream(); while ((read = httpInputStream.read(cbuf)) >= 0) { baos.write(cbuf, 0, read); if (baos.size() >= maximumResponseByteSize) { break; } } String content = baos.toString(responseCharSet); return content; } logger.error(String.format( "getResponseBodyAsString failed, responseCode: %s, should be 200, 301, 302", responseCode)); return ""; } catch (Exception e) { logger.error("getResponseBodyAsString failed", e); } finally { IOUtils.closeQuietly(httpInputStream); method.releaseConnection(); } } return ""; }
From source file:com.microsoft.tfs.core.httpclient.HttpParser.java
/** * Return byte array from an (unchunked) input stream. Stop reading when * <tt>"\n"</tt> terminator encountered If the stream ends before the line * terminator is found, the last part of the string will still be returned. * If no input data available, <code>null</code> is returned. * * @param inputStream// www . j a v a 2s . c om * the stream to read from * * @throws IOException * if an I/O problem occurs * @return a byte array from the stream */ public static byte[] readRawLine(final InputStream inputStream) throws IOException { LOG.trace("enter HttpParser.readRawLine()"); final ByteArrayOutputStream buf = new ByteArrayOutputStream(); int ch; while ((ch = inputStream.read()) >= 0) { buf.write(ch); if (ch == '\n') { // be tolerant (RFC-2616 Section 19.3) break; } } if (buf.size() == 0) { return null; } return buf.toByteArray(); }
From source file:org.ardverk.daap.bio.HttpParser.java
/** * Return byte array from an (unchunked) input stream. Stop reading when * <tt>"\n"</tt> terminator encountered If the stream ends before the line * terminator is found, the last part of the string will still be returned. * If no input data available, <code>null</code> is returned. * /*from w w w . ja v a 2 s.c om*/ * @param inputStream * the stream to read from * * @throws IOException * if an I/O problem occurs * @return a byte array from the stream */ public static byte[] readRawLine(InputStream inputStream) throws IOException { LOG.trace("enter HttpParser.readRawLine()"); ByteArrayOutputStream buf = new ByteArrayOutputStream(); int ch; while ((ch = inputStream.read()) >= 0) { buf.write(ch); if (ch == '\n') { // be tolerant (RFC-2616 Section 19.3) break; } } if (buf.size() == 0) { return null; } return buf.toByteArray(); }
From source file:org.omegat.util.WikiGet.java
/** * Post data to the remote URL./*w w w . j a v a 2 s.c o m*/ * * @param address * address to post * @param params * parameters * @param additionalHeaders * additional headers for request, can be null * @return sever output */ public static String post(String address, Map<String, String> params, Map<String, String> additionalHeaders) throws IOException { URL url = new URL(address); ByteArrayOutputStream pout = new ByteArrayOutputStream(); if (params != null) { for (Map.Entry<String, String> p : params.entrySet()) { if (pout.size() > 0) { pout.write('&'); } pout.write(p.getKey().getBytes(StandardCharsets.UTF_8)); pout.write('='); pout.write(URLEncoder.encode(p.getValue(), StandardCharsets.UTF_8.name()) .getBytes(StandardCharsets.UTF_8)); } } HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", Integer.toString(pout.size())); if (additionalHeaders != null) { for (Map.Entry<String, String> en : additionalHeaders.entrySet()) { conn.setRequestProperty(en.getKey(), en.getValue()); } } addProxyAuthentication(conn); conn.setDoInput(true); conn.setDoOutput(true); try (OutputStream cout = conn.getOutputStream()) { cout.write(pout.toByteArray()); cout.flush(); return getStringContent(conn); } finally { conn.disconnect(); } }
From source file:arena.utils.FileUtils.java
public static byte[] convertStreamToByteArray(InputStream in, int maxLength) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); int count = 0; int read = 0; byte buffer[] = new byte[4096]; while (((maxLength < 0) || (count < maxLength)) && ((read = in.read(buffer)) != -1)) { out.write(buffer, 0, maxLength < 0 ? read : Math.min(maxLength - out.size(), read)); count += read;//from w w w .ja va 2s . c o m } return out.toByteArray(); }
From source file:org.vuphone.assassins.android.http.HTTPGetter.java
private static HashMap<String, Double> handleGameAreaResponse(HttpGet get) { HttpResponse resp;//www .j a v a 2 s . c om // Execute the get try { resp = c.execute(get); } catch (ClientProtocolException e1) { e1.printStackTrace(); Log.e(VUphone.tag, pre + "HTTP error while executing post"); return null; } catch (SocketException se) { // If we have no Internet connection, we don't want to wipe the // existing list of land mines by returning null. Log.e(VUphone.tag, pre + "SocketException: Invalid Internet " + "Connection"); se.printStackTrace(); return null; } catch (IOException e1) { e1.printStackTrace(); Log.e(VUphone.tag, pre + "HTTP error in server response"); return null; } catch (Exception e) { Log.e(VUphone.tag, pre + "An unknown exception was thrown"); e.printStackTrace(); return null; } Log.i(VUphone.tag, pre + "HTTP operation complete. Processing response."); // Convert Response Entity to usable format ByteArrayOutputStream bao = new ByteArrayOutputStream(); try { resp.getEntity().writeTo(bao); Log.v(VUphone.tag, pre + "Http response: " + bao); } catch (IOException e) { e.printStackTrace(); Log.e(VUphone.tag, pre + "Unable to write response to byte[]"); return null; } if (bao.size() == 0) { Log.w(VUphone.tag, pre + "Response was completely empty, " + "are you sure you are using the " + "same version client and server? " + "At the least, there should have " + "been empty XML here"); } HashMap<String, Double> data = new HashMap<String, Double>(); String response = bao.toString(); String[] vals = response.split("&"); for (int i = 0; i < vals.length; i++) { String[] val = vals[i].split("="); data.put(val[0], Double.valueOf(val[1])); } return data; }
From source file:dk.netarkivet.archive.arcrepository.ARCLookupTester.java
/** * Reads a raw line from an InputStream, up till \n. Since HTTP allows \r\n and \n as terminators, this gets the * whole line. This code is adapted from org.apache.commons.httpclient.HttpParser * * @param inputStream A stream to read from. * @return Array of bytes read or null if none are available. * @throws IOException if the underlying reads fail *///from w w w . j av a 2s . c o m private static byte[] readRawLine(InputStream inputStream) throws IOException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); int ch; while ((ch = inputStream.read()) >= 0) { buf.write(ch); if (ch == '\n') { break; } } if (buf.size() == 0) { return null; } return buf.toByteArray(); }
From source file:org.apache.hadoop.hbase.codec.CodecPerformance.java
static byte[] runEncoderTest(final int index, final int initialBufferSize, final ByteArrayOutputStream baos, final CellOutputStream encoder, final Cell[] cells) throws IOException { long startTime = System.currentTimeMillis(); for (int i = 0; i < cells.length; i++) { encoder.write(cells[i]);//from w ww . jav a 2 s . c o m } encoder.flush(); LOG.info("" + index + " encoded count=" + cells.length + " in " + (System.currentTimeMillis() - startTime) + "ms for encoder " + encoder); // Ensure we did not have to grow the backing buffer. assertTrue(baos.size() < initialBufferSize); return baos.toByteArray(); }
From source file:org.vuphone.assassins.android.http.HTTPGetter.java
private static ArrayList<LandMine> handleLandMineResponse(HttpGet get) { HttpResponse resp;/*from w w w . j a va 2 s . com*/ // Execute the get try { resp = c.execute(get); } catch (ClientProtocolException e1) { e1.printStackTrace(); Log.e(VUphone.tag, pre + "HTTP error while executing post"); return null; } catch (SocketException se) { // If we have no Internet connection, we don't want to wipe the // existing list of land mines by returning null. Log.e(VUphone.tag, pre + "SocketException: handled by " + "returning current land mine list."); se.printStackTrace(); return GameObjects.getInstance().getLandMines(); } catch (IOException e1) { e1.printStackTrace(); Log.e(VUphone.tag, pre + "HTTP error in server response"); return null; } catch (Exception e) { Log.e(VUphone.tag, pre + "An unknown exception was thrown"); e.printStackTrace(); return null; } Log.i(VUphone.tag, pre + "HTTP operation complete. Processing response."); // Convert Response Entity to usable format ByteArrayOutputStream bao = new ByteArrayOutputStream(); try { resp.getEntity().writeTo(bao); Log.v(VUphone.tag, pre + "Http response: " + bao); } catch (IOException e) { e.printStackTrace(); Log.e(VUphone.tag, pre + "Unable to write response to byte[]"); return null; } // Extract Land Mines from response if (bao.size() == 0) { Log.w(VUphone.tag, pre + "Response was completely empty, " + "are you sure you are using the " + "same version client and server? " + "At the least, there should have " + "been empty XML here"); } ArrayList<LandMine> mines = new ArrayList<LandMine>( landMineHandler_.processXML(new InputSource(new ByteArrayInputStream(bao.toByteArray())))); return mines; //return GameObjects.getInstance().getLandMines(); //return null; }