java.io.ByteArrayOutputStream Java Examples

The following examples show how to use java.io.ByteArrayOutputStream. 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: CrossDomainConfigTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void marshal() {
    CrossDomainConfig config = new CrossDomainConfig();
    config.setAllowedMethods(Arrays.asList("GET", "OPTIONS"));
    config.setAllowedOrigins(Arrays.asList("a", "b"));
    config.setAllowedHeaders(Arrays.asList("A", "B"));
    config.setAllowCredentials(Boolean.TRUE);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    JaxbUtil.marshal(config, out);

    JsonObject result = Json.createReader(new ByteArrayInputStream(out.toByteArray())).readObject();

    assertThat(result.getJsonArray("allowedMethods").getValuesAs(JsonString.class)).containsExactlyInAnyOrder(Json.createValue("GET"), Json.createValue("OPTIONS"));
    assertThat(result.getJsonArray("allowedOrigins").getValuesAs(JsonString.class)).containsExactlyInAnyOrder(Json.createValue("a"), Json.createValue("b"));
    assertThat(result.getJsonArray("allowedHeaders").getValuesAs(JsonString.class)).containsExactlyInAnyOrder(Json.createValue("A"), Json.createValue("B"));
    assertThat(result.get("allowCredentials")).isEqualTo(JsonValue.TRUE);
}
 
Example #2
Source File: GelfMessage.java    From xian with Apache License 2.0 6 votes vote down vote up
private byte[] gzipMessage(byte[] message) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        GZIPOutputStream stream = new GZIPOutputStream(bos);

        stream.write(message);
        stream.finish();
        Closer.close(stream);
        byte[] zipped = bos.toByteArray();
        Closer.close(bos);
        return zipped;
    } catch (IOException e) {
        return null;
    }
}
 
Example #3
Source File: IOUtilsTest.java    From gadtry with Apache License 2.0 6 votes vote down vote up
@Test
public void copyByTestReturnCheckError()
        throws InstantiationException
{
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PrintStream printStream = AopFactory.proxy(PrintStream.class)
            .byInstance(UnsafeHelper.allocateInstance(PrintStream.class))
            .whereMethod(methodInfo -> methodInfo.getName().equals("checkError"))
            .around(proxyContext -> true);

    try (ByteArrayInputStream inputStream = new ByteArrayInputStream("IOUtilsTest".getBytes(UTF_8))) {
        IOUtils.copyBytes(inputStream, printStream, 1024, false);
        Assert.assertEquals("IOUtilsTest", outputStream.toString(UTF_8.name()));
        Assert.fail();
    }
    catch (IOException e) {
        Assert.assertEquals(e.getMessage(), "Unable to write to output stream.");
    }
}
 
Example #4
Source File: CDARoundTripTests.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
@Test
/**
 * verify that umlaut like äö etc are not encoded in UTF-8 in attributes
 */
public void testSerializeUmlaut() throws IOException {
  Element xml = Manager.parse(context,
	  TestingUtilities.loadTestResourceStream("validator", "cda", "example.xml"), FhirFormat.XML);
  
  List<Element> title = xml.getChildrenByName("title");
  assertTrue(title != null && title.size() == 1);
  
  
  Element value = title.get(0).getChildren().get(0);
  Assertions.assertEquals("Episode Note", value.getValue());
  value.setValue("öé");
  
  ByteArrayOutputStream baosXml = new ByteArrayOutputStream();
  Manager.compose(TestingUtilities.context(), xml, baosXml, FhirFormat.XML, OutputStyle.PRETTY, null);
  String cdaSerialised = baosXml.toString("UTF-8");
  assertTrue(cdaSerialised.indexOf("öé") > 0);
}
 
Example #5
Source File: PercentEncoder.java    From db with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Encodes a byte array into percent encoding
 *
 * @param source The byte-representation of the string.
 * @param bitSet The BitSet for characters to skip encoding
 * @return The percent-encoded byte array
 */
public static byte[] encode(byte[] source, BitSet bitSet) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream(source.length * 2);
    for (int i = 0; i < source.length; i++) {
        int b = source[i];
        if (b < 0) {
            b += 256;
        }
        if (bitSet.get(b)) {
            bos.write(b);
        } else {
            bos.write('%');
            char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, 16));
            char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, 16));
            bos.write(hex1);
            bos.write(hex2);
        }
    }
    return bos.toByteArray();
}
 
