下面列出了怎么用org.apache.commons.io.output.ByteArrayOutputStream的API类实例代码及写法,或者点击链接到github查看源代码。
public S3TransportBuffer(long maxBytes, boolean useCompression, S3TransportSerializer serializer)
throws TransportException {
this.maxBytes = maxBytes;
this.serializer = serializer;
baos = new ByteArrayOutputStream();
cos = new CountingOutputStream(baos);
if (useCompression) {
this.isCompressed = true;
try {
os = new BZip2CompressorOutputStream(cos);
} catch (IOException e) {
throw new TransportException("unable to create BZip2CompressorOutputStream", e);
}
} else {
this.isCompressed = false;
os = cos;
}
}
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.ALL })
@Test(groups = "wso2.esb", description = "disabling auto primitive option with a given regex pattern in synapse "
+ "properties ")
public void testDisablingAutoConversionToScientificNotationInJsonStreamFormatter() throws Exception {
String payload = "<coordinates>\n" + " <location>\n" + " <name>Bermuda Triangle</name>\n"
+ " <n>25e1</n>\n" + " <w>7.1e1</w>\n" + " </location>\n" + " <location>\n"
+ " <name>Eiffel Tower</name>\n" + " <n>4.8e3</n>\n" + " <e>1.8e2</e>\n"
+ " </location>\n" + "</coordinates>";
HttpResponse response = httpClient
.doPost(getProxyServiceURLHttp("JSONDisableAutoPrimitiveNumericTestProxy"), null, payload,
"application/xml");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
response.getEntity().writeTo(bos);
String actualResult = new String(bos.toByteArray());
String expectedPayload = "{\"coordinates\":{\"location\":[{\"name\":\"Bermuda Triangle\",\"n\":\"25e1\""
+ ",\"w\":\"7.1e1\"},{\"name\":\"Eiffel Tower\",\"n\":\"4.8e3\",\"e\":\"1.8e2\"}]}}";
Assert.assertEquals(actualResult, expectedPayload);
}
@SetEnvironment(executionEnvironments = {ExecutionEnvironment.ALL})
@Test(groups = "wso2.esb", description = "disabling auto primitive option in synapse properties ", enabled = false)
public void testDisablingAutoConversionToScientificNotationInJsonStreamFormatter() throws Exception {
String payload =
"{\"state\":[{\"path\":\"user_programs_progress\",\"entry\":" +
"[{\"value\":\"false\",\"key\":\"testJson14\"}]}]}";
HttpResponse response = httpClient.doPost("http://localhost:8280/ESBJAVA4572abc/dd",
null, payload, "application/json");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
response.getEntity().writeTo(bos);
String exPayload = new String(bos.toByteArray());
String val = "{\"state\":[{\"path\":\"user_programs_progress\",\"entry\":" +
"[{\"value\":\"false\",\"key\":\"testJson14\"}]}]}";
Assert.assertEquals(val, exPayload);
}
@Before
public void initTest() {
outputStream = new ByteArrayOutputStream();
ps = new PrintStream(outputStream, true);
marathon = Mockito.mock(Marathon.class);
mesosCluster = Mockito.mock(MesosCluster.class);
when(mesosCluster.getMarathon()).thenReturn(marathon);
repository = Mockito.mock(ClusterRepository.class);
when(repository.loadCluster(Matchers.any(MesosClusterFactory.class))).thenReturn(mesosCluster);
commandUninstall = new CommandUninstall(ps);
commandUninstall.setRepository(repository);
}
@Test
public void body() {
Request request = new RequestBuilderImpl()
.body(new JsonObject().put("name", "value"))
.build();
assertEquals("value", request.body().asJson().toBlocking().last().get("name").asString());
assertEquals("value", new JsonObject(request.body().asString().toBlocking().last()).get("name").asString());
assertEquals("value", new JsonObject(new String(request.body().asBytes().toBlocking().last())).get("name").asString());
assertEquals("value", new JsonObject(new String(request.body().asChunks()
.collect(
() -> new ByteArrayOutputStream(),
(stream, chunk) -> {
try {
stream.write(chunk);
} catch (IOException e) { }
})
.map(stream -> stream.toByteArray())
.toBlocking().last())).get("name").asString());
request = new RequestBuilderImpl()
.body(new JsonArray("[{\"name\" : \"value\"}]"))
.build();
assertEquals("value", request.body().asJsonArray().toBlocking().last().get("name").asString());
}
/**
* 데이타 전송
* @param event
* @throws Exception
* @return void
*/
public void send(COL_ONEM2M event) throws Exception {
EncoderFactory avroEncoderFactory = EncoderFactory.get();
SpecificDatumWriter<COL_ONEM2M> avroEventWriter = new SpecificDatumWriter<COL_ONEM2M>(COL_ONEM2M.SCHEMA$);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
BinaryEncoder binaryEncoder = avroEncoderFactory.binaryEncoder(stream,null);
try {
avroEventWriter.write(event, binaryEncoder);
binaryEncoder.flush();
} catch (IOException e) {
e.printStackTrace();
throw e;
}
IOUtils.closeQuietly(stream);
KeyedMessage<String, byte[]> data = new KeyedMessage<String, byte[]>(
TOPIC, stream.toByteArray());
producer.send(data);
}
/**
* Converts an inputStream to a byte array. The input stream should be a stream of profile
* picture bytes that comes in the response to a GET request on the Microsoft Graph API
*
* @param inputStream
* @return
*/
private byte[] inputStreamToByteArray(InputStream inputStream) throws IOException {
byte[] pictureBytes = null;
try {
BufferedInputStream bufferedInputStream = (BufferedInputStream) inputStream;
byte[] buff = new byte[8000];
ByteArrayOutputStream bao = new ByteArrayOutputStream();
int bytesRead = 0;
//This seems to be executing on the main thread!!!
while ((bytesRead = bufferedInputStream.read(buff)) != -1) {
bao.write(buff, 0, bytesRead);
}
pictureBytes = bao.toByteArray();
bao.close();
} catch (IOException ex) {
DebugLogger.getInstance().writeLog(Level.SEVERE,
"Attempting to read buffered network resource",
ex);
}
return pictureBytes;
}
@Override
public DataBuffer compress(DataBuffer buffer) {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(stream);
DataOutputStream dos = new DataOutputStream(gzip);
buffer.write(dos);
dos.flush();
dos.close();
byte[] bytes = stream.toByteArray();
// logger.info("Bytes: {}", Arrays.toString(bytes));
BytePointer pointer = new BytePointer(bytes);
CompressionDescriptor descriptor = new CompressionDescriptor(buffer, this);
descriptor.setCompressedLength(bytes.length);
CompressedDataBuffer result = new CompressedDataBuffer(pointer, descriptor);
return result;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected byte[] getBytes(int compressLevel) {
try {
CloverDataFormatter formatter = new CloverDataFormatter();
formatter.setCompressLevel(compressLevel);
DataRecordMetadata metadata = getMetadata();
formatter.init(metadata);
ByteArrayOutputStream os = new ByteArrayOutputStream();
formatter.setDataTarget(os);
formatter.writeHeader();
DataRecord record = DataRecordFactory.newRecord(metadata);
CloverBuffer buffer = null;
if (formatter.isDirect()) {
buffer = CloverBuffer.allocate(Defaults.Record.RECORD_INITIAL_SIZE, Defaults.Record.RECORD_LIMIT_SIZE);
}
record.getField(0).setValue("test1");
writeRecord(formatter, record, buffer);
record.getField(0).setValue("test2");
writeRecord(formatter, record, buffer);
formatter.writeFooter();
formatter.flush();
formatter.close();
return os.toByteArray();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
protected byte[] getBytes() {
if (bytes == null) {
try {
XLSXDataFormatter formatter = new XLSXDataFormatter(false, false);
formatter.init(getMetadata());
ByteArrayOutputStream os = new ByteArrayOutputStream();
formatter.setDataTarget(Channels.newChannel(os));
formatter.prepareSheet();
formatter.writeHeader();
formatter.writeFooter();
formatter.close();
bytes = os.toByteArray();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return bytes;
}
public int getVersion() throws Exception {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CommandLine cmdLine = new CommandLine(p4d);
cmdLine.addArgument("-V");
DefaultExecutor executor = new DefaultExecutor();
PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
executor.setStreamHandler(streamHandler);
executor.execute(cmdLine);
int version = 0;
for (String line : outputStream.toString().split("\\n")) {
if (line.startsWith("Rev. P4D")) {
Pattern p = Pattern.compile("\\d{4}\\.\\d{1}");
Matcher m = p.matcher(line);
while (m.find()) {
String found = m.group();
found = found.replace(".", ""); // strip "."
version = Integer.parseInt(found);
}
}
}
logger.info("P4D Version: " + version);
return version;
}
/**
* Encrypt a test string with an asymmetric key and check that it can be decrypted
* @throws IOException
* @throws PGPException
*/
@Test
public void encryptAsym() throws IOException, PGPException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream os = GPGFileEncryptor.encryptFile(baos, getClass().getResourceAsStream(PUBLIC_KEY),
Long.parseUnsignedLong(KEY_ID, 16), "CAST5");
os.write(EXPECTED_FILE_CONTENT_BYTES);
os.close();
baos.close();
byte[] encryptedBytes = baos.toByteArray();
try (InputStream is = GPGFileDecryptor.decryptFile(new ByteArrayInputStream(encryptedBytes),
getClass().getResourceAsStream(PRIVATE_KEY), PASSPHRASE)) {
byte[] decryptedBytes = IOUtils.toByteArray(is);
Assert.assertNotEquals(EXPECTED_FILE_CONTENT_BYTES, encryptedBytes);
Assert.assertEquals(EXPECTED_FILE_CONTENT_BYTES, decryptedBytes);
}
}
ActionResult<Wo> execute(EffectivePerson effectivePerson, String id) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Attachment2 attachment = emc.find(id, Attachment2.class, ExceptionWhen.not_found);
/* 判断文件的当前用户是否是管理员或者文件创建者 或者当前用户在分享或者共同编辑中 */
if (effectivePerson.isNotManager() && effectivePerson.isNotPerson(attachment.getPerson())) {
throw new Exception("person{name:" + effectivePerson.getDistinguishedName() + "} access attachment{id:"
+ id + "} denied.");
}
OriginFile originFile = emc.find(attachment.getOriginFile(),OriginFile.class);
if (null == originFile) {
throw new ExceptionAttachmentNotExist(id,attachment.getOriginFile());
}
StorageMapping mapping = ThisApplication.context().storageMappings().get(OriginFile.class,
originFile.getStorage());
try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
originFile.readContent(mapping, output);
String value = Base64.encodeBase64String(output.toByteArray());
Wo wo = new Wo();
wo.setValue(value);
result.setData(wo);
}
return result;
}
}
@Test
public void testLogMessagesWithEmptyLastParams() throws IOException {
List<LogData> list = new ArrayList<>();
LogData ld1 = new LogDataBuilder().withId(1).withDate(new Date()).withLevel(Level.INFO).withMessage("My Message1").build();
LogData ld2 = new LogDataBuilder().withId(2).withDate(new Date()).withLevel(Level.INFO).withMessage("My Message2").build();
list.add(ld1);
list.add(ld2);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ver2.saveLogsList(out, list);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
List<LogData> loadLogsList = ver2.loadLogsList(in);
AssertJUnit.assertEquals(2, loadLogsList.size());
AssertJUnit.assertEquals(ld1.getMessage(), loadLogsList.get(0).getMessage());
AssertJUnit.assertEquals(ld2.getMessage(), loadLogsList.get(1).getMessage());
AssertJUnit.assertEquals(ld1, loadLogsList.get(0));
AssertJUnit.assertEquals(ld2, loadLogsList.get(1));
}
/**
* Serializes the {@link Serializable} object passed and returns it as a byte array.
*
* @param object The object to serialize
*
* @return the byte stream with the object serialized in it.
*
* @throws ObjectSerializationException if an I/O exception occurs while serializing the object.
*/
public final byte[] writeObject(final Serializable object) throws ObjectSerializationException
{
final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try(final ObjectOutputStream stream = new ObjectOutputStream(bytes))
{
stream.writeObject(object);
}
catch(final IOException e)
{
throw new ObjectSerializationException(e);
}
return bytes.toByteArray();
}
@Test
public void entityTests() {
assertEquals("test", new BytesBody("test".getBytes()).asString().toBlocking().last());
assertEquals("test", new String(new BytesBody("test".getBytes()).asBytes().toBlocking().last()));
assertEquals("test", new String(new BytesBody("test".getBytes())
.asChunks()
.collect(
() -> new ByteArrayOutputStream(),
(stream, chunk) -> {
try {
stream.write(chunk);
} catch (IOException e) {
}
})
.map(stream -> stream.toByteArray()).toBlocking().last()));
Assert.assertEquals("value", new BytesBody("{\"name\":\"value\"}".getBytes())
.asJson().toBlocking().last().get("name").asString());
assertEquals("value", new BytesBody("[{\"name\":\"value\"}]".getBytes())
.asJsonArray().toBlocking().last().get("name").asString());
}
@Test
public void testSerDe() {
TinyMetric metric = createMetric();
for (int i = 1; i <= 10; i++) {
metric.append(i);
}
Kryo kryo = new Kryo();
ByteArrayOutputStream bao = new ByteArrayOutputStream();
Output output = new Output(bao);
kryo.writeObject(output, metric);
output.close();
TinyMetric deser =
kryo.readObject(new Input(new ByteArrayInputStream(bao.toByteArray())), TinyMetric.class);
assertEquals(metric.size(), deser.size());
assertEquals(metric.getNumRecords(), deser.getNumRecords());
for (int i = 0; i < metric.getNumRecords(); i++) {
assertEquals(metric.get(i), deser.get(i));
}
}
public static WarpScriptStackFunction wrap(String name, InputStream in, boolean secure) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
while(true) {
int len = in.read(buf);
if (len < 0) {
break;
}
baos.write(buf, 0, len);
}
in.close();
String mc2 = new String(baos.toByteArray(), StandardCharsets.UTF_8);
return wrap(name, mc2, secure);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
@Override
public void getNext(CAS aCAS)
throws IOException, CollectionException
{
// nextTarEntry cannot be null here!
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int size = IOUtils.copy(tarArchiveInputStream, buffer);
String entryName = nextTarEntry.getName();
getLogger().debug("Loaded " + size + " bytes from " + entryName);
// and move forward
fastForwardToNextValidEntry();
// and now create JCas
InputStream inputStream = new ByteArrayInputStream(buffer.toByteArray());
try {
XmiCasDeserializer.deserialize(inputStream, aCAS, lenient);
}
catch (SAXException e) {
throw new IOException(e);
}
}
@Test
public void testSecureCopyFile() throws JSchException, IOException {
final JschBuilder mockJschBuilder = mock(JschBuilder.class);
final JSch mockJsch = mock(JSch.class);
final Session mockSession = mock(Session.class);
final ChannelExec mockChannelExec = mock(ChannelExec.class);
final byte [] bytes = {0};
final ByteArrayOutputStream out = new ByteArrayOutputStream();
when(mockChannelExec.getInputStream()).thenReturn(new TestInputStream());
when(mockChannelExec.getOutputStream()).thenReturn(out);
when(mockSession.openChannel(eq("exec"))).thenReturn(mockChannelExec);
when(mockJsch.getSession(anyString(), anyString(), anyInt())).thenReturn(mockSession);
when(mockJschBuilder.build()).thenReturn(mockJsch);
when(Config.mockSshConfig.getJschBuilder()).thenReturn(mockJschBuilder);
when(Config.mockRemoteCommandExecutorService.executeCommand(any(RemoteExecCommand.class))).thenReturn(mock(RemoteCommandReturnInfo.class));
final String source = BinaryDistributionControlServiceImplTest.class.getClassLoader().getResource("binarydistribution/copy.txt").getPath();
binaryDistributionControlService.secureCopyFile("someHost", source, "./build/tmp");
verify(Config.mockSshConfig).getJschBuilder();
assertEquals("C0644 12 copy.txt\nsome content\0", out.toString(StandardCharsets.UTF_8));
}
public MemoryJarClassLoader(ClassLoader parentClassLoader, File jarFile) throws FileNotFoundException, IOException {
super(parentClassLoader);
this.jarFile = jarFile;
try (FileInputStream fileInputStream = new FileInputStream(jarFile)) {
try (JarInputStream jarInputStream = new JarInputStream(fileInputStream)) {
JarEntry entry = jarInputStream.getNextJarEntry();
while (entry != null) {
if (entry.getName().endsWith(".jar")) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
IOUtils.copy(jarInputStream, byteArrayOutputStream);
// Not storing the original JAR, so future code will be unable to read the original
loadSubJars(byteArrayOutputStream.toByteArray());
} else {
// Files are being stored deflated in memory because most of the time a lot of files are not being used (or the complete plugin is not being used)
addDataToMap(jarInputStream, entry);
}
entry = jarInputStream.getNextJarEntry();
}
}
}
}
/**
* Converts a BufferedInputStream to a byte array
*
* @param inputStream
* @param bufferLength
* @return
* @throws IOException
*/
private byte[] convertBufferToBytes(BufferedInputStream inputStream, int bufferLength) throws IOException {
if (inputStream == null)
return null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[bufferLength];
int x = inputStream.read(buffer, 0, bufferLength);
Log.i("GraphServiceController", "bytes read from picture input stream " + String.valueOf(x));
int n = 0;
try {
while ((n = inputStream.read(buffer, 0, bufferLength)) >= 0) {
outputStream.write(buffer, 0, n);
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
outputStream.close();
return outputStream.toByteArray();
}
@Test
public void testExportToM3U() throws Exception {
when(mediaFileDao.getFilesInPlaylist(eq(23))).thenReturn(getPlaylistFiles());
when(settingsService.getPlaylistExportFormat()).thenReturn("m3u");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
playlistService.exportPlaylist(23, outputStream);
String actual = outputStream.toString();
Assert.assertEquals(IOUtils.toString(getClass().getResourceAsStream("/PLAYLISTS/23.m3u")), actual);
}
/**
* Plots the chart and sends it in the form of ByteArrayOutputStream to
* outside.
*
* @return Returns the byteArrayOutputStream.
*/
public synchronized ByteArrayOutputStream writePlot ( ) {
if ( !changed ) return byteArrayOutputStream;
byteArrayOutputStream.reset( );
try {
ChartUtilities.writeChartAsPNG( byteArrayOutputStream , chart , width , height , false , 8 );
} catch ( IOException e ) {
logger.warn( e.getMessage( ) , e );
}
return byteArrayOutputStream;
}
public byte[] createDelta() {
/// The following call informs the state engine that we have finished writing
/// all of our snapshot / delta files, and we are ready to begin adding fresh
/// object instances for the next cycle.
stateEngine.prepareForNextCycle();
// Again, we add each of our object instances to the state engine.
// This operation is still thread safe and can be called from multiple processing threads.
stateEngine.add("A", getExampleA1());
stateEngine.add("A", getExampleA2Prime());
/// We must again let the state engine know that we have finished adding all of our
/// objects to the state.
stateEngine.prepareForWrite();
/// Create a writer, which will be responsible for creating snapshot and/or delta blobs.
FastBlobWriter writer = new FastBlobWriter(stateEngine);
/// Again create an output stream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream outputStream = new DataOutputStream(baos);
try {
/// This time write the delta file.
writer.writeDelta(outputStream);
} catch(IOException e) {
/// thrown if the FastBlobWriter was unable to write to the provided stream.
} finally {
try {
outputStream.close();
} catch(IOException ignore){ }
}
byte delta[] = baos.toByteArray();
return delta;
}
@Test(groups = "wso2.esb", description = "Verify whether the WSDL Bindings contain Policyreference element when security policy is added via capp.")
public void testPolicyReferenceInWSDLBindings() throws IOException, InterruptedException {
String epr = "http://localhost:8280/services/SecpolicyCappTest?wsdl";
final SimpleHttpClient httpClient = new SimpleHttpClient();
HttpResponse response = httpClient.doGet(epr, null);
Thread.sleep(4000);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
response.getEntity().writeTo(bos);
String wsdlResponse = new String(bos.toByteArray());
CharSequence expectedTag = "PolicyReference";
Assert.assertTrue(wsdlResponse.contains(expectedTag));
}
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.ALL })
@Test(groups = "wso2.esb", description = "disabling auto primitive option in synapse properties ", enabled = false)
public void testDisablingAutoConversionToScientificNotationInJsonStreamFormatter() throws Exception {
String payload = "{\"state\":[{\"path\":\"user_programs_progress\",\"entry\":"
+ "[{\"value\":\"false\",\"key\":\"testJson14\"}]}]}";
HttpResponse response = httpClient
.doPost("http://localhost:8280/ESBJAVA4572abc/dd", null, payload, "application/json");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
response.getEntity().writeTo(bos);
String exPayload = new String(bos.toByteArray());
String val = "{\"state\":[{\"path\":\"user_programs_progress\",\"entry\":"
+ "[{\"value\":\"false\",\"key\":\"testJson14\"}]}]}";
Assert.assertEquals(val, exPayload);
}
public Serializer(Schema schema) {
try {
this.writer = new GenericDatumWriter<>(schema);
this.outputStream = new ByteArrayOutputStream();
this.encoder = EncoderFactory.get().jsonEncoder(schema, this.outputStream);
} catch (IOException ioe) {
throw new RuntimeException("Could not initialize avro json encoder.");
}
}
@Test
void testInputStreamSizeSpecialCharacters() throws IOException {
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
byteArrayOutputStream.write(messageSpecialChar.getFullContent());
assertThat(byteArrayOutputStream.size()).isEqualTo(MESSAGE_CONTENT_SPECIAL_CHAR.getBytes(MESSAGE_CHARSET).length);
}
}
public CachedVectorContainer(WritableBatch batch, BufferAllocator allocator) throws IOException {
VectorAccessibleSerializable va = new VectorAccessibleSerializable(batch, allocator);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
va.writeToStream(baos);
this.allocator = allocator;
this.data = baos.toByteArray();
va.clear();
}