Java Code Examples for java.io.ByteArrayOutputStream#flush()

The following examples show how to use java.io.ByteArrayOutputStream#flush() . 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: IndexMatchTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
/**
 * Write the provided IndexMatch to a byte array and construct a fresh IndexMatch from that byte array.
 *
 * @param match
 *            the IndexMatch to be written to a byte array.
 * @return a new IndexMatch constructed from the byte array
 * @throws IOException
 */
private IndexMatch writeRead(IndexMatch match) throws IOException {
    // Write the IndexMatch to a byte array.
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    DataOutput output = new DataOutputStream(outputStream);
    match.write(output);
    outputStream.flush();
    
    // Construct input stream from byte array.
    ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
    DataInput input = new DataInputStream(inputStream);
    
    // Construct IndexMatch from input stream and return.
    IndexMatch other = new IndexMatch();
    other.readFields(input);
    return other;
}
 
Example 2
Source File: JacketArtMsg.java    From onpc with GNU General Public License v3.0 6 votes vote down vote up
public Bitmap loadFromBuffer(ByteArrayOutputStream coverBuffer)
{
    if (coverBuffer == null)
    {
        Logging.info(this, "can not open image: empty stream");
        return null;
    }
    Bitmap cover = null;
    try
    {
        Logging.info(this, "loading image from stream");
        coverBuffer.flush();
        coverBuffer.close();
        final byte[] out = coverBuffer.toByteArray();
        cover = BitmapFactory.decodeByteArray(out, 0, out.length);
    }
    catch (Exception e)
    {
        Logging.info(this, "can not open image: " + e.getLocalizedMessage());
    }
    if (cover == null)
    {
        Logging.info(this, "can not open image");
    }
    return cover;
}
 
Example 3
Source File: Parse.java    From protect with MIT License 6 votes vote down vote up
/**
 * Generates a deterministic serialization of a group of EC Points
 * 
 * @param integers
 * @return
 * @throws IOException
 */
public static byte[] concatenate(EcPoint... points) {
	try {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(bos);
		for (EcPoint p : points) {
			byte[] encoded1 = p.getX().toByteArray();
			dos.writeInt(encoded1.length);
			dos.write(encoded1);
			
			byte[] encoded2 = p.getY().toByteArray();
			dos.writeInt(encoded2.length);
			dos.write(encoded2);
		}
		dos.flush();
		bos.flush();
		return bos.toByteArray();
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example 4
Source File: SignedDataWriter.java    From java-11-examples with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] writeData(SignedData data) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dataOutputStream = new DataOutputStream(baos);
    dataOutputStream.writeUTF(data.getAlgorithm());
    byte[] payload = data.getData();
    dataOutputStream.writeInt(payload.length);
    dataOutputStream.write(payload);
    byte[] signature = data.getSignature();
    dataOutputStream.writeInt(signature.length);
    dataOutputStream.write(signature);
    dataOutputStream.flush();
    baos.flush();
    byte[] result = baos.toByteArray();
    dataOutputStream.close();
    baos.close();
    return result;
}
 
Example 5
Source File: BFTMapServer.java    From protect with MIT License 6 votes vote down vote up
@Override
public byte[] getSnapshot() {
	try {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutput out = new ObjectOutputStream(bos);
		out.writeObject(tableMap);
		out.flush();
		bos.flush();
		out.close();
		bos.close();
		return bos.toByteArray();
	} catch (IOException ex) {
		ex.printStackTrace();
		return new byte[0];
	}
}
 
Example 6
Source File: Parse.java    From protect with MIT License 6 votes vote down vote up
/**
 * Generates a deterministic serialization of a list of byte arrays
 * 
 * @param arrays
 * @return
 * @throws IOException
 */