Example #6
Source File: Test.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
static void serial(URI u) throws IOException, URISyntaxException {

        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = new ObjectOutputStream(bo);

        oo.writeObject(u);
        oo.close();

        ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
        ObjectInputStream oi = new ObjectInputStream(bi);
        try {
            Object o = oi.readObject();
            eq(u, (URI)o);
        } catch (ClassNotFoundException x) {
            x.printStackTrace();
            throw new RuntimeException(x.toString());
        }

        testCount++;
    }
 
Example #7
Source File: MicroHessianInput.java    From sofa-hessian with Apache License 2.0 6 votes vote down vote up
/**
 * Reads a byte array
 *
 * <pre>
 * B b16 b8 data value
 * </pre>
 */
public byte[] readBytes()
    throws IOException
{
    int tag = is.read();

    if (tag == 'N')
        return null;

    if (tag != 'B')
        throw expect("bytes", tag);

    int b16 = is.read();
    int b8 = is.read();

    int len = (b16 << 8) + b8;

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    for (int i = 0; i < len; i++)
        bos.write(is.read());

    return bos.toByteArray();
}
 
Example #8
Source File: GzipUtils.java    From Ffast-Java with MIT License 6 votes vote down vote up
/**
 * 解压
 * @param data
 * @return
 * @throws Exception
 */
public static byte[] ungzip(byte[] data) throws Exception {
    ByteArrayInputStream bis = new ByteArrayInputStream(data);
    GZIPInputStream gzip = new GZIPInputStream(bis);
    byte[] buf = new byte[1024];
    int num = -1;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    while ((num = gzip.read(buf, 0, buf.length)) != -1) {
        bos.write(buf, 0, num);
    }
    gzip.close();
    bis.close();
    byte[] ret = bos.toByteArray();
    bos.flush();
    bos.close();
    return ret;
}
 
Example #9
Source File: KeyUtil.java    From snowblossom with Apache License 2.0 6 votes vote down vote up
/**
 * Produce a string that is a decomposition of the given x.509 or ASN1 encoded
 * object.  For learning and debugging purposes.
 */
public static String decomposeASN1Encoded(ByteString input)
  throws Exception
{
  ByteArrayOutputStream byte_out = new ByteArrayOutputStream();
  PrintStream out = new PrintStream(byte_out);

  ASN1StreamParser parser = new ASN1StreamParser(input.toByteArray());
  out.println("ASN1StreamParser");

  while(true)
  {
    ASN1Encodable encodable = parser.readObject();
    if (encodable == null) break;

    decomposeEncodable(encodable, 2, out);
  }

  out.flush();
  return new String(byte_out.toByteArray());

}
 
Example #10
Source File: DistributedKeySignature.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
DistributedKeySignature(String signatureAlgorithm) throws NoSuchAlgorithmException {
   LOG.debug("constructor: " + signatureAlgorithm);
   this.signatureAlgorithm = signatureAlgorithm;
   if (!digestAlgos.containsKey(signatureAlgorithm)) {
      LOG.error("no such algo: " + signatureAlgorithm);
      throw new NoSuchAlgorithmException(signatureAlgorithm);
   } else {
      String digestAlgo = (String)digestAlgos.get(signatureAlgorithm);
      if (null != digestAlgo) {
         this.messageDigest = MessageDigest.getInstance(digestAlgo);
         this.precomputedDigestOutputStream = null;
      } else {
         LOG.debug("NONE message digest");
         this.messageDigest = null;
         this.precomputedDigestOutputStream = new ByteArrayOutputStream();
      }

   }
}
 
Example #11
Source File: ImageUtils.java    From Tok-Android with GNU General Public License v3.0 6 votes vote down vote up
private static Bitmap compressBitmap(Bitmap bitmap, long sizeLimit) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int quality = 90;
    bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
    LogUtil.i(TAG, "origin size:" + baos.size());
    //TODO has problem
    while (baos.size() / 1024 > sizeLimit) {
        LogUtil.i(TAG, "after size:" + baos.size());
        // 清空baos
        baos.reset();
        quality -= 10;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
    }

    return BitmapFactory.decodeStream(new ByteArrayInputStream(baos.toByteArray()), null, null);
}
 
