Java 类org.apache.commons.io.output.ByteArrayOutputStream 实例源码
项目:shrinker
文件:JarProcessor.java
@Override
public void proceed() {
try {
List<Pair<String, byte[]>> entryList = readZipEntries(src)
.parallelStream()
.map(this::transformClassBlob)
.collect(Collectors.toList());
if (entryList.isEmpty()) return;
try (OutputStream fileOut = Files.newOutputStream(dst)) {
ByteArrayOutputStream buffer = zipEntries(entryList);
buffer.writeTo(fileOut);
}
} catch (IOException e) {
throw new RuntimeException("Reading jar entries failure", e);
}
}
项目:shrinker
文件:JarProcessor.java
private ByteArrayOutputStream zipEntries(List<Pair<String, byte[]>> entryList) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream(8192);
try (ZipOutputStream jar = new ZipOutputStream(buffer)) {
jar.setMethod(ZipOutputStream.STORED);
final CRC32 crc = new CRC32();
for (Pair<String, byte[]> entry : entryList) {
byte[] bytes = entry.second;
final ZipEntry newEntry = new ZipEntry(entry.first);
newEntry.setMethod(ZipEntry.STORED); // chose STORED method
crc.reset();
crc.update(entry.second);
newEntry.setCrc(crc.getValue());
newEntry.setSize(bytes.length);
writeEntryToJar(newEntry, bytes, jar);
}
jar.flush();
}
return buffer;
}
项目:jmeter-bzm-plugins
文件:HttpUtils.java
private String getResponseEntity(HttpResponse result) throws IOException {
HttpEntity entity = result.getEntity();
if (entity == null) {
log.debug("Null response entity");
return null;
}
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
entity.writeTo(bos);
byte[] bytes = bos.toByteArray();
if (bytes == null) {
bytes = "null".getBytes();
}
String response = new String(bytes);
log.debug("Response with code " + result + ": " + response);
return response;
} finally {
InputStream content = entity.getContent();
if (content != null) {
content.close();
}
}
}
项目:commons-sandbox
文件:Tests.java
public static void main(String[] args) throws Exception {
String cmd = "/tmp/test.sh";
CommandLine cmdLine = CommandLine.parse("/bin/bash " + cmd);
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
ByteArrayOutputStream stderr = new ByteArrayOutputStream();
PumpStreamHandler psh = new PumpStreamHandler(stdout, stderr);
psh.setStopTimeout(TIMEOUT_FIVE_MINUTES);
ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT_TEN_MINUTES); // timeout in milliseconds
Executor executor = new DefaultExecutor();
executor.setExitValue(0);
executor.setStreamHandler(psh);
executor.setWatchdog(watchdog);
int exitValue = executor.execute(cmdLine, Collections.emptyMap());
System.out.println(exitValue);
}
项目:Lester
文件:CreatePDF.java
/**
* Renders an input file (XML or XSL-FO) into a PDF file. It uses the JAXP
* transformer given to optionally transform the input document to XSL-FO.
* The transformer may be an identity transformer in which case the input
* must already be XSL-FO. The PDF is written to a byte array that is
* returned as the method's result.
* @param src Input XML or XSL-FO
* @param transformer Transformer to use for optional transformation
* @param response HTTP response object
* @throws FOPException If an error occurs during the rendering of the
* XSL-FO
* @throws TransformerException If an error occurs during XSL
* transformation
* @throws IOException In case of an I/O problem
*/
public void render(Source src, Transformer transformer, HttpServletResponse response, String realpath)
throws FOPException, TransformerException, IOException {
FOUserAgent foUserAgent = getFOUserAgent(realpath);
//Setup output
ByteArrayOutputStream out = new ByteArrayOutputStream();
//Setup FOP
fopFactory.setBaseURL(realpath);
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
//Make sure the XSL transformation's result is piped through to FOP
Result res = new SAXResult(fop.getDefaultHandler());
//Start the transformation and rendering process
transformer.transform(src, res);
//Return the result
sendPDF(out.toByteArray(), response);
}
项目:argument-reasoning-comprehension-task
文件:CompressedXmiReader.java
@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);
}
}
项目:jwala
文件:BinaryDistributionControlServiceImplTest.java
@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));
}
项目:bootstrap
文件:JpaBenchResourceTest.java
@Test
public void testDownloadDataBlob() throws Exception {
final URL jarLocation = getBlobFile();
InputStream openStream = null;
try {
// Get the JAR input
openStream = jarLocation.openStream();
// Proceed to the test
resource.prepareData(openStream, 1);
final StreamingOutput downloadLobFile = resource.downloadLobFile();
final ByteArrayOutputStream output = new ByteArrayOutputStream();
downloadLobFile.write(output);
org.junit.Assert.assertTrue(output.toByteArray().length > 3000000);
} finally {
IOUtils.closeQuietly(openStream);
}
}
项目:dremio-oss
文件:ProtostuffUtil.java
/**
* Clone a Protostuff object
*
* @param t the protobuf message to copy
* @return a deep copy of {@code t}
*/
public static <T extends Message<T>> T copy(T t) {
try {
Schema<T> schema = t.cachedSchema();
ByteArrayOutputStream out = new ByteArrayOutputStream();
GraphIOUtil.writeDelimitedTo(new DataOutputStream(out), t, schema);
// TODO: avoid array copy
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
T newMessage = schema.newMessage();
GraphIOUtil.mergeDelimitedFrom(in, newMessage, schema);
return newMessage;
} catch (IOException e) {
throw UserException.dataReadError(e)
.message("Failure decoding object, please ensure that you ran dremio-admin upgrade on Dremio.")
.build(logger);
}
}
项目:PACE
文件:AESValueEncryptor.java
@Override
byte[] encrypt(byte[] key, byte[] data) {
try {
SecretKeySpec keySpec = new SecretKeySpec(key, AES);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] ciphertext = cipher.doFinal(data);
// Write out the metadata.
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DataOutput out = new DataOutputStream(stream);
byte[] params = cipher.getParameters().getEncoded();
WritableUtils.writeVInt(out, params.length);
out.write(params);
// Write the original ciphertext and return the new ciphertext.
out.write(ciphertext);
return stream.toByteArray();
} catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException | IOException e) {
throw new EncryptionException(e);
}
}
项目:plugin-bt-jira
文件:JiraExportPluginResourceTest.java
@Test
public void getStatusHistory() throws Exception {
final int subscription = getSubscription("MDA");
final StreamingOutput csv = (StreamingOutput) resource.getStatusHistory(subscription, "file1").getEntity();
final ByteArrayOutputStream out = new ByteArrayOutputStream();
csv.write(out);
final BufferedReader inputStreamReader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(out.toByteArray()), "cp1252"));
final String header = inputStreamReader.readLine();
Assert.assertEquals("issueid;key;author;from;to;fromText;toText;date;dateTimestamp", header);
String lastLine = inputStreamReader.readLine();
Assert.assertEquals("11432;MDA-1;fdaugan;;1;;OPEN;2009/03/23 15:26:43;1237818403000", lastLine);
lastLine = inputStreamReader.readLine();
Assert.assertEquals("11437;MDA-4;xsintive;;1;;OPEN;2009/03/23 16:23:31;1237821811000", lastLine);
lastLine = inputStreamReader.readLine();
lastLine = inputStreamReader.readLine();
lastLine = inputStreamReader.readLine();
lastLine = inputStreamReader.readLine();
Assert.assertEquals("11535;MDA-8;challer;;1;;OPEN;2009/04/01 14:20:29;1238588429000", lastLine);
lastLine = inputStreamReader.readLine();
lastLine = inputStreamReader.readLine();
lastLine = inputStreamReader.readLine();
Assert.assertEquals("11535;MDA-8;fdaugan;1;10024;OPEN;ASSIGNED;2009/04/09 09:45:16;1239263116000", lastLine);
lastLine = inputStreamReader.readLine();
Assert.assertEquals("11535;MDA-8;fdaugan;10024;3;ASSIGNED;IN PROGRESS;2009/04/09 09:45:30;1239263130000", lastLine);
}
项目:pipegen
文件:InterceptedFileInputStreamTests.java
@Test
public void testReadByte() throws Exception {
ByteArrayOutputStream stream = new ByteArrayOutputStream(1024);
OptimizedInterceptedFileOutputStream outStream = new OptimizedInterceptedFileOutputStream(stream);
outStream.write(new AugmentedString(1, ',', 1.5, ',', "foo", '\n'));
outStream.close();
OptimizedInterceptedFileInputStream inStream =
new OptimizedInterceptedFileInputStream(new ByteArrayInputStream(stream.toByteArray()));
ByteBuffer buffer = ByteBuffer.allocate(10);
for(int i = 0; i < "1,1.5,foo\n".length(); i++)
buffer.put((byte)inStream.read());
assert(new String(buffer.array()).equals("1,1.5,foo\n"));
assert(inStream.read() == -1);
}
项目:android-java-connect-sample
文件:GraphServiceController.java
/**
* 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();
}
项目:SDA
文件:AvroOneM2MDataPublish.java
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);
}
项目:SDA
文件:AvroOneM2MStatusDataPublish.java
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);
}
项目:SDA
文件:AvroRdbmsTimeTableWattagePublish.java
public void send(COL_RDBMS event) throws Exception {
EncoderFactory avroEncoderFactory = EncoderFactory.get();
SpecificDatumWriter<COL_RDBMS> avroEventWriter = new SpecificDatumWriter<COL_RDBMS>(COL_RDBMS.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);
}
项目:Gargoyle
文件:BehaviorReader.java
protected String decompress(byte[] compressed) throws DataFormatException, IOException {
Inflater decompresser = new Inflater(true);
byte[] result = new byte[1024];
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
decompresser.setInput(compressed);
while (!decompresser.finished()) {
int count = decompresser.inflate(result);
out.write(result, 0, count);
}
decompresser.end();
return out.toString();
}
}
项目:pipegen
文件:OptimizedInterceptedFileOutputStreamTests.java
@Test
public void testInferenceMultipleWrites() throws Exception {
ByteArrayOutputStream stream = new ByteArrayOutputStream(1024);
OptimizedInterceptedFileOutputStream iStream = new OptimizedInterceptedFileOutputStream(stream);
iStream.write(new AugmentedString(1));
iStream.write(new AugmentedString(','));
iStream.write(new AugmentedString(1.5));
iStream.write(new AugmentedString(','));
iStream.write(new AugmentedString("foo"));
iStream.write(new AugmentedString('\n'));
CompositeVector vector = iStream.getVector();
assert (vector.getVectors().size() == 3);
assert (vector.getVectors().get(0).getClass() == IntVector.class);
assert (vector.getVectors().get(1).getClass() == Float8Vector.class);
assert (vector.getVectors().get(2).getClass() == VarCharVector.class);
}
项目:pipegen
文件:OptimizedInterceptedFileOutputStreamTests.java
@Test
public void testMultiRowVectorFlush() throws Exception {
ByteArrayOutputStream stream = new ByteArrayOutputStream(1024);
OptimizedInterceptedFileOutputStream iStream = new OptimizedInterceptedFileOutputStream(stream);
iStream.write(new AugmentedString(123456789));
iStream.write(new AugmentedString(','));
iStream.write(new AugmentedString(11111111.5));
iStream.write(new AugmentedString(','));
iStream.write(new AugmentedString("foo"));
iStream.write(new AugmentedString('\n'));
iStream.write(new AugmentedString(234567890, ',', 22222222.5, ',', "bar", "\n"));
iStream.flush();
ByteBuffer buffer = ByteBuffer.wrap(stream.toByteArray());
assert(InterceptMetadata.read(buffer) != null);
assertVector(buffer, 8, new Integer[] {123456789, 234567890});
assertVector(buffer, 16, new Double[] {11111111.5, 22222222.5});
assertVarCharVector(buffer, 6, new Integer[] {0, 3, 6}, new String[] {"foo", "bar"});
assert(!buffer.hasRemaining());
}
项目:pipegen
文件:InterceptedFileInputStreamTests.java
@Test
public void testMixedReadLine() throws Exception {
ByteArrayOutputStream stream = new ByteArrayOutputStream(1024);
OptimizedInterceptedFileOutputStream outStream = new OptimizedInterceptedFileOutputStream(stream);
outStream.write(new AugmentedString(1, ',', 1.5, ',', "foo", '\n'));
outStream.write(new AugmentedString(2, ',', 2.5, ',', "bar", '\n'));
outStream.close();
OptimizedInterceptedFileInputStream inStream =
new OptimizedInterceptedFileInputStream(new ByteArrayInputStream(stream.toByteArray()));
AugmentedString line = inStream.readLine();
assert(line.getState()[0].equals(1));
assert(line.getState()[1].equals(1.5));
assert(line.getState()[2].toString().equals("foo"));
byte[] bytes = new byte[6];
int read = inStream.read(bytes, 2, 6);
assert(read == 6);
assert(new String(bytes).equals("2.5,ba"));
assert(inStream.readLine().equals("r\n"));
}
项目:pipegen
文件:InterceptedFileInputStreamTests.java
@Test
public void testReadLine() throws Exception {
ByteArrayOutputStream stream = new ByteArrayOutputStream(1024);
OptimizedInterceptedFileOutputStream outStream = new OptimizedInterceptedFileOutputStream(stream);
outStream.write(new AugmentedString(1, ',', 1.5, ',', "foo", '\n'));
outStream.write(new AugmentedString(2, ',', 2.5, ',', "bar", '\n'));
outStream.close();
OptimizedInterceptedFileInputStream inStream =
new OptimizedInterceptedFileInputStream(new ByteArrayInputStream(stream.toByteArray()));
AugmentedString line = inStream.readLine();
assert(line.getState()[0].equals(1));
assert(line.getState()[1].equals(1.5));
assert(line.getState()[2].toString().equals("foo"));
line = inStream.readLine();
assert(line.getState()[0].equals(2));
assert(line.getState()[1].equals(2.5));
assert(line.getState()[2].toString().equals("bar"));
assert(inStream.readLine() == null);
}
项目:bender
文件:S3TransportBuffer.java
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;
}
}
项目:aml
文件:Context.java
/**
* <p>generate.</p>
*
* @return a {@link java.util.Set} object.
* @throws java.io.IOException if any.
*/
public Set<String> generate() throws IOException
{
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final PrintStream ps = new PrintStream(baos);
codeModel.build(configuration.getOutputDirectory(), ps);
ps.close();
final Set<String> generatedFiles = new HashSet<String>();
if (shouldGenerateResponseWrapper)
{
generatedFiles.add(generateResponseWrapper());
}
generatedFiles.addAll(Arrays.asList(StringUtils.split(baos.toString())));
return generatedFiles;
}
项目:aml
文件:Context.java
/**
* <p>generate.</p>
*
* @return a {@link java.util.Set} object.
* @throws java.io.IOException if any.
*/
public Set<String> generate() throws IOException
{
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final PrintStream ps = new PrintStream(baos);
codeModel.build(configuration.getOutputDirectory(), ps);
ps.close();
final Set<String> generatedFiles = new HashSet<String>();
if (shouldGenerateResponseWrapper)
{
generatedFiles.add(generateResponseWrapper());
}
generatedFiles.addAll(Arrays.asList(StringUtils.split(baos.toString())));
return generatedFiles;
}
项目:closure-maven-plugin
文件:JsonStreamOutputHandler.java
@Override
public OutputStream openStream() throws IOException {
synchronized (this) { ++countOpen; }
return new ByteArrayOutputStream() {
boolean closed = false;
@SuppressWarnings("synthetic-access")
@Override
public void close() throws IOException {
super.close();
processBytes(this.toByteArray());
synchronized (JsonStreamOutputHandler.this) {
if (!closed) {
--countOpen;
closed = true;
}
if (countOpen == 0) {
JsonStreamOutputHandler.this.notifyAll();
}
}
}
};
}
项目:warp10-platform
文件:MacroHelper.java
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(), Charsets.UTF_8);
return wrap(name, mc2, secure);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
项目:product-ei
文件:JSONDisableAutoPrimitiveNumericTestCase.java
@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);
}
项目:product-ei
文件:DistributedCachingHeaderSerializationTestcase.java
@Test(groups = "wso2.esb", description = "cache meditor test enabling axis2 clustering.")
public void testDistributedCachingHeaderSerialization() throws Exception {
String requestXml = "<a>ABC</a>";
SimpleHttpClient httpClient = new SimpleHttpClient();
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/xml;charset=UTF-8");
HttpResponse response1 = httpClient.doPost(getApiInvocationURL("CachingTest")+"/test", headers, requestXml, "application/xml;charset=UTF-8");
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
response1.getEntity().writeTo(baos1);
String actualValue1 = baos1.toString();
// this is to populate response from cache mediator
HttpResponse response2 = httpClient.doPost(getApiInvocationURL("CachingTest")+"/test", headers, requestXml, "application/xml;charset=UTF-8");
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
response2.getEntity().writeTo(baos2);
String actualValue2 = baos2.toString();
Assert.assertEquals(actualValue1, requestXml);
Assert.assertEquals(actualValue2, requestXml);
Assert.assertTrue(stringExistsInLog("CACHEMATCHEDCACHEMATCHED"));
}
项目:pipegen
文件:OptimizedInterceptedFileOutputStreamWriterTests.java
@Test
public void testVectorFlush() throws Exception {
ByteArrayOutputStream stream = new ByteArrayOutputStream(1024);
OptimizedInterceptedFileOutputStream iStream = new OptimizedInterceptedFileOutputStream(stream);
OptimizedInterceptedOutputStreamWriter writer = new OptimizedInterceptedOutputStreamWriter(iStream);
writer.write(new AugmentedString(1));
writer.write(new AugmentedString(','));
writer.write(new AugmentedString(1.5));
writer.write(new AugmentedString(','));
writer.write(new AugmentedString("foo"));
writer.write(new AugmentedString('\n'));
writer.flush();
ByteBuffer buffer = ByteBuffer.wrap(stream.toByteArray());
assert(InterceptMetadata.read(buffer) != null);
assertVector(buffer, 4, new Integer[] {1});
assertVector(buffer, 8, new Double[] {1.5});
assertVarCharVector(buffer, 3, new Integer[] {0, 3}, new String[] {"foo"});
assert(!buffer.hasRemaining());
}
项目:product-ei
文件:ESBJAVA_4572TestCase.java
@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);
}
项目:pipegen
文件:InterceptedFileInputStreamTests.java
@Test
public void testReadBytes() throws Exception {
ByteArrayOutputStream stream = new ByteArrayOutputStream(1024);
OptimizedInterceptedFileOutputStream outStream = new OptimizedInterceptedFileOutputStream(stream);
outStream.write(new AugmentedString(1, ',', 1.5, ',', "foo", '\n'));
outStream.write(new AugmentedString(2, ',', 2.5, ',', "bar", '\n'));
outStream.close();
OptimizedInterceptedFileInputStream inStream =
new OptimizedInterceptedFileInputStream(new ByteArrayInputStream(stream.toByteArray()));
byte[] bytes = new byte[20];
assert(inStream.read(bytes) == 20);
assert(new String(bytes).equals("1,1.5,foo\n2,2.5,bar\n"));
assert(inStream.read() == -1);
}
项目:pipegen
文件:InterceptedFileInputStreamTests.java
@Test
public void testReadMoreBytes() throws Exception {
ByteArrayOutputStream stream = new ByteArrayOutputStream(1024);
OptimizedInterceptedFileOutputStream outStream = new OptimizedInterceptedFileOutputStream(stream);
outStream.write(new AugmentedString(1, ',', 1.5, ',', "foo", '\n'));
outStream.write(new AugmentedString(2, ',', 2.5, ',', "bar", '\n'));
outStream.close();
OptimizedInterceptedFileInputStream inStream =
new OptimizedInterceptedFileInputStream(new ByteArrayInputStream(stream.toByteArray()));
byte[] bytes = new byte[30];
assert(inStream.read(bytes) == 20);
assert(new String(bytes, 0, 20).equals("1,1.5,foo\n2,2.5,bar\n"));
assert(inStream.read() == -1);
}
项目:pipegen
文件:InterceptedFileInputStreamTests.java
@Test
public void testReadFewerBytes() throws Exception {
ByteArrayOutputStream stream = new ByteArrayOutputStream(1024);
OptimizedInterceptedFileOutputStream outStream = new OptimizedInterceptedFileOutputStream(stream);
outStream.write(new AugmentedString(1, ',', 1.5, ',', "foo", '\n'));
outStream.write(new AugmentedString(2, ',', 2.5, ',', "bar", '\n'));
outStream.close();
OptimizedInterceptedFileInputStream inStream =
new OptimizedInterceptedFileInputStream(new ByteArrayInputStream(stream.toByteArray()));
byte[] bytes = new byte[10];
assert(inStream.read(bytes) == 10);
assert(new String(bytes).equals("1,1.5,foo\n"));
byte[] bytes2 = new byte[9];
assert(inStream.read(bytes2) == 9);
assert(new String(bytes2).equals("2,2.5,bar"));
assert(inStream.read() != -1);
assert(inStream.read() == -1);
}
项目:JACWfA
文件:BZip2.java
@Override
public void init(RunConfig config) throws InvalidTestFormatException {
super.init(config);
outBuffer = new ByteArrayOutputStream();
File file = new File(GR.getGoldenDir(), goldenFileName);
try {
data = MTTestResourceManager.goldenFileToByteArray(file.getPath());
dataBuffer = new ByteArrayInputStream(data);
compressZip(dataBuffer, outBuffer);
compressedBuffer = new ByteArrayInputStream(outBuffer.toByteArray());
} catch (IOException e) {
throw new GoldenFileNotFoundException(file, this.getClass());
}
}
项目:cubedb
文件:TinyMetricTest.java
@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));
}
}
项目:ryf_mms2
文件:CreateExcelUtil.java
/**
* 创建文件
* @param response
* @param workbook
* @param fileName
* @return boolean
* @throws Exception
*/
public static FileTransfer createExcel(HttpServletResponse response,
HSSFWorkbook workbook, String fileName) throws Exception {
boolean flag = false;
try {
response.reset();
response.setHeader("Content-Disposition", "attachment;filename="
+ new String(fileName.getBytes(), "iso8859-1"));
//ServletOutputStream out = response.getOutputStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
workbook.write(buffer);
return new FileTransfer(fileName, "application/vnd.ms-excel", buffer.toByteArray());
// 弹出下载对话框
//out.flush();
//out.close();
//flag = true;
} catch (Exception e) {
logger.error(fileName + " :文件创建失败");
throw e;
}
//return flag;
}
项目:ryf_mms2
文件:SettlementService.java
/**
* 结算制表下载
* @param batch 结算批次号
* @return
* @throws Exception
*/
public FileTransfer downloadSettleTB(String batch) throws Exception {
String fileName = batch + "settleTB.xls";
File settlementFile = new File(Ryt.getParameter("SettlementFilePath") + fileName);
if (settlementFile.exists()) {
BufferedInputStream bis = null;
try {
InputStream is = new FileInputStream(settlementFile);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
buffer.write(is);
return new FileTransfer(fileName, "application/x-xls", buffer.toByteArray());
} catch (IOException e) {
throw e;
} finally {
if (bis != null)
bis.close();
}
} else {
return null;
}
}
项目:q-mail
文件:DeferredFileBodyTest.java
@Test
public void withShortData__writeTo__shouldWriteData() throws Exception {
writeShortTestData();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
deferredFileBody.writeTo(baos);
assertArrayEquals(TEST_DATA_SHORT, baos.toByteArray());
}
项目:mtgo-best-bot
文件:RobotWrapper.java
public Pair<ProcessingLifecycleStatus, byte[]> getCurrentScreen(final ProcessingLifecycleStatus status, final AssumedScreenTest screenTest) throws ApplicationDownException, IOException {
if(!processManager.isMtgoRunningOrLoading()) {
throw new ApplicationDownException("MTGO is not running!");
}
BufferedImage bi = robot.createScreenCapture(new Rectangle(0, 0, screenWidth, screenHeight));
if(bi != null) {
RawLines rawLines;
if (screenTest == AssumedScreenTest.NOT_NEEDED) {
rawLines = tesseractWrapper.getRawText(bi);
} else {
rawLines = tesseractWrapper.getRawText(bi, screenTest.getScreenTestBounds());
}
logger.info("Processing raw lines");
final ProcessingLifecycleStatus outcomeStatus = rawLinesProcessor.determineLifecycleStatus(rawLines);
logger.info("Determined new status: " + status.name());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi, "jpg", baos);
baos.flush();
byte[] imageAsByteArray = baos.toByteArray();
baos.close();
return new ImmutablePair<>(outcomeStatus, imageAsByteArray);
}
throw new ApplicationDownException("Somehow made it to this unreachable point");
}
项目:mtgo-best-bot
文件:RobotWrapper.java
private BotCamera createBotCamera(BufferedImage image, PlayerBot remotePlayerBot) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos );
baos.flush();
byte[] imageInByte = baos.toByteArray();
BotCamera botCamera = new BotCamera(imageInByte, new Date());
botCamera.setPlayerBot(remotePlayerBot);
return botCamera;
}