Java Code Examples for java.io.ByteArrayOutputStream#size()
The following examples show how to use
java.io.ByteArrayOutputStream#size() .
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: MultipartRequestInputStream.java From yue-library with Apache License 2.0 | 6 votes |
/** * 输入流中读取边界 * * @return 边界 * @throws IOException IO异常 */ public byte[] readBoundary() throws IOException { ByteArrayOutputStream boundaryOutput = new ByteArrayOutputStream(1024); byte b; // skip optional whitespaces while ((b = readByte()) <= ' ') { } boundaryOutput.write(b); // now read boundary chars while ((b = readByte()) != '\r') { boundaryOutput.write(b); } if (boundaryOutput.size() == 0) { throw new IOException("Problems with parsing request: invalid boundary"); } skipBytes(1); boundary = new byte[boundaryOutput.size() + 2]; System.arraycopy(boundaryOutput.toByteArray(), 0, boundary, 2, boundary.length - 2); boundary[0] = '\r'; boundary[1] = '\n'; return boundary; }
Example 2
Source File: CdmrfWriter.java From netcdf-java with BSD 3-Clause "New" or "Revised" License | 6 votes |
private long sendData(Array data, OutputStream out, boolean deflate) throws IOException { // length of data uncompressed long uncompressedLength = data.getSizeBytes(); long size = 0; if (deflate) { // write to an internal buffer, so we can find out the size ByteArrayOutputStream bout = new ByteArrayOutputStream(); DeflaterOutputStream dout = new DeflaterOutputStream(bout); IospHelper.copyToOutputStream(data, dout); // write internal buffer to output stream dout.close(); int deflatedSize = bout.size(); size += NcStream.writeVInt(out, deflatedSize); bout.writeTo(out); size += deflatedSize; } else { size += NcStream.writeVInt(out, (int) uncompressedLength); size += IospHelper.copyToOutputStream(data, out); } return size; }
Example 3
Source File: HarFileHandler.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
private String getEnvelope(SOAPMessage message) throws SOAPException, IOException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); String var3; try { message.writeTo(stream); if (stream.size() >= 1232896) { var3 = "message to large to log"; return var3; } var3 = stream.toString(Charset.UTF_8.getName()); } finally { ConnectorIOUtils.closeQuietly((Object)stream); } return var3; }
Example 4
Source File: HarFileHandler.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
private String getEnvelope(SOAPMessage message) throws SOAPException, IOException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); String var3; try { message.writeTo(stream); if (stream.size() < 1232896) { var3 = stream.toString(Charset.UTF_8.getName()); return var3; } var3 = "message to large to log"; } finally { ConnectorIOUtils.closeQuietly((Object)stream); } return var3; }
Example 5
Source File: Utils.java From LPR with Apache License 2.0 | 6 votes |
public static Mat loadResource(Context context, int resourceId, int flags) throws IOException { InputStream is = context.getResources().openRawResource(resourceId); ByteArrayOutputStream os = new ByteArrayOutputStream(is.available()); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } is.close(); Mat encoded = new Mat(1, os.size(), CvType.CV_8U); encoded.put(0, 0, os.toByteArray()); os.close(); Mat decoded = Imgcodecs.imdecode(encoded, flags); encoded.release(); return decoded; }
Example 6
Source File: SocketWindowWordCountITCase.java From flink with Apache License 2.0 | 5 votes |
@Test public void testScalaProgram() throws Exception { InetAddress localhost = InetAddress.getByName("localhost"); // suppress sysout messages from this example final PrintStream originalSysout = System.out; final PrintStream originalSyserr = System.err; final ByteArrayOutputStream errorMessages = new ByteArrayOutputStream(); System.setOut(new PrintStream(new NullStream())); System.setErr(new PrintStream(errorMessages)); try { try (ServerSocket server = new ServerSocket(0, 10, localhost)) { final ServerThread serverThread = new ServerThread(server); serverThread.setDaemon(true); serverThread.start(); final int serverPort = server.getLocalPort(); org.apache.flink.streaming.scala.examples.socket.SocketWindowWordCount.main( new String[] { "--port", String.valueOf(serverPort) }); if (errorMessages.size() != 0) { fail("Found error message: " + new String(errorMessages.toByteArray(), ConfigConstants.DEFAULT_CHARSET)); } serverThread.join(); serverThread.checkError(); } } finally { System.setOut(originalSysout); System.setErr(originalSyserr); } }
Example 7
Source File: AbstractClient.java From tencentcloud-sdk-java with Apache License 2.0 | 5 votes |
private byte[] getMultipartPayload(AbstractModel request, String boundary) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); String[] binaryParams = request.getBinaryParams(); for (Map.Entry<String, byte[]> entry : request.getMultipartRequestParams().entrySet()) { baos.write("--".getBytes(StandardCharsets.UTF_8)); baos.write(boundary.getBytes(StandardCharsets.UTF_8)); baos.write("\r\n".getBytes(StandardCharsets.UTF_8)); baos.write("Content-Disposition: form-data; name=\"".getBytes(StandardCharsets.UTF_8)); baos.write(entry.getKey().getBytes(StandardCharsets.UTF_8)); if (Arrays.asList(binaryParams).contains(entry.getKey())) { baos.write("\"; filename=\"".getBytes(StandardCharsets.UTF_8)); baos.write(entry.getKey().getBytes(StandardCharsets.UTF_8)); baos.write("\"\r\n".getBytes(StandardCharsets.UTF_8)); } else { baos.write("\"\r\n".getBytes(StandardCharsets.UTF_8)); } baos.write("\r\n".getBytes(StandardCharsets.UTF_8)); baos.write(entry.getValue()); baos.write("\r\n".getBytes(StandardCharsets.UTF_8)); } if (baos.size() != 0) { baos.write("--".getBytes(StandardCharsets.UTF_8)); baos.write(boundary.getBytes(StandardCharsets.UTF_8)); baos.write("--\r\n".getBytes(StandardCharsets.UTF_8)); } byte[] bytes = baos.toByteArray(); baos.close(); return bytes; }
Example 8
Source File: NetworkInterpreter.java From DoraemonKit with Apache License 2.0 | 5 votes |
public void responseReadFinished(int requestId, NetworkRecord record, ByteArrayOutputStream outputStream) { if (outputStream != null) { record.responseLength = outputStream.size(); record.mResponseBody = outputStream.toString(); //LogHelper.i(TAG, "[responseReadFinished] body: " + record.mResponseBody.toString().length()); } else { //LogHelper.i(TAG, "[responseReadFinished] outputStream is null request id: " + requestId); } }
Example 9
Source File: SocketWindowWordCountITCase.java From Flink-CEPplus with Apache License 2.0 | 5 votes |
@Test public void testJavaProgram() throws Exception { InetAddress localhost = InetAddress.getByName("localhost"); // suppress sysout messages from this example final PrintStream originalSysout = System.out; final PrintStream originalSyserr = System.err; final ByteArrayOutputStream errorMessages = new ByteArrayOutputStream(); System.setOut(new PrintStream(new NullStream())); System.setErr(new PrintStream(errorMessages)); try { try (ServerSocket server = new ServerSocket(0, 10, localhost)) { final ServerThread serverThread = new ServerThread(server); serverThread.setDaemon(true); serverThread.start(); final int serverPort = server.getLocalPort(); SocketWindowWordCount.main(new String[] { "--port", String.valueOf(serverPort) }); if (errorMessages.size() != 0) { fail("Found error message: " + new String(errorMessages.toByteArray(), ConfigConstants.DEFAULT_CHARSET)); } serverThread.join(); serverThread.checkError(); } } finally { System.setOut(originalSysout); System.setErr(originalSyserr); } }
Example 10
Source File: ImageDecoder.java From ShareLoginPayUtil with Apache License 2.0 | 5 votes |
public static byte[] compress2Byte(String imagePath, int size, int length) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(imagePath, options); int outH = options.outHeight; int outW = options.outWidth; int inSampleSize = 1; while (outH / inSampleSize > size || outW / inSampleSize > size) { inSampleSize *= 2; } options.inSampleSize = inSampleSize; options.inJustDecodeBounds = false; Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options); ByteArrayOutputStream result = new ByteArrayOutputStream(); int quality = 100; bitmap.compress(Bitmap.CompressFormat.JPEG, quality, result); if (result.size() > length) { result.reset(); quality -= 10; bitmap.compress(Bitmap.CompressFormat.JPEG, quality, result); } bitmap.recycle(); return result.toByteArray(); }
Example 11
Source File: StompDecoder.java From spring-analysis-note with MIT License | 5 votes |
private void readHeaders(ByteBuffer byteBuffer, StompHeaderAccessor headerAccessor) { while (true) { ByteArrayOutputStream headerStream = new ByteArrayOutputStream(256); boolean headerComplete = false; while (byteBuffer.hasRemaining()) { if (tryConsumeEndOfLine(byteBuffer)) { headerComplete = true; break; } headerStream.write(byteBuffer.get()); } if (headerStream.size() > 0 && headerComplete) { String header = new String(headerStream.toByteArray(), StandardCharsets.UTF_8); int colonIndex = header.indexOf(':'); if (colonIndex <= 0) { if (byteBuffer.remaining() > 0) { throw new StompConversionException("Illegal header: '" + header + "'. A header must be of the form <name>:[<value>]."); } } else { String headerName = unescape(header.substring(0, colonIndex)); String headerValue = unescape(header.substring(colonIndex + 1)); try { headerAccessor.addNativeHeader(headerName, headerValue); } catch (InvalidMimeTypeException ex) { if (byteBuffer.remaining() > 0) { throw ex; } } } } else { break; } } }
Example 12
Source File: SmartPost.java From Android-POS with MIT License | 5 votes |
/** * �������� * @param cmd AN * @param code ACK/NAK���� * @param tip ���� * @param path ������������ * @return */ public static byte[] InitMessage(byte[] cmd, String code, String tip, byte path) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { baos.write(PostDefine.START); baos.write(PostDefine.STX); ByteArrayOutputStream lsContent = new ByteArrayOutputStream(); lsContent.write(path); // PostDefine.PATH_1 lsContent.write(PostDefine.TYPE_1); lsContent.write(id); lsContent.write(cmd); if (code != null) { lsContent.write(PostDefine.FS); lsContent.write(code.getBytes()); if (tip != null) { lsContent.write(PostDefine.FS); lsContent.write(tip.getBytes()); } } int len = lsContent.size(); baos.write(Function.toHex2Len(len)); baos.write(lsContent.toByteArray()); baos.write(PostDefine.ETX); byte[] buffer = baos.toByteArray(); byte[] LRCContent = new byte[buffer.length-4]; System.arraycopy(buffer, 4, LRCContent, 0, buffer.length-4); byte LRC = Function.Enteryparity(LRCContent); baos.write(LRC); baos.write(PostDefine.END); lsContent.close(); baos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return baos.toByteArray(); }
Example 13
Source File: NcStreamIosp.java From netcdf-java with BSD 3-Clause "New" or "Revised" License | 5 votes |
public String showDeflate() { if (!(what instanceof NcStreamIosp.DataStorage)) return "Must select a NcStreamIosp.DataStorage object"; Formatter f = new Formatter(); try { NcStreamIosp.DataStorage dataStorage = (NcStreamIosp.DataStorage) what; raf.seek(dataStorage.filePos); byte[] data = new byte[dataStorage.size]; raf.readFully(data); ByteArrayInputStream bin = new ByteArrayInputStream(data); ByteArrayOutputStream bout = new ByteArrayOutputStream(); DeflaterOutputStream dout = new DeflaterOutputStream(bout); IO.copy(bin, dout); dout.close(); int deflatedSize = bout.size(); float ratio = ((float) data.length) / deflatedSize; f.format("Original size = %d bytes, deflated = %d bytes ratio = %f %n", data.length, deflatedSize, ratio); return f.toString(); } catch (IOException e) { e.printStackTrace(); return e.getMessage(); } }
Example 14
Source File: JFIFMarkerSegment.java From TencentKona-8 with GNU General Public License v2.0 | 4 votes |
JFIFThumbJPEG(BufferedImage thumb) throws IllegalThumbException { int INITIAL_BUFSIZE = 4096; int MAZ_BUFSIZE = 65535 - 2 - PREAMBLE_SIZE; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(INITIAL_BUFSIZE); MemoryCacheImageOutputStream mos = new MemoryCacheImageOutputStream(baos); JPEGImageWriter thumbWriter = new JPEGImageWriter(null); thumbWriter.setOutput(mos); // get default metadata for the thumb JPEGMetadata metadata = (JPEGMetadata) thumbWriter.getDefaultImageMetadata (new ImageTypeSpecifier(thumb), null); // Remove the jfif segment, which should be there. MarkerSegment jfif = metadata.findMarkerSegment (JFIFMarkerSegment.class, true); if (jfif == null) { throw new IllegalThumbException(); } metadata.markerSequence.remove(jfif); /* Use this if removing leaves a hole and causes trouble // Get the tree String format = metadata.getNativeMetadataFormatName(); IIOMetadataNode tree = (IIOMetadataNode) metadata.getAsTree(format); // If there is no app0jfif node, the image is bad NodeList jfifs = tree.getElementsByTagName("app0JFIF"); if (jfifs.getLength() == 0) { throw new IllegalThumbException(); } // remove the app0jfif node Node jfif = jfifs.item(0); Node parent = jfif.getParentNode(); parent.removeChild(jfif); metadata.setFromTree(format, tree); */ thumbWriter.write(new IIOImage(thumb, null, metadata)); thumbWriter.dispose(); // Now check that the size is OK if (baos.size() > MAZ_BUFSIZE) { throw new IllegalThumbException(); } data = baos.toByteArray(); } catch (IOException e) { throw new IllegalThumbException(); } }
Example 15
Source File: LedgerHelper.java From java-sdk with Apache License 2.0 | 4 votes |
public static byte[] unwrapResponseAPDU(int channel, byte[] data, int packetSize) throws IOException { ByteArrayOutputStream response = new ByteArrayOutputStream(); int offset = 0; int responseLength; int sequenceIdx = 0; if ((data == null) || (data.length < 7 + 5)) { return null; } if (data[offset++] != (channel >> 8)) { throw new IOException("Invalid channel"); } if (data[offset++] != (channel & 0xff)) { throw new IOException("Invalid channel"); } if (data[offset++] != TAG_APDU) { throw new IOException("Invalid tag"); } if (data[offset++] != 0x00) { throw new IOException("Invalid sequence"); } if (data[offset++] != 0x00) { throw new IOException("Invalid sequence"); } responseLength = ((data[offset++] & 0xff) << 8); responseLength |= (data[offset++] & 0xff); if (data.length < 7 + responseLength) { return null; } int blockSize = (responseLength > packetSize - 7 ? packetSize - 7 : responseLength); response.write(data, offset, blockSize); offset += blockSize; while (response.size() != responseLength) { sequenceIdx++; if (offset == data.length) { return null; } if (data[offset++] != (channel >> 8)) { throw new IOException("Invalid channel"); } if (data[offset++] != (channel & 0xff)) { throw new IOException("Invalid channel"); } if (data[offset++] != TAG_APDU) { throw new IOException("Invalid tag"); } if (data[offset++] != (sequenceIdx >> 8)) { throw new IOException("Invalid sequence"); } if (data[offset++] != (sequenceIdx & 0xff)) { throw new IOException("Invalid sequence"); } blockSize = (responseLength - response.size() > packetSize - 5 ? packetSize - 5 : responseLength - response.size()); if (blockSize > data.length - offset) { return null; } response.write(data, offset, blockSize); offset += blockSize; } return response.toByteArray(); }
Example 16
Source File: SmartPost.java From Android-POS with MIT License | 4 votes |
/** * ���� * @param cmd ��������������CMD�� * @param path ������������ * @param amount ��������N12 * @param certificateNo ������������n6(��������) * @return */ public static byte[] InitMessage(byte[] cmd, byte path, BigDecimal amount, String certificateNo) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { baos.write(PostDefine.START); baos.write(PostDefine.STX); ByteArrayOutputStream lsContent = new ByteArrayOutputStream(); lsContent.write(path); lsContent.write(PostDefine.TYPE_1); lsContent.write(id); lsContent.write(cmd); lsContent.write(PostDefine.FS); lsContent.write(businessNo.getBytes()); lsContent.write(PostDefine.FS); lsContent.write(terminalNo.getBytes()); lsContent.write(PostDefine.FS); lsContent.write(business_zh.getBytes()); lsContent.write(PostDefine.FS); lsContent.write(business_en.getBytes()); if (amount.intValue() > -1) { lsContent.write(PostDefine.FS); // int value = (int) (amount.intValue() * 100); int value = (int) amount.intValue(); NumberFormat numberFormat = new DecimalFormat("#000000000000"); lsContent.write(numberFormat.format(value).getBytes()); // ��������,������������ if (certificateNo != null) { lsContent.write(PostDefine.FS); lsContent.write(certificateNo.getBytes()); } } int len = lsContent.size(); baos.write(Function.toHex2Len(len)); baos.write(lsContent.toByteArray()); baos.write(PostDefine.ETX); byte[] buffer = baos.toByteArray(); byte[] LRCContent = new byte[buffer.length-4]; System.arraycopy(buffer, 4, LRCContent, 0, buffer.length-4); byte LRC = Function.Enteryparity(LRCContent); baos.write(LRC); baos.write(PostDefine.END); lsContent.close(); baos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return baos.toByteArray(); }
Example 17
Source File: ProxyHttpTransparent.java From PacketProxy with Apache License 2.0 | 4 votes |
private void createHttpTransparentProxy(Socket client) throws Exception { InputStream ins = client.getInputStream(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); HostPort hostPort = null; byte[] input_data = new byte[4096]; int length = 0; while ((length = ins.read(input_data, 0, input_data.length)) != -1) { bout.write(input_data, 0, length); int accepted_input_size = 0; if (bout.size() > 0 && (accepted_input_size = Http.parseHttpDelimiter(bout.toByteArray())) > 0) { hostPort = parseHostName(ArrayUtils.subarray(bout.toByteArray(), 0, accepted_input_size)); break; } } if (hostPort == null) { PacketProxyUtility.getInstance().packetProxyLogErr(new String(input_data)); PacketProxyUtility.getInstance().packetProxyLogErr("bout length == " + bout.size()); if(bout.size() == 0){ PacketProxyUtility.getInstance().packetProxyLogErr("empty request!!"); return; } PacketProxyUtility.getInstance().packetProxyLogErr("HTTP Host field is not found."); return ; } ByteArrayInputStream lookaheadBuffer = new ByteArrayInputStream(bout.toByteArray()); try { Endpoint client_e = EndpointFactory.createClientEndpoint(client, lookaheadBuffer); Endpoint server_e = EndpointFactory.createServerEndpoint(hostPort.getInetSocketAddress()); Server server = Servers.getInstance().queryByHostNameAndPort(hostPort.getHostName(), listen_info.getPort()); createConnection(client_e, server_e, server); } catch(ConnectException e) { InetSocketAddress addr = hostPort.getInetSocketAddress(); PacketProxyUtility.getInstance().packetProxyLog("Connection Refused: " + addr.getHostName() + ":" + addr.getPort()); e.printStackTrace(); } }
Example 18
Source File: JFIFMarkerSegment.java From jdk8u60 with GNU General Public License v2.0 | 4 votes |
JFIFThumbJPEG(BufferedImage thumb) throws IllegalThumbException { int INITIAL_BUFSIZE = 4096; int MAZ_BUFSIZE = 65535 - 2 - PREAMBLE_SIZE; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(INITIAL_BUFSIZE); MemoryCacheImageOutputStream mos = new MemoryCacheImageOutputStream(baos); JPEGImageWriter thumbWriter = new JPEGImageWriter(null); thumbWriter.setOutput(mos); // get default metadata for the thumb JPEGMetadata metadata = (JPEGMetadata) thumbWriter.getDefaultImageMetadata (new ImageTypeSpecifier(thumb), null); // Remove the jfif segment, which should be there. MarkerSegment jfif = metadata.findMarkerSegment (JFIFMarkerSegment.class, true); if (jfif == null) { throw new IllegalThumbException(); } metadata.markerSequence.remove(jfif); /* Use this if removing leaves a hole and causes trouble // Get the tree String format = metadata.getNativeMetadataFormatName(); IIOMetadataNode tree = (IIOMetadataNode) metadata.getAsTree(format); // If there is no app0jfif node, the image is bad NodeList jfifs = tree.getElementsByTagName("app0JFIF"); if (jfifs.getLength() == 0) { throw new IllegalThumbException(); } // remove the app0jfif node Node jfif = jfifs.item(0); Node parent = jfif.getParentNode(); parent.removeChild(jfif); metadata.setFromTree(format, tree); */ thumbWriter.write(new IIOImage(thumb, null, metadata)); thumbWriter.dispose(); // Now check that the size is OK if (baos.size() > MAZ_BUFSIZE) { throw new IllegalThumbException(); } data = baos.toByteArray(); } catch (IOException e) { throw new IllegalThumbException(); } }
Example 19
Source File: ImageUtils.java From Android-utils with Apache License 2.0 | 4 votes |
public static Bitmap compressByQuality(final Bitmap src, final long maxByteSize, final boolean recycle) { if (isEmptyBitmap(src) || maxByteSize <= 0) return null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); src.compress(CompressFormat.JPEG, 100, baos); byte[] bytes; if (baos.size() <= maxByteSize) { bytes = baos.toByteArray(); } else { baos.reset(); src.compress(CompressFormat.JPEG, 0, baos); if (baos.size() >= maxByteSize) { bytes = baos.toByteArray(); } else { // find the best quality using binary search int st = 0; int end = 100; int mid = 0; while (st < end) { mid = (st + end) / 2; baos.reset(); src.compress(CompressFormat.JPEG, mid, baos); int len = baos.size(); if (len == maxByteSize) { break; } else if (len > maxByteSize) { end = mid - 1; } else { st = mid + 1; } } if (end == mid - 1) { baos.reset(); src.compress(CompressFormat.JPEG, st, baos); } bytes = baos.toByteArray(); } } if (recycle && !src.isRecycled()) src.recycle(); return BitmapFactory.decodeByteArray(bytes, 0, bytes.length); }
Example 20
Source File: RepositoryContentHandlerV1.java From ADT_Frontend with MIT License | 4 votes |
protected MessageBody(ByteArrayOutputStream outputStream) { super(CONTENT_TYPE_V3); this.stream = new ByteArrayInputStream(outputStream.toByteArray(), 0, outputStream.size()); }