Example #12
Source File: Base64GetEncoderTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static void testWrapEncode2(final Base64.Encoder encoder)
        throws IOException {
    System.err.println("\nEncoder.wrap test II ");
    final byte[] secondTestBuffer =
            "api/java_util/Base64/index.html#GetEncoderMimeCustom[noLineSeparatorInEncodedString]"
            .getBytes(US_ASCII);
    String base64EncodedString;
    ByteArrayOutputStream secondEncodingStream = new ByteArrayOutputStream();
    OutputStream base64EncodingStream = encoder.wrap(secondEncodingStream);
    base64EncodingStream.write(secondTestBuffer);
    base64EncodingStream.close();

    final byte[] encodedByteArray = secondEncodingStream.toByteArray();

    System.err.print("result = " + new String(encodedByteArray, US_ASCII)
            + "  after wrap Base64 encoding of string");

    base64EncodedString = new String(encodedByteArray, US_ASCII);

    if (base64EncodedString.contains("$$$")) {
        throw new RuntimeException(
                "Base64 encoding contains line separator after wrap 2 invoked  ... \n");
    }
}
 
Example #13
Source File: BandStructure.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public void setInputStreamFrom(InputStream in) throws IOException {
    assert(bytes == null);
    assert(assertReadyToReadFrom(this, in));
    setPhase(READ_PHASE);
    this.in = in;
    if (optDumpBands) {
        // Tap the stream.
        bytesForDump = new ByteArrayOutputStream();
        this.in = new FilterInputStream(in) {
            @Override
            public int read() throws IOException {
                int ch = in.read();
                if (ch >= 0)  bytesForDump.write(ch);
                return ch;
            }
            @Override
            public int read(byte b[], int off, int len) throws IOException {
                int nr = in.read(b, off, len);
                if (nr >= 0)  bytesForDump.write(b, off, nr);
                return nr;
            }
        };
    }
    super.readyToDisburse();
}
 
Example #14
Source File: VMSupport.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Write the given properties list to a byte array and return it. Properties with
 * a key or value that is not a String is filtered out. The stream written to the byte
 * array is ISO 8859-1 encoded.
 */
private static byte[] serializePropertiesToByteArray(Properties p) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream(4096);

    Properties props = new Properties();

    // stringPropertyNames() returns a snapshot of the property keys
    Set<String> keyset = p.stringPropertyNames();
    for (String key : keyset) {
        String value = p.getProperty(key);
        props.put(key, value);
    }

    props.store(out, null);
    return out.toByteArray();
}
 
Example #15
Source File: HtmlUtil.java    From Kepler with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static String encodeToString(BufferedImage image, String type) {
    String imageString = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        ImageIO.write(image, type, bos);
        byte[] imageBytes = bos.toByteArray();

        imageString =  new String(Base64.encodeBase64(imageBytes));

        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return imageString;
}
 
Example #16
Source File: HttpService.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public static byte[] content(URI uri, ProgressMonitor<Long> monitor) throws IOException {
   try (CloseableHttpResponse rsp = get(uri)) {
      if (rsp.getStatusLine().getStatusCode() != 200) {
         throw new IOException("http request failed: " + rsp.getStatusLine().getStatusCode());
      }

      HttpEntity entity = rsp.getEntity();

      long length = entity.getContentLength();
      int clength = (int)length;
      if (clength <= 0 || length >= Integer.MAX_VALUE) clength = 256;

      try (InputStream is = entity.getContent();
           ByteArrayOutputStream os = new ByteArrayOutputStream(clength)) {
         copy(is, os, length, monitor);
         EntityUtils.consume(entity);
         return os.toByteArray();
      }
   }
}
 
Example #17
Source File: SysGeneratorServiceImpl.java    From open-capacity-platform with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] generatorCode(String[] tableNames) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ZipOutputStream zip = new ZipOutputStream(outputStream);

    for(String tableName : tableNames){
        //查询表信息
        Map<String, String> table = queryTable(tableName);
        //查询列信息
        List<Map<String, String>> columns = queryColumns(tableName);
        //生成代码
        GenUtils.generatorCode(table, columns, zip);
    }
    IOUtils.closeQuietly(zip);
    return outputStream.toByteArray();
}
 
Example #18
Source File: Compression.java    From xyz-hub with Apache License 2.0 6 votes vote down vote up
/**
 * Decompress a byte array which was compressed using Deflate.
 * @param bytearray non-null byte array to be decompressed
 * @return the decompressed payload or an empty array in case of bytearray is null
 * @throws DataFormatException in case the payload cannot be decompressed
 */