public static byte[] concatenate(final List<byte[]> list) {
	try {
		final ByteArrayOutputStream bos = new ByteArrayOutputStream();
		final DataOutputStream dos = new DataOutputStream(bos);
		for (byte[] array : list) {
			dos.writeInt(array.length);
			dos.write(array);
		}

		dos.flush();
		bos.flush();
		return bos.toByteArray();
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example 7
Source File: MetricsHttpServer.java    From dts with Apache License 2.0 6 votes vote down vote up
public void handle(HttpExchange t) throws IOException {
    String query = t.getRequestURI().getRawQuery();
    ByteArrayOutputStream response = this.response.get();
    response.reset();
    OutputStreamWriter osw = new OutputStreamWriter(response);
    TextFormat.write004(osw, registry.filteredMetricFamilySamples(parseQuery(query)));
    osw.flush();
    osw.close();
    response.flush();
    response.close();
    t.getResponseHeaders().set("Content-Type", TextFormat.CONTENT_TYPE_004);
    t.getResponseHeaders().set("Content-Length", String.valueOf(response.size()));
    if (shouldUseCompression(t)) {
        t.getResponseHeaders().set("Content-Encoding", "gzip");
        t.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
        final GZIPOutputStream os = new GZIPOutputStream(t.getResponseBody());
        response.writeTo(os);
        os.finish();
    } else {
        t.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.size());
        response.writeTo(t.getResponseBody());
    }
    t.close();
}
 
Example 8
Source File: CommonUtils.java    From search-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
public static String inputStream2String(InputStream in) throws IOException {
    byte[] b = new byte[512];
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    int read = 0;
    while ((read = in.read(b)) != -1) {
        bos.write(b, 0, read);
    }
    byte[] outbyte = bos.toByteArray();
    bos.flush();
    bos.close();
    if (in != null) {
        in.close();
    }

    String result = new String(outbyte, "utf-8");
    return result;
}
 
Example 9
Source File: CommonIOUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static byte[] decompress(byte[] unSealmessage) throws IOException {
   long size = (long)unSealmessage.length;
   ByteArrayInputStream inputstream = new ByteArrayInputStream(unSealmessage);
   GZIPInputStream input = new GZIPInputStream(inputstream);
   ByteArrayOutputStream o = new ByteArrayOutputStream();
   byte[] buffer = new byte[1024];

   int i;
   while((i = input.read(buffer)) > 0) {
      o.write(buffer, 0, i);
   }

   o.flush();
   input.close();
   inputstream.close();
   o.close();
   byte[] ret = o.toByteArray();
   LOG.info("Decompression of data from " + size + " bytes to " + ret.length + " bytes");
   return ret;
}
 
Example 10
Source File: EmailSendTaskTest.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected String getMessage(MimeMessage mimeMessage) throws MessagingException, IOException {
  DataHandler dataHandler = mimeMessage.getDataHandler();
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  dataHandler.writeTo(baos);
  baos.flush();
  return baos.toString();
}
 
Example 11
Source File: InternalUtils.java    From huobi_Java with Apache License 2.0 5 votes vote down vote up
public static byte[] decode(byte[] data) throws IOException {
  ByteArrayInputStream bais = new ByteArrayInputStream(data);
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  decompress(bais, baos);
  baos.flush();
  baos.close();
  bais.close();
  return baos.toByteArray();
}
 
Example 12
Source File: FileUtil.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the given {@link InputStream} into a byte array.
 *
 * @param _is a {@link java.io.InputStream} object.
 * @throws java.io.IOException
 * @return an array of {@link byte} objects.
 */
public static byte[] readInputStream(InputStream _is) throws IOException {
	final ByteArrayOutputStream bos = new ByteArrayOutputStream();
	final byte[] byte_buffer = new byte[1024];
	int len = 0;
	while((len = _is.read(byte_buffer)) != -1)
		bos.write(byte_buffer,0,len);
	bos.flush();
	return bos.toByteArray();		
}
 
Example 13
Source File: SerializationTestUtils.java    From java-technology-stack with MIT License 5 votes vote down vote up
public static Object serializeAndDeserialize(Object o) throws IOException, ClassNotFoundException {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	ObjectOutputStream oos = new ObjectOutputStream(baos);
	oos.writeObject(o);
	oos.flush();
	baos.flush();
	byte[] bytes = baos.toByteArray();

	ByteArrayInputStream is = new ByteArrayInputStream(bytes);
	ObjectInputStream ois = new ObjectInputStream(is);
	Object o2 = ois.readObject();
	return o2;
}
 
Example 14
Source File: Packet.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String toString() {
  StringBuilder buf = new StringBuilder();
  buf.append(super.toString());
  String content;
    try {
        Message msg = getMessage();
    if (msg != null) {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    XMLStreamWriter xmlWriter = XMLStreamWriterFactory.create(baos, "UTF-8");
                    msg.copy().writeTo(xmlWriter);
                    xmlWriter.flush();
                    xmlWriter.close();
                    baos.flush();
                    XMLStreamWriterFactory.recycle(xmlWriter);

                    byte[] bytes = baos.toByteArray();
                    //message = Messages.create(XMLStreamReaderFactory.create(null, new ByteArrayInputStream(bytes), "UTF-8", true));
                    content = new String(bytes, "UTF-8");
            } else {
                content = "<none>";
    }
    } catch (Throwable t) {
            throw new WebServiceException(t);
    }
  buf.append(" Content: ").append(content);
  return buf.toString();
}
 
Example 15
Source File: TestUnloadingEventClass.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static MyClassLoader createClassLoaderWithEventClass() throws Exception {
    String resourceName = EVENT_NAME.replace('.', '/') + ".class";
    try (InputStream is = TestUnloadingEventClass.class.getClassLoader().getResourceAsStream(resourceName)) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int byteValue = 0;
        while ((byteValue = is.read(buffer, 0, buffer.length)) != -1) {
            baos.write(buffer, 0, byteValue);
        }
        baos.flush();
        MyClassLoader myClassLoader = new MyClassLoader();
        Class<?> eventClass = myClassLoader.defineClass(EVENT_NAME, baos.toByteArray());
        if (eventClass == null) {
            throw new Exception("Could not define test class");
        }
        if (eventClass.getSuperclass() != Event.class) {
            throw new Exception("Superclass should be jdk.jfr.Event");
        }
        if (eventClass.getSuperclass().getClassLoader() != null) {
            throw new Exception("Class loader of jdk.jfr.Event should be null");
        }
        if (eventClass.getClassLoader() != myClassLoader) {
            throw new Exception("Incorrect class loader for event class");
        }
        eventClass.newInstance(); // force <clinit>
        return myClassLoader;
    }
}
 