public static byte[] decompressUsingInflate(byte[] bytearray) throws DataFormatException {
  if (bytearray == null) return new byte[0];

  try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
    final Inflater inflater = new Inflater();
    final byte[] buff = new byte[1024];

    inflater.setInput(bytearray);

    while (!inflater.finished()) {
      int count = inflater.inflate(buff);
      bos.write(buff, 0, count);
    }

    inflater.end();
    bos.flush();
    return bos.toByteArray();
  } catch (IOException e) {
    throw new DataFormatException(e.getMessage());
  }
}
 
Example #19
Source File: LambdaWrapperTest.java    From cloudformation-cli-java-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void invokeHandler_invalidModelTypes_causesSchemaValidationFailure() throws IOException {
    // use actual validator to verify behaviour
    final WrapperOverride wrapper = new WrapperOverride(providerLoggingCredentialsProvider, platformEventsLogger,
                                                        providerEventsLogger, providerMetricsPublisher, new Validator() {
                                                        }, httpClient);

    wrapper.setTransformResponse(resourceHandlerRequest);

    try (final InputStream in = loadRequestStream("create.request.with-invalid-model-types.json");
        final OutputStream out = new ByteArrayOutputStream()) {
        final Context context = getLambdaContext();

        wrapper.handleRequest(in, out, context);

        // verify output response
        verifyHandlerResponse(out,
            ProgressEvent.<TestModel, TestContext>builder().errorCode(HandlerErrorCode.InvalidRequest)
                .status(OperationStatus.FAILED)
                .message("Model validation failed (#/property1: expected type: String, found: JSONArray)").build());
    }
}
 
Example #20
Source File: TestPushdownSupportedBlockWriter.java    From yosegi with Apache License 2.0 6 votes vote down vote up
@Test
public void T_dataSizeAfterAppend_equalsDataBinarySize_withNestedSimpleCaseChild() throws IOException {
  PushdownSupportedBlockWriter writer = new PushdownSupportedBlockWriter();
  writer.setup( 1024 * 1024 * 8 , new Configuration() );
  List<ColumnBinary> childList = createSimpleCaseData();
  List<ColumnBinary> list = Arrays.asList( DumpSpreadColumnBinaryMaker.createSpreadColumnBinary(
      "parent" , 10 , childList ) );
  int sizeAfterAppend = writer.sizeAfterAppend( list );
  writer.append( 10 , list );

  int outputDataSize = writer.size();
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  writer.writeVariableBlock( out );
  byte[] block = out.toByteArray();
  assertEquals( outputDataSize , block.length );
}
 
Example #21
Source File: BTChipDongle.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
public void provideLiquidIssuanceInformation(final int numInputs) throws BTChipException {
	// we can safely assume that we will never sign any issuance here
	ByteArrayOutputStream data = new ByteArrayOutputStream(numInputs);
	for (int i = 0; i < numInputs; i++) {
		data.write(0x00);
	}

	exchangeApdu(BTCHIP_CLA, BTCHIP_INS_GET_LIQUID_ISSUANCE_INFORMATION, (byte)0x80, (byte)0x00, data.toByteArray(), OK);
}
 
Example #22
Source File: SimpleHttpInvokerRequestExecutor.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Execute the given request through a standard {@link HttpURLConnection}.
 * <p>This method implements the basic processing workflow:
 * The actual work happens in this class's template methods.
 * @see #openConnection
 * @see #prepareConnection
 * @see #writeRequestBody
 * @see #validateResponse
 * @see #readResponseBody
 */
@Override
protected RemoteInvocationResult doExecuteRequest(
		HttpInvokerClientConfiguration config, ByteArrayOutputStream baos)
		throws IOException, ClassNotFoundException {

	HttpURLConnection con = openConnection(config);
	prepareConnection(con, baos.size());
	writeRequestBody(config, con, baos);
	validateResponse(config, con);
	InputStream responseBody = readResponseBody(config, con);

	return readRemoteInvocationResult(responseBody, config.getCodebaseUrl());
}
 
Example #23
Source File: StreamObject.java    From Launcher with GNU General Public License v3.0 5 votes vote down vote up
public final byte[] write() throws IOException {
    try (ByteArrayOutputStream array = IOHelper.newByteArrayOutput()) {
        try (HOutput output = new HOutput(array)) {
            write(output);
        }
        return array.toByteArray();
    }
}
 
Example #24
Source File: GzipInterceptor.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * @param data  Data to decompress
 * @return      Decompressed data
 * @throws IOException Compression error
 */
public static byte[] decompress(byte[] data) throws IOException {
    ByteArrayOutputStream bout =
        new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE);
    ByteArrayInputStream bin = new ByteArrayInputStream(data);
    GZIPInputStream gin = new GZIPInputStream(bin);
    byte[] tmp = new byte[DEFAULT_BUFFER_SIZE];
    int length = gin.read(tmp);
    while (length > -1) {
        bout.write(tmp, 0, length);
        length = gin.read(tmp);
    }
    return bout.toByteArray();
}
 
Example #25
Source File: CharacterEncoder.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * A 'streamless' version of encode that simply takes a buffer of
 * bytes and returns a string containing the encoded buffer.
 */
public String encodeBuffer(byte aBuffer[]) {
    ByteArrayOutputStream   outStream = new ByteArrayOutputStream();
    ByteArrayInputStream    inStream = new ByteArrayInputStream(aBuffer);
    try {
        encodeBuffer(inStream, outStream);
    } catch (Exception IOException) {
        // This should never happen.
        throw new Error("CharacterEncoder.encodeBuffer internal error");
    }
    return (outStream.toString());
}
 
Example #26
Source File: LavalinkUtil.java    From Lavalink-Client with MIT License 5 votes vote down vote up
/**
 * @param track the track to serialize
 * @return the serialized track as binary
 * @throws IOException if there is an IO problem
 */
@SuppressWarnings("WeakerAccess")
public static byte[] toBinary(AudioTrack track) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PLAYER_MANAGER.encodeTrack(new MessageOutput(baos), track);
    return baos.toByteArray();
}
 
Example #27
Source File: IoUtils.java    From easyexcel with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the contents of an InputStream as a byte[].
 *
 * @param input
 * @return
 * @throws IOException
 */
public static byte[] toByteArray(final InputStream input) throws IOException {
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    try {
        copy(input, output);
        return output.toByteArray();
    } finally {
        output.toByteArray();
    }
}
 
Example #28
Source File: RecordStoreUtilities.java    From constellation with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a {@link RecordStore} into a JSON document.
 * <p>
 * The JSON document consist of an array of objects, with each object
 * representing a record in the specified {@link RecordStore}. Each field in
 * each object is corresponds to an entry in the corresponding record of the
 * {@link RecordStore}.
 *
 * @param recordStore The {@link RecordStore} you wish to parse into a JSON
 * document.
 * @return A {@link String} representing a JSON document derived from the
 * specified {@link RecordStore}.
 * @throws IOException If something goes wrong while writing to the JSON
 * document.
 */
public static String toJson(final RecordStore recordStore) throws IOException {
    final String json;
    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
        try (final JsonGenerator jg = new JsonFactory().createGenerator(outputStream)) {
            jg.writeStartArray();

            if (recordStore != null && recordStore.size() > 0) {
                recordStore.reset();
                while (recordStore.next()) {
                    jg.writeStartObject();
                    for (String key : recordStore.keys()) {
                        final String value = recordStore.get(key);
                        if (value == null) {
                            continue;
                        }
                        jg.writeStringField(key, value);
                    }
                    jg.writeEndObject();
                }
            }
            jg.writeEndArray();
        }
        json = outputStream.toString(StandardCharsets.UTF_8.name());
    }
    return json;
}
 
Example #29
Source File: WritableUtil.java    From datawave with Apache License 2.0 5 votes vote down vote up
/**
 * A convenience method for serializing a long into a byte array.
 * 
 * @param l
 * @return
 */
public static byte[] getLongBytes(long l) {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        new LongWritable(l).write(new DataOutputStream(baos));
        return baos.toByteArray();
    } catch (IOException e) {
        return EmptyValue.getEmptyBytes();
    }
}
 
Example #30
Source File: S3SyncClientResource.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
@GET
@Path("download/{objectKey}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadFile(@PathParam("objectKey") String objectKey) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GetObjectResponse object = s3.getObject(buildGetRequest(objectKey), ResponseTransformer.toOutputStream(baos));

    ResponseBuilder response = Response.ok((StreamingOutput) output -> baos.writeTo(output));
    response.header("Content-Disposition", "attachment;filename=" + objectKey);
    response.header("Content-Type", object.contentType());
    return response.build();
}