Example 16
Source File: RSAUtils.java    From juice with Apache License 2.0 5 votes vote down vote up
private static byte[] doRSA(Cipher cipher, int mode, byte[] data, int keySize) throws IOException, BadPaddingException, IllegalBlockSizeException {
    int maxBlock;
    if(mode == Cipher.DECRYPT_MODE){
        maxBlock = keySize / 8;
    }else{
        maxBlock = keySize / 8 - 11;
    }
    int length = data.length;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        int offset = 0;
        byte[] buf;
        int i = 0;
        // 对数据分段加密
        while (length - offset > 0) {
            if (length - offset > maxBlock) {
                buf = cipher.doFinal(data, offset, maxBlock);
            } else {
                buf = cipher.doFinal(data, offset, length - offset);
            }
            baos.write(buf, 0, buf.length);
            i++;
            offset = i * maxBlock;
        }
        baos.flush();
        return baos.toByteArray();
    } finally {
        baos.close();
    }
}
 
Example 17
Source File: TestUnloadingEventClass.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static MyClassLoader createClassLoaderWithEventClass() throws Exception {
    String resourceName = EVENT_NAME.replace('.', '/') + ".class";
    try (InputStream is = TestUnloadingEventClass.class.getClassLoader().getResourceAsStream(resourceName)) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int byteValue = 0;
        while ((byteValue = is.read(buffer, 0, buffer.length)) != -1) {
            baos.write(buffer, 0, byteValue);
        }
        baos.flush();
        MyClassLoader myClassLoader = new MyClassLoader();
        Class<?> eventClass = myClassLoader.defineClass(EVENT_NAME, baos.toByteArray());
        if (eventClass == null) {
            throw new Exception("Could not define test class");
        }
        if (eventClass.getSuperclass() != Event.class) {
            throw new Exception("Superclass should be jdk.jfr.Event");
        }
        if (eventClass.getSuperclass().getClassLoader() != null) {
            throw new Exception("Class loader of jdk.jfr.Event should be null");
        }
        if (eventClass.getClassLoader() != myClassLoader) {
            throw new Exception("Incorrect class loader for event class");
        }
        eventClass.newInstance(); // force <clinit>
        return myClassLoader;
    }
}
 
Example 18
Source File: TestFlowFileAttributesSerializer.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testBothWays() throws SerializationException, IOException {
    Map<String, String> attributes = new HashMap<>();
    attributes.put("a", "1");
    attributes.put("b", "2");

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    serializer.serialize(attributes, output);
    output.flush();

    Map<String, String> result = serializer.deserialize(output.toByteArray());
    Assert.assertEquals(attributes, result);
}
 
Example 19
Source File: TestUnloadEventClassCount.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static MyClassLoader createClassLoaderWithEventClass() throws Exception {
    String resourceName = EVENT_NAME.replace('.', '/') + ".class";
    try (InputStream is = TestUnloadEventClassCount.class.getClassLoader().getResourceAsStream(resourceName)) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int byteValue = 0;
        while ((byteValue = is.read(buffer, 0, buffer.length)) != -1) {
            baos.write(buffer, 0, byteValue);
        }
        baos.flush();
        MyClassLoader myClassLoader = new MyClassLoader();
        Class<?> eventClass = myClassLoader.defineClass(EVENT_NAME, baos.toByteArray());
        if (eventClass == null) {
            throw new Exception("Could not define test class");
        }
        if (eventClass.getSuperclass() != Event.class) {
            throw new Exception("Superclass should be jdk.jfr.Event");
        }
        if (eventClass.getSuperclass().getClassLoader() != null) {
            throw new Exception("Class loader of jdk.jfr.Event should be null");
        }
        if (eventClass.getClassLoader() != myClassLoader) {
            throw new Exception("Incorrect class loader for event class");
        }
        eventClass.newInstance(); // force <clinit>
        return myClassLoader;
    }
}
 
Example 20
Source File: JIClassInstrumentation.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static byte[] getOriginalClassBytes(Class<?> clazz) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    String name = "/" + clazz.getName().replace(".", "/") + ".class";
    InputStream is = SecuritySupport.getResourceAsStream(name);
    int bytesRead;
    byte[] buffer = new byte[16384];
    while ((bytesRead = is.read(buffer, 0, buffer.length)) != -1) {
        baos.write(buffer, 0, bytesRead);
    }
    baos.flush();
    is.close();
    return baos.toByteArray();